@camstack/addon-admin-ui 1.2.653 → 1.2.655
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 +14 -0
- package/dist/assets/Addons-DyJCfk3K.js +5 -0
- package/dist/assets/{AdminPage-IHC_FLB8.js → AdminPage-aLHp47jf.js} +1 -1
- package/dist/assets/{AdminSectionedPage-Ch-ZRoVJ.js → AdminSectionedPage-DC99_NYO.js} +1 -1
- package/dist/assets/AiProfiles-7TjJU7gH.js +3 -0
- package/dist/assets/{BootstrapSettingsForm-BIJKJjHp.js → BootstrapSettingsForm-DujO7xd3.js} +1 -1
- package/dist/assets/Build-5EPZNJc_.js +40 -0
- package/dist/assets/Calendars-B21A2j3J.js +1 -0
- package/dist/assets/{CameraGrids-MUUhy0x2.js → CameraGrids-CXNpT_B8.js} +1 -1
- package/dist/assets/Cluster-DpgPRLih.js +1 -0
- package/dist/assets/CompositionBlockEditor-GDw9wpyC.js +2 -0
- package/dist/assets/{CompositionEditorPage-Dz7XI_eP.js → CompositionEditorPage-D4mYMm-K.js} +1 -1
- package/dist/assets/Data-BTlEa5yB.js +2 -0
- package/dist/assets/DeviceDetail-CNtpEA24.js +2 -0
- package/dist/assets/{Devices-Bf4nCnel.js → Devices-DcZIXngR.js} +1 -1
- package/dist/assets/EmbedDevicePage-NUKM9Y94.js +1 -0
- package/dist/assets/{EmbedPlayerPage-BBY-Sx6F.js → EmbedPlayerPage-CzDEkeN3.js} +1 -1
- package/dist/assets/History-Co3N1ECB.js +1 -0
- package/dist/assets/Identity-Cb_y_j4v.js +1 -0
- package/dist/assets/InstancesTable-DZHp204O.js +1 -0
- package/dist/assets/IntegrationDetail-oeZTeQnA.js +1 -0
- package/dist/assets/IntegrationWizard-BZ2-i83L.js +1 -0
- package/dist/assets/{Integrations-Cj6uWWN_.js → Integrations-B0sKe_MX.js} +2 -2
- package/dist/assets/Integrations-D9FcrJXz.js +1 -0
- package/dist/assets/Library-BqYimbZR.js +1 -0
- package/dist/assets/Locations-9q72GJxA.js +3 -0
- package/dist/assets/{Logs-BhqOgQ6e.js → Logs-DyUEl7-W.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-LlW1oTr3.js → MaskShapeCanvas-D4W6rB-U.js} +1 -1
- package/dist/assets/{MotionZonesSettings-Dw3DU6pD.js → MotionZonesSettings-CI3yCbis.js} +1 -1
- package/dist/assets/MyAccess-CCWVg8X1.js +2 -0
- package/dist/assets/Network-ChHr4jPK.js +1 -0
- package/dist/assets/{NodeAddonsSettingsPanel-BaDE0Pex.js → NodeAddonsSettingsPanel-DyAkVlR3.js} +2 -2
- package/dist/assets/Notifications-CxxZDBll.js +1 -0
- package/dist/assets/Pipeline-Bsh224Sd.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-DCVqX841.js → PrivacyMaskSettings-C4UU_fXQ.js} +1 -1
- package/dist/assets/Recordings-DEvP3Bfl.js +1 -0
- package/dist/assets/{RemoteGrid--NiAHBK3.js → RemoteGrid-Bsj2x0GN.js} +1 -1
- package/dist/assets/{ScanSubnetEditor-Dp0E5C1_.js → ScanSubnetEditor-83bxeuIV.js} +1 -1
- package/dist/assets/SceneMonitorEditor-OVXtamOi.js +1 -0
- package/dist/assets/SessionsList-DPfHCju_.js +2 -0
- package/dist/assets/{Showroom-l4vJyL2_.js → Showroom-JytwI7ts.js} +1 -1
- package/dist/assets/StorageLocationsTable-D0-iwXJt.js +1 -0
- package/dist/assets/{System-XHHHEn1g.js → System-CfB4TfTX.js} +1 -1
- package/dist/assets/Templates-Cu0Zx0WB.js +1 -0
- package/dist/assets/{Terminal-CSQtVQmE.js → Terminal-D2wG4YSv.js} +4 -4
- package/dist/assets/{TrainingProviders-De81MhS-.js → TrainingProviders-BKBWflor.js} +1 -1
- package/dist/assets/{Viewer-FR0LH5M7.js → Viewer-rKCQt8Pi.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BBA_NCm-.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-rv5WZowx.js} +1 -1
- package/dist/assets/{action-draft-BUIf6miK.js → action-draft-BpL552GS.js} +1 -1
- package/dist/assets/{ai-page.helpers-CowRsr4f.js → ai-page.helpers-DLFlpj3G.js} +1 -1
- package/dist/assets/{assignment-candidates-DNvncHM2.js → assignment-candidates-BK42JAzD.js} +1 -1
- package/dist/assets/{authed-media-DQUbrVb4.js → authed-media-CdfUt51r.js} +1 -1
- package/dist/assets/{board-model-YFLbUrn6.js → board-model-BACBh92I.js} +1 -1
- package/dist/assets/client-BD4NsqEN.js +1115 -0
- package/dist/assets/{command-vocab-tdjzfkdy.js → command-vocab-B_sqDpAc.js} +1 -1
- package/dist/assets/create-composition-CtkD_L5c.js +1 -0
- package/dist/assets/device-detail-DNqKt0La.js +1 -0
- package/dist/assets/{device-integration-icon-BT-_hxIF.js → device-integration-icon-BLg5i-Lj.js} +1 -1
- package/dist/assets/device-picker-model-Du6UAsiy.js +1 -0
- package/dist/assets/dist-BK12oHz3.js +1115 -0
- package/dist/assets/{dist-BGrtxcme.js → dist-BonRqxy_.js} +1 -1
- package/dist/assets/{format--HuC16nb.js → format-DRt7qFMH.js} +1 -1
- package/dist/assets/{hostInit-3uCgRlGz.js → hostInit-Bgo3XaDt.js} +1 -1
- package/dist/assets/i18n-EpyjWJGh.js +1 -0
- package/dist/assets/icons-BiHuBwzY.js +1 -0
- package/dist/assets/index-C_D8eRsf.js +4 -0
- package/dist/assets/index-DHx7H0Qb.css +2 -0
- package/dist/assets/{linked-devices-model-JZgr5Mkd.js → linked-devices-model-4oBb-ZIa.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-01002c42.js → mf-entry-bootstrap-0-b3c36c58.js} +2 -2
- package/dist/assets/mount-Du6UAsiy.js +1 -0
- package/dist/assets/{notification-rule-status-DIIXoVdn.js → notification-rule-status-jGDjCnq5.js} +1 -1
- package/dist/assets/player-overlays-Bs9A8fez.js +1 -0
- package/dist/assets/remoteEntry-BFByx-0h.js +1 -0
- package/dist/assets/src-CNcEcLrI.js +263 -0
- package/dist/assets/{step-inspector-model-C76V4MWJ.js → step-inspector-model-CQ4ZhPOo.js} +1 -1
- package/dist/assets/{video-De6y5yax.js → terminal-BSZfUawf.js} +1 -1
- package/dist/assets/{use-scenes-feed-cmZKGNSW.js → use-scenes-feed-DZp1AHrK.js} +1 -1
- package/dist/assets/{use-stationary-objects-BoUGi1JO.js → use-stationary-objects-B_EMLFx7.js} +1 -1
- package/dist/assets/{useAdminDeviceRemoval-DLI0kLAU.js → useAdminDeviceRemoval-BGavriCa.js} +1 -1
- package/dist/assets/useEventInvalidation-Du6UAsiy.js +1 -0
- package/dist/assets/{useNodeUrlSelection-DMmVYpSE.js → useNodeUrlSelection-DnHxOtlP.js} +1 -1
- package/dist/assets/useTemplateSave-CT5IvdL4.js +1 -0
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-6S8fCuje.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-922VMW57.js} +2 -2
- package/dist/index.html +9 -9
- package/dist/server/addon.js +65 -10
- package/package.json +2 -2
- package/dist/assets/Addons-B-UM6GSX.js +0 -5
- package/dist/assets/AiProfiles-B4SUJQ9G.js +0 -3
- package/dist/assets/Build-BHR9T6UJ.js +0 -40
- package/dist/assets/Calendars-GKfsLcqY.js +0 -1
- package/dist/assets/Cluster-DxEZYSF0.js +0 -1
- package/dist/assets/CompositionBlockEditor-BFBeiHR4.js +0 -2
- package/dist/assets/Data-BaAuEhoW.js +0 -2
- package/dist/assets/DeviceDetail-C0SC_4iD.js +0 -2
- package/dist/assets/EmbedDevicePage-C3NGsRrc.js +0 -1
- package/dist/assets/History-DCTkD2C5.js +0 -1
- package/dist/assets/Identity-nbJoxA5E.js +0 -1
- package/dist/assets/InstancesTable-D2eTsMze.js +0 -1
- package/dist/assets/IntegrationDetail-DL_jE7Ho.js +0 -1
- package/dist/assets/IntegrationWizard-BeAKGqkD.js +0 -1
- package/dist/assets/Integrations-B6dYn6fd.js +0 -1
- package/dist/assets/Library-DZE79diS.js +0 -1
- package/dist/assets/Locations-CqKj6DUZ.js +0 -3
- package/dist/assets/MyAccess-D-Cz_u-P.js +0 -2
- package/dist/assets/Network-B1Tex5sO.js +0 -1
- package/dist/assets/Notifications-DhTbXKSI.js +0 -1
- package/dist/assets/Pipeline-DdOSXsJd.js +0 -1
- package/dist/assets/Recordings-Clozl5li.js +0 -1
- package/dist/assets/SceneMonitorEditor-Djr3jYA7.js +0 -1
- package/dist/assets/SessionsList-GT-Vu8fp.js +0 -2
- package/dist/assets/StorageLocationsTable-BnmqVIjs.js +0 -1
- package/dist/assets/Templates-DdfynSCT.js +0 -1
- package/dist/assets/bell-off-ChsIJ9tx.js +0 -1
- package/dist/assets/client-BPycW7-C.js +0 -1115
- package/dist/assets/create-composition-DLzarGQj.js +0 -1
- package/dist/assets/device-detail-CLGID6OK.js +0 -1
- package/dist/assets/device-picker-model-Dp5rCpVe.js +0 -1
- package/dist/assets/dist-D_CJWYmG.js +0 -1115
- package/dist/assets/i18n-DMi5B3uV.js +0 -1
- package/dist/assets/icons-Q-ksrnyT.js +0 -1
- package/dist/assets/index-CfI8I1jw.css +0 -2
- package/dist/assets/index-D4P9-tQo.js +0 -4
- package/dist/assets/mount-Dp5rCpVe.js +0 -1
- package/dist/assets/player-overlays-DuVrpJ5X.js +0 -1
- package/dist/assets/remoteEntry-Cll_F6YF.js +0 -1
- package/dist/assets/settings-2-BIrKVPOG.js +0 -1
- package/dist/assets/src-CDP4x5TP.js +0 -253
- package/dist/assets/useEventInvalidation-Dp5rCpVe.js +0 -1
- package/dist/assets/useTemplateSave-j5OtpDNQ.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,o as l,p as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Bn as p,Da as m,En as h,Er as g,Fa as _,Kt as v,Ni as y,Nr as b,Oa as x,Pi as S,Q as C,Rr as w,Vn as T,Yn as E,Yt as D,aa as O,b as k,ct as A,ei as j,gi as M,gt as N,ii as P,jn as ee,ka as te,oa as ne,ut as F,v as I,y as re,z as ie,zn as L}from"./player-overlays-DuVrpJ5X.js";import{At as R,Cn as z,Ct as ae,D as oe,Dt as se,E as ce,G as le,I as ue,It as de,J as fe,Jr as pe,Jt as me,K as B,Ln as he,M as ge,Mt as _e,Nt as ve,O as V,Ot as ye,P as be,Pt as xe,Q as Se,R as Ce,Tt as we,Wa as Te,Wr as Ee,X as De,Xr as Oe,Y as ke,Yr as Ae,Ys as je,Yt as Me,Z as Ne,_t as Pe,at as Fe,bt as Ie,it as Le,j as Re,jt as ze,k as Be,nt as Ve,q as He,rt as Ue,st as We,tt as Ge,us as Ke,yt as qe,z as Je,zt as Ye}from"./client-BPycW7-C.js";import{L as Xe,M as Ze,O as Qe,P as $e,b as et,k as tt,y as nt}from"./__vite-browser-external-B6QEsNSJ.js";import{t as rt}from"./bell-off-ChsIJ9tx.js";import{v as it}from"./video-De6y5yax.js";import{n as at,t as ot}from"./send-D_NAoo3n.js";import{n as st,t as ct}from"./languages-Du_pOBpX.js";import{$ as lt,A as ut,D as dt,Er as ft,Gd as pt,Gn as mt,Gr as ht,Jd as gt,Jr as _t,Kd as vt,Kn as yt,Kr as bt,Li as xt,M as St,Nr as Ct,O as wt,Oi as Tt,Q as Et,Qd as Dt,Ro as Ot,Ua as kt,Wr as At,Xd as jt,Xr as Mt,Yd as Nt,Yr as Pt,Zd as Ft,_r as It,bn as Lt,cf as Rt,cr as H,df as U,ff as zt,g as Bt,gt as Vt,hr as W,j as Ht,ji as Ut,k as Wt,ki as Gt,lf as Kt,lr as qt,mi as Jt,ot as Yt,qd as G,rf as K,sr as Xt,ti as Zt,uf as Qt,ur as $t,zr as en}from"./src-CDP4x5TP.js";import{t as q}from"./i18n-DMi5B3uV.js";import{t as J}from"./useTranslation-BJr-n0es.js";import"./mount-Dp5rCpVe.js";import{$n as tn,$t as nn,An as rn,Ar as an,At as on,Bn as sn,Bt as cn,Cn as ln,Cr as un,Ct as dn,Dn as fn,Dr as pn,Dt as mn,En as hn,Er as gn,Et as _n,Fn as vn,Fr as yn,Ft as bn,Gn as xn,Gt as Sn,Hn as Cn,Ht as wn,In as Tn,Ir as En,It as Dn,Jn as On,Jt as kn,Kn as An,Kr as jn,Kt as Mn,Ln as Nn,Lr as Pn,Lt as Fn,Mn as In,Mr as Ln,Mt as Rn,Nn as zn,Nr as Bn,Nt as Vn,On as Hn,Or as Un,Ot as Wn,Pn as Gn,Pr as Kn,Pt as qn,Qn as Jn,Qr as Yn,Qt as Xn,Rn as Zn,Rr as Qn,Rt as $n,S as er,Sn as tr,Sr as nr,St as rr,Tn as ir,Tr as ar,Tt as or,Un as sr,Ut as cr,Vn as lr,Vt as ur,Wn as dr,Wt as fr,Xn as pr,Xt as mr,Yn as hr,Yt as gr,Zn as _r,Zt as vr,_n as yr,_r as br,_t as xr,an as Sr,ar as Cr,bn as wr,br as Tr,bt as Er,cn as Dr,cr as Or,dn as kr,dr as Ar,en as jr,er as Mr,fn as Nr,fr as Pr,ft as Fr,gn as Ir,gr as Lr,gt as Rr,hn as zr,hr as Br,ht as Vr,in as Hr,ir as Ur,jn as Wr,jr as Gr,jt as Kr,kn as qr,kr as Jr,kt as Yr,ln as Xr,lr as Zr,mn as Qr,mr as $r,mt as ei,nn as ti,nr as ni,on as ri,or as ii,pn as ai,pr as oi,pt as si,qn as ci,qr as li,qt as ui,rn as di,rr as fi,sn as pi,sr as mi,tn as hi,tr as gi,un as _i,ur as vi,vn as yi,vr as bi,vt as xi,wn as Si,wr as Ci,wt as wi,x as Ti,xn as Ei,xr as Di,xt as Oi,yn as ki,yr as Ai,yt as Y,zn as ji,zr as Mi,zt as Ni}from"./index-D4P9-tQo.js";import{t as Pi}from"./AdminSectionedPage-Ch-ZRoVJ.js";import{n as Fi}from"./format--HuC16nb.js";import"./device-picker-model-Dp5rCpVe.js";import{t as Ii}from"./action-draft-BUIf6miK.js";import{t as Li}from"./AdminPage-IHC_FLB8.js";import{c as Ri,i as zi,n as Bi,o as Vi,r as Hi,s as Ui,t as Wi}from"./notification-rule-status-DIIXoVdn.js";import{t as Gi}from"./use-scenes-feed-cmZKGNSW.js";import{t as Ki}from"./InstancesTable-D2eTsMze.js";import{l as qi,s as Ji}from"./ai-page.helpers-CowRsr4f.js";c();var Yi=[`contact`,`cover`,`lock-control`,`switch`];function Xi(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 Zi(e){let t=new Set(Xi(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 Qi(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function $i(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=>Dt([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?q.t(`uiLibrary.devicePicker.deviceId`,{id:e}):jt(t,`device`,er))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function ea(e){let t=e.name.trim();return t===``?q.t(`uiLibrary.devicePicker.deviceId`,{id:e.deviceId}):t}function ta(e){return e===0?q.t(`helpers.alarmNonblocking.refusedNoName`):q.t(`helpers.alarmNonblocking.refusedOpen`)}var na={home:`Home`,away:`Away`,night:`Night`};function ra(e){return na[e]??e}function ia(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?q.t(`helpers.notificationAlarm.delayMin`,{minutes:n}):q.t(`helpers.notificationAlarm.delayMinSec`,{minutes:n,seconds:r})}function aa(e,t){if(e.ruleCount===0)return q.t(`helpers.notificationAlarm.armsNothing`);if(e.allDevices&&e.allDevicesExcept.length>0){let n=e.allDevicesExcept.map(t);return q.t(`helpers.notificationAlarm.allExcept`,{count:n.length,names:n.join(`, `)})}return e.allDevices?q.t(`helpers.notificationAlarm.everyDevice`,{count:e.ruleCount}):e.deviceIds.length===0?q.t(`helpers.notificationAlarm.noRestriction`,{count:e.ruleCount}):e.deviceIds.map(t).join(`, `)}function oa(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${sa[e.reason]})`);return q.t(`helpers.notificationAlarm.skipped`,{count:e.length,parts:n.join(`, `)})}var sa={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function ca(e){return e.ruleCount===0}function la(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 ua=2e3,da=15e3,fa=new Set([`arming`,`pending`,`triggered`]);function pa(e){return e!==void 0&&fa.has(e)?ua:da}var ma={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 ha(e){let t=ma[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${ra(e.targetMode)}`}function ga(e){return e!==`disarmed`}function _a(e){return e===`open`?q.t(`helpers.notificationAlarm.phaseOpen`):q.t(`helpers.notificationAlarm.phaseClosed`)}function va(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function ya(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function ba(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function xa(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 Sa(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 Ca(e,t,n,r){let i=xa(e,t,n);return r==="default"?i===void 0?null:Sa(t,n,null):i===r?null:Sa(t,n,r)}function wa(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=Ve(e,t),a=r!==n,o=n!==`doNothing`&&i.triggeredDurationSec===0;return!a&&!o?null:{mode:t,...a?{postTriggeredAction:n}:{},...o?{triggeredDurationSec:30}:{}}}function Ta(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 Ea=[`unknown-refusal`,`stale`,`expired`,`used`];function Da(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Oa(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Da(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 ka(e){if(!Da(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Oa(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Oa(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Ea.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var Aa={"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 ja(e){return Aa[e]}function Ma(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 Na=`pipeline-analytics`,Pa=`The hub answered something this build cannot read — refresh after updating.`;function Fa(e){return e instanceof Error?e.message:String(e)}function Ia(e){return e.map(e=>`${ea(e)} (${e.state})`).join(`, `)}function La({live:t,onChanged:n}){let{t:r}=J(),a=N(),[s,c]=o(null),[l,u]=o(null),[f,p]=o(null),m=(e,t)=>a.trpcClient.addons.custom.mutate({addonId:Na,action:e,input:t}),h=e=>{if(e===null){u(Pa);return}if(e.outcome===`refused`){c({refusalId:e.refusalId,blocking:e.blocking});return}if(c(null),e.outcome===`rejected`){u(`Arm anyway was not accepted: ${ja(e.reason)}.`);return}if(e.outcome===`outside-schedule`){u(`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: ${Ia(e.excluded)}.`)},_=()=>{u(null),p(null)},v=d({mutationFn:async e=>ka(await m(`nc.armAlarm`,{mode:e})),onMutate:_,onSuccess:h,onError:e=>u(Fa(e)),onSettled:n}),y=d({mutationFn:async e=>ka(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:_,onSuccess:h,onError:e=>u(Fa(e)),onSettled:n}),b=d({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{_(),c(null)},onSuccess:()=>p(`Disarmed.`),onError:e=>u(Fa(e)),onSettled:n});if(t===void 0)return e(Zt,{className:`p-4`,children:[i(`h3`,{className:`text-sm font-semibold mb-1`,children:r(`system.alarmLiveCard.panel`,`Panel`)}),i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.alarmLiveCard.thisHubDoesNotReport`,`This hub does not report the panel's live state yet — update it to arm from here.`)})]});let x=v.isPending||y.isPending||b.isPending;return e(Zt,{className:`p-4`,children:[e(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[e(`div`,{children:[i(`h3`,{className:`text-sm font-semibold`,children:r(`system.alarmLiveCard.panel`,`Panel`)}),i(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:ha(t)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[x?i(g,{className:`h-4 w-4 animate-spin`}):null,t.availableModes.map(e=>i(K,{type:`button`,size:`md`,variant:`outline`,disabled:x,onClick:()=>v.mutate(e),"data-testid":`alarm-arm-${e}`,children:r(`system.alarmLiveCard.arm`,{mode:ra(e)})},e)),i(K,{type:`button`,size:`md`,variant:ga(t.state)?`danger`:`secondary`,disabled:x,onClick:()=>b.mutate(),"data-testid":`alarm-disarm`,children:r(`system.alarmLiveCard.disarm`,`Disarm`)})]})]}),l===null?null:i(`div`,{className:`mt-3`,children:i(pt,{title:r(`system.alarmLiveCard.thePanelDidNotDo`,`The panel did not do that`),message:l})}),f===null?null:i(`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:[i(`p`,{className:`text-sm font-medium`,children:ta(s.blocking.length)}),s.blocking.length>0?i(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:s.blocking.map(t=>e(`li`,{children:[ea(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:[i(K,{type:`button`,size:`md`,variant:`danger`,disabled:x,onClick:()=>y.mutate(s.refusalId),children:r(`system.alarmLiveCard.armAnyway`,`Arm anyway`)}),i(`span`,{className:`text-xs text-foreground-subtle`,children:r(`system.alarmLiveCard.eachOpenDeviceIsIgnored`,`Each open device is ignored until it closes, then monitored again.`)})]})]}),e(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[i(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:r(`system.alarmLiveCard.excludedSensors`,`Excluded sensors`)}),t.exclusions.length===0?i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.alarmLiveCard.noSensorIsExcluded`,`No sensor is excluded.`)}):i(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:t.exclusions.map(t=>e(`li`,{children:[ea(t),` —`,` `,i(`span`,{className:`text-foreground-subtle`,children:_a(t.phase)})]},t.deviceId))})]})]})}c();var Ra=[{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:Ee,zeroMeansKey:`system.alarmDelay.sirenZero`}];function za(e){return q.t(`system.alarmDelay.rangeError`,{max:e})}function Ba(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${za(t)}`}function Va({label:t,value:n,max:r,zeroMeans:a,disabled:s,testId:c,hint:l,adornment:u,onCommit:d}){let[f,p]=o(null),[m,h]=o(null),g=f??String(n),_=f!==null&&f.trim()!==``&&la(f,r)===null,v=ia(n,a),y=()=>{let e=f===null?null:la(f,r);p(null),e===null?f!==null&&h(f):(h(null),d(e))};return e(Yt,{label:t,...l===void 0?{}:{description:l},..._?{error:za(r)}:m===null?{}:{error:Ba(m,r)},children:[e(`div`,{className:`flex items-center gap-2`,children:[i(U,{type:`number`,min:0,max:r,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}),i(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),u]}),v===`${n} s`?null:i(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function Ha(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=St(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function Ua(e){switch(e.kind){case`checking`:return{word:q.t(`system.alarmSensorTable.cellChecking`),note:null};case`hub-too-old`:return{word:q.t(`system.alarmSensorTable.cellUnknown`),note:q.t(`system.alarmSensorTable.cellHubTooOld`)};case`read-failed`:return{word:q.t(`system.alarmSensorTable.cellUnknown`),note:q.t(`system.alarmSensorTable.cellReadFailedError`,{error:e.error})};case`open`:case`closed`:return{word:e.word,note:e.offline?q.t(`system.alarmSensorTable.cellOfflineLastKnown`):null};case`unknown`:return{word:q.t(`system.alarmSensorTable.cellUnknown`),note:e.why===`not-answered`?q.t(`system.alarmSensorTable.cellNotAnswered`):e.why===`read-failed`?q.t(`system.alarmSensorTable.cellReadFailed`):q.t(`system.alarmSensorTable.cellNoState`)};case`not-opening`:return{word:q.t(`system.alarmSensorTable.cellNotOpening`),note:null};case`removed`:return{word:q.t(`system.alarmSensorTable.cellRemoved`),note:q.t(`system.alarmSensorTable.cellRemovedNote`)}}}function Wa(){return q.t(`system.alarmSensorTable.listedUncovered`)}function Ga(e){return e.listedUncovered?{word:q.t(`system.alarmSensorTable.cellNo`),note:Wa()}:Ka(e.coverage)}function Ka(e){switch(e.kind){case`arm-checked`:return{word:q.t(`system.alarmSensorTable.cellYes`),note:null};case`arm-checked-skipped`:{let t=e.reason===`detection-off`?q.t(`system.alarmSensorTable.detectionOff`):e.reason;return{word:q.t(`system.alarmSensorTable.cellSkipped`),note:q.t(`system.alarmSensorTable.cellSkippedNote`,{why:t})}}case`unscoped`:return{word:q.t(`system.alarmSensorTable.cellAllDevices`),note:q.t(`system.alarmSensorTable.cellNeverBlocks`)};case`not-covered`:return{word:q.t(`system.alarmSensorTable.cellNo`),note:q.t(`system.alarmSensorTable.cellNeverBlocks`)}}}function qa(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 Ja(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 Ya({name:t,variant:n,words:r}){return e(`span`,{"data-testid":`alarm-cell-${t}`,className:`flex flex-col items-start gap-0.5`,children:[i(G,{variant:n,"data-testid":`alarm-cell-${t}-badge`,children:r.word}),r.note===null?null:i(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${t}-note`,children:r.note})]})}var Xa=`hidden sm:table-cell`;function Za({id:e,stored:t}){return i(`span`,{className:`truncate text-xs font-medium text-foreground`,children:Jt(e,`compact`,t)})}function Qa(e){let t=Jt(e.deviceId,`compact`,e.storedName);return i(W,{checked:e.checked,onCheckedChange:e.onCheckedChange,disabled:e.disabled,"data-device-id":String(e.deviceId),"data-testid":e.testId,"aria-label":q.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 $a(t){let{mode:n,inFlight:r,onSwitch:a,zones:o,disabled:s}=t;return[{key:`name`,header:q.t(`system.alarmSensorTable.name`,`Name`),cell:t=>{let n=Ha(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:[i(Za,{id:t.device.id,stored:t.device.name}),n===``?null:i(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:n})]})}},{key:`type`,header:q.t(`system.alarmSensorTable.type`,`Type`),headerClassName:Xa,cellClassName:`${Xa} text-[11px] text-foreground-subtle`,cell:e=>Ht(e.device.type??null,er)},{key:`state`,header:q.t(`system.alarmSensorTable.state`,`State`),cell:e=>i(Ya,{name:`state`,variant:qa(e.cell),words:Ua(e.cell)})},{key:`coverage`,header:q.t(`system.alarmSensorTable.checkedWhenArming`,`Checked when arming`),headerClassName:Xa,cellClassName:Xa,cell:e=>i(Ya,{name:`coverage`,variant:Ja(e),words:Ga(e)})},{key:`blocks`,header:q.t(`system.alarmSensorTable.blocksArming`,`Blocks arming`),headerClassName:`text-right`,cellClassName:`text-right`,cell:t=>{let o=r!==null&&r.mode===n&&r.deviceId===t.device.id&&r.kind===`blocks`,c=r!==null&&!o;return e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[o?i(g,{className:`h-3 w-3 animate-spin`}):null,i(Qa,{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:i(`span`,{title:q.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),children:q.t(`system.alarmSensorTable.secureOnArm`,`Secure on arm`)}),headerClassName:`text-right`,cellClassName:`text-right`,cell:t=>{if(!t.controllable)return i(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let o=r!==null&&r.mode===n&&r.deviceId===t.device.id&&r.kind===`secureOnArm`,c=r!==null&&!o;return e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[o?i(g,{className:`h-3 w-3 animate-spin`}):null,i(Qa,{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:q.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`)})]})}}]}function eo(t){let{t:n}=J(),r=_(),{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:[i(`span`,{children:n(`system.alarmSensorTable.couldNotReadTheSensor`,`Could not read the sensor states.`)}),i(K,{type:`button`,size:`sm`,variant:`outline`,onClick:s,children:n(`common.retry`,`Retry`)})]}),i(Vt,{mode:`generic`,items:o,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,Ha(e.device.location,c),Ht(e.device.type??null,r)].join(` `),getFilterType:e=>Ht(e.device.type??null,r),columns:$a(t),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:n(`system.alarmSensorTable.searchSensors`,`Search sensors`),emptyLabel:`No sensor matches.`})]})}var to=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function no(e){return to.some(t=>t.test(e))}function ro(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return no(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 io(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 ao(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 oo(e){return e.kind===`unscoped`||e.kind===`not-covered`}function so(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=ao(e.coverage,r.id),a=io(e.sensors,r.id,t,r.type),o=Le({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=Fe({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&&oo(i)&&(!o||c)&&c;!t&&oo(i)&&!c||n.push({device:r,removed:t,cell:ro(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function co(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function lo(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 uo(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 fo(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 po(e,t){return Ge(fo(e),t)?{kind:`landed`}:{kind:`not-landed`}}var mo=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function ho({coverage:t,settings:n,disabled:r,onNotifyEdit:a}){let{t:o}=J(),s=Ue(n,t.mode);return e(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${t.mode}`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:o(`notificationRules.alarmNotify.title`)}),mo.map(({field:n,key:c})=>e(`div`,{className:`flex items-start justify-between gap-3`,children:[e(`div`,{className:`min-w-0`,children:[i(`p`,{className:`text-xs text-foreground`,children:o(`notificationRules.alarmNotify.${c}`)}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`notificationRules.alarmNotify.${c}Hint`)})]}),i(W,{checked:s[n],onCheckedChange:e=>a(n,e),disabled:r,"data-testid":`alarm-notify-${t.mode}-${n}`,"aria-label":o(`notificationRules.alarmNotify.${c}`)})]},n))]})}function go({coverage:t,rows:n,names:r}){let{t:a}=J(),o=n.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,s=aa(t,r.nameOf);return e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${t.mode}`,children:[ca(t)?i(G,{variant:`warning`,title:s,"data-testid":`alarm-arms-nothing`,children:a(`system.alarmModeCard.armsNothingNoEnabledRule`,`Arms nothing — no enabled rule is gated on this mode`)}):i(G,{variant:`default`,title:s,"data-testid":`alarm-covers`,children:a(`system.alarmModeCard.checksSensors`,{count:o})}),t.skippedDevices.length>0?i(G,{variant:`warning`,title:oa(t.skippedDevices,r.nameOf),"data-testid":`alarm-skipped`,children:a(`system.alarmModeCard.notNotified`,{count:t.skippedDevices.length})}):null]})}function _o(e){return e.status===`answered`?e.openingIds:null}function vo({check:t,view:n}){let{t:r}=J();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:[i(g,{className:`h-3 w-3 animate-spin`}),r(`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:[i(`span`,{children:r(`system.alarmModeCard.openingsCheckFailed`,{error:t.error})}),i(K,{type:`button`,size:`sm`,variant:`outline`,onClick:t.retry,children:r(`common.retry`,`Retry`)})]}):null:null}var yo=[{value:`rearmAfter`,labelKey:`system.alarmModeCard.postRearm`},{value:`disableAfter`,labelKey:`system.alarmModeCard.postDisarm`},{value:`doNothing`,labelKey:`system.alarmModeCard.postNothing`}];function bo({coverage:t,settings:n,disabled:r,onDelayEdit:a,onPostTriggeredEdit:o,onScheduleEdit:s}){let{t:c}=J(),l=t.mode,u=Ve(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:[Ra.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let t=u.source[e.field]==="default";return i(Va,{label:c(e.labelKey),value:u[e.field],max:e.max,zeroMeans:c(e.zeroMeansKey),disabled:r,testId:`alarm-delay-${l}-${e.key}`,onCommit:t=>a(e.field,t),adornment:t?i(G,{variant:`default`,title:c(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:n[e.field]}),children:c(`system.alarmModeCard.default`,`Default`)}):i(K,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,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:i(L,{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?i(G,{variant:`default`,className:`ml-1.5 align-middle`,title:c(`system.alarmModeCard.usesTheSystemDefault`,`Uses the system default`),children:c(`system.alarmModeCard.default`,`Default`)}):i(K,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:r,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:i(L,{className:`h-3.5 w-3.5`})})]}),i(F,{className:`mt-1 w-full`,value:u.postTriggeredAction,disabled:r,"data-testid":`alarm-delay-${l}-post`,onChange:e=>{let t=pe.safeParse(e.target.value);t.success&&o(t.data)},children:yo.map(e=>i(`option`,{value:e.value,children:c(e.labelKey)},e.value))})]}),f?Ra.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let t=u.source[e.field]==="default";return i(Va,{label:c(e.labelKey),value:u[e.field],max:e.max,zeroMeans:c(e.zeroMeansKey),disabled:r,testId:`alarm-delay-${l}-${e.key}`,onCommit:t=>a(e.field,t),adornment:t?i(G,{variant:`default`,title:c(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:n[e.field]}),children:c(`system.alarmModeCard.default`,`Default`)}):i(K,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,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:i(L,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),e(`div`,{"data-testid":`alarm-schedule-${l}`,children:[i(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.alarmModeCard.activationSchedule`,`Activation schedule`)}),i(`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.`)}),i(`fieldset`,{disabled:r,className:`min-w-0 border-0 p-0`,children:i(Fr,{value:p,onChange:s,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var xo={"no-opening":`This household has no contact, cover or lock.`};function So({coverage:t,live:n,settings:r,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:_}=J(),v=Zi({live:n,listed:va(r,t.mode),openingIds:_o(o)}),y=Qi(v),b=co({rowCount:s.length,candidatesComplete:!v.unresolved});return e(`div`,{className:`flex flex-col gap-3`,"data-mode":t.mode,"data-empty":ca(t)?`true`:`false`,children:[i(go,{coverage:t,rows:s,names:a}),i(bo,{coverage:t,settings:r,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:_(`system.alarmModeCard.delaysHint`,{seconds:30})}),i(ho,{coverage:t,settings:r,disabled:g,onNotifyEdit:h}),e(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${t.mode}`,children:[i(vo,{check:o,view:v}),y===null?null:i(`p`,{className:`text-xs text-foreground-subtle`,children:xo[y]}),b===`none`&&y===null?i(`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`?i(eo,{mode:t.mode,rows:s,sensorsRetry:c,inFlight:l,onSwitch:u,zones:d,disabled:g}):null]})]})}c();function Co({profiles:t,busy:n,onActivate:r,onCreate:a,onClone:s,onRename:c,onDelete:l}){let{t:u}=J(),[d,p]=o(``),[m,h]=o(!1),g=t.items.find(e=>e.id===t.activeId)??t.items[0],_=g!==void 0&&!g.isDefault,v=d.trim(),y=()=>{v.length!==0&&(a(v),p(``))},b=()=>{v.length===0||g===void 0||(s(g.id,v),p(``))},x=()=>{v.length===0||g===void 0||(c(g.id,v),p(``),h(!1))};return e(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface p-3`,"data-testid":`alarm-profiles`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:u(`system.alarmProfileBar.profile`,`Profile`)}),i(F,{wrapperClassName:`inline-block w-auto`,id:`alarm-profile-select`,className:`min-w-[10rem]`,"data-testid":`alarm-profile-select`,disabled:n,value:t.activeId,onChange:e=>r(e.target.value),children:t.items.map(t=>e(`option`,{value:t.id,children:[t.name,t.isDefault?` (${u(`system.alarmProfileBar.defaultSuffix`)})`:``]},t.id))}),_?i(K,{type:`button`,variant:`ghost`,size:`sm`,disabled:n,"data-testid":`alarm-profile-delete`,title:u(`system.alarmProfileBar.deleteThisProfile`,`Delete this profile`),onClick:()=>{g!==void 0&&l(g.id)},children:i(D,{className:`h-3.5 w-3.5`})}):null]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(U,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:m?u(`system.alarmProfileBar.newName`,`New name`):u(`system.alarmProfileBar.newProfileName`,`New profile name`),value:d,disabled:n,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(m?x():y())}}),m?e(f,{children:[i(K,{type:`button`,size:`sm`,disabled:n||v.length===0,"data-testid":`alarm-profile-rename-save`,onClick:x,children:u(`system.alarmProfileBar.rename`,`Rename`)}),i(K,{type:`button`,variant:`ghost`,size:`sm`,disabled:n,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{h(!1),p(``)},children:u(`common.cancel`,`Cancel`)})]}):e(f,{children:[e(K,{type:`button`,size:`sm`,disabled:n||v.length===0,"data-testid":`alarm-profile-create`,title:u(`system.alarmProfileBar.createWithSystemDefaults`,`Create with system defaults`),onClick:y,children:[i(E,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.create`,`Create`)]}),e(K,{type:`button`,size:`sm`,variant:`secondary`,disabled:n||v.length===0||g===void 0,"data-testid":`alarm-profile-clone`,title:u(`system.alarmProfileBar.cloneTheSelectedProfile`,`Clone the selected profile`),onClick:b,children:[i(M,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.clone`,`Clone`)]}),i(K,{type:`button`,size:`sm`,variant:`ghost`,disabled:n||g===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{h(!0),p(g?.name??``)},children:u(`system.alarmProfileBar.rename`,`Rename`)})]})]}),i(`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.`)})]})}c();var wo=[`notificationRules`,`getAlarmConfig`],To=[`notificationRules`,`getAlarmSensors`],Eo=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],Do=6e4;function Oo(e){return e instanceof Error?e.message:String(e)}function ko({notice:e}){let{t}=J();switch(e.kind){case`refused`:return i(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:t(`system.notificationAlarm.refused`,{name:e.inFlight.name,mode:ra(e.inFlight.mode)})});case`not-landed`:return i(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:t(`system.notificationAlarm.notLanded`,{name:e.write.name,mode:ra(e.write.mode)})});case`failed`:return i(`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:ra(e.write.mode),error:e.error})})}}function Ao(){let{t:r}=J(),a=N(),c=l(),f=s({queryKey:wo,queryFn:async()=>a.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>pa(e.state.data?.live?.state)}),p=Ot({projection:`slim`}),[m,_]=o(!1),v=d({mutationFn:e=>a.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{c.setQueryData(wo,e),_(!Ge(t,e.settings))}}),y=d({mutationFn:async e=>{switch(e.kind){case`activate`:return a.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return a.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return a.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return a.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return a.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{c.setQueryData(wo,e),_(!1)}}),b=()=>c.invalidateQueries({queryKey:wo}),x=n(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),S=f.data?.live,C=s({queryKey:Eo,staleTime:Do,queryFn:async()=>new Set(await a.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...Yi]}))}),w=n(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),T=n(()=>new Map(w.map(e=>[e.id,e])),[w]),E=C.isError?{status:`failed`,error:C.error instanceof Error?C.error.message:String(C.error),retry:()=>void C.refetch()}:C.data===void 0?{status:`pending`}:{status:`answered`,openingIds:C.data},D=n(()=>{let e=new Map;for(let t of S?.openings??[])for(let n of t.devices)e.set(n.deviceId,ea(n));return $i(x,Ft(p),e)},[S,x,p]),O=Wt(!0),[k,A]=o(null),j=n(()=>{let e=new Map,t=f.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,Zi({live:t.live,listed:va(t.settings,n.mode),openingIds:C.data??null}).ids);return e},[f.data,C.data]),M=n(()=>{let e=new Set;for(let t of j.values())for(let n of t)D.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[j,D]),P=s({queryKey:[...To,M],enabled:M.length>0,placeholderData:u,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&no(Oo(e.state.error))?!1:S!==void 0&&ga(S.state)?5e3:15e3,retry:(e,t)=>!no(Oo(t))&&e<2,queryFn:async()=>{let e=[];for(let t of lo(M,500))e.push(await a.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...t]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),ee=P.isError?{status:`failed`,error:Oo(P.error)}:P.data===void 0?{status:`pending`}:{status:`answered`,sensors:P.data.sensors},te=t(null),[ne,F]=o(null),[I,re]=o(null),ie=async e=>{try{let t=await a.trpcClient.notificationRules.setAlarmConfig.mutate({patch:fo(e)});po(e,t.settings).kind===`landed`?c.setQueryData(wo,t):(re({kind:`not-landed`,write:e}),c.invalidateQueries({queryKey:wo}))}catch(t){re({kind:`failed`,write:e,error:Oo(t)}),c.invalidateQueries({queryKey:wo})}finally{te.current=null,F(null),re(e=>e?.kind===`refused`?null:e)}},L=(e,t,n,r)=>{let i=uo(te.current,e,t,n,r);if(i.kind===`refused`){re({kind:`refused`,inFlight:i.inFlight});return}te.current=i.write,F(i.write),re(null),ie(i.write)};if(f.isLoading)return i(Li,{embedded:!0,icon:h,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(g,{className:`h-5 w-5 animate-spin`})});let R=f.data;if(R===void 0||f.isError)return i(Li,{embedded:!0,icon:h,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(pt,{title:r(`system.notificationAlarm.alarmSettingsAreNotAvailable`,`Alarm settings are not available`),message:r(`system.notificationAlarm.thisHubHasNotBeen`,`This hub has not been updated to serve the alarm configuration yet.`)})});if(R.deviceId===null)return i(Li,{embedded:!0,icon:h,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(Zt,{className:`p-4`,children:i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`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 z=R.settings,ae=v.isPending||y.isPending,oe=e=>{_(!1),v.mutate(e)},se=(e,t,n)=>{let r=Ca(z,e,t,n);r!==null&&oe({modeDelays:[r]})},ce=(e,t)=>{let n=wa(z,e,t);n!==null&&oe({modeDelays:[n]})},le=(e,t)=>{let n=Ta(z,e,t);n!==null&&oe({modeDelays:[n]})},ue=(e,t,n)=>{let r=Ma(z,e,t,n);r!==null&&oe({modeDelays:[r]})},de=new Map(R.coverage.map(e=>[e.mode,so({candidates:(j.get(e.mode)??[]).map(e=>({...T.get(e),id:e,name:D.nameOf(e)})),removedIds:new Set((j.get(e.mode)??[]).filter(D.isRemoved)),coverage:e,nonBlocking:va(z,e.mode),blocking:ya(z,e.mode),secureOnArmOff:ba(z,e.mode),sensors:ee})])),fe=R.coverage.find(e=>e.mode===k)??R.coverage.find(e=>(de.get(e.mode)?.length??0)>0)??R.coverage[0],pe=fe?.mode??``;return e(Li,{embedded:!0,icon:h,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.thePanelWhatEachMode`,`The panel, what each mode arms, and who hears about it.`),children:[v.isError?i(pt,{title:r(`system.notificationAlarm.couldNotSave`,`Could not save`),message:String(v.error)}):null,y.isError?i(pt,{title:r(`system.notificationAlarm.couldNotUpdateProfile`,`Could not update profile`),message:String(y.error)}):null,m?i(`div`,{"data-testid":`alarm-save-not-landed`,children:i(pt,{variant:`warning`,title:r(`system.notificationAlarm.notApplied`,`Not applied`),message:r(`system.notificationAlarm.theHubDidNotApply`,`The hub did not apply this change — another editor may have changed it, or the hub needs an update`)})}):null,R.profiles===void 0?null:i(Co,{profiles:R.profiles,busy:ae,onActivate:e=>y.mutate({kind:`activate`,id:e}),onCreate:e=>y.mutate({kind:`create`,name:e}),onClone:(e,t)=>y.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>y.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>y.mutate({kind:`delete`,id:e})}),i(La,{live:R.live,onChanged:b}),e(Zt,{className:`p-4`,"data-testid":`alarm-coverage`,children:[i(Xt,{value:pe,onValueChange:e=>{let t=R.coverage.find(t=>t.mode===e);t!==void 0&&A(t.mode)},children:i(qt,{className:`mb-3`,children:R.coverage.map(t=>e($t,{value:t.mode,"data-testid":`alarm-tab-${t.mode}`,children:[ra(t.mode),i(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:de.get(t.mode)?.length??0})]},t.mode))})}),I===null?null:i(ko,{notice:I}),fe===void 0?null:i(So,{coverage:fe,live:R.live,settings:z,names:D,openingsCheck:E,rows:de.get(fe.mode)??[],sensorsRetry:ee.status===`failed`&&!no(ee.error)?()=>void P.refetch():null,inFlight:ne,onSwitch:(e,t,n)=>L(fe.mode,e,t,n),zones:O,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 jo=`history`,Mo=`ruleId`,No=[Mo],Po=24,Fo=0,Io=100;function Lo(e,t){let n=new URLSearchParams(e);return n.set(`tab`,jo),n.set(Mo,t),n}function Ro(e,t){let n=new URLSearchParams(e);return t===``?n.delete(Mo):n.set(Mo,t),n}function zo(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Po:Fo,limit:Io}}function Bo(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?q.t(`helpers.notificationHistory.deletedRule`,{id:e.selected}):e.selected}]:[];return[{value:``,label:q.t(`helpers.notificationHistory.allRules`)},...t,...n]}c();var Vo=[{value:1,labelKey:`system.notificationHistory.windowLastHour`},{value:24,labelKey:`system.notificationHistory.windowLast24h`},{value:168,labelKey:`system.notificationHistory.windowLast7d`},{value:0,labelKey:`system.notificationHistory.windowAllTime`}],Ho=[{value:``,labelKey:`system.notificationHistory.statusAny`},{value:`pending`,labelKey:`system.notificationHistory.statusPending`},{value:`sent`,labelKey:`system.notificationHistory.statusSent`},{value:`dead`,labelKey:`system.notificationHistory.statusDead`}],Uo=[50,100,250,500];function Wo(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Go(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Ko(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 qo({entry:t,cameraName:n,onClose:r}){let{t:a}=J(),o=Ko(t),s=t.subject.systemEvent;return i(At,{open:!0,onOpenChange:e=>!e&&r(),children:e(bt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[i(Pt,{children:i(Mt,{className:`min-w-0 break-words`,children:o.title||t.ruleName})}),i(ht,{children:e(`dl`,{className:`space-y-3`,children:[e(`div`,{children:[i(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:a(`system.notificationHistory.body`,`Body`)}),i(`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:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.when`,`When`)}),i(`dd`,{className:`text-foreground`,children:new Date(t.createdAt).toLocaleString()})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.status`,`Status`)}),i(`dd`,{className:`text-foreground`,children:t.status})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.rule`,`Rule`)}),i(`dd`,{className:`text-foreground`,children:t.ruleName})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.device`,`Device`)}),i(`dd`,{className:`text-foreground`,children:n})]}),s===void 0?null:e(`div`,{className:`col-span-2`,children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.kind`,`Kind`)}),i(`dd`,{className:`text-foreground`,children:s.kind})]}),t.error===void 0?null:e(`div`,{className:`col-span-2`,children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`common.error`,`Error`)}),i(`dd`,{className:`text-danger`,children:t.error})]})]})]})}),i(_t,{children:i(K,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:a(`common.close`,`Close`)})})]})})}function Jo(){let{t}=J(),r=N(),[a,c]=Yn(),[l,u]=o(()=>zo(a)),[d,f]=o(null),m=e=>u(t=>({...t,...e})),h=e=>{m({ruleId:e}),c(Ro(a,e),{replace:!0})},_=s({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await r.trpcClient.notificationRules.listRules.query({})).rules}),v=Ot({projection:`slim`}),y=Date.now(),b=s({queryKey:[`notificationRules`,`getHistory`,l],retry:!1,queryFn:async()=>{let e=l.windowHours>0?y-l.windowHours*36e5:void 0;return(await r.trpcClient.notificationRules.getHistory.query({filter:{limit:l.limit,...l.ruleId?{ruleId:l.ruleId}:{},...l.deviceId?{deviceId:Number(l.deviceId)}:{},...Wo(l.status)?{status:Wo(l.status)}:{},...e===void 0?{}:{since:e}}})).entries}}),x=n(()=>{let e=new Map;for(let t of v.data??[])t.type===Ke.Camera&&e.set(t.id,t.name);return e},[v.data]),S=e=>x.get(e)??t(`system.notificationHistory.cameraFallback`,{deviceId:e}),C=b.data??[],T=b.isError;return e(Li,{embedded:!0,icon:w,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:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.rule`,`Rule`)}),i(F,{"data-testid":`history-rule-filter`,value:l.ruleId,onChange:e=>h(e.target.value),options:[...Bo({rules:_.data??[],answered:_.isSuccess,selected:l.ruleId})]})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.camera`,`Camera`)}),i(F,{value:l.deviceId,onChange:e=>m({deviceId:e.target.value}),options:[{value:``,label:t(`system.notificationHistory.allCameras`,`All cameras`)},...(v.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.status`,`Status`)}),i(F,{value:l.status,onChange:e=>m({status:e.target.value}),options:Ho.map(e=>({value:e.value,label:t(e.labelKey)}))})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.window`,`Window`)}),i(F,{value:String(l.windowHours),onChange:e=>m({windowHours:Number(e.target.value)}),options:Vo.map(e=>({value:String(e.value),label:t(e.labelKey)}))})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.limit`,`Limit`)}),i(F,{value:String(l.limit),onChange:e=>m({limit:Number(e.target.value)}),options:Uo.map(e=>({value:String(e),label:String(e)}))})]})]}),b.isLoading&&i(`div`,{className:`flex items-center justify-center py-16`,children:i(g,{className:`h-6 w-6 animate-spin text-primary`})}),T&&!b.isLoading&&i(Zt,{children:e(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[i(w,{className:`h-6 w-6 text-foreground-subtle`}),i(`div`,{className:`text-sm font-medium text-foreground`,children:t(`system.notificationHistory.deliveryHistoryRequiresAServer`,`Delivery history requires a server update`)}),i(`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(K,{variant:`unstyled`,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:[i(p,{className:`h-3 w-3`}),` `,t(`common.retry`)]})]})}),!T&&!b.isLoading&&C.length===0&&i(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:t(`system.notificationHistory.noDeliveriesMatchTheseFilters`,`No deliveries match these filters.`)}),!T&&C.length>0&&i(Zt,{children:i(mt,{columns:Yo(S),rows:C,rowKey:e=>e.id,minWidthPx:720,bordered:!1,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>f(e)})}),d!==null&&i(qo,{entry:d,cameraName:S(d.deviceId),onClose:()=>f(null)})]})}function Yo(t){return[{key:`when`,header:q.t(`system.notificationHistory.when`,`When`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:q.t(`system.notificationHistory.rule`,`Rule`),render:e=>i(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:q.t(`system.notificationHistory.camera`,`Camera`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t(e.deviceId)})},{key:`subject`,header:q.t(`system.notificationHistory.notification`,`Notification`),render:t=>{let n=Ko(t);return e(`span`,{className:`block max-w-[18rem]`,children:[i(`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?i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:n.body}):null]})}},{key:`status`,header:q.t(`system.notificationHistory.status`,`Status`),nowrap:!0,render:t=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(G,{variant:Go(t.status),children:t.status}),t.attempts>1?e(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,t.attempts]}):null]})},{key:`error`,header:q.t(`system.notificationHistory.detail`,`Detail`),render:e=>e.error?i(`span`,{className:`text-[11px] text-danger`,children:e.error}):i(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var Xo=/\{\{\s*(\w+)\s*\}\}/g,Zo=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function Qo(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function $o(e){return[...e.matchAll(Xo)].map(e=>e[1]??``).filter(e=>e.length>0)}function es(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function ts(e,t){return[...new Set($o(e))].filter(e=>!es(e,t))}var ns={previewText:[`device`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function rs(e){return e.map(e=>{let t=He.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)||B.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function is(e){let t=new Set(e.map(e=>e.name)),n=He.filter(e=>fe(e)&&!t.has(e.name));return[...e,...n]}function as(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=ns[t.field];return e.filter(e=>e.families.includes(t.family)&&n.includes(e.name)&&!e.dynamic)}return e.filter(e=>!e.families.includes(t.family)||e.fields&&!e.fields.includes(t.field)||!De(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:Ne(e,t)&&ke(e,t))}function os(e){return Zo.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var ss=[`nc`,`template-catalog`],cs=400;function ls(){let e=N();return s({queryKey:ss,staleTime:5*6e4,queryFn:async()=>is(rs((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function us(e,t,n){let r=N(),i=en(t.title??``,cs),a=en(t.body??``,cs);return s({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}:{}}})})}c();var ds={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},fs=`block text-[11px] font-medium text-foreground mb-1`;function ps({label:n,value:r,onChange:a,vars:o,multiline:s=!1,placeholder:c,disabled:l=!1,deviceValues:u=!0,testId:d}){let{t:f}=J(),p=t(null),m=t(null),h=o?ts(r,o):[],g=e=>{let t=Qo(e);if(u){p.current?.insertText(t.text,t.cursorOffset);return}let n=m.current,i=n?.selectionStart??r.length,o=n?.selectionEnd??r.length;a(r.slice(0,i)+t.text+r.slice(o));let s=i+t.cursorOffset;requestAnimationFrame(()=>{n?.focus(),n?.setSelectionRange(s,s)})},_=e=>a(e.target.value);return e(`div`,{className:`space-y-1`,children:[i(`label`,{className:fs,children:n}),u?i(Bt,{label:n,value:r,onChange:a,multiline:s,placeholder:c,disabled:l,handle:p,heldSlots:`placeholders`,testId:d}):s?i(It,{ref:m,"aria-label":n,value:r,rows:2,disabled:l,placeholder:c,onChange:_,"data-testid":`${d}-input`}):i(U,{ref:m,"aria-label":n,value:r,disabled:l,placeholder:c,onChange:_,"data-testid":`${d}-input`}),o&&o.length===0?i(`p`,{className:`text-[10px] text-foreground-subtle`,children:f(`notifications.templateField.noVariablesForThisField`,`No variables for this field.`)}):null,o&&o.length>0?i(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:os(o).map(t=>e(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${d}-group-${t.group}`,children:[i(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:ds[t.group]}),t.vars.map(e=>i(K,{variant:`unstyled`,type:`button`,disabled:l,onMouseDown:e=>e.preventDefault(),onClick:()=>g(e),title:`${e.description??e.label} — e.g. "${e.example}"`,className:`rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-foreground hover:bg-surface-hover`,"data-testid":`${d}-chip-${e.name}`,children:e.dynamic?f(`notifications.templateField.class`,`{{name}}<class>`,{name:e.name}):e.name},e.name))]},t.group))}):null,h.length>0?e(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${d}-unknown`,children:[i(v,{className:`h-3 w-3`}),f(`notifications.templateField.willBeEmpty`,{names:h.map(e=>`{{${e}}}`).join(` `)})]}):null]})}function ms({context:t,title:n,body:r,testId:a}){let{t:o}=J(),s=us(t,{title:n,body:r},!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:[i(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:o(`notifications.templateField.previewExampleValues`,`Preview (example values)`)}),s.data.title===null?null:i(`p`,{className:`font-medium`,children:s.data.title}),s.data.body===null?null:i(`p`,{className:`whitespace-pre-wrap`,children:s.data.body})]}):null}var hs=`/build?tab=actions&create=1`,gs=`/build?tab=actions&create=1&preset=${Ii}`,_s=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,vs=`block text-[11px] font-medium text-foreground`;function ys({title:t,description:n,children:r}){return e(`div`,{className:`flex flex-col gap-2`,children:[e(`div`,{children:[i(`h4`,{className:`text-xs font-semibold text-foreground`,children:t}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:n})]}),r!==void 0&&i(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function bs(){let{t}=J();return e(li,{to:hs,target:`_blank`,rel:`noopener noreferrer`,title:t(`system.notificationRuleActions.createActionHint`,`Opens the Actions page in a new tab. Reopen the list here afterwards.`),className:`inline-flex items-center gap-1 text-[11px] font-medium text-primary hover:underline`,children:[i(P,{className:`h-3.5 w-3.5 shrink-0`}),t(`system.notificationRuleActions.createActionLink`,`Create a new Action`)]})}function xs(){let{t:e}=J();return i(li,{to:gs,target:`_blank`,rel:`noopener noreferrer`,title:e(`system.notificationRuleActions.presetAlarmHint`,`Presses the alarm panel. The panel's entry delay still runs, and a disarm during it cancels the alarm.`),className:`inline-flex items-center gap-1 text-[11px] font-medium text-primary hover:underline`,children:e(`system.notificationRuleActions.presetAlarm`,`Trigger the alarm`)})}function Ss({value:t,actions:n,onChange:r}){let{t:a}=J(),o=t!==``&&!n.some(e=>e.id===t);return e(F,{wrapperClassName:`block w-full`,className:_s,value:t,onChange:e=>r(e.target.value),children:[t===``&&i(`option`,{value:``,children:a(`system.notificationRuleActions.pickAction`,`Pick an Action`)}),o&&i(`option`,{value:t,children:a(`system.notificationRuleActions.missingAction`,`Missing Action ({{id}})`,{id:t})}),n.map(e=>i(`option`,{value:e.id,children:e.name},e.id))]})}function Cs({value:t,onChange:n,actions:r,showProblems:a=!0}){let{t:o}=J(),s=ai(t,new Set(r.map(e=>e.id))),c=(e,r)=>n({...t,[e]:r}),l=(e,r)=>n({...t,buttons:t.buttons.map((t,n)=>n===e?r:t)});return e(`div`,{className:`space-y-4`,children:[a&&s.length>0?i(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:s.map(e=>i(`p`,{children:e.message},e.message))}):null,r.length===0&&e(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[o(`system.notificationRuleActions.noActionsYet`,`There are no Actions yet. Create one on the Actions page — a rule or a button runs an Action, it does not define its own steps.`),` `,i(bs,{}),` `,i(xs,{})]}),Dr.map(e=>i(ws,{hookKey:e,actionIds:t[e],actions:r,onChange:t=>c(e,t)},e)),e(`section`,{className:`space-y-2`,children:[e(ys,{title:o(`system.notificationRuleActions.buttonsOnTheNotification`,`Buttons on the notification`),description:o(`system.notificationRuleActions.eachButtonRunsOneAction`,`Each button runs one Action when tapped.`),children:[e(K,{size:`sm`,variant:`ghost`,type:`button`,disabled:r.length===0,onClick:()=>n({...t,buttons:[...t.buttons,kr(t.buttons.length,r[0]?.id??``)]}),children:[i(E,{className:`h-3.5 w-3.5 shrink-0`}),` `,o(`system.notificationRuleActions.button`)]}),i(bs,{}),i(xs,{})]}),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:[i(v,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),i(`span`,{children:i(jn,{i18nKey:`system.notificationRuleActions.buttonLinkNote`,components:{b:i(`strong`,{})}})})]}),t.buttons.length===0?i(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:o(`system.notificationRuleActions.noButtonsTheNotificationArrives`,`No buttons. The notification arrives with nothing to tap.`)}):t.buttons.map((e,a)=>i(Ts,{button:e,actions:r,onChange:e=>l(a,e),onRemove:()=>n({...t,buttons:t.buttons.filter((e,t)=>t!==a)})},`btn-${String(a)}`))]})]})}function ws({hookKey:t,actionIds:n,actions:r,onChange:a}){let{t:o}=J(),s=Xr[t];return e(`section`,{className:`space-y-2`,children:[i(ys,{title:s.title,description:s.hint,children:e(K,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.length>=4||r.length===0,onClick:()=>a([...n,r[0]?.id??``]),children:[i(E,{className:`h-3.5 w-3.5`}),` `,o(`system.notificationRuleActions.addAction`)]})}),n.length===0?i(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:o(`system.notificationRuleActions.nothingOnThisEdge`,`Nothing on this edge.`)}):n.map((s,c)=>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:[i(`label`,{className:vs,children:o(`system.notificationRuleActions.action`,`Action`)}),i(Ss,{value:s,actions:r,onChange:e=>a(n.map((t,n)=>n===c?e:t))})]}),i(K,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>a(n.filter((e,t)=>t!==c)),title:o(`common.remove`,`Remove`),children:i(D,{className:`h-3.5 w-3.5`})})]},`${t}-${String(c)}`))]})}function Ts({button:t,actions:n,onChange:r,onRemove:a}){let{t:o}=J();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:[i(`label`,{className:vs,children:o(`system.notificationRuleActions.id`,`Id`)}),i(U,{className:`mt-1`,value:t.id,onChange:e=>r({...t,id:e.target.value})})]}),e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:vs,children:o(`system.notificationRuleActions.label`,`Label`)}),i(U,{className:`mt-1`,value:t.label,onChange:e=>r({...t,label:e.target.value})})]}),e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:vs,children:o(`system.notificationRuleActions.action`,`Action`)}),i(Ss,{value:t.actionId,actions:n,onChange:e=>r({...t,actionId:e})})]}),e(`div`,{className:`w-32`,children:[i(`label`,{className:vs,children:o(`system.notificationRuleActions.icon`,`Icon`)}),e(F,{wrapperClassName:`inline-block w-auto`,className:_s,value:t.icon??``,onChange:e=>{let{icon:n,...i}=t,a=pi.find(t=>t.value===e.target.value);r(a===void 0?i:{...i,icon:a.value})},children:[i(`option`,{value:``,children:`—`}),pi.map(e=>i(`option`,{value:e.value,children:e.label},e.value))]})]}),i(K,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,title:o(`common.remove`,`Remove`),children:i(D,{className:`h-3.5 w-3.5`})})]})}function Es({param:e,value:t,onChange:n}){let{t:r}=J(),a=e.default===void 0?void 0:String(e.default);return e.type===`enum`?i(F,{value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`system.notificationRules.deliveryOptions.useDefault`,`Use the target setting`)},...e.options??[]]}):e.type===`boolean`?i(W,{checked:t===!0,onCheckedChange:e=>n(e),label:e.label}):i(U,{type:e.type===`number`?`number`:`text`,value:typeof t==`number`||typeof t==`string`?String(t):``,placeholder:a,min:e.min,max:e.max,onChange:t=>{let r=t.target.value;if(r===``)return n(void 0);if(e.type===`string`)return n(r);let i=Number(r);n(Number.isFinite(i)?i:void 0)}})}function Ds(e,t){return t.find(t=>t.kind===e.kind&&t.addonId===e.addonId)}function Os(e,t,n){let r=t.find(t=>t.id===e);return(r===void 0?void 0:Ds(r,n)?.deliveryParams)??[]}c();function ks(t){let{t:n}=J(),[r,a]=o(()=>new Set(t.targetIds.filter(e=>t.overrides[e]!==void 0)));if(t.targetIds.length===0)return null;let s=ur(t.targets,t.kinds),c=(e,t)=>a(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r});return e(`div`,{className:`flex flex-col gap-2`,"data-testid":`rule-target-settings`,children:[i(`p`,{className:`text-sm font-medium text-foreground`,children:n(`system.notificationRules.targetSettings.title`,`Per-target settings`)}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:n(`system.notificationRules.targetSettings.help`,`Each target follows the rule unless you change it here. A target offers only what its notifier can deliver.`)}),t.targetIds.map(e=>i(As,{...t,targetId:e,name:t.targets.find(t=>t.id===e)?.name??e,fields:s(e),expanded:r.has(e),onExpandedChange:t=>c(e,t)},e))]})}function As(t){let{t:n}=J(),{targetId:r,fields:a}=t,o=t.overrides[r]??{},s=t.surface??`rule`,c=e=>Ni(s,e)&&(a===void 0||a.includes(e)),l=t.onTargetParamsChange,u=t.targetParams??{},d=l===void 0?[]:Os(r,t.targets,t.kinds),f=Object.keys(o).length>0||u[r]!==void 0,p=e=>t.onOverridesChange(cr(t.overrides,r,Object.keys(e).length>0?e:void 0)),m=(e,t)=>{let{[e]:n,...r}=o.template??{},i=t===``?r:{...r,[e]:t},{template:a,...s}=o;p(Object.keys(i).length>0?{...s,template:i}:s)},h=e=>{let{priority:t,...n}=o;p(e===``?n:{...n,priority:Number(e)})},g=e=>{let{schedule:t,...n}=o;p(e===void 0?n:{...n,schedule:e})},_=e=>{let{attachment:t,...n}=o,r=Ae.safeParse(e);p(r.success?{...n,attachment:r.data}:n)},v=e=>{let{actions:t,...n}=o;p(e?{...n,actions:!1}:n)},y=cn(r,t.targets,t.kinds),b=y===void 0?void 0:{...y,attachmentKinds:$n(s,y.attachmentKinds)},x=b!==void 0&&b.levels.length>0?b.levels.map(e=>({value:e.ordinal??0,label:e.label})):Jn,S=x.find(e=>e.value===t.rulePriority)?.label;return i(ft,{expanded:t.expanded,onExpandedChange:t.onExpandedChange,header:e(`span`,{className:`flex items-center gap-2 text-xs`,"data-testid":`rule-target-settings-${r}`,children:[i(`span`,{className:`font-medium text-foreground`,children:t.name}),i(`span`,{className:`text-foreground-subtle`,children:f?n(`system.notificationRules.targetSettings.customised`,`Own settings`):n(`system.notificationRules.targetSettings.followsRule`,`Follows the rule`)})]}),children:e(`div`,{className:`flex flex-col gap-3`,children:[c(`title`)&&i(ps,{label:n(`system.notificationRules.targetSettings.titleOverride`,`Title for this target`),value:o.template?.title??``,onChange:e=>m(`title`,e),vars:t.varsFor(`title`),placeholder:n(`system.notificationRules.targetSettings.useRuleText`,`The rule's text`),testId:`rule-target-${r}-title`}),c(`body`)&&i(ps,{label:n(`system.notificationRules.targetSettings.bodyOverride`,`Body for this target`),value:o.template?.body??``,onChange:e=>m(`body`,e),vars:t.varsFor(`body`),placeholder:n(`system.notificationRules.targetSettings.useRuleText`,`The rule's text`),multiline:!0,testId:`rule-target-${r}-body`}),c(`priority`)&&i(Yt,{label:n(`system.notificationRules.priority`,`Priority`),children:i(F,{value:o.priority===void 0?``:String(o.priority),onChange:e=>h(e.target.value),options:[{value:``,label:n(`system.notificationRules.targetSettings.rulePriority`,{defaultValue:`The rule's priority ({{priority}})`,priority:S??String(t.rulePriority)})},...x.map(e=>({value:String(e.value),label:e.label}))],"data-testid":`rule-target-${r}-priority`})}),c(`attachments`)&&b!==void 0&&b.attachmentKinds.length>0&&i(Yt,{label:n(`system.notificationRules.targetSettings.attachment`,`Picture`),children:i(F,{value:o.attachment??``,onChange:e=>_(e.target.value),options:[{value:``,label:n(`system.notificationRules.targetSettings.attachmentRule`,`Whatever the rule produces`)},...b.attachmentKinds.map(e=>({value:e,label:n(`system.notificationRules.targetSettings.attachmentKind.${e}`,e)}))],"data-testid":`rule-target-${r}-attachment`})}),c(`actions`)&&i(W,{checked:o.actions===!1,onCheckedChange:v,label:n(`system.notificationRules.targetSettings.noButtons`,`No action buttons`),"data-testid":`rule-target-${r}-no-buttons`}),i(Yt,{label:n(`system.notificationRules.targetSettings.schedule`,`When this target is notified`),children:i(Fr,{value:o.schedule,onChange:g,emptyHint:n(`system.notificationRules.targetSettings.scheduleEmpty`,`Whenever the rule fires.`)})}),d.map(e=>i(Yt,{label:e.label,children:i(Es,{param:e,value:u[r]?.[e.key],onChange:t=>l?.(fr(u,r,e.key,t))})},e.key))]})})}function js({support:e}){let{t}=J();return e===void 0||e.droppedBy.length===0?null:i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-field-dropped-${e.field}`,children:t(`system.notificationRules.targetSettings.droppedBy`,{defaultValue:`Not delivered to: {{targets}}`,targets:e.droppedBy.join(`, `)})})}c();function Ms(){let e=N();return s({queryKey:[`notificationOutput`,`listTargetKinds`,`forRuleDelivery`],queryFn:()=>e.trpcClient.notificationOutput.listTargetKinds.query({})}).data??[]}function Ns(e){let t=Ms(),r=ls(),a=n(()=>wn(e.targets),[e.targets]),o=e.templateFamily;return i(ks,{surface:e.surface,targetIds:e.targetIds,targets:a,kinds:t,overrides:e.overrides,rulePriority:e.rulePriority,onOverridesChange:e.onChange,varsFor:e=>r.data!==void 0&&o!==void 0?as(r.data,{family:o,field:e}):void 0})}var Ps=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Fs=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],Is={minConfidence:`class`},Ls=[{id:`system`,get label(){return q.t(`notificationRules.groups.system`)}},{id:`class`,get label(){return q.t(`notificationRules.groups.class`)}},{id:`zones`,get label(){return q.t(`notificationRules.groups.zones`)}},{id:`label`,get label(){return q.t(`notificationRules.groups.label`)}},{id:`quality`,get label(){return q.t(`notificationRules.groups.quality`)}},{id:`scope`,get label(){return q.t(`notificationRules.groups.scope`)}},{id:`device`,get label(){return q.t(`notificationRules.groups.device`)}},{id:`package`,get label(){return q.t(`notificationRules.groups.package`)}},{id:`occupancy`,get label(){return q.t(`notificationRules.groups.occupancy`)}},{id:`audio`,get label(){return q.t(`notificationRules.groups.audio`)}},{id:`schedule`,get label(){return q.t(`notificationRules.groups.schedule`)}}];function Rs(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Fs)t.has(e)&&n.add(r);return n}function zs(e){return Is[e.id]??e.group}function Bs(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Vs(e){let t=Rs(e),n=e.filter(e=>!Ps.has(e.id)&&!t.has(e.id)),r=new Set(Ls.map(e=>e.id)),i=[],a=e=>n.filter(t=>zs(t)===e);for(let e of Ls){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=zs(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Bs(e),descriptors:a(e)});return i}function Hs(e,t){switch(e){case`zones`:return yi(t.zones?.ids,t.zonesExclude);case`labels`:return yi(t.labelEquals,void 0);case`identities`:return Us(t)}}function Us(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?yi(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function Ws(e,t,n){switch(e){case`zones`:return Gs(t,n);case`labels`:return Ks(t,n);case`identities`:return qs(t,n)}}function Gs(e,t){let{zones:n,zonesExclude:r,...i}=e,a=zr(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function Ks(e,t){let{labelEquals:n,...r}=e,i=zr(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function qs(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=ki(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=zr(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var Js={all:`All`,only:`Only these`,except:`All except these`},Ys={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 Xs({draft:t,onChange:n,exceptOffered:r,plural:a,renderPicker:o,describe:s,testId:c}){let{t:l}=J(),u=(e,t,n)=>l(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),d=l(`ruleScope.items.${a}`,Ys[a].items),f=Qr.filter(e=>e!==`except`||r||t.mode===`except`),p=ki(t),m=yr(t),h=t.mode===`all`?null:t.mode;return e(`div`,{className:`mt-1 space-y-1.5`,"data-testid":c,children:[i(`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 r=e===t.mode;return i(K,{variant:`unstyled`,type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${e}`,onClick:()=>n(tr(t,e)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,children:l(`ruleScope.mode.${e}`,Js[e])},e)})}),h===null?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:l(`ruleScope.every.${a}`,Ys[a].every)}):o(wr(t),e=>n(Ei(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(`, `)),` `,i(K,{variant:`unstyled`,type:`button`,className:`underline hover:no-underline`,onClick:()=>n(Ir(t)),children:l(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&i(`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 Zs(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 Qs(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})}c();function $s(e,t,n){let[r,i]=o(()=>Hs(e,t));return[r,r=>{i(r),n(Ws(e,t,r))}]}function ec(e,t){return t?`failed`:e?`pending`:`answered`}function tc({conditions:e,onConditionsChange:t,exceptOffered:r,cameraIds:a,cameras:o}){let{t:s}=J(),[c,l]=$s(`zones`,e,t),{options:u,loading:d,failed:f}=un(a,o),p=n(()=>Qs(u),[u]),m=ec(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 i(Xs,{draft:c,onChange:l,exceptOffered:r,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>a.length===0?i(`p`,{className:xi,children:s(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):i(wt,{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 nc({conditions:e,onConditionsChange:t,exceptOffered:r}){let{t:a}=J(),[o,s]=$s(`identities`,e,t),{options:c,loading:l,failed:u}=nr(),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 i(Xs,{draft:o,onChange:s,exceptOffered:r,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>i(wt,{devices:d,listState:ec(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 rc({conditions:e,onConditionsChange:t}){let{t:n}=J(),[r,a]=$s(`labels`,e,t);return i(Xs,{draft:r,onChange:a,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>i(wi,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function ic(e){let t=Me(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function ac(e){return e.type??q.t(`helpers.classPickerItems.other`)}c();function oc({taxonomy:e,scope:t,onChange:r,exceptOffered:a}){let{t:o}=J(),s=n(()=>ic(e),[e]),c=n(()=>new Map((s??[]).map(e=>[e.id,e.name])),[s]);return i(Xs,{draft:t,onChange:r,exceptOffered:a,plural:`classes`,describe:e=>c.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>s===null?i(wi,{value:e,placeholder:o(`system.notificationClassScopeField.addValue`,`Add value…`),onChange:t}):i(wt,{devices:s,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:ac,testId:`class-picker`},n)})}function sc(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function cc({devices:e,value:t,onChange:n,listState:r,savedHadDevices:a}){return i(wt,{devices:e.map(sc),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:a,noun:`device`,showAll:!0})}function lc({devices:e,scope:t,onChange:n,listState:r,savedScope:a,exceptOffered:o}){let s=new Map(e.map(e=>[e.id,e.name]));return i(Xs,{draft:t,onChange:n,exceptOffered:o,plural:`devices`,describe:e=>s.get(e)??q.t(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`rule-device-scope`,renderPicker:(t,n,o)=>i(cc,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(o===`only`?a.include:a.exclude).length>0},o)})}function uc(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function dc(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function fc(e){let t=uc(e),n=e.data===void 0?[]:Re(e.data.nodes),r=dc(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function pc(e){let t=uc(e),n=e.data===void 0?[]:ge(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var mc=[`nc-pickers`,`node-directory`],hc=[`nc-pickers`,`package-list`],gc=6e4,_c={get hub(){return q.t(`system.scopePickers.roleHub`)},get agent(){return q.t(`system.scopePickers.roleAgents`)}},vc={get server(){return q.t(`system.scopePickers.pkgServer`)},get framework(){return q.t(`system.scopePickers.pkgFramework`)},get wrapper(){return q.t(`system.scopePickers.pkgWrapper`)},get addon(){return q.t(`system.scopePickers.pkgAddons`)}};function yc(e){let t=_c[e.type??``]??q.t(`system.scopePickers.roleNodes`);return e.location===`offline`?q.t(`system.scopePickers.offlineSuffix`,{role:t}):t}function bc(e){return vc[e.type??``]??q.t(`system.scopePickers.pkgPackages`)}function xc({value:t,onChange:n,testId:r}){let{t:a}=J(),o=N().trpcClient,c=s({queryKey:mc,staleTime:gc,queryFn:()=>o.nodes.directory.query()}),l=fc(c);return e(`div`,{children:[i(wt,{devices:l.items,listState:l.listState,fleet:l.fleet,value:t,onChange:n,emptyMeansAll:!0,noun:`node`,groupTitle:yc,...r===void 0?{}:{testId:r}}),c.data?.complete===!1&&i(`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 Sc({value:e,onChange:t,testId:n}){let r=N().trpcClient,a=pc(s({queryKey:hc,staleTime:gc,queryFn:()=>r.addons.listPackages.query()}));return i(wt,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:bc,...n===void 0?{}:{testId:n}})}var Cc={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-consumable-low`]},template:{body:`{{deviceName}}`}};function wc(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 Tc(e,t){return e===`pending`?`pending`:e===`success`?`current`:wc(t)===`BAD_REQUEST`?`outdated`:`unknown`}function Ec(e){let t=N(),n=s({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(Cc)});return e?Tc(n.status,n.error):`pending`}c();var Dc=`/system/settings`,Oc=`/system/notifications?tab=alarm`,kc=`text-primary underline-offset-2 hover:underline`;function Ac(e,t){let n=zr(t);return fn(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function jc({family:t,value:r,cameras:a,allDevices:s,fleet:c,savedHadDevices:l,onChange:u,scheduleOnly:d=!1}){let{t:f}=J(),p=n(()=>r?.kinds??[],[r]),m=n(()=>s===void 0?a:s.map(sc),[s,a]),h=n(()=>a.map(e=>({id:e.id,name:e.name,type:`camera`})),[a]),g=rn(t,p),_=Ec(t===`device-events`),v=t===`alarm`,[y,b]=o(()=>yi(r?.deviceIds,r?.excludeDeviceIds)),[x]=o(()=>yi(r?.deviceIds,r?.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:[i(`p`,{className:xi,"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.`)}),In(t).map(n=>e(`div`,{children:[i(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:n.label}),i(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:Wr(n,d).map(e=>{let n=Gn(p,e),a=e.noSnapshot===!0?`${e.label} — ${f(`system.notificationSystemEventField.noSnapshot`,`no state snapshot, reports nothing`)}`:e.label;return i(K,{variant:`unstyled`,type:`button`,role:`checkbox`,"aria-checked":n,"aria-label":a,onClick:()=>u(vn(r,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):`),` `,i(li,{to:Dc,target:`_blank`,rel:`noreferrer`,className:kc,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:[i(li,{to:Oc,target:`_blank`,rel:`noreferrer`,className:kc,children:f(`system.notificationSystemEventField.alarmSettings`,`Alarm settings`)}),p.includes(`alarm-triggered`)&&i(`span`,{className:`ml-1`,children:f(`system.notificationSystemEventField.alarmPictures`)})]}),_===`outdated`&&i(`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`&&i(`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:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:f(`system.notificationSystemEventField.consumableLowAt`,`Consumable low at (%)`)}),i(U,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:ln,step:1,placeholder:`15`,value:r?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let t=hn(e.target.value);t.kind!==`invalid`&&u(fn(r,{consumableLowPercent:t.kind===`set`?t.value:void 0}))}})]}),g.deviceTypes&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.deviceTypes`,`Device types`)}),i(Di,{options:Si,value:r?.deviceTypes??[],onChange:e=>u(fn(r,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:f(`system.notificationSystemEventField.deviceType`,`Device type…`)})]}),ir(r)&&i(`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:[i(Xs,{draft:y,onChange:e=>{b(e),u(Ac(r,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)=>i(wt,{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`&&i(Nt,{noun:v?`camera`:`device`})]}),g.nodes&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.nodes`,`Nodes`)}),i(xc,{value:r?.nodeIds??[],onChange:e=>u(fn(r,{nodeIds:e})),testId:`system-event-nodes`})]}),g.packages&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.packages`,`Packages`)}),i(Sc,{value:r?.packageNames??[],onChange:e=>u(fn(r,{packageNames:e})),testId:`system-event-packages`})]})]})}function Mc({value:t}){let{t:n}=J(),r=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:[i(`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.`)}),r.length>0&&i(`p`,{className:`mt-1 text-foreground`,children:r.map(zn).join(`, `)})]})}function Nc({family:t,onChange:n}){let{t:r}=J();return e(`div`,{"data-testid":`system-family-select`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:r(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`)}),i(F,{value:t,"aria-label":r(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`),onChange:e=>{let t=e.target.value;Ye(t)&&n(t)},options:de.map(e=>({value:e,label:ze(e).label}))}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:r(`system.notificationSystemEventField.oneRuleAnswersOneQuestion`,`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`)})]})}c();function Pc({catalog:t,taxonomy:r,delivery:a,conditions:o,classScope:s,onClassScopeChange:c,actions:l,actionStepsOf:u,savedConditions:d,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x,scheduleOnly:S}){let{t:C}=J(),w=(e,t)=>{let n={...o};t===void 0?delete n[e]:n[e]=t,b(n)},T=R({delivery:a,conditions:o}),E=n(()=>t.filter(e=>ae(e,a,T)&&ni(e.id,o)),[t,a,T,o]),D=n(()=>Vs(E),[E]),O=e=>E.some(t=>t.id===e),k=e=>Ic.has(e.id)?i(oc,{taxonomy:r,scope:s,onChange:c,exceptOffered:O(`classesExclude`)}):Lc.has(e.id)?i(tc,{conditions:o,onConditionsChange:b,exceptOffered:O(`zonesExclude`),cameraIds:m??p,cameras:h}):Rc.has(e.id)?i(nc,{conditions:o,onConditionsChange:b,exceptOffered:O(`identitiesExclude`)}):e.id===`labelEquals`?i(rc,{conditions:o,onConditionsChange:b}):null;return i(`div`,{className:`space-y-4`,children:D.map(t=>e(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${t.id}`,children:[i(`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:[i(`label`,{className:Y,children:zc(t,C)}),n??i(Hc,{descriptor:t,kind:T,scheduleOnly:S===!0,taxonomy:r,conditions:o,actions:l,actionStepsOf:u,savedConditions:d,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:w,onScheduleChange:x}),Bc(t,C)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Bc(t,C)})]},t.id)})]},t.id))})}function Fc({kinds:t}){let{t:n,i18n:r}=J(),a=r.language.startsWith(`it`)?`it`:`en`,o=t.flatMap(e=>{let t=Se(e);return t===void 0?[]:[{kind:e,text:n(`system.notificationRuleConditions.transitionMeaning`,`{{kind}}: starts = {{starts}} · finishes = {{finishes}}`,{kind:Be(e,a),starts:t.starts[a],finishes:t.finishes[a],interpolation:{escapeValue:!1}})}]});return o.length===0?null:e(Rt,{className:`inline-block`,children:[i(Qt,{tabIndex:0,children:i(b,{className:`h-4 w-4 cursor-help text-foreground-subtle`,"aria-label":n(`system.notificationRuleConditions.transitionInfo`,`What start and finish mean`),"data-testid":`nc-sensor-transition-info`})}),i(Kt,{className:`left-auto right-0 translate-x-0`,children:i(`ul`,{className:`w-60 space-y-1 whitespace-normal text-left text-[11px]`,children:o.map(e=>i(`li`,{children:e.text},e.kind))})})]})}var Ic=new Set([`classes`,`classesExclude`]),Lc=new Set([`zones`,`zonesExclude`]),Rc=new Set([`identities`,`identitiesExclude`]);function zc(e,t){return Ic.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):Lc.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):Rc.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 Bc(e,t){if(!Vc.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.id===`schedule`?t(`notificationRules.schedule.hint`,`Only fire inside these weekly windows. Leave it empty to fire at any time.`):e.description}var Vc=new Set([...Ic,...Lc,...Rc,`labelEquals`,`crossing`]);function Hc({descriptor:t,kind:n,taxonomy:r,conditions:a,actions:o,actionStepsOf:s,savedConditions:c,schedule:l,deviceIds:u,cameras:d,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v,scheduleOnly:y}){let{t:b}=J();switch(t.valueType){case`deviceIdList`:{if(!gn(t.id))break;let e=t.id,n=a[e]??[];return i(Vr,{cameras:d,fleet:p,emptyMeansAll:!0,savedHadDevices:(c?.[e]?.length??0)>0,value:n,onChange:t=>_(e,t.length>0?t:void 0)})}case`stringList`:{if(!En(t.id))break;let e=t.id,n=t=>_(e,t.length>0?t:void 0);if(e===`eventTypeTokens`)return i(xr,{deviceIds:u,cameras:d,...m===void 0?{}:{allDevices:m},value:Mi(a,e),onChange:n});let o=me(e,r);return o===null?i(wi,{value:Mi(a,e),placeholder:b(`system.notificationRuleConditions.addValue`,`Add value…`),onChange:n}):i(or,{picker:o,value:Mi(a,e),onChange:n})}case`number01`:{if(!Un(t.id))break;let e=t.id;return i(Er,{value:Qn(a,e),min:0,max:1,step:.05,onChange:t=>_(e,t)})}case`number`:{if(!Jr(t.id))break;let e=t.id;return i(Er,{value:Qn(a,e),min:0,step:1,onChange:t=>_(e,t)})}case`sourceSelect`:{if(!yn(t.id))break;let e=t.id;return qc(t,a[e],t=>_(e,t))}case`systemEvent`:{if(!Pn(t.id))break;let e=t.id,r=xe(n);return r===void 0?i(Mc,{value:a[e]}):i(jc,{family:r,value:a[e],cameras:d,fleet:p,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[e]?.deviceIds?.length??0)>0,onChange:t=>_(e,t),scheduleOnly:y===!0})}case`deviceState`:if(!pn(t.id))break;return i(Rr,{gateable:h,value:a.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!Bn(t.id))break;return i(dn,{scenes:g,value:a.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!ar(t.id))break;let e=t.id;return Jc(t,a[e],t=>_(e,t))}case`packagePhase`:{if(!Gr(t.id))break;let e=t.id;return i(F,{value:a[e]??``,options:[{value:``,label:b(`system.notificationRuleConditions.anyPhase`,`— any phase —`)},...ii(t,_r).map(e=>({value:e.value,label:e.label}))],onChange:t=>_(e,Kc(t.target.value))})}case`sensorTransition`:{if(!Kn(t.id))break;let n=t.id,r=We({conditions:a,...o===void 0?{}:{actions:o},...s===void 0?{}:{actionStepsOf:s}});return e(f,{children:[e(`div`,{className:`flex items-center gap-2`,children:[i(F,{value:a[n]??``,options:ii(t,Mr).map(e=>({value:e.value,label:e.label})),onChange:e=>_(n,Ai(e.target.value))}),i(Fc,{kinds:a.sensorKinds??[]})]}),r&&i(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`nc-sensor-transition-never-fires`,children:`This rule belongs to the alarm, and an alarm rule fires only when an opening OPENS. Set to “only when it clears”, it can never fire.`})]})}case`plateMatcher`:{if(!Ln(t.id))break;let e=t.id;return i(rr,{value:a[e],onChange:t=>_(e,t)})}case`occupancy`:{if(!an(t.id))break;let e=t.id;return i(Oi,{deviceIds:u,cameras:d,classOptions:Uc(r),value:a[e],onChange:t=>_(e,t)})}case`audio`:{if(!Ci(t.id))break;let e=t.id;return i(si,{taxonomy:r,value:a[e],onChange:t=>_(e,t)})}case`schedule`:return i(Fr,{value:l,onChange:v});default:break}return i(Wc,{descriptor:t,conditions:a})}function Uc(e){let t=me(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Wc({descriptor:t,conditions:n}){let{t:r}=J(),i=Object.entries(n).find(([e])=>e===t.id);return e(`p`,{className:xi,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 Gc(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Kc(e){return _r.find(t=>t.value===e)?.value}function qc(e,t,n){return i(F,{value:t??`any`,options:ii(e,gi).map(e=>({value:e.value,label:e.label})),onChange:e=>n(Gc(e.target.value))})}function Jc(e,t,n){return i(ei,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function Yc({catalog:t,delivery:n,conditions:r,onConditionsChange:a}){let{t:o}=J(),s=R({delivery:n,conditions:r}),c=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,a(n)},l=e=>t.find(t=>t.id===e&&ae(t,n,s)&&ni(e,r)),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&&yn(u.id)&&e(`div`,{"data-testid":`condition-source`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:zc(u,o)}),qc(u,r.source,e=>c(`source`,e)),Bc(u,o)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Bc(u,o)})]}),d&&ar(d.id)&&e(`div`,{"data-testid":`condition-crossing`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:zc(d,o)}),Jc(d,r.crossing,e=>c(`crossing`,e)),Bc(d,o)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Bc(d,o)})]})]})}var Xc=[`notificationRules`,`getRuleLastRuns`],Zc=3e4;function Qc(){let e=N(),t=s({queryKey:Xc,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:Zc});return{status:t.status,data:t.data,error:t.error}}var $c={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function el({cell:t}){let{t:n}=J();switch(t.kind){case`pending`:return i(`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 i(`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 i(`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:[i(`span`,{"data-testid":`rule-last-run-dot`,title:t.status,className:`inline-block h-2 w-2 rounded-full ${$c[t.status]}`}),i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Fi(t.lastAt)})]})}}function tl({rule:e,onOpenHistory:t}){let{t:n}=J();return i(K,{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:i(w,{className:`h-3.5 w-3.5`})})}c();var nl=[`notificationRules`,`listSnoozes`],rl=[10,30,60,120];function il({ruleId:t,ruleName:n,exempt:r=!1,variant:a=`icon`}){let{t:s}=J(),c=N(),u=l(),[f,p]=o(30),[m,h]=o(null),_=d({mutationFn:e=>c.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:t,durationMinutes:e}}),onMutate:()=>h(null),onSuccess:()=>u.invalidateQueries({queryKey:nl}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?a===`icon`?null:i(`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.`)}):a===`icon`?i(K,{size:`sm`,variant:`ghost`,type:`button`,disabled:_.isPending,onClick:()=>_.mutate(30),title:s(`system.notificationRuleSnoozeControl.silenceThisRuleForIt`,`Silence this rule for {{value1}} — it appears under "Silenced right now"`,{value1:Hr(30)}),"aria-label":s(`system.notificationRuleSnoozeControl.snooze`,`snooze {{ruleName}}`,{ruleName:n}),"data-testid":`nc-rule-snooze-now`,children:_.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(rt,{className:`h-3.5 w-3.5`})}):e(`div`,{className:`space-y-1`,children:[e(`div`,{className:`flex items-end gap-2`,children:[i(`div`,{className:`w-32`,children:i(F,{value:String(f),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:rl.map(e=>({value:String(e),label:Hr(e)}))})}),e(K,{size:`sm`,variant:`outline`,type:`button`,disabled:_.isPending,onClick:()=>_.mutate(f),"data-testid":`nc-rule-snooze-now`,children:[_.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(rt,{className:`h-3.5 w-3.5`}),s(`system.notificationRuleSnoozeControl.silenceThisRuleNow`,`Silence this rule now`)]})]}),i(`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&&i(`p`,{className:`text-[10px] text-danger`,children:m})]})}c();function al(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function ol(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 sl(e,t){let[,n]=o(0);a(()=>{let r=ol(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 cl(){let e=N();return s({queryKey:nl,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function ll({rule:t,snoozes:n,exempt:r}){let{t:a}=J(),o=N(),s=l();sl(n,t.id);let c=al(n,t.id,Date.now()),u=()=>s.invalidateQueries({queryKey:nl}),f=d({mutationFn:()=>o.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:t.id,durationMinutes:30}}),onSuccess:u}),p=d({mutationFn:async e=>{for(let t of e)await o.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:u});if(r)return null;let m=f.isError||p.isError;return e(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[i(W,{checked:c.length>0,disabled:!t.enabled||f.isPending||p.isPending,onCheckedChange:e=>e?f.mutate():p.mutate(c),"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&&i(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:a(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var ul=`nc.listPrunes`;function dl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fl=new Set([`rule`,`timelapse`,`summary`]),pl=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function ml(e){return typeof e==`string`&&fl.has(e)}function hl(e){return typeof e==`string`&&pl.has(e)}function gl(e){return e===`device`||e===`target`}function _l(e){if(!dl(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!ml(t)||!gl(r)||!hl(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 vl(e){return!dl(e)||!Array.isArray(e.prunes)?null:e.prunes.map(_l).filter(e=>e!==null)}function yl(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 bl(e,t){let n=t(e.at);return e.subjectKind===`device`?q.t(`helpers.notificationPrunes.lastDevice`,{when:n,subject:e.subject}):q.t(`helpers.notificationPrunes.lastTarget`,{when:n,subject:e.subject})}function xl(e){return new Date(e).toLocaleDateString()}function Sl({kind:t,ruleId:n,enabled:r,updatedAt:a}){let o=N(),c=s({queryKey:[`pipelineAnalytics`,ul],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>vl(await o.trpcClient.addons.custom.mutate({addonId:Wi,action:ul,input:{}}))}).data;if(c==null)return null;let l=yl(c,t,n,r,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:[i(b,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),i(`span`,{children:bl(l,xl)})]})}var Cl=5e3;function wl({status:t,now:n,name:r}){let{t:a}=J();if(t.openWindows===null)return e(`p`,{className:`flex items-start gap-1.5`,children:[i(T,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),i(`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}=zi(o);return e(f,{children:[e(`p`,{className:`flex items-start gap-1.5`,children:[i(T,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),i(`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:[i(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),i(`span`,{children:a(`notificationRules.status.grouped.windowLine`,{camera:r(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 Tl({ruleId:t,cameraName:n}){let{t:r}=J(),a=N(),o=s({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,t],refetchInterval:Cl,queryFn:async()=>Ui(await a.trpcClient.addons.custom.mutate({addonId:Wi,action:Bi,input:{ruleId:t}}))}).data;if(o==null||o.kind===`none`)return null;let c=Date.now(),l=e=>n?.(e)??r(`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:[o.kind===`occupancy`&&e(`p`,{className:`flex items-start gap-1.5`,children:[o.unavailable!==void 0||o.warning!==void 0?i(v,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):i(T,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),e(`span`,{children:[i(`span`,{className:`text-foreground`,children:l(o.deviceId)}),` —`,` `,Vi(o,c)]})]}),o.kind===`grouped`&&i(wl,{status:o,now:c,name:l}),o.kind===`timelapse`&&e(f,{children:[o.devices.map(t=>e(`p`,{className:`flex items-start gap-1.5`,children:[i(T,{className:`mt-0.5 h-3 w-3 shrink-0 ${t.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),e(`span`,{children:[Ri(t,l(t.deviceId),c),t.lastArtifact!==void 0&&e(f,{children:[` · `,i(`a`,{className:`text-primary hover:underline`,href:`/${t.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:r(`common.open`)})]})]})]},t.deviceId)),e(`p`,{className:`flex items-start gap-1.5`,children:[i(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),e(`span`,{children:[o.nextWindow===void 0?r(`system.notificationRuleStatus.noFurtherWindowOpensIn`,`No further window opens in the next nine days`):r(`system.notificationRuleStatus.nextWindowOpens`,`Next window opens {{value1}}`,{value1:new Date(o.nextWindow.startMs).toLocaleString()}),o.settleMs>0&&` · ${r(`system.notificationRuleStatus.settled`,{minutes:Math.round(o.settleMs/6e4)})}`]})]})]})]})}function El(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dl(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ol(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function kl(e){if(!El(e))return null;let t=Dl(e,`ruleId`),n=Dl(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=Dl(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:Dl(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Ol(e,`targetIds`)}}function Al(e){if(!El(e))return null;let t=Dl(e,`conditionId`),n=Dl(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function jl(e){if(!El(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(!El(t))continue;let e=Dl(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(!El(t))continue;let e=Dl(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 Ml(e){if(!El(e))return null;let t=Dl(e,`recordId`),n=Dl(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=kl(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Al(t);e!==null&&i.push(e)}let a=Dl(e,`droppedBy`),o=jl(e.stateSummary);return{recordId:t,delivery:n,trigger:Dl(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:Dl(e,`still`)??`none`,notes:Ol(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function Nl(e){if(e.stateSummary!==void 0)return Pl(e,e.stateSummary);if(e.droppedBy!==void 0)return q.t(`helpers.notificationRuleTest.dropped`,{reason:e.droppedBy});let t=e.outcomes[0];if(t===void 0)return q.t(`helpers.notificationRuleTest.notCandidate`,{trigger:e.trigger});if(!t.matched)return t.failedCondition===void 0?q.t(`helpers.notificationRuleTest.noMatchOwn`):q.t(`helpers.notificationRuleTest.noMatchCond`,{condition:t.failedCondition});if(t.enqueued===0)return q.t(`helpers.notificationRuleTest.matchedNoQueue`);let n=e.still===`live`?` ${q.t(`helpers.notificationRuleTest.stillLive`)}`:e.still===`unavailable`?` ${q.t(`helpers.notificationRuleTest.stillUnavailable`)}`:e.still===`unattachable`?` ${q.t(`helpers.notificationRuleTest.stillUnattachable`)}`:``;return q.t(`helpers.notificationRuleTest.matched`,{queued:t.enqueued,targets:t.targetIds.length,still:n})}function Pl(e,t){if(t.nothingToReport){let e=t.sections.map(e=>`${e.id}: ${e.status===`unavailable`?q.t(`helpers.notificationRuleTest.unavailable`):q.t(`helpers.notificationRuleTest.noneOpen`)}`).join(`, `);return q.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 q.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`?` (${q.t(`helpers.notificationRuleTest.perCategory`,{sections:i.join(`, `)})})`:``;return q.t(`helpers.notificationRuleTest.summaryBuilt`,{queued:n,perCategory:a,targets:r})}c();function Fl({ruleId:t,ruleName:n,fallbackDeviceId:r,variant:a=`icon`,showResult:s=!1,summary:c=!1}){let{t:l}=J(),u=N(),[p,m]=o(null),[h,_]=o(null),y=d({mutationFn:async()=>Ml(await u.trpcClient.addons.custom.mutate({addonId:Wi,action:Hi,input:{ruleId:t,...c?{summary:!0}:{},...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{m(null),_(null)},onSuccess:e=>m(e),onError:e=>_(e instanceof Error?e.message:`The test could not be run.`)}),b=p===null?h===null?void 0:h:Nl(p);return e(f,{children:[e(K,{size:`sm`,variant:a===`icon`?`ghost`:`outline`,type:`button`,disabled:y.isPending,onClick:()=>y.mutate(),title:b??(c?l(`system.notificationRuleTestButton.sendSummaryTitle`,`Sends this rule’s state summary now, to every target`):l(`system.notificationRuleTestButton.testNowFiresThisRule`,`Test now — fires this rule and really sends the notification`)),"aria-label":c?l(`system.notificationRuleTestButton.sendSummaryAria`,`send the summary of {{ruleName}} now`,{ruleName:n}):l(`system.notificationRuleTestButton.testNow`,`test {{ruleName}} now`,{ruleName:n}),"data-testid":c?`nc-rule-test-summary`:`nc-rule-test-now`,children:[y.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(ot,{className:`h-3.5 w-3.5`}),a===`full`&&(c?l(`system.notificationRuleTestButton.sendSummaryNow`,`Send the summary now`):l(`system.notificationRuleTestButton.testNow2`,`Test now`))]}),s&&h!==null&&i(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:h}),s&&p!==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:[i(`p`,{className:`text-foreground`,children:Nl(p)}),p.planNotes.map(t=>e(`p`,{className:`flex gap-1.5`,children:[i(v,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),i(`span`,{children:t.note})]},t.conditionId)),p.notes.map(t=>e(`p`,{children:[`· `,t]},t))]})]})}c();var Il=[`notificationRules`,`listSnoozes`],Ll=3e4;function Rl(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function zl(e){if(e===0)return q.t(`system.notificationSnoozes.remEnding`);if(e<60)return q.t(`system.notificationSnoozes.remMin`,{count:e});let t=Math.floor(e/60),n=e%60;return n===0?q.t(`system.notificationSnoozes.remHour`,{count:t}):q.t(`system.notificationSnoozes.remHourMin`,{hours:t,minutes:n})}function Bl({rules:t}){let{t:r}=J(),a=N(),o=l(),c=s({queryKey:Il,refetchInterval:Ll,queryFn:async()=>(await a.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),u=d({mutationFn:e=>a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>o.invalidateQueries({queryKey:Il})}),f=n(()=>{let e=new Map;for(let n of t)e.set(n.id,n.name);return e},[t]),p=Date.now(),m=(c.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return e(Zt,{className:`p-4`,children:[e(`div`,{className:`flex items-center gap-2 mb-3`,children:[i(rt,{className:`h-4 w-4 text-foreground-subtle`}),i(`h3`,{className:`text-sm font-medium text-foreground`,children:r(`system.notificationSnoozes.silencedRightNow`,`Silenced right now`)})]}),m.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`system.notificationSnoozes.nothingIsSilencedASnooze`,`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`)}),i(`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:[i(`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&&i(G,{variant:`warning`,className:`text-[10px]`,children:r(`common.everyone`)}),t.classes!==void 0&&t.classes.length>0&&i(G,{variant:`info`,className:`text-[10px]`,children:t.classes.join(`, `)}),!t.summary&&i(G,{variant:`default`,className:`text-[10px]`,children:r(`system.notificationSnoozes.noSummary`,`no summary`)})]}),i(`span`,{className:`text-[10px] text-foreground-subtle`,children:r(`system.notificationSnoozes.setBy`,{user:t.userId,remaining:zl(Rl(t,p))})})]}),i(K,{size:`sm`,variant:`outline`,disabled:u.isPending,onClick:()=>u.mutate(t.id),children:r(`system.notificationSnoozes.endNow`,`End now`)})]},t.id))})]})}var X=`block text-[11px] font-medium text-foreground mb-1`,Vl=`mt-1 text-[10px] text-foreground-subtle`;function Z({title:t,hint:n,children:r}){return e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:t}),n!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:n}),i(`div`,{className:`space-y-3`,children:r})]})}function Hl({problems:t,testId:n=`digest-problems`}){let{t:r}=J();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:[i(v,{className:`h-3.5 w-3.5`}),r(`system.notificationDigestFields.thisRuleCouldNeverProduce`,`This rule could never produce anything, so it cannot be saved:`)]}),i(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:t.map(e=>i(`li`,{children:e},e))})]})}function Ul({warnings:t,testId:n=`digest-warnings`}){let{t:r}=J();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:[i(b,{className:`h-3.5 w-3.5`}),r(`system.notificationDigestFields.worthKnowing`,`Worth knowing:`)]}),i(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:t.map(e=>i(`li`,{children:e},e))})]})}function Wl({cameras:t,value:n,onChange:r,fleet:a,hint:o}){return e(`div`,{className:`space-y-1`,children:[i(wt,{devices:t,listState:a.state,fleet:a,value:n,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),o!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:o})]})}function Gl(e){let{t}=J();return i(Tt,{...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 Q({label:t,value:n,onChange:r,min:a,max:o,step:s,hint:c,emptyPlaceholder:l,testId:u,disabled:d=!1}){return e(`div`,{children:[i(`label`,{className:X,children:t}),i(U,{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){r(void 0);return}let n=Number(t);Number.isFinite(n)&&r(n)}}),c!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:c})]})}function Kl({label:t,checked:n,onChange:r,hint:a,testId:o}){return e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(W,{checked:n,onCheckedChange:r,"aria-label":t,...o===void 0?{}:{"data-testid":o}}),t]}),a!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function ql({title:t,body:n,onTitleChange:r,onBodyChange:a,family:o,testIdPrefix:s}){let{t:c}=J(),l=ls(),u=e=>l.data?as(l.data,{family:o,field:e}):void 0;return e(`div`,{className:`space-y-2`,children:[i(ps,{label:c(`system.notificationDigestFields.notificationTitle`,`Notification title`),value:t,onChange:r,vars:u(`title`),testId:`${s}-title`}),i(ps,{label:c(`system.notificationDigestFields.notificationBody`,`Notification body`),value:n,onChange:a,vars:u(`body`),multiline:!0,testId:`${s}-body`}),i(`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).`)}),i(ms,{context:{family:o,field:`body`},title:t,body:n,testId:`${s}-preview`})]})}function Jl({open:t,ruleName:n,windowDescription:r,targetDescription:a,pending:o,onConfirm:s,onCancel:c,extra:l,confirmDisabled:u=!1}){let{t:d}=J();return t?i(At,{open:!0,onOpenChange:e=>!e&&c(),children:i(bt,{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:[i(ot,{className:`h-4 w-4 text-warning`}),d(`system.notificationDigestFields.sendARealNotificationNow`,`Send a real notification now?`)]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:d(`system.notificationDigestFields.confirmSend`,{rule:n,window:r,target:a})}),i(`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:[i(K,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:d(`common.cancel`,`Cancel`)}),i(K,{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 Yl(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 Zl(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Ql(e){let t=e.windows[0];if(t===void 0)return q.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} ${Zl(t.startMinute)}–${Zl(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function $l(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return q.t(`helpers.notificationDigest.ago`,{duration:Yl(Math.round(r/1e3))})}function eu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tu(e){return Array.isArray(e)?`[${e.map(tu).join(`,`)}]`:eu(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${tu(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function nu(e,t){return tu(e)===tu(t)}function ru(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,iu=`nc.getTexts`,au=`nc.setLanguage`,ou=`nc.setTextOverrides`,su={en:`English`,it:`Italiano`};function cu(e){return e===`en`||e===`it`}function lu(e){return e===`override`||e===`shipped`||e===`fallback`}function uu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function du(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(!uu(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`||!cu(r)||!lu(o)||i!==null&&typeof i!=`string`)return null;let s=du(e.placeholders),c=du(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 pu(e){if(!uu(e))return null;let{language:t,activeLanguage:n}=e;if(!cu(t)||!cu(n))return null;let r=du(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)cu(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=fu(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function mu(e,t){return t.get(e.key)??e.override??e.shipped}function hu(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 gu(e,t){return Object.keys(hu(e,t)).length}function _u(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 vu(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function yu(e){return e.pluralCategories.length===0?null:q.t(`helpers.notificationTexts.pluralWarning`,{categories:e.pluralCategories.join(`, `)})}var bu=[`notificationCalendarEvents`,`list`],xu=`nc.listCalendarEventsRules`,Su=`nc.upsertCalendarEventsRule`,Cu=`nc.deleteCalendarEventsRule`,wu=tt({timezone:$e().min(1),windows:nt(tt({days:nt(Qe().int().min(0).max(6)).min(1),startMinute:Qe().int().min(0).max(1439),endMinute:Qe().int().min(0).max(1439)})).min(1),invert:et().optional()}),Tu=tt({targetId:$e().min(1),params:Ze($e(),Xe()).optional()}),Eu=tt({rules:nt(tt({id:$e().min(1),name:$e().min(1),enabled:et(),schedule:wu,calendars:nt($e().min(1)).max(64).optional(),calendarsExclude:nt($e().min(1)).max(64).optional(),horizonDays:Qe().int(),deliverEmpty:et(),targets:nt(Tu).min(1),template:tt({title:$e().optional(),body:$e().optional()}).optional(),priority:Qe().int(),targetOverrides:Oe.optional(),generatedAt:Qe().optional(),readOnly:et().optional()}))});function Du(e){let t=Eu.safeParse(e);return t.success?t.data.rules:null}function Ou(e){return e.readOnly!==!0}var ku=[{key:`basics`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_basics`)}},{key:`schedule`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_schedule`)}},{key:`calendars`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_calendars`)}},{key:`targets`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_targets`)}},{key:`template`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_template`)}}],Au=`basics`;function ju(){return ue([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function Mu(e){let t=Ce(e);if(t===null||t.length===0)return Ql(e);let n=t[0];if(n===void 0)return Ql(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 q.t(`helpers.notificationCalendarEvents.scheduleAt`,{time:`${r}:${i}`,more:a})}function Nu(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:ju(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``,targetOverrides:{}}}function Pu(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??``,targetOverrides:e.targetOverrides??{}}}function Fu(e){return e.name.trim().length>0&&e.targetIds.length>0&&e.horizonDays>=1&&e.horizonDays<=30&&e.schedule.windows.length>0}function Iu(e,t){let n=Fn(e.targetIds,e.targetOverrides,t),r=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:r,...Object.keys(n).length>0?{targetOverrides:n}:{},...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,n){let r=Iu(e,n);return{...r,...r.targetOverrides===void 0&&Object.keys(t.targetOverrides??{}).length>0?{targetOverrides:{}}:{},calendars:e.calendars.length===0&&(t.calendars?.length??0)>0?null:r.calendars,calendarsExclude:e.calendarsExclude.length===0&&(t.calendarsExclude?.length??0)>0?null:r.calendarsExclude,template:e.templateTitle.trim().length===0&&e.templateBody.trim().length===0&&t.template!==void 0?null:r.template}}function Ru(e){return q.t(`helpers.notificationCalendarEvents.horizon`,{count:e})}function zu(e){return e.calendars!==void 0&&e.calendars.length>0?q.t(`helpers.notificationCalendarEvents.calendars`,{count:e.calendars.length}):e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?q.t(`helpers.notificationCalendarEvents.allExcept`,{count:e.calendarsExclude.length}):q.t(`helpers.notificationCalendarEvents.allCalendars`)}c();function Bu({rule:t,targets:n,onSaved:r,onCancel:a}){let{t:s}=J(),c=N(),l=kt(),[u,f]=o(()=>t===null?Nu():Pu(t)),[p,m]=o(()=>yi(t===null?void 0:t.calendars,t===null?void 0:t.calendarsExclude)),[h,_]=o(Au),[v,y]=o(null),b=e=>f(t=>({...t,...e})),x=Ms(),S=ur(wn(n),x),C=d({mutationFn:async()=>{let e=zr(p),n={...u,calendars:e.include??[],calendarsExclude:e.exclude??[]};if(!Fu(n))throw Error(`Name, at least one target, and a schedule are required`);let r=t===null?{rule:Iu(n,S)}:{ruleId:t.id,patch:Lu(n,t,S)};await c.trpcClient.addons.custom.mutate({addonId:$,action:Su,input:r})},onSuccess:()=>r(),onError:e=>{y(e instanceof Error?e.message:String(e))}}),w=(l.data??[]).map(e=>({id:e.id,name:e.name}));return i(At,{open:!0,onOpenChange:e=>!e&&a(),children:e(bt,{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:[i(it,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:t===null?s(`system.notificationCalendarEventsEditor.newCalendarEvents`,`New calendar events`):u.name})]}),i(K,{size:`sm`,type:`button`,disabled:C.isPending,onClick:()=>{y(null),C.mutateAsync()},"data-testid":`calendar-events-save`,children:C.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):s(`common.save`,`Save`)})]}),e(Xt,{value:h,onValueChange:e=>{let t=ku.find(t=>t.key===e);t!==void 0&&_(t.key)},children:[i(qt,{className:`mb-3`,children:ku.map(e=>i($t,{value:e.key,children:e.label},e.key))}),e(ht,{className:`space-y-4 pr-1`,children:[v===null?null:i(`p`,{className:`text-sm text-destructive`,children:v}),i(H,{value:`basics`,className:`space-y-3`,children:e(Z,{title:s(`system.notificationCalendarEventsEditor.basics`,`Basics`),children:[e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.name`,`Name`),i(U,{className:`mt-1`,value:u.name,onChange:e=>b({name:e.target.value}),"data-testid":`calendar-events-name`})]}),i(Q,{label:s(`system.notificationCalendarEventsEditor.horizonDays`,`Horizon (days)`),value:u.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&b({horizonDays:e})}}),i(Q,{label:s(`system.notificationCalendarEventsEditor.priority`,`Priority`),value:u.priority,min:1,max:5,onChange:e=>{e!==void 0&&b({priority:e})}}),i(Kl,{label:s(`system.notificationCalendarEventsEditor.enabled`,`Enabled`),checked:u.enabled,onChange:e=>b({enabled:e})}),i(Kl,{label:s(`system.notificationCalendarEventsEditor.deliverWhenEmpty`,`Deliver when empty`),checked:u.deliverEmpty,onChange:e=>b({deliverEmpty:e})})]})}),i(H,{value:`schedule`,className:`space-y-3`,children:e(Z,{title:s(`system.notificationCalendarEventsEditor.schedule`,`Schedule`),children:[i(Fr,{mode:`times`,value:u.schedule,onChange:e=>b({schedule:e})}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:s(`system.notificationCalendarEventsEditor.oneSendTimePerRow`,`One send time per row. The digest fires at that minute.`)})]})}),i(H,{value:`calendars`,className:`space-y-3`,children:i(Z,{title:s(`system.notificationCalendarEventsEditor.calendars`,`Calendars`),children:i(Xs,{draft:p,onChange:m,exceptOffered:!0,plural:`calendars`,describe:e=>w.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>i(wt,{devices:w,listState:l.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),i(H,{value:`targets`,className:`space-y-3`,children:i(Z,{title:s(`system.notificationCalendarEventsEditor.targets`,`Targets`),children:i(Gl,{targets:n,value:u.targetIds,onChange:e=>b({targetIds:e})})})}),i(H,{value:`template`,className:`space-y-3`,children:e(Z,{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`),i(U,{className:`mt-1`,value:u.templateTitle,onChange:e=>b({templateTitle:e.target.value})})]}),e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.body`,`Body`),i(It,{className:`mt-1 min-h-[8rem] w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:u.templateBody,onChange:e=>b({templateBody:e.target.value})})]}),i(Ns,{surface:`calendar-events`,targetIds:u.targetIds,targets:n,overrides:u.targetOverrides,rulePriority:u.priority,onChange:e=>b({targetOverrides:e})})]})})]})]})]})})}var Vu=`nc.listSummaryRules`,Hu=`nc.upsertSummaryRule`,Uu=`nc.deleteSummaryRule`,Wu=`nc.testSummaryRule`,Gu=3600,Ku=86400,qu=3600,Ju=3600,Yu=3*36e5,Xu=[`importance`,`recency`,`dwell`],Zu={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},Qu=[`none`,`tiles`,`all`],$u=`none`,ed={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},td=[`en`,`it`],nd=[`deliver-without-text`,`skip`],rd=2048,id=2e3;function ad(e){return e.window.kind!==`unsupported`&&!e.readOnly}function od(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sd(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 cd(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 ld(e){if(e!==void 0)return typeof e==`string`?e:null}function ud(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function dd(e){return Xu.some(t=>t===e)}function fd(e){return e===void 0?$u:Qu.find(t=>t===e)??null}function pd(e){if(!od(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!od(n))return null;let e=sd(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=ld(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 md(e){if(!od(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=pd(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 hd(e){if(e==null)return;if(!od(e))return null;let t=e.classes===void 0?void 0:cd(e.classes),n=e.classesExclude===void 0?void 0:cd(e.classesExclude),r=e.zones===void 0?void 0:cd(e.zones);if(t===null||n===null||r===null)return null;let i=ud(e.minImportance),a=ud(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 gd(e){if(e==null)return;if(!od(e))return null;let t=ld(e.title),n=ld(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function _d(e){return td.some(t=>t===e)}function vd(e){return nd.some(t=>t===e)}function yd(e){if(e==null)return;if(!od(e)||typeof e.enabled!=`boolean`)return null;let t=ld(e.profileId),n=ld(e.prompt);if(t===null||n===null)return null;let r=ud(e.maxImagePx),i=ud(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!_d(a))return null;let o=e.onFailure;return o!==void 0&&!vd(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 bd(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!od(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!od(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function xd(e){if(e===void 0)return;let t=Oe.safeParse(e);return t.success?t.data:null}function Sd(e){if(!od(e))return null;let{id:t,name:n,enabled:r,maxTiles:i,maxAiImages:a,rank:o,barrierSeconds:s,deliverEmpty:c}=e;if(typeof t!=`string`||t.length===0||typeof n!=`string`||typeof r!=`boolean`||typeof i!=`number`||typeof a!=`number`||!dd(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=sd(e.deviceIds),u=md(e.window),d=bd(e.targets);if(l===null||u===null||d===null)return null;let f=hd(e.filters),p=gd(e.template);if(f===null||p===null)return null;let m=ld(e.captionText),h=ud(e.generatedAt),g=ud(e.updatedAt);if(m===null||h===null||g===null)return null;let _=fd(e.captions);if(_===null)return null;let v=yd(e.ai);if(v===null)return null;let y=xd(e.targetOverrides);return y===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,...y===void 0?{}:{targetOverrides:y},...h===void 0?{}:{generatedAt:h},...g===void 0?{}:{updatedAt:g},readOnly:e.readOnly===!0,...v===void 0?{}:{ai:v}}}function Cd(e){if(!od(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=Sd(n);if(e===null)return null;t.push(e)}return t}function wd(e){if(!od(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=ud(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=ud(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=ld(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 Td(){return{name:``,enabled:!0,deviceIds:[],windowKind:`motion`,schedule:void 0,quietSeconds:60,maxWindowSeconds:300,classes:[],classesExclude:[],zones:[],minImportance:void 0,minDwellSeconds:void 0,includeStationary:!1,maxTiles:12,maxAiImages:6,rank:`importance`,barrierSeconds:120,targetIds:[],templateTitle:``,templateBody:``,mosaicCaptions:$u,captionText:``,deliverEmpty:!1,priority:3,targetOverrides:{},aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function Ed(e){let t=Td(),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,targetOverrides:e.targetOverrides??{},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 Dd(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Od(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 kd(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 Ad(e){return ru(e.targetIds)}function jd(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 Md(e,t){let n=Od(e),r=kd(e),i=jd(e),a=e.captionText.trim(),o=Fn(e.targetIds,e.targetOverrides,t);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:Dd(e),...n===void 0?{}:{filters:n},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Ad(e),...r===void 0?{}:{template:r},captions:e.mosaicCaptions,...a.length>0?{captionText:a}:{},deliverEmpty:e.deliverEmpty,priority:e.priority,...Object.keys(o).length>0?{targetOverrides:o}:{},...i===void 0?{}:{ai:i}}}function Nd(e,t,n){let r=Md(e,n),i={};return r.name!==t.name&&(i.name=r.name),r.enabled!==t.enabled&&(i.enabled=r.enabled),nu(r.deviceIds,t.deviceIds)||(i.deviceIds=r.deviceIds),nu(r.window,t.window)||(i.window=r.window),nu(r.filters,t.filters)||(i.filters=r.filters??null),r.maxTiles!==t.maxTiles&&(i.maxTiles=r.maxTiles),r.maxAiImages!==t.maxAiImages&&(i.maxAiImages=r.maxAiImages),r.rank!==t.rank&&(i.rank=r.rank),r.barrierSeconds!==t.barrierSeconds&&(i.barrierSeconds=r.barrierSeconds),nu(r.targets,t.targets)||(i.targets=r.targets),nu(r.template,t.template)||(i.template=r.template??null),r.captions!==t.captions&&(i.captions=r.captions),(r.captionText??``)!==(t.captionText??``)&&(i.captionText=r.captionText??``),r.deliverEmpty!==t.deliverEmpty&&(i.deliverEmpty=r.deliverEmpty),r.priority!==t.priority&&(i.priority=r.priority),nu(r.targetOverrides??{},t.targetOverrides??{})||(i.targetOverrides=r.targetOverrides??{}),nu(r.ai,t.ai)||(i.ai=r.ai??null),i}function Pd(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 ${Gu}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${Ku}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 ${qu}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 ${Ju}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 ${id} 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 ${rd} 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 Fd(e){return Pd(e).length===0}function Id(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 Ld=[{key:`rule`,get label(){return q.t(`helpers.notificationSummaries.tab_rule`)},fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,get label(){return q.t(`helpers.notificationSummaries.tab_window`)},fields:[`windowKind`,`schedule`,`quietSeconds`,`maxWindowSeconds`,`barrierSeconds`]},{key:`content`,get label(){return q.t(`helpers.notificationSummaries.tab_content`)},fields:[`classes`,`classesExclude`,`zones`,`minImportance`,`minDwellSeconds`,`includeStationary`]},{key:`mosaic`,get label(){return q.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 q.t(`helpers.notificationSummaries.tab_delivery`)},fields:[`targetIds`,`priority`,`deliverEmpty`,`templateTitle`,`templateBody`,`targetOverrides`]}],Rd=`rule`;function zd(e){return Ld.find(t=>t.key===e)?.key}function Bd(e){return e.kind===`motion`?q.t(`helpers.notificationSummaries.winMotion`,{quiet:Yl(e.quietSeconds),max:Yl(e.maxWindowSeconds)}):e.kind===`unsupported`?q.t(`helpers.notificationSummaries.winUnsupported`,{raw:e.raw}):q.t(`helpers.notificationSummaries.winSchedule`,{schedule:Ql(e.schedule)})}function Vd(e,t){return $l(e,t,`Never run`)}function Hd(e){if(e===void 0)return q.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(q.t(`helpers.notificationSummaries.filterNot`,{classes:e.classesExclude.join(`, `)})),e.zones!==void 0&&e.zones.length>0&&t.push(q.t(`helpers.notificationSummaries.filterZones`,{count:e.zones.length})),e.minImportance!==void 0&&t.push(q.t(`helpers.notificationSummaries.filterImportance`,{value:e.minImportance})),e.minDwellSeconds!==void 0&&t.push(q.t(`helpers.notificationSummaries.filterStay`,{value:Yl(e.minDwellSeconds)})),e.includeStationary===!0&&t.push(q.t(`helpers.notificationSummaries.filterParked`)),t.length===0?q.t(`helpers.notificationSummaries.allPassages`):t.join(` · `)}function Ud(e){return{windowStartMs:e-Yu,windowEndMs:e}}c();var Wd={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},Gd={en:`English`,it:`Italiano`};function Kd(e){return Xu.find(t=>t===e)}function qd(e){return Qu.find(t=>t===e)}function Jd(e){return td.find(t=>t===e)??``}function Yd(e){return nd.find(t=>t===e)}function Xd({rule:t,cameras:r,fleet:a,targets:s,taxonomy:c,onSaved:l,onCancel:u}){let{t:f}=J(),p=N(),[m,h]=o(()=>t===null?Td():Ed(t)),[_,v]=o(null),[y,b]=o(t!==null),[x,S]=o(Rd),C=e=>h(t=>({...t,...e})),w=n(()=>{let e=me(`occupancy`,c);return e===null?[]:e.groups.flatMap(e=>e.options)},[c]),{options:T,loading:E}=un(m.deviceIds,r.map(e=>({id:e.id,name:e.name}))),D=Ut({functionCap:`llm`}),O=(D.data??[]).filter(qi),k=Ms(),A=ur(wn(s),k),j=d({mutationFn:async()=>{let e=t===null?{rule:Md(m,A)}:{ruleId:t.id,patch:Nd(m,t,A)};await p.trpcClient.addons.custom.mutate({addonId:$,action:Hu,input:e})},onSuccess:l,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),M=ls(),P=M.data?as(M.data,{family:`summary`,field:`captionText`}):void 0,ee=m.mosaicCaptions===`all`,te=Pd(m),ne=Id(m),I=Ld.some(e=>e.key===x)?x:Rd;return i(At,{open:!0,onOpenChange:e=>!e&&u(),children:e(bt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(`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:[i(st,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`span`,{className:`truncate`,children:t===null?f(`system.notificationSummaryEditor.newSummary`,`New summary`):f(`system.notificationSummaryEditor.edit`,`Edit {{name}}`,{name:t.name})})]})}),_!==null&&i(`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&&i(Sl,{kind:`summary`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt??1/0}),y?i(Hl,{problems:te,testId:`summary-problems`}):null,i(Ul,{warnings:ne,testId:`summary-warnings`})]}),e(Xt,{value:I,onValueChange:e=>S(zd(e)??x),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[i(qt,{className:`mb-3 shrink-0`,children:Ld.map(e=>i($t,{value:e.key,children:e.label},e.key))}),e(ht,{className:`pr-1`,children:[e(H,{value:`rule`,className:`space-y-3`,children:[i(Z,{title:f(`system.notificationSummaryEditor.whatItIs`,`What it is`),hint:f(`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:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.name`,`Name`)}),i(U,{value:m.name,onChange:e=>C({name:e.target.value}),placeholder:f(`system.notificationSummaryEditor.eGOvernightSweep`,`e.g. Overnight sweep`),"data-testid":`summary-name`})]}),i(`div`,{className:`pb-1.5`,children:i(Kl,{label:f(`system.notificationSummaryEditor.enabled`,`Enabled`),checked:m.enabled,onChange:e=>C({enabled:e}),testId:`summary-enabled`})})]})}),i(Z,{title:f(`system.notificationSummaryEditor.cameras`,`Cameras`),hint:f(`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:i(Wl,{cameras:r,value:m.deviceIds,fleet:a,onChange:e=>C({deviceIds:e}),hint:f(`system.notificationSummaryEditor.theFirstCameraSelectedOwns`,`The first camera selected owns the delivered notification.`)})})]}),i(H,{value:`window`,className:`space-y-3`,children:e(Z,{title:f(`system.notificationSummaryEditor.whenTheWindowCloses`,`When the window closes`),children:[e(`div`,{children:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.window`,`Window`)}),i(F,{value:m.windowKind,options:[{value:`motion`,label:f(`system.notificationSummaryEditor.motionOpenedAndClosedBy`,`Motion — opened and closed by activity`)},{value:`schedule`,label:f(`system.notificationSummaryEditor.scheduleFixedWeeklyWindows`,`Schedule — fixed weekly windows`)}],onChange:e=>C({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),m.windowKind===`motion`?e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Q,{label:f(`system.notificationSummaryEditor.quietPeriodSeconds`,`Quiet period (seconds)`),value:m.quietSeconds,min:30,max:Gu,onChange:e=>C({quietSeconds:e??0}),hint:f(`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`}),i(Q,{label:f(`system.notificationSummaryEditor.longestWindowSeconds`,`Longest window (seconds)`),value:m.maxWindowSeconds,min:60,max:Ku,onChange:e=>C({maxWindowSeconds:e??0}),hint:f(`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:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.weeklyWindows`,`Weekly windows`)}),i(Fr,{value:m.schedule,onChange:e=>C({schedule:e})}),i(`p`,{className:Vl,children:f(`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.`)})]}),i(Q,{label:f(`system.notificationSummaryEditor.waitForOpenTracksSeconds`,`Wait for open tracks (seconds)`),value:m.barrierSeconds,min:0,max:qu,onChange:e=>C({barrierSeconds:e??0}),hint:f(`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`})]})}),i(H,{value:`content`,className:`space-y-3`,children:e(Z,{title:f(`system.notificationSummaryEditor.whatGoesIn`,`What goes in`),hint:f(`system.notificationSummaryEditor.evaluatedOnTracksOnePassage`,`Evaluated on tracks: one passage is one tile.`),children:[e(`div`,{children:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.classes`,`Classes`)}),i(Di,{options:w,value:m.classes,onChange:e=>C({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),i(`p`,{className:Vl,children:f(`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:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.excludedClasses`,`Excluded classes`)}),i(Di,{options:w,value:m.classesExclude,onChange:e=>C({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),e(`div`,{children:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.zones`,`Zones`)}),i(Di,{options:T,value:m.zones,onChange:e=>C({zones:e}),loading:E,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),i(`p`,{className:Vl,children:f(`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:[i(Q,{label:f(`system.notificationSummaryEditor.minimumImportance`,`Minimum importance`),value:m.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>C({minImportance:e}),hint:f(`system.notificationSummaryEditor.thePipelineSOwnScore`,`The pipeline's own score, 0–1. Empty keeps everything.`),testId:`summary-min-importance`}),i(Q,{label:f(`system.notificationSummaryEditor.minimumStaySeconds`,`Minimum stay (seconds)`),value:m.minDwellSeconds,min:0,max:Ju,emptyPlaceholder:`any`,onChange:e=>C({minDwellSeconds:e}),hint:f(`system.notificationSummaryEditor.dropsThePassagesTooBrief`,`Drops the passages too brief to be worth a tile.`),testId:`summary-min-dwell`})]}),i(Kl,{label:f(`system.notificationSummaryEditor.includeParkedObjects`,`Include parked objects`),checked:m.includeStationary,onChange:e=>C({includeStationary:e}),hint:f(`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`})]})}),i(H,{value:`mosaic`,className:`space-y-3`,children:e(Z,{title:f(`system.notificationSummaryEditor.theMosaic`,`The mosaic`),children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Q,{label:f(`system.notificationSummaryEditor.tiles`,`Tiles`),value:m.maxTiles,min:1,max:24,onChange:e=>C({maxTiles:e??1}),hint:f(`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:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.whenThereAreMoreTracks`,`When there are more tracks than tiles`)}),i(F,{value:m.rank,options:Xu.map(e=>({value:e,label:Zu[e]})),onChange:e=>{let t=Kd(e.target.value);t!==void 0&&C({rank:t})},"data-testid":`summary-rank`}),i(`p`,{className:Vl,children:f(`system.notificationSummaryEditor.everyContributingCameraKeepsIts`,`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`)})]})]}),e(`div`,{children:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.textOnTheMosaic`,`Text on the mosaic`)}),i(F,{value:m.mosaicCaptions,options:Qu.map(e=>({value:e,label:ed[e]})),onChange:e=>{let t=qd(e.target.value);t!==void 0&&C({mosaicCaptions:t})},"data-testid":`summary-captions`}),i(`p`,{className:Vl,children:f(`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:[i(ps,{label:f(`system.notificationSummaryEditor.captionBurnedOntoTheMosaic`,`Caption burned onto the mosaic`),value:m.captionText,disabled:!ee,onChange:e=>C({captionText:e}),placeholder:f(`system.notificationSummaryEditor.leaveEmptyForNoCaption`,`Leave empty for no caption`),vars:P,deviceValues:!1,testId:`summary-caption`}),i(`p`,{className:Vl,children:ee?f(`system.notificationSummaryEditor.acrossTheTopBand`,`Across the top band.`):f(`system.notificationSummaryEditor.onlyDrawnWithTileLabels`,`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`)})]})]})}),i(H,{value:`ai`,className:`space-y-3`,children:e(Z,{title:f(`system.notificationSummaryEditor.writtenSummary`,`Written summary`),hint:f(`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:[i(Kl,{label:f(`system.notificationSummaryEditor.haveAModelDescribeThe`,`Have a model describe the window`),checked:m.aiEnabled,onChange:e=>C({aiEnabled:e}),hint:f(`system.notificationSummaryEditor.offByDefaultTheMosaic`,`Off by default. The mosaic and the counts are delivered either way.`),testId:`summary-ai-enabled`}),!m.aiEnabled&&i(`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:f(`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:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.visionProfile`,`Vision profile`)}),i(F,{value:m.aiProfileId,disabled:!m.aiEnabled,options:[{value:``,label:f(`system.notificationSummaryEditor.theHubSDefaultVision`,`The hub's default vision profile`)},...O.map(e=>({value:e.id,label:`${e.name} · ${Ji(e)}${e.enabled?``:` · disabled`}`}))],onChange:e=>C({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),i(`p`,{className:Vl,children:D.isError?f(`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.`):O.length===0?f(`system.notificationSummaryEditor.noVisionCapableProfileOn`,`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`):f(`system.notificationSummaryEditor.onlyVisionCapableProfilesAre`,`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`)})]}),e(`div`,{children:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.answerIn`,`Answer in`)}),i(F,{value:m.aiLanguage,disabled:!m.aiEnabled,options:[{value:``,label:f(`system.notificationSummaryEditor.donTAskForA`,`Don’t ask for a language`)},...td.map(e=>({value:e,label:Gd[e]}))],onChange:e=>C({aiLanguage:Jd(e.target.value)}),"data-testid":`summary-ai-language`}),i(`p`,{className:Vl,children:f(`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:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.yourQuestionOptional`,`Your question (optional)`)}),i(It,{value:m.aiPrompt,rows:3,maxLength:id,disabled:!m.aiEnabled,onChange:e=>C({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:f(`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`}),i(`p`,{className:Vl,children:f(`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:[i(Q,{label:f(`system.notificationSummaryEditor.framesTheModelMayLook`,`Frames the model may look at`),value:m.maxAiImages,min:1,max:8,disabled:!m.aiEnabled,onChange:e=>C({maxAiImages:e??1}),hint:f(`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`}),i(Q,{label:f(`system.notificationSummaryEditor.timeLimitSeconds`,`Time limit (seconds)`),value:m.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!m.aiEnabled,onChange:e=>C({aiTimeoutSeconds:e}),hint:f(`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:[i(Q,{label:f(`system.notificationSummaryEditor.frameSizeSentPixels`,`Frame size sent (pixels)`),value:m.aiMaxImagePx,min:64,max:rd,emptyPlaceholder:`448`,disabled:!m.aiEnabled,onChange:e=>C({aiMaxImagePx:e}),hint:f(`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:[i(`label`,{className:X,children:f(`system.notificationSummaryEditor.ifTheModelGivesNo`,`If the model gives no answer`)}),i(F,{value:m.aiOnFailure,disabled:!m.aiEnabled,options:nd.map(e=>({value:e,label:Wd[e]})),onChange:e=>{let t=Yd(e.target.value);t!==void 0&&C({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),i(`p`,{className:Vl,children:f(`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.`)})]})]})]})}),i(H,{value:`delivery`,className:`space-y-3`,children:e(Z,{title:f(`system.notificationSummaryEditor.delivery`,`Delivery`),children:[i(Gl,{targets:s,value:m.targetIds,onChange:e=>C({targetIds:e})}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Q,{label:f(`system.notificationSummaryEditor.priority`,`Priority`),value:m.priority,min:1,max:5,onChange:e=>C({priority:e??3}),testId:`summary-priority`}),i(Kl,{label:f(`system.notificationSummaryEditor.deliverAWindowThatMatched`,`Deliver a window that matched nothing`),checked:m.deliverEmpty,onChange:e=>C({deliverEmpty:e}),hint:f(`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`})]}),i(ql,{title:m.templateTitle,body:m.templateBody,onTitleChange:e=>C({templateTitle:e}),onBodyChange:e=>C({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),i(`p`,{className:Vl,children:i(jn,{i18nKey:`system.notificationSummaryEditor.aiToken`,values:{token:`{{ai}}`},components:{code:i(`code`,{})}})}),i(Ns,{surface:`summary`,templateFamily:`summary`,targetIds:m.targetIds,targets:s,overrides:m.targetOverrides,rulePriority:m.priority,onChange:e=>C({targetOverrides:e})})]})})]})]}),e(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[i(K,{size:`sm`,variant:`secondary`,type:`button`,onClick:u,children:f(`common.cancel`,`Cancel`)}),e(K,{size:`sm`,type:`button`,disabled:j.isPending,onClick:()=>{b(!0),!(!Fd(m)||j.isPending)&&j.mutate()},children:[j.isPending&&i(g,{className:`h-3.5 w-3.5 animate-spin`}),t===null?f(`system.notificationSummaryEditor.create`,`Create`):f(`common.save`,`Save`)]})]})]})})}var Zd=`nc.listTimelapseRules`,Qd=`nc.upsertTimelapseRule`,$d=`nc.deleteTimelapseRule`,ef=`nc.testTimelapseRule`,tf=3600,nf=3600,rf=30,af=1,of=[`image`,`gif`],sf={image:`Still frame`,gif:`Short animation (GIF)`},cf=tt({rules:nt(V.extend({readOnly:et().optional()}))});function lf(e){let t=cf.safeParse(e);return t.success?t.data.rules:null}function uf(e){return e.readOnly!==!0}var df=tt({produced:Qe(),exportId:$e().optional(),coveragePercent:Qe().optional(),enqueued:Qe().optional(),windowStartMs:Qe().optional(),windowEndMs:Qe().optional(),error:$e().optional()});function ff(e){let t=df.safeParse(e);return t.success?t.data:null}function pf(){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,targetOverrides:{}}}function mf(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,targetOverrides:e.targetOverrides??{}}}var hf={windows:[{days:[1],startMinute:0,endMinute:60}]};function gf(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 _f(e,t){let n=gf(e),r=Fn(e.targetIds,e.targetOverrides,t);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??hf,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:ru(e.targetIds),...n===void 0?{}:{template:n},...e.previewTextSet?{previewText:e.previewText}:{},previewMode:e.previewMode,...e.reportClasses.length>0?{reportClasses:[...e.reportClasses]}:{},priority:e.priority,...Object.keys(r).length>0?{targetOverrides:r}:{}}}function vf(e,t,n){let r=_f(e,n),i={};return r.name!==t.name&&(i.name=r.name),r.enabled!==t.enabled&&(i.enabled=r.enabled),nu(r.deviceIds,t.deviceIds)||(i.deviceIds=r.deviceIds),nu(r.schedule,t.schedule)||(i.schedule=r.schedule),r.cadenceSec!==t.cadenceSec&&(i.cadenceSec=r.cadenceSec),r.framerate!==t.framerate&&(i.framerate=r.framerate),r.denseCadenceSec!==t.denseCadenceSec&&(i.denseCadenceSec=r.denseCadenceSec??yf(r.cadenceSec)),r.minDwellSec!==t.minDwellSec&&r.minDwellSec!==void 0&&(i.minDwellSec=r.minDwellSec),nu(r.targets,t.targets)||(i.targets=r.targets),nu(r.template,t.template)||(i.template=r.template??null),r.previewText!==t.previewText&&r.previewText!==void 0&&(i.previewText=r.previewText),r.previewMode!==t.previewMode&&(i.previewMode=r.previewMode),nu(r.reportClasses,t.reportClasses)||(i.reportClasses=r.reportClasses??[]),r.priority!==t.priority&&(i.priority=r.priority),nu(r.targetOverrides??{},t.targetOverrides??{})||(i.targetOverrides=r.targetOverrides??{}),i}function yf(e){return Math.max(af,e/rf)}function bf(e,t,n){return t<=0||n<=0?0:e/t/n}function xf(e,t){return e*t*oe}function Sf(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 ${tf}.`),(!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 ${oe}s and ${nf}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 Cf(e){return Sf(e).length===0}function wf(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=xf(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 Tf(e){return Ql(e)}function Ef(e,t){return $l(e,t,`Never run`)}function Df(e){return e.denseCadenceSec===void 0?{seconds:yf(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var Of=[{key:`rule`,get label(){return q.t(`helpers.notificationTimelapse.tab_rule`)},fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,get label(){return q.t(`helpers.notificationTimelapse.tab_window`)},fields:[`schedule`]},{key:`sampling`,get label(){return q.t(`helpers.notificationTimelapse.tab_sampling`)},fields:[`cadenceSec`,`framerate`,`denseCadenceSec`,`minDwellSec`]},{key:`delivery`,get label(){return q.t(`helpers.notificationTimelapse.tab_delivery`)},fields:[`targetIds`,`priority`,`previewMode`,`previewText`,`previewTextSet`,`templateTitle`,`templateBody`,`reportClasses`,`targetOverrides`]}],kf=`rule`;function Af(e){return Of.find(t=>t.key===e)?.key}c();var jf=7;function Mf(e){return of.find(t=>t===e)}function Nf({rule:t,cameras:n,fleet:r,targets:a,onSaved:s,onCancel:c}){let{t:l}=J(),u=N(),[p,m]=o(()=>t===null?pf():mf(t)),[h,_]=o(null),[v,y]=o(t!==null),[b,x]=o(kf),S=e=>m(t=>({...t,...e})),C=ls(),w=C.data?as(C.data,{family:`timelapse`,field:`previewText`}):void 0,T=Ms(),E=ur(wn(a),T),D=d({mutationFn:async()=>{let e=t===null?{rule:_f(p,E)}:{ruleId:t.id,patch:vf(p,t,E)};await u.trpcClient.addons.custom.mutate({addonId:$,action:Qd,input:e})},onSuccess:s,onError:e=>_(e instanceof Error?e.message:`Save failed`)}),O=Sf(p),k=wf(p),A=Df(p),M=bf(jf,A.seconds,p.framerate),P=Of.some(e=>e.key===b)?b:kf;return i(At,{open:!0,onOpenChange:e=>!e&&c(),children:e(bt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(`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:[i(j,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`span`,{className:`truncate`,children:t===null?l(`system.notificationTimelapseEditor.newTimelapse`,`New timelapse`):l(`system.notificationTimelapseEditor.edit`,`Edit {{name}}`,{name:t.name})})]})}),h!==null&&i(`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&&i(Sl,{kind:`timelapse`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt}),v?i(Hl,{problems:O,testId:`timelapse-problems`}):null,i(Ul,{warnings:k,testId:`timelapse-warnings`})]}),e(Xt,{value:P,onValueChange:e=>x(Af(e)??b),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[i(qt,{className:`mb-3 shrink-0`,children:Of.map(e=>i($t,{value:e.key,children:e.label},e.key))}),e(ht,{className:`pr-1`,children:[e(H,{value:`rule`,className:`space-y-3`,children:[i(Z,{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:[i(`label`,{className:X,children:l(`system.notificationTimelapseEditor.name`,`Name`)}),i(U,{value:p.name,onChange:e=>S({name:e.target.value}),placeholder:l(`system.notificationTimelapseEditor.eGNightDriveway`,`e.g. Night driveway`),"data-testid":`timelapse-name`})]}),i(`div`,{className:`pb-1.5`,children:i(Kl,{label:l(`system.notificationTimelapseEditor.enabled`,`Enabled`),checked:p.enabled,onChange:e=>S({enabled:e}),testId:`timelapse-enabled`})})]})}),i(Z,{title:l(`system.notificationTimelapseEditor.cameras`,`Cameras`),children:i(Wl,{cameras:n,value:p.deviceIds,fleet:r,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.`)})})]}),i(H,{value:`window`,className:`space-y-3`,children:i(Z,{title:l(`system.notificationTimelapseEditor.when`,`When`),children:e(`div`,{children:[i(`label`,{className:X,children:l(`system.notificationTimelapseEditor.weeklyWindows`,`Weekly windows`)}),i(Fr,{value:p.schedule,onChange:e=>S({schedule:e})}),i(`p`,{className:Vl,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.`)})]})})}),i(H,{value:`sampling`,className:`space-y-3`,children:e(Z,{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:[i(Q,{label:l(`system.notificationTimelapseEditor.baseCadenceSeconds`,`Base cadence (seconds)`),value:p.cadenceSec,min:2,max:tf,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`}),i(Q,{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:[i(`label`,{className:X,children:l(`system.notificationTimelapseEditor.denseCadenceNearTheDetections`,`Dense cadence, near the detections`)}),e(`div`,{className:`flex items-center gap-2`,children:[i(F,{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:Df(p).seconds}),"data-testid":`timelapse-dense-mode`}),p.denseCadenceSec!==void 0&&i(U,{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:Vl,"data-testid":`timelapse-dense-hint`,children:[l(`system.notificationTimelapseEditor.denseHint`,{seconds:A.seconds,fps:p.framerate,passage:jf,onScreen:M.toFixed(2)}),` `,A.derived?l(`system.notificationTimelapseEditor.denseDerived`):l(`system.notificationTimelapseEditor.denseFixed`,{seconds:Df({...p,denseCadenceSec:void 0}).seconds})]})]}),i(Q,{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`})]})}),i(H,{value:`delivery`,className:`space-y-3`,children:e(Z,{title:l(`system.notificationTimelapseEditor.theNotification`,`The notification`),children:[i(Gl,{targets:a,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:[i(`label`,{className:X,children:l(`system.notificationTimelapseEditor.preview`,`Preview`)}),i(F,{value:p.previewMode,options:of.map(e=>({value:e,label:sf[e]})),onChange:e=>{let t=Mf(e.target.value);t!==void 0&&S({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),i(Q,{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:[i(ps,{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:ce}),onChange:e=>S({previewText:e,previewTextSet:!0}),vars:w,deviceValues:!1,testId:`timelapse-preview-text`}),e(`p`,{className:Vl,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:ce}),p.previewTextSet&&e(f,{children:[` `,i(K,{variant:`unstyled`,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`)})]})]})]}),i(ql,{title:p.templateTitle,body:p.templateBody,onTitleChange:e=>S({templateTitle:e}),onBodyChange:e=>S({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:i(jn,{i18nKey:`system.notificationTimelapseEditor.detectionSummaryNote`,values:{token:`{{detectionSummary}}`},components:{code:i(`code`,{})}})}),i(Ns,{surface:`timelapse`,templateFamily:`timelapse`,targetIds:p.targetIds,targets:a,overrides:p.targetOverrides,rulePriority:p.priority,onChange:e=>S({targetOverrides:e})})]})})]})]}),e(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[i(K,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:l(`common.cancel`,`Cancel`)}),e(K,{size:`sm`,type:`button`,disabled:D.isPending,onClick:()=>{y(!0),!(!Cf(p)||D.isPending)&&D.mutate()},children:[D.isPending&&i(g,{className:`h-3.5 w-3.5 animate-spin`}),t===null?l(`system.notificationTimelapseEditor.create`,`Create`):l(`common.save`,`Save`)]})]})]})})}c();var Pf=`notification-output`;function Ff(e){return e.map(e=>({id:e.id,name:e.name,kind:je(e.recordKind),addonId:e.addonId,enabled:e.enabled,config:{...e.formValues}}))}function If(){let e=Ut({functionCap:Pf});return{data:n(()=>e.data===void 0?void 0:Ff(e.data),[e.data]),isError:e.isError}}function Lf({children:e,className:t}){return i(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function Rf(){return i(`div`,{className:`flex items-center justify-center py-16`,children:i(g,{className:`h-6 w-6 animate-spin text-primary`})})}function zf({children:e,testId:t}){return i(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function Bf({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:a}){return i(Zt,{children:i(mt,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,maxBodyHeight:yt,...a===void 0?{}:{onRowClick:a}})})}function Vf({name:t,enabled:n,onOpen:r,badges:a,openTestId:o}){let{t:s}=J();return e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[r===void 0?i(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t}):i(Lf,{children:i(K,{variant:`unstyled`,type:`button`,onClick:r,className:`truncate rounded text-left text-sm font-medium text-foreground hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,...o===void 0?{}:{"data-testid":o},children:t})}),!n&&i(G,{variant:`warning`,children:s(`common.disabled`)}),a]})}function Hf({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:a=`Delete`,cancelLabel:o=`Cancel`,ariaLabel:s,testId:c,onConfirm:l}){let u=A(),d=async()=>{await u({title:n,message:r,confirmLabel:a,cancelLabel:o,variant:`danger`})&&l()};return i(K,{variant:`unstyled`,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:i(D,{className:`h-3.5 w-3.5 text-danger`})})}c();var Uf=[`notificationSummaries`,`listSummaryRules`];function Wf(t){return[{key:`name`,header:q.t(`system.notificationSummaries.digest`,`Digest`),render:n=>i(Vf,{name:n.name,enabled:n.enabled,...ad(n)?{onOpen:()=>t.onOpen(n)}:{},openTestId:`summary-edit-${n.id}`,badges:e(f,{children:[!ad(n)&&i(G,{variant:`warning`,children:`read-only`}),n.ai?.enabled===!0&&i(G,{variant:`info`,children:`AI`}),n.ai!==void 0&&!n.ai.enabled&&i(G,{variant:`default`,children:q.t(`system.notificationSummaries.aiOff`,`AI off`)})]})})},{key:`cameras`,header:q.t(`system.notificationSummaries.cameras`,`Cameras`),align:`center`,nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:q.t(`system.notificationSummaries.window`,`Window`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Bd(e.window)})},{key:`filters`,header:q.t(`system.notificationSummaries.keeps`,`Keeps`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Hd(e.filters)})},{key:`mosaic`,header:q.t(`system.notificationSummaries.mosaic`,`Mosaic`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:q.t(`system.notificationSummaries.tilesRank`,{count:e.maxTiles,rank:e.rank})})},{key:`targets`,header:q.t(`system.notificationSummaries.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r!==null?r:q.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:q.t(`system.notificationSummaries.lastRun`,`Last run`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${e.id}`,children:Vd(e.generatedAt,t.nowMs)})},{key:`enabled`,header:q.t(`system.notificationSummaries.on`,`On`),align:`center`,nowrap:!0,render:e=>i(Lf,{children:i(W,{checked:e.enabled,disabled:e.readOnly,onCheckedChange:n=>t.onToggle(e,n),"aria-label":q.t(`system.notificationSummaries.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(Lf,{className:`flex items-center justify-end gap-1`,children:[i(K,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.readOnly,onClick:()=>t.onTest(n),title:q.t(`system.notificationSummaries.produceThisDigestNowAnd`,`Produce this digest now and DELIVER it`),"aria-label":q.t(`system.notificationSummaries.test`,`test {{name}}`,{name:n.name}),"data-testid":`summary-test-${n.id}`,children:i(at,{className:`h-3.5 w-3.5`})}),i(Hf,{disabled:n.readOnly,pending:t.deletePending,title:q.t(`system.notificationSummaries.deleteThisSummary`,`Delete this summary?`),message:q.t(`system.notificationSummaries.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:n.name}),ariaLabel:q.t(`system.notificationSummaries.delete`,`delete {{name}}`,{name:n.name}),testId:`summary-delete-${n.id}`,onConfirm:()=>t.onConfirmDelete(n)})]})}]}c();var Gf=[`notificationTimelapses`,`listTimelapseRules`];function Kf(t){return[{key:`name`,header:q.t(`system.notificationTimelapses.timelapse`,`Timelapse`),render:e=>i(Vf,{name:e.name,enabled:e.enabled,...uf(e)?{onOpen:()=>t.onOpen(e),openTestId:`timelapse-edit-${e.id}`}:{},badges:uf(e)?null:i(G,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:q.t(`system.notificationTimelapses.cameras`,`Cameras`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length===1?t.cameraNameById.get(e.deviceIds[0]??-1)??`#${e.deviceIds[0]}`:q.t(`system.notificationTimelapses.cameras2`,`{{length}} cameras`,{length:e.deviceIds.length})})},{key:`schedule`,header:q.t(`system.notificationTimelapses.window`,`Window`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Tf(e.schedule)})},{key:`sampling`,header:q.t(`system.notificationTimelapses.sampling`,`Sampling`),nowrap:!0,render:t=>{let n=Df(mf(t));return e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[q.t(n.derived?`system.notificationTimelapses.ruleSummaryAuto`:`system.notificationTimelapses.ruleSummary`,{cadence:t.cadenceSec,fps:t.framerate,dense:n.seconds}),t.minDwellSec===void 0?``:` · ${q.t(`system.notificationTimelapses.ruleDwell`,{sec:t.minDwellSec})}`]})}},{key:`targets`,header:q.t(`system.notificationTimelapses.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r!==null?r:q.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:q.t(`system.notificationTimelapses.lastRun`,`Last run`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${e.id}`,children:Ef(e.lastGeneratedAt,t.nowMs)})},{key:`enabled`,header:q.t(`system.notificationTimelapses.on`,`On`),align:`center`,nowrap:!0,render:e=>i(Lf,{children:i(W,{checked:e.enabled,disabled:!uf(e),onCheckedChange:n=>t.onToggle(e,n),"aria-label":q.t(`system.notificationTimelapses.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(Lf,{className:`flex items-center justify-end gap-1`,children:[i(K,{size:`sm`,variant:`ghost`,type:`button`,disabled:!uf(n),onClick:()=>t.onTest(n),title:q.t(`system.notificationTimelapses.renderThisRuleSLast`,`Render this rule's last closed window now and DELIVER it`),"aria-label":q.t(`system.notificationTimelapses.test`,`test {{name}}`,{name:n.name}),"data-testid":`timelapse-test-${n.id}`,children:i(at,{className:`h-3.5 w-3.5`})}),i(Hf,{disabled:!uf(n),pending:t.deletePending,title:q.t(`system.notificationTimelapses.deleteThisTimelapse`,`Delete this timelapse?`),message:q.t(`system.notificationTimelapses.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:n.name}),ariaLabel:q.t(`system.notificationTimelapses.delete`,`delete {{name}}`,{name:n.name}),testId:`timelapse-delete-${n.id}`,onConfirm:()=>t.onConfirmDelete(n)})]})}]}c();var qf={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`}},Jf=`system.notificationProducerRules.unreadableMessage`;function Yf(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function Xf({cameras:t,fleet:n,targets:r,taxonomy:a}){let{t:c}=J(),l=N(),[u,p]=o({mode:`closed`}),[m,h]=o(null),[g,_]=o(null),[v,y]=o(null),[b,x]=o(null),S=s({queryKey:Uf,queryFn:async()=>Cd(await l.trpcClient.addons.custom.mutate({addonId:$,action:Vu,input:{}}))}),C=s({queryKey:Gf,queryFn:async()=>lf(await l.trpcClient.addons.custom.mutate({addonId:$,action:Zd,input:{}}))}),w=s({queryKey:bu,queryFn:async()=>Du(await l.trpcClient.addons.custom.mutate({addonId:$,action:xu,input:{}}))}),T=S.data??[],E=C.data??[],D=w.data??[],O=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Hu,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),k=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Uu,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),A=d({mutationFn:async e=>wd(await l.trpcClient.addons.custom.mutate({addonId:$,action:Wu,input:{ruleId:e,...Ud(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),j=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Qd,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),M=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:$d,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),P=d({mutationFn:async e=>ff(await l.trpcClient.addons.custom.mutate({addonId:$,action:ef,input:e})),onSuccess:e=>{y(null),x(e)}}),ee=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Su,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void w.refetch()}),te=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Cu,input:{ruleId:e}}),onSuccess:()=>void w.refetch()}),ne=t.toSorted((e,t)=>e.name.localeCompare(t.name)),I=r.map(e=>({id:e.id,name:e.name,enabled:e.enabled,kind:e.kind,addonId:e.addonId})),re=new Map(I.map(e=>[e.id,e.name])),ie=new Map(ne.map(e=>[e.id,e.name])),L=Date.now(),R={summary:{nowMs:L,targetNameById:re,deletePending:k.isPending,onToggle:(e,t)=>O.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{ad(e)&&p({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>k.mutate(e.id)},timelapse:{nowMs:L,cameraNameById:ie,targetNameById:re,deletePending:M.isPending,onToggle:(e,t)=>j.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{uf(e)&&p({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>M.mutate(e.id)},calendar:{nowMs:L,targetNameById:re,deletePending:te.isPending,onToggle:(e,t)=>ee.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Ou(e)&&p({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>te.mutate(e.id)}},z=e=>{switch(e.family){case`summary`:R.summary.onOpen(e.rule);return;case`timelapse`:R.timelapse.onOpen(e.rule);return;case`calendar-events`:R.calendar.onOpen(e.rule);return}},ae=e=>{p(e===`summary`?{mode:`summary`,rule:null}:e===`timelapse`?{mode:`timelapse`,rule:null}:{mode:`calendar-events`,rule:null})},oe=e=>{let t=e===`summary`?S:e===`timelapse`?C:w;return t.isLoading?null:t.isError?{unreadable:!1}:t.data===null?{unreadable:!0}:null},se=e=>{e===`summary`?S.refetch():e===`timelapse`?C.refetch():w.refetch()},ce=e=>{let t=Yf(e);return t!==null&&oe(t)!==null},le=t=>{let n=Yf(t),r=n===null?null:oe(n);return e(f,{children:[n!==null&&r!==null&&i(pt,{title:c(qf[n].titleKey),message:c(r.unreadable?Jf:qf[n].messageKey),onRetry:()=>se(n)}),k.isError&&i(pt,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(k.error)}),M.isError&&i(pt,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(M.error)}),te.isError&&i(pt,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(te.error)}),A.isError&&i(pt,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(A.error)}),P.isError&&i(pt,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(P.error)}),g!==null&&i(Zf,{outcome:g,onDismiss:()=>_(null)}),b!==null&&i(Qf,{outcome:b,onDismiss:()=>x(null)})]})},ue=()=>p({mode:`closed`}),de=e(f,{children:[u.mode===`summary`&&i(Xd,{rule:u.rule,cameras:ne,fleet:n,targets:I,taxonomy:a,onCancel:ue,onSaved:()=>{ue(),S.refetch()}}),u.mode===`timelapse`&&i(Nf,{rule:u.rule,cameras:ne,fleet:n,targets:I,onCancel:ue,onSaved:()=>{ue(),C.refetch()}}),u.mode===`calendar-events`&&i(Bu,{rule:u.rule,targets:I,onCancel:ue,onSaved:()=>{ue(),w.refetch()}}),i(Jl,{open:m!==null,ruleName:m?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${m?.targets.length??0} target${(m?.targets.length??0)===1?``:`s`}`,pending:A.isPending,onCancel:()=>h(null),onConfirm:()=>{m!==null&&A.mutate(m.id)}}),i(Jl,{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:[i(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.notificationProducerRules.whichCamera`,`Which camera`)}),i(F,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:ie.get(e)??`#${e}`})),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&y({rule:v.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>y(null),onConfirm:()=>{v!==null&&v.deviceId!==null&&P.mutate({ruleId:v.rule.id,deviceId:v.deviceId})}})]});return{summaries:T,timelapses:E,calendarEvents:D,loading:S.isLoading||C.isLoading||w.isLoading,columnDeps:R,open:z,create:ae,notices:le,listFailed:ce,overlays:de}}function Zf({outcome:t,onDismiss:n}){let{t:r}=J();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:[r(`system.notificationProducerRules.summaryProduced`,{digests:r(`system.notificationProducerRules.digestCount`,{count:t.produced}),tiles:r(`system.notificationProducerRules.tileCount`,{count:t.tiles??0}),cameras:r(`system.notificationProducerRules.cameraCount`,{count:t.cameras??0}),matched:r(`system.notificationProducerRules.tracksMatched`,{count:t.matched??0}),sent:r(`system.notificationProducerRules.notificationsSent`,{count:t.enqueued??0})}),(t.droppedStationary??0)>0&&i(`span`,{"data-testid":`summary-test-dropped-stationary`,className:`ml-1`,children:r(`system.notificationProducerRules.droppedStationary`,{count:t.droppedStationary})})]}):e(`span`,{className:`text-warning`,children:[r(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,t.error]}),i(K,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:n,children:r(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}function Qf({outcome:t,onDismiss:n}){let{t:r}=J();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?i(`span`,{children:r(t.coveragePercent===void 0?`system.notificationProducerRules.timelapseProduced`:`system.notificationProducerRules.timelapseProducedCoverage`,{videos:r(`system.notificationProducerRules.videoCount`,{count:t.produced}),percent:Math.round(t.coveragePercent??0),sent:r(`system.notificationProducerRules.notificationsSent`,{count:t.enqueued??0})})}):e(`span`,{className:`text-warning`,children:[r(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,t.error]}),i(K,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:n,children:r(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}var $f=[{key:`summaries`,get label(){return q.t(`helpers.notificationRulesArea.sumLabel`)},get blurb(){return q.t(`helpers.notificationRulesArea.sumBlurb`)},get newLabel(){return q.t(`helpers.notificationRulesArea.sumNew`)},get emptyHint(){return q.t(`helpers.notificationRulesArea.sumEmpty`)}},{key:`timelapses`,get label(){return q.t(`helpers.notificationRulesArea.tlLabel`)},get blurb(){return q.t(`helpers.notificationRulesArea.tlBlurb`)},get newLabel(){return q.t(`helpers.notificationRulesArea.tlNew`)},get emptyHint(){return q.t(`helpers.notificationRulesArea.tlEmpty`)}},{key:`calendar-events`,get label(){return q.t(`helpers.notificationRulesArea.calLabel`)},get blurb(){return q.t(`helpers.notificationRulesArea.calBlurb`)},get newLabel(){return q.t(`helpers.notificationRulesArea.calNew`)},get emptyHint(){return q.t(`helpers.notificationRulesArea.calEmpty`)}}],ep=[{type:`detection`,get label(){return q.t(`helpers.notificationRulesArea.opt_detection_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_detection_hint`)}},{type:`sensor`,get label(){return q.t(`helpers.notificationRulesArea.opt_sensor_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_sensor_hint`)}},{type:`audio`,get label(){return q.t(`helpers.notificationRulesArea.opt_audio_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_audio_hint`)}},{type:`occupancy`,get label(){return q.t(`helpers.notificationRulesArea.opt_occupancy_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_occupancy_hint`)}},{type:`device-events`,get label(){return q.t(`helpers.notificationRulesArea.opt_deviceEvents_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_deviceEvents_hint`)}},{type:`system`,get label(){return q.t(`helpers.notificationRulesArea.opt_system_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_system_hint`)}},{type:`alarm`,get label(){return q.t(`helpers.notificationRulesArea.opt_alarm_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_alarm_hint`)}},{type:`summary`,get label(){return q.t(`helpers.notificationRulesArea.opt_summary_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_summary_hint`)}},{type:`timelapse`,get label(){return q.t(`helpers.notificationRulesArea.opt_timelapse_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_timelapse_hint`)}},{type:`calendar-events`,get label(){return q.t(`helpers.notificationRulesArea.opt_calendarEvents_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_calendarEvents_hint`)}}];function tp(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function np(e){if(!(e==null||e.length===0))return tp(e)?e:se(e)}function rp(e){let t=$f.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function ip(e){return[...tn.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...$f]}function ap(e){return!tp(e)}function op(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}c();function sp(e){return[{key:`name`,header:q.t(`system.notificationCalendarEventsPage.rule`,`Rule`),render:t=>i(Vf,{name:t.name,enabled:t.enabled,...Ou(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:Ou(t)?null:i(G,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:q.t(`system.notificationCalendarEventsPage.when`,`When`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Mu(e.schedule)})},{key:`horizon`,header:q.t(`system.notificationCalendarEventsPage.horizon`,`Horizon`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Ru(e.horizonDays)})},{key:`calendars`,header:q.t(`system.notificationCalendarEventsPage.calendars`,`Calendars`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:zu(e)})},{key:`targets`,header:q.t(`system.notificationCalendarEventsPage.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:q.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:q.t(`system.notificationCalendarEventsPage.lastRun`,`Last run`),nowrap:!0,render:t=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:Vd(t.generatedAt,e.nowMs)})},{key:`enabled`,header:q.t(`system.notificationCalendarEventsPage.on`,`On`),align:`center`,nowrap:!0,render:t=>i(Lf,{children:i(W,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":q.t(`system.notificationCalendarEventsPage.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>i(Lf,{className:`flex items-center justify-end gap-1`,children:i(Hf,{disabled:t.readOnly,pending:e.deletePending,title:q.t(`system.notificationCalendarEventsPage.deleteThisCalendarEventsRule`,`Delete this calendar-events rule?`),message:q.t(`system.notificationCalendarEventsPage.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:q.t(`system.notificationCalendarEventsPage.delete`,`delete {{name}}`,{name:t.name}),testId:`calendar-events-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})})}]}function cp(e,t){return e.replaceAll(`{{name}}`,t)}function lp(t){return[{key:`name`,header:q.t(`system.notificationRuleColumns.rule`,`Rule`),render:e=>i(Vf,{name:e.name,enabled:e.enabled,...Or(e)?{onOpen:()=>t.onOpen(e)}:{}})},{key:`trigger`,header:q.t(`system.notificationRuleColumns.trigger`,`Trigger`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Tr(n,t.t(`notificationRules.grouping.choice`,On))}),!mi(n.delivery)&&i(G,{variant:`warning`,children:q.t(`common.readOnly`)})]})},{key:`targets`,header:q.t(`system.notificationRuleColumns.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r?r:q.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:q.t(`system.notificationRuleColumns.lastRun`,`Last run`),nowrap:!0,render:e=>i(el,{cell:t.lastRunOf(e.id)})},{key:`priority`,header:q.t(`system.notificationRuleColumns.priority`,`Priority`),align:`center`,nowrap:!0,render:e=>i(`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=>i(Lf,{children:i(ll,{rule:e,snoozes:t.snoozes,exempt:nn(e.conditions,vr({onActivation:e.actions?.onActivation??[],onDeactivation:e.actions?.onDeactivation??[],onTrigger:e.actions?.onTrigger??[],onTriggerOff:e.actions?.onTriggerOff??[],buttons:e.actions?.buttons??[]},t.actions))})})},{key:`enabled`,header:q.t(`system.notificationRuleColumns.on`,`On`),align:`center`,nowrap:!0,render:e=>i(Lf,{children:i(W,{checked:e.enabled,onCheckedChange:n=>t.onToggle(e,n),"aria-label":q.t(`system.notificationRuleColumns.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>Or(n)?e(Lf,{className:`flex items-center justify-end gap-1`,children:[i(Fl,{ruleId:n.id,ruleName:n.name,...n.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:n.conditions.devices[0]}}),t.onOpenHistory&&i(tl,{rule:n,onOpenHistory:t.onOpenHistory}),t.onTest&&i(K,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest?.(n),title:q.t(`system.notificationRuleColumns.openInTheSimulatorDescribe`,`Open in the simulator — describe an event and tune it before injecting`),"aria-label":q.t(`system.notificationRuleColumns.simulate`,`simulate {{name}}`,{name:n.name}),children:i(at,{className:`h-3.5 w-3.5`})}),i(K,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDuplicate(n),title:q.t(`system.notificationRuleColumns.duplicate`,`Duplicate`),children:i(M,{className:`h-3.5 w-3.5`})}),i(dp,{rule:n,deps:t})]}):i(up,{rule:n,deps:t})}]}function up({rule:t,deps:n}){let{t:r}=J();return e(Lf,{className:`flex items-center justify-end gap-1`,children:[i(`span`,{title:ze(R(t)).blurb,children:i(G,{variant:`warning`,children:r(`system.notificationRuleColumns.recreateAsOneRulePer`,`Recreate as one rule per family`)})}),n.onOpenHistory&&i(tl,{rule:t,onOpenHistory:n.onOpenHistory}),i(dp,{rule:t,deps:n})]})}function dp({rule:e,deps:t}){let{t:n}=J();return i(Hf,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:cp(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:cp(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function fp(e){let t=lp(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:q.t(`system.notificationRuleColumns.events`,`Events`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Hn(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:q.t(`system.notificationRuleColumns.scope`,`Scope`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:qr(e.conditions.systemEvent)})},{key:`targets`,header:q.t(`system.notificationRuleColumns.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:q.t(`common.targetCount`,{count:t.targets.length})})}},{key:`cooldown`,header:q.t(`system.notificationRuleColumns.cooldown`,`Cooldown`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:fi(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function pp(e){switch(e){case`detection`:return q.t(`helpers.unifiedRulesModel.kind_detection`);case`sensor`:return q.t(`helpers.unifiedRulesModel.kind_sensor`);case`sound`:return q.t(`helpers.unifiedRulesModel.kind_sound`);case`occupancy`:return q.t(`helpers.unifiedRulesModel.kind_occupancy`);case`device-events`:return q.t(`helpers.unifiedRulesModel.kind_device_events`);case`system`:return q.t(`helpers.unifiedRulesModel.kind_system`);case`alarm`:return q.t(`helpers.unifiedRulesModel.kind_alarm`);case`mixed`:return q.t(`helpers.unifiedRulesModel.kind_mixed`);case`summary`:return q.t(`helpers.unifiedRulesModel.kind_summary`);case`timelapse`:return q.t(`helpers.unifiedRulesModel.kind_timelapse`);case`calendar-events`:return q.t(`helpers.unifiedRulesModel.kind_calendar_events`)}}function mp(e){return{family:`event`,kind:R(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function hp(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function gp(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function _p(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function vp(e){return[...e.events.map(mp),...e.summaries.map(hp),...e.timelapses.map(gp),...e.calendarEvents.map(_p)]}function yp(e,t){return t===`all`?!0:tp(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:ap(t)&&e.family===`event`?_e(e.rule,t):!1}function bp(e,t){return vp(t).filter(t=>yp(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function xp(e,t){return bp(e,t).length}function Sp(e){return e===`all`?900:860}function Cp(e){return e.family===`event`?e.rule:null}function wp(e){return e.family===`summary`?e.rule:null}function Tp(e){return e.family===`timelapse`?e.rule:null}function Ep(e){return e.family===`calendar-events`?e.rule:null}function Dp(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 Op(e,t){return e.map(e=>Dp(e,t))}function kp(e,t){return e.find(e=>e.key===t)}function Ap(e,t,n){let r=kp(lp(n.event),e),i=kp(Wf(n.summary),e),a=kp(Kf(n.timelapse),e),o=kp(sp(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 jp(e){switch(e.family){case`event`:return null;case`summary`:return Bd(e.rule.window);case`timelapse`:return Tf(e.rule.schedule);case`calendar-events`:return Mu(e.rule.schedule)}}function Mp(e){let t=kp(lp(e.event),`trigger`);return{key:`when`,header:q.t(`system.unifiedRulesColumns.when`,`When`),render:(e,n)=>{let r=jp(e);return r===null?e.family===`event`?t?.render(e.rule,n)??null:null:i(`span`,{className:`text-[11px] text-foreground-subtle`,children:r})}}}function Np(e){return[Ap(`name`,`Name`,e),{key:`type`,header:q.t(`system.unifiedRulesColumns.type`,`Type`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:pp(e.kind)})},Mp(e),Ap(`targets`,`Targets`,e),Ap(`lastRun`,`Last run`,e),Ap(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),Ap(`enabled`,`On`,e),Ap(`actions`,``,e)]}function Pp(e,t){return e===`all`?Np(t):e===`summaries`?Op(Wf(t.summary),wp):e===`timelapses`?Op(Kf(t.timelapse),Tp):e===`calendar-events`?Op(sp(t.calendar),Ep):ap(e)&&Zr(e)?Op(fp(t.event),Cp):Op(lp(t.event),Cp)}function Fp({value:t,family:n,kinds:r,onChange:a,draft:o}){let{t:s}=J();if(!Nn(n))return null;let c=Zn(t,r),l=[{id:`activation`,on:c.onActivation,label:s(`system.notificationSystemEventDelivery.whenItStarts`,`When it starts`)},{id:`deactivation`,on:c.onDeactivation,label:s(`system.notificationSystemEventDelivery.whenItClears`,`When it clears`)},{id:`schedule`,on:c.onSchedule!==void 0,label:s(`system.notificationSystemEventDelivery.onASchedule`,`On a schedule`)}],u=Je({delivery:`system-event`,conditions:r.length>0?{systemEvent:{kinds:[...r]}}:{},systemEventDelivery:c}).filter(e=>e.code===`no-mode`||e.code===`no-instant-kind`).map(be);return e(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:s(`system.notificationSystemEventDelivery.delivery`,`Delivery`)}),i(`div`,{className:`flex flex-wrap gap-1.5`,role:`group`,children:l.map(t=>e(`label`,{className:te(re,`cursor-pointer`,t.on?I:k),children:[i(m,{checked:t.on,onChange:e=>a(sn(c,t.id,e.target.checked)),"data-testid":`rule-delivery-${t.id}`}),t.label]},t.id))}),i(Ip,{modes:c,kinds:r}),u.map(e=>i(`p`,{className:`mt-2 text-[11px] text-danger`,"data-testid":`rule-delivery-problem`,children:e},e)),c.onSchedule!==void 0&&i(Lp,{value:c,onChange:a,draft:o})]})}function Ip({modes:t,kinds:n}){let{t:r}=J(),a=Tn(n),o=!t.onActivation&&!t.onDeactivation;return e(`div`,{className:`mt-2 space-y-1`,"data-testid":`rule-delivery-hints`,children:[t.onDeactivation&&a.adds.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-clears-hint`,children:r(`system.notificationSystemEventDelivery.clearsAdds`,`When it clears also reports the recovery of: {{what}}.`,{what:a.adds.join(` · `)})}),t.onDeactivation&&a.without>0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-no-clearing-hint`,children:r(`system.notificationSystemEventDelivery.noClearingEvent`,{count:a.without})}),t.onSchedule!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-schedule-hint`,children:o?r(`system.notificationSystemEventDelivery.scheduleOnlyHint`,`Only on a schedule: nothing is sent per event, and the active hours and actions of this rule do not apply.`):r(`system.notificationSystemEventDelivery.scheduleBesideHint`,`The summary is sent at the times below whatever the active hours of this rule say, and runs no actions.`)})]})}function Lp({value:t,onChange:n,draft:r}){let{t:a}=J(),o=t.onSchedule;return o===void 0?null:e(`div`,{className:`mt-2 space-y-2`,children:[i(`p`,{className:xi,children:a(`system.notificationSystemEventDelivery.summaryExplain`,`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. Nothing to report sends nothing. Time zone: {{timezone}}.`,{timezone:o.schedule.timezone??a(`system.notificationSystemEventDelivery.theHubS`,`the hub’s`)})}),i(Fr,{mode:`times`,value:o.schedule,onChange:e=>{e!==void 0&&n(Cn(t,e))}}),i(W,{checked:o.grouping===`section`,onCheckedChange:e=>n(lr(t,e?`section`:`rule`)),label:a(`system.notificationSystemEventDelivery.onePerCategory`,`One notification per category`),"data-testid":`rule-delivery-grouping`}),i(Rp,{draft:r,split:o.grouping})]})}function Rp({draft:t,split:n}){let{t:r}=J(),a=N(),o=d({mutationFn:e=>a.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),s=ji(o.status,o.data,o.error,n);return e(`div`,{className:`space-y-1.5`,children:[i(K,{size:`sm`,variant:`secondary`,onClick:()=>o.mutate(t()),disabled:o.isPending,"data-testid":`rule-delivery-preview`,children:o.isPending?r(`system.notificationSystemEventDelivery.readingTheState`,`Reading the state…`):r(`system.notificationSystemEventDelivery.previewTheSummaryNow`,`Preview the summary now`)}),s!==null&&i(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:s.lines.map((e,t)=>i(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function zp(e,t){if(e.status===`error`)return{kind:`failed`,reason:e.error instanceof Error?e.error.message:q.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 Bp=6e4,Vp=60*Bp,Hp=24*Vp;function Up(e){return e===null?q.t(`helpers.notificationRuleLastRun.noDelivery`):e>=Hp?q.t(`helpers.notificationRuleLastRun.notInDay`,{count:Math.floor(e/Hp)}):e>=Vp?q.t(`helpers.notificationRuleLastRun.notInHour`,{count:Math.floor(e/Vp)}):e>=Bp?q.t(`helpers.notificationRuleLastRun.notInMinute`,{count:Math.floor(e/Bp)}):q.t(`helpers.notificationRuleLastRun.notInWindow`)}c();var Wp=[`notificationRules`,`listRules`],Gp=[`notificationRules`,`getConditionCatalog`],Kp=[`deviceManager`,`gateableDevices`],qp=Te.options;function Jp({onSimulateRule:r,onOpenHistory:c,createRequested:l=!1,onCreateConsumed:u,createTypeRequested:f=null,onCreateTypeConsumed:p,headerOwnsCreate:m=!1}={}){let h=N(),{t:g}=J(),{state:_,openEdit:v,close:y}=Et({editKey:`rule`}),[b,x]=Lt(`section`),[S,C]=Lt(`editTab`),[w,T]=o({mode:`closed`}),[D,O]=o(!1),k=np(b)??`all`,A=e=>{x(e===`all`?null:e)},j=s({queryKey:Wp,queryFn:async()=>(await h.trpcClient.notificationRules.listRules.query({})).rules}),M=t(null);a(()=>{if(w.mode!==`closed`)return;if(_.mode!==`edit`){_.mode===`closed`&&(M.current=null);return}let e=_.id;if(e===`new`||M.current===e)return;let t=j.data?.find(t=>t.id===e);t===void 0||!Or(t)||(M.current=e,T({mode:`form`,rule:t}))},[w.mode,_,j.data]);let P=If(),ee=s({queryKey:Gp,queryFn:()=>h.trpcClient.notificationRules.getConditionCatalog.query({})}),te=Ot({projection:`slim`}),F=Qc(),I=n(()=>te.data??[],[te.data]),re=dt(te),ie=n(()=>I.map(e=>e.id),[I]),L=s({queryKey:[...Kp,ie],enabled:ie.length>0,queryFn:async()=>{let e=[];for(let t of I){let n=he(await h.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),qp);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),R=n(()=>{let e=ut(I);return I.filter(e=>z(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))},[I]),ae=n(()=>I.filter(e=>e.type===Ke.Camera).map(e=>({id:e.id,name:e.name})),[I]),oe=Gi(n(()=>ae.map(e=>e.id),[ae])),se=n(()=>{let e=new Map(ae.map(e=>[e.id,e.name]));return oe.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})))},[oe.results,ae]),ce=n(()=>{let e=new Map;for(let t of P.data??[])e.set(t.id,t.name);return e},[P.data]),le=d({mutationFn:e=>h.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void j.refetch()}),ue=d({mutationFn:e=>h.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void j.refetch()}),de=cl(),fe=xt({},{refetchInterval:Xp}),pe=fe.data??[],me=j.data??[],B=Xf({cameras:ae,fleet:re,targets:P.data??[],taxonomy:ee.data?.taxonomy}),ge={events:me,summaries:B.summaries,timelapses:B.timelapses,calendarEvents:B.calendarEvents},_e=ip(new Map(tn.map(e=>[e.key,xp(e.key,ge)]))),V=_e.find(e=>e.key===k)??_e[0]??tn[0],ye=tp(V.key)?rp(V.key):void 0;ap(V.key)&&V.key;let be=bp(V.key,ge),xe=()=>{_.mode===`edit`&&(M.current=_.id),T({mode:`closed`}),y(),C(null)},Se=e=>{if(!Or(e))return;let t=e.id.length>0?e.id:`new`;M.current=t,T({mode:`form`,rule:e}),v(t),C(null)},Ce=e=>{if(op(e)){M.current=`new`,T({mode:`form`,rule:null,seed:ve(e)}),v(`new`),C(null);return}B.create(e)};a(()=>{f!==null&&(Ce(f),p?.())},[f]),a(()=>{l&&(O(!0),u?.())},[l]);let we=e=>{if(e.family===`event`){Se(e.rule);return}B.open(e)},Te={targetNameById:ce,snoozes:de,actions:pe,deletePending:ue.isPending,onToggle:(e,t)=>le.mutate({ruleId:e.id,enabled:t}),onOpen:Se,t:g,onDuplicate:e=>Se({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>ue.mutate(e.id),...r?{onTest:r}:{},lastRunOf:e=>zp(F,e),...c?{onOpenHistory:c}:{}},Ee=Pp(V.key,{event:Te,summary:B.columnDeps.summary,timelapse:B.columnDeps.timelapse,calendar:B.columnDeps.calendar}),De=ye?.blurb??(`blurb`in V?V.blurb:``),Oe=ye===void 0?`creatable`in V?V.creatable:!1:!0,ke=m||!Oe?null:k===`all`?e(K,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:()=>O(!0),children:[i(E,{className:`h-3.5 w-3.5`}),g(`system.notificationRules.newRule`,`New rule`)]}):ye===void 0?e(K,{size:`sm`,type:`button`,onClick:()=>Ce(V.key),"data-testid":`rules-new-${V.key}`,children:[i(E,{className:`h-3.5 w-3.5`}),`newRuleLabel`in V?V.newRuleLabel:g(`system.notificationRules.newRule`,`New rule`)]}):e(K,{size:`sm`,type:`button`,onClick:()=>Ce(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:[i(E,{className:`h-3.5 w-3.5`}),ye.newLabel]});return i(Li,{embedded:!0,icon:ne,title:g(`system.notificationRules.rules`,`Rules`),subtitle:De,children:e(`div`,{className:`flex flex-col gap-3`,children:[ke===null?null:i(`div`,{className:`flex justify-end`,children:ke}),i(Xt,{appearance:`pills`,value:V.key,onValueChange:e=>A(np(e)??k),children:i(qt,{children:_e.map(t=>e($t,{value:t.key,children:[t.label,i(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:xp(t.key,ge)})]},t.key))})}),i(Bl,{rules:me}),B.notices(V.key),(j.isLoading||B.loading)&&i(Rf,{}),j.isError&&!j.isLoading&&i(pt,{title:g(`system.notificationRules.failedToLoadRules`,`Failed to load rules`),message:j.error instanceof Error?j.error.message:g(`system.notificationRules.unknownError`,`Unknown error`),onRetry:()=>void j.refetch()}),!j.isLoading&&!B.loading&&!j.isError&&!B.listFailed(V.key)&&be.length===0&&i(zf,{children:ye?.emptyHint??(`emptyHint`in V?V.emptyHint:g(`system.notificationRules.noRulesYet`,`No rules yet.`))}),be.length>0&&i(Bf,{columns:Ee,rows:be,rowKey:e=>`${e.family}:${e.id}`,onRowClick:we,minWidthPx:Sp(V.key)}),w.mode===`form`&&i(Zp,{rule:w.rule,...w.seed?{seed:w.seed}:{},targets:P.data??[],actuatable:R,fleet:re,actions:pe,actionsAnswered:fe.data!==void 0,catalog:bn(ee.data?.catalog??[]),taxonomy:ee.data?.taxonomy,cameras:ae,gateable:L.data??[],gateableScenes:se,initialEditTab:on(S??``)??`rule`,onEditTabChange:e=>C(e===`rule`?null:e),onCancel:xe,onSaved:()=>{xe(),j.refetch()}}),B.overlays,D?i(Yp,{onCancel:()=>O(!1),onPick:e=>{O(!1),Ce(e)}}):null]})})}function Yp({onPick:t,onCancel:n}){let{t:r}=J();return i(lt,{open:!0,onClose:n,title:r(`system.notificationRules.chooseARuleType`,`Choose a rule type`),width:`lg`,children:i(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:ep.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:[i(`span`,{className:`font-medium text-foreground`,children:n.label}),i(`span`,{className:`text-[10px] font-normal text-foreground-subtle`,children:n.hint})]},n.type))})})}var Xp=1e4;function Zp({rule:t,seed:r,targets:a,catalog:c,taxonomy:l,cameras:u,gateable:p,gateableScenes:h,actuatable:_,fleet:v,actions:y,actionsAnswered:b,initialEditTab:x=mn,onEditTabChange:S,onSaved:C,onCancel:w}){let T=N(),{t:E}=J(),D=t!=null&&t.id.length>0,[O]=o(()=>t?di(t):gr(r?.delivery,r?.conditions)),[k,A]=o(O),[j,M]=o(null),[P,ee]=o(D),[te,I]=o(null),[re,ie]=o(x),L=e=>A(t=>({...t,...e})),z=t?qn(t):void 0,ae=d({mutationFn:async()=>{let e=Vn(k,z,c,fe);if(D&&t){let n=Rn(k,c);await T.trpcClient.notificationRules.updateRule.mutate({ruleId:t.id,patch:e,...n.length>0?{clear:n}:{}})}else await T.trpcClient.notificationRules.createRule.mutate({rule:e})},onSuccess:C,onError:e=>M(e instanceof Error?e.message:`Save failed`)}),oe=d({mutationFn:async()=>{let e=Vn(k,z,c,fe);return(await T.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>I(null),onSuccess:e=>I(e),onError:e=>M(e instanceof Error?e.message:`Test failed`)}),se=k.targetIds.map(e=>a.find(t=>t.id===e)?.name??e),ce=Ms(),ue=Dn(k.targetIds,a,ce),de=e=>ue.get(e)?.shown??!0,fe=ur(a,ce),pe=s({queryKey:[`userManagement`,`listUsers`],queryFn:()=>T.trpcClient.userManagement.listUsers.query()}).data,me=n(()=>(pe??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[pe]),B=Ur(k),he=B===`immediate-grouped`,ge=String(k.groupingSec??20),_e=Cr(k).map(e=>({...e,label:e.value===`immediate-grouped`?E(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?E(`notificationRules.grouping.hint`,{n:ge,defaultValue:`Immediate, grouped — waits up to {{n}} s for subjects to be recognised, then sends one message with a mosaic, one picture per subject. Closes earlier when every subject is final.`}).replaceAll(`{{n}}`,ge):e.hint})),ve=_e.find(e=>e.value===B)?.hint,V=hi(k,z),be=we(k.delivery),Se=le({...k.systemEventDelivery===void 0?{}:{systemEventDelivery:k.systemEventDelivery}}),Ce=be&&Se.schedule!==null&&!jr(k),Te=R(k),Ee=ze(Te),De=Pe(Te),Oe=hr.filter(e=>De.includes(e.value)),ke=qe(k.conditions).length>0,Ae=xe(Te),je=ye(Te),Me=s({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,je??[]],enabled:je!==null,queryFn:async()=>{let e=await Promise.all((je??[]).map(e=>T.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),Ne=n(()=>{if(je===null||Me.data===void 0)return _;let e=Me.data,t=new Set(wr(k.deviceScope));return _.filter(n=>e.has(n.id)||t.has(n.id))},[_,je,Me.data,k.deviceScope]),Fe=je!==null&&Me.isLoading,Le=je!==null&&Me.isError,Re=ls(),Be=e=>({family:`rule`,field:e,kind:Te,delivery:k.delivery,...jr(k)?{systemEventDelivery:`summary`}:{},...k.conditions.systemEvent?{systemEventKinds:[...k.conditions.systemEvent.kinds]}:{}}),Ve=e=>Re.data?as(Re.data,Be(e)):void 0,He=Yr(k),Ue=b?new Set(y.map(e=>e.id)):Nr(k.actions),We=nn(k.conditions,vr(k.actions,y)),Ge=k.conditions.identities!==void 0||k.conditions.plates!==void 0,Ke=Kr(k.delivery,k.conditions),Je=Ke.some(e=>e.key===re)?re:mn;return mi(k.delivery)?i(Xt,{value:Je,onValueChange:e=>{let t=on(e);t!==void 0&&(ie(t),S?.(t))},children:e(lt,{open:!0,onClose:w,title:D?E(`system.notificationRules.edit`,`Edit {{name}}`,{name:t?.name}):E(`system.notificationRules.newNotificationRule`,`New notification rule`),icon:ne,error:j,width:`lg`,testId:`rule-form-dialog`,beforeBody:e(f,{children:[D&&t&&e(`div`,{className:`mb-3 space-y-2`,children:[i(Sl,{kind:`rule`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt}),i(Tl,{ruleId:t.id,cameraName:e=>u.find(t=>t.id===e)?.name??E(`system.notificationRuleStatus.cameraFallback`,{deviceId:e})})]}),i(qt,{className:`mb-3`,children:Ke.map(e=>i($t,{value:e.key,children:e.label},e.key))})]}),footer:e(`div`,{className:`flex w-full flex-col gap-3`,children:[He.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:[i(`p`,{className:`text-foreground`,children:E(`system.notificationRules.savingDrops`,{count:He.length})}),He.map(t=>e(`p`,{children:[i(`span`,{className:`text-foreground`,children:t.conditionId}),` — `,t.reason]},t.conditionId))]}),P&&V.length>0?i(`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:V.map(e=>i(`p`,{children:e},e))}):null,i(`div`,{className:`flex justify-end gap-2`,children:e(K,{size:`sm`,type:`button`,disabled:ae.isPending,onClick:()=>{ee(!0),M(null),!(!Xn(k,z,Ue)||ae.isPending)&&ae.mutate()},children:[ae.isPending&&i(g,{className:`h-3.5 w-3.5 animate-spin`}),D?E(`system.notificationRules.saveChanges`,`Save changes`):E(`system.notificationRules.createRule`,`Create rule`)]})})]}),children:[e(H,{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:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.name`,`Name`)}),i(U,{value:k.name,onChange:e=>L({name:e.target.value}),placeholder:E(`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:[i(W,{checked:k.enabled,onCheckedChange:e=>L({enabled:e}),"aria-label":E(`system.notificationRules.enabled`,`Enabled`)}),E(`system.notificationRules.enabled`,`Enabled`)]})]}),e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.trigger`,`Trigger`)}),i(F,{value:B,onChange:e=>{let t=Br(e.target.value);t&&A(e=>ui(e,t))},options:_e.map(e=>({value:e.value,label:e.label}))}),ve&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:ve}),he&&e(`div`,{className:`mt-2`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),i(U,{type:`number`,min:5,max:60,step:1,value:ge,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=Lr(e.target.value);t!==void 0&&L({groupingSec:t})}}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),Ge&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`notificationRules.grouping.scopedHint`,{n:ge,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,ge)})]}),e(`div`,{className:`mt-2`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`notificationRules.groupWithin.seconds`,`Group notifications within (s)`)}),i(U,{type:`number`,min:0,max:300,step:1,value:String(k.groupWithinSec),"data-testid":`rule-group-within-sec`,onChange:e=>{let t=Lr(e.target.value);t!==void 0&&L({groupWithinSec:t})}}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`notificationRules.groupWithin.hint`,`0 sends each notification immediately. Two or more in the window become one summary.`)})]}),B===`immediate`&&Ge&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!D&&Ae!==void 0&&i(Nc,{family:Ae,onChange:e=>A(t=>kn(t,e))}),i(Tt,{label:E(`system.notificationRules.deliveryTargets`,`Delivery targets`),targets:a,value:k.targetIds,onChange:e=>A(t=>({...t,targetIds:e})),emptyMessage:E(`system.notificationRules.noDeliveryTargetsConfiguredAdd`,`No delivery targets configured. Add one under the Targets tab first.`),testIdPrefix:`rule-target`}),i(ks,{targetIds:k.targetIds,targets:a,kinds:ce,overrides:k.targetOverrides,targetParams:k.targetParams,rulePriority:k.priority,onOverridesChange:e=>L({targetOverrides:e}),onTargetParamsChange:e=>L({targetParams:e}),varsFor:Ve}),i(Gt,{mode:`multi`,options:me,value:k.targetUsers,onChange:e=>L({targetUsers:e}),searchable:!0,creatable:!1,label:E(`system.notificationRules.notifyUsers`,`Notify users`),description:E(`system.notificationRules.deliversToTheTargetsEach`,`Delivers to the targets each user owns, only for cameras that user can access.`),emptyMessage:E(`system.notificationRules.noUsersToNotify`,`No users to notify.`),placeholder:E(`system.notificationRules.searchUsers`,`Search users…`),testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),e(H,{value:`devices`,className:`space-y-4`,children:[Fe&&i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:E(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Le&&i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:E(`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.`)}),i(lc,{devices:Ne,scope:k.deviceScope,onChange:e=>L({deviceScope:e}),listState:v.state,savedScope:O.deviceScope,exceptOffered:ti(c,`devicesExclude`,k)})]}),i(H,{value:`actions`,className:`space-y-4`,children:i(Cs,{value:k.actions,onChange:e=>L({actions:e}),actions:y,showProblems:P})}),e(H,{value:`advanced`,className:`space-y-4`,children:[i(Yc,{catalog:c,delivery:k.delivery,conditions:k.conditions,onConditionsChange:e=>L({conditions:e})}),e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.cooldownSeconds`,`Cooldown (seconds)`)}),i(U,{type:`number`,min:0,max:An,step:1,value:String(k.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=Pr(e.target.value);t!==void 0&&L({cooldownSec:t})}}),e(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[be?E(`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.`):E(`system.notificationRules.theShortestGapBetweenTwo`,`The shortest gap between two deliveries of this rule, counted as chosen below.`),` `,E(`system.notificationRules.cooldownRange`,{max:String(An)})]})]}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.cooldownCounted`,`Cooldown counted`)}),i(F,{value:k.cooldownScope,onChange:e=>{let t=$r(e.target.value);t!==void 0&&L({cooldownScope:t})},options:ci.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`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:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.acrossObjectClasses`,`Across object classes`)}),i(F,{value:k.cooldownGranularity??`per-class`,onChange:e=>L({cooldownGranularity:oi(e.target.value)}),options:xn.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`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:[i(W,{checked:k.snoozeAllowGlobal,onCheckedChange:e=>L({snoozeAllowGlobal:e}),"aria-label":E(`system.notificationRules.allowGlobalSnooze`,`allow global snooze`),disabled:We}),E(`system.notificationRules.anyoneMaySnoozeThisRule`,`Anyone may snooze this rule for everyone`)]}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`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.`)})]}),ri(k)&&e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(W,{checked:k.askVerdict===!0,onCheckedChange:e=>L({askVerdict:e}),"aria-label":E(`system.notificationRules.askVerdictAria`,`ask me to confirm detections`),"data-testid":`rule-ask-verdict`}),E(`system.notificationRules.askVerdict`,`Ask me to confirm detections`)]}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`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.`)})]}),!We&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.snoozeButtons`,`Snooze buttons`)}),e(f,{children:[i(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Mn.map(e=>{let t=k.snoozeOptions??Sn,n=t.includes(e);return i(K,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>L({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Hr(e)},e)})}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:k.snoozeOptions===void 0?E(`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:Sn.map(Hr).join(`, `)}):k.snoozeOptions.length===0?E(`system.notificationRules.noSnoozeButtonsOnThis`,`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`):E(`system.notificationRules.fourAtMostEverySnooze`,`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`)}),k.snoozeOptions!==void 0&&i(K,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>L({snoozeOptions:void 0}),children:E(`system.notificationRules.backToTheDefaults`,`Back to the defaults`)})]})]}),D&&t&&!We&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.silenceItNow`,`Silence it now`)}),i(il,{ruleId:t.id,ruleName:t.name,exempt:We,variant:`full`})]})]}),e(H,{value:`notification`,className:`space-y-4`,children:[e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[de(`priority`)&&e(`div`,{"data-testid":`rule-priority`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.priority`,`Priority`)}),i(F,{value:String(k.priority),onChange:e=>L({priority:Number(e.target.value)}),options:Jn.map(e=>({value:String(e.value),label:e.label}))}),i(js,{support:ue.get(`priority`)})]}),!Ee.carriesMedia&&i(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:Ee.mediaBlurb??E(`system.notificationRules.aSystemEventCarriesNo`,`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`)}),Ee.carriesMedia&&!de(`attachments`)&&i(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-undeliverable`,children:E(`system.notificationRules.targetSettings.noTargetShowsMedia`,`None of the selected targets can show a picture or a clip, so this rule sends none.`)}),Ee.carriesMedia&&de(`attachments`)&&Ee.mediaBlurb!==void 0&&i(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:Ee.mediaBlurb}),Ee.carriesMedia&&de(`attachments`)&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.notificationImage`,`Image`)}),i(js,{support:ue.get(`attachments`)}),i(F,{value:k.mediaImage,onChange:e=>{let t=bi(e.target.value);t&&L({mediaImage:t})},options:Oe.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-image`}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Oe.find(e=>e.value===k.mediaImage)?.description}),e(`div`,{className:`mt-2 space-y-1`,children:[ke&&k.mediaImage!==`crop`&&k.mediaImage!==`none`&&e(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(m,{checked:k.mediaShowTriggerZone,onChange:e=>L({mediaShowTriggerZone:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-trigger-zone`}),e(`span`,{children:[E(`system.notificationRules.showTriggerZone`,`Draw the zone that triggered the rule`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.showTriggerZoneHelp`,`Outlines the zone on the scene. Not drawn on a subject crop.`)})]})]}),Ie(Te)&&k.mediaImage!==`none`&&e(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(m,{checked:k.mediaShowSubjectPath,onChange:e=>L({mediaShowSubjectPath:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-subject-path`}),e(`span`,{children:[E(`system.notificationRules.showSubjectPath`,`Show the subject's path`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:E(`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:[i(m,{checked:k.mediaGif,onChange:e=>L({mediaGif:e.target.checked}),className:`accent-primary`}),E(`system.notificationRules.attachAGifAroundThe`,`Attach a GIF around the event`)]}),e(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[i(m,{checked:k.mediaClip,onChange:e=>L({mediaClip:e.target.checked}),className:`accent-primary`}),E(`system.notificationRules.attachAnMp4ClipAround`,`Attach an MP4 clip around the event`)]})]}),(k.mediaGif||k.mediaClip)&&e(`div`,{className:`mt-2`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.videoQuality`,`Video quality`)}),i(F,{value:k.mediaProfile??``,onChange:e=>L({mediaProfile:vi(e.target.value)}),options:sr.map(e=>({value:e.value,label:e.label}))}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`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.`)}),i(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.playbackSpeed`,`Playback speed`)}),i(F,{value:k.mediaClipSpeed===void 0?``:String(k.mediaClipSpeed),onChange:e=>L({mediaClipSpeed:Ar(e.target.value)}),options:dr.map(e=>({value:e.value,label:e.label}))}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`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.`)})]})]}),Te===`sensor`&&Ee.carriesMedia&&k.mediaImage!==`none`&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.linkedCameras`,`Linked cameras`)}),i(F,{value:k.mediaLinkedCameras??``,onChange:e=>L({mediaLinkedCameras:br(e.target.value)}),options:pr.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`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(`label`,{className:`mt-2 flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(m,{checked:k.mediaWakeSleepingCamera!==!1,onChange:e=>L({mediaWakeSleepingCamera:e.target.checked?void 0:!1}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-wake-sleeping-camera`}),e(`span`,{children:[E(`system.notificationRules.wakeSleepingCamera`,`Wake a sleeping battery camera for the picture`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.wakeSleepingCameraHelp`,`Costs battery and waits up to 15 s before the notification is sent.`)})]})]})]})]}),e(`div`,{className:`space-y-2`,children:[de(`title`)&&e(f,{children:[i(ps,{label:E(`system.notificationRules.notificationTitle`,`Notification title`),value:k.templateTitle,onChange:e=>L({templateTitle:e}),vars:Ve(`title`),testId:`rule-template-title`}),i(js,{support:ue.get(`title`)})]}),de(`body`)&&e(f,{children:[i(ps,{label:E(`system.notificationRules.notificationBody`,`Notification body`),value:k.templateBody,onChange:e=>L({templateBody:e}),vars:Ve(`body`),multiline:!0,testId:`rule-template-body`}),i(js,{support:ue.get(`body`)})]}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.leaveBothBlankForThe`,`Leave both blank for the hub's own wording (editable on the Texts tab).`)}),Sr(k)!==null&&i(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:Sr(k)}),i(ms,{context:Be(`body`),title:k.templateTitle,body:k.templateBody,testId:`rule-template-preview`})]}),be&&i(Fp,{value:k.systemEventDelivery,family:Ae,kinds:k.conditions.systemEvent?.kinds??[],onChange:e=>L({systemEventDelivery:e}),draft:()=>Vn(k,z,c,fe)})]}),e(H,{value:`conditions`,className:`space-y-4`,children:[e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:be?E(`system.notificationRules.whichSystemEvents`,`Which system events`):Wn(k.conditions)??E(`system.notificationRules.conditions`,`Conditions`)}),k.conditions.audio!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:E(`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).`)}),k.conditions.occupancy!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:E(`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.`)}),be&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:E(`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?i(`p`,{className:`text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.conditionCatalogUnavailableThisRule`,`Condition catalog unavailable — this rule matches on its trigger and targets alone.`)}):i(Pc,{catalog:jr(k)?c.filter(e=>e.id!==`schedule`):c,taxonomy:l,delivery:k.delivery,conditions:k.conditions,classScope:k.classScope,onClassScopeChange:e=>L({classScope:e}),actions:_i(k.actions),actionStepsOf:e=>y.find(t=>t.id===e)?.steps,savedConditions:O.conditions,schedule:k.schedule,deviceIds:mr(k),zoneCameraIds:Zs(k.deviceScope,u),cameras:u,fleet:v,allDevices:_,gateable:p,gateableScenes:h,onConditionsChange:e=>L({conditions:e}),onScheduleChange:e=>L({schedule:e}),scheduleOnly:jr(k)})]}),D&&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:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:E(`system.notificationRules.testThisRuleForReal`,`Test this rule for real`)}),i(Fl,{ruleId:t.id,ruleName:t.name,variant:`full`,showResult:!0,...mr(k)[0]===void 0?{}:{fallbackDeviceId:mr(k)[0]}})]}),Ce&&e(`div`,{className:`mt-2 flex items-center justify-between gap-2`,children:[i(`span`,{className:`text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.sendSummaryHint`,`The scheduled summary is sent on its own: to every target, now.`)}),i(Fl,{ruleId:t.id,ruleName:t.name,variant:`full`,showResult:!0,summary:!0})]}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`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.`)})]}),!be&&e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:E(`system.notificationRules.testRule`,`Test rule`)}),e(K,{size:`sm`,variant:`outline`,type:`button`,disabled:oe.isPending||!Xn(k,z,Ue),onClick:()=>{M(null),oe.mutate()},children:[oe.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(at,{className:`h-3.5 w-3.5`}),E(`system.notificationRules.dryRunLast60Min`,`Dry-run (last 60 min)`)]})]}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.evaluateTheCurrentUnsavedRule`,`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`)}),te!==null&&i($p,{delivery:k.delivery,results:te,targetNames:se})]})]})]})}):i(Qp,{rule:t,onCancel:w})}function Qp({rule:t,onCancel:n}){let{t:r}=J(),a=Object.keys(t?.conditions??{});return e(lt,{open:!0,onClose:n,title:t?.name??r(`system.notificationRules.rule`,`Rule`),icon:ne,width:`lg`,children:[i(G,{variant:`warning`,className:`mb-3`,children:`read-only`}),i(`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:i(jn,{i18nKey:`system.notificationRules.unsupportedTrigger`,values:{trigger:t?.delivery},components:{code:i(`code`,{})}})}),e(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.trigger`,`Trigger`)}),i(`dd`,{className:`text-foreground`,children:t?.delivery})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.enabled`,`Enabled`)}),i(`dd`,{className:`text-foreground`,children:t?.enabled?r(`common.yes`):r(`common.no`)})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.targets`,`Targets`)}),i(`dd`,{className:`text-foreground`,children:t?.targets.length??0})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.conditions`,`Conditions`)}),i(`dd`,{className:`text-foreground`,children:a.length>0?a.join(`, `):r(`common.none`)})]})]})]})}function $p({delivery:t,results:n,targetNames:r}){let{t:a}=J();if(t===`device-event`)return i(`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 i(`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:[i(`div`,{className:`text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.wouldFire`,{firing:o,count:n.length})}),i(`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?i(y,{className:`h-3.5 w-3.5 shrink-0 text-success`}):i(S,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`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]}),i(`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:[`→ `,r.join(`, `)||a(`system.notificationRules.targetsFallback`)]}):t.failedCondition&&e(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,t.failedCondition]})]},t.recordId))})]})}var em=`alert-center`,tm=`alerts`;function nm(){let{t}=J(),n=N();return e(`div`,{className:`space-y-3`,"data-testid":`notification-settings`,children:[i(`p`,{className:ie,children:t(`systemPage.notifications.settingsHint`,`Alert storage and retention. Alerts are notified only through notification rules on the alert kinds.`)}),i(Ct,{trpc:n.trpcClient,addonId:em,cap:tm,scope:`cluster`,bare:!0})]})}var rm=[{value:`object-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.objectLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.objectHint`)}},{value:`track-end`,get label(){return q.t(`helpers.notificationSimulateHelpers.trackEndLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.trackEndHint`)}},{value:`device-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.deviceEventLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.deviceEventHint`)}},{value:`package-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.packageEventLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.packageEventHint`)}},{value:`audio-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.audioEventLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.audioEventHint`)}},{value:`occupancy-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.occupancyEdgeLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.occupancyEdgeHint`)}}];function im(e){return rm.find(t=>t.value===e)?.value}function am(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function om(e){return``}var sm={x:.25,y:.25,w:.5,h:.5},cm={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function lm(){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:sm,occupancy:cm,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function um(e){return e.deviceId!==null}function dm(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function fm(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function pm(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 mm(e){if(e.deviceId===null)return null;let t=e.trigger,n=fm(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:hm(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 hm(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 gm(e){return Math.min(1,Math.round((e+.05)*100)/100)}function _m(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 vm(e){let t=lm(),n=e.conditions,r=_m(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:gm(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:gm(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:gm(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:om(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:ym(n.occupancy)},onlyRuleId:e.id}}function ym(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 bm(e){let t=[];return e.conditions.deviceState!==void 0&&t.push({conditionId:`deviceState`,note:q.t(`helpers.notificationSimulateHelpers.caveatDevice`,{deviceId:e.conditions.deviceState.deviceId})}),e.conditions.scene!==void 0&&t.push({conditionId:`scene`,note:q.t(`helpers.notificationSimulateHelpers.caveatScene`,{state:e.conditions.scene.requiredState})}),e.conditions.customZones!==void 0&&e.conditions.customZones.length>0&&t.push({conditionId:`customZones`,note:q.t(`helpers.notificationSimulateHelpers.caveatZones`)}),t}function xm(e){return{form:vm(e),caveats:bm(e),ruleName:e.name}}var Sm=null;function Cm(e){Sm=e}function wm(){return Sm}function Tm(){Sm=null}var Em=[`n/a`,`clear`,`suppressed`,`bypassed`],Dm=[`live`,`none`,`unavailable`,`unattachable`];function Om(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function km(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Am(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function jm(e){if(!Om(e))return null;let t=km(e,`ruleId`),n=km(e,`ruleName`),r=km(e,`cooldown`),i=Em.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=km(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Am(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:Am(e,`targetIds`)}}function Mm(e){if(!Om(e))return null;let t=km(e,`recordId`),n=km(e,`delivery`),r=km(e,`still`),i=Dm.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=jm(e);t!==null&&o.push(t)}let s=km(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Am(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Nm(e){if(e.droppedBy!==void 0)return q.t(`helpers.notificationSimulateHelpers.dropped`,{reason:e.droppedBy});if(e.candidates===0)return q.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?q.t(`helpers.notificationSimulateHelpers.noneMatched`,{count:e.candidates}):q.t(`helpers.notificationSimulateHelpers.matchedSummary`,{matched:t,candidates:e.candidates,enqueued:n})}var Pm=new Set([`sensor`,`control`,`custom`]);function Fm({form:t,cameras:n,taxonomy:r,kinds:a,kindsLoading:o,onPatch:s}){let{t:c}=J(),l=t.deviceId===null?[]:[t.deviceId],u=me(`classes`,r);if(t.trigger===`device-event`)return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(Im,{form:t,kinds:a,loading:o,onPatch:s})]});if(t.trigger===`audio-event`){let r=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:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),e(`div`,{children:[i(`label`,{className:Y,children:c(`system.notificationSimulateFields.audioClasses`,`Audio classes`)}),i(Di,{options:r,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:[i(`label`,{className:Y,children:c(`system.notificationSimulateFields.zones`,`Zones`)}),i(_n,{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:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(Lm,{form:t,cameras:n,taxonomy:r,onPatch:s})]}):e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),e(`div`,{children:[i(`label`,{className:Y,children:c(`system.notificationSimulateFields.detectedClasses`,`Detected classes`)}),u===null?i(wi,{value:t.classNames,placeholder:c(`system.notificationSimulateFields.classIdPersonCar`,`Class id (person, car…)`),onChange:e=>s({classNames:e})}):i(or,{picker:u,value:t.classNames,onChange:e=>s({classNames:e})})]}),e(`div`,{children:[i(`label`,{className:Y,children:c(`system.notificationSimulateFields.zonesTheSubjectIsIn`,`Zones the subject is in`)}),i(_n,{deviceIds:l,cameras:n,value:t.zones,onChange:e=>s({zones:e})})]}),t.trigger===`package-event`&&e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:c(`system.notificationSimulateFields.packagePhase`,`Package phase`)}),i(F,{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 Im({form:t,kinds:n,loading:r,onPatch:a}){let{t:o}=J(),s=n.filter(e=>Pm.has(e.category)),c=s.find(e=>e.kind===t.sensorKind);return e(f,{children:[e(`div`,{children:[i(`label`,{className:Y,children:o(`system.notificationSimulateFields.eventKind`,`Event kind`)}),i(F,{value:t.sensorKind,options:[{value:``,label:r?o(`system.notificationSimulateFields.loadingKinds`,`Loading kinds…`):o(`system.notificationSimulateFields.pickAKind`,`— pick a kind —`)},...s.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=s.find(t=>t.kind===e.target.value);a({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!r&&s.length===0&&i(`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:[i(`label`,{className:Y,children:o(`system.notificationSimulateFields.sourceDevice`,`Source device`)}),i(U,{type:`number`,value:t.sourceDeviceId===null?``:String(t.sourceDeviceId),placeholder:o(`system.notificationSimulateFields.theCameraItself`,`the camera itself`),onChange:e=>a({sourceDeviceId:dm(e.target.value)??null})}),i(`p`,{className:xi,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:[i(`label`,{className:Y,children:o(`system.notificationSimulateFields.eventTypeToken`,`Event type token`)}),i(U,{value:t.eventType,placeholder:o(`system.notificationSimulateFields.pressPressLong`,`press, press_long…`),onChange:e=>a({eventType:e.target.value})}),i(`p`,{className:xi,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 Lm({form:t,cameras:n,taxonomy:r,onPatch:a}){let{t:o}=J(),s=t.deviceId===null?[]:[t.deviceId],c=me(`occupancy`,r),l=c===null?[]:c.groups.flatMap(e=>e.options),u=t.occupancy,d=e=>a({occupancy:{...u,...e}});return e(f,{children:[e(`div`,{children:[i(`label`,{className:Y,children:o(`system.notificationSimulateFields.zone`,`Zone`)}),i(_n,{deviceIds:s,cameras:n,value:u.zoneId===``?[]:[u.zoneId],onChange:e=>d({zoneId:e[e.length-1]??``})}),i(`p`,{className:xi,children:o(`system.notificationSimulateFields.leaveEmptyForTheWhole`,`Leave empty for the whole frame.`)})]}),e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:Y,children:o(`system.notificationSimulateFields.class`,`Class`)}),i(F,{value:u.className,options:[{value:``,label:o(`system.notificationSimulateFields.anyClass`,`— any class —`)},...l.map(e=>({value:e.value,label:e.label}))],onChange:e=>d({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`),i(U,{type:`number`,min:0,className:`w-20`,value:String(u.count),onChange:e=>d({count:dm(e.target.value)??0})})]}),e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countBefore`,`Count before`),i(U,{type:`number`,min:0,className:`w-20`,value:String(u.previousCount),onChange:e=>d({previousCount:dm(e.target.value)??0})})]}),e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.threshold`,`Threshold`),i(U,{type:`number`,min:1,className:`w-20`,value:String(u.threshold),onChange:e=>d({threshold:dm(e.target.value)??1})})]}),e(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[i(W,{checked:u.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":o(`system.notificationSimulateFields.occupiedLabel`)}),o(`system.notificationSimulateFields.occupiedLabel`,`Occupied`)]})]})]})}function Rm({form:t,cameras:n,onPatch:r}){let{t:a}=J(),o=t.deviceId===null?[]:[t.deviceId];return e(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[i(`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:[i(W,{checked:t.crossingEnabled,onCheckedChange:e=>r({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:[i(`div`,{className:`max-w-[12rem]`,children:i(F,{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=>r({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),i(_n,{deviceIds:o,cameras:n,value:t.crossingZoneId===``?[]:[t.crossingZoneId],onChange:e=>r({crossingZoneId:e[e.length-1]??``})})]})]}),e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(W,{checked:t.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":a(`system.notificationSimulateFields.boundingBox`,`bounding box`)}),a(`system.notificationSimulateFields.carryABoundingBox`,`Carry a bounding box`)]}),i(`p`,{className:xi,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&&i(`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,i(U,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(t.bbox[n]),onChange:e=>r({bbox:{...t.bbox,[n]:dm(e.target.value)??0}})})]},n))})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:Y,children:a(`system.notificationSimulateFields.happenedAt`,`Happened at`)}),e(`div`,{className:`flex items-center gap-2`,children:[i(U,{type:`datetime-local`,value:t.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),t.timestampLocal===``?i(K,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:pm(Date.now())}),children:a(`system.notificationSimulateFields.set`,`Set`)}):i(K,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:a(`system.notificationSimulateFields.now`,`Now`)})]}),i(`p`,{className:xi,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:[i(`label`,{className:Y,children:a(`system.notificationSimulateFields.detectionSource`,`Detection source`)}),i(F,{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;r({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function zm({checked:t,label:n,hint:r,danger:a=!1,onChange:o}){let{t:s}=J();return e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(W,{checked:t,onCheckedChange:o,"aria-label":n}),n,a&&i(G,{variant:`danger`,children:s(`system.notificationSimulateFields.actuatesDevices`,`actuates devices`)})]}),i(`p`,{className:xi,children:r})]})}c();var Bm={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.`},Vm={"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 Hm({result:t,targetName:n}){let{t:r}=J();return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[i(`p`,{className:`text-xs font-medium text-foreground`,children:Nm(t)}),e(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[i(Um,{recordId:t.recordId}),i(`span`,{children:i(jn,{i18nKey:`system.notificationSimulateResult.delivery`,values:{value:t.delivery},components:{b:i(`span`,{className:`text-foreground`})}})}),i(`span`,{children:i(jn,{i18nKey:`system.notificationSimulateResult.candidates`,values:{value:t.candidates},components:{b:i(`span`,{className:`text-foreground`})}})}),i(`span`,{title:Bm[t.still],children:i(jn,{i18nKey:`system.notificationSimulateResult.still`,values:{value:t.still},components:{b:i(`span`,{className:`text-foreground`})}})}),t.droppedBy!==void 0&&i(G,{variant:`warning`,children:r(`system.notificationSimulateResult.droppedBy`,{by:t.droppedBy})})]}),t.notes.length>0&&i(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:t.notes.map(e=>i(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),t.outcomes.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:i(jn,{i18nKey:`system.notificationSimulateResult.noRuleEvaluated`,values:{delivery:t.delivery},components:{b:i(`span`,{className:`text-foreground`})}})}):i(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.outcomes.map(e=>i(Wm,{outcome:e,targetName:n},e.ruleId))})]})}function Um({recordId:t}){let{t:n}=J(),[r,a]=o(!1);return e(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[i(`code`,{className:`text-[10px] text-foreground`,children:t}),i(K,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let e=navigator.clipboard;e!==void 0&&e.writeText(t).then(()=>{a(!0),setTimeout(()=>a(!1),1500)},()=>a(!1))},title:n(`system.notificationSimulateResult.copyRecordId`,`Copy record id`),children:i(M,{className:`h-3 w-3`})}),r&&i(`span`,{className:`text-[10px] text-success`,children:n(`common.copiedLower`)})]})}function Wm({outcome:t,targetName:n}){let{t:r}=J();return e(`li`,{className:`space-y-1 px-2.5 py-2`,children:[e(`div`,{className:`flex items-center gap-2`,children:[t.matched?i(y,{className:`h-3.5 w-3.5 shrink-0 text-success`}):i(S,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`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:Vm[t.cooldown],children:[`cooldown: `,t.cooldown]})]}),!t.matched&&i(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:t.failedCondition===void 0?r(`system.notificationSimulateResult.didNotMatchTheEngine`,`Did not match. The engine reported no failing condition id.`):i(jn,{i18nKey:`system.notificationSimulateResult.failingCondition`,values:{condition:t.failedCondition},components:{code:i(`code`,{className:`text-foreground`})}})}),t.matched&&e(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[r(`system.notificationSimulateResult.enqueued`,{count:t.enqueued}),t.targetIds.length>0?` → ${t.targetIds.map(n).join(`, `)}`:` — ${r(`system.notificationSimulateResult.noTargetResolved`)}`,`.`]}),t.matchedOn!==void 0&&t.matchedOn.length>0&&i(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:r(`system.notificationSimulateResult.matchedOn`,{on:t.matchedOn.join(`, `)})})]})}c();var Gm=`pipeline-analytics`,Km=`nc.injectTestEvent`;function qm(){let{t}=J(),r=N(),[c,l]=o(()=>wm()?.form??lm()),[u,f]=o(()=>wm()?.caveats??[]),[p,m]=o(()=>wm()?.ruleName??null);a(()=>Tm(),[]);let[h,_]=o(null),[y,b]=o(!1),[x,S]=o(null),C=e=>l(t=>({...t,...e})),w=Ot({projection:`slim`}),T=s({queryKey:Gp,queryFn:()=>r.trpcClient.notificationRules.getConditionCatalog.query({})}),E=s({queryKey:Wp,queryFn:async()=>(await r.trpcClient.notificationRules.listRules.query({})).rules}),D=If(),O=c.deviceId,k=s({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:O}],enabled:O!==null,staleTime:6e4,queryFn:async()=>O===null?[]:(await r.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[O]})).flatMap(e=>[...e.kinds])}),A=n(()=>(w.data??[]).filter(e=>e.type===Ke.Camera).map(e=>({id:e.id,name:e.name})),[w.data]),j=T.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=d({mutationFn:async()=>{let e=mm(c);if(e===null)throw Error(`Pick a camera first.`);return r.trpcClient.addons.custom.mutate({addonId:Gm,action:Km,input:e})},onMutate:()=>{_(null),b(!1),S(null)},onSuccess:e=>{let t=Mm(e);_(t),b(t===null)},onError:e=>S(e instanceof Error?e.message:`The simulation failed.`)}),te=am(c.trigger),ne=E.data?.find(e=>e.id===c.onlyRuleId);return e(Li,{embedded:!0,icon:at,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:[w.isError&&i(pt,{title:t(`system.notificationSimulate.failedToLoadCameras`,`Failed to load cameras`),message:w.error instanceof Error?w.error.message:t(`system.notificationSimulate.unknownError`,`Unknown error`),onRetry:()=>void w.refetch()}),p!==null&&i(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:i(jn,{i18nKey:`system.notificationSimulate.seededFrom`,values:{rule:p},components:{b:i(`span`,{className:`font-medium`})}})}),u.length>0&&i(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:u.map(t=>e(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[i(v,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),i(`span`,{children:t.note})]},t.conditionId))}),e(Zt,{className:`space-y-4`,children:[e(`div`,{children:[i(`label`,{className:Y,children:t(`system.notificationSimulate.ruleToSimulate`,`Rule to simulate`)}),i(F,{"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(lm()),f([]),m(null);return}let n=E.data?.find(e=>e.id===t);if(n===void 0){C({onlyRuleId:t});return}l(vm(n)),f(bm(n)),m(n.name)}}),i(`p`,{className:xi,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:[i(`label`,{className:Y,children:t(`system.notificationSimulate.camera`,`Camera`)}),i(F,{"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=>{C({deviceId:dm(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...c.occupancy,zoneId:``}})}}),i(`p`,{className:xi,children:t(`system.notificationSimulate.theCameraTheEventIs`,`The camera the event is attributed to — what a notification shows.`)})]}),e(`div`,{children:[i(`label`,{className:Y,children:t(`system.notificationSimulate.trigger`,`Trigger`)}),i(F,{"data-testid":`simulate-trigger`,value:c.trigger,options:rm.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=im(e.target.value);if(!t)return;let n=om(c.trigger);C({trigger:t,source:c.source===``||c.source===n?om(t):c.source})}}),e(`p`,{className:xi,children:[rm.find(e=>e.value===c.trigger)?.hint,` `,i(jn,{i18nKey:`system.notificationSimulate.onlyRulesWhoseTrigger`,values:{delivery:te},components:{b:i(`span`,{className:`text-foreground`})}})]})]}),i(Fm,{form:c,cameras:A,taxonomy:j,kinds:M,kindsLoading:k.isLoading,onPatch:C}),e(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[i(`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:[i(`p`,{className:xi,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:[i(`label`,{className:Y,children:t(`system.notificationSimulate.labelIdentityNamePlateSubclass`,`Label (identity name / plate / subclass)`)}),i(U,{value:c.label,placeholder:t(`system.notificationSimulate.eGMarcoAb123cd`,`e.g. Marco, AB123CD`),onChange:e=>C({label:e.target.value})})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:Y,children:t(`system.notificationSimulate.detectionConfidence`,`Detection confidence`)}),i(Er,{value:c.confidence,min:0,max:1,step:.05,onChange:e=>C({confidence:e})})]}),e(`div`,{children:[i(`label`,{className:Y,children:t(`system.notificationSimulate.labelMatchConfidence`,`Label-match confidence`)}),i(Er,{value:c.labelConfidence,min:0,max:1,step:.05,onChange:e=>C({labelConfidence:e})})]}),e(`div`,{children:[i(`label`,{className:Y,children:t(`system.notificationSimulate.importance`,`Importance`)}),i(Er,{value:c.importance,min:0,max:1,step:.05,onChange:e=>C({importance:e})})]}),e(`div`,{children:[i(`label`,{className:Y,children:t(`system.notificationSimulate.dwellSeconds`,`Dwell (seconds)`)}),i(Er,{value:c.dwellSeconds,min:0,step:1,onChange:e=>C({dwellSeconds:e})})]})]})]})]}),i(Rm,{form:c,cameras:A,onPatch:C}),e(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:t(`system.notificationSimulate.howToRunIt`,`How to run it`)}),i(zm,{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=>C({bypassCooldown:e})}),i(zm,{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=>C({bypassMute:e})}),i(zm,{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=>C({runActions:e})}),e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:Y,children:t(`system.notificationSimulate.stillImage`,`Still image`)}),i(F,{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=>C({still:e.target.value===`none`?`none`:`live`})})]}),e(`div`,{children:[i(`label`,{className:Y,children:t(`system.notificationSimulate.evaluateOnlyOneRule`,`Evaluate only one rule`)}),i(F,{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=>C({onlyRuleId:e.target.value})}),c.onlyRuleId.length>0&&ne===void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:i(jn,{i18nKey:`system.notificationSimulate.ruleNotInList`,values:{id:c.onlyRuleId},components:{code:i(`code`,{})}})})]})]}),x!==null&&i(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:x}),e(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[i(`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(K,{size:`sm`,type:`button`,disabled:ee.isPending||!um(c),onClick:()=>ee.mutate(),children:[ee.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(at,{className:`h-3.5 w-3.5`}),t(`system.notificationSimulate.injectEvent`,`Inject event`)]})]})]}),y&&i(`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&&i(Hm,{result:h,targetName:e=>P.get(e)??e})]})}var Jm=e=>typeof e==`string`&&e.length>0;function Ym(e){return{levels:e.levels,formats:e.format,bodyMaxLen:e.bodyMaxLen,attachmentSlots:e.attachments.mediaTypes,attachmentMode:e.attachments.mode,attachmentMax:e.attachments.max,attachmentMaxBytes:e.attachments.maxBytes,maxActions:e.actions,showActions:e.actions>0,showClickUrl:e.clickUrl,showSound:e.sound,showTtl:e.ttl,showTag:!0}}function Xm(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Zm(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Jm(i)&&n.push({mediaType:r,url:i})}return n}function Qm(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Jm(r.label),i=Jm(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:q.t(`helpers.notificationTestComposer.actionN`,{n:n.length+1}),...i?{url:r.url}:{}})}return n}function $m(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Zm(e,t.attachmentUrls),i=Qm(e,t.actions),a=e.ttl&&Jm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:Xm(e,t.format),priority:eh(t.priority),...Jm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Jm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Jm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Jm(t.tag)?{tag:t.tag}:{}}}function eh(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function th(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 nh(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var rh={image:C(`/addon/notifiers/samples/image`),video:C(`/addon/notifiers/samples/video`),gif:C(`/addon/notifiers/samples/gif`),audio:C(`/addon/notifiers/samples/audio`),icon:C(`/addon/notifiers/samples/icon`)};function ih(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function ah(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])ih(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function oh(e,t,n){let r=nh(e);return ih(e,t)?{...r,body:n,attachmentUrls:{[t]:rh[t]}}:{...r,body:n}}function sh(e,t){let n=nh(e);switch(t){case`text`:return{...n,title:`CamStack`,body:q.t(`helpers.notificationTestComposer.presetText`)};case`image`:return oh(e,`image`,q.t(`helpers.notificationTestComposer.presetImage`));case`gif`:return oh(e,`gif`,q.t(`helpers.notificationTestComposer.presetGif`));case`video`:return oh(e,`video`,q.t(`helpers.notificationTestComposer.presetVideo`));case`audio`:return oh(e,`audio`,q.t(`helpers.notificationTestComposer.presetAudio`));case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:q.t(`helpers.notificationTestComposer.actionN`,{n:t+1}),url:`/`}));return{...n,title:`CamStack`,body:q.t(`helpers.notificationTestComposer.presetActions`),actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=th(e);return{...n,title:`CamStack`,body:q.t(`helpers.notificationTestComposer.presetCritical`),priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}c();var ch={get text(){return q.t(`system.notificationTestPanel.presetText`)},get image(){return q.t(`system.notificationTestPanel.presetImage`)},get gif(){return q.t(`system.notificationTestPanel.presetGif`)},get video(){return q.t(`system.notificationTestPanel.presetVideo`)},get audio(){return q.t(`system.notificationTestPanel.presetAudio`)},get actions(){return q.t(`system.notificationTestPanel.presetActions`)},get critical(){return q.t(`system.notificationTestPanel.presetCritical`)},get overflow(){return q.t(`system.notificationTestPanel.presetOverflow`)}},lh=`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`,uh=`block text-[11px] font-medium text-foreground mb-1`;function dh({target:t,kind:r,open:a,onClose:s}){let{t:c}=J(),l=N(),u=n(()=>Ym(r.caps),[r.caps]),f=n(()=>ah(r.caps),[r.caps]),[p,m]=o(()=>nh(r.caps)),[h,_]=o(null),v=n(()=>$m(r.caps,p),[r.caps,p]),y=p.body.length,b=y>u.bodyMaxLen,S=e=>m(t=>({...t,...e})),C=d({mutationFn:()=>l.trpcClient.notificationOutput.testTarget.mutate({addonId:t.addonId,targetId:t.id,sample:$m(r.caps,p)}),onMutate:()=>_(null),onSuccess:e=>_(e),onError:e=>_({success:!1,error:e instanceof Error?e.message:q.t(`system.notificationTestPanel.testFailed`)})}),w=e=>{m(sh(r.caps,e)),_(null)},T=(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},S({actions:r})};return i(At,{open:a,onOpenChange:e=>!e&&s(),children:e(bt,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[i(Pt,{children:i(Mt,{children:c(`system.notificationTestPanel.testTitle`,{name:t.name,kind:r.label})})}),e(ht,{className:`space-y-4 pr-1`,children:[i(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map(e=>i(K,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>w(e),children:ch[e]},e))}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[u.levels.length>0&&e(`div`,{children:[i(`label`,{className:uh,children:c(`system.notificationTestPanel.level`,`Level`)}),e(F,{wrapperClassName:`inline-block w-auto`,className:lh,value:p.level,onChange:e=>S({level:e.target.value}),children:[i(`option`,{value:``,children:c(`system.notificationTestPanel.deriveFromPriority`,`— derive from priority —`)}),u.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=u.levels.find(e=>e.id===p.level);return t?e(`div`,{className:`mt-1 space-y-1`,children:[t.description&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:t.description}),e(`div`,{className:`flex flex-wrap gap-1`,children:[t.flags?.critical&&i(G,{variant:`danger`,"data-testid":`flag-critical`,children:c(`system.notificationTestPanel.critical`)}),t.flags?.silent&&i(G,{variant:`info`,children:c(`system.notificationTestPanel.silent`)}),t.flags?.noPush&&i(G,{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:uh,children:[c(`system.notificationTestPanel.priorityOrdinal`,`Priority (ordinal):`),` `,p.priority]}),i(x,{min:1,max:5,step:1,value:p.priority,onChange:e=>S({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":c(`system.notificationTestPanel.priority`)})]})]}),u.formats.length>0&&e(`div`,{children:[i(`label`,{className:uh,children:c(`system.notificationTestPanel.format`,`Format`)}),i(`div`,{className:`flex flex-wrap gap-2`,children:u.formats.map(t=>e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[i(vt,{name:`format`,className:`accent-primary`,checked:p.format===t,onChange:()=>S({format:t})}),t]},t))})]}),e(`div`,{children:[i(`label`,{className:uh,children:c(`system.notificationTestPanel.testTitle`,`Title`)}),i(U,{className:lh,value:p.title,onChange:e=>S({title:e.target.value})})]}),e(`div`,{children:[e(`label`,{className:uh,children:[c(`system.notificationTestPanel.body`),` `,e(`span`,{className:b?`text-danger`:`text-foreground-subtle`,children:[`(`,y,`/`,u.bodyMaxLen,b?` — ${c(`system.notificationTestPanel.overflow`)}`:``,`)`]})]}),i(It,{className:`${lh} min-h-[80px] resize-y`,value:p.body,onChange:e=>S({body:e.target.value})})]}),u.attachmentSlots.length>0&&e(`div`,{children:[e(`label`,{className:uh,children:[c(`system.notificationTestPanel.attachments`),` `,i(`span`,{className:`text-foreground-subtle`,children:u.attachmentMaxBytes?c(`system.notificationTestPanel.attachmentsMetaMb`,{mode:u.attachmentMode,max:u.attachmentMax,mb:Math.round(u.attachmentMaxBytes/1024/1024)}):c(`system.notificationTestPanel.attachmentsMeta`,{mode:u.attachmentMode,max:u.attachmentMax})})]}),i(`div`,{className:`space-y-1.5`,children:u.attachmentSlots.map(t=>e(`div`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:t}),i(U,{className:lh,placeholder:c(`system.notificationTestPanel.url`,`{{mt}} URL`,{mt:t}),value:p.attachmentUrls[t]??``,onChange:e=>S({attachmentUrls:{...p.attachmentUrls,[t]:e.target.value}})})]},t))})]}),u.showActions&&e(`div`,{children:[i(`label`,{className:uh,children:c(`system.notificationTestPanel.actionsUpTo`,{max:u.maxActions})}),i(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(u.maxActions,3)},(t,n)=>e(`div`,{className:`flex items-center gap-2`,children:[i(U,{className:lh,placeholder:c(`system.notificationTestPanel.actionLabelPlaceholder`),value:p.actions[n]?.label??``,onChange:e=>T(n,`label`,e.target.value)}),i(U,{className:lh,placeholder:c(`system.notificationTestPanel.actionUrlPlaceholder`),value:p.actions[n]?.url??``,onChange:e=>T(n,`url`,e.target.value)})]},n))})]}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[u.showClickUrl&&e(`div`,{children:[i(`label`,{className:uh,children:c(`system.notificationTestPanel.clickUrl`,`Click URL`)}),i(U,{className:lh,value:p.clickUrl,onChange:e=>S({clickUrl:e.target.value})})]}),u.showSound&&e(`div`,{children:[i(`label`,{className:uh,children:c(`system.notificationTestPanel.sound`,`Sound`)}),i(U,{className:lh,value:p.sound,onChange:e=>S({sound:e.target.value})})]}),u.showTtl&&e(`div`,{children:[i(`label`,{className:uh,children:c(`system.notificationTestPanel.ttlSeconds`,`TTL (seconds)`)}),i(U,{className:lh,type:`number`,value:p.ttl,onChange:e=>S({ttl:e.target.value})})]}),u.showTag&&e(`div`,{children:[i(`label`,{className:uh,children:c(`system.notificationTestPanel.tag`,`Tag`)}),i(U,{className:lh,value:p.tag,onChange:e=>S({tag:e.target.value})})]})]}),h&&i(fh,{result:h}),e(`details`,{className:`text-[10px]`,children:[i(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:c(`system.notificationTestPanel.payloadPreview`,`Payload preview`)}),i(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(v,null,2)})]})]}),e(_t,{children:[i(K,{variant:`secondary`,size:`sm`,type:`button`,onClick:s,children:c(`common.close`,`Close`)}),e(K,{size:`sm`,type:`button`,disabled:C.isPending||p.body.length===0,onClick:()=>C.mutate(),children:[C.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(ot,{className:`h-3.5 w-3.5`}),c(`system.notificationTestPanel.sendTest`,`Send test`)]})]})]})})}function fh({result:t}){let{t:n}=J(),r=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?i(y,{className:`h-3.5 w-3.5 text-success`}):i(S,{className:`h-3.5 w-3.5 text-danger`}),i(`span`,{children:t.success?n(`system.notificationTestPanel.delivered`,`Delivered`):n(`system.notificationTestPanel.failed`,`Failed`)})]}),t.error&&i(`p`,{className:`mt-1 text-danger`,children:t.error}),r&&e(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[i(`dt`,{children:n(`system.notificationTestPanel.resolvedLevel`,`Resolved level`)}),i(`dd`,{className:`text-foreground`,children:r.level}),i(`dt`,{children:n(`system.notificationTestPanel.formatSent`,`Format sent`)}),i(`dd`,{className:`text-foreground`,children:r.format}),i(`dt`,{children:n(`system.notificationTestPanel.attachmentsSent`,`Attachments sent`)}),i(`dd`,{className:`text-foreground`,children:r.attachmentsSent}),i(`dt`,{children:n(`system.notificationTestPanel.actionsSent`,`Actions sent`)}),i(`dd`,{className:`text-foreground`,children:r.actionsSent}),i(`dt`,{children:n(`system.notificationTestPanel.truncated`,`Truncated`)}),i(`dd`,{className:`text-foreground`,children:r.truncated?n(`common.yes`):n(`common.no`)}),i(`dt`,{children:n(`system.notificationTestPanel.dropped`,`Dropped`)}),i(`dd`,{className:`text-foreground`,children:r.dropped.length>0?r.dropped.join(`, `):`—`})]})]})}c();var ph=`ownerUserId`,mh=`notification-output`;function hh(e){let t=e.formValues[ph];return typeof t==`string`&&t.length>0?t:null}function gh({row:e}){let{t}=J(),n=N(),r=Ut({functionCap:mh}),a=s({queryKey:[`userManagement`,`listUsers`],queryFn:()=>n.trpcClient.userManagement.listUsers.query()});if(e.kind!==`instance`)return null;let o=(r.data??[]).find(t=>t.id===e.id),c=o===void 0?null:hh(o);if(c===null)return i(G,{variant:`default`,children:t(`common.systemWord`,`system`)});if(a.data===void 0&&!a.isError)return i(gt,{className:`h-3 w-16`});let l=(a.data??[]).find(e=>e.id===c)?.username;return i(`span`,{className:`text-xs text-foreground`,children:l??t(`system.notificationTargets.unknownUser`,`unknown user`)})}function _h(e){return{key:`owner`,header:e,nowrap:!0,notSortableReason:e,render:e=>i(gh,{row:e})}}function vh(){let{t}=J(),n=N(),a=s({queryKey:[`notificationOutput`,`listTargetKinds`],queryFn:()=>n.trpcClient.notificationOutput.listTargetKinds.query({})}),[c,l]=o(null),u=c===null||c.kindId===void 0?void 0:(a.data??[]).find(e=>e.kind===je(c.kindId??``)&&e.addonId===c.addonId),d=r(e=>i(zt,{icon:ot,variant:`ghost`,size:`sm`,"aria-label":t(`system.notificationTargets.testTarget`,`Send a test to {{name}}`,{name:e.name}),onClick:()=>l(e)}),[t]),p=c===null||u===void 0?null:{id:c.id,name:c.name,kind:u.kind,addonId:c.addonId,enabled:c.enabled,config:{}};return e(f,{children:[i(Ki,{functionCap:mh,icon:O,title:t(`system.notificationTargets.notificationTargets`,`Notification Targets`),subtitle:t(`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.`),emptyTitle:t(`system.notificationTargets.emptyTitle`,`No notification targets yet`),emptyDescription:t(`system.notificationTargets.emptyDescription`,`Add a target to deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more.`),addLabel:t(`system.notificationTargets.addTarget`,`Add target`),extraColumns:[_h(t(`system.notificationTargets.owner`,`Owner`))],rowActions:d}),p!==null&&u!==void 0&&i(dh,{target:p,kind:u,open:!0,onClose:()=>l(null)})]})}c();var yh=`notificationTexts`,bh=`Every sentence the Notification Center can print — and your wording for it.`;function xh({entry:t,value:n,busy:r,onChange:a,onReset:o}){let{t:s}=J(),c=yu(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:[i(`code`,{className:`text-xs font-medium`,children:t.key}),l?i(G,{variant:`info`,children:s(`common.customised`)}):null,t.source===`fallback`?i(G,{variant:`warning`,children:s(`system.notificationTexts.englishFallback`,`English fallback`)}):null]}),e(`div`,{className:`flex items-start gap-2`,children:[i(`div`,{className:`flex-1`,children:i(ps,{label:``,value:n,onChange:a,vars:vu(t),deviceValues:!1,disabled:r,testId:`text-input-${t.key}`})}),i(K,{variant:`ghost`,size:`sm`,disabled:r||!l&&n===t.shipped,onClick:o,title:s(`system.notificationTexts.resetToTheShippedWording`,`Reset to the shipped wording`),"data-testid":`text-reset-${t.key}`,children:i(L,{className:`h-3.5 w-3.5`})})]}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[i(`span`,{className:`font-medium`,children:s(`system.notificationTexts.shipped`,`Shipped:`)}),` `,i(`span`,{className:`font-mono`,children:t.shipped})]}),c===null?null:i(`p`,{className:`text-xs text-warning`,children:c})]})}function Sh(){let{t}=J(),r=N(),a=l(),[c,u]=o(null),[f,p]=o(``),[m,h]=o(new Map),[_,v]=o(!1),y=s({queryKey:[yh,c??`hub`],queryFn:async()=>{let e=pu(await r.trpcClient.addons.custom.mutate({addonId:$,action:iu,input:c===null?{}:{language:c}}));return v(e===null),e}}),b=()=>{h(new Map),a.invalidateQueries({queryKey:[yh]})},x=d({mutationFn:e=>r.trpcClient.addons.custom.mutate({addonId:$,action:au,input:{language:e}}),onSuccess:b}),S=d({mutationFn:e=>r.trpcClient.addons.custom.mutate({addonId:$,action:ou,input:e}),onSuccess:b}),C=y.data??null,w=n(()=>C===null?[]:_u(C.entries,f),[C,f]);if(y.isLoading)return i(Li,{embedded:!0,icon:ct,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:bh,children:i(g,{className:`h-5 w-5 animate-spin`})});if(y.isError||C===null)return i(Li,{embedded:!0,icon:ct,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:bh,children:i(pt,{title:t(`system.notificationTexts.theNotificationTextCatalogIs`,`The notification text catalog is not available on this hub`),message:_?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 T=C.language,E=x.isPending||S.isPending,D=hu(C.entries,m),O=gu(C.entries,m),k=C.entries.filter(e=>e.override!==null).length,A=C.languages.map(e=>({value:e,label:su[e]})),j=(e,t)=>h(n=>new Map(n).set(e,t)),M=e=>j(e.key,e.shipped);return i(Li,{embedded:!0,icon:ct,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:bh,children:e(`div`,{className:`flex flex-col gap-4`,children:[x.isError?i(pt,{title:t(`system.notificationTexts.couldNotChangeTheLanguage`,`Could not change the language`),message:String(x.error)}):null,S.isError?i(pt,{title:t(`system.notificationTexts.couldNotSave`,`Could not save`),message:String(S.error)}):null,e(Zt,{className:`p-4`,children:[e(`div`,{className:`flex flex-wrap items-end gap-6`,children:[e(`div`,{className:`flex flex-col gap-1`,children:[i(`label`,{className:`text-sm font-medium`,children:t(`system.notificationTexts.hubLanguage`,`Hub language`)}),i(`div`,{className:`w-44`,children:i(F,{value:C.activeLanguage,disabled:E,options:A,onChange:e=>{let t=e.target.value;cu(t)&&x.mutate(t)},"data-testid":`texts-hub-language`})}),i(`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:[i(`label`,{className:`text-sm font-medium`,children:t(`system.notificationTexts.editing`,`Editing`)}),i(`div`,{className:`w-44`,children:i(F,{value:T,disabled:E,options:A,onChange:e=>{let t=e.target.value;cu(t)&&(h(new Map),u(t))},"data-testid":`texts-editing-language`})}),i(`p`,{className:`text-xs text-foreground-subtle`,children:T===C.activeLanguage?t(`system.notificationTexts.ofTextsCustomised`,`{{overriddenCount}} of {{length}} texts customised.`,{overriddenCount:k,length:C.entries.length}):t(`system.notificationTexts.thisHubDoesNotSpeak`,`This hub does not speak this language — these words are not in use yet.`)})]})]}),i(`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:[i(ee,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),i(U,{searchHotkey:!0,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:[w.length,` of `,C.entries.length]}),e(K,{className:`ml-auto`,disabled:E||O===0,onClick:()=>S.mutate({language:T,overrides:D}),"data-testid":`texts-save`,children:[E?i(g,{className:`h-3.5 w-3.5 animate-spin`}):null,O===0?t(`common.save`,`Save`):t(`system.notificationTexts.save`,`Save {{pending}}`,{pending:O})]})]}),i(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?i(`p`,{className:`text-sm text-foreground-subtle`,children:t(`system.notificationTexts.noTextMatchesThatSearch`,`No text matches that search.`)}):w.map(e=>i(xh,{entry:e,value:mu(e,m),busy:E,onChange:t=>j(e.key,t),onReset:()=>M(e)},e.key))})]})})}c();var Ch=`simulate`,wh=`rules`,Th=[`instance`,`instance-new`],Eh=new Set([wh]);function Dh(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function Oh(t,n,r){if(t===`mixed`)return;if(t===`all`)return e(K,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:n,children:[i(E,{className:`h-3.5 w-3.5`}),q.t(`systemPage.notifications.newRule`,`New rule`)]});if(tp(t)){let n=rp(t),a=Dh(t);return a===null?void 0:e(K,{size:`sm`,type:`button`,onClick:()=>r(a),"data-testid":t===`summaries`?`summary-new`:t===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[i(E,{className:`h-3.5 w-3.5`}),n.newLabel]})}let a=tn.find(e=>e.key===t);if(!(a===void 0||!a.creatable))return e(K,{size:`sm`,type:`button`,onClick:()=>r(t),"data-testid":`rules-new-${t}`,children:[i(E,{className:`h-3.5 w-3.5`}),a.newRuleLabel]})}function kh(){let{t:e}=J(),[t,n]=Yn(),[r,s]=o(!1),[c,l]=o(null);a(()=>{let e=t.get(`tab`);if(e===null||!tp(e))return;let r=new URLSearchParams(t);r.set(`tab`,wh),r.set(`section`,e),n(r,{replace:!0})},[t,n]);let u=t.get(`tab`)??`targets`,[d]=Lt(`section`),f=np(d)??`all`,p=e=>{Cm(xm(e));let r=new URLSearchParams(t);r.set(`tab`,Ch),n(r,{replace:!0})},m=e=>{n(Lo(t,e.id),{replace:!0})},h=Ti(`/system/notifications`,{t:e,isAdmin:!0})??{icon:O,title:e(`system.notifications`,`Notifications`)},g=()=>s(!1),_=(()=>{if(u===wh)return Oh(f,()=>s(!0),e=>l(e))})();return a(()=>{Eh.has(u)||(s(!1),l(null))},[u]),i(Pi,{icon:h.icon,title:h.title,defaultSection:`targets`,sectionsLabel:`${h.title} sections`,actions:_,sections:[{id:`targets`,label:e(`systemPage.notifications.targets`,`Targets`),content:i(vh,{}),ownedParams:Th},{id:wh,label:e(`systemPage.notifications.rules`,`Rules`),content:i(Jp,{onSimulateRule:p,onOpenHistory:m,headerOwnsCreate:!0,createRequested:u===wh&&r,onCreateConsumed:g,createTypeRequested:u===wh?c:null,onCreateTypeConsumed:()=>l(null)}),ownedParams:[`section`,`rule`,`editTab`]},{id:Ch,label:e(`systemPage.notifications.simulate`,`Simulate`),content:i(qm,{})},{id:jo,label:e(`systemPage.notifications.history`,`History`),content:i(Jo,{}),ownedParams:No},{id:`alarm`,label:e(`systemPage.notifications.alarm`,`Alarm`),content:i(Ao,{})},{id:`texts`,label:e(`systemPage.notifications.texts`,`Texts`),content:i(Sh,{})},{id:`settings`,label:e(`systemPage.notifications.settings`,`Settings`),content:i(nm,{})}]})}export{kh as NotificationsPage,kh as default};
|