@camstack/addon-admin-ui 1.2.442 → 1.2.444
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AddonAssetIcon-BccuV0q0.js → AddonAssetIcon-Bu6mMt1C.js} +1 -1
- package/dist/assets/Addons-COIVGqm1.js +4 -0
- package/dist/assets/AdminPage-CQo22qlS.js +1 -0
- package/dist/assets/AdminSectionedPage-B-vU2e0-.js +1 -0
- package/dist/assets/AiProfiles-CU2eppU9.js +3 -0
- package/dist/assets/{BrokerForm-DzQNeSxm.js → BrokerForm-F3TuyGuz.js} +1 -1
- package/dist/assets/Build-kD_UpwAf.js +40 -0
- package/dist/assets/{Calendars-Cla89sbi.js → Calendars-BIK8tWWW.js} +1 -1
- package/dist/assets/Cluster-_ehM-rcf.js +1 -0
- package/dist/assets/ClusterStepModel-_rs8hojC.js +1 -0
- package/dist/assets/CompositionEditor-CAVyLS8E.js +1 -0
- package/dist/assets/{CompositionEditorPage-BgQSiVo8.js → CompositionEditorPage-LHnmpaBG.js} +1 -1
- package/dist/assets/Data-CjKZYFLT.js +2 -0
- package/dist/assets/DeviceDetail-Bg0CFoFt.js +2 -0
- package/dist/assets/{DeviceDoActionFields-BjVWVHu7.js → DeviceDoActionFields-oa5LfgEc.js} +1 -1
- package/dist/assets/{Devices-D9zuTHOW.js → Devices-poYGMM17.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-MXUvBkWX.js → EmbedPlayerPage-DHUkmfpi.js} +1 -1
- package/dist/assets/History-BemofISk.js +1 -0
- package/dist/assets/Identity-i5HDvKSk.js +1 -0
- package/dist/assets/IntegrationDetail-DhTGMtwY.js +1 -0
- package/dist/assets/IntegrationHub-yEjjqm-b.js +1 -0
- package/dist/assets/Integrations-Bx1K8v1_.js +1 -0
- package/dist/assets/Integrations-DM18WhBS.js +1 -0
- package/dist/assets/Library-BlINo2aE.js +1 -0
- package/dist/assets/Locations-ClflpavL.js +3 -0
- package/dist/assets/{Logs-CVR97TYT.js → Logs-DCYNwky1.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-DEZFJVo5.js → MaskShapeCanvas-CLIOU75o.js} +1 -1
- package/dist/assets/{MotionZonesSettings-Bwo-3iRG.js → MotionZonesSettings-CnE1SA-E.js} +1 -1
- package/dist/assets/MyAccess-CfC5QQ3s.js +2 -0
- package/dist/assets/{Network-CNhaeFmn.js → Network-BQ4JNadZ.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-CRyxRlRb.js → NodeAddonsSettingsPanel-Cxa0ELmc.js} +1 -1
- package/dist/assets/Notifications-CZCz5f4V.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-cDl1Qu_T.js → PrivacyMaskSettings-D9OU-0Bn.js} +1 -1
- package/dist/assets/Recordings-D2V7gQg4.js +1 -0
- package/dist/assets/{ScanNetworkModal-C5RUKriq.js → ScanNetworkModal-qXvq-PVn.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-BmaWm_DT.js → SceneMonitorEditor-Z1tONQgv.js} +1 -1
- package/dist/assets/SessionsList-DRTHtQFG.js +2 -0
- package/dist/assets/Showroom-DsWM4R62.js +1 -0
- package/dist/assets/System-BO2ViXLt.js +1 -0
- package/dist/assets/{Terminal-BdKedDZS.js → Terminal-DSlfvSeb.js} +3 -3
- package/dist/assets/{Viewer-LdYt8Q3H.js → Viewer-B9E-i-aL.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DId7Mdzp.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Bxpb3Ns6.js} +1 -1
- package/dist/assets/{addon-icons-context-BNhm5nij.js → addon-icons-context-HpTz6tFr.js} +1 -1
- package/dist/assets/{archive-Dj3rQasM.js → archive-BhX0MX1x.js} +1 -1
- package/dist/assets/{authed-media-CRKmATDJ.js → authed-media-ajJETyPB.js} +1 -1
- package/dist/assets/{bell-off-BxB4ohQe.js → bell-off-2A9pKMoS.js} +1 -1
- package/dist/assets/{board-model-Bx9i2Ikh.js → board-model-BVOHJW-k.js} +1 -1
- package/dist/assets/{boxes-Cyb74Sc2.js → boxes-DKovb6Yx.js} +1 -1
- package/dist/assets/circle-slash-ioY3pbkD.js +1 -0
- package/dist/assets/client-BOc9ypnl.js +358 -0
- package/dist/assets/{cloud-upload-STkEa8On.js → cloud-upload-CsCUf2VU.js} +1 -1
- package/dist/assets/crop-BbAQnCUc.js +1 -0
- package/dist/assets/{device-integration-icon-NmvFHcoT.js → device-integration-icon-CkT2sHMd.js} +1 -1
- package/dist/assets/device-picker-model-CQpRlaca.js +1 -0
- package/dist/assets/{dist-CboU_aT5.js → dist-Cj5HXsk2.js} +1 -1
- package/dist/assets/dist-Dw33BAaG.js +358 -0
- package/dist/assets/{eraser-MfKJ-xHy.js → eraser-CNEtQPIU.js} +1 -1
- package/dist/assets/{hard-drive-download-DNMTqY2h.js → hard-drive-download-CwMKGnle.js} +1 -1
- package/dist/assets/{hostInit-LP6ARUYA.js → hostInit-CDGHjPjp.js} +1 -1
- package/dist/assets/i18n-DzruZdmx.js +1 -0
- package/dist/assets/icons-CDiKrupg.js +1 -0
- package/dist/assets/index-CcCgJ28N.css +2 -0
- package/dist/assets/index-DzDx8M2g.js +4 -0
- package/dist/assets/{key-LDVs0Hda.js → key-BX-E7v5U.js} +1 -1
- package/dist/assets/{key-round-ufq1OhZE.js → key-round-B4PhAHaZ.js} +1 -1
- package/dist/assets/{layers-DMR3HPTk.js → layers-NfjCHzhF.js} +1 -1
- package/dist/assets/{linked-devices-model-BhIH5Kho.js → linked-devices-model-C2Gvr2Rq.js} +1 -1
- package/dist/assets/{list-ordered-iFgP3FdK.js → list-ordered-BU_60EAm.js} +1 -1
- package/dist/assets/{location-owned-usage-ChRB3Z7a.js → location-owned-usage-Dive37hg.js} +1 -1
- package/dist/assets/{log-in-4wTdM9C2.js → log-in-R8rfmtnj.js} +1 -1
- package/dist/assets/{memory-stick-BVZbZTDE.js → memory-stick-C-FtHTf2.js} +1 -1
- package/dist/assets/{message-square-plus-DTEXt10L.js → message-square-plus-CTNIdqDb.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-6f3bb22b.js → mf-entry-bootstrap-0-adac5fea.js} +2 -2
- package/dist/assets/{mic-off-BOvuLxyG.js → mic-off-DbMF1Y3I.js} +1 -1
- package/dist/assets/{monitor-off-BJJUHiNu.js → monitor-off-CKeLNGdf.js} +1 -1
- package/dist/assets/{monitor-smartphone-BaRjkvN9.js → monitor-smartphone-DkSAqU6y.js} +1 -1
- package/dist/assets/mount-CQpRlaca.js +1 -0
- package/dist/assets/notification-schedule-field-BxKX0BnZ.js +1 -0
- package/dist/assets/player-overlays-CAMZYPzW.js +1 -0
- package/dist/assets/{recycle-CjrRLz-b.js → recycle-coHHb6k6.js} +1 -1
- package/dist/assets/remoteEntry-BM1N_mRj.js +1 -0
- package/dist/assets/{scan-eye-D35EojCj.js → scan-eye-C4uwlmDz.js} +1 -1
- package/dist/assets/{scissors-DreuVKed.js → scissors-D7cwr443.js} +1 -1
- package/dist/assets/{search-x-DQHP4OCR.js → search-x-Bslo2FkO.js} +1 -1
- package/dist/assets/{send-Dta9lxhX.js → send-BlcnRlFD.js} +1 -1
- package/dist/assets/{settings-2-DPZ8CKFD.js → settings-2-BWuIEodd.js} +1 -1
- package/dist/assets/{speaker-D95jrOt6.js → speaker-BzFTvxeb.js} +1 -1
- package/dist/assets/src-K7pIMCyE.js +67 -0
- package/dist/assets/{timer-reset-EEmenpu7.js → timer-reset-pzWKM4kj.js} +1 -1
- package/dist/assets/uPlot.esm-B6hGABOr.js +10 -0
- package/dist/assets/{ungroup-Db4urNO1.js → ungroup-COyVBHW5.js} +1 -1
- package/dist/assets/{unlink-6J-SREPz.js → unlink-CK2LhAFN.js} +1 -1
- package/dist/assets/{usb-UiuX4lHP.js → usb-D8FdL_8F.js} +1 -1
- package/dist/assets/{use-scenes-feed-xAvk3mdK.js → use-scenes-feed-BHhoT9GM.js} +1 -1
- package/dist/assets/{use-stationary-objects-BSuACN9l.js → use-stationary-objects-BEzZKgd5.js} +1 -1
- package/dist/assets/useEventInvalidation-CQpRlaca.js +1 -0
- package/dist/assets/{useNodeUrlSelection-itsA69-a.js → useNodeUrlSelection-1qoQDGNg.js} +1 -1
- package/dist/assets/user-round-DvukaL-O.js +1 -0
- package/dist/assets/{user-x-BiLr1XcR.js → user-x-6Zpsyjh-.js} +1 -1
- package/dist/assets/{video-DSVienqW.js → video-CBDxZVQI.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BzdoZPn9.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-qIFS5MFb.js} +2 -2
- package/dist/index.html +11 -11
- package/dist/server/addon.js +272 -25
- package/package.json +1 -1
- package/dist/assets/Addons-kSQ_LfKG.js +0 -4
- package/dist/assets/AdminPage-C_5SnDIL.js +0 -1
- package/dist/assets/AdminSectionedPage-9KWXxykK.js +0 -1
- package/dist/assets/AiProfiles-jgiZ-hEI.js +0 -3
- package/dist/assets/Build-DCeob-yZ.js +0 -40
- package/dist/assets/Cluster-eTZjguTx.js +0 -1
- package/dist/assets/ClusterStepModel-8aoPvS-k.js +0 -1
- package/dist/assets/CompositionEditor-CJR7m-qo.js +0 -1
- package/dist/assets/Data-xUdBOATt.js +0 -2
- package/dist/assets/DeviceDetail-BxgqCzrO.js +0 -2
- package/dist/assets/Identity-0TfWSUca.js +0 -1
- package/dist/assets/IntegrationDetail-e-6OvQx9.js +0 -1
- package/dist/assets/IntegrationHub-CA9MM1oL.js +0 -1
- package/dist/assets/Integrations-BbsiTLtO.js +0 -1
- package/dist/assets/Integrations-BdrRZHfb.js +0 -1
- package/dist/assets/Library-B9_Scpen.js +0 -1
- package/dist/assets/Locations-DdCSAAsc.js +0 -3
- package/dist/assets/MyAccess-oZ9l9GBy.js +0 -2
- package/dist/assets/Notifications-2cTCf7lp.js +0 -1
- package/dist/assets/Recordings-DycF_b6H.js +0 -1
- package/dist/assets/SessionsList-Cu3ZE31w.js +0 -2
- package/dist/assets/Showroom-ndc_ZezE.js +0 -1
- package/dist/assets/System-C_RpKyaA.js +0 -1
- package/dist/assets/circle-slash-CJ8sDXES.js +0 -1
- package/dist/assets/client-CqoBi3ym.js +0 -358
- package/dist/assets/crop-Cvf_bPJF.js +0 -1
- package/dist/assets/device-picker-model-2g0u_pQE.js +0 -1
- package/dist/assets/dist-yylqec5a.js +0 -358
- package/dist/assets/history-ohLSkO2A.js +0 -1
- package/dist/assets/i18n-Bldp2nug.js +0 -1
- package/dist/assets/icons-Bft8hsua.js +0 -1
- package/dist/assets/index-CN7xsFJi.css +0 -2
- package/dist/assets/index-WxoBkjSL.js +0 -4
- package/dist/assets/mount-2g0u_pQE.js +0 -1
- package/dist/assets/notification-schedule-field-BHhbg0a-.js +0 -1
- package/dist/assets/player-overlays-CpALjVtS.js +0 -1
- package/dist/assets/remoteEntry-CgICLtvC.js +0 -1
- package/dist/assets/src-CsHgYIi2.js +0 -67
- package/dist/assets/useEventInvalidation-2g0u_pQE.js +0 -1
- package/dist/assets/user-round-t1eXjuPz.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$ as e,B as t,G as n,J as r,S as i,a,b as o,o as s,p as c,q as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{Ir as f,It as p,Mr as m,Nt as h,Q as g,Qr as _,Ri as v,bn as y,ca as b,fn as x,gi as S,hi as C,kn as w,mr as T,or as E,ot as D,sn as O,xn as k,yn as A,yr as j,z as M,zi as N}from"./player-overlays-CAMZYPzW.js";import{A as P,B as F,D as I,E as ee,G as te,Gn as L,H as ne,Hn as R,I as re,J as ie,Kn as z,M as ae,O as oe,P as se,Q as ce,R as le,Tt as ue,U as de,V as fe,W as pe,X as me,Xr as he,Y as B,Yt as ge,Z as _e,at as ve,et as V,ft as ye,gt as be,ht as xe,in as Se,j as Ce,lt as we,mt as Te,pt as Ee,rt as De,st as Oe,tt as ke,ut as Ae,vt as je,wt as Me,xt as Ne}from"./client-BOc9ypnl.js";import{D as Pe,F as Fe,M as Ie,O as Le,j as Re,v as ze,y as Be}from"./__vite-browser-external-BlMfPwfH.js";import{t as Ve}from"./bell-off-2A9pKMoS.js";import{h as He}from"./video-CBDxZVQI.js";import{n as Ue,r as We,t as Ge}from"./list-ordered-BU_60EAm.js";import{t as Ke}from"./send-BlcnRlFD.js";import{$n as qe,An as Je,Ar as Ye,B as Xe,Cu as H,Dn as Ze,Dt as Qe,Er as $e,F as et,Ga as tt,H as nt,I as rt,Is as it,Kn as at,L as ot,Ns as st,On as U,Ou as W,P as ct,Pr as G,Ps as lt,Qi as ut,Qn as dt,Qt as ft,R as pt,Rs as mt,V as ht,_n as gt,dt as _t,er as vt,fr as K,gn as yt,hr as q,ir as bt,jn as xt,kn as St,kr as Ct,lt as wt,nr as Tt,qn as Et,rr as Dt,sr as Ot,ut as kt,vt as At,z as jt}from"./src-K7pIMCyE.js";import{t as J}from"./i18n-DzruZdmx.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import"./mount-CQpRlaca.js";import{$ as Mt,$t as Nt,A as Pt,At as Ft,B as It,Bt as Lt,C as Rt,Ct as zt,D as Bt,Dt as Vt,E as Ht,Et as Ut,F as Wt,Ft as Gt,G as Kt,Gt as qt,H as Jt,Ht as Yt,I as Xt,It as Zt,J as Qt,Jt as $t,K as en,Kt as tn,L as nn,Lt as rn,M as an,Mt as on,N as sn,Nt as cn,O as ln,Ot as un,P as dn,Pt as fn,Q as pn,Qt as mn,R as hn,Rt as gn,S as _n,St as vn,T as yn,Tt as bn,U as xn,Ut as Sn,V as Cn,Vt as wn,W as Tn,Wt as En,X as Dn,Xt as On,Y as kn,Yt as An,Z as jn,Zt as Mn,_ as Nn,_t as Pn,a as Fn,an as In,at as Ln,b as Rn,bt as zn,c as Bn,cn as Vn,ct as Hn,d as Un,dn as Wn,dt as Gn,en as Kn,et as qn,f as X,fn as Jn,ft as Yn,g as Xn,gt as Zn,h as Qn,hn as $n,ht as er,i as tr,in as nr,it as rr,j as ir,jt as ar,k as or,kt as sr,l as cr,ln as lr,lt as ur,m as dr,mn as fr,mt as pr,n as mr,nn as hr,nt as gr,o as _r,on as vr,ot as yr,p as br,pn as xr,pt as Sr,q as Cr,qt as wr,r as Tr,rn as Er,rt as Dr,s as Or,sn as kr,st as Ar,t as jr,tn as Mr,tt as Nr,u as Pr,un as Fr,ut as Ir,v as Lr,vt as Rr,w as zr,wt as Br,x as Vr,xt as Hr,y as Ur,yt as Wr,z as Gr,zt as Kr}from"./notification-schedule-field-BxKX0BnZ.js";import{D as qr,E as Jr,Q as Yr,T as Xr,Z as Zr,nt as Qr}from"./index-DzDx8M2g.js";import{t as $r}from"./AdminSectionedPage-B-vU2e0-.js";import{t as ei}from"./DeviceDoActionFields-oa5LfgEc.js";import{t as ti}from"./AdminPage-CQo22qlS.js";import"./device-picker-model-CQpRlaca.js";import{t as ni}from"./use-scenes-feed-BHhoT9GM.js";e();var ri=[`contact`,`cover`,`lock-control`,`switch`];function ii(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 ai(e){let t=new Set(ii(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 oi(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function si(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=>jt([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?J.t(`uiLibrary.devicePicker.deviceId`,{id:e}):ot(t,`device`,qr))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function ci(e){let t=e.name.trim();return t===``?J.t(`uiLibrary.devicePicker.deviceId`,{id:e.deviceId}):t}function li(e){return e===0?J.t(`helpers.alarmNonblocking.refusedNoName`):J.t(`helpers.alarmNonblocking.refusedOpen`)}var ui={home:`Home`,away:`Away`,night:`Night`};function di(e){return ui[e]??e}function fi(e,t){if(e<=0)return t;if(e<60)return`${e} s`;let n=Math.floor(e/60),r=e%60;return r===0?J.t(`helpers.notificationAlarm.delayMin`,{minutes:n}):J.t(`helpers.notificationAlarm.delayMinSec`,{minutes:n,seconds:r})}function pi(e,t){if(e.ruleCount===0)return J.t(`helpers.notificationAlarm.armsNothing`);if(e.allDevices&&e.allDevicesExcept.length>0){let n=e.allDevicesExcept.map(t);return J.t(`helpers.notificationAlarm.allExcept`,{count:n.length,names:n.join(`, `)})}return e.allDevices?J.t(`helpers.notificationAlarm.everyDevice`,{count:e.ruleCount}):e.deviceIds.length===0?J.t(`helpers.notificationAlarm.noRestriction`,{count:e.ruleCount}):e.deviceIds.map(t).join(`, `)}function mi(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${hi[e.reason]})`);return J.t(`helpers.notificationAlarm.skipped`,{count:e.length,parts:n.join(`, `)})}var hi={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function gi(e){return e.ruleCount===0}function _i(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 vi=2e3,yi=15e3,bi=new Set([`arming`,`pending`,`triggered`]);function xi(e){return e!==void 0&&bi.has(e)?vi:yi}var Si={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 Ci(e){let t=Si[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${di(e.targetMode)}`}function wi(e){return e!==`disarmed`}function Ti(e){return e===`open`?J.t(`helpers.notificationAlarm.phaseOpen`):J.t(`helpers.notificationAlarm.phaseClosed`)}function Ei(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Di(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Oi(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function ki(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 Ai(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 ji(e,t,n,r){let i=ki(e,t,n);return r==="default"?i===void 0?null:Ai(t,n,null):i===r?null:Ai(t,n,r)}function Mi(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=B(e,t),a=r!==n,o=n!==`doNothing`&&i.triggeredDurationSec===0;return!a&&!o?null:{mode:t,...a?{postTriggeredAction:n}:{},...o?{triggeredDurationSec:30}:{}}}function Ni(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 Pi=[`unknown-refusal`,`stale`,`expired`,`used`];function Fi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ii(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Fi(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 Li(e){if(!Fi(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Ii(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Ii(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Pi.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var Ri={"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 zi(e){return Ri[e]}function Bi(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 Vi=`pipeline-analytics`,Hi=`The hub answered something this build cannot read — refresh after updating.`;function Ui(e){return e instanceof Error?e.message:String(e)}function Wi(e){return e.map(e=>`${ci(e)} (${e.state})`).join(`, `)}function Gi({live:e,onChanged:t}){let{t:n}=Y(),a=D(),[o,s]=r(null),[c,l]=r(null),[f,p]=r(null),m=(e,t)=>a.trpcClient.addons.custom.mutate({addonId:Vi,action:e,input:t}),h=e=>{if(e===null){l(Hi);return}if(e.outcome===`refused`){s({refusalId:e.refusalId,blocking:e.blocking});return}if(s(null),e.outcome===`rejected`){l(`Arm anyway was not accepted: ${zi(e.reason)}.`);return}if(e.outcome===`outside-schedule`){l(`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: ${Wi(e.excluded)}.`)},g=()=>{l(null),p(null)},_=u({mutationFn:async e=>Li(await m(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>l(Ui(e)),onSettled:t}),v=u({mutationFn:async e=>Li(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>l(Ui(e)),onSettled:t}),y=u({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{g(),s(null)},onSuccess:()=>p(`Disarmed.`),onError:e=>l(Ui(e)),onSettled:t});if(e===void 0)return i(Ot,{className:`p-4`,children:[d(`h3`,{className:`text-sm font-semibold mb-1`,children:n(`system.alarmLiveCard.panel`,`Panel`)}),d(`p`,{className:`text-sm text-foreground-subtle`,children:n(`system.alarmLiveCard.thisHubDoesNotReport`,`This hub does not report the panel's live state yet — update it to arm from here.`)})]});let b=_.isPending||v.isPending||y.isPending;return i(Ot,{className:`p-4`,children:[i(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[i(`div`,{children:[d(`h3`,{className:`text-sm font-semibold`,children:n(`system.alarmLiveCard.panel`,`Panel`)}),d(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:Ci(e)})]}),i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?d(E,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>d(q,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:n(`system.alarmLiveCard.arm`,{mode:di(e)})},e)),d(q,{type:`button`,size:`md`,variant:wi(e.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:n(`system.alarmLiveCard.disarm`,`Disarm`)})]})]}),c===null?null:d(`div`,{className:`mt-3`,children:d(K,{title:n(`system.alarmLiveCard.thePanelDidNotDo`,`The panel did not do that`),message:c})}),f===null?null:d(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:f}),o===null?null:i(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[d(`p`,{className:`text-sm font-medium`,children:li(o.blocking.length)}),o.blocking.length>0?d(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:o.blocking.map(e=>i(`li`,{children:[ci(e),` `,i(`span`,{className:`text-foreground-subtle`,children:[`(`,e.state,`)`]})]},e.deviceId))}):null,i(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[d(q,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(o.refusalId),children:n(`system.alarmLiveCard.armAnyway`,`Arm anyway`)}),d(`span`,{className:`text-xs text-foreground-subtle`,children:n(`system.alarmLiveCard.eachOpenDeviceIsIgnored`,`Each open device is ignored until it closes, then monitored again.`)})]})]}),i(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[d(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:n(`system.alarmLiveCard.excludedSensors`,`Excluded sensors`)}),e.exclusions.length===0?d(`p`,{className:`text-sm text-foreground-subtle`,children:n(`system.alarmLiveCard.noSensorIsExcluded`,`No sensor is excluded.`)}):d(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:e.exclusions.map(e=>i(`li`,{children:[ci(e),` —`,` `,d(`span`,{className:`text-foreground-subtle`,children:Ti(e.phase)})]},e.deviceId))})]})]})}e();var Ki=[{field:`exitDelaySec`,key:`exit`,labelKey:`system.alarmDelay.exitLabel`,hintKey:`system.alarmDelay.exitHint`,max:600,zeroMeansKey:`system.alarmDelay.exitZero`},{field:`entryDelaySec`,key:`entry`,labelKey:`system.alarmDelay.entryLabel`,hintKey:`system.alarmDelay.entryHint`,max:600,zeroMeansKey:`system.alarmDelay.entryZero`},{field:`triggeredDurationSec`,key:`siren`,labelKey:`system.alarmDelay.sirenLabel`,hintKey:`system.alarmDelay.sirenHint`,max:R,zeroMeansKey:`system.alarmDelay.sirenZero`}];function qi(e){return J.t(`system.alarmDelay.rangeError`,{max:e})}function Ji(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${qi(t)}`}function Yi({label:e,value:t,max:n,zeroMeans:a,disabled:o,testId:s,hint:c,adornment:l,onCommit:u}){let[f,p]=r(null),[m,h]=r(null),g=f??String(t),_=f!==null&&f.trim()!==``&&_i(f,n)===null,v=fi(t,a),y=()=>{let e=f===null?null:_i(f,n);p(null),e===null?f!==null&&h(f):(h(null),u(e))};return i(At,{label:e,...c===void 0?{}:{description:c},..._?{error:qi(n)}:m===null?{}:{error:Ji(m,n)},children:[i(`div`,{className:`flex items-center gap-2`,children:[d(W,{type:`number`,min:0,max:n,value:g,disabled:o,state:_||m!==null?`error`:`default`,"aria-label":e,onChange:e=>{h(null),p(e.target.value)},onBlur:y,className:`w-20`,"data-testid":s}),d(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),l]}),v===`${t} s`?null:d(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function Xi(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=nt(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function Zi(e){switch(e.kind){case`checking`:return{word:J.t(`system.alarmSensorTable.cellChecking`),note:null};case`hub-too-old`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:J.t(`system.alarmSensorTable.cellHubTooOld`)};case`read-failed`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:J.t(`system.alarmSensorTable.cellReadFailedError`,{error:e.error})};case`open`:case`closed`:return{word:e.word,note:e.offline?J.t(`system.alarmSensorTable.cellOfflineLastKnown`):null};case`unknown`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:e.why===`not-answered`?J.t(`system.alarmSensorTable.cellNotAnswered`):e.why===`read-failed`?J.t(`system.alarmSensorTable.cellReadFailed`):J.t(`system.alarmSensorTable.cellNoState`)};case`not-opening`:return{word:J.t(`system.alarmSensorTable.cellNotOpening`),note:null};case`removed`:return{word:J.t(`system.alarmSensorTable.cellRemoved`),note:J.t(`system.alarmSensorTable.cellRemovedNote`)}}}function Qi(){return J.t(`system.alarmSensorTable.listedUncovered`)}function $i(e){return e.listedUncovered?{word:J.t(`system.alarmSensorTable.cellNo`),note:Qi()}:ea(e.coverage)}function ea(e){switch(e.kind){case`arm-checked`:return{word:J.t(`system.alarmSensorTable.cellYes`),note:null};case`arm-checked-skipped`:{let t=e.reason===`detection-off`?J.t(`system.alarmSensorTable.detectionOff`):e.reason;return{word:J.t(`system.alarmSensorTable.cellSkipped`),note:J.t(`system.alarmSensorTable.cellSkippedNote`,{why:t})}}case`unscoped`:return{word:J.t(`system.alarmSensorTable.cellAllDevices`),note:J.t(`system.alarmSensorTable.cellNeverBlocks`)};case`not-covered`:return{word:J.t(`system.alarmSensorTable.cellNo`),note:J.t(`system.alarmSensorTable.cellNeverBlocks`)}}}function ta(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 na(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 ra({name:e,variant:t,words:n}){return i(`span`,{"data-testid":`alarm-cell-${e}`,className:`flex flex-col items-start gap-0.5`,children:[d(G,{variant:t,"data-testid":`alarm-cell-${e}-badge`,children:n.word}),n.note===null?null:d(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${e}-note`,children:n.note})]})}var ia=`hidden sm:table-cell`;function aa(e){let{mode:t,inFlight:n,onSwitch:r,zones:a,disabled:o}=e;return[{key:`name`,header:J.t(`system.alarmSensorTable.name`,`Name`),cell:e=>{let t=Xi(e.device.location,a);return i(`span`,{className:`flex min-w-0 flex-col`,"data-testid":`alarm-cell-name`,"data-muted":e.listedUncovered?`true`:void 0,children:[d(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.device.name}),t===``?null:d(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:t})]})}},{key:`type`,header:J.t(`system.alarmSensorTable.type`,`Type`),headerClassName:ia,cellClassName:`${ia} text-[11px] text-foreground-subtle`,cell:e=>ht(e.device.type??null,qr)},{key:`state`,header:J.t(`system.alarmSensorTable.state`,`State`),cell:e=>d(ra,{name:`state`,variant:ta(e.cell),words:Zi(e.cell)})},{key:`coverage`,header:J.t(`system.alarmSensorTable.checkedWhenArming`,`Checked when arming`),headerClassName:ia,cellClassName:ia,cell:e=>d(ra,{name:`coverage`,variant:na(e),words:$i(e)})},{key:`blocks`,header:J.t(`system.alarmSensorTable.blocksArming`,`Blocks arming`),headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{let a=n!==null&&n.mode===t&&n.deviceId===e.device.id&&n.kind===`blocks`,s=n!==null&&!a;return i(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?d(E,{className:`h-3 w-3 animate-spin`}):null,d(xt,{checked:e.blocks,onCheckedChange:t=>r(e,`blocks`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-blocks`,"aria-label":J.t(`system.alarmSensorTable.blocksArming2`,`Blocks arming: {{name}}`,{name:e.device.name}),"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}},{key:`secure`,header:d(`span`,{title:J.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),children:J.t(`system.alarmSensorTable.secureOnArm`,`Secure on arm`)}),headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{if(!e.controllable)return d(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let a=n!==null&&n.mode===t&&n.deviceId===e.device.id&&n.kind===`secureOnArm`,s=n!==null&&!a;return i(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?d(E,{className:`h-3 w-3 animate-spin`}):null,d(xt,{checked:e.secureOnArm,onCheckedChange:t=>r(e,`secureOnArm`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-secure`,"aria-label":J.t(`system.alarmSensorTable.secureOnArmCloseLock`,`Secure on arm (close/lock/off): {{name}}`,{name:e.device.name}),title:J.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}}]}function oa(e){let{t}=Y(),n=b(),{mode:r,rows:a,sensorsRetry:o,zones:s}=e;return i(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${r}`,children:[o===null?null:i(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[d(`span`,{children:t(`system.alarmSensorTable.couldNotReadTheSensor`,`Could not read the sensor states.`)}),d(q,{type:`button`,size:`sm`,variant:`outline`,onClick:o,children:t(`common.retry`,`Retry`)})]}),d(Qe,{mode:`generic`,items:a,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,Xi(e.device.location,s),ht(e.device.type??null,n)].join(` `),getFilterType:e=>ht(e.device.type??null,n),columns:aa(e),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:t(`system.alarmSensorTable.searchSensors`,`Search sensors`),emptyLabel:`No sensor matches.`})]})}var sa=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function ca(e){return sa.some(t=>t.test(e))}function la(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return ca(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 ua(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 da(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 fa(e){return e.kind===`unscoped`||e.kind===`not-covered`}function pa(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=da(e.coverage,r.id),a=ua(e.sensors,r.id,t,r.type),o=_e({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=ce({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&&fa(i)&&(!o||c)&&c;!t&&fa(i)&&!c||n.push({device:r,removed:t,cell:la(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function ma(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function ha(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 ga(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 _a(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 va(e,t){return ie(_a(e),t)?{kind:`landed`}:{kind:`not-landed`}}var ya=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function ba({coverage:e,settings:t,disabled:n,onNotifyEdit:r}){let{t:a}=Y(),o=me(t,e.mode);return i(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${e.mode}`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:a(`notificationRules.alarmNotify.title`)}),ya.map(({field:t,key:s})=>i(`div`,{className:`flex items-start justify-between gap-3`,children:[i(`div`,{className:`min-w-0`,children:[d(`p`,{className:`text-xs text-foreground`,children:a(`notificationRules.alarmNotify.${s}`)}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:a(`notificationRules.alarmNotify.${s}Hint`)})]}),d(xt,{checked:o[t],onCheckedChange:e=>r(t,e),disabled:n,"data-testid":`alarm-notify-${e.mode}-${t}`,"aria-label":a(`notificationRules.alarmNotify.${s}`)})]},t))]})}function xa({coverage:e,rows:t,names:n}){let{t:r}=Y(),a=t.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,o=pi(e,n.nameOf);return i(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${e.mode}`,children:[gi(e)?d(G,{variant:`warning`,title:o,"data-testid":`alarm-arms-nothing`,children:r(`system.alarmModeCard.armsNothingNoEnabledRule`,`Arms nothing — no enabled rule is gated on this mode`)}):d(G,{variant:`default`,title:o,"data-testid":`alarm-covers`,children:r(`system.alarmModeCard.checksSensors`,{count:a})}),e.skippedDevices.length>0?d(G,{variant:`warning`,title:mi(e.skippedDevices,n.nameOf),"data-testid":`alarm-skipped`,children:r(`system.alarmModeCard.notNotified`,{count:e.skippedDevices.length})}):null]})}function Sa(e){return e.status===`answered`?e.openingIds:null}function Ca({check:e,view:t}){let{t:n}=Y();return t.unresolved?e.status===`pending`?i(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[d(E,{className:`h-3 w-3 animate-spin`}),n(`system.alarmModeCard.checkingWhichDevicesAreOpenings`,`Checking which devices are openings…`)]}):e.status===`failed`?i(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[d(`span`,{children:n(`system.alarmModeCard.openingsCheckFailed`,{error:e.error})}),d(q,{type:`button`,size:`sm`,variant:`outline`,onClick:e.retry,children:n(`common.retry`,`Retry`)})]}):null:null}var wa=[{value:`rearmAfter`,labelKey:`system.alarmModeCard.postRearm`},{value:`disableAfter`,labelKey:`system.alarmModeCard.postDisarm`},{value:`doNothing`,labelKey:`system.alarmModeCard.postNothing`}];function Ta({coverage:e,settings:t,disabled:n,onDelayEdit:r,onPostTriggeredEdit:a,onScheduleEdit:o}){let{t:s}=Y(),c=e.mode,l=B(t,c),u=l.source.postTriggeredAction==="default",f=l.postTriggeredAction!==`doNothing`,p=(t.modeDelays??[]).find(e=>e.mode===c)?.schedule;return i(`div`,{className:`space-y-3`,"data-testid":`alarm-delays-${c}`,children:[i(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:[Ki.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let i=l.source[e.field]==="default";return d(Yi,{label:s(e.labelKey),value:l[e.field],max:e.max,zeroMeans:s(e.zeroMeansKey),disabled:n,testId:`alarm-delay-${c}-${e.key}`,onCommit:t=>r(e.field,t),adornment:i?d(G,{variant:`default`,title:s(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:t[e.field]}),children:s(`system.alarmModeCard.default`,`Default`)}):d(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:s(e.labelKey)}),onClick:()=>r(e.field,`default`),"data-testid":`alarm-delay-${c}-${e.key}-default`,children:d(A,{className:`h-3.5 w-3.5`})})},e.field)}),i(`div`,{children:[i(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:[s(`system.alarmModeCard.afterTrigger`,`After trigger`),u?d(G,{variant:`default`,className:`ml-1.5 align-middle`,title:s(`system.alarmModeCard.usesTheSystemDefault`,`Uses the system default`),children:s(`system.alarmModeCard.default`,`Default`)}):d(q,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:n,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.afterTriggerUseTheDefault`,`After trigger: use the default`),onClick:()=>a(`default`),"data-testid":`alarm-delay-${c}-post-default`,children:d(A,{className:`h-3.5 w-3.5`})})]}),d(`select`,{className:`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:l.postTriggeredAction,disabled:n,"data-testid":`alarm-delay-${c}-post`,onChange:e=>{let t=L.safeParse(e.target.value);t.success&&a(t.data)},children:wa.map(e=>d(`option`,{value:e.value,children:s(e.labelKey)},e.value))})]}),f?Ki.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let i=l.source[e.field]==="default";return d(Yi,{label:s(e.labelKey),value:l[e.field],max:e.max,zeroMeans:s(e.zeroMeansKey),disabled:n,testId:`alarm-delay-${c}-${e.key}`,onCommit:t=>r(e.field,t),adornment:i?d(G,{variant:`default`,title:s(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:t[e.field]}),children:s(`system.alarmModeCard.default`,`Default`)}):d(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:s(e.labelKey)}),onClick:()=>r(e.field,`default`),"data-testid":`alarm-delay-${c}-${e.key}-default`,children:d(A,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),i(`div`,{"data-testid":`alarm-schedule-${c}`,children:[d(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:s(`system.alarmModeCard.activationSchedule`,`Activation schedule`)}),d(`p`,{className:`mb-1 text-[10px] text-foreground-subtle`,children:s(`system.alarmModeCard.whenThisModeMayBe`,`When this mode may be armed. Empty means any day and time.`)}),d(`fieldset`,{disabled:n,className:`min-w-0 border-0 p-0`,children:d(jr,{value:p,onChange:o,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var Ea={"no-opening":`This household has no contact, cover or lock.`};function Da({coverage:e,live:t,settings:n,names:r,openingsCheck:a,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:u,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m,onNotifyEdit:h,disabled:g}){let{t:_}=Y(),v=ai({live:t,listed:Ei(n,e.mode),openingIds:Sa(a)}),y=oi(v),b=ma({rowCount:o.length,candidatesComplete:!v.unresolved});return i(`div`,{className:`flex flex-col gap-3`,"data-mode":e.mode,"data-empty":gi(e)?`true`:`false`,children:[d(xa,{coverage:e,rows:o,names:r}),d(Ta,{coverage:e,settings:n,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:_(`system.alarmModeCard.delaysHint`,{seconds:30})}),d(ba,{coverage:e,settings:n,disabled:g,onNotifyEdit:h}),i(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[d(Ca,{check:a,view:v}),y===null?null:d(`p`,{className:`text-xs text-foreground-subtle`,children:Ea[y]}),b===`none`&&y===null?d(`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`?d(oa,{mode:e.mode,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:u,disabled:g}):null]})]})}e();function Oa({profiles:e,busy:t,onActivate:n,onCreate:a,onClone:s,onRename:c,onDelete:l}){let{t:u}=Y(),[f,m]=r(``),[h,g]=r(!1),v=e.items.find(t=>t.id===e.activeId)??e.items[0],y=v!==void 0&&!v.isDefault,b=f.trim(),x=()=>{b.length!==0&&(a(b),m(``))},S=()=>{b.length===0||v===void 0||(s(v.id,b),m(``))},C=()=>{b.length===0||v===void 0||(c(v.id,b),m(``),g(!1))};return i(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface-1 p-3`,"data-testid":`alarm-profiles`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:u(`system.alarmProfileBar.profile`,`Profile`)}),d(`select`,{id:`alarm-profile-select`,className:`h-8 min-w-[10rem] rounded-md border border-border bg-background px-2 text-sm`,"data-testid":`alarm-profile-select`,disabled:t,value:e.activeId,onChange:e=>n(e.target.value),children:e.items.map(e=>i(`option`,{value:e.id,children:[e.name,e.isDefault?` (${u(`system.alarmProfileBar.defaultSuffix`)})`:``]},e.id))}),y?d(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-delete`,title:u(`system.alarmProfileBar.deleteThisProfile`,`Delete this profile`),onClick:()=>{v!==void 0&&l(v.id)},children:d(p,{className:`h-3.5 w-3.5`})}):null]}),i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(W,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:h?u(`system.alarmProfileBar.newName`,`New name`):u(`system.alarmProfileBar.newProfileName`,`New profile name`),value:f,disabled:t,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(h?C():x())}}),h?i(o,{children:[d(q,{type:`button`,size:`sm`,disabled:t||b.length===0,"data-testid":`alarm-profile-rename-save`,onClick:C,children:u(`system.alarmProfileBar.rename`,`Rename`)}),d(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{g(!1),m(``)},children:u(`common.cancel`,`Cancel`)})]}):i(o,{children:[i(q,{type:`button`,size:`sm`,disabled:t||b.length===0,"data-testid":`alarm-profile-create`,title:u(`system.alarmProfileBar.createWithSystemDefaults`,`Create with system defaults`),onClick:x,children:[d(w,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.create`,`Create`)]}),i(q,{type:`button`,size:`sm`,variant:`secondary`,disabled:t||b.length===0||v===void 0,"data-testid":`alarm-profile-clone`,title:u(`system.alarmProfileBar.cloneTheSelectedProfile`,`Clone the selected profile`),onClick:S,children:[d(_,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.clone`,`Clone`)]}),d(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:t||v===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{g(!0),m(v?.name??``)},children:u(`system.alarmProfileBar.rename`,`Rename`)})]})]}),d(`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.`)})]})}e();var ka=[`notificationRules`,`getAlarmConfig`],Aa=[`notificationRules`,`getAlarmSensors`],ja=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],Ma=6e4;function Na(e){return e instanceof Error?e.message:String(e)}function Pa({notice:e}){let{t}=Y();switch(e.kind){case`refused`:return d(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:t(`system.notificationAlarm.refused`,{name:e.inFlight.name,mode:di(e.inFlight.mode)})});case`not-landed`:return d(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:t(`system.notificationAlarm.notLanded`,{name:e.write.name,mode:di(e.write.mode)})});case`failed`:return d(`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:di(e.write.mode),error:e.error})})}}function Fa(){let{t:e}=Y(),t=D(),o=s(),f=a({queryKey:ka,queryFn:async()=>t.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>xi(e.state.data?.live?.state)}),p=tt({projection:`slim`}),[m,h]=r(!1),g=u({mutationFn:e=>t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{o.setQueryData(ka,e),h(!ie(t,e.settings))}}),_=u({mutationFn:async e=>{switch(e.kind){case`activate`:return t.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return t.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return t.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{o.setQueryData(ka,e),h(!1)}}),v=()=>o.invalidateQueries({queryKey:ka}),y=n(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),b=f.data?.live,x=a({queryKey:ja,staleTime:Ma,queryFn:async()=>new Set(await t.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...ri]}))}),S=n(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),C=n(()=>new Map(S.map(e=>[e.id,e])),[S]),w=x.isError?{status:`failed`,error:x.error instanceof Error?x.error.message:String(x.error),retry:()=>void x.refetch()}:x.data===void 0?{status:`pending`}:{status:`answered`,openingIds:x.data},T=n(()=>{let e=new Map;for(let t of b?.openings??[])for(let n of t.devices)e.set(n.deviceId,ci(n));return si(y,pt(p),e)},[b,y,p]),k=Xe(!0),[A,j]=r(null),M=n(()=>{let e=new Map,t=f.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,ai({live:t.live,listed:Ei(t.settings,n.mode),openingIds:x.data??null}).ids);return e},[f.data,x.data]),N=n(()=>{let e=new Set;for(let t of M.values())for(let n of t)T.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[M,T]),P=a({queryKey:[...Aa,N],enabled:N.length>0,placeholderData:c,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&ca(Na(e.state.error))?!1:b!==void 0&&wi(b.state)?5e3:15e3,retry:(e,t)=>!ca(Na(t))&&e<2,queryFn:async()=>{let e=[];for(let n of ha(N,500))e.push(await t.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...n]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),F=P.isError?{status:`failed`,error:Na(P.error)}:P.data===void 0?{status:`pending`}:{status:`answered`,sensors:P.data.sensors},I=l(null),[ee,te]=r(null),[L,ne]=r(null),R=async e=>{try{let n=await t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:_a(e)});va(e,n.settings).kind===`landed`?o.setQueryData(ka,n):(ne({kind:`not-landed`,write:e}),o.invalidateQueries({queryKey:ka}))}catch(t){ne({kind:`failed`,write:e,error:Na(t)}),o.invalidateQueries({queryKey:ka})}finally{I.current=null,te(null),ne(e=>e?.kind===`refused`?null:e)}},re=(e,t,n,r)=>{let i=ga(I.current,e,t,n,r);if(i.kind===`refused`){ne({kind:`refused`,inFlight:i.inFlight});return}I.current=i.write,te(i.write),ne(null),R(i.write)};if(f.isLoading)return d(ti,{embedded:!0,icon:O,title:e(`system.notificationAlarm.alarm`,`Alarm`),subtitle:e(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:d(E,{className:`h-5 w-5 animate-spin`})});let z=f.data;if(z===void 0||f.isError)return d(ti,{embedded:!0,icon:O,title:e(`system.notificationAlarm.alarm`,`Alarm`),subtitle:e(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:d(K,{title:e(`system.notificationAlarm.alarmSettingsAreNotAvailable`,`Alarm settings are not available`),message:e(`system.notificationAlarm.thisHubHasNotBeen`,`This hub has not been updated to serve the alarm configuration yet.`)})});if(z.deviceId===null)return d(ti,{embedded:!0,icon:O,title:e(`system.notificationAlarm.alarm`,`Alarm`),subtitle:e(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:d(Ot,{className:`p-4`,children:d(`p`,{className:`text-sm text-foreground-subtle`,children:e(`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 ae=z.settings,oe=g.isPending||_.isPending,se=e=>{h(!1),g.mutate(e)},ce=(e,t,n)=>{let r=ji(ae,e,t,n);r!==null&&se({modeDelays:[r]})},le=(e,t)=>{let n=Mi(ae,e,t);n!==null&&se({modeDelays:[n]})},ue=(e,t)=>{let n=Ni(ae,e,t);n!==null&&se({modeDelays:[n]})},de=(e,t,n)=>{let r=Bi(ae,e,t,n);r!==null&&se({modeDelays:[r]})},fe=new Map(z.coverage.map(e=>[e.mode,pa({candidates:(M.get(e.mode)??[]).map(e=>({...C.get(e),id:e,name:T.nameOf(e)})),removedIds:new Set((M.get(e.mode)??[]).filter(T.isRemoved)),coverage:e,nonBlocking:Ei(ae,e.mode),blocking:Di(ae,e.mode),secureOnArmOff:Oi(ae,e.mode),sensors:F})])),pe=z.coverage.find(e=>e.mode===A)??z.coverage.find(e=>(fe.get(e.mode)?.length??0)>0)??z.coverage[0],me=pe?.mode??``;return i(ti,{embedded:!0,icon:O,title:e(`system.notificationAlarm.alarm`,`Alarm`),subtitle:e(`system.notificationAlarm.thePanelWhatEachMode`,`The panel, what each mode arms, and who hears about it.`),children:[g.isError?d(K,{title:e(`system.notificationAlarm.couldNotSave`,`Could not save`),message:String(g.error)}):null,_.isError?d(K,{title:e(`system.notificationAlarm.couldNotUpdateProfile`,`Could not update profile`),message:String(_.error)}):null,m?d(`div`,{"data-testid":`alarm-save-not-landed`,children:d(K,{variant:`warning`,title:e(`system.notificationAlarm.notApplied`,`Not applied`),message:e(`system.notificationAlarm.theHubDidNotApply`,`The hub did not apply this change — another editor may have changed it, or the hub needs an update`)})}):null,z.profiles===void 0?null:d(Oa,{profiles:z.profiles,busy:oe,onActivate:e=>_.mutate({kind:`activate`,id:e}),onCreate:e=>_.mutate({kind:`create`,name:e}),onClone:(e,t)=>_.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>_.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>_.mutate({kind:`delete`,id:e})}),d(Gi,{live:z.live,onChanged:v}),i(Ot,{className:`p-4`,"data-testid":`alarm-coverage`,children:[d(Ze,{value:me,onValueChange:e=>{let t=z.coverage.find(t=>t.mode===e);t!==void 0&&j(t.mode)},children:d(St,{className:`mb-3`,children:z.coverage.map(e=>i(Je,{value:e.mode,"data-testid":`alarm-tab-${e.mode}`,children:[di(e.mode),d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:fe.get(e.mode)?.length??0})]},e.mode))})}),L===null?null:d(Pa,{notice:L}),pe===void 0?null:d(Da,{coverage:pe,live:z.live,settings:ae,names:T,openingsCheck:w,rows:fe.get(pe.mode)??[],sensorsRetry:F.status===`failed`&&!ca(F.error)?()=>void P.refetch():null,inFlight:ee,onSwitch:(e,t,n)=>re(pe.mode,e,t,n),zones:k,onDelayEdit:(e,t)=>ce(pe.mode,e,t),onPostTriggeredEdit:e=>le(pe.mode,e),onScheduleEdit:e=>ue(pe.mode,e),onNotifyEdit:(e,t)=>de(pe.mode,e,t),disabled:oe},pe.mode)]})]})}var Ia=`history`,La=`ruleId`,Ra=[La],za=24,Ba=0,Va=100;function Ha(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Ia),n.set(La,t),n}function Ua(e,t){let n=new URLSearchParams(e);return t===``?n.delete(La):n.set(La,t),n}function Wa(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?za:Ba,limit:Va}}function Ga(e){let t=e.rules.map(e=>({value:e.id,label:e.name})),n=e.selected!==``&&!e.rules.some(t=>t.id===e.selected)?[{value:e.selected,label:e.answered?J.t(`helpers.notificationHistory.deletedRule`,{id:e.selected}):e.selected}]:[];return[{value:``,label:J.t(`helpers.notificationHistory.allRules`)},...t,...n]}e();var Ka=[{value:1,labelKey:`system.notificationHistory.windowLastHour`},{value:24,labelKey:`system.notificationHistory.windowLast24h`},{value:168,labelKey:`system.notificationHistory.windowLast7d`},{value:0,labelKey:`system.notificationHistory.windowAllTime`}],qa=[{value:``,labelKey:`system.notificationHistory.statusAny`},{value:`pending`,labelKey:`system.notificationHistory.statusPending`},{value:`sent`,labelKey:`system.notificationHistory.statusSent`},{value:`dead`,labelKey:`system.notificationHistory.statusDead`}],Ja=[50,100,250,500];function Ya(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Xa(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Za(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 Qa({entry:e,cameraName:t,onClose:n}){let{t:r}=Y(),a=Za(e),o=e.subject.systemEvent;return d(dt,{open:!0,onOpenChange:e=>!e&&n(),children:i(vt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[d(Dt,{children:d(bt,{className:`min-w-0 break-words`,children:a.title||e.ruleName})}),d(qe,{children:i(`dl`,{className:`space-y-3`,children:[i(`div`,{children:[d(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:r(`system.notificationHistory.body`,`Body`)}),d(`dd`,{className:`mt-1 whitespace-pre-wrap text-sm text-foreground`,children:a.body.length>0?a.body:`—`})]}),i(`div`,{className:`grid grid-cols-2 gap-3 text-[11px]`,children:[i(`div`,{children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.when`,`When`)}),d(`dd`,{className:`text-foreground`,children:new Date(e.createdAt).toLocaleString()})]}),i(`div`,{children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.status`,`Status`)}),d(`dd`,{className:`text-foreground`,children:e.status})]}),i(`div`,{children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.rule`,`Rule`)}),d(`dd`,{className:`text-foreground`,children:e.ruleName})]}),i(`div`,{children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.device`,`Device`)}),d(`dd`,{className:`text-foreground`,children:t})]}),o===void 0?null:i(`div`,{className:`col-span-2`,children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.kind`,`Kind`)}),d(`dd`,{className:`text-foreground`,children:o.kind})]}),e.error===void 0?null:i(`div`,{className:`col-span-2`,children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`common.error`,`Error`)}),d(`dd`,{className:`text-danger`,children:e.error})]})]})]})}),d(Tt,{children:d(q,{type:`button`,size:`sm`,variant:`secondary`,onClick:n,children:r(`common.close`,`Close`)})})]})})}function $a(){let{t:e}=Y(),t=D(),[o,s]=Qr(),[c,l]=r(()=>Wa(o)),[u,f]=r(null),p=e=>l(t=>({...t,...e})),m=e=>{p({ruleId:e}),s(Ua(o,e),{replace:!0})},h=a({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await t.trpcClient.notificationRules.listRules.query({})).rules}),g=tt({projection:`slim`}),_=Date.now(),v=a({queryKey:[`notificationRules`,`getHistory`,c],retry:!1,queryFn:async()=>{let e=c.windowHours>0?_-c.windowHours*36e5:void 0;return(await t.trpcClient.notificationRules.getHistory.query({filter:{limit:c.limit,...c.ruleId?{ruleId:c.ruleId}:{},...c.deviceId?{deviceId:Number(c.deviceId)}:{},...Ya(c.status)?{status:Ya(c.status)}:{},...e===void 0?{}:{since:e}}})).entries}}),b=n(()=>{let e=new Map;for(let t of g.data??[])t.type===he.Camera&&e.set(t.id,t.name);return e},[g.data]),x=t=>b.get(t)??e(`system.notificationHistory.cameraFallback`,{deviceId:t}),S=v.data??[],C=v.isError;return i(ti,{embedded:!0,icon:j,title:e(`system.notificationHistory.deliveryHistory`,`Delivery history`),subtitle:e(`system.notificationHistory.aSearchableLogOfEvery`,`A searchable log of every notification the rules delivered (or failed to deliver).`),children:[i(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.rule`,`Rule`)}),d(H,{"data-testid":`history-rule-filter`,value:c.ruleId,onChange:e=>m(e.target.value),options:[...Ga({rules:h.data??[],answered:h.isSuccess,selected:c.ruleId})]})]}),i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.camera`,`Camera`)}),d(H,{value:c.deviceId,onChange:e=>p({deviceId:e.target.value}),options:[{value:``,label:e(`system.notificationHistory.allCameras`,`All cameras`)},...(g.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.status`,`Status`)}),d(H,{value:c.status,onChange:e=>p({status:e.target.value}),options:qa.map(t=>({value:t.value,label:e(t.labelKey)}))})]}),i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.window`,`Window`)}),d(H,{value:String(c.windowHours),onChange:e=>p({windowHours:Number(e.target.value)}),options:Ka.map(t=>({value:String(t.value),label:e(t.labelKey)}))})]}),i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.limit`,`Limit`)}),d(H,{value:String(c.limit),onChange:e=>p({limit:Number(e.target.value)}),options:Ja.map(e=>({value:String(e),label:String(e)}))})]})]}),v.isLoading&&d(`div`,{className:`flex items-center justify-center py-16`,children:d(E,{className:`h-6 w-6 animate-spin text-primary`})}),C&&!v.isLoading&&d(Ot,{children:i(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[d(j,{className:`h-6 w-6 text-foreground-subtle`}),d(`div`,{className:`text-sm font-medium text-foreground`,children:e(`system.notificationHistory.deliveryHistoryRequiresAServer`,`Delivery history requires a server update`)}),d(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:e(`system.notificationHistory.theHistoryQueryIsNot`,`The history query is not available on this hub yet. It becomes queryable after the next server update ships the notification-center history endpoint. Rules still deliver and record their outcome in the meantime.`)}),i(`button`,{type:`button`,onClick:()=>void v.refetch(),className:`mt-1 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:[d(y,{className:`h-3 w-3`}),` `,e(`common.retry`)]})]})}),!C&&!v.isLoading&&S.length===0&&d(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`system.notificationHistory.noDeliveriesMatchTheseFilters`,`No deliveries match these filters.`)}),!C&&S.length>0&&d(Ot,{children:d(yt,{columns:eo(x),rows:S,rowKey:e=>e.id,minWidthPx:720,bordered:!1,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>f(e)})}),u!==null&&d(Qa,{entry:u,cameraName:x(u.deviceId),onClose:()=>f(null)})]})}function eo(e){return[{key:`when`,header:J.t(`system.notificationHistory.when`,`When`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:J.t(`system.notificationHistory.rule`,`Rule`),render:e=>d(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:J.t(`system.notificationHistory.camera`,`Camera`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:J.t(`system.notificationHistory.notification`,`Notification`),render:e=>{let t=Za(e);return i(`span`,{className:`block max-w-[18rem]`,children:[d(`span`,{className:`block truncate text-[11px] font-medium text-foreground`,children:t.title.length>0?t.title:e.subject.label??e.subject.className}),t.body.length>0?d(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:t.body}):null]})}},{key:`status`,header:J.t(`system.notificationHistory.status`,`Status`),nowrap:!0,render:e=>i(`span`,{className:`flex items-center gap-1.5`,children:[d(G,{variant:Xa(e.status),children:e.status}),e.attempts>1?i(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:J.t(`system.notificationHistory.detail`,`Detail`),render:e=>e.error?d(`span`,{className:`text-[11px] text-danger`,children:e.error}):d(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var to=/\{\{\s*(\w+)\s*\}\}/g,no=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function ro(e,t,n){let r=Math.min(Math.max(t.start,0),e.length),i=Math.min(Math.max(t.end,r),e.length);return{value:e.slice(0,r)+n+e.slice(i),cursor:r+n.length}}function io(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function ao(e){return[...e.matchAll(to)].map(e=>e[1]??``).filter(e=>e.length>0)}function oo(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function so(e,t){return[...new Set(ao(e))].filter(e=>!oo(e,t))}var co={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function lo(e){return e.map(e=>{let t=fe.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)||F.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function uo(e){let t=new Set(e.map(e=>e.name)),n=fe.filter(e=>ne(e)&&!t.has(e.name));return[...e,...n]}function fo(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=co[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)||!pe(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:te(e,t)&&de(e,t))}function po(e){return no.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var mo=[`nc`,`template-catalog`],ho=400;function go(){let e=D();return a({queryKey:mo,staleTime:5*6e4,queryFn:async()=>uo(lo((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function _o(e,t,n){let r=D(),i=ft(t.title??``,ho),o=ft(t.body??``,ho);return a({queryKey:[`nc`,`template-preview`,e,i,o],enabled:n&&(i.length>0||o.length>0),staleTime:3e4,queryFn:()=>r.trpcClient.notificationRules.previewTemplate.mutate({context:e,template:{...i?{title:i}:{},...o?{body:o}:{}}})})}e();var vo={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},yo=`block text-[11px] font-medium text-foreground mb-1`,bo=`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`;function xo({label:e,value:t,onChange:n,vars:r,multiline:a=!1,placeholder:o,disabled:s=!1,testId:c}){let{t:u}=Y(),f=l(null),p=l(null),m=r?so(t,r):[],g=e=>{let r=a?p.current:f.current,i={start:r?.selectionStart??t.length,end:r?.selectionEnd??t.length},o=io(e),s=ro(t,i,o.text);n(s.value);let c=s.cursor-o.text.length+o.cursorOffset;requestAnimationFrame(()=>{r?.focus(),r?.setSelectionRange(c,c)})},_=e=>n(e.target.value);return i(`div`,{className:`space-y-1`,children:[d(`label`,{className:yo,children:e}),a?d(`textarea`,{ref:p,value:t,rows:2,disabled:s,placeholder:o,onChange:_,className:bo,"data-testid":`${c}-input`}):d(W,{ref:f,value:t,disabled:s,placeholder:o,onChange:_,"data-testid":`${c}-input`}),r&&r.length===0?d(`p`,{className:`text-[10px] text-foreground-subtle`,children:u(`notifications.templateField.noVariablesForThisField`,`No variables for this field.`)}):null,r&&r.length>0?d(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:po(r).map(e=>i(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${c}-group-${e.group}`,children:[d(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:vo[e.group]}),e.vars.map(e=>d(`button`,{type:`button`,disabled:s,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":`${c}-chip-${e.name}`,children:e.dynamic?u(`notifications.templateField.class`,`{{name}}<class>`,{name:e.name}):e.name},e.name))]},e.group))}):null,m.length>0?i(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${c}-unknown`,children:[d(h,{className:`h-3 w-3`}),u(`notifications.templateField.willBeEmpty`,{names:m.map(e=>`{{${e}}}`).join(` `)})]}):null]})}function So({context:e,title:t,body:n,testId:r}){let{t:a}=Y(),o=_o(e,{title:t,body:n},!0);return o.data?i(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":r,children:[d(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:a(`notifications.templateField.previewExampleValues`,`Preview (example values)`)}),o.data.title===null?null:d(`p`,{className:`font-medium`,children:o.data.title}),o.data.body===null?null:d(`p`,{className:`whitespace-pre-wrap`,children:o.data.body})]}):null}var Co=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,wo=`block text-[11px] font-medium text-foreground`;function To({title:e,description:t,children:n}){return i(`div`,{className:`flex flex-col gap-2`,children:[i(`div`,{children:[d(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:t})]}),n!==void 0&&d(`div`,{className:`flex flex-wrap items-center gap-1`,children:n})]})}function Eo(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function Do(e,t){return{kind:`cap`,deviceId:t,cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}}}function Oo(e){let t=Eo(e.deviceId);return t.length===0?[Do(e,0)]:t.map(t=>Do(e,t))}function ko(e){return Oo(e).map(e=>({kind:`do`,action:e}))}function Ao(e,t){let n=e[t];if(n===void 0||n.kind!==`cap`)return{wire:{deviceId:0,cap:``,method:``},length:1};let r=n.deviceId>0?[n.deviceId]:[],i=1;for(let a=t+1;a<e.length;a+=1){let t=e[a];if(t===void 0||t.kind!==`cap`||t.cap!==n.cap||t.method!==n.method||JSON.stringify(t.args??{})!==JSON.stringify(n.args??{}))break;t.deviceId>0&&r.push(t.deviceId),i+=1}return{wire:{deviceId:r.length===0?0:r.length===1?r[0]:[...r],cap:n.cap,method:n.method,...n.args===void 0?{}:{args:{...n.args}}},length:i}}function jo(e,t){let n=e[t];return n===void 0||n.kind!==`do`?{wire:{deviceId:0,cap:``,method:``},length:1}:Ao(e.slice(t).map(e=>e.kind===`do`?e.action:{kind:`wait`,seconds:0}),0)}function Mo({value:e,onChange:t,devices:n,devicesState:r,sequences:a=[],showProblems:o=!0}){let{t:s}=Y(),c=pn(e,new Set(a.map(e=>e.id))),l=(n,r)=>t({...e,[n]:r}),u=(n,r)=>t({...e,buttons:e.buttons.map((e,t)=>t===n?r:e)});return i(`div`,{className:`space-y-4`,children:[o&&c.length>0?d(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:c.map(e=>d(`p`,{children:e.message},e.message))}):null,Kt.map(t=>d(No,{hookKey:t,bindings:e[t],sequences:a,devices:n,devicesState:r,onChange:e=>l(t,e)},t)),i(`section`,{className:`space-y-2`,children:[d(To,{title:s(`system.notificationRuleActions.buttonsOnTheNotification`,`Buttons on the notification`),description:s(`system.notificationRuleActions.eachButtonRunsOneShared`,`Each button runs one shared sequence when tapped.`),children:i(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:a.length===0,onClick:()=>t({...e,buttons:[...e.buttons,Qt(e.buttons.length,a[0]?.id??``)]}),children:[d(w,{className:`h-3.5 w-3.5 shrink-0`}),` `,s(`system.notificationRuleActions.button`)]})}),e.buttons.length>0&&i(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:[d(h,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),d(`span`,{children:d(Zr,{i18nKey:`system.notificationRuleActions.buttonLinkNote`,components:{b:d(`strong`,{})}})})]}),a.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:s(`system.notificationRuleActions.createASequenceOnThe`,`Create a sequence on the Sequences tab first — a button runs one, it does not define its own steps.`)}):e.buttons.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:s(`system.notificationRuleActions.noButtonsTheNotificationArrives`,`No buttons. The notification arrives with nothing to tap.`)}):e.buttons.map((n,r)=>d(Po,{button:n,sequences:a,onChange:e=>u(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function No({hookKey:e,bindings:t,sequences:n,devices:r,devicesState:a,onChange:o}){let{t:s}=Y(),c=en[e],l=[],u=0;for(;u<t.length;){if(t[u].kind===`sequence`){l.push({start:u,kind:`sequence`,length:1}),u+=1;continue}let e=jo(t,u);l.push({start:u,kind:`do`,length:e.length}),u+=e.length}return i(`section`,{className:`space-y-2`,children:[i(To,{title:c.title,description:c.hint,children:[i(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4||n.length===0,onClick:()=>o([...t,Dn(n[0]?.id??``)]),children:[d(w,{className:`h-3.5 w-3.5`}),` `,s(`system.notificationRuleActions.sequence`)]}),i(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4,onClick:()=>o([...t,kn()]),children:[d(w,{className:`h-3.5 w-3.5`}),` `,s(`system.notificationRuleActions.singleAction`)]})]}),t.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:s(`system.notificationRuleActions.nothingOnThisEdge`,`Nothing on this edge.`)}):l.map(e=>{if(e.kind===`sequence`){let r=t[e.start];return r.kind===`sequence`?i(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:wo,children:s(`system.notificationRuleActions.sequence`,`Sequence`)}),d(`select`,{className:Co,value:r.sequenceId,onChange:n=>{let r=[...t];r[e.start]={kind:`sequence`,sequenceId:n.target.value},o(r)},children:n.map(e=>d(`option`,{value:e.id,children:e.name},e.id))})]}),d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o(t.filter((t,n)=>n!==e.start)),title:s(`common.remove`,`Remove`),children:d(p,{className:`h-3.5 w-3.5`})})]},`seq-${String(e.start)}`):null}return d(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:i(`div`,{className:`flex items-start justify-between gap-2`,children:[d(`div`,{className:`min-w-0 flex-1`,children:d(ei,{value:jo(t,e.start).wire,devices:r,listState:a,allowMultiSameFamily:!0,onChange:n=>{let r=ko(n);o([...t.slice(0,e.start),...r,...t.slice(e.start+e.length)])}})}),d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o([...t.slice(0,e.start),...t.slice(e.start+e.length)]),title:s(`common.remove`,`Remove`),children:d(p,{className:`h-3.5 w-3.5`})})]})},`do-${String(e.start)}`)})]})}function Po({button:e,sequences:t,onChange:n,onRemove:r}){let{t:a}=Y();return i(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[i(`div`,{className:`w-28`,children:[d(`label`,{className:wo,children:a(`system.notificationRuleActions.id`,`Id`)}),d(W,{className:`mt-1`,value:e.id,onChange:t=>n({...e,id:t.target.value})})]}),i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:wo,children:a(`system.notificationRuleActions.label`,`Label`)}),d(W,{className:`mt-1`,value:e.label,onChange:t=>n({...e,label:t.target.value})})]}),i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:wo,children:a(`system.notificationRuleActions.sequence`,`Sequence`)}),d(`select`,{className:Co,value:e.sequenceId,onChange:t=>n({...e,sequenceId:t.target.value}),children:t.map(e=>d(`option`,{value:e.id,children:e.name},e.id))})]}),i(`div`,{className:`w-32`,children:[d(`label`,{className:wo,children:a(`system.notificationRuleActions.icon`,`Icon`)}),i(`select`,{className:Co,value:e.icon??``,onChange:t=>{let r={...e};t.target.value===``?delete r.icon:r.icon=t.target.value,n(r)},children:[d(`option`,{value:``,children:`—`}),Tn.map(e=>d(`option`,{value:e.value,children:e.label},e.value))]})]}),d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:a(`common.remove`,`Remove`),children:d(p,{className:`h-3.5 w-3.5`})})]})}var Fo=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Io=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],Lo={minConfidence:`class`},Ro=[{id:`system`,get label(){return J.t(`notificationRules.groups.system`)}},{id:`class`,get label(){return J.t(`notificationRules.groups.class`)}},{id:`zones`,get label(){return J.t(`notificationRules.groups.zones`)}},{id:`label`,get label(){return J.t(`notificationRules.groups.label`)}},{id:`quality`,get label(){return J.t(`notificationRules.groups.quality`)}},{id:`scope`,get label(){return J.t(`notificationRules.groups.scope`)}},{id:`device`,get label(){return J.t(`notificationRules.groups.device`)}},{id:`package`,get label(){return J.t(`notificationRules.groups.package`)}},{id:`occupancy`,get label(){return J.t(`notificationRules.groups.occupancy`)}},{id:`audio`,get label(){return J.t(`notificationRules.groups.audio`)}},{id:`schedule`,get label(){return J.t(`notificationRules.groups.schedule`)}}];function zo(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Io)t.has(e)&&n.add(r);return n}function Bo(e){return Lo[e.id]??e.group}function Vo(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Ho(e){let t=zo(e),n=e.filter(e=>!Fo.has(e.id)&&!t.has(e.id)),r=new Set(Ro.map(e=>e.id)),i=[],a=e=>n.filter(t=>Bo(t)===e);for(let e of Ro){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=Bo(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Vo(e),descriptors:a(e)});return i}function Uo(e,t){switch(e){case`zones`:return Dr(t.zones?.ids,t.zonesExclude);case`labels`:return Dr(t.labelEquals,void 0);case`identities`:return Wo(t)}}function Wo(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?Dr(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function Go(e,t,n){switch(e){case`zones`:return Ko(t,n);case`labels`:return qo(t,n);case`identities`:return Jo(t,n)}}function Ko(e,t){let{zones:n,zonesExclude:r,...i}=e,a=qn(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function qo(e,t){let{labelEquals:n,...r}=e,i=qn(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function Jo(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=rr(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=qn(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var Yo={all:`All`,only:`Only these`,except:`All except these`},Xo={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 Zo({draft:e,onChange:t,exceptOffered:n,plural:r,renderPicker:a,describe:o,testId:s}){let{t:c}=Y(),l=(e,t,n)=>c(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),u=c(`ruleScope.items.${r}`,Xo[r].items),f=Mt.filter(t=>t!==`except`||n||e.mode===`except`),p=rr(e),m=gr(e),h=e.mode===`all`?null:e.mode;return i(`div`,{className:`mt-1 space-y-1.5`,"data-testid":s,children:[d(`div`,{role:`radiogroup`,"aria-label":l(`ruleScope.which`,`Which {{items}}`,u),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(n=>{let r=n===e.mode;return d(`button`,{type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${n}`,onClick:()=>t(Ar(e,n)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,children:c(`ruleScope.mode.${n}`,Yo[n])},n)})}),h===null?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(`ruleScope.every.${r}`,Xo[r].every)}):a(Ln(e),n=>t(yr(e,n)),h),p.length>0&&i(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[l(`ruleScope.legacy`,`This rule also excludes {{items}} — kept when you save.`,p.map(o).join(`, `)),` `,d(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>t(Nr(e)),children:c(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:l(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(o).join(`, `))})]})}function Qo(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 $o(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})}e();function es(e,t,n){let[i,a]=r(()=>Uo(e,t));return[i,r=>{a(r),n(Go(e,t,r))}]}function ts(e,t){return t?`failed`:e?`pending`:`answered`}function ns({conditions:e,onConditionsChange:t,exceptOffered:r,cameraIds:i,cameras:a}){let{t:o}=Y(),[s,c]=es(`zones`,e,t),{options:l,loading:u,failed:f}=Nt(i,a),p=n(()=>$o(l),[l]),m=ts(u,!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 d(Zo,{draft:s,onChange:c,exceptOffered:r,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>i.length===0?d(`p`,{className:Un,children:o(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):d(et,{devices:p,listState:m,fleet:h,value:e,onChange:t,emptyMeansAll:!0,noun:`zone`,groupTitle:e=>e.type??o(`notificationRules.zones.group`,`Zones`),testId:`zone-picker`},n)})}function rs({conditions:e,onConditionsChange:t,exceptOffered:r}){let{t:i}=Y(),[a,o]=es(`identities`,e,t),{options:s,loading:c,failed:l}=mn(),u=n(()=>s.map(e=>({id:e.value,name:e.label})),[s]),f=n(()=>new Map(u.map(e=>[e.id,e.name])),[u]);return d(Zo,{draft:a,onChange:o,exceptOffered:r,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>d(et,{devices:u,listState:ts(c,l),value:e,onChange:t,emptyMeansAll:n===`except`,...n===`only`?{emptyLabel:i(`notificationRules.faces.anyKnown`,`Any known face — nobody in particular`)}:{},noun:`face`,groupTitle:()=>i(`notificationRules.faces.group`,`Known faces`),testId:`identity-picker`},n)})}function is({conditions:e,onConditionsChange:t}){let{t:n}=Y(),[r,i]=es(`labels`,e,t);return d(Zo,{draft:r,onChange:i,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>d(Nn,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function as(e){let t=ue(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function os(e){return e.type??J.t(`helpers.classPickerItems.other`)}e();function ss({taxonomy:e,scope:t,onChange:r,exceptOffered:i}){let{t:a}=Y(),o=n(()=>as(e),[e]),s=n(()=>new Map((o??[]).map(e=>[e.id,e.name])),[o]);return d(Zo,{draft:t,onChange:r,exceptOffered:i,plural:`classes`,describe:e=>s.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>o===null?d(Nn,{value:e,placeholder:a(`system.notificationClassScopeField.addValue`,`Add value…`),onChange:t}):d(et,{devices:o,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:os,testId:`class-picker`},n)})}function cs(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function ls({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return d(et,{devices:e.map(cs),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`,showAll:!0})}function us({devices:e,scope:t,onChange:n,listState:r,savedScope:i,exceptOffered:a}){let o=new Map(e.map(e=>[e.id,e.name]));return d(Zo,{draft:t,onChange:n,exceptOffered:a,plural:`devices`,describe:e=>o.get(e)??J.t(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`rule-device-scope`,renderPicker:(t,n,a)=>d(ls,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function ds(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function fs(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function ps(e){let t=ds(e),n=e.data===void 0?[]:P(e.data.nodes),r=fs(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function ms(e){let t=ds(e),n=e.data===void 0?[]:Ce(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var hs=[`nc-pickers`,`node-directory`],gs=[`nc-pickers`,`package-list`],_s=6e4,vs={get hub(){return J.t(`system.scopePickers.roleHub`)},get agent(){return J.t(`system.scopePickers.roleAgents`)}},ys={get server(){return J.t(`system.scopePickers.pkgServer`)},get framework(){return J.t(`system.scopePickers.pkgFramework`)},get wrapper(){return J.t(`system.scopePickers.pkgWrapper`)},get addon(){return J.t(`system.scopePickers.pkgAddons`)}};function bs(e){let t=vs[e.type??``]??J.t(`system.scopePickers.roleNodes`);return e.location===`offline`?J.t(`system.scopePickers.offlineSuffix`,{role:t}):t}function xs(e){return ys[e.type??``]??J.t(`system.scopePickers.pkgPackages`)}function Ss({value:e,onChange:t,testId:n}){let{t:r}=Y(),o=D().trpcClient,s=a({queryKey:hs,staleTime:_s,queryFn:()=>o.nodes.directory.query()}),c=ps(s);return i(`div`,{children:[d(et,{devices:c.items,listState:c.listState,fleet:c.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:bs,...n===void 0?{}:{testId:n}}),s.data?.complete===!1&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:r(`system.scopePickers.theNodeHistoryCouldNot`,`The node history could not be read — offline nodes may be missing from this list.`)})]})}function Cs({value:e,onChange:t,testId:n}){let r=D().trpcClient,i=ms(a({queryKey:gs,staleTime:_s,queryFn:()=>r.addons.listPackages.query()}));return d(et,{devices:i.items,listState:i.listState,fleet:i.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:xs,...n===void 0?{}:{testId:n}})}var ws={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-tank-low`]},template:{body:`{{deviceName}}`}};function Ts(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 Es(e,t){return e===`pending`?`pending`:e===`success`?`current`:Ts(t)===`BAD_REQUEST`?`outdated`:`unknown`}function Ds(e){let t=D(),n=a({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(ws)});return e?Es(n.status,n.error):`pending`}e();var Os=`/system/settings`,ks=`/system/notifications?tab=alarm`,As=`text-primary underline-offset-2 hover:underline`;function js(e,t){let n=qn(t);return Yn(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function Ms({family:e,value:t,cameras:a,allDevices:o,fleet:s,savedHadDevices:c,onChange:l}){let{t:u}=Y(),f=n(()=>t?.kinds??[],[t]),p=n(()=>o===void 0?a:o.map(cs),[o,a]),m=n(()=>a.map(e=>({id:e.id,name:e.name,type:`camera`})),[a]),h=er(e,f),g=Ds(e===`device-events`),_=e===`alarm`,[v,y]=r(()=>Dr(t?.deviceIds,t?.excludeDeviceIds)),[b]=r(()=>Dr(t?.deviceIds,t?.excludeDeviceIds)),x=n(()=>{let e=new Map;for(let t of _?m:p)e.set(t.id,t.name);return e},[m,_,p]);return i(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[Zn(e).map(n=>i(`div`,{children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:n.label}),d(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:n.kinds.map(n=>{let r=f.includes(n.value);return d(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":n.label,onClick:()=>l(Rr(t,n.value,e)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-1 text-[11px] text-primary`:`rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:n.label},n.value)})})]},n.id)),e===`device-events`&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-device-alert-settings`,children:[u(`system.notificationSystemEventField.theBatteryThresholdAndThe`,`The battery threshold and the reminder interval are cluster settings (the consumable threshold is this rule’s own, below):`),` `,d(Yr,{to:Os,target:`_blank`,rel:`noreferrer`,className:As,children:u(`system.notificationSystemEventField.settingsBatteryOfflineAlerts`,`Settings → Battery & offline alerts`)}),`.`]}),e===`alarm`&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[d(Yr,{to:ks,target:`_blank`,rel:`noreferrer`,className:As,children:u(`system.notificationSystemEventField.alarmSettings`,`Alarm settings`)}),f.includes(`alarm-triggered`)&&d(`span`,{className:`ml-1`,children:u(`system.notificationSystemEventField.alarmPictures`)})]}),g===`outdated`&&d(`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:u(`system.notificationSystemEventField.hubOutdated`,{percent:15})}),g===`unknown`&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:u(`system.notificationSystemEventField.couldNotCheckWhetherThis`,`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`)}),h.consumableThreshold&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:u(`system.notificationSystemEventField.consumableLowAt`,`Consumable low at (%)`)}),d(W,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:Hn,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=Gn(e.target.value);n.kind!==`invalid`&&l(Yn(t,{consumableLowPercent:n.kind===`set`?n.value:void 0}))}})]}),h.deviceTypes&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:u(`system.notificationSystemEventField.deviceTypes`,`Device types`)}),d(Mn,{options:ur,value:t?.deviceTypes??[],onChange:e=>l(Yn(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:u(`system.notificationSystemEventField.deviceType`,`Device type…`)})]}),Ir(t)&&d(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`battery-device-types-warning`,children:u(`system.notificationSystemEventField.batteryAndConsumableAlertsAre`,`Battery and consumable alerts are narrowed by device type here. Batteries and consumables belong to sensors, containers, vacuums and mowers — rarely to a camera — so a type filter meant for liveness silences them. Leave the types empty, or put these kinds in a rule of their own.`)}),h.devices&&i(`div`,{children:[d(Zo,{draft:v,onChange:e=>{y(e),l(js(t,e))},exceptOffered:h.excludeDevices,plural:`devices`,describe:e=>x.get(e)??u(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`system-event-device-scope`,renderPicker:(e,t,n)=>d(et,{devices:_?m:p,listState:s.state,fleet:s,emptyMeansAll:!0,savedHadDevices:(n===`only`?b.include:b.exclude).length>0||n===`only`&&c,noun:_?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),c&&v.mode===`all`&&d(rt,{noun:_?`camera`:`device`})]}),h.nodes&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:u(`system.notificationSystemEventField.nodes`,`Nodes`)}),d(Ss,{value:t?.nodeIds??[],onChange:e=>l(Yn(t,{nodeIds:e})),testId:`system-event-nodes`})]}),h.packages&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:u(`system.notificationSystemEventField.packages`,`Packages`)}),d(Cs,{value:t?.packageNames??[],onChange:e=>l(Yn(t,{packageNames:e})),testId:`system-event-packages`})]})]})}function Ns({value:e}){let{t}=Y(),n=e?.kinds??[];return i(`div`,{className:`mt-1 rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-mixed`,children:[d(`p`,{children:t(`system.notificationSystemEventField.thisRuleIsNotOne`,`This rule is not one kind of system rule — its events span device events, system and alarm, or it names none. It keeps firing as it is, but it cannot be edited here: recreate it as one rule per kind.`)}),n.length>0&&d(`p`,{className:`mt-1 text-foreground`,children:n.map(Pn).join(`, `)})]})}function Ps({family:e,onChange:t}){let{t:n}=Y();return i(`div`,{"data-testid":`system-family-select`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:n(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`)}),d(H,{value:e,"aria-label":n(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`),onChange:e=>{let n=e.target.value;Ne(n)&&t(n)},options:je.map(e=>({value:e,label:Ee(e).label}))}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:n(`system.notificationSystemEventField.oneRuleAnswersOneQuestion`,`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`)})]})}e();function Fs({catalog:e,taxonomy:t,delivery:r,conditions:a,classScope:o,onClassScopeChange:s,actions:c,sequenceActionsOf:l,savedConditions:u,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x}){let{t:S}=Y(),C=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,b(n)},w=ye({delivery:r,conditions:a}),T=n(()=>e.filter(e=>ve(e,r,w)&&on(e.id,a)),[e,r,w,a]),E=n(()=>Ho(T),[T]),D=e=>T.some(t=>t.id===e),O=e=>Is.has(e.id)?d(ss,{taxonomy:t,scope:o,onChange:s,exceptOffered:D(`classesExclude`)}):Ls.has(e.id)?d(ns,{conditions:a,onConditionsChange:b,exceptOffered:D(`zonesExclude`),cameraIds:m??p,cameras:h}):Rs.has(e.id)?d(rs,{conditions:a,onConditionsChange:b,exceptOffered:D(`identitiesExclude`)}):e.id===`labelEquals`?d(is,{conditions:a,onConditionsChange:b}):null;return d(`div`,{className:`space-y-4`,children:E.map(e=>i(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${e.id}`,children:[d(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:S(`notificationRules.groups.${e.id}`,e.label)}),e.descriptors.map(e=>{let n=O(e);return i(`div`,{"data-testid":`condition-${e.id}`,children:[d(`label`,{className:X,children:zs(e,S)}),n??d(Hs,{descriptor:e,kind:w,taxonomy:t,conditions:a,actions:c,sequenceActionsOf:l,savedConditions:u,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:C,onScheduleChange:x}),Bs(e,S)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Bs(e,S)})]},e.id)})]},e.id))})}var Is=new Set([`classes`,`classesExclude`]),Ls=new Set([`zones`,`zonesExclude`]),Rs=new Set([`identities`,`identitiesExclude`]);function zs(e,t){return Is.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):Ls.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):Rs.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 Bs(e,t){if(!Vs.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var Vs=new Set([...Is,...Ls,...Rs,`labelEquals`,`crossing`]);function Hs({descriptor:e,kind:t,taxonomy:n,conditions:r,actions:a,sequenceActionsOf:s,savedConditions:c,schedule:l,deviceIds:u,cameras:f,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v}){let{t:y}=Y();switch(e.valueType){case`deviceIdList`:{if(!hr(e.id))break;let t=e.id,n=r[t]??[];return d(Bn,{cameras:f,fleet:p,emptyMeansAll:!0,savedHadDevices:(c?.[t]?.length??0)>0,value:n,onChange:e=>_(t,e.length>0?e:void 0)})}case`stringList`:{if(!Jn(e.id))break;let t=e.id,i=e=>_(t,e.length>0?e:void 0);if(t===`eventTypeTokens`)return d(Pr,{deviceIds:u,value:$n(r,t),onChange:i});let a=Me(t,n);return a===null?d(Nn,{value:$n(r,t),placeholder:y(`system.notificationRuleConditions.addValue`,`Add value…`),onChange:i}):d(Lr,{picker:a,value:$n(r,t),onChange:i})}case`number01`:{if(!nr(e.id))break;let t=e.id;return d(br,{value:fr(r,t),min:0,max:1,step:.05,onChange:e=>_(t,e)})}case`number`:{if(!In(e.id))break;let t=e.id;return d(br,{value:fr(r,t),min:0,step:1,onChange:e=>_(t,e)})}case`sourceSelect`:{if(!Wn(e.id))break;let t=e.id;return qs(e,r[t],e=>_(t,e))}case`systemEvent`:{if(!xr(e.id))break;let n=e.id,i=be(t);return i===void 0?d(Ns,{value:r[n]}):d(Ms,{family:i,value:r[n],cameras:f,fleet:p,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[n]?.deviceIds?.length??0)>0,onChange:e=>_(n,e)})}case`deviceState`:if(!Er(e.id))break;return d(cr,{gateable:h,value:r.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!lr(e.id))break;return d(Xn,{scenes:g,value:r.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!Mr(e.id))break;let t=e.id;return Js(e,r[t],e=>_(t,e))}case`packagePhase`:{if(!kr(e.id))break;let t=e.id;return d(H,{value:r[t]??``,options:[{value:``,label:y(`system.notificationRuleConditions.anyPhase`,`— any phase —`)},...Zt(e,Vt).map(e=>({value:e.value,label:e.label}))],onChange:e=>_(t,Ks(e.target.value))})}case`sensorTransition`:{if(!Fr(e.id))break;let t=e.id,n=V({conditions:r,...a===void 0?{}:{actions:a},...s===void 0?{}:{sequenceActionsOf:s}});return i(o,{children:[d(H,{value:r[t]??``,options:Zt(e,Ft).map(e=>({value:e.value,label:e.label})),onChange:e=>_(t,An(e.target.value))}),n&&d(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`nc-sensor-transition-never-fires`,children:`This rule belongs to the alarm, and an alarm rule fires only when an opening OPENS. Set to “only when it clears”, it can never fire.`})]})}case`plateMatcher`:{if(!Vn(e.id))break;let t=e.id;return d(Qn,{value:r[t],onChange:e=>_(t,e)})}case`occupancy`:{if(!vr(e.id))break;let t=e.id;return d(dr,{deviceIds:u,cameras:f,classOptions:Us(n),value:r[t],onChange:e=>_(t,e)})}case`audio`:{if(!Kn(e.id))break;let t=e.id;return d(_r,{taxonomy:n,value:r[t],onChange:e=>_(t,e)})}case`schedule`:return d(jr,{value:l,onChange:v});default:break}return d(Ws,{descriptor:e,conditions:r})}function Us(e){let t=Me(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Ws({descriptor:e,conditions:t}){let{t:n}=Y(),r=Object.entries(t).find(([t])=>t===e.id);return i(`p`,{className:Un,children:[r!==void 0&&r[1]!==void 0?n(`system.notificationRuleConditions.authoredElsewhereAndPreservedThis`,`Authored elsewhere and preserved — this admin editor cannot change it yet.`):n(`system.notificationRuleConditions.notEditableHereYetThis`,`Not editable here yet — this condition has no admin editor.`),` `,i(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function Gs(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Ks(e){return Vt.find(t=>t.value===e)?.value}function qs(e,t,n){return d(H,{value:t??`any`,options:Zt(e,ar).map(e=>({value:e.value,label:e.label})),onChange:e=>n(Gs(e.target.value))})}function Js(e,t,n){return d(Or,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function Ys({catalog:e,delivery:t,conditions:n,onConditionsChange:r}){let{t:a}=Y(),o=ye({delivery:t,conditions:n}),s=(e,t)=>{let i={...n};t===void 0?delete i[e]:i[e]=t,r(i)},c=r=>e.find(e=>e.id===r&&ve(e,t,o)&&on(r,n)),l=c(`source`),u=c(`crossing`);return l===void 0&&u===void 0?null:i(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[l&&Wn(l.id)&&i(`div`,{"data-testid":`condition-source`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:zs(l,a)}),qs(l,n.source,e=>s(`source`,e)),Bs(l,a)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Bs(l,a)})]}),u&&Mr(u.id)&&i(`div`,{"data-testid":`condition-crossing`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:zs(u,a)}),Js(u,n.crossing,e=>s(`crossing`,e)),Bs(u,a)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Bs(u,a)})]})]})}var Xs=6e4,Zs=60*Xs,Qs=24*Zs,$s=Date.UTC(2e3,0,1);function ec(e){if(e==null||e<$s)return`—`;let t=Date.now()-e;return t<0||t<3e4?J.t(`helpers.relativeTime.justNow`):t<Zs?J.t(`helpers.relativeTime.minutesAgo`,{count:Math.floor(t/Xs)}):t<Qs?J.t(`helpers.relativeTime.hoursAgo`,{count:Math.floor(t/Zs)}):J.t(`helpers.relativeTime.daysAgo`,{count:Math.floor(t/Qs)})}var tc=[`notificationRules`,`getRuleLastRuns`],nc=3e4;function rc(){let e=D(),t=a({queryKey:tc,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:nc});return{status:t.status,data:t.data,error:t.error}}var ic={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function ac({cell:e}){let{t}=Y();switch(e.kind){case`pending`:return d(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":t(`system.notificationRuleLastRun.lastRunLoading`,`Last run loading`),className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return d(`span`,{"data-testid":`rule-last-run-failed`,title:t(`system.notificationRuleLastRun.lastRunCouldNotBe`,`Last run could not be read: {{reason}}`,{reason:e.reason}),className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.phrase});case`ran`:return i(`span`,{className:`flex items-center gap-1.5`,title:new Date(e.lastAt).toLocaleString(),children:[d(`span`,{"data-testid":`rule-last-run-dot`,title:e.status,className:`inline-block h-2 w-2 rounded-full ${ic[e.status]}`}),d(`span`,{className:`text-[11px] text-foreground-subtle`,children:ec(e.lastAt)})]})}}function oc({rule:e,onOpenHistory:t}){let{t:n}=Y();return d(q,{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:d(j,{className:`h-3.5 w-3.5`})})}e();var sc=[`notificationRules`,`listSnoozes`],cc=[10,30,60,120];function lc({ruleId:e,ruleName:t,exempt:n=!1,variant:a=`icon`}){let{t:o}=Y(),c=D(),l=s(),[f,p]=r(30),[m,h]=r(null),g=u({mutationFn:t=>c.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>l.invalidateQueries({queryKey:sc}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return n?a===`icon`?null:d(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`system.notificationRuleSnoozeControl.thisRuleConcernsOrTriggers`,`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`)}):a===`icon`?d(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:o(`system.notificationRuleSnoozeControl.silenceThisRuleForIt`,`Silence this rule for {{value1}} — it appears under "Silenced right now"`,{value1:Jt(30)}),"aria-label":o(`system.notificationRuleSnoozeControl.snooze`,`snooze {{ruleName}}`,{ruleName:t}),"data-testid":`nc-rule-snooze-now`,children:g.isPending?d(E,{className:`h-3.5 w-3.5 animate-spin`}):d(Ve,{className:`h-3.5 w-3.5`})}):i(`div`,{className:`space-y-1`,children:[i(`div`,{className:`flex items-end gap-2`,children:[d(`div`,{className:`w-32`,children:d(H,{value:String(f),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:cc.map(e=>({value:String(e),label:Jt(e)}))})}),i(q,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(f),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?d(E,{className:`h-3.5 w-3.5 animate-spin`}):d(Ve,{className:`h-3.5 w-3.5`}),o(`system.notificationRuleSnoozeControl.silenceThisRuleNow`,`Silence this rule now`)]})]}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`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&&d(`p`,{className:`text-[10px] text-danger`,children:m})]})}e();function uc(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function dc(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 fc(e,n){let[,i]=r(0);t(()=>{let t=dc(e,n,Date.now());if(t===null)return;let r=setTimeout(()=>i(e=>e+1),Math.max(0,t-Date.now())+50);return()=>clearTimeout(r)},[e,n])}function pc(){let e=D();return a({queryKey:sc,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function mc({rule:e,snoozes:t,exempt:n}){let{t:r}=Y(),a=D(),o=s();fc(t,e.id);let c=uc(t,e.id,Date.now()),l=()=>o.invalidateQueries({queryKey:sc}),f=u({mutationFn:()=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e.id,durationMinutes:30}}),onSuccess:l}),p=u({mutationFn:async e=>{for(let t of e)await a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:l});if(n)return null;let m=f.isError||p.isError;return i(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[d(xt,{checked:c.length>0,disabled:!e.enabled||f.isPending||p.isPending,onCheckedChange:e=>e?f.mutate():p.mutate(c),"aria-label":r(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,e.name),title:r(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),m&&d(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:r(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var hc=`pipeline-analytics`,gc=`nc.getRuleStatus`,_c=`nc.testRule`;function vc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function yc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function bc(e){if(!vc(e))return;let t=yc(e,`id`),n=yc(e,`downloadPath`),r=Z(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:yc(e,`mediaType`)??`video`,sizeBytes:Z(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function xc(e){if(!vc(e))return;let t=Z(e,`startMs`),n=Z(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function Sc(e){if(!vc(e))return null;let t=Z(e,`deviceId`);if(t===void 0)return null;let n=Z(e,`lastGeneratedAt`),r=bc(e.lastArtifact),i=e.rendering,a=vc(i)?{startedAt:Z(i,`startedAt`)??0,windowStartMs:Z(i,`windowStartMs`)??0,windowEndMs:Z(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function Cc(e){if(!vc(e))return null;let t=Z(e,`deviceId`),n=yc(e,`windowKey`),r=Z(e,`openedAt`),i=Z(e,`closesAt`),a=Z(e,`members`),o=Z(e,`pending`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0?null:{deviceId:t,windowKey:n,openedAt:r,closesAt:i,members:a,pending:o}}function wc(e){if(!vc(e))return null;let t=yc(e,`kind`);if(t===`none`)return{kind:`none`,reason:yc(e,`reason`)??``};if(t===`occupancy`){let t=Z(e,`deviceId`),n=Z(e,`threshold`),r=Z(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=yc(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=Z(e,`count`),s=Z(e,`observedAt`),c=Z(e,`since`),l=yc(e,`scope`),u=yc(e,`className`),d=yc(e,`warning`);return{kind:`occupancy`,deviceId:t,threshold:n,sustainSeconds:r,...l===void 0?{}:{scope:l},...u===void 0?{}:{className:u},...o===void 0?{}:{count:o},...typeof e.occupied==`boolean`?{occupied:e.occupied}:{},...s===void 0?{}:{observedAt:s},...c===void 0?{}:{since:c},...a===void 0?{}:{unavailable:a},...d===void 0?{}:{warning:d}}}if(t===`grouped`){let t=Z(e,`groupingSec`);if(t===void 0)return null;if(e.openWindows===null){let n=yc(e,`reason`);return{kind:`grouped`,groupingSec:t,openWindows:null,...n===void 0?{}:{reason:n}}}if(!Array.isArray(e.openWindows))return null;let n=[];for(let t of e.openWindows){let e=Cc(t);if(e===null)return null;n.push(e)}return{kind:`grouped`,groupingSec:t,openWindows:n}}if(t===`timelapse`){let t=Array.isArray(e.devices)?e.devices:[],n=[];for(let e of t){let t=Sc(e);t!==null&&n.push(t)}let r=xc(e.lastWindow),i=e.nextWindow,a=vc(i)?{startMs:Z(i,`startMs`)??0,endMs:Z(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:Z(e,`settleMs`)??0}}return null}function Tc(e){let t=Math.max(0,Math.floor(e/6e4));if(t<1)return J.t(`helpers.notificationRuleStatus.lessThanMinute`);if(t<60)return J.t(`helpers.notificationRuleStatus.durMin`,{count:t});let n=Math.floor(t/60),r=t%60;if(n<24)return r===0?J.t(`helpers.notificationRuleStatus.durH`,{count:n}):J.t(`helpers.notificationRuleStatus.durHMin`,{hours:n,minutes:r});let i=Math.floor(n/24),a=n%24;return a===0?J.t(`helpers.notificationRuleStatus.durD`,{count:i}):J.t(`helpers.notificationRuleStatus.durDH`,{days:i,hours:a})}function Ec(e){if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return J.t(`helpers.notificationRuleStatus.sizeKb`,{value:t.toFixed(0)});let n=t/1024;return n<1024?J.t(`helpers.notificationRuleStatus.sizeMb`,{value:n.toFixed(1)}):J.t(`helpers.notificationRuleStatus.sizeGb`,{value:(n/1024).toFixed(2)})}function Dc(e,t){let n=e.scope??`the whole frame`,r=e.className??`objects`;if(e.unavailable!==void 0){let t=e.unavailable===`no-snapshot`?`no live count for this camera yet — the condition fails closed until one arrives`:`“${n}” is not in this camera’s current snapshot — the condition fails closed (deleted zone?)`;return e.warning===void 0?t:`${e.warning} · ${t}`}let i=[`Now: ${String(e.count??0)}/${String(e.threshold)} ${r} in ${n}`,e.occupied===!0?`condition TRUE`:`condition false`];e.since!==void 0&&i.push(`for ${Tc(Math.max(0,t-e.since))}`),i.push(`holds ${String(e.sustainSeconds)} s before firing`);let a=i.join(` · `);return e.warning===void 0?a:`${e.warning} · ${a}`}function Oc(e,t,n){if(e.rendering!==void 0)return J.t(`helpers.notificationRuleStatus.tlRendering`,{camera:t,duration:Tc(Math.max(0,n-e.rendering.startedAt)),from:new Date(e.rendering.windowStartMs).toLocaleString(),to:new Date(e.rendering.windowEndMs).toLocaleString()});if(e.lastGeneratedAt===void 0)return J.t(`helpers.notificationRuleStatus.tlNever`,{camera:t});let r=new Date(e.lastGeneratedAt).toLocaleString(),i=e.lastArtifact;return i===void 0?J.t(`helpers.notificationRuleStatus.tlGone`,{camera:t,when:r}):J.t(`helpers.notificationRuleStatus.tlLast`,{camera:t,when:r,size:Ec(i.sizeBytes)})}function kc(e){return{windows:e.length,waiting:e.reduce((e,t)=>e+t.pending,0)}}var Ac=`nc.listPrunes`;function jc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Mc=new Set([`rule`,`timelapse`,`summary`]),Nc=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function Pc(e){return typeof e==`string`&&Mc.has(e)}function Fc(e){return typeof e==`string`&&Nc.has(e)}function Ic(e){return e===`device`||e===`target`}function Lc(e){if(!jc(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!Pc(t)||!Ic(r)||!Fc(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 Rc(e){return!jc(e)||!Array.isArray(e.prunes)?null:e.prunes.map(Lc).filter(e=>e!==null)}function zc(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 Bc(e,t){let n=t(e.at);return e.subjectKind===`device`?J.t(`helpers.notificationPrunes.lastDevice`,{when:n,subject:e.subject}):J.t(`helpers.notificationPrunes.lastTarget`,{when:n,subject:e.subject})}function Vc(e){return new Date(e).toLocaleDateString()}function Hc({kind:e,ruleId:t,enabled:n,updatedAt:r}){let o=D(),s=a({queryKey:[`pipelineAnalytics`,Ac],enabled:!n,staleTime:3e4,retry:!1,queryFn:async()=>Rc(await o.trpcClient.addons.custom.mutate({addonId:hc,action:Ac,input:{}}))}).data;if(s==null)return null;let c=zc(s,e,t,n,r);return c===null?null:i(`div`,{"data-testid":`nc-prune-banner`,className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-foreground`,children:[d(T,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),d(`span`,{children:Bc(c,Vc)})]})}var Uc=5e3;function Wc({status:e,now:t,name:n}){let{t:r}=Y();if(e.openWindows===null)return i(`p`,{className:`flex items-start gap-1.5`,children:[d(k,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),d(`span`,{"data-testid":`nc-grouped-status-headline`,children:r(`notificationRules.status.grouped.unknown`,{reason:e.reason??``,defaultValue:`Open windows unknown — {{reason}}`})})]});let a=e.openWindows,{windows:s,waiting:c}=kc(a);return i(o,{children:[i(`p`,{className:`flex items-start gap-1.5`,children:[d(k,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),d(`span`,{"data-testid":`nc-grouped-status-headline`,children:s===0?r(`notificationRules.status.grouped.none`,`No window open`):`${r(`notificationRules.status.grouped.windows`,{count:s,defaultValue_one:`{{count}} open window`,defaultValue_other:`{{count}} open windows`})} · ${r(`notificationRules.status.grouped.waiting`,{count:c,defaultValue:`{{count}} waiting`})}`})]}),a.map(e=>i(`p`,{className:`flex items-start gap-1.5`,children:[d(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),d(`span`,{children:r(`notificationRules.status.grouped.windowLine`,{camera:n(e.deviceId),members:e.members,pending:e.pending,seconds:Math.max(0,Math.ceil((e.closesAt-t)/1e3)),defaultValue:`{{camera}} · {{members}} in the window · {{pending}} waiting · closes within {{seconds}} s`})})]},e.windowKey))]})}function Gc({ruleId:e,cameraName:t}){let{t:n}=Y(),r=D(),s=a({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:Uc,queryFn:async()=>wc(await r.trpcClient.addons.custom.mutate({addonId:hc,action:gc,input:{ruleId:e}}))}).data;if(s==null||s.kind===`none`)return null;let c=Date.now(),l=e=>t?.(e)??n(`system.notificationRuleStatus.cameraFallback`,{deviceId:e});return i(`div`,{"data-testid":`nc-rule-status`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[s.kind===`occupancy`&&i(`p`,{className:`flex items-start gap-1.5`,children:[s.unavailable!==void 0||s.warning!==void 0?d(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):d(k,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),i(`span`,{children:[d(`span`,{className:`text-foreground`,children:l(s.deviceId)}),` —`,` `,Dc(s,c)]})]}),s.kind===`grouped`&&d(Wc,{status:s,now:c,name:l}),s.kind===`timelapse`&&i(o,{children:[s.devices.map(e=>i(`p`,{className:`flex items-start gap-1.5`,children:[d(k,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),i(`span`,{children:[Oc(e,l(e.deviceId),c),e.lastArtifact!==void 0&&i(o,{children:[` · `,d(`a`,{className:`text-primary hover:underline`,href:`/${e.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:n(`common.open`)})]})]})]},e.deviceId)),i(`p`,{className:`flex items-start gap-1.5`,children:[d(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),i(`span`,{children:[s.nextWindow===void 0?n(`system.notificationRuleStatus.noFurtherWindowOpensIn`,`No further window opens in the next nine days`):n(`system.notificationRuleStatus.nextWindowOpens`,`Next window opens {{value1}}`,{value1:new Date(s.nextWindow.startMs).toLocaleString()}),s.settleMs>0&&` · ${n(`system.notificationRuleStatus.settled`,{minutes:Math.round(s.settleMs/6e4)})}`]})]})]})]})}function Kc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Jc(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Yc(e){if(!Kc(e))return null;let t=qc(e,`ruleId`),n=qc(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=qc(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:qc(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Jc(e,`targetIds`)}}function Xc(e){if(!Kc(e))return null;let t=qc(e,`conditionId`),n=qc(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Zc(e){if(!Kc(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(!Kc(t))continue;let e=qc(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(!Kc(t))continue;let e=qc(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 Qc(e){if(!Kc(e))return null;let t=qc(e,`recordId`),n=qc(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=Yc(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Xc(t);e!==null&&i.push(e)}let a=qc(e,`droppedBy`),o=Zc(e.stateSummary);return{recordId:t,delivery:n,trigger:qc(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:qc(e,`still`)??`none`,notes:Jc(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function $c(e){if(e.stateSummary!==void 0)return el(e,e.stateSummary);if(e.droppedBy!==void 0)return J.t(`helpers.notificationRuleTest.dropped`,{reason:e.droppedBy});let t=e.outcomes[0];if(t===void 0)return J.t(`helpers.notificationRuleTest.notCandidate`,{trigger:e.trigger});if(!t.matched)return t.failedCondition===void 0?J.t(`helpers.notificationRuleTest.noMatchOwn`):J.t(`helpers.notificationRuleTest.noMatchCond`,{condition:t.failedCondition});if(t.enqueued===0)return J.t(`helpers.notificationRuleTest.matchedNoQueue`);let n=e.still===`live`?` ${J.t(`helpers.notificationRuleTest.stillLive`)}`:e.still===`unavailable`?` ${J.t(`helpers.notificationRuleTest.stillUnavailable`)}`:e.still===`unattachable`?` ${J.t(`helpers.notificationRuleTest.stillUnattachable`)}`:``;return J.t(`helpers.notificationRuleTest.matched`,{queued:t.enqueued,targets:t.targetIds.length,still:n})}function el(e,t){if(t.nothingToReport){let e=t.sections.map(e=>`${e.id}: ${e.status===`unavailable`?J.t(`helpers.notificationRuleTest.unavailable`):J.t(`helpers.notificationRuleTest.noneOpen`)}`).join(`, `);return J.t(`helpers.notificationRuleTest.nothingToReport`,{reads:e})}let n=t.rows.reduce((e,t)=>e+t.enqueued,0),r=e.outcomes[0]?.targetIds.length??0;if(n===0)return J.t(`helpers.notificationRuleTest.summaryNoQueue`);let i=t.rows.flatMap(e=>e.section===void 0?[]:[e.section]).map(e=>`${e} (${String(t.sections.find(t=>t.id===e)?.items??0)})`),a=t.split===`section`?` (${J.t(`helpers.notificationRuleTest.perCategory`,{sections:i.join(`, `)})})`:``;return J.t(`helpers.notificationRuleTest.summaryBuilt`,{queued:n,perCategory:a,targets:r})}e();function tl({ruleId:e,ruleName:t,fallbackDeviceId:n,variant:a=`icon`,showResult:s=!1}){let{t:c}=Y(),l=D(),[f,p]=r(null),[m,g]=r(null),_=u({mutationFn:async()=>Qc(await l.trpcClient.addons.custom.mutate({addonId:hc,action:_c,input:{ruleId:e,...n===void 0?{}:{deviceId:n}}})),onMutate:()=>{p(null),g(null)},onSuccess:e=>p(e),onError:e=>g(e instanceof Error?e.message:`The test could not be run.`)}),v=f===null?m===null?void 0:m:$c(f);return i(o,{children:[i(q,{size:`sm`,variant:a===`icon`?`ghost`:`outline`,type:`button`,disabled:_.isPending,onClick:()=>_.mutate(),title:v??c(`system.notificationRuleTestButton.testNowFiresThisRule`,`Test now — fires this rule and really sends the notification`),"aria-label":c(`system.notificationRuleTestButton.testNow`,`test {{ruleName}} now`,{ruleName:t}),"data-testid":`nc-rule-test-now`,children:[_.isPending?d(E,{className:`h-3.5 w-3.5 animate-spin`}):d(Ke,{className:`h-3.5 w-3.5`}),a===`full`&&c(`system.notificationRuleTestButton.testNow2`,`Test now`)]}),s&&m!==null&&d(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:m}),s&&f!==null&&i(`div`,{"data-testid":`nc-rule-test-result`,className:`mt-2 space-y-1 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[d(`p`,{className:`text-foreground`,children:$c(f)}),f.planNotes.map(e=>i(`p`,{className:`flex gap-1.5`,children:[d(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),d(`span`,{children:e.note})]},e.conditionId)),f.notes.map(e=>i(`p`,{children:[`· `,e]},e))]})]})}e();var nl=[`notificationRules`,`listSnoozes`],rl=3e4;function il(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function al(e){if(e===0)return J.t(`system.notificationSnoozes.remEnding`);if(e<60)return J.t(`system.notificationSnoozes.remMin`,{count:e});let t=Math.floor(e/60),n=e%60;return n===0?J.t(`system.notificationSnoozes.remHour`,{count:t}):J.t(`system.notificationSnoozes.remHourMin`,{hours:t,minutes:n})}function ol({rules:e}){let{t}=Y(),r=D(),o=s(),c=a({queryKey:nl,refetchInterval:rl,queryFn:async()=>(await r.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),l=u({mutationFn:e=>r.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>o.invalidateQueries({queryKey:nl})}),f=n(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),p=Date.now(),m=(c.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return i(Ot,{className:`p-4`,children:[i(`div`,{className:`flex items-center gap-2 mb-3`,children:[d(Ve,{className:`h-4 w-4 text-foreground-subtle`}),d(`h3`,{className:`text-sm font-medium text-foreground`,children:t(`system.notificationSnoozes.silencedRightNow`,`Silenced right now`)})]}),m.length===0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`system.notificationSnoozes.nothingIsSilencedASnooze`,`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`)}),d(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:m.map(e=>i(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`min-w-0`,children:[i(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:f.get(e.ruleId??``)??`A rule`}),e.global&&d(G,{variant:`warning`,className:`text-[10px]`,children:t(`common.everyone`)}),e.classes!==void 0&&e.classes.length>0&&d(G,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&d(G,{variant:`default`,className:`text-[10px]`,children:t(`system.notificationSnoozes.noSummary`,`no summary`)})]}),d(`span`,{className:`text-[10px] text-foreground-subtle`,children:t(`system.notificationSnoozes.setBy`,{user:e.userId,remaining:al(il(e,p))})})]}),d(q,{size:`sm`,variant:`outline`,disabled:l.isPending,onClick:()=>l.mutate(e.id),children:t(`system.notificationSnoozes.endNow`,`End now`)})]},e.id))})]})}var Q=`block text-[11px] font-medium text-foreground mb-1`,sl=`mt-1 text-[10px] text-foreground-subtle`;function cl({title:e,hint:t,children:n}){return i(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),d(`div`,{className:`space-y-3`,children:n})]})}function ll({problems:e,testId:t=`digest-problems`}){let{t:n}=Y();return e.length===0?null:i(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":t,children:[i(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[d(h,{className:`h-3.5 w-3.5`}),n(`system.notificationDigestFields.thisRuleCouldNeverProduce`,`This rule could never produce anything, so it cannot be saved:`)]}),d(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>d(`li`,{children:e},e))})]})}function ul({warnings:e,testId:t=`digest-warnings`}){let{t:n}=Y();return e.length===0?null:i(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":t,children:[i(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[d(T,{className:`h-3.5 w-3.5`}),n(`system.notificationDigestFields.worthKnowing`,`Worth knowing:`)]}),d(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>d(`li`,{children:e},e))})]})}function dl({cameras:e,value:t,onChange:n,fleet:r,hint:a}){return i(`div`,{className:`space-y-1`,children:[d(et,{devices:e,listState:r.state,fleet:r,value:t,onChange:n,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),a!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function fl(e){let{t}=Y();return d(Ct,{...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 pl({label:e,value:t,onChange:n,min:r,max:a,step:o,hint:s,emptyPlaceholder:c,testId:l,disabled:u=!1}){return i(`div`,{children:[d(`label`,{className:Q,children:e}),d(W,{type:`number`,value:t===void 0?``:String(t),disabled:u,...r===void 0?{}:{min:r},...a===void 0?{}:{max:a},...o===void 0?{}:{step:o},...c===void 0?{}:{placeholder:c},...l===void 0?{}:{"data-testid":l},onChange:e=>{let t=e.target.value.trim();if(t.length===0){n(void 0);return}let r=Number(t);Number.isFinite(r)&&n(r)}}),s!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function ml({label:e,checked:t,onChange:n,hint:r,testId:a}){return i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(xt,{checked:t,onCheckedChange:n,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),r!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:r})]})}function hl({title:e,body:t,onTitleChange:n,onBodyChange:r,family:a,testIdPrefix:o}){let{t:s}=Y(),c=go(),l=e=>c.data?fo(c.data,{family:a,field:e}):void 0;return i(`div`,{className:`space-y-2`,children:[d(xo,{label:s(`system.notificationDigestFields.notificationTitle`,`Notification title`),value:e,onChange:n,vars:l(`title`),testId:`${o}-title`}),d(xo,{label:s(`system.notificationDigestFields.notificationBody`,`Notification body`),value:t,onChange:r,vars:l(`body`),multiline:!0,testId:`${o}-body`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`system.notificationDigestFields.leaveBothBlankToUse`,`Leave both blank to use the hub's own wording (editable on the Texts tab).`)}),d(So,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function gl({open:e,ruleName:t,windowDescription:n,targetDescription:r,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){let{t:u}=Y();return e?d(dt,{open:!0,onOpenChange:e=>!e&&s(),children:d(vt,{width:`sm`,children:i(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[i(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[d(Ke,{className:`h-4 w-4 text-warning`}),u(`system.notificationDigestFields.sendARealNotificationNow`,`Send a real notification now?`)]}),d(`p`,{className:`text-xs text-foreground-subtle`,children:u(`system.notificationDigestFields.confirmSend`,{rule:t,window:n,target:r})}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`system.notificationDigestFields.itDoesNotConsumeThe`,`It does not consume the schedule: the next scheduled run still happens.`)}),c,i(`div`,{className:`flex justify-end gap-2`,children:[d(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:u(`common.cancel`,`Cancel`)}),d(q,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?u(`system.notificationDigestFields.sending`,`Sending…`):u(`system.notificationDigestFields.produceAndSend`,`Produce and send`)})]})]})})}):null}function _l(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 vl=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function yl(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function bl(e){let t=e.windows[0];if(t===void 0)return J.t(`helpers.notificationDigest.noWindow`);let n=t.days.toSorted((e,t)=>e-t).map(e=>vl[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${yl(t.startMinute)}–${yl(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function xl(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return J.t(`helpers.notificationDigest.ago`,{duration:_l(Math.round(r/1e3))})}function Sl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cl(e){return Array.isArray(e)?`[${e.map(Cl).join(`,`)}]`:Sl(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${Cl(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function wl(e,t){return Cl(e)===Cl(t)}function Tl(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,El=`nc.getTexts`,Dl=`nc.setLanguage`,Ol=`nc.setTextOverrides`,kl={en:`English`,it:`Italiano`};function Al(e){return e===`en`||e===`it`}function jl(e){return e===`override`||e===`shipped`||e===`fallback`}function Ml(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nl(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 Pl(e){if(!Ml(e))return null;let{key:t,shipped:n,shippedLanguage:r,override:i,effective:a,source:o}=e;if(typeof t!=`string`||t.length===0||typeof n!=`string`||typeof a!=`string`||!Al(r)||!jl(o)||i!==null&&typeof i!=`string`)return null;let s=Nl(e.placeholders),c=Nl(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 Fl(e){if(!Ml(e))return null;let{language:t,activeLanguage:n}=e;if(!Al(t)||!Al(n))return null;let r=Nl(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Al(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=Pl(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Il(e,t){return t.get(e.key)??e.override??e.shipped}function Ll(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 Rl(e,t){return Object.keys(Ll(e,t)).length}function zl(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 Bl(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Vl(e){return e.pluralCategories.length===0?null:J.t(`helpers.notificationTexts.pluralWarning`,{categories:e.pluralCategories.join(`, `)})}var Hl=[`notificationCalendarEvents`,`list`],Ul=`nc.listCalendarEventsRules`,Wl=`nc.upsertCalendarEventsRule`,Gl=`nc.deleteCalendarEventsRule`,Kl=Le({timezone:Ie().min(1),windows:ze(Le({days:ze(Pe().int().min(0).max(6)).min(1),startMinute:Pe().int().min(0).max(1439),endMinute:Pe().int().min(0).max(1439)})).min(1),invert:Be().optional()}),ql=Le({targetId:Ie().min(1),params:Re(Ie(),Fe()).optional()}),Jl=Le({rules:ze(Le({id:Ie().min(1),name:Ie().min(1),enabled:Be(),schedule:Kl,calendars:ze(Ie().min(1)).max(64).optional(),calendarsExclude:ze(Ie().min(1)).max(64).optional(),horizonDays:Pe().int(),deliverEmpty:Be(),targets:ze(ql).min(1),template:Le({title:Ie().optional(),body:Ie().optional()}).optional(),priority:Pe().int(),generatedAt:Pe().optional(),readOnly:Be().optional()}))});function Yl(e){let t=Jl.safeParse(e);return t.success?t.data.rules:null}function Xl(e){return e.readOnly!==!0}var Zl=[{key:`basics`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_basics`)}},{key:`schedule`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_schedule`)}},{key:`calendars`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_calendars`)}},{key:`targets`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_targets`)}},{key:`template`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_template`)}}],Ql=`basics`;function $l(){return se([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function eu(e){let t=re(e);if(t===null||t.length===0)return bl(e);let n=t[0];if(n===void 0)return bl(e);let r=String(Math.floor(n.minute/60)).padStart(2,`0`),i=String(n.minute%60).padStart(2,`0`),a=t.length>1?` +${t.length-1}`:``;return J.t(`helpers.notificationCalendarEvents.scheduleAt`,{time:`${r}:${i}`,more:a})}function tu(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:$l(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``}}function nu(e){return{name:e.name,enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,calendars:e.calendars??[],calendarsExclude:e.calendarsExclude??[],targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``}}function ru(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){let t=e.targetIds.map(e=>({targetId:e}));return{name:e.name.trim(),enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,...e.calendars.length>0?{calendars:[...e.calendars]}:{},...e.calendarsExclude.length>0&&e.calendars.length===0?{calendarsExclude:[...e.calendarsExclude]}:{},targets:t,...e.templateTitle.trim().length>0||e.templateBody.trim().length>0?{template:{...e.templateTitle.trim().length>0?{title:e.templateTitle.trim()}:{},...e.templateBody.trim().length>0?{body:e.templateBody.trim()}:{}}}:{}}}function au(e,t){let n=iu(e);return{...n,calendars:e.calendars.length===0&&(t.calendars?.length??0)>0?null:n.calendars,calendarsExclude:e.calendarsExclude.length===0&&(t.calendarsExclude?.length??0)>0?null:n.calendarsExclude,template:e.templateTitle.trim().length===0&&e.templateBody.trim().length===0&&t.template!==void 0?null:n.template}}function ou(e){return J.t(`helpers.notificationCalendarEvents.horizon`,{count:e})}function su(e){return e.calendars!==void 0&&e.calendars.length>0?J.t(`helpers.notificationCalendarEvents.calendars`,{count:e.calendars.length}):e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?J.t(`helpers.notificationCalendarEvents.allExcept`,{count:e.calendarsExclude.length}):J.t(`helpers.notificationCalendarEvents.allCalendars`)}e();function cu({rule:e,targets:t,onSaved:n,onCancel:a}){let{t:o}=Y(),s=D(),c=ut(),[l,f]=r(()=>e===null?tu():nu(e)),[p,m]=r(()=>Dr(e===null?void 0:e.calendars,e===null?void 0:e.calendarsExclude)),[h,g]=r(Ql),[_,v]=r(null),y=e=>f(t=>({...t,...e})),b=u({mutationFn:async()=>{let t=qn(p),n={...l,calendars:t.include??[],calendarsExclude:t.exclude??[]};if(!ru(n))throw Error(`Name, at least one target, and a schedule are required`);let r=e===null?{rule:iu(n)}:{ruleId:e.id,patch:au(n,e)};await s.trpcClient.addons.custom.mutate({addonId:$,action:Wl,input:r})},onSuccess:()=>n(),onError:e=>{v(e instanceof Error?e.message:String(e))}}),x=(c.data??[]).map(e=>({id:e.id,name:e.name}));return d(dt,{open:!0,onOpenChange:e=>!e&&a(),children:i(vt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendar-events-editor`,children:[i(`div`,{className:`mb-3 flex shrink-0 items-center justify-between gap-2 pr-10`,children:[i(`div`,{className:`flex min-w-0 items-center gap-2`,children:[d(He,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:e===null?o(`system.notificationCalendarEventsEditor.newCalendarEvents`,`New calendar events`):l.name})]}),d(q,{size:`sm`,type:`button`,disabled:b.isPending,onClick:()=>{v(null),b.mutateAsync()},"data-testid":`calendar-events-save`,children:b.isPending?d(E,{className:`h-3.5 w-3.5 animate-spin`}):o(`common.save`,`Save`)})]}),i(Ze,{value:h,onValueChange:e=>{let t=Zl.find(t=>t.key===e);t!==void 0&&g(t.key)},children:[d(St,{className:`mb-3`,children:Zl.map(e=>d(Je,{value:e.key,children:e.label},e.key))}),i(qe,{className:`space-y-4 pr-1`,children:[_===null?null:d(`p`,{className:`text-sm text-destructive`,children:_}),d(U,{value:`basics`,className:`space-y-3`,children:i(cl,{title:o(`system.notificationCalendarEventsEditor.basics`,`Basics`),children:[i(`label`,{className:`block text-sm`,children:[o(`system.notificationCalendarEventsEditor.name`,`Name`),d(W,{className:`mt-1`,value:l.name,onChange:e=>y({name:e.target.value}),"data-testid":`calendar-events-name`})]}),d(pl,{label:o(`system.notificationCalendarEventsEditor.horizonDays`,`Horizon (days)`),value:l.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&y({horizonDays:e})}}),d(pl,{label:o(`system.notificationCalendarEventsEditor.priority`,`Priority`),value:l.priority,min:1,max:5,onChange:e=>{e!==void 0&&y({priority:e})}}),d(ml,{label:o(`system.notificationCalendarEventsEditor.enabled`,`Enabled`),checked:l.enabled,onChange:e=>y({enabled:e})}),d(ml,{label:o(`system.notificationCalendarEventsEditor.deliverWhenEmpty`,`Deliver when empty`),checked:l.deliverEmpty,onChange:e=>y({deliverEmpty:e})})]})}),d(U,{value:`schedule`,className:`space-y-3`,children:i(cl,{title:o(`system.notificationCalendarEventsEditor.schedule`,`Schedule`),children:[d(jr,{mode:`times`,value:l.schedule,onChange:e=>y({schedule:e})}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`system.notificationCalendarEventsEditor.oneSendTimePerRow`,`One send time per row. The digest fires at that minute.`)})]})}),d(U,{value:`calendars`,className:`space-y-3`,children:d(cl,{title:o(`system.notificationCalendarEventsEditor.calendars`,`Calendars`),children:d(Zo,{draft:p,onChange:m,exceptOffered:!0,plural:`calendars`,describe:e=>x.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>d(et,{devices:x,listState:c.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),d(U,{value:`targets`,className:`space-y-3`,children:d(cl,{title:o(`system.notificationCalendarEventsEditor.targets`,`Targets`),children:d(fl,{targets:t,value:l.targetIds,onChange:e=>y({targetIds:e})})})}),d(U,{value:`template`,className:`space-y-3`,children:i(cl,{title:o(`system.notificationCalendarEventsEditor.template`,`Template`),children:[i(`p`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationCalendarEventsEditor.optionalLeaveBlankForThe`,`Optional. Leave blank for the default digest body (tomorrow highlighted, then later days). Variables:`),` `,o(`system.notificationCalendarEventsEditor.templateVars`,{ruleVar:`{{rule}}`,countVar:`{{count}}`,horizonVar:`{{horizonDays}}`,eventsVar:`{{events}}`})]}),i(`label`,{className:`block text-sm`,children:[o(`system.notificationCalendarEventsEditor.title`,`Title`),d(W,{className:`mt-1`,value:l.templateTitle,onChange:e=>y({templateTitle:e.target.value})})]}),i(`label`,{className:`block text-sm`,children:[o(`system.notificationCalendarEventsEditor.body`,`Body`),d(`textarea`,{className:`mt-1 min-h-[8rem] w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:l.templateBody,onChange:e=>y({templateBody:e.target.value})})]})]})})]})]})]})})}var lu=`nc.listSummaryRules`,uu=`nc.upsertSummaryRule`,du=`nc.deleteSummaryRule`,fu=`nc.testSummaryRule`,pu=3600,mu=86400,hu=3600,gu=3600,_u=3*36e5,vu=[`importance`,`recency`,`dwell`],yu={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},bu=[`none`,`tiles`,`all`],xu=`none`,Su={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},Cu=[`en`,`it`],wu=[`deliver-without-text`,`skip`],Tu=2048,Eu=2e3;function Du(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Ou(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ku(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 Au(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 ju(e){if(e!==void 0)return typeof e==`string`?e:null}function Mu(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function Nu(e){return vu.some(t=>t===e)}function Pu(e){return e===void 0?xu:bu.find(t=>t===e)??null}function Fu(e){if(!Ou(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Ou(n))return null;let e=ku(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=ju(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 Iu(e){if(!Ou(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=Fu(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 Lu(e){if(e==null)return;if(!Ou(e))return null;let t=e.classes===void 0?void 0:Au(e.classes),n=e.classesExclude===void 0?void 0:Au(e.classesExclude),r=e.zones===void 0?void 0:Au(e.zones);if(t===null||n===null||r===null)return null;let i=Mu(e.minImportance),a=Mu(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 Ru(e){if(e==null)return;if(!Ou(e))return null;let t=ju(e.title),n=ju(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function zu(e){return Cu.some(t=>t===e)}function Bu(e){return wu.some(t=>t===e)}function Vu(e){if(e==null)return;if(!Ou(e)||typeof e.enabled!=`boolean`)return null;let t=ju(e.profileId),n=ju(e.prompt);if(t===null||n===null)return null;let r=Mu(e.maxImagePx),i=Mu(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!zu(a))return null;let o=e.onFailure;return o!==void 0&&!Bu(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 Hu(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Ou(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Ou(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function Uu(e){if(!Ou(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`||!Nu(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=ku(e.deviceIds),u=Iu(e.window),d=Hu(e.targets);if(l===null||u===null||d===null)return null;let f=Lu(e.filters),p=Ru(e.template);if(f===null||p===null)return null;let m=ju(e.captionText),h=Mu(e.generatedAt),g=Mu(e.updatedAt);if(m===null||h===null||g===null)return null;let _=Pu(e.captions);if(_===null)return null;let v=Vu(e.ai);return v===null?null:{id:t,name:n,enabled:r,deviceIds:l,window:u,...f===void 0?{}:{filters:f},maxTiles:i,maxAiImages:a,rank:o,barrierSeconds:s,targets:d,...p===void 0?{}:{template:p},captions:_,...m===void 0?{}:{captionText:m},deliverEmpty:c,priority:e.priority,...h===void 0?{}:{generatedAt:h},...g===void 0?{}:{updatedAt:g},readOnly:e.readOnly===!0,...v===void 0?{}:{ai:v}}}function Wu(e){if(!Ou(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=Uu(n);if(e===null)return null;t.push(e)}return t}function Gu(e){if(!Ou(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=Mu(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=Mu(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=ju(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 Ku(){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:xu,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function qu(e){let t=Ku(),n=e.window.kind===`motion`?e.window:null;return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],windowKind:e.window.kind,schedule:e.window.kind===`schedule`?e.window.schedule:void 0,quietSeconds:n?.quietSeconds??t.quietSeconds,maxWindowSeconds:n?.maxWindowSeconds??t.maxWindowSeconds,classes:[...e.filters?.classes??[]],classesExclude:[...e.filters?.classesExclude??[]],zones:[...e.filters?.zones??[]],minImportance:e.filters?.minImportance,minDwellSeconds:e.filters?.minDwellSeconds,includeStationary:e.filters?.includeStationary===!0,maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,mosaicCaptions:e.captions,captionText:e.captionText??``,deliverEmpty:e.deliverEmpty,priority:e.priority,aiEnabled:e.ai?.enabled??t.aiEnabled,aiProfileId:e.ai?.profileId??``,aiPrompt:e.ai?.prompt??``,aiLanguage:e.ai?.language??``,aiMaxImagePx:e.ai?.maxImagePx,aiTimeoutSeconds:e.ai?.timeoutMs===void 0?void 0:Math.round(e.ai.timeoutMs/1e3),aiOnFailure:e.ai?.onFailure??t.aiOnFailure}}function Ju(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Yu(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 Xu(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 Zu(e){return Tl(e.targetIds)}function Qu(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 $u(e){let t=Yu(e),n=Xu(e),r=Qu(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:Ju(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Zu(e),...n===void 0?{}:{template:n},captions:e.mosaicCaptions,...i.length>0?{captionText:i}:{},deliverEmpty:e.deliverEmpty,priority:e.priority,...r===void 0?{}:{ai:r}}}function ed(e,t){let n=$u(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),wl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),wl(n.window,t.window)||(r.window=n.window),wl(n.filters,t.filters)||(r.filters=n.filters??null),n.maxTiles!==t.maxTiles&&(r.maxTiles=n.maxTiles),n.maxAiImages!==t.maxAiImages&&(r.maxAiImages=n.maxAiImages),n.rank!==t.rank&&(r.rank=n.rank),n.barrierSeconds!==t.barrierSeconds&&(r.barrierSeconds=n.barrierSeconds),wl(n.targets,t.targets)||(r.targets=n.targets),wl(n.template,t.template)||(r.template=n.template??null),n.captions!==t.captions&&(r.captions=n.captions),(n.captionText??``)!==(t.captionText??``)&&(r.captionText=n.captionText??``),n.deliverEmpty!==t.deliverEmpty&&(r.deliverEmpty=n.deliverEmpty),n.priority!==t.priority&&(r.priority=n.priority),wl(n.ai,t.ai)||(r.ai=n.ai??null),r}function td(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 ${pu}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${mu}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 ${hu}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 ${gu}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 ${Eu} 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 ${Tu} 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 nd(e){return td(e).length===0}function rd(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 id=[{key:`rule`,get label(){return J.t(`helpers.notificationSummaries.tab_rule`)},fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,get label(){return J.t(`helpers.notificationSummaries.tab_window`)},fields:[`windowKind`,`schedule`,`quietSeconds`,`maxWindowSeconds`,`barrierSeconds`]},{key:`content`,get label(){return J.t(`helpers.notificationSummaries.tab_content`)},fields:[`classes`,`classesExclude`,`zones`,`minImportance`,`minDwellSeconds`,`includeStationary`]},{key:`mosaic`,get label(){return J.t(`helpers.notificationSummaries.tab_mosaic`)},fields:[`maxTiles`,`rank`,`mosaicCaptions`,`captionText`]},{key:`ai`,label:`AI`,fields:[`aiEnabled`,`aiProfileId`,`aiPrompt`,`aiLanguage`,`aiMaxImagePx`,`aiTimeoutSeconds`,`aiOnFailure`,`maxAiImages`]},{key:`delivery`,get label(){return J.t(`helpers.notificationSummaries.tab_delivery`)},fields:[`targetIds`,`priority`,`deliverEmpty`,`templateTitle`,`templateBody`]}],ad=`rule`;function od(e){return id.find(t=>t.key===e)?.key}function sd(e){return e.kind===`motion`?J.t(`helpers.notificationSummaries.winMotion`,{quiet:_l(e.quietSeconds),max:_l(e.maxWindowSeconds)}):e.kind===`unsupported`?J.t(`helpers.notificationSummaries.winUnsupported`,{raw:e.raw}):J.t(`helpers.notificationSummaries.winSchedule`,{schedule:bl(e.schedule)})}function cd(e,t){return xl(e,t,`Never run`)}function ld(e){if(e===void 0)return J.t(`helpers.notificationSummaries.allPassages`);let t=[];return e.classes!==void 0&&e.classes.length>0&&t.push(e.classes.join(`, `)),e.classesExclude!==void 0&&e.classesExclude.length>0&&t.push(J.t(`helpers.notificationSummaries.filterNot`,{classes:e.classesExclude.join(`, `)})),e.zones!==void 0&&e.zones.length>0&&t.push(J.t(`helpers.notificationSummaries.filterZones`,{count:e.zones.length})),e.minImportance!==void 0&&t.push(J.t(`helpers.notificationSummaries.filterImportance`,{value:e.minImportance})),e.minDwellSeconds!==void 0&&t.push(J.t(`helpers.notificationSummaries.filterStay`,{value:_l(e.minDwellSeconds)})),e.includeStationary===!0&&t.push(J.t(`helpers.notificationSummaries.filterParked`)),t.length===0?J.t(`helpers.notificationSummaries.allPassages`):t.join(` · `)}function ud(e){return{windowStartMs:e-_u,windowEndMs:e}}e();var dd={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},fd={en:`English`,it:`Italiano`};function pd(e){return vu.find(t=>t===e)}function md(e){return bu.find(t=>t===e)}function hd(e){return Cu.find(t=>t===e)??``}function gd(e){return wu.find(t=>t===e)}function _d({rule:e,cameras:t,fleet:o,targets:s,taxonomy:c,onSaved:l,onCancel:f}){let{t:p}=Y(),m=D(),[h,g]=r(()=>e===null?Ku():qu(e)),[_,v]=r(null),[y,b]=r(e!==null),[x,S]=r(ad),C=e=>g(t=>({...t,...e})),w=n(()=>{let e=Me(`occupancy`,c);return e===null?[]:e.groups.flatMap(e=>e.options)},[c]),{options:T,loading:O}=Nt(h.deviceIds,t.map(e=>({id:e.id,name:e.name}))),k=a({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>m.trpcClient.llm.listProfiles.query({}),retry:!1}),A=(k.data??[]).filter(e=>e.supportsVision),j=u({mutationFn:async()=>{let t=e===null?{rule:$u(h)}:{ruleId:e.id,patch:ed(h,e)};await m.trpcClient.addons.custom.mutate({addonId:$,action:uu,input:t})},onSuccess:l,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),M=go(),N=M.data?fo(M.data,{family:`summary`,field:`captionText`}):void 0,P=h.mosaicCaptions===`all`,F=td(h),I=rd(h),ee=id.some(e=>e.key===x)?x:ad;return d(dt,{open:!0,onOpenChange:e=>!e&&f(),children:i(vt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[d(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:i(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[d(We,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:e===null?p(`system.notificationSummaryEditor.newSummary`,`New summary`):p(`system.notificationSummaryEditor.edit`,`Edit {{name}}`,{name:e.name})})]})}),_!==null&&d(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),i(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&d(Hc,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),y?d(ll,{problems:F,testId:`summary-problems`}):null,d(ul,{warnings:I,testId:`summary-warnings`})]}),i(Ze,{value:ee,onValueChange:e=>S(od(e)??x),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[d(St,{className:`mb-3 shrink-0`,children:id.map(e=>d(Je,{value:e.key,children:e.label},e.key))}),i(qe,{className:`pr-1`,children:[i(U,{value:`rule`,className:`space-y-3`,children:[d(cl,{title:p(`system.notificationSummaryEditor.whatItIs`,`What it is`),hint:p(`system.notificationSummaryEditor.oneWindowOnePictureThe`,`One window, one picture: the best shot of every track the window held, laid out as one mosaic and delivered once.`),children:i(`div`,{className:`flex items-end gap-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.name`,`Name`)}),d(W,{value:h.name,onChange:e=>C({name:e.target.value}),placeholder:p(`system.notificationSummaryEditor.eGOvernightSweep`,`e.g. Overnight sweep`),"data-testid":`summary-name`})]}),d(`div`,{className:`pb-1.5`,children:d(ml,{label:p(`system.notificationSummaryEditor.enabled`,`Enabled`),checked:h.enabled,onChange:e=>C({enabled:e}),testId:`summary-enabled`})})]})}),d(cl,{title:p(`system.notificationSummaryEditor.cameras`,`Cameras`),hint:p(`system.notificationSummaryEditor.everyCameraInTheDigest`,`Every camera in the digest gets at least one tile when it contributed anything — a digest in which two of six cameras never appear is not multi-camera.`),children:d(dl,{cameras:t,value:h.deviceIds,fleet:o,onChange:e=>C({deviceIds:e}),hint:p(`system.notificationSummaryEditor.theFirstCameraSelectedOwns`,`The first camera selected owns the delivered notification.`)})})]}),d(U,{value:`window`,className:`space-y-3`,children:i(cl,{title:p(`system.notificationSummaryEditor.whenTheWindowCloses`,`When the window closes`),children:[i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.window`,`Window`)}),d(H,{value:h.windowKind,options:[{value:`motion`,label:p(`system.notificationSummaryEditor.motionOpenedAndClosedBy`,`Motion — opened and closed by activity`)},{value:`schedule`,label:p(`system.notificationSummaryEditor.scheduleFixedWeeklyWindows`,`Schedule — fixed weekly windows`)}],onChange:e=>C({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),h.windowKind===`motion`?i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(pl,{label:p(`system.notificationSummaryEditor.quietPeriodSeconds`,`Quiet period (seconds)`),value:h.quietSeconds,min:30,max:pu,onChange:e=>C({quietSeconds:e??0}),hint:p(`system.notificationSummaryEditor.theWindowOpensOnThe`,`The window opens on the first motion on any of these cameras and stays open while more arrives. This much silence closes it.`),testId:`summary-quiet`}),d(pl,{label:p(`system.notificationSummaryEditor.longestWindowSeconds`,`Longest window (seconds)`),value:h.maxWindowSeconds,min:60,max:mu,onChange:e=>C({maxWindowSeconds:e??0}),hint:p(`system.notificationSummaryEditor.aPermanentlyBusyDrivewayWould`,`A permanently busy driveway would otherwise never deliver. At this bound the window closes with whatever it holds.`),testId:`summary-max-window`})]}):i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.weeklyWindows`,`Weekly windows`)}),d(jr,{value:h.schedule,onChange:e=>C({schedule:e})}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.theDigestIsProducedWhen`,`The digest is produced when a window CLOSES, and covers exactly that window. The first one is the first window that closes after you save — nothing is backfilled.`)})]}),d(pl,{label:p(`system.notificationSummaryEditor.waitForOpenTracksSeconds`,`Wait for open tracks (seconds)`),value:h.barrierSeconds,min:0,max:hu,onChange:e=>C({barrierSeconds:e??0}),hint:p(`system.notificationSummaryEditor.aTrackSBestShot`,`A track's best shot is written when the track ENDS. Rendering the instant the window closes would show every still-moving subject with no picture. 0 disables the wait.`),testId:`summary-barrier`})]})}),d(U,{value:`content`,className:`space-y-3`,children:i(cl,{title:p(`system.notificationSummaryEditor.whatGoesIn`,`What goes in`),hint:p(`system.notificationSummaryEditor.evaluatedOnTracksOnePassage`,`Evaluated on tracks: one passage is one tile.`),children:[i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.classes`,`Classes`)}),d(Mn,{options:w,value:h.classes,onChange:e=>C({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.emptyEveryClassOnlyThe`,`Empty = every class. Only the macro classes are offered: a digest matches the class stored on the track, and tracks store macros — a sub-type would match nothing, forever.`)})]}),i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.excludedClasses`,`Excluded classes`)}),d(Mn,{options:w,value:h.classesExclude,onChange:e=>C({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.zones`,`Zones`)}),d(Mn,{options:T,value:h.zones,onChange:e=>C({zones:e}),loading:O,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.zonesAreScopedPerCamera`,`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`)})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(pl,{label:p(`system.notificationSummaryEditor.minimumImportance`,`Minimum importance`),value:h.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>C({minImportance:e}),hint:p(`system.notificationSummaryEditor.thePipelineSOwnScore`,`The pipeline's own score, 0–1. Empty keeps everything.`),testId:`summary-min-importance`}),d(pl,{label:p(`system.notificationSummaryEditor.minimumStaySeconds`,`Minimum stay (seconds)`),value:h.minDwellSeconds,min:0,max:gu,emptyPlaceholder:`any`,onChange:e=>C({minDwellSeconds:e}),hint:p(`system.notificationSummaryEditor.dropsThePassagesTooBrief`,`Drops the passages too brief to be worth a tile.`),testId:`summary-min-dwell`})]}),d(ml,{label:p(`system.notificationSummaryEditor.includeParkedObjects`,`Include parked objects`),checked:h.includeStationary,onChange:e=>C({includeStationary:e}),hint:p(`system.notificationSummaryEditor.offByDefaultACar`,`Off by default. A car left in the drive is tracked until it is recognised as parked, and it stays parked for as long as it is there — with this on, a digest fills up with the same stationary object instead of the passages. Parked objects remain on the Events page either way.`),testId:`summary-include-stationary`})]})}),d(U,{value:`mosaic`,className:`space-y-3`,children:i(cl,{title:p(`system.notificationSummaryEditor.theMosaic`,`The mosaic`),children:[i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(pl,{label:p(`system.notificationSummaryEditor.tiles`,`Tiles`),value:h.maxTiles,min:1,max:24,onChange:e=>C({maxTiles:e??1}),hint:p(`system.notificationSummaryEditor.9A33Grid`,`9 (a 3×3 grid) is the most a phone lock-screen thumbnail can carry and still be read.`),testId:`summary-max-tiles`}),i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.whenThereAreMoreTracks`,`When there are more tracks than tiles`)}),d(H,{value:h.rank,options:vu.map(e=>({value:e,label:yu[e]})),onChange:e=>{let t=pd(e.target.value);t!==void 0&&C({rank:t})},"data-testid":`summary-rank`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.everyContributingCameraKeepsIts`,`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`)})]})]}),i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.textOnTheMosaic`,`Text on the mosaic`)}),d(H,{value:h.mosaicCaptions,options:bu.map(e=>({value:e,label:Su[e]})),onChange:e=>{let t=md(e.target.value);t!==void 0&&C({mosaicCaptions:t})},"data-testid":`summary-captions`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.imagesOnlyIsTheDefault`,`Images only is the default, and it is what a rule with nothing set here does. Anything drawn is burnt into the picture for good — a label covers the bottom of the tile, which is where feet, wheels and parcels are, and a caption from a detection that was wrong cannot be un-drawn. Nothing downstream needs the words: the written summary reads the frames themselves and is told the camera, the class and the time in its prompt.`)})]}),i(`div`,{children:[d(xo,{label:p(`system.notificationSummaryEditor.captionBurnedOntoTheMosaic`,`Caption burned onto the mosaic`),value:h.captionText,disabled:!P,onChange:e=>C({captionText:e}),placeholder:p(`system.notificationSummaryEditor.leaveEmptyForNoCaption`,`Leave empty for no caption`),vars:N,testId:`summary-caption`}),d(`p`,{className:sl,children:P?p(`system.notificationSummaryEditor.acrossTheTopBand`,`Across the top band.`):p(`system.notificationSummaryEditor.onlyDrawnWithTileLabels`,`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`)})]})]})}),d(U,{value:`ai`,className:`space-y-3`,children:i(cl,{title:p(`system.notificationSummaryEditor.writtenSummary`,`Written summary`),hint:p(`system.notificationSummaryEditor.oneVisionCallOverThe`,`One vision call over the window's best frames TOGETHER, so the answer is an account of what happened rather than a list of pictures. The sentence goes in the notification body.`),children:[d(ml,{label:p(`system.notificationSummaryEditor.haveAModelDescribeThe`,`Have a model describe the window`),checked:h.aiEnabled,onChange:e=>C({aiEnabled:e}),hint:p(`system.notificationSummaryEditor.offByDefaultTheMosaic`,`Off by default. The mosaic and the counts are delivered either way.`),testId:`summary-ai-enabled`}),!h.aiEnabled&&d(`p`,{className:`rounded-md border border-border bg-surface px-2.5 py-1.5 text-[10px] text-foreground-muted`,"data-testid":`summary-ai-off-note`,children:p(`system.notificationSummaryEditor.theSwitchAboveIsOff`,`The switch above is off, so nothing below it can be edited. Everything you already set is kept — turning it on hands the fields back exactly as you left them.`)}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.visionProfile`,`Vision profile`)}),d(H,{value:h.aiProfileId,disabled:!h.aiEnabled,options:[{value:``,label:p(`system.notificationSummaryEditor.theHubSDefaultVision`,`The hub's default vision profile`)},...A.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>C({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),d(`p`,{className:sl,children:k.isError?p(`system.notificationSummaryEditor.thisHubDidNotAnswer`,`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`):A.length===0?p(`system.notificationSummaryEditor.noVisionCapableProfileOn`,`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`):p(`system.notificationSummaryEditor.onlyVisionCapableProfilesAre`,`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`)})]}),i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.answerIn`,`Answer in`)}),d(H,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:p(`system.notificationSummaryEditor.donTAskForA`,`Don’t ask for a language`)},...Cu.map(e=>({value:e,label:fd[e]}))],onChange:e=>C({aiLanguage:hd(e.target.value)}),"data-testid":`summary-ai-language`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.nothingIsAddedToThe`,`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`)})]})]}),i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.yourQuestionOptional`,`Your question (optional)`)}),d(`textarea`,{value:h.aiPrompt,rows:3,maxLength:Eu,disabled:!h.aiEnabled,onChange:e=>C({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:p(`system.notificationSummaryEditor.eGTellMeWhether`,`e.g. Tell me whether anybody approached the gate, and whether a parcel was left.`),className:`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.leaveBlankForWhatHappened`,`Leave blank for “what happened during this period?”. Your words are the only free text the model is given: what the cameras are called and what the pipeline classified are reduced to plain labels first, and anything written INSIDE a frame — a sign, a plate, an overlay — is treated as scenery, never as an instruction.`)})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(pl,{label:p(`system.notificationSummaryEditor.framesTheModelMayLook`,`Frames the model may look at`),value:h.maxAiImages,min:1,max:8,disabled:!h.aiEnabled,onChange:e=>C({maxAiImages:e??1}),hint:p(`system.notificationSummaryEditor.theHighestRankedTilesSent`,`The highest-ranked tiles, sent as ONE question. Bounded separately from the tile budget — one is bounded by pixels, the other by the model's time — and never larger than it.`),testId:`summary-max-ai-images`}),d(pl,{label:p(`system.notificationSummaryEditor.timeLimitSeconds`,`Time limit (seconds)`),value:h.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!h.aiEnabled,onChange:e=>C({aiTimeoutSeconds:e}),hint:p(`system.notificationSummaryEditor.nobodyIsWaitingOnA`,`Nobody is waiting on a phone for a digest, so this is generous. At the bound the generation is cancelled, not merely abandoned.`),testId:`summary-ai-timeout`})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(pl,{label:p(`system.notificationSummaryEditor.frameSizeSentPixels`,`Frame size sent (pixels)`),value:h.aiMaxImagePx,min:64,max:Tu,emptyPlaceholder:`448`,disabled:!h.aiEnabled,onChange:e=>C({aiMaxImagePx:e}),hint:p(`system.notificationSummaryEditor.longestEdge448IsThe`,`Longest edge. 448 is the native tile size of these vision encoders — larger costs tokens and latency without adding detail the encoder can see.`),testId:`summary-ai-max-px`}),i(`div`,{children:[d(`label`,{className:Q,children:p(`system.notificationSummaryEditor.ifTheModelGivesNo`,`If the model gives no answer`)}),d(H,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:wu.map(e=>({value:e,label:dd[e]})),onChange:e=>{let t=gd(e.target.value);t!==void 0&&C({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.aColdModelAnUnreachable`,`A cold model, an unreachable endpoint or an answer the hub cannot parse are all this case. The default delivers: the mosaic and the counts are worth more than silence, and a closed window does not come back.`)})]})]})]})}),d(U,{value:`delivery`,className:`space-y-3`,children:i(cl,{title:p(`system.notificationSummaryEditor.delivery`,`Delivery`),children:[d(fl,{targets:s,value:h.targetIds,onChange:e=>C({targetIds:e})}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(pl,{label:p(`system.notificationSummaryEditor.priority`,`Priority`),value:h.priority,min:1,max:5,onChange:e=>C({priority:e??3}),testId:`summary-priority`}),d(ml,{label:p(`system.notificationSummaryEditor.deliverAWindowThatMatched`,`Deliver a window that matched nothing`),checked:h.deliverEmpty,onChange:e=>C({deliverEmpty:e}),hint:p(`system.notificationSummaryEditor.offByDefaultANightly`,`Off by default: a nightly '0 events' is a line nobody reads, and it costs the lines beside it their reader.`),testId:`summary-deliver-empty`})]}),d(hl,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>C({templateTitle:e}),onBodyChange:e=>C({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),d(`p`,{className:sl,children:d(Zr,{i18nKey:`system.notificationSummaryEditor.aiToken`,values:{token:`{{ai}}`},components:{code:d(`code`,{})}})})]})})]})]}),i(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[d(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:p(`common.cancel`,`Cancel`)}),i(q,{size:`sm`,type:`button`,disabled:j.isPending,onClick:()=>{b(!0),!(!nd(h)||j.isPending)&&j.mutate()},children:[j.isPending&&d(E,{className:`h-3.5 w-3.5 animate-spin`}),e===null?p(`system.notificationSummaryEditor.create`,`Create`):p(`common.save`,`Save`)]})]})]})})}var vd=`nc.listTimelapseRules`,yd=`nc.upsertTimelapseRule`,bd=`nc.deleteTimelapseRule`,xd=`nc.testTimelapseRule`,Sd=3600,Cd=3600,wd=30,Td=1,Ed=[`image`,`gif`],Dd={image:`Still frame`,gif:`Short animation (GIF)`},Od=Le({rules:ze(oe.extend({readOnly:Be().optional()}))});function kd(e){let t=Od.safeParse(e);return t.success?t.data.rules:null}function Ad(e){return e.readOnly!==!0}var jd=Le({produced:Pe(),exportId:Ie().optional(),coveragePercent:Pe().optional(),enqueued:Pe().optional(),windowStartMs:Pe().optional(),windowEndMs:Pe().optional(),error:Ie().optional()});function Md(e){let t=jd.safeParse(e);return t.success?t.data:null}function Nd(){return{name:``,enabled:!0,deviceIds:[],schedule:void 0,cadenceSec:15,framerate:10,denseCadenceSec:void 0,minDwellSec:void 0,targetIds:[],templateTitle:``,templateBody:``,previewText:``,previewTextSet:!1,previewMode:`image`,reportClasses:[],priority:3}}function Pd(e){return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule,cadenceSec:e.cadenceSec,framerate:e.framerate,denseCadenceSec:e.denseCadenceSec,minDwellSec:e.minDwellSec,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,previewText:e.previewText??``,previewTextSet:e.previewText!==void 0,previewMode:e.previewMode,reportClasses:[...e.reportClasses??[]],priority:e.priority}}var Fd={windows:[{days:[1],startMinute:0,endMinute:60}]};function Id(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 Ld(e){let t=Id(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??Fd,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Tl(e.targetIds),...t===void 0?{}:{template:t},...e.previewTextSet?{previewText:e.previewText}:{},previewMode:e.previewMode,...e.reportClasses.length>0?{reportClasses:[...e.reportClasses]}:{},priority:e.priority}}function Rd(e,t){let n=Ld(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),wl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),wl(n.schedule,t.schedule)||(r.schedule=n.schedule),n.cadenceSec!==t.cadenceSec&&(r.cadenceSec=n.cadenceSec),n.framerate!==t.framerate&&(r.framerate=n.framerate),n.denseCadenceSec!==t.denseCadenceSec&&(r.denseCadenceSec=n.denseCadenceSec??zd(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),wl(n.targets,t.targets)||(r.targets=n.targets),wl(n.template,t.template)||(r.template=n.template??null),n.previewText!==t.previewText&&n.previewText!==void 0&&(r.previewText=n.previewText),n.previewMode!==t.previewMode&&(r.previewMode=n.previewMode),wl(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function zd(e){return Math.max(Td,e/wd)}function Bd(e,t,n){return t<=0||n<=0?0:e/t/n}function Vd(e,t){return e*t*I}function Hd(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 ${Sd}.`),(!Number.isInteger(e.framerate)||e.framerate<1||e.framerate>60)&&t.push(`The output frame rate is a whole number between 1 and 60 fps.`),e.denseCadenceSec!==void 0&&(e.denseCadenceSec<.1||e.denseCadenceSec>3600?t.push(`The dense cadence is between ${I}s and ${Cd}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 Ud(e){return Hd(e).length===0}function Wd(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=Vd(e.minDwellSec,e.framerate);n>3&&t.push(`A passage shorter than ${n.toFixed(1)}s can never reach this stay, even at the finest sampling — it is rendered with every frame that exists and no more.`)}return e.previewMode===`gif`&&t.push(`A GIF preview costs a dozen extra seeks and a palette pass per delivery. If it cannot be assembled it degrades to the still — never to nothing.`),t}function Gd(e){return bl(e)}function Kd(e,t){return xl(e,t,`Never run`)}function qd(e){return e.denseCadenceSec===void 0?{seconds:zd(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var Jd=[{key:`rule`,get label(){return J.t(`helpers.notificationTimelapse.tab_rule`)},fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,get label(){return J.t(`helpers.notificationTimelapse.tab_window`)},fields:[`schedule`]},{key:`sampling`,get label(){return J.t(`helpers.notificationTimelapse.tab_sampling`)},fields:[`cadenceSec`,`framerate`,`denseCadenceSec`,`minDwellSec`]},{key:`delivery`,get label(){return J.t(`helpers.notificationTimelapse.tab_delivery`)},fields:[`targetIds`,`priority`,`previewMode`,`previewText`,`previewTextSet`,`templateTitle`,`templateBody`,`reportClasses`]}],Yd=`rule`;function Xd(e){return Jd.find(t=>t.key===e)?.key}e();var Zd=7;function Qd(e){return Ed.find(t=>t===e)}function $d({rule:e,cameras:t,fleet:n,targets:a,onSaved:s,onCancel:c}){let{t:l}=Y(),p=D(),[m,h]=r(()=>e===null?Nd():Pd(e)),[g,_]=r(null),[v,y]=r(e!==null),[b,x]=r(Yd),S=e=>h(t=>({...t,...e})),C=go(),w=C.data?fo(C.data,{family:`timelapse`,field:`previewText`}):void 0,T=u({mutationFn:async()=>{let t=e===null?{rule:Ld(m)}:{ruleId:e.id,patch:Rd(m,e)};await p.trpcClient.addons.custom.mutate({addonId:$,action:yd,input:t})},onSuccess:s,onError:e=>_(e instanceof Error?e.message:`Save failed`)}),O=Hd(m),k=Wd(m),A=qd(m),j=Bd(Zd,A.seconds,m.framerate),M=Jd.some(e=>e.key===b)?b:Yd;return d(dt,{open:!0,onOpenChange:e=>!e&&c(),children:i(vt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[d(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:i(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[d(f,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:e===null?l(`system.notificationTimelapseEditor.newTimelapse`,`New timelapse`):l(`system.notificationTimelapseEditor.edit`,`Edit {{name}}`,{name:e.name})})]})}),g!==null&&d(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:g}),i(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&d(Hc,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),v?d(ll,{problems:O,testId:`timelapse-problems`}):null,d(ul,{warnings:k,testId:`timelapse-warnings`})]}),i(Ze,{value:M,onValueChange:e=>x(Xd(e)??b),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[d(St,{className:`mb-3 shrink-0`,children:Jd.map(e=>d(Je,{value:e.key,children:e.label},e.key))}),i(qe,{className:`pr-1`,children:[i(U,{value:`rule`,className:`space-y-3`,children:[d(cl,{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:i(`div`,{className:`flex items-end gap-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Q,children:l(`system.notificationTimelapseEditor.name`,`Name`)}),d(W,{value:m.name,onChange:e=>S({name:e.target.value}),placeholder:l(`system.notificationTimelapseEditor.eGNightDriveway`,`e.g. Night driveway`),"data-testid":`timelapse-name`})]}),d(`div`,{className:`pb-1.5`,children:d(ml,{label:l(`system.notificationTimelapseEditor.enabled`,`Enabled`),checked:m.enabled,onChange:e=>S({enabled:e}),testId:`timelapse-enabled`})})]})}),d(cl,{title:l(`system.notificationTimelapseEditor.cameras`,`Cameras`),children:d(dl,{cameras:t,value:m.deviceIds,fleet:n,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.`)})})]}),d(U,{value:`window`,className:`space-y-3`,children:d(cl,{title:l(`system.notificationTimelapseEditor.when`,`When`),children:i(`div`,{children:[d(`label`,{className:Q,children:l(`system.notificationTimelapseEditor.weeklyWindows`,`Weekly windows`)}),d(jr,{value:m.schedule,onChange:e=>S({schedule:e})}),d(`p`,{className:sl,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.`)})]})})}),d(U,{value:`sampling`,className:`space-y-3`,children:i(cl,{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:[i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(pl,{label:l(`system.notificationTimelapseEditor.baseCadenceSeconds`,`Base cadence (seconds)`),value:m.cadenceSec,min:2,max:Sd,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`}),d(pl,{label:l(`system.notificationTimelapseEditor.outputFrameRateFps`,`Output frame rate (fps)`),value:m.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`})]}),i(`div`,{children:[d(`label`,{className:Q,children:l(`system.notificationTimelapseEditor.denseCadenceNearTheDetections`,`Dense cadence, near the detections`)}),i(`div`,{className:`flex items-center gap-2`,children:[d(H,{value:m.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:qd(m).seconds}),"data-testid":`timelapse-dense-mode`}),m.denseCadenceSec!==void 0&&d(W,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(m.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&S({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),i(`p`,{className:sl,"data-testid":`timelapse-dense-hint`,children:[l(`system.notificationTimelapseEditor.denseHint`,{seconds:A.seconds,fps:m.framerate,passage:Zd,onScreen:j.toFixed(2)}),` `,A.derived?l(`system.notificationTimelapseEditor.denseDerived`):l(`system.notificationTimelapseEditor.denseFixed`,{seconds:qd({...m,denseCadenceSec:void 0}).seconds})]})]}),d(pl,{label:l(`system.notificationTimelapseEditor.minimumSecondsOfVideoPer`,`Minimum seconds of video per detection (optional)`),value:m.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`})]})}),d(U,{value:`delivery`,className:`space-y-3`,children:i(cl,{title:l(`system.notificationTimelapseEditor.theNotification`,`The notification`),children:[d(fl,{targets:a,value:m.targetIds,onChange:e=>S({targetIds:e})}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:Q,children:l(`system.notificationTimelapseEditor.preview`,`Preview`)}),d(H,{value:m.previewMode,options:Ed.map(e=>({value:e,label:Dd[e]})),onChange:e=>{let t=Qd(e.target.value);t!==void 0&&S({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),d(pl,{label:l(`system.notificationTimelapseEditor.priority`,`Priority`),value:m.priority,min:1,max:5,onChange:e=>S({priority:e??3}),testId:`timelapse-priority`})]}),i(`div`,{children:[d(xo,{label:l(`system.notificationTimelapseEditor.captionOnThePreviewFrame`,`Caption on the preview frame`),value:m.previewTextSet?m.previewText:``,placeholder:l(`system.notificationTimelapseEditor.shippedDefault`,`{{DEFAULT_TIMELAPSE_PREVIEW_TEXT}} (shipped default)`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:ee}),onChange:e=>S({previewText:e,previewTextSet:!0}),vars:w,testId:`timelapse-preview-text`}),i(`p`,{className:sl,children:[m.previewTextSet&&m.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:ee}),m.previewTextSet&&i(o,{children:[` `,d(`button`,{type:`button`,className:`underline`,onClick:()=>S({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:l(`system.notificationTimelapseEditor.backToTheShippedCaption`,`Back to the shipped caption`)})]})]})]}),d(hl,{title:m.templateTitle,body:m.templateBody,onTitleChange:e=>S({templateTitle:e}),onBodyChange:e=>S({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(Zr,{i18nKey:`system.notificationTimelapseEditor.detectionSummaryNote`,values:{token:`{{detectionSummary}}`},components:{code:d(`code`,{})}})})]})})]})]}),i(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[d(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:l(`common.cancel`,`Cancel`)}),i(q,{size:`sm`,type:`button`,disabled:T.isPending,onClick:()=>{y(!0),!(!Ud(m)||T.isPending)&&T.mutate()},children:[T.isPending&&d(E,{className:`h-3.5 w-3.5 animate-spin`}),e===null?l(`system.notificationTimelapseEditor.create`,`Create`):l(`common.save`,`Save`)]})]})]})})}function ef({children:e,className:t}){return d(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function tf(){return d(`div`,{className:`flex items-center justify-center py-16`,children:d(E,{className:`h-6 w-6 animate-spin text-primary`})})}function nf({children:e,testId:t}){return d(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function rf({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:i}){return d(Ot,{children:d(yt,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,maxBodyHeight:gt,...i===void 0?{}:{onRowClick:i}})})}function af({name:e,enabled:t,onOpen:n,badges:r,openTestId:a}){let{t:o}=Y();return i(`span`,{className:`flex flex-wrap items-center gap-2`,children:[n===void 0?d(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e}):d(ef,{children:d(`button`,{type:`button`,onClick:n,className:`truncate rounded text-left text-sm font-medium text-foreground hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,...a===void 0?{}:{"data-testid":a},children:e})}),!t&&d(G,{variant:`warning`,children:o(`common.disabled`)}),r]})}function of({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:i=`Delete`,cancelLabel:a=`Cancel`,ariaLabel:o,testId:s,onConfirm:c}){let l=$e(),u=async()=>{await l({title:n,message:r,confirmLabel:i,cancelLabel:a,variant:`danger`})&&c()};return d(`button`,{type:`button`,title:i,"aria-label":o,disabled:e||t,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void u(),...s===void 0?{}:{"data-testid":s},children:d(p,{className:`h-3.5 w-3.5 text-danger`})})}e();var sf=[`notificationSummaries`,`listSummaryRules`];function cf(e){return[{key:`name`,header:J.t(`system.notificationSummaries.digest`,`Digest`),render:t=>d(af,{name:t.name,enabled:t.enabled,...Du(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`summary-edit-${t.id}`,badges:i(o,{children:[!Du(t)&&d(G,{variant:`warning`,children:`read-only`}),t.ai?.enabled===!0&&d(G,{variant:`info`,children:`AI`}),t.ai!==void 0&&!t.ai.enabled&&d(G,{variant:`default`,children:J.t(`system.notificationSummaries.aiOff`,`AI off`)})]})})},{key:`cameras`,header:J.t(`system.notificationSummaries.cameras`,`Cameras`),align:`center`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:J.t(`system.notificationSummaries.window`,`Window`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:sd(e.window)})},{key:`filters`,header:J.t(`system.notificationSummaries.keeps`,`Keeps`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:ld(e.filters)})},{key:`mosaic`,header:J.t(`system.notificationSummaries.mosaic`,`Mosaic`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:J.t(`system.notificationSummaries.tilesRank`,{count:e.maxTiles,rank:e.rank})})},{key:`targets`,header:J.t(`system.notificationSummaries.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationSummaries.lastRun`,`Last run`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:cd(t.generatedAt,e.nowMs)})},{key:`enabled`,header:J.t(`system.notificationSummaries.on`,`On`),align:`center`,nowrap:!0,render:t=>d(ef,{children:d(xt,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":J.t(`system.notificationSummaries.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>i(ef,{className:`flex items-center justify-end gap-1`,children:[d(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onTest(t),title:J.t(`system.notificationSummaries.produceThisDigestNowAnd`,`Produce this digest now and DELIVER it`),"aria-label":J.t(`system.notificationSummaries.test`,`test {{name}}`,{name:t.name}),"data-testid":`summary-test-${t.id}`,children:d(m,{className:`h-3.5 w-3.5`})}),d(of,{disabled:t.readOnly,pending:e.deletePending,title:J.t(`system.notificationSummaries.deleteThisSummary`,`Delete this summary?`),message:J.t(`system.notificationSummaries.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:J.t(`system.notificationSummaries.delete`,`delete {{name}}`,{name:t.name}),testId:`summary-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}e();var lf=[`notificationTimelapses`,`listTimelapseRules`];function uf(e){return[{key:`name`,header:J.t(`system.notificationTimelapses.timelapse`,`Timelapse`),render:t=>d(af,{name:t.name,enabled:t.enabled,...Ad(t)?{onOpen:()=>e.onOpen(t),openTestId:`timelapse-edit-${t.id}`}:{},badges:Ad(t)?null:d(G,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:J.t(`system.notificationTimelapses.cameras`,`Cameras`),render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.deviceIds.length===1?e.cameraNameById.get(t.deviceIds[0]??-1)??`#${t.deviceIds[0]}`:J.t(`system.notificationTimelapses.cameras2`,`{{length}} cameras`,{length:t.deviceIds.length})})},{key:`schedule`,header:J.t(`system.notificationTimelapses.window`,`Window`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Gd(e.schedule)})},{key:`sampling`,header:J.t(`system.notificationTimelapses.sampling`,`Sampling`),nowrap:!0,render:e=>{let t=qd(Pd(e));return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:[J.t(t.derived?`system.notificationTimelapses.ruleSummaryAuto`:`system.notificationTimelapses.ruleSummary`,{cadence:e.cadenceSec,fps:e.framerate,dense:t.seconds}),e.minDwellSec===void 0?``:` · ${J.t(`system.notificationTimelapses.ruleDwell`,{sec:e.minDwellSec})}`]})}},{key:`targets`,header:J.t(`system.notificationTimelapses.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationTimelapses.lastRun`,`Last run`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:Kd(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:J.t(`system.notificationTimelapses.on`,`On`),align:`center`,nowrap:!0,render:t=>d(ef,{children:d(xt,{checked:t.enabled,disabled:!Ad(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":J.t(`system.notificationTimelapses.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>i(ef,{className:`flex items-center justify-end gap-1`,children:[d(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Ad(t),onClick:()=>e.onTest(t),title:J.t(`system.notificationTimelapses.renderThisRuleSLast`,`Render this rule's last closed window now and DELIVER it`),"aria-label":J.t(`system.notificationTimelapses.test`,`test {{name}}`,{name:t.name}),"data-testid":`timelapse-test-${t.id}`,children:d(m,{className:`h-3.5 w-3.5`})}),d(of,{disabled:!Ad(t),pending:e.deletePending,title:J.t(`system.notificationTimelapses.deleteThisTimelapse`,`Delete this timelapse?`),message:J.t(`system.notificationTimelapses.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:J.t(`system.notificationTimelapses.delete`,`delete {{name}}`,{name:t.name}),testId:`timelapse-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}e();var df={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`}},ff=`system.notificationProducerRules.unreadableMessage`;function pf(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function mf({cameras:e,fleet:t,targets:n,taxonomy:s}){let{t:c}=Y(),l=D(),[f,p]=r({mode:`closed`}),[m,h]=r(null),[g,_]=r(null),[v,y]=r(null),[b,x]=r(null),S=a({queryKey:sf,queryFn:async()=>Wu(await l.trpcClient.addons.custom.mutate({addonId:$,action:lu,input:{}}))}),C=a({queryKey:lf,queryFn:async()=>kd(await l.trpcClient.addons.custom.mutate({addonId:$,action:vd,input:{}}))}),w=a({queryKey:Hl,queryFn:async()=>Yl(await l.trpcClient.addons.custom.mutate({addonId:$,action:Ul,input:{}}))}),T=S.data??[],E=C.data??[],O=w.data??[],k=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:uu,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),A=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:du,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),j=u({mutationFn:async e=>Gu(await l.trpcClient.addons.custom.mutate({addonId:$,action:fu,input:{ruleId:e,...ud(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),M=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:yd,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),N=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:bd,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),P=u({mutationFn:async e=>Md(await l.trpcClient.addons.custom.mutate({addonId:$,action:xd,input:e})),onSuccess:e=>{y(null),x(e)}}),F=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Wl,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void w.refetch()}),I=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Gl,input:{ruleId:e}}),onSuccess:()=>void w.refetch()}),ee=e.toSorted((e,t)=>e.name.localeCompare(t.name)),te=n.map(e=>({id:e.id,name:e.name,enabled:e.enabled})),L=new Map(te.map(e=>[e.id,e.name])),ne=new Map(ee.map(e=>[e.id,e.name])),R=Date.now(),re={summary:{nowMs:R,targetNameById:L,deletePending:A.isPending,onToggle:(e,t)=>k.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Du(e)&&p({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>A.mutate(e.id)},timelapse:{nowMs:R,cameraNameById:ne,targetNameById:L,deletePending:N.isPending,onToggle:(e,t)=>M.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Ad(e)&&p({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>N.mutate(e.id)},calendar:{nowMs:R,targetNameById:L,deletePending:I.isPending,onToggle:(e,t)=>F.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Xl(e)&&p({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>I.mutate(e.id)}},ie=e=>{switch(e.family){case`summary`:re.summary.onOpen(e.rule);return;case`timelapse`:re.timelapse.onOpen(e.rule);return;case`calendar-events`:re.calendar.onOpen(e.rule);return}},z=e=>{p(e===`summary`?{mode:`summary`,rule:null}:e===`timelapse`?{mode:`timelapse`,rule:null}:{mode:`calendar-events`,rule:null})},ae=e=>{let t=e===`summary`?S:e===`timelapse`?C:w;return t.isLoading?null:t.isError?{unreadable:!1}:t.data===null?{unreadable:!0}:null},oe=e=>{e===`summary`?S.refetch():e===`timelapse`?C.refetch():w.refetch()},se=e=>{let t=pf(e);return t!==null&&ae(t)!==null},ce=e=>{let t=pf(e),n=t===null?null:ae(t);return i(o,{children:[t!==null&&n!==null&&d(K,{title:c(df[t].titleKey),message:c(n.unreadable?ff:df[t].messageKey),onRetry:()=>oe(t)}),A.isError&&d(K,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(A.error)}),N.isError&&d(K,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(N.error)}),I.isError&&d(K,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(I.error)}),j.isError&&d(K,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(j.error)}),P.isError&&d(K,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(P.error)}),g!==null&&d(hf,{outcome:g,onDismiss:()=>_(null)}),b!==null&&d(gf,{outcome:b,onDismiss:()=>x(null)})]})},le=()=>p({mode:`closed`}),ue=i(o,{children:[f.mode===`summary`&&d(_d,{rule:f.rule,cameras:ee,fleet:t,targets:te,taxonomy:s,onCancel:le,onSaved:()=>{le(),S.refetch()}}),f.mode===`timelapse`&&d($d,{rule:f.rule,cameras:ee,fleet:t,targets:te,onCancel:le,onSaved:()=>{le(),C.refetch()}}),f.mode===`calendar-events`&&d(cu,{rule:f.rule,targets:te,onCancel:le,onSaved:()=>{le(),w.refetch()}}),d(gl,{open:m!==null,ruleName:m?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${m?.targets.length??0} target${(m?.targets.length??0)===1?``:`s`}`,pending:j.isPending,onCancel:()=>h(null),onConfirm:()=>{m!==null&&j.mutate(m.id)}}),d(gl,{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:i(`div`,{children:[d(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.notificationProducerRules.whichCamera`,`Which camera`)}),d(H,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:ne.get(e)??`#${e}`})),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&y({rule:v.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>y(null),onConfirm:()=>{v!==null&&v.deviceId!==null&&P.mutate({ruleId:v.rule.id,deviceId:v.deviceId})}})]});return{summaries:T,timelapses:E,calendarEvents:O,loading:S.isLoading||C.isLoading||w.isLoading,columnDeps:re,open:ie,create:z,notices:ce,listFailed:se,overlays:ue}}function hf({outcome:e,onDismiss:t}){let{t:n}=Y();return i(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[e.error===void 0?i(`span`,{children:[n(`system.notificationProducerRules.summaryProduced`,{digests:n(`system.notificationProducerRules.digestCount`,{count:e.produced}),tiles:n(`system.notificationProducerRules.tileCount`,{count:e.tiles??0}),cameras:n(`system.notificationProducerRules.cameraCount`,{count:e.cameras??0}),matched:n(`system.notificationProducerRules.tracksMatched`,{count:e.matched??0}),sent:n(`system.notificationProducerRules.notificationsSent`,{count:e.enqueued??0})}),(e.droppedStationary??0)>0&&d(`span`,{"data-testid":`summary-test-dropped-stationary`,className:`ml-1`,children:n(`system.notificationProducerRules.droppedStationary`,{count:e.droppedStationary})})]}):i(`span`,{className:`text-warning`,children:[n(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,e.error]}),d(q,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:n(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}function gf({outcome:e,onDismiss:t}){let{t:n}=Y();return i(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[e.error===void 0?d(`span`,{children:n(e.coveragePercent===void 0?`system.notificationProducerRules.timelapseProduced`:`system.notificationProducerRules.timelapseProducedCoverage`,{videos:n(`system.notificationProducerRules.videoCount`,{count:e.produced}),percent:Math.round(e.coveragePercent??0),sent:n(`system.notificationProducerRules.notificationsSent`,{count:e.enqueued??0})})}):i(`span`,{className:`text-warning`,children:[n(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,e.error]}),d(q,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:n(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}var _f=[{key:`summaries`,get label(){return J.t(`helpers.notificationRulesArea.sumLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.sumBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.sumNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.sumEmpty`)}},{key:`timelapses`,get label(){return J.t(`helpers.notificationRulesArea.tlLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.tlBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.tlNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.tlEmpty`)}},{key:`calendar-events`,get label(){return J.t(`helpers.notificationRulesArea.calLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.calBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.calNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.calEmpty`)}}],vf=[{type:`detection`,get label(){return J.t(`helpers.notificationRulesArea.opt_detection_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_detection_hint`)}},{type:`sensor`,get label(){return J.t(`helpers.notificationRulesArea.opt_sensor_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_sensor_hint`)}},{type:`audio`,get label(){return J.t(`helpers.notificationRulesArea.opt_audio_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_audio_hint`)}},{type:`occupancy`,get label(){return J.t(`helpers.notificationRulesArea.opt_occupancy_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_occupancy_hint`)}},{type:`device-events`,get label(){return J.t(`helpers.notificationRulesArea.opt_deviceEvents_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_deviceEvents_hint`)}},{type:`system`,get label(){return J.t(`helpers.notificationRulesArea.opt_system_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_system_hint`)}},{type:`alarm`,get label(){return J.t(`helpers.notificationRulesArea.opt_alarm_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_alarm_hint`)}},{type:`summary`,get label(){return J.t(`helpers.notificationRulesArea.opt_summary_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_summary_hint`)}},{type:`timelapse`,get label(){return J.t(`helpers.notificationRulesArea.opt_timelapse_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_timelapse_hint`)}},{type:`calendar-events`,get label(){return J.t(`helpers.notificationRulesArea.opt_calendarEvents_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_calendarEvents_hint`)}}];function yf(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function bf(e){if(!(e==null||e.length===0))return yf(e)?e:we(e)}function xf(e){let t=_f.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function Sf(e){return[...sr.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),..._f]}function Cf(e){return!yf(e)}function wf(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}e();function Tf(e){return[{key:`name`,header:J.t(`system.notificationCalendarEventsPage.rule`,`Rule`),render:t=>d(af,{name:t.name,enabled:t.enabled,...Xl(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:Xl(t)?null:d(G,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:J.t(`system.notificationCalendarEventsPage.when`,`When`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:eu(e.schedule)})},{key:`horizon`,header:J.t(`system.notificationCalendarEventsPage.horizon`,`Horizon`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:ou(e.horizonDays)})},{key:`calendars`,header:J.t(`system.notificationCalendarEventsPage.calendars`,`Calendars`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:su(e)})},{key:`targets`,header:J.t(`system.notificationCalendarEventsPage.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationCalendarEventsPage.lastRun`,`Last run`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:cd(t.generatedAt,e.nowMs)})},{key:`enabled`,header:J.t(`system.notificationCalendarEventsPage.on`,`On`),align:`center`,nowrap:!0,render:t=>d(ef,{children:d(xt,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":J.t(`system.notificationCalendarEventsPage.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>d(ef,{className:`flex items-center justify-end gap-1`,children:d(of,{disabled:t.readOnly,pending:e.deletePending,title:J.t(`system.notificationCalendarEventsPage.deleteThisCalendarEventsRule`,`Delete this calendar-events rule?`),message:J.t(`system.notificationCalendarEventsPage.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:J.t(`system.notificationCalendarEventsPage.delete`,`delete {{name}}`,{name:t.name}),testId:`calendar-events-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})})}]}function Ef(e,t){return e.replaceAll(`{{name}}`,t)}function Df(e){return[{key:`name`,header:J.t(`system.notificationRuleColumns.rule`,`Rule`),render:t=>d(af,{name:t.name,enabled:t.enabled,...gn(t)?{onOpen:()=>e.onOpen(t)}:{}})},{key:`trigger`,header:J.t(`system.notificationRuleColumns.trigger`,`Trigger`),nowrap:!0,render:t=>i(`span`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`text-[11px] text-foreground-subtle`,children:On(t,e.t(`notificationRules.grouping.choice`,Br))}),!rn(t.delivery)&&d(G,{variant:`warning`,children:J.t(`common.readOnly`)})]})},{key:`targets`,header:J.t(`system.notificationRuleColumns.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationRuleColumns.lastRun`,`Last run`),nowrap:!0,render:t=>d(ac,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:J.t(`system.notificationRuleColumns.priority`,`Priority`),align:`center`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:e.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:t=>d(ef,{children:d(mc,{rule:t,snoozes:e.snoozes,exempt:nn(t.conditions,Wt({onActivation:t.actions?.onActivation??[],onDeactivation:t.actions?.onDeactivation??[],onTrigger:t.actions?.onTrigger??[],onTriggerOff:t.actions?.onTriggerOff??[],buttons:t.actions?.buttons??[]},e.sequences))})})},{key:`enabled`,header:J.t(`system.notificationRuleColumns.on`,`On`),align:`center`,nowrap:!0,render:t=>d(ef,{children:d(xt,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":J.t(`system.notificationRuleColumns.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>gn(t)?i(ef,{className:`flex items-center justify-end gap-1`,children:[d(tl,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&d(oc,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:J.t(`system.notificationRuleColumns.openInTheSimulatorDescribe`,`Open in the simulator — describe an event and tune it before injecting`),"aria-label":J.t(`system.notificationRuleColumns.simulate`,`simulate {{name}}`,{name:t.name}),children:d(m,{className:`h-3.5 w-3.5`})}),d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:J.t(`system.notificationRuleColumns.duplicate`,`Duplicate`),children:d(_,{className:`h-3.5 w-3.5`})}),d(kf,{rule:t,deps:e})]}):d(Of,{rule:t,deps:e})}]}function Of({rule:e,deps:t}){let{t:n}=Y();return i(ef,{className:`flex items-center justify-end gap-1`,children:[d(`span`,{title:Ee(ye(e)).blurb,children:d(G,{variant:`warning`,children:n(`system.notificationRuleColumns.recreateAsOneRulePer`,`Recreate as one rule per family`)})}),t.onOpenHistory&&d(oc,{rule:e,onOpenHistory:t.onOpenHistory}),d(kf,{rule:e,deps:t})]})}function kf({rule:e,deps:t}){let{t:n}=Y();return d(of,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:Ef(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:Ef(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function Af(e){let t=Df(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:J.t(`system.notificationRuleColumns.events`,`Events`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Sr(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:J.t(`system.notificationRuleColumns.scope`,`Scope`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:pr(e.conditions.systemEvent)})},{key:`targets`,header:J.t(`system.notificationRuleColumns.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`cooldown`,header:J.t(`system.notificationRuleColumns.cooldown`,`Cooldown`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:cn(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function jf(e){switch(e){case`detection`:return J.t(`helpers.unifiedRulesModel.kind_detection`);case`sensor`:return J.t(`helpers.unifiedRulesModel.kind_sensor`);case`sound`:return J.t(`helpers.unifiedRulesModel.kind_sound`);case`occupancy`:return J.t(`helpers.unifiedRulesModel.kind_occupancy`);case`device-events`:return J.t(`helpers.unifiedRulesModel.kind_device_events`);case`system`:return J.t(`helpers.unifiedRulesModel.kind_system`);case`alarm`:return J.t(`helpers.unifiedRulesModel.kind_alarm`);case`mixed`:return J.t(`helpers.unifiedRulesModel.kind_mixed`);case`summary`:return J.t(`helpers.unifiedRulesModel.kind_summary`);case`timelapse`:return J.t(`helpers.unifiedRulesModel.kind_timelapse`);case`calendar-events`:return J.t(`helpers.unifiedRulesModel.kind_calendar_events`)}}function Mf(e){return{family:`event`,kind:ye(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Nf(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Pf(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Ff(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function If(e){return[...e.events.map(Mf),...e.summaries.map(Nf),...e.timelapses.map(Pf),...e.calendarEvents.map(Ff)]}function Lf(e,t){return t===`all`?!0:yf(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:Cf(t)&&e.family===`event`?Te(e.rule,t):!1}function Rf(e,t){return If(t).filter(t=>Lf(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function zf(e,t){return Rf(e,t).length}function Bf(e){return e===`all`?900:860}function Vf(e){return e.family===`event`?e.rule:null}function Hf(e){return e.family===`summary`?e.rule:null}function Uf(e){return e.family===`timelapse`?e.rule:null}function Wf(e){return e.family===`calendar-events`?e.rule:null}function Gf(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 Kf(e,t){return e.map(e=>Gf(e,t))}function qf(e,t){return e.find(e=>e.key===t)}function Jf(e,t,n){let r=qf(Df(n.event),e),i=qf(cf(n.summary),e),a=qf(uf(n.timelapse),e),o=qf(Tf(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 Yf(e){switch(e.family){case`event`:return null;case`summary`:return sd(e.rule.window);case`timelapse`:return Gd(e.rule.schedule);case`calendar-events`:return eu(e.rule.schedule)}}function Xf(e){let t=qf(Df(e.event),`trigger`);return{key:`when`,header:J.t(`system.unifiedRulesColumns.when`,`When`),render:(e,n)=>{let r=Yf(e);return r===null?e.family===`event`?t?.render(e.rule,n)??null:null:d(`span`,{className:`text-[11px] text-foreground-subtle`,children:r})}}}function Zf(e){return[Jf(`name`,`Name`,e),{key:`type`,header:J.t(`system.unifiedRulesColumns.type`,`Type`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:jf(e.kind)})},Xf(e),Jf(`targets`,`Targets`,e),Jf(`lastRun`,`Last run`,e),Jf(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),Jf(`enabled`,`On`,e),Jf(`actions`,``,e)]}function Qf(e,t){return e===`all`?Zf(t):e===`summaries`?Kf(cf(t.summary),Hf):e===`timelapses`?Kf(uf(t.timelapse),Uf):e===`calendar-events`?Kf(Tf(t.calendar),Wf):Cf(e)&&Kr(e)?Kf(Af(t.event),Vf):Kf(Df(t.event),Vf)}function $f({value:e,family:t,onChange:n,draft:r}){let{t:a}=Y();if(t===void 0||!ae.includes(t))return null;let o=e?.mode===`summary`?e:null;return i(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:a(`system.notificationSystemEventDelivery.delivery`,`Delivery`)}),i(`div`,{className:`flex flex-wrap gap-3 text-xs`,children:[i(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-delivery`,checked:o===null,onChange:()=>n({mode:`instant`}),"data-testid":`rule-delivery-instant`}),a(`system.notificationSystemEventDelivery.instantANotificationPerEvent`,`Instant — a notification per event`)]}),i(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-delivery`,checked:o!==null,onChange:()=>n({mode:`summary`,schedule:se([mr])}),"data-testid":`rule-delivery-summary`}),a(`system.notificationSystemEventDelivery.summaryOnScheduleTheCurrent`,`Summary on schedule — the current state, at set times`)]})]}),o!==null&&d(ep,{value:o,onChange:n,draft:r})]})}function ep({value:e,onChange:t,draft:n}){let{t:r}=Y(),a=e.schedule.timezone,o=le({systemEventDelivery:e});return i(`div`,{className:`mt-2 space-y-2`,children:[i(`p`,{className:Un,children:[r(`system.notificationSystemEventDelivery.nothingIsSentPerEvent`,`Nothing is sent per event. At each time below, one notification lists what is still true for the kinds and filters of this rule — low batteries, consumables, devices or streams offline, updates available — or one notification per category, if you choose so below. Nothing to report sends nothing. Time zone:`),` `,a??r(`system.notificationSystemEventDelivery.theHubS`,`the hub’s`),`.`]}),d(jr,{mode:`times`,value:e.schedule,onChange:n=>{n!==void 0&&t(tr(e,n))}}),i(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[d(`legend`,{className:`sr-only`,children:r(`system.notificationSystemEventDelivery.howTheSummaryIsSent`,`How the summary is sent`)}),i(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-summary-split`,checked:o===`rule`,onChange:()=>t(Fn(e,`rule`)),"data-testid":`rule-delivery-split-rule`}),r(`system.notificationSystemEventDelivery.oneMessageWithEveryCategory`,`One message with every category`)]}),i(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-summary-split`,checked:o===`section`,onChange:()=>t(Fn(e,`section`)),"data-testid":`rule-delivery-split-section`}),r(`system.notificationSystemEventDelivery.oneNotificationPerCategoryBatteries`,`One notification per category (batteries, consumables, devices…)`)]})]}),d(tp,{draft:n,split:o})]})}function tp({draft:e,split:t}){let{t:n}=Y(),r=D(),a=u({mutationFn:e=>r.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),o=Tr(a.status,a.data,a.error,t);return i(`div`,{className:`space-y-1.5`,children:[d(q,{size:`sm`,variant:`secondary`,onClick:()=>a.mutate(e()),disabled:a.isPending,"data-testid":`rule-delivery-preview`,children:a.isPending?n(`system.notificationSystemEventDelivery.readingTheState`,`Reading the state…`):n(`system.notificationSystemEventDelivery.previewTheSummaryNow`,`Preview the summary now`)}),o!==null&&d(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:o.lines.map((e,t)=>d(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function np(e,t){if(e.status===`error`)return{kind:`failed`,reason:e.error instanceof Error?e.error.message:J.t(`helpers.notificationRuleLastRun.unknownError`)};if(e.status!==`success`||e.data===void 0)return{kind:`pending`};let n=e.data.runs.find(e=>e.ruleId===t);return n===void 0?{kind:`absent`,phrase:op(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var rp=6e4,ip=60*rp,ap=24*ip;function op(e){return e===null?J.t(`helpers.notificationRuleLastRun.noDelivery`):e>=ap?J.t(`helpers.notificationRuleLastRun.notInDay`,{count:Math.floor(e/ap)}):e>=ip?J.t(`helpers.notificationRuleLastRun.notInHour`,{count:Math.floor(e/ip)}):e>=rp?J.t(`helpers.notificationRuleLastRun.notInMinute`,{count:Math.floor(e/rp)}):J.t(`helpers.notificationRuleLastRun.notInWindow`)}e();var sp=[`notificationRules`,`listRules`],cp=[`notificationOutput`,`listTargets`,`forRules`],lp=[`notificationRules`,`getConditionCatalog`],up=[`deviceManager`,`gateableDevices`],dp=z.options;function fp({onSimulateRule:e,onOpenHistory:o,createRequested:s=!1,onCreateConsumed:c,createTypeRequested:f=null,onCreateTypeConsumed:p,headerOwnsCreate:m=!1}={}){let h=D(),{t:g}=Y(),{state:_,openEdit:v,close:y}=wt({editKey:`rule`}),[b,x]=kt(`section`),[S,C]=kt(`editTab`),[T,E]=r({mode:`closed`}),[O,k]=r(!1),A=bf(b)??`all`,j=e=>{x(e===`all`?null:e)},M=a({queryKey:sp,queryFn:async()=>(await h.trpcClient.notificationRules.listRules.query({})).rules}),P=l(null);t(()=>{if(T.mode!==`closed`)return;if(_.mode!==`edit`){_.mode===`closed`&&(P.current=null);return}let e=_.id;if(e===`new`||P.current===e)return;let t=M.data?.find(t=>t.id===e);t===void 0||!gn(t)||(P.current=e,E({mode:`form`,rule:t}))},[T.mode,_,M.data]);let F=a({queryKey:cp,queryFn:()=>h.trpcClient.notificationOutput.listTargets.query({})}),I=a({queryKey:lp,queryFn:()=>h.trpcClient.notificationRules.getConditionCatalog.query({})}),ee=tt({projection:`slim`}),te=rc(),L=n(()=>ee.data??[],[ee.data]),ne=ct(ee),R=n(()=>L.map(e=>e.id),[L]),re=a({queryKey:[...up,R],enabled:R.length>0,queryFn:async()=>{let e=[];for(let t of L){let n=Se(await h.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),dp);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),ie=n(()=>{let e=Jr(L);return L.filter(e=>ge(String(e.type))).map(t=>{let n=e.get(t.id);return{id:t.id,name:t.name,type:String(t.type),location:t.location??null,...n===void 0?{}:{parentName:n}}}).sort((e,t)=>e.name.localeCompare(t.name))},[L]),z=n(()=>L.filter(e=>e.type===he.Camera).map(e=>({id:e.id,name:e.name})),[L]),ae=ni(n(()=>z.map(e=>e.id),[z])),oe=n(()=>{let e=new Map(z.map(e=>[e.id,e.name]));return ae.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})))},[ae.results,z]),se=n(()=>{let e=new Map;for(let t of F.data??[])e.set(t.id,t.name);return e},[F.data]),ce=u({mutationFn:e=>h.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void M.refetch()}),le=u({mutationFn:e=>h.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void M.refetch()}),ue=pc(),de=it({}),fe=de.data?.sequences??[],pe=st(),me=M.data??[],B=mf({cameras:z,fleet:ne,targets:F.data??[],taxonomy:I.data?.taxonomy}),_e={events:me,summaries:B.summaries,timelapses:B.timelapses,calendarEvents:B.calendarEvents},ve=Sf(new Map(sr.map(e=>[e.key,zf(e.key,_e)]))),V=ve.find(e=>e.key===A)??ve[0]??sr[0],ye=yf(V.key)?xf(V.key):void 0;Cf(V.key)&&V.key;let be=Rf(V.key,_e),Ce=()=>{_.mode===`edit`&&(P.current=_.id),E({mode:`closed`}),y(),C(null)},we=e=>{if(!gn(e))return;let t=e.id.length>0?e.id:`new`;P.current=t,E({mode:`form`,rule:e}),v(t),C(null)},Te=e=>{if(wf(e)){P.current=`new`,E({mode:`form`,rule:null,seed:xe(e)}),v(`new`),C(null);return}B.create(e)};t(()=>{f!==null&&(Te(f),p?.())},[f]),t(()=>{s&&(k(!0),c?.())},[s]);let Ee=e=>{if(e.family===`event`){we(e.rule);return}B.open(e)},De={targetNameById:se,snoozes:ue,sequences:fe,deletePending:le.isPending,onToggle:(e,t)=>ce.mutate({ruleId:e.id,enabled:t}),onOpen:we,t:g,onDuplicate:e=>we({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>le.mutate(e.id),...e?{onTest:e}:{},lastRunOf:e=>np(te,e),...o?{onOpenHistory:o}:{}},Oe=Qf(V.key,{event:De,summary:B.columnDeps.summary,timelapse:B.columnDeps.timelapse,calendar:B.columnDeps.calendar}),ke=ye?.blurb??(`blurb`in V?V.blurb:``),Ae=ye===void 0?`creatable`in V?V.creatable:!1:!0,je=m||!Ae?null:A===`all`?i(q,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:()=>k(!0),children:[d(w,{className:`h-3.5 w-3.5`}),g(`system.notificationRules.newRule`,`New rule`)]}):ye===void 0?i(q,{size:`sm`,type:`button`,onClick:()=>Te(V.key),"data-testid":`rules-new-${V.key}`,children:[d(w,{className:`h-3.5 w-3.5`}),`newRuleLabel`in V?V.newRuleLabel:g(`system.notificationRules.newRule`,`New rule`)]}):i(q,{size:`sm`,type:`button`,onClick:()=>Te(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:[d(w,{className:`h-3.5 w-3.5`}),ye.newLabel]});return d(ti,{embedded:!0,icon:N,title:g(`system.notificationRules.rules`,`Rules`),subtitle:ke,children:i(`div`,{className:`flex flex-col gap-3`,children:[je===null?null:d(`div`,{className:`flex justify-end`,children:je}),d(Ze,{appearance:`pills`,value:V.key,onValueChange:e=>j(bf(e)??A),children:d(St,{children:ve.map(e=>i(Je,{value:e.key,children:[e.label,d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:zf(e.key,_e)})]},e.key))})}),d(ol,{rules:me}),B.notices(V.key),(M.isLoading||B.loading)&&d(tf,{}),M.isError&&!M.isLoading&&d(K,{title:g(`system.notificationRules.failedToLoadRules`,`Failed to load rules`),message:M.error instanceof Error?M.error.message:g(`system.notificationRules.unknownError`,`Unknown error`),onRetry:()=>void M.refetch()}),!M.isLoading&&!B.loading&&!M.isError&&!B.listFailed(V.key)&&be.length===0&&d(nf,{children:ye?.emptyHint??(`emptyHint`in V?V.emptyHint:g(`system.notificationRules.noRulesYet`,`No rules yet.`))}),be.length>0&&d(rf,{columns:Oe,rows:be,rowKey:e=>`${e.family}:${e.id}`,onRowClick:Ee,minWidthPx:Bf(V.key)}),T.mode===`form`&&d(mp,{rule:T.rule,...T.seed?{seed:T.seed}:{},targets:F.data??[],actuatable:ie,fleet:ne,sequences:fe,onCreateSequence:async e=>{let t=await pe.mutateAsync({sequence:{name:e.name,...e.minDelaySec===void 0?{}:{minDelaySec:e.minDelaySec},actions:[...e.actions]}});return await de.refetch(),t.sequence.id},catalog:ln(I.data?.catalog??[]),taxonomy:I.data?.taxonomy,cameras:z,gateable:re.data??[],gateableScenes:oe,initialEditTab:Rt(S??``)??`rule`,onEditTabChange:e=>C(e===`rule`?null:e),onCancel:Ce,onSaved:()=>{Ce(),M.refetch()}}),B.overlays,O?d(pp,{onCancel:()=>k(!1),onPick:e=>{k(!1),Te(e)}}):null]})})}function pp({onPick:e,onCancel:t}){let{t:n}=Y();return d(_t,{open:!0,onClose:t,title:n(`system.notificationRules.chooseARuleType`,`Choose a rule type`),width:`lg`,children:d(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:vf.map(t=>i(`button`,{type:`button`,"data-testid":`rules-new-${t.type}`,title:t.hint,onClick:()=>e(t.type),className:`flex flex-col items-start gap-1 rounded-lg border border-border bg-surface px-3 py-3 text-left text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[d(`span`,{className:`font-medium text-foreground`,children:t.label}),d(`span`,{className:`text-[10px] font-normal text-foreground-subtle`,children:t.hint})]},t.type))})})}function mp({rule:e,seed:t,targets:s,catalog:c,taxonomy:l,cameras:f,gateable:p,gateableScenes:h,actuatable:g,fleet:_,sequences:v,onCreateSequence:y,initialEditTab:b=Rn,onEditTabChange:x,onSaved:S,onCancel:C}){let w=D(),{t:T}=Y(),O=e!=null&&e.id.length>0,[k]=r(()=>e?Cn(e):sn(t?.delivery,t?.conditions)),[A,j]=r(k),[M,P]=r(null),[F,I]=r(O),[ee,te]=r(null),[L,ne]=r(b),R=e=>j(t=>({...t,...e})),re=e?Bt(e):void 0,ie=u({mutationFn:async()=>{let t=Ht(A,re,c);if(O&&e){let n=yn(A,c);await w.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await w.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:S,onError:e=>P(e instanceof Error?e.message:`Save failed`)}),z=u({mutationFn:async()=>{let e=Ht(A,re,c);return(await w.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>te(null),onSuccess:e=>te(e),onError:e=>P(e instanceof Error?e.message:`Test failed`)}),ae=A.targetIds.map(e=>s.find(t=>t.id===e)?.name??e),oe=a({queryKey:[`userManagement`,`listUsers`],queryFn:()=>w.trpcClient.userManagement.listUsers.query()}).data,se=n(()=>(oe??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[oe]),ce=fn(A),le=ce===`immediate-grouped`,ue=String(A.groupingSec??20),de=Gt(A).map(e=>({...e,label:e.value===`immediate-grouped`?T(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?T(`notificationRules.grouping.hint`,{n:ue,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}}`,ue):e.hint})),fe=de.find(e=>e.value===ce)?.hint,pe=Gr(A,re),me=Oe(A.delivery),he=ye(A),B=Ee(he),ge=ke(he),_e=bn.filter(e=>ge.includes(e.value)),ve=De(A.conditions).length>0,V=be(he),xe=Ae(he),Se=a({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,xe??[]],enabled:xe!==null,queryFn:async()=>{let e=await Promise.all((xe??[]).map(e=>w.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),Ce=n(()=>{if(xe===null||Se.data===void 0)return g;let e=Se.data,t=new Set(Ln(A.deviceScope));return g.filter(n=>e.has(n.id)||t.has(n.id))},[g,xe,Se.data,A.deviceScope]),we=xe!==null&&Se.isLoading,Te=xe!==null&&Se.isError,je=go(),Me=e=>({family:`rule`,field:e,kind:he,delivery:A.delivery,...hn(A)?{systemEventDelivery:`summary`}:{},...A.conditions.systemEvent?{systemEventKinds:[...A.conditions.systemEvent.kinds]}:{}}),Ne=e=>je.data?fo(je.data,Me(e)):void 0,Pe=_n(A),Fe=nn(A.conditions,Wt(A.actions,v)),Ie=A.conditions.identities!==void 0||A.conditions.plates!==void 0,Le=zr(A.delivery,A.conditions),Re=Le.some(e=>e.key===L)?L:Rn;return rn(A.delivery)?d(Ze,{value:Re,onValueChange:e=>{let t=Rt(e);t!==void 0&&(ne(t),x?.(t))},children:i(_t,{open:!0,onClose:C,title:O?T(`system.notificationRules.edit`,`Edit {{name}}`,{name:e?.name}):T(`system.notificationRules.newNotificationRule`,`New notification rule`),icon:N,error:M,width:`lg`,testId:`rule-form-dialog`,beforeBody:i(o,{children:[O&&e&&i(`div`,{className:`mb-3 space-y-2`,children:[d(Hc,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),d(Gc,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??T(`system.notificationRuleStatus.cameraFallback`,{deviceId:e})})]}),d(St,{className:`mb-3`,children:Le.map(e=>d(Je,{value:e.key,children:e.label},e.key))})]}),footer:i(`div`,{className:`flex w-full flex-col gap-3`,children:[Pe.length>0&&i(`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:[d(`p`,{className:`text-foreground`,children:T(`system.notificationRules.savingDrops`,{count:Pe.length})}),Pe.map(e=>i(`p`,{children:[d(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),F&&pe.length>0?d(`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:pe.map(e=>d(`p`,{children:e},e))}):null,d(`div`,{className:`flex justify-end gap-2`,children:i(q,{size:`sm`,type:`button`,disabled:ie.isPending,onClick:()=>{I(!0),P(null),!(!Xt(A,re,new Set(v.map(e=>e.id)))||ie.isPending)&&ie.mutate()},children:[ie.isPending&&d(E,{className:`h-3.5 w-3.5 animate-spin`}),O?T(`system.notificationRules.saveChanges`,`Save changes`):T(`system.notificationRules.createRule`,`Create rule`)]})})]}),children:[i(U,{value:`rule`,className:`space-y-4`,children:[i(`div`,{className:`flex items-end gap-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.name`,`Name`)}),d(W,{value:A.name,onChange:e=>R({name:e.target.value}),placeholder:T(`system.notificationRules.eGFrontDoorPackage`,`e.g. Front door package`)})]}),i(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[d(xt,{checked:A.enabled,onCheckedChange:e=>R({enabled:e}),"aria-label":T(`system.notificationRules.enabled`,`Enabled`)}),T(`system.notificationRules.enabled`,`Enabled`)]})]}),i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.trigger`,`Trigger`)}),d(H,{value:ce,onChange:e=>{let t=qt(e.target.value);t&&j(e=>ir(e,t))},options:de.map(e=>({value:e.value,label:e.label}))}),fe&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:fe}),le&&i(`div`,{className:`mt-2`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),d(W,{type:`number`,min:5,max:60,step:1,value:ue,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=tn(e.target.value);t!==void 0&&R({groupingSec:t})}}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:T(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),Ie&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:T(`notificationRules.grouping.scopedHint`,{n:ue,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,ue)})]}),ce===`immediate`&&Ie&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:T(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!O&&V!==void 0&&d(Ps,{family:V,onChange:e=>j(t=>an(t,e))}),d(Ct,{label:T(`system.notificationRules.deliveryTargets`,`Delivery targets`),targets:s,value:A.targetIds,onChange:e=>j(t=>({...t,targetIds:e})),emptyMessage:T(`system.notificationRules.noDeliveryTargetsConfiguredAdd`,`No delivery targets configured. Add one under the Targets tab first.`),testIdPrefix:`rule-target`}),d(Ye,{mode:`multi`,options:se,value:A.targetUsers,onChange:e=>R({targetUsers:e}),searchable:!0,creatable:!1,label:T(`system.notificationRules.notifyUsers`,`Notify users`),description:T(`system.notificationRules.deliversToTheTargetsEach`,`Delivers to the targets each user owns, only for cameras that user can access.`),emptyMessage:T(`system.notificationRules.noUsersToNotify`,`No users to notify.`),placeholder:T(`system.notificationRules.searchUsers`,`Search users…`),testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),i(U,{value:`devices`,className:`space-y-4`,children:[we&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:T(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Te&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:T(`notificationRules.devices.compatFailed`,`Couldn't check which devices this rule's kind can use — every device is listed. The hub still refuses an incompatible one on save.`)}),d(us,{devices:Ce,scope:A.deviceScope,onChange:e=>R({deviceScope:e}),listState:_.state,savedScope:k.deviceScope,exceptOffered:It(c,`devicesExclude`,A)})]}),d(U,{value:`actions`,className:`space-y-4`,children:d(Mo,{value:A.actions,onChange:e=>R({actions:e}),devices:g,devicesState:_.state,sequences:v,onCreateSequence:y,showProblems:F})}),i(U,{value:`advanced`,className:`space-y-4`,children:[d(Ys,{catalog:c,delivery:A.delivery,conditions:A.conditions,onConditionsChange:e=>R({conditions:e})}),i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.cooldownSeconds`,`Cooldown (seconds)`)}),d(W,{type:`number`,min:0,max:vn,step:1,value:String(A.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=Yt(e.target.value);t!==void 0&&R({cooldownSec:t})}}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[me?T(`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.`):T(`system.notificationRules.theShortestGapBetweenTwo`,`The shortest gap between two deliveries of this rule, counted as chosen below.`),` `,T(`system.notificationRules.cooldownRange`,{max:String(vn)})]})]}),i(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.cooldownCounted`,`Cooldown counted`)}),d(H,{value:A.cooldownScope,onChange:e=>{let t=En(e.target.value);t!==void 0&&R({cooldownScope:t})},options:zt.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:T(`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.`)})]}),i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.acrossObjectClasses`,`Across object classes`)}),d(H,{value:A.cooldownGranularity??`per-class`,onChange:e=>R({cooldownGranularity:Sn(e.target.value)}),options:Hr.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:T(`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.`)})]})]}),i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(xt,{checked:A.snoozeAllowGlobal,onCheckedChange:e=>R({snoozeAllowGlobal:e}),"aria-label":T(`system.notificationRules.allowGlobalSnooze`,`allow global snooze`),disabled:Fe}),T(`system.notificationRules.anyoneMaySnoozeThisRule`,`Anyone may snooze this rule for everyone`)]}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:T(`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.`)})]}),!Fe&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.snoozeButtons`,`Snooze buttons`)}),i(o,{children:[d(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Pt.map(e=>{let t=A.snoozeOptions??or,n=t.includes(e);return d(q,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>R({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Jt(e)},e)})}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:A.snoozeOptions===void 0?T(`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:or.map(Jt).join(`, `)}):A.snoozeOptions.length===0?T(`system.notificationRules.noSnoozeButtonsOnThis`,`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`):T(`system.notificationRules.fourAtMostEverySnooze`,`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`)}),A.snoozeOptions!==void 0&&d(q,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>R({snoozeOptions:void 0}),children:T(`system.notificationRules.backToTheDefaults`,`Back to the defaults`)})]})]}),O&&e&&!Fe&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.silenceItNow`,`Silence it now`)}),d(lc,{ruleId:e.id,ruleName:e.name,exempt:Fe,variant:`full`})]})]}),i(U,{value:`notification`,className:`space-y-4`,children:[i(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.priority`,`Priority`)}),d(H,{value:String(A.priority),onChange:e=>R({priority:Number(e.target.value)}),options:un.map(e=>({value:String(e.value),label:e.label}))})]}),!B.carriesMedia&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:B.mediaBlurb??T(`system.notificationRules.aSystemEventCarriesNo`,`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`)}),B.carriesMedia&&B.mediaBlurb!==void 0&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:B.mediaBlurb}),B.carriesMedia&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.notificationImage`,`Image`)}),d(H,{value:A.mediaImage,onChange:e=>{let t=$t(e.target.value);t&&R({mediaImage:t})},options:_e.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-image`}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:_e.find(e=>e.value===A.mediaImage)?.description}),i(`div`,{className:`mt-2 space-y-1`,children:[ve&&A.mediaImage!==`crop`&&A.mediaImage!==`none`&&i(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:A.mediaShowTriggerZone,onChange:e=>R({mediaShowTriggerZone:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-trigger-zone`}),i(`span`,{children:[T(`system.notificationRules.showTriggerZone`,`Draw the zone that triggered the rule`),d(`span`,{className:`block text-[10px] text-foreground-subtle`,children:T(`system.notificationRules.showTriggerZoneHelp`,`Outlines the zone on the scene. Not drawn on a subject crop.`)})]})]}),i(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:A.mediaGif,onChange:e=>R({mediaGif:e.target.checked}),className:`accent-primary`}),T(`system.notificationRules.attachAGifAroundThe`,`Attach a GIF around the event`)]}),i(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:A.mediaClip,onChange:e=>R({mediaClip:e.target.checked}),className:`accent-primary`}),T(`system.notificationRules.attachAnMp4ClipAround`,`Attach an MP4 clip around the event`)]})]}),(A.mediaGif||A.mediaClip)&&i(`div`,{className:`mt-2`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.videoQuality`,`Video quality`)}),d(H,{value:A.mediaProfile??``,onChange:e=>R({mediaProfile:Lt(e.target.value)}),options:Wr.map(e=>({value:e.value,label:e.label}))}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:T(`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.`)}),d(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.playbackSpeed`,`Playback speed`)}),d(H,{value:A.mediaClipSpeed===void 0?``:String(A.mediaClipSpeed),onChange:e=>R({mediaClipSpeed:wn(e.target.value)}),options:zn.map(e=>({value:e.value,label:e.label}))}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:T(`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.`)})]})]}),he===`sensor`&&B.carriesMedia&&A.mediaImage!==`none`&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:T(`system.notificationRules.linkedCameras`,`Linked cameras`)}),d(H,{value:A.mediaLinkedCameras??``,onChange:e=>R({mediaLinkedCameras:wr(e.target.value)}),options:Ut.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:T(`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.`)})]})]}),i(`div`,{className:`space-y-2`,children:[d(xo,{label:T(`system.notificationRules.notificationTitle`,`Notification title`),value:A.templateTitle,onChange:e=>R({templateTitle:e}),vars:Ne(`title`),testId:`rule-template-title`}),d(xo,{label:T(`system.notificationRules.notificationBody`,`Notification body`),value:A.templateBody,onChange:e=>R({templateBody:e}),vars:Ne(`body`),multiline:!0,testId:`rule-template-body`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:T(`system.notificationRules.leaveBothBlankForThe`,`Leave both blank for the hub's own wording (editable on the Texts tab).`)}),xn(A)!==null&&d(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:xn(A)}),d(So,{context:Me(`body`),title:A.templateTitle,body:A.templateBody,testId:`rule-template-preview`})]})]}),i(U,{value:`conditions`,className:`space-y-4`,children:[i(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:me?T(`system.notificationRules.whichSystemEvents`,`Which system events`):Vr(A.conditions)??T(`system.notificationRules.conditions`,`Conditions`)}),A.conditions.audio!==void 0&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:T(`system.notificationRules.thisIsASoundRule`,`This is a SOUND rule: it fires on a confirmed sampling window of audio, never on a picture. Name the sounds and/or keep a level threshold — with neither it can never match. Everything else below still composes (a camera scope, a schedule).`)}),A.conditions.occupancy!==void 0&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:T(`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.`)}),me&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:T(`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?d(`p`,{className:`text-[10px] text-foreground-subtle`,children:T(`system.notificationRules.conditionCatalogUnavailableThisRule`,`Condition catalog unavailable — this rule matches on its trigger and targets alone.`)}):d(Fs,{catalog:hn(A)?c.filter(e=>e.id!==`schedule`):c,taxonomy:l,delivery:A.delivery,conditions:A.conditions,classScope:A.classScope,onClassScopeChange:e=>R({classScope:e}),actions:Cr(A.actions),sequenceActionsOf:e=>v.find(t=>t.id===e)?.actions,savedConditions:k.conditions,schedule:A.schedule,deviceIds:dn(A),zoneCameraIds:Qo(A.deviceScope,f),cameras:f,fleet:_,allDevices:g,gateable:p,gateableScenes:h,onConditionsChange:e=>R({conditions:e}),onScheduleChange:e=>R({schedule:e})})]}),me&&d($f,{value:A.systemEventDelivery,family:V,onChange:e=>R({systemEventDelivery:e}),draft:()=>Ht(A,re,c)}),O&&e&&i(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:T(`system.notificationRules.testThisRuleForReal`,`Test this rule for real`)}),d(tl,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...dn(A)[0]===void 0?{}:{fallbackDeviceId:dn(A)[0]}})]}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:T(`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.`)})]}),!me&&i(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:T(`system.notificationRules.testRule`,`Test rule`)}),i(q,{size:`sm`,variant:`outline`,type:`button`,disabled:z.isPending||!Xt(A,re,new Set(v.map(e=>e.id))),onClick:()=>{P(null),z.mutate()},children:[z.isPending?d(E,{className:`h-3.5 w-3.5 animate-spin`}):d(m,{className:`h-3.5 w-3.5`}),T(`system.notificationRules.dryRunLast60Min`,`Dry-run (last 60 min)`)]})]}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:T(`system.notificationRules.evaluateTheCurrentUnsavedRule`,`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`)}),ee!==null&&d(gp,{delivery:A.delivery,results:ee,targetNames:ae})]})]})]})}):d(hp,{rule:e,onCancel:C})}function hp({rule:e,onCancel:t}){let{t:n}=Y(),r=Object.keys(e?.conditions??{});return i(_t,{open:!0,onClose:t,title:e?.name??n(`system.notificationRules.rule`,`Rule`),icon:N,width:`lg`,children:[d(G,{variant:`warning`,className:`mb-3`,children:`read-only`}),d(`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:d(Zr,{i18nKey:`system.notificationRules.unsupportedTrigger`,values:{trigger:e?.delivery},components:{code:d(`code`,{})}})}),i(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[i(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:n(`system.notificationRules.trigger`,`Trigger`)}),d(`dd`,{className:`text-foreground`,children:e?.delivery})]}),i(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:n(`system.notificationRules.enabled`,`Enabled`)}),d(`dd`,{className:`text-foreground`,children:e?.enabled?n(`common.yes`):n(`common.no`)})]}),i(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:n(`system.notificationRules.targets`,`Targets`)}),d(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),i(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:n(`system.notificationRules.conditions`,`Conditions`)}),d(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):n(`common.none`)})]})]})]})}function gp({delivery:e,results:t,targetNames:n}){let{t:r}=Y();if(e===`device-event`)return d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:r(`system.notificationRules.deviceEventRulesCannotBe`,`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`)});if(t.length===0)return d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:r(`system.notificationRules.noRecordsInTheLast`,`No records in the last 60 minutes matched — nothing to evaluate.`)});let a=t.filter(e=>e.wouldFire).length;return i(`div`,{className:`mt-2 space-y-1.5`,children:[d(`div`,{className:`text-[11px] text-foreground-subtle`,children:r(`system.notificationRules.wouldFire`,{firing:a,count:t.length})}),d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>i(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?d(C,{className:`h-3.5 w-3.5 shrink-0 text-success`}):d(S,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),i(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),d(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??r(`system.notificationRules.objectFallback`)}),e.wouldFire?i(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,n.join(`, `)||r(`system.notificationRules.targetsFallback`)]}):e.failedCondition&&i(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}e();var _p=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,vp=`block text-[11px] font-medium text-foreground`,yp=[{value:`cap`,labelKey:`system.notificationSequences.stepDo`},{value:`wait`,labelKey:`system.notificationSequences.stepWait`}],bp=[[`notificationRules`,`listSequences`]],xp=[`sequence`,`new`];function Sp(){return{name:``,minDelaySec:``,actions:[jn()]}}function Cp(e){return{id:e.id,name:e.name,minDelaySec:e.minDelaySec===void 0?``:String(e.minDelaySec),actions:[...e.actions]}}function wp(e){return e instanceof Error?e.message:String(e)}function Tp(e){let t=[],n=0;for(;n<e.length;){if(e[n].kind===`wait`){t.push({start:n,kind:`wait`,length:1}),n+=1;continue}let r=Ao(e,n);t.push({start:n,kind:`cap`,length:r.length}),n+=r.length}return t}function Ep(e){let t=e.actions.length;return e.minDelaySec===void 0?J.t(`system.notificationSequences.stepsLabel`,{count:t}):J.t(`system.notificationSequences.stepsDelay`,{count:t,delay:e.minDelaySec})}function Dp({draft:e,devices:t,fleetView:n,onChange:r}){let{t:a}=Y(),o=Tp(e.actions);return i(`div`,{className:`space-y-3`,children:[i(`div`,{className:`flex flex-wrap items-end gap-2`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:vp,children:a(`system.notificationSequences.name`,`Name`)}),d(W,{className:`mt-1`,value:e.name,onChange:t=>r({...e,name:t.target.value})})]}),i(`div`,{className:`w-28`,children:[d(`label`,{className:vp,children:a(`system.notificationSequences.minDelayS`,`Min delay (s)`)}),d(`input`,{type:`number`,min:0,className:_p,value:e.minDelaySec,onChange:t=>r({...e,minDelaySec:t.target.value})})]})]}),i(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[o.map(o=>{let s=e.actions[o.start];if(o.kind===`wait`&&s.kind===`wait`)return d(kp,{step:s,devices:t,listState:n.state,fleet:n,onChange:t=>r({...e,actions:e.actions.map((e,n)=>n===o.start?t:e)}),onRemove:()=>r({...e,actions:e.actions.filter((e,t)=>t!==o.start)})},`s-${String(o.start)}`);let c=Ao(e.actions,o.start);return i(`div`,{className:`flex flex-wrap items-start gap-2`,children:[i(`div`,{className:`w-24`,children:[d(`label`,{className:vp,children:a(`system.notificationSequences.step`,`Step`)}),d(H,{className:_p,value:`cap`,options:yp.map(e=>({value:e.value,label:a(e.labelKey)})),onChange:t=>{t.target.value===`wait`&&r({...e,actions:[...e.actions.slice(0,o.start),{kind:`wait`,seconds:5},...e.actions.slice(o.start+o.length)]})}})]}),d(ei,{value:c.wire,devices:t,listState:n.state,fleet:n,allowMultiSameFamily:!0,onChange:t=>{let n=Oo(t);r({...e,actions:[...e.actions.slice(0,o.start),...n,...e.actions.slice(o.start+o.length)]})}}),d(q,{size:`sm`,variant:`ghost`,type:`button`,title:a(`common.remove`,`Remove`),onClick:()=>r({...e,actions:[...e.actions.slice(0,o.start),...e.actions.slice(o.start+o.length)]}),children:d(p,{className:`h-3.5 w-3.5`})})]},`s-${String(o.start)}`)}),i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({...e,actions:[...e.actions,jn()]}),children:[d(w,{className:`h-3.5 w-3.5`}),` `,a(`common.step`)]})]})]})}function Op({createRequested:e=!1,onCreateConsumed:a,headerOwnsCreate:o=!1}={}){let{t:c}=Y(),l=s(),u=it({}),f=st(),p=mt(),m=lt(),{state:h,openNew:g,openEdit:_,close:v}=wt({editKey:`sequence`,newKey:`new`}),[y,b]=r(null),[x,S]=r(null);t(()=>{e&&(S(null),g(),a?.())},[e]);let C=tt({projection:`slim`}),T=ct(C),E=n(()=>(C.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[C.data]),D=u.data?.sequences??[],O=u.data!==void 0&&D.length===0,k=h.mode!==`closed`,A=f.isPending||p.isPending;t(()=>{if(h.mode===`closed`){b(null),S(null);return}if(h.mode===`new`){b(e=>e!==null&&e.id===void 0?e:Sp());return}let e=D.find(e=>e.id===h.id);e!==void 0&&b(t=>t?.id===h.id?t:Cp(e))},[h,D]);let j=()=>{l.invalidateQueries({queryKey:bp})},M=()=>{f.reset(),p.reset(),S(null),b(null),v()},N=async()=>{if(y===null||y.name.trim()===``||y.actions.length===0)return;let e={name:y.name.trim(),...y.minDelaySec===``?{}:{minDelaySec:Number(y.minDelaySec)},actions:y.actions};try{y.id===void 0?await f.mutateAsync({sequence:e}):await p.mutateAsync({sequenceId:y.id,sequence:e}),M(),j()}catch(e){S(wp(e))}},P=n(()=>[{key:`name`,header:c(`system.notificationSequences.name`,`Name`),nowrap:!1,sortValue:e=>e.name,render:e=>d(af,{name:e.name,enabled:!0,onOpen:()=>_(e.id),openTestId:`sequence-open-${e.id}`})},{key:`steps`,header:c(`system.notificationSequences.steps`,`Steps`),nowrap:!0,sortValue:e=>e.actions.length,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Ep(e)})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:e=>i(ef,{className:`flex items-center justify-end gap-1`,children:[d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>_(e.id),children:c(`common.edit`,`Edit`)}),d(of,{pending:m.isPending,title:c(`system.notificationSequences.deleteThisSequence`,`Delete this sequence?`),message:c(`system.notificationSequences.willBeRemovedRulesAnd`,`“{{name}}” will be removed. Rules and buttons that bind to it keep the id until you re-point them.`,{name:e.name}),ariaLabel:c(`system.notificationSequences.delete`,`Delete {{name}}`,{name:e.name}),testId:`sequence-delete-${e.id}`,onConfirm:()=>{m.mutateAsync({sequenceId:e.id}).then(j)}})]})}],[m,_,c]);return i(ti,{embedded:!0,icon:Ge,title:c(`system.notificationSequences.sequences`,`Sequences`),subtitle:c(`system.notificationSequences.namedStepListsSharedBy`,`Named step lists shared by notification rules and buttons. A rule binds to one by id; two rules sharing a gate share its throttle.`),children:[o?null:d(`div`,{className:`mb-3 flex justify-end`,children:i(q,{size:`sm`,type:`button`,onClick:()=>{S(null),g()},children:[d(w,{className:`h-3.5 w-3.5`}),` `,c(`system.notificationSequences.newSequence`)]})}),u.error!=null&&d(K,{title:c(`system.notificationSequences.couldNotReadSequences`,`Could not read sequences`),message:wp(u.error),onRetry:()=>void u.refetch()}),u.isPending&&d(tf,{}),O&&d(nf,{testId:`sequences-empty`,children:c(`system.notificationSequences.noSequencesYetCreateOne`,`No sequences yet. Create one, then bind it from a rule's Actions tab.`)}),D.length>0&&d(rf,{columns:P,rows:D,rowKey:e=>e.id,minWidthPx:480,onRowClick:e=>_(e.id)}),d(_t,{open:k&&y!==null,onClose:M,title:y?.id===void 0?c(`system.notificationSequences.newSequence`,`New sequence`):c(`system.notificationSequences.edit`,`Edit {{value1}}`,{value1:y.name||`sequence`}),icon:Ge,width:`xl`,error:x,testId:`sequence-editor-panel`,footer:d(q,{size:`sm`,type:`button`,disabled:A||y===null||y.name.trim()===``||y.actions.length===0,onClick:()=>void N(),children:A?c(`system.notificationSequences.saving`,`Saving…`):c(`common.save`,`Save`)}),children:y!==null&&d(Dp,{draft:y,devices:E,fleetView:T,onChange:b})}),m.error!=null&&d(K,{message:wp(m.error)})]})}function kp({step:e,devices:t,listState:n,fleet:r,onChange:a,onRemove:o}){let{t:s}=Y();return i(`div`,{className:`flex flex-wrap items-start gap-2`,children:[i(`div`,{className:`w-24`,children:[d(`label`,{className:vp,children:s(`system.notificationSequences.step`,`Step`)}),d(H,{className:_p,value:`wait`,options:yp.map(e=>({value:e.value,label:s(e.labelKey)})),onChange:n=>a(n.target.value===`wait`?{kind:`wait`,seconds:e.seconds}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``})})]}),i(`div`,{className:`w-28`,children:[d(`label`,{className:vp,children:s(`system.notificationSequences.seconds`,`Seconds`)}),d(`input`,{type:`number`,min:0,max:300,className:_p,value:e.seconds,onChange:e=>a({kind:`wait`,seconds:Number(e.target.value)})})]}),d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:s(`common.remove`,`Remove`),children:d(p,{className:`h-3.5 w-3.5`})})]})}var Ap=`alert-center`;function jp(){let{t:e}=Y(),t=D();return i(`div`,{className:`space-y-3`,"data-testid":`notification-settings`,children:[d(`p`,{className:M,children:e(`systemPage.notifications.settingsHint`,`Alert storage and retention. Alerts are notified only through notification rules on the alert kinds.`)}),d(at,{trpc:t.trpcClient,addonId:Ap,nodeId:`hub`,bare:!0})]})}var Mp=[{value:`object-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.objectLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.objectHint`)}},{value:`track-end`,get label(){return J.t(`helpers.notificationSimulateHelpers.trackEndLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.trackEndHint`)}},{value:`device-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.deviceEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.deviceEventHint`)}},{value:`package-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.packageEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.packageEventHint`)}},{value:`audio-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.audioEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.audioEventHint`)}},{value:`occupancy-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.occupancyEdgeLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.occupancyEdgeHint`)}}];function Np(e){return Mp.find(t=>t.value===e)?.value}function Pp(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Fp(e){return``}var Ip={x:.25,y:.25,w:.5,h:.5},Lp={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Rp(){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:Ip,occupancy:Lp,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function zp(e){return e.deviceId!==null}function Bp(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Vp(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Hp(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 Up(e){if(e.deviceId===null)return null;let t=e.trigger,n=Vp(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:Wp(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 Wp(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 Gp(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Kp(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 qp(e){let t=Rp(),n=e.conditions,r=Kp(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:Gp(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Gp(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Gp(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:Fp(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Jp(n.occupancy)},onlyRuleId:e.id}}function Jp(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 Yp(e){let t=[];return e.conditions.deviceState!==void 0&&t.push({conditionId:`deviceState`,note:J.t(`helpers.notificationSimulateHelpers.caveatDevice`,{deviceId:e.conditions.deviceState.deviceId})}),e.conditions.scene!==void 0&&t.push({conditionId:`scene`,note:J.t(`helpers.notificationSimulateHelpers.caveatScene`,{state:e.conditions.scene.requiredState})}),e.conditions.customZones!==void 0&&e.conditions.customZones.length>0&&t.push({conditionId:`customZones`,note:J.t(`helpers.notificationSimulateHelpers.caveatZones`)}),t}function Xp(e){return{form:qp(e),caveats:Yp(e),ruleName:e.name}}var Zp=null;function Qp(e){Zp=e}function $p(){return Zp}function em(){Zp=null}var tm=[`n/a`,`clear`,`suppressed`,`bypassed`],nm=[`live`,`none`,`unavailable`,`unattachable`];function rm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function im(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 om(e){if(!rm(e))return null;let t=im(e,`ruleId`),n=im(e,`ruleName`),r=im(e,`cooldown`),i=tm.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=im(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 sm(e){if(!rm(e))return null;let t=im(e,`recordId`),n=im(e,`delivery`),r=im(e,`still`),i=nm.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=om(e);t!==null&&o.push(t)}let s=im(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 cm(e){if(e.droppedBy!==void 0)return J.t(`helpers.notificationSimulateHelpers.dropped`,{reason:e.droppedBy});if(e.candidates===0)return J.t(`helpers.notificationSimulateHelpers.noCandidates`,{delivery:e.delivery});let t=e.outcomes.filter(e=>e.matched).length,n=e.outcomes.reduce((e,t)=>e+t.enqueued,0);return t===0?J.t(`helpers.notificationSimulateHelpers.noneMatched`,{count:e.candidates}):J.t(`helpers.notificationSimulateHelpers.matchedSummary`,{matched:t,candidates:e.candidates,enqueued:n})}var lm=new Set([`sensor`,`control`,`custom`]);function um({form:e,cameras:t,taxonomy:n,kinds:r,kindsLoading:a,onPatch:o}){let{t:s}=Y(),c=e.deviceId===null?[]:[e.deviceId],l=Me(`classes`,n);if(e.trigger===`device-event`)return i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),d(dm,{form:e,kinds:r,loading:a,onPatch:o})]});if(e.trigger===`audio-event`){let n=r.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(`div`,{children:[d(`label`,{className:X,children:s(`system.notificationSimulateFields.audioClasses`,`Audio classes`)}),d(Mn,{options:n,value:e.classNames,onChange:e=>o({classNames:e}),loading:a,emptyHint:e.deviceId===null?`Pick a camera first — the audio vocabulary is per camera.`:`This camera advertises no audio kinds. The audio classifier is probably off for it.`,placeholder:s(`system.notificationSimulateFields.audioClassId`,`Audio class id…`)})]}),i(`div`,{children:[d(`label`,{className:X,children:s(`system.notificationSimulateFields.zones`,`Zones`)}),d(Ur,{deviceIds:c,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]})]})}return e.trigger===`occupancy-event`?i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),d(fm,{form:e,cameras:t,taxonomy:n,onPatch:o})]}):i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(`div`,{children:[d(`label`,{className:X,children:s(`system.notificationSimulateFields.detectedClasses`,`Detected classes`)}),l===null?d(Nn,{value:e.classNames,placeholder:s(`system.notificationSimulateFields.classIdPersonCar`,`Class id (person, car…)`),onChange:e=>o({classNames:e})}):d(Lr,{picker:l,value:e.classNames,onChange:e=>o({classNames:e})})]}),i(`div`,{children:[d(`label`,{className:X,children:s(`system.notificationSimulateFields.zonesTheSubjectIsIn`,`Zones the subject is in`)}),d(Ur,{deviceIds:c,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&i(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:s(`system.notificationSimulateFields.packagePhase`,`Package phase`)}),d(H,{value:e.packagePhase,options:[{value:``,label:s(`system.notificationSimulateFields.none`,`— none —`)},{value:`delivered`,label:s(`system.notificationSimulateFields.delivered`,`Delivered`)},{value:`picked-up`,label:s(`system.notificationSimulateFields.pickedUp`,`Picked up`)}],onChange:e=>o({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function dm({form:e,kinds:t,loading:n,onPatch:r}){let{t:a}=Y(),s=t.filter(e=>lm.has(e.category)),c=s.find(t=>t.kind===e.sensorKind);return i(o,{children:[i(`div`,{children:[d(`label`,{className:X,children:a(`system.notificationSimulateFields.eventKind`,`Event kind`)}),d(H,{value:e.sensorKind,options:[{value:``,label:n?a(`system.notificationSimulateFields.loadingKinds`,`Loading kinds…`):a(`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);r({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!n&&s.length===0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.deviceId===null?a(`system.notificationSimulateFields.pickACameraFirstSensor`,`Pick a camera first — sensor and control kinds come from the devices linked to it.`):a(`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.`)})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:X,children:a(`system.notificationSimulateFields.sourceDevice`,`Source device`)}),d(W,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:a(`system.notificationSimulateFields.theCameraItself`,`the camera itself`),onChange:e=>r({sourceDeviceId:Bp(e.target.value)??null})}),d(`p`,{className:Un,children:c===void 0?a(`system.notificationSimulateFields.theLinkedDeviceWhoseState`,`The linked device whose state changed. Filled in for you when you pick a kind.`):a(`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})})]}),i(`div`,{children:[d(`label`,{className:X,children:a(`system.notificationSimulateFields.eventTypeToken`,`Event type token`)}),d(W,{value:e.eventType,placeholder:a(`system.notificationSimulateFields.pressPressLong`,`press, press_long…`),onChange:e=>r({eventType:e.target.value})}),d(`p`,{className:Un,children:a(`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 fm({form:e,cameras:t,taxonomy:n,onPatch:r}){let{t:a}=Y(),s=e.deviceId===null?[]:[e.deviceId],c=Me(`occupancy`,n),l=c===null?[]:c.groups.flatMap(e=>e.options),u=e.occupancy,f=e=>r({occupancy:{...u,...e}});return i(o,{children:[i(`div`,{children:[d(`label`,{className:X,children:a(`system.notificationSimulateFields.zone`,`Zone`)}),d(Ur,{deviceIds:s,cameras:t,value:u.zoneId===``?[]:[u.zoneId],onChange:e=>f({zoneId:e[e.length-1]??``})}),d(`p`,{className:Un,children:a(`system.notificationSimulateFields.leaveEmptyForTheWhole`,`Leave empty for the whole frame.`)})]}),i(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:X,children:a(`system.notificationSimulateFields.class`,`Class`)}),d(H,{value:u.className,options:[{value:``,label:a(`system.notificationSimulateFields.anyClass`,`— any class —`)},...l.map(e=>({value:e.value,label:e.label}))],onChange:e=>f({className:e.target.value})})]}),i(`div`,{className:`flex flex-wrap items-end gap-3`,children:[i(`label`,{className:`text-[11px] text-foreground-subtle`,children:[a(`system.notificationSimulateFields.countNow`,`Count now`),d(W,{type:`number`,min:0,className:`w-20`,value:String(u.count),onChange:e=>f({count:Bp(e.target.value)??0})})]}),i(`label`,{className:`text-[11px] text-foreground-subtle`,children:[a(`system.notificationSimulateFields.countBefore`,`Count before`),d(W,{type:`number`,min:0,className:`w-20`,value:String(u.previousCount),onChange:e=>f({previousCount:Bp(e.target.value)??0})})]}),i(`label`,{className:`text-[11px] text-foreground-subtle`,children:[a(`system.notificationSimulateFields.threshold`,`Threshold`),d(W,{type:`number`,min:1,className:`w-20`,value:String(u.threshold),onChange:e=>f({threshold:Bp(e.target.value)??1})})]}),i(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[d(xt,{checked:u.occupied,onCheckedChange:e=>f({occupied:e}),"aria-label":a(`system.notificationSimulateFields.occupiedLabel`)}),a(`system.notificationSimulateFields.occupiedLabel`,`Occupied`)]})]})]})}function pm({form:e,cameras:t,onPatch:n}){let{t:r}=Y(),a=e.deviceId===null?[]:[e.deviceId];return i(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[d(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:r(`system.notificationSimulateFields.advanced`,`Advanced`)}),i(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(xt,{checked:e.crossingEnabled,onCheckedChange:e=>n({crossingEnabled:e}),"aria-label":r(`system.notificationSimulateFields.zoneCrossing`,`zone crossing`)}),r(`system.notificationSimulateFields.thisEventIsAConfirmed`,`This event is a confirmed zone crossing`)]}),e.crossingEnabled&&i(`div`,{className:`mt-1 space-y-1.5`,children:[d(`div`,{className:`max-w-[12rem]`,children:d(H,{value:e.crossingDirection,options:[{value:`enter`,label:r(`system.notificationSimulateFields.enteredTheZone`,`Entered the zone`)},{value:`exit`,label:r(`system.notificationSimulateFields.leftTheZone`,`Left the zone`)}],onChange:e=>n({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),d(Ur,{deviceIds:a,cameras:t,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>n({crossingZoneId:e[e.length-1]??``})})]})]}),i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(xt,{checked:e.bboxEnabled,onCheckedChange:e=>n({bboxEnabled:e}),"aria-label":r(`system.notificationSimulateFields.boundingBox`,`bounding box`)}),r(`system.notificationSimulateFields.carryABoundingBox`,`Carry a bounding box`)]}),d(`p`,{className:Un,children:r(`system.notificationSimulateFields.normalized01TopLeft`,"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed.")}),e.bboxEnabled&&d(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>i(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,d(W,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:r=>n({bbox:{...e.bbox,[t]:Bp(r.target.value)??0}})})]},t))})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:X,children:r(`system.notificationSimulateFields.happenedAt`,`Happened at`)}),i(`div`,{className:`flex items-center gap-2`,children:[d(W,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>n({timestampLocal:e.target.value})}),e.timestampLocal===``?d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:Hp(Date.now())}),children:r(`system.notificationSimulateFields.set`,`Set`)}):d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:``}),children:r(`system.notificationSimulateFields.now`,`Now`)})]}),d(`p`,{className:Un,children:r(`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.`)})]}),i(`div`,{children:[d(`label`,{className:X,children:r(`system.notificationSimulateFields.detectionSource`,`Detection source`)}),d(H,{value:e.source,options:[{value:``,label:r(`system.notificationSimulateFields.unsetReadsAsPipeline`,`— unset (reads as pipeline) —`)},{value:`pipeline`,label:r(`system.notificationSimulateFields.pipeline`,`Pipeline`)},{value:`onboard`,label:r(`system.notificationSimulateFields.onboardCamera`,`Onboard (camera)`)},{value:`sensor`,label:r(`system.notificationSimulateFields.sensor`,`Sensor`)},{value:`audio`,label:r(`system.notificationSimulateFields.audio`,`Audio`)}],onChange:e=>{let t=e.target.value;n({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function mm({checked:e,label:t,hint:n,danger:r=!1,onChange:a}){let{t:o}=Y();return i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(xt,{checked:e,onCheckedChange:a,"aria-label":t}),t,r&&d(G,{variant:`danger`,children:o(`system.notificationSimulateFields.actuatesDevices`,`actuates devices`)})]}),d(`p`,{className:Un,children:n})]})}e();var hm={live:`A live snapshot of the camera was taken and attached.`,none:`No still was requested.`,unavailable:`A still was requested but the camera could not produce one.`,unattachable:`This trigger cannot carry a still at all — an audio or occupancy notification freezes no media owner, so it ships text-only in production too. This is not a limit of the test.`},gm={"n/a":`The rule did not match, so no cooldown was consulted.`,clear:`No cooldown was in effect — the rule was free to fire.`,suppressed:`A cooldown from an earlier fire silenced this one. Re-run with "Ignore cooldown".`,bypassed:`A cooldown was in effect and was deliberately ignored for this run.`};function _m({result:e,targetName:t}){let{t:n}=Y();return i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[d(`p`,{className:`text-xs font-medium text-foreground`,children:cm(e)}),i(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[d(vm,{recordId:e.recordId}),d(`span`,{children:d(Zr,{i18nKey:`system.notificationSimulateResult.delivery`,values:{value:e.delivery},components:{b:d(`span`,{className:`text-foreground`})}})}),d(`span`,{children:d(Zr,{i18nKey:`system.notificationSimulateResult.candidates`,values:{value:e.candidates},components:{b:d(`span`,{className:`text-foreground`})}})}),d(`span`,{title:hm[e.still],children:d(Zr,{i18nKey:`system.notificationSimulateResult.still`,values:{value:e.still},components:{b:d(`span`,{className:`text-foreground`})}})}),e.droppedBy!==void 0&&d(G,{variant:`warning`,children:n(`system.notificationSimulateResult.droppedBy`,{by:e.droppedBy})})]}),e.notes.length>0&&d(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>d(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:d(Zr,{i18nKey:`system.notificationSimulateResult.noRuleEvaluated`,values:{delivery:e.delivery},components:{b:d(`span`,{className:`text-foreground`})}})}):d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>d(ym,{outcome:e,targetName:t},e.ruleId))})]})}function vm({recordId:e}){let{t}=Y(),[n,a]=r(!1);return i(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[d(`code`,{className:`text-[10px] text-foreground`,children:e}),d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),1500)},()=>a(!1))},title:t(`system.notificationSimulateResult.copyRecordId`,`Copy record id`),children:d(_,{className:`h-3 w-3`})}),n&&d(`span`,{className:`text-[10px] text-success`,children:t(`common.copiedLower`)})]})}function ym({outcome:e,targetName:t}){let{t:n}=Y();return i(`li`,{className:`space-y-1 px-2.5 py-2`,children:[i(`div`,{className:`flex items-center gap-2`,children:[e.matched?d(C,{className:`h-3.5 w-3.5 shrink-0 text-success`}):d(S,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),i(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:gm[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&d(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?n(`system.notificationSimulateResult.didNotMatchTheEngine`,`Did not match. The engine reported no failing condition id.`):d(Zr,{i18nKey:`system.notificationSimulateResult.failingCondition`,values:{condition:e.failedCondition},components:{code:d(`code`,{className:`text-foreground`})}})}),e.matched&&i(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[n(`system.notificationSimulateResult.enqueued`,{count:e.enqueued}),e.targetIds.length>0?` → ${e.targetIds.map(t).join(`, `)}`:` — ${n(`system.notificationSimulateResult.noTargetResolved`)}`,`.`]}),e.matchedOn!==void 0&&e.matchedOn.length>0&&d(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:n(`system.notificationSimulateResult.matchedOn`,{on:e.matchedOn.join(`, `)})})]})}e();var bm=`pipeline-analytics`,xm=`nc.injectTestEvent`;function Sm(){let{t:e}=Y(),o=D(),[s,c]=r(()=>$p()?.form??Rp()),[l,f]=r(()=>$p()?.caveats??[]),[p,g]=r(()=>$p()?.ruleName??null);t(()=>em(),[]);let[_,v]=r(null),[y,b]=r(!1),[x,S]=r(null),C=e=>c(t=>({...t,...e})),w=tt({projection:`slim`}),T=a({queryKey:lp,queryFn:()=>o.trpcClient.notificationRules.getConditionCatalog.query({})}),O=a({queryKey:sp,queryFn:async()=>(await o.trpcClient.notificationRules.listRules.query({})).rules}),k=a({queryKey:cp,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),A=s.deviceId,j=a({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:A}],enabled:A!==null,staleTime:6e4,queryFn:async()=>A===null?[]:(await o.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[A]})).flatMap(e=>[...e.kinds])}),M=n(()=>(w.data??[]).filter(e=>e.type===he.Camera).map(e=>({id:e.id,name:e.name})),[w.data]),N=T.data?.taxonomy,P=j.data??[],F=n(()=>{let e=new Map;for(let t of k.data??[])e.set(t.id,t.name);return e},[k.data]),I=u({mutationFn:async()=>{let e=Up(s);if(e===null)throw Error(`Pick a camera first.`);return o.trpcClient.addons.custom.mutate({addonId:bm,action:xm,input:e})},onMutate:()=>{v(null),b(!1),S(null)},onSuccess:e=>{let t=sm(e);v(t),b(t===null)},onError:e=>S(e instanceof Error?e.message:`The simulation failed.`)}),ee=Pp(s.trigger),te=O.data?.find(e=>e.id===s.onlyRuleId);return i(ti,{embedded:!0,icon:m,title:e(`system.notificationSimulate.simulateAnEvent`,`Simulate an event`),subtitle:e(`system.notificationSimulate.injectASyntheticDetectionDoorbell`,`Inject a synthetic detection, doorbell press or occupancy edge and see exactly which rules match it, which condition each one fails on, and what would be delivered. Nothing is persisted — no track, no event row, no media.`),children:[w.isError&&d(K,{title:e(`system.notificationSimulate.failedToLoadCameras`,`Failed to load cameras`),message:w.error instanceof Error?w.error.message:e(`system.notificationSimulate.unknownError`,`Unknown error`),onRetry:()=>void w.refetch()}),p!==null&&d(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:d(Zr,{i18nKey:`system.notificationSimulate.seededFrom`,values:{rule:p},components:{b:d(`span`,{className:`font-medium`})}})}),l.length>0&&d(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:l.map(e=>i(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[d(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),d(`span`,{children:e.note})]},e.conditionId))}),i(Ot,{className:`space-y-4`,children:[i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.ruleToSimulate`,`Rule to simulate`)}),d(H,{"data-testid":`simulate-seed-rule`,value:s.onlyRuleId,options:[{value:``,label:e(`system.notificationSimulate.pickARuleToPrefill`,`— pick a rule to prefill trigger + conditions —`)},...(O.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.delivery}`}))],onChange:e=>{let t=e.target.value;if(t.length===0){c(Rp()),f([]),g(null);return}let n=O.data?.find(e=>e.id===t);if(n===void 0){C({onlyRuleId:t});return}c(qp(n)),f(Yp(n)),g(n.name)}}),d(`p`,{className:Un,children:e(`system.notificationSimulate.picksTheTriggerThatRule`,`Picks the trigger that rule listens for and fills the fields from its conditions. Edit any value below, then inject.`)})]}),i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.camera`,`Camera`)}),d(H,{"data-testid":`simulate-camera`,value:s.deviceId===null?``:String(s.deviceId),options:[{value:``,label:M.length===0?e(`system.notificationSimulate.loadingCameras`,`Loading cameras…`):e(`system.notificationSimulate.pickACamera`,`— pick a camera —`)},...M.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{C({deviceId:Bp(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...s.occupancy,zoneId:``}})}}),d(`p`,{className:Un,children:e(`system.notificationSimulate.theCameraTheEventIs`,`The camera the event is attributed to — what a notification shows.`)})]}),i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.trigger`,`Trigger`)}),d(H,{"data-testid":`simulate-trigger`,value:s.trigger,options:Mp.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Np(e.target.value);if(!t)return;let n=Fp(s.trigger);C({trigger:t,source:s.source===``||s.source===n?Fp(t):s.source})}}),i(`p`,{className:Un,children:[Mp.find(e=>e.value===s.trigger)?.hint,` `,d(Zr,{i18nKey:`system.notificationSimulate.onlyRulesWhoseTrigger`,values:{delivery:ee},components:{b:d(`span`,{className:`text-foreground`})}})]})]}),d(um,{form:s,cameras:M,taxonomy:N,kinds:P,kindsLoading:j.isLoading,onPatch:C}),i(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[d(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:e(`system.notificationSimulate.quality`,`Quality`)}),i(`div`,{className:`mt-2 space-y-3`,children:[d(`p`,{className:Un,children:e(`system.notificationSimulate.everyFieldHereCanBe`,`Every field here can be left EMPTY, and empty is a real state: a rule with a minimum confidence FAILS on a subject that carries none. Leave one blank to reproduce exactly that.`)}),i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.labelIdentityNamePlateSubclass`,`Label (identity name / plate / subclass)`)}),d(W,{value:s.label,placeholder:e(`system.notificationSimulate.eGMarcoAb123cd`,`e.g. Marco, AB123CD`),onChange:e=>C({label:e.target.value})})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.detectionConfidence`,`Detection confidence`)}),d(br,{value:s.confidence,min:0,max:1,step:.05,onChange:e=>C({confidence:e})})]}),i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.labelMatchConfidence`,`Label-match confidence`)}),d(br,{value:s.labelConfidence,min:0,max:1,step:.05,onChange:e=>C({labelConfidence:e})})]}),i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.importance`,`Importance`)}),d(br,{value:s.importance,min:0,max:1,step:.05,onChange:e=>C({importance:e})})]}),i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.dwellSeconds`,`Dwell (seconds)`)}),d(br,{value:s.dwellSeconds,min:0,step:1,onChange:e=>C({dwellSeconds:e})})]})]})]})]}),d(pm,{form:s,cameras:M,onPatch:C}),i(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:e(`system.notificationSimulate.howToRunIt`,`How to run it`)}),d(mm,{checked:s.bypassCooldown,label:e(`system.notificationSimulate.ignoreTheCooldown`,`Ignore the cooldown`),hint:e(`system.notificationSimulate.aRuleThatAlreadyFired`,`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`),onChange:e=>C({bypassCooldown:e})}),d(mm,{checked:s.bypassMute,label:e(`system.notificationSimulate.ignoreMutesAndSnoozes`,`Ignore mutes and snoozes`),hint:e(`system.notificationSimulate.aMutedCameraOrA`,`A muted camera or a snoozed rule drops the event before any rule is consulted.`),onChange:e=>C({bypassMute:e})}),d(mm,{checked:s.runActions,danger:!0,label:e(`system.notificationSimulate.runTheRuleSActions`,`Run the rule's actions — this actuates real devices`),hint:e(`system.notificationSimulate.aMatchedRuleSOntrigger`,`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`),onChange:e=>C({runActions:e})}),i(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:X,children:e(`system.notificationSimulate.stillImage`,`Still image`)}),d(H,{value:s.still,options:[{value:`live`,label:e(`system.notificationSimulate.liveSnapshotOfTheCamera`,`Live snapshot of the camera`)},{value:`none`,label:e(`system.notificationSimulate.noImage`,`No image`)}],onChange:e=>C({still:e.target.value===`none`?`none`:`live`})})]}),i(`div`,{children:[d(`label`,{className:X,children:e(`system.notificationSimulate.evaluateOnlyOneRule`,`Evaluate only one rule`)}),d(H,{value:s.onlyRuleId,options:[{value:``,label:e(`system.notificationSimulate.everyEnabledRule`,`— every enabled rule —`)},...(O.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>C({onlyRuleId:e.target.value})}),s.onlyRuleId.length>0&&te===void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:d(Zr,{i18nKey:`system.notificationSimulate.ruleNotInList`,values:{id:s.onlyRuleId},components:{code:d(`code`,{})}})})]})]}),x!==null&&d(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:x}),i(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[d(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:e(`system.notificationSimulate.nothingIsPersistedNoTrack`,`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`)}),i(q,{size:`sm`,type:`button`,disabled:I.isPending||!zp(s),onClick:()=>I.mutate(),children:[I.isPending?d(E,{className:`h-3.5 w-3.5 animate-spin`}):d(m,{className:`h-3.5 w-3.5`}),e(`system.notificationSimulate.injectEvent`,`Inject event`)]})]})]}),y&&d(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:e(`system.notificationSimulate.theHubAnsweredButThis`,`The hub answered, but this build could not read the answer. That is what a hub older than the simulator looks like — update the server, then re-run.`)}),_!==null&&d(_m,{result:_,targetName:e=>F.get(e)??e})]})}var Cm=e=>typeof e==`string`&&e.length>0;function wm(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 Tm(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Em(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Cm(i)&&n.push({mediaType:r,url:i})}return n}function Dm(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Cm(r.label),i=Cm(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:J.t(`helpers.notificationTestComposer.actionN`,{n:n.length+1}),...i?{url:r.url}:{}})}return n}function Om(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Em(e,t.attachmentUrls),i=Dm(e,t.actions),a=e.ttl&&Cm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:Tm(e,t.format),priority:km(t.priority),...Cm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Cm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Cm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Cm(t.tag)?{tag:t.tag}:{}}}function km(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function Am(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 jm(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Mm={image:g(`/addon/notifiers/samples/image`),video:g(`/addon/notifiers/samples/video`),gif:g(`/addon/notifiers/samples/gif`),audio:g(`/addon/notifiers/samples/audio`),icon:g(`/addon/notifiers/samples/icon`)};function Nm(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function Pm(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])Nm(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function Fm(e,t,n){let r=jm(e);return Nm(e,t)?{...r,body:n,attachmentUrls:{[t]:Mm[t]}}:{...r,body:n}}function Im(e,t){let n=jm(e);switch(t){case`text`:return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetText`)};case`image`:return Fm(e,`image`,J.t(`helpers.notificationTestComposer.presetImage`));case`gif`:return Fm(e,`gif`,J.t(`helpers.notificationTestComposer.presetGif`));case`video`:return Fm(e,`video`,J.t(`helpers.notificationTestComposer.presetVideo`));case`audio`:return Fm(e,`audio`,J.t(`helpers.notificationTestComposer.presetAudio`));case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:J.t(`helpers.notificationTestComposer.actionN`,{n:t+1}),url:`/`}));return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetActions`),actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=Am(e);return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetCritical`),priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}e();var Lm={get text(){return J.t(`system.notificationTestPanel.presetText`)},get image(){return J.t(`system.notificationTestPanel.presetImage`)},get gif(){return J.t(`system.notificationTestPanel.presetGif`)},get video(){return J.t(`system.notificationTestPanel.presetVideo`)},get audio(){return J.t(`system.notificationTestPanel.presetAudio`)},get actions(){return J.t(`system.notificationTestPanel.presetActions`)},get critical(){return J.t(`system.notificationTestPanel.presetCritical`)},get overflow(){return J.t(`system.notificationTestPanel.presetOverflow`)}},Rm=`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`,zm=`block text-[11px] font-medium text-foreground mb-1`;function Bm({target:e,kind:t,open:a,onClose:o}){let{t:s}=Y(),c=D(),l=n(()=>wm(t.caps),[t.caps]),f=n(()=>Pm(t.caps),[t.caps]),[p,m]=r(()=>jm(t.caps)),[h,g]=r(null),_=n(()=>Om(t.caps,p),[t.caps,p]),v=p.body.length,y=v>l.bodyMaxLen,b=e=>m(t=>({...t,...e})),x=u({mutationFn:()=>c.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:Om(t.caps,p)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:J.t(`system.notificationTestPanel.testFailed`)})}),S=e=>{m(Im(t.caps,e)),g(null)},C=(e,t,n)=>{let r=p.actions.length>0?[...p.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},b({actions:r})};return d(dt,{open:a,onOpenChange:e=>!e&&o(),children:i(vt,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[d(Dt,{children:d(bt,{children:s(`system.notificationTestPanel.testTitle`,{name:e.name,kind:t.label})})}),i(qe,{className:`space-y-4 pr-1`,children:[d(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map(e=>d(q,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>S(e),children:Lm[e]},e))}),i(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[l.levels.length>0&&i(`div`,{children:[d(`label`,{className:zm,children:s(`system.notificationTestPanel.level`,`Level`)}),i(`select`,{className:Rm,value:p.level,onChange:e=>b({level:e.target.value}),children:[d(`option`,{value:``,children:s(`system.notificationTestPanel.deriveFromPriority`,`— derive from priority —`)}),l.levels.map(e=>i(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (${s(`system.notificationTestPanel.qualitative`)})`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=l.levels.find(e=>e.id===p.level);return e?i(`div`,{className:`mt-1 space-y-1`,children:[e.description&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),i(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&d(G,{variant:`danger`,"data-testid":`flag-critical`,children:s(`system.notificationTestPanel.critical`)}),e.flags?.silent&&d(G,{variant:`info`,children:s(`system.notificationTestPanel.silent`)}),e.flags?.noPush&&d(G,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&i(`p`,{className:`text-[10px] text-warning`,children:[s(`system.notificationTestPanel.requiresTargetConfig`,`Requires target config:`),` `,e.requires.join(`, `)]})]}):null})()]}),i(`div`,{children:[i(`label`,{className:zm,children:[s(`system.notificationTestPanel.priorityOrdinal`,`Priority (ordinal):`),` `,p.priority]}),d(`input`,{type:`range`,min:1,max:5,step:1,value:p.priority,onChange:e=>b({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":s(`system.notificationTestPanel.priority`)})]})]}),l.formats.length>0&&i(`div`,{children:[d(`label`,{className:zm,children:s(`system.notificationTestPanel.format`,`Format`)}),d(`div`,{className:`flex flex-wrap gap-2`,children:l.formats.map(e=>i(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:p.format===e,onChange:()=>b({format:e})}),e]},e))})]}),i(`div`,{children:[d(`label`,{className:zm,children:s(`system.notificationTestPanel.testTitle`,`Title`)}),d(`input`,{className:Rm,value:p.title,onChange:e=>b({title:e.target.value})})]}),i(`div`,{children:[i(`label`,{className:zm,children:[s(`system.notificationTestPanel.body`),` `,i(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,l.bodyMaxLen,y?` — ${s(`system.notificationTestPanel.overflow`)}`:``,`)`]})]}),d(`textarea`,{className:`${Rm} min-h-[80px] resize-y`,value:p.body,onChange:e=>b({body:e.target.value})})]}),l.attachmentSlots.length>0&&i(`div`,{children:[i(`label`,{className:zm,children:[s(`system.notificationTestPanel.attachments`),` `,d(`span`,{className:`text-foreground-subtle`,children:l.attachmentMaxBytes?s(`system.notificationTestPanel.attachmentsMetaMb`,{mode:l.attachmentMode,max:l.attachmentMax,mb:Math.round(l.attachmentMaxBytes/1024/1024)}):s(`system.notificationTestPanel.attachmentsMeta`,{mode:l.attachmentMode,max:l.attachmentMax})})]}),d(`div`,{className:`space-y-1.5`,children:l.attachmentSlots.map(e=>i(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),d(`input`,{className:Rm,placeholder:s(`system.notificationTestPanel.url`,`{{mt}} URL`,{mt:e}),value:p.attachmentUrls[e]??``,onChange:t=>b({attachmentUrls:{...p.attachmentUrls,[e]:t.target.value}})})]},e))})]}),l.showActions&&i(`div`,{children:[d(`label`,{className:zm,children:s(`system.notificationTestPanel.actionsUpTo`,{max:l.maxActions})}),d(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(l.maxActions,3)},(e,t)=>i(`div`,{className:`flex items-center gap-2`,children:[d(`input`,{className:Rm,placeholder:s(`system.notificationTestPanel.actionLabelPlaceholder`),value:p.actions[t]?.label??``,onChange:e=>C(t,`label`,e.target.value)}),d(`input`,{className:Rm,placeholder:s(`system.notificationTestPanel.actionUrlPlaceholder`),value:p.actions[t]?.url??``,onChange:e=>C(t,`url`,e.target.value)})]},t))})]}),i(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[l.showClickUrl&&i(`div`,{children:[d(`label`,{className:zm,children:s(`system.notificationTestPanel.clickUrl`,`Click URL`)}),d(`input`,{className:Rm,value:p.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),l.showSound&&i(`div`,{children:[d(`label`,{className:zm,children:s(`system.notificationTestPanel.sound`,`Sound`)}),d(`input`,{className:Rm,value:p.sound,onChange:e=>b({sound:e.target.value})})]}),l.showTtl&&i(`div`,{children:[d(`label`,{className:zm,children:s(`system.notificationTestPanel.ttlSeconds`,`TTL (seconds)`)}),d(`input`,{className:Rm,type:`number`,value:p.ttl,onChange:e=>b({ttl:e.target.value})})]}),l.showTag&&i(`div`,{children:[d(`label`,{className:zm,children:s(`system.notificationTestPanel.tag`,`Tag`)}),d(`input`,{className:Rm,value:p.tag,onChange:e=>b({tag:e.target.value})})]})]}),h&&d(Vm,{result:h}),i(`details`,{className:`text-[10px]`,children:[d(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:s(`system.notificationTestPanel.payloadPreview`,`Payload preview`)}),d(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),i(Tt,{children:[d(q,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:s(`common.close`,`Close`)}),i(q,{size:`sm`,type:`button`,disabled:x.isPending||p.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?d(E,{className:`h-3.5 w-3.5 animate-spin`}):d(Ke,{className:`h-3.5 w-3.5`}),s(`system.notificationTestPanel.sendTest`,`Send test`)]})]})]})})}function Vm({result:e}){let{t}=Y(),n=e.renderedAs;return i(`div`,{className:`rounded-md border px-3 py-2 text-xs ${e.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[i(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?d(C,{className:`h-3.5 w-3.5 text-success`}):d(S,{className:`h-3.5 w-3.5 text-danger`}),d(`span`,{children:e.success?t(`system.notificationTestPanel.delivered`,`Delivered`):t(`system.notificationTestPanel.failed`,`Failed`)})]}),e.error&&d(`p`,{className:`mt-1 text-danger`,children:e.error}),n&&i(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[d(`dt`,{children:t(`system.notificationTestPanel.resolvedLevel`,`Resolved level`)}),d(`dd`,{className:`text-foreground`,children:n.level}),d(`dt`,{children:t(`system.notificationTestPanel.formatSent`,`Format sent`)}),d(`dd`,{className:`text-foreground`,children:n.format}),d(`dt`,{children:t(`system.notificationTestPanel.attachmentsSent`,`Attachments sent`)}),d(`dd`,{className:`text-foreground`,children:n.attachmentsSent}),d(`dt`,{children:t(`system.notificationTestPanel.actionsSent`,`Actions sent`)}),d(`dd`,{className:`text-foreground`,children:n.actionsSent}),d(`dt`,{children:t(`system.notificationTestPanel.truncated`,`Truncated`)}),d(`dd`,{className:`text-foreground`,children:n.truncated?t(`common.yes`):t(`common.no`)}),d(`dt`,{children:t(`system.notificationTestPanel.dropped`,`Dropped`)}),d(`dd`,{className:`text-foreground`,children:n.dropped.length>0?n.dropped.join(`, `):`—`})]})]})}function Hm(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.addonId);e?e.push(r):(n.set(r.addonId,[r]),t.push(r.addonId))}return t.map(e=>({addonId:e,kinds:n.get(e)??[]}))}function Um(e){let t=[],n=e=>{for(let r of e){if(r.type===`password`){t.push(r.key);continue}if(r.type===`group`){n(r.fields);continue}if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields)}};for(let t of e.sections)n(t.fields);return t}function Wm(e){let t=new Map,n=e=>{for(let r of e)if(r.type===`group`)n(r.fields);else if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields);else r.type!==`separator`&&t.set(r.key,r.label)};for(let t of e.sections)n(t.fields);return t}var Gm=`••••••••`;function Km(e){return e===`••••••••`||e===`__redacted__`}function qm(e,t,n){let r=new Set(n),i={};for(let[t,n]of Object.entries(e)){if(!r.has(t)){i[t]=n;continue}n==null||n===``||Km(n)||(i[t]=n)}return i}function Jm(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e)){if(!n.has(t)){r[t]=i;continue}r[t]=i!=null&&i!==``?Gm:``}return r}function Ym(e){return{...e}}var Xm=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function Zm(e){return Xm.some(t=>e.includes(t))}function Qm(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function $m(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&Qm(e[n])!==Qm(t[n]))}function eh(e,t,n,r){if(r===void 0)return $m(e,t,n);let i=new Set(n),a=qm(e,t,n);return r.filter(n=>i.has(n)?n in a:Qm(e[n])!==Qm(t[n]))}function th(e,t,n){let r=qm(e,t,n);return n.filter(e=>!(e in r))}function nh(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:nh(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:nh(e.fields,t)}))}:e)}function rh(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:nh(e.fields,n)}))}}function ih(e){let t=e.trim();return t.length===0?J.t(`common.copy`):J.t(`helpers.notificationTargets.copyOf`,{name:t})}function ah(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,placeholder:e.placeholder??J.t(`helpers.notificationTargets.keepSecret`)}:e.type===`group`?{...e,fields:ah(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:ah(e.fields,t)}))}:e)}function oh(e,t,n){let r=new Set(n.filter(e=>{let n=t[e];return n!=null&&n!==``}));return r.size===0?e:{...e,sections:e.sections.map(e=>({...e,fields:ah(e.fields,r)}))}}var sh=`target`,ch=`kind`,lh=[sh,ch];function uh({refusal:e,edited:t,reenter:n}){let{t:r}=Y(),a=n.length>0?`Re-type: ${n.join(`, `)}.`:null;return e===null?t.length===0||a===null?null:d(`p`,{className:`text-[11px] text-warning`,"data-testid":`target-secret-reenter`,children:r(`system.targetSecretNotice.changed`,{fields:t.join(`, `),toType:a})}):i(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-secret-refusal`,role:`alert`,children:[d(`p`,{className:`font-semibold`,children:r(`system.targetSecretNotice.theHubNeedsTheSecret`,`The hub needs the secret again — nothing was saved.`)}),d(`p`,{className:`mt-1`,children:e}),a===null?null:d(`p`,{className:`mt-1 font-medium`,children:a})]})}e();var dh=[`notificationOutput`,`listTargets`],fh=[`notificationOutput`,`listTargetKinds`],ph=[`userManagement`,`listUsers`],mh=`ownerUserId`;function hh(e){let t=e.config[mh];return typeof t==`string`&&t.length>0?t:null}function gh(e){return[{key:`name`,header:J.t(`system.notificationTargets.target`,`Target`),render:t=>{let n=e.kindByKey.get(t.kind);return i(`span`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:n?.label??t.kind,children:d(_h,{kind:n,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),d(af,{name:t.name,enabled:t.enabled,...n===void 0?{}:{onOpen:()=>e.onOpen(t,n)}})]})}},{key:`kind`,header:J.t(`system.notificationTargets.kind`,`Kind`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByKey.get(t.kind)?.label??t.kind})},{key:`owner`,header:J.t(`system.notificationTargets.owner`,`Owner`),nowrap:!0,render:t=>{let n=hh(t);return n===null?d(G,{variant:`default`,children:J.t(`common.systemWord`)}):d(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:J.t(`system.notificationTargets.on`,`On`),align:`center`,nowrap:!0,render:t=>d(ef,{children:d(xt,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":J.t(`system.notificationTargets.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let n=e.kindByKey.get(t.kind);return i(ef,{className:`flex items-center justify-end gap-1`,children:[d(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>e.onTest(t),title:J.t(`system.notificationTargets.test`,`Test`),children:d(Ke,{className:`h-3.5 w-3.5`})}),d(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>n&&e.onDuplicate(t,n),title:J.t(`system.notificationTargets.duplicate`,`Duplicate`),children:d(_,{className:`h-3.5 w-3.5`})}),d(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:J.t(`common.delete`,`Delete`),children:d(p,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function _h({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?d(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):d(`span`,{className:n,children:e?.icon??`🔔`})}function vh({createRequested:e=!1,onCreateConsumed:o,headerOwnsCreate:s=!1}={}){let{t:c}=Y(),f=D(),{state:p,openEdit:m,close:h}=wt({editKey:`target`}),[g,_]=kt(ch),[y,b]=r({mode:`closed`}),[x,S]=r(null),C=l(null),T=a({queryKey:dh,queryFn:()=>f.trpcClient.notificationOutput.listTargets.query({})}),E=a({queryKey:fh,queryFn:async()=>(await f.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),O=n(()=>E.data??[],[E.data]),k=n(()=>{let e=new Map;for(let t of O)e.set(t.kind,t);return e},[O]),A=a({queryKey:ph,queryFn:()=>f.trpcClient.userManagement.listUsers.query()}),j=n(()=>{let e=new Map;for(let t of A.data??[])e.set(t.id,t.username);return e},[A.data]),M=u({mutationFn:e=>f.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:e.target.addonId,targetId:e.target.id,enabled:e.enabled}),onSuccess:()=>void T.refetch()}),N=u({mutationFn:e=>f.trpcClient.notificationOutput.deleteTarget.mutate({addonId:e.addonId,targetId:e.id}),onSuccess:()=>void T.refetch()}),P=x?k.get(x.kind):void 0,F=()=>{p.mode===`edit`&&(C.current=p.id),b({mode:`closed`}),h(),_(null)},I=()=>{C.current=`new`,b({mode:`pick-kind`}),m(`new`),_(null)};t(()=>{e&&(I(),o?.())},[e]);let ee=e=>{C.current=`new:${e.kind}`,b({mode:`form`,kind:e,target:null,cloneFrom:null}),m(`new`),_(e.kind)},te=(e,t)=>{C.current=e.id,b({mode:`form`,kind:t,target:e,cloneFrom:null}),m(e.id),_(null)};return t(()=>{if(y.mode!==`closed`)return;if(p.mode!==`edit`){p.mode===`closed`&&(C.current=null);return}let e=p.id;if(C.current===e)return;if(e===`new`){if(g===null||g.length===0){C.current=`new`,b({mode:`pick-kind`});return}let e=k.get(g);if(e===void 0)return;C.current=`new:${g}`,b({mode:`form`,kind:e,target:null,cloneFrom:null});return}let t=T.data?.find(t=>t.id===e);if(t===void 0)return;let n=k.get(t.kind);n!==void 0&&(C.current=e,b({mode:`form`,kind:n,target:t,cloneFrom:null}))},[y.mode,p,g,T.data,k]),i(ti,{embedded:!0,icon:v,title:c(`system.notificationTargets.notificationTargets`,`Notification Targets`),subtitle:c(`system.notificationTargets.deliverNotificationsToNtfyPushover`,`Deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more. Each target's kind declares its capabilities; the test panel shows exactly what a message degrades to.`),children:[s?null:d(`div`,{className:`mb-3 flex justify-end`,children:i(q,{size:`sm`,type:`button`,onClick:I,children:[d(w,{className:`h-3.5 w-3.5`}),c(`system.notificationTargets.addTarget`,`Add target`)]})}),T.isLoading&&d(tf,{}),T.isError&&!T.isLoading&&d(K,{title:c(`system.notificationTargets.failedToLoadTargets`,`Failed to load targets`),message:T.error instanceof Error?T.error.message:c(`system.notificationTargets.unknownError`,`Unknown error`),onRetry:()=>void T.refetch()}),!T.isLoading&&!T.isError&&(T.data??[]).length===0&&d(nf,{children:c(`system.notificationTargets.noNotificationTargetsYetClick`,`No notification targets yet. Click "Add target" to configure one.`)}),(T.data??[]).length>0&&d(rf,{columns:gh({kindByKey:k,userNameById:j,onToggle:(e,t)=>M.mutate({target:e,enabled:t}),onTest:S,onOpen:te,onDuplicate:(e,t)=>{C.current=`new:${t.kind}`,b({mode:`form`,kind:t,target:null,cloneFrom:e}),m(`new`),_(t.kind)},onDelete:e=>N.mutate(e)}),rows:T.data??[],rowKey:e=>e.id,minWidthPx:720,onRowClick:e=>{let t=k.get(e.kind);t!==void 0&&te(e,t)}}),y.mode===`pick-kind`&&d(yh,{kinds:O,onCancel:F,onPick:ee}),y.mode===`form`&&d(bh,{kind:y.kind,target:y.target,cloneFrom:y.cloneFrom,users:A.data??[],onCancel:F,onSaved:()=>{F(),T.refetch()}},y.target?.id??(y.cloneFrom===null?`new:${y.kind.kind}`:`dup:${y.cloneFrom.id}`)),x&&P&&d(Bm,{target:x,kind:P,open:!0,onClose:()=>S(null)})]})}function yh({kinds:e,onPick:t,onCancel:r}){let{t:a}=Y(),o=n(()=>Hm(e),[e]);return d(_t,{open:!0,onClose:r,title:a(`system.notificationTargets.chooseANotificationKind`,`Choose a notification kind`),width:`lg`,children:i(`div`,{className:`space-y-4`,children:[o.length===0&&d(`p`,{className:`text-xs text-foreground-subtle`,children:a(`system.notificationTargets.noNotificationProvidersAreInstalled`,`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`)}),o.map(e=>i(`div`,{children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),d(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(n=>i(`button`,{type:`button`,onClick:()=>t(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[d(_h,{kind:n,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),d(`span`,{className:`font-medium text-foreground`,children:n.label})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})})}function bh({kind:e,target:a,cloneFrom:s,users:c,onSaved:l,onCancel:f}){let{t:p}=Y(),m=D(),h=n(()=>Um(e.configSchema),[e.configSchema]),g=a??s,_=a?.id??s?.id,[y,b]=r(()=>s===null?a?.name??e.label:ih(s.name)),[x,S]=r(()=>g?.config??{}),[C,w]=r(()=>g?Jm(g.config,h):{}),[T,O]=r(_===void 0),[k,A]=r(null),[j,M]=r(null),[N,P]=r(g?hh(g)??``:``);t(()=>{if(_===void 0)return;let t=!1;return m.trpcClient.notificationOutput.getTarget.query({addonId:e.addonId,targetId:_}).then(e=>{if(t)return;let n=Ym(e.config);S(n),w(n),P(hh(e)??``),O(!0)}).catch(e=>{t||(A(e instanceof Error?e.message:`Failed to load target secrets`),O(!0))}),()=>{t=!0}},[_,e.addonId,m.trpcClient]);let F=()=>qm(C,x,h),[I,ee]=r(null),te=e.kind===`whatsapp`,L=u({mutationFn:()=>m.trpcClient.notificationOutput.probeTargetConfig.mutate({addonId:e.addonId,kind:e.kind,config:F(),..._===void 0?{}:{targetId:_}}),onSuccess:e=>ee(e),onError:e=>{ee(null),A(e instanceof Error?e.message:`Connection test failed`)}}),ne=u({mutationFn:()=>{let{[mh]:t,...n}=qm(C,x,h),r=N===``?n:{...n,[mh]:N},i={id:a?.id??`${e.kind}-${Date.now()}`,name:y,kind:e.kind,addonId:e.addonId,enabled:a?.enabled??!0,config:r};return m.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:i,...s===null?{}:{cloneSecretsFrom:s.id}})},onSuccess:l,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;Zm(t)?M(t):A(t)}}),R=n(()=>Wm(e.configSchema),[e.configSchema]),re=n(()=>_===void 0?[]:eh(C,x,h,e.destinationKeys),[_,C,x,h,e.destinationKeys]),ie=n(()=>_!==void 0&&(j!==null||re.length>0)?th(C,x,h):[],[_,j,re,C,x,h]),z=n(()=>oh(rh(e.configSchema,ie),x,h),[e.configSchema,ie,x,h]),ae=e=>R.get(e)??e;return d(_t,{open:!0,onClose:f,title:a?`Edit ${a.name}`:s?`Duplicate ${s.name}`:`Add ${e.label} target`,icon:v,width:`lg`,testId:`target-form-dialog`,beforeBody:i(o,{children:[k!=null&&k!==``&&d(`div`,{className:`mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-form-error`,children:k}),i(`div`,{className:`mb-3 flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(_h,{kind:e,imgClassName:`h-5 w-5 object-contain shrink-0`,fallbackClassName:`text-lg leading-5`}),d(`span`,{children:e.label})]})]}),footer:i(q,{size:`sm`,type:`button`,disabled:ne.isPending||!T||y.trim().length===0,onClick:()=>{A(null),M(null),ne.mutate()},children:[ne.isPending||!T?d(E,{className:`h-3.5 w-3.5 animate-spin`}):null,a?p(`system.notificationTargets.saveChanges`,`Save changes`):p(`system.notificationTargets.createTarget`,`Create target`)]}),children:i(`div`,{className:`space-y-4`,children:[i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:p(`system.notificationTargets.name`,`Name`)}),d(`input`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,value:y,onChange:e=>b(e.target.value)})]}),i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:p(`system.notificationTargets.owner`,`Owner`)}),d(H,{value:N,options:[{value:``,label:p(`system.notificationTargets.systemSharedAdminManaged`,`System (shared, admin-managed)`)},...c.map(e=>({value:e.id,label:e.username}))],onChange:e=>P(e.target.value)}),d(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:p(`system.notificationTargets.aUserOwnedTargetBelongs`,`A user-owned target belongs to that user: it shows in their viewer and their own rules may deliver to it. System targets stay admin-managed.`)})]}),h.length>0&&_!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:p(`system.notificationTargets.storedSecretsLoadIntoThe`,`Stored secrets load into the masked fields (eye to reveal). Clear a field to leave the stored value unchanged on save; type a new value to replace it.`)}),d(uh,{refusal:j,edited:re.map(ae),reenter:ie.map(ae)}),d(Et,{schema:z,values:C,onChange:w}),te&&i(`div`,{className:`space-y-2`,children:[i(q,{size:`sm`,variant:`outline`,type:`button`,disabled:L.isPending,onClick:()=>{A(null),ee(null),L.mutate()},children:[L.isPending?d(E,{className:`h-3.5 w-3.5 animate-spin`}):d(Ke,{className:`h-3.5 w-3.5`}),p(`system.notificationTargets.testConnection`,`Test connection`)]}),I!==null&&i(`p`,{className:I.ok?`text-[11px] text-success`:`text-[11px] text-danger`,"data-testid":`target-probe-result`,children:[I.ok?p(`system.notificationTargets.connected`,`Connected — {{value1}}`,{value1:I.stateInstance??`authorized`}):I.error??p(`system.notificationTargets.connectionFailed`,`Connection failed`),I.resolvedUrl.length>0?` · ${I.resolvedUrl}`:``]})]})]})})}e();var xh=`notificationTexts`,Sh=`Every sentence the Notification Center can print — and your wording for it.`;function Ch({entry:e,value:t,busy:n,onChange:r,onReset:a}){let{t:o}=Y(),s=Vl(e),c=e.override!==null;return i(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${e.key}`,"data-source":e.source,children:[i(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[d(`code`,{className:`text-xs font-medium`,children:e.key}),c?d(G,{variant:`info`,children:o(`common.customised`)}):null,e.source===`fallback`?d(G,{variant:`warning`,children:o(`system.notificationTexts.englishFallback`,`English fallback`)}):null]}),i(`div`,{className:`flex items-start gap-2`,children:[d(`div`,{className:`flex-1`,children:d(xo,{label:``,value:t,onChange:r,vars:Bl(e),disabled:n,testId:`text-input-${e.key}`})}),d(q,{variant:`ghost`,size:`sm`,disabled:n||!c&&t===e.shipped,onClick:a,title:o(`system.notificationTexts.resetToTheShippedWording`,`Reset to the shipped wording`),"data-testid":`text-reset-${e.key}`,children:d(A,{className:`h-3.5 w-3.5`})})]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:[d(`span`,{className:`font-medium`,children:o(`system.notificationTexts.shipped`,`Shipped:`)}),` `,d(`span`,{className:`font-mono`,children:e.shipped})]}),s===null?null:d(`p`,{className:`text-xs text-warning`,children:s})]})}function wh(){let{t:e}=Y(),t=D(),o=s(),[c,l]=r(null),[f,p]=r(``),[m,h]=r(new Map),[g,_]=r(!1),v=a({queryKey:[xh,c??`hub`],queryFn:async()=>{let e=Fl(await t.trpcClient.addons.custom.mutate({addonId:$,action:El,input:c===null?{}:{language:c}}));return _(e===null),e}}),y=()=>{h(new Map),o.invalidateQueries({queryKey:[xh]})},b=u({mutationFn:e=>t.trpcClient.addons.custom.mutate({addonId:$,action:Dl,input:{language:e}}),onSuccess:y}),S=u({mutationFn:e=>t.trpcClient.addons.custom.mutate({addonId:$,action:Ol,input:e}),onSuccess:y}),C=v.data??null,w=n(()=>C===null?[]:zl(C.entries,f),[C,f]);if(v.isLoading)return d(ti,{embedded:!0,icon:Ue,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:Sh,children:d(E,{className:`h-5 w-5 animate-spin`})});if(v.isError||C===null)return d(ti,{embedded:!0,icon:Ue,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:Sh,children:d(K,{title:e(`system.notificationTexts.theNotificationTextCatalogIs`,`The notification text catalog is not available on this hub`),message:g?e(`system.notificationTexts.theHubAnsweredSomethingThis`,`The hub answered something this admin build does not understand. Update both and reload.`):e(`system.notificationTexts.thisHubHasNotBeen`,`This hub has not been updated to serve the notification text catalog yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime: notifications keep using the shipped wording.`)})});let T=C.language,O=b.isPending||S.isPending,k=Ll(C.entries,m),A=Rl(C.entries,m),j=C.entries.filter(e=>e.override!==null).length,M=C.languages.map(e=>({value:e,label:kl[e]})),N=(e,t)=>h(n=>new Map(n).set(e,t)),P=e=>N(e.key,e.shipped);return d(ti,{embedded:!0,icon:Ue,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:Sh,children:i(`div`,{className:`flex flex-col gap-4`,children:[b.isError?d(K,{title:e(`system.notificationTexts.couldNotChangeTheLanguage`,`Could not change the language`),message:String(b.error)}):null,S.isError?d(K,{title:e(`system.notificationTexts.couldNotSave`,`Could not save`),message:String(S.error)}):null,i(Ot,{className:`p-4`,children:[i(`div`,{className:`flex flex-wrap items-end gap-6`,children:[i(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:e(`system.notificationTexts.hubLanguage`,`Hub language`)}),d(`div`,{className:`w-44`,children:d(H,{value:C.activeLanguage,disabled:O,options:M,onChange:e=>{let t=e.target.value;Al(t)&&b.mutate(t)},"data-testid":`texts-hub-language`})}),d(`p`,{className:`text-xs text-foreground-subtle`,children:e(`system.notificationTexts.everyNotificationIsWrittenIn`,`Every notification is written in this language.`)})]}),i(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:e(`system.notificationTexts.editing`,`Editing`)}),d(`div`,{className:`w-44`,children:d(H,{value:T,disabled:O,options:M,onChange:e=>{let t=e.target.value;Al(t)&&(h(new Map),l(t))},"data-testid":`texts-editing-language`})}),d(`p`,{className:`text-xs text-foreground-subtle`,children:T===C.activeLanguage?e(`system.notificationTexts.ofTextsCustomised`,`{{overriddenCount}} of {{length}} texts customised.`,{overriddenCount:j,length:C.entries.length}):e(`system.notificationTexts.thisHubDoesNotSpeak`,`This hub does not speak this language — these words are not in use yet.`)})]})]}),d(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:e(`system.notificationTexts.aRuleThatWritesIts`,`A rule that writes its own title or body still overrides everything here — this page is the wording used when a rule does not.`)})]}),i(`div`,{className:`flex flex-wrap items-center gap-3`,children:[i(`div`,{className:`relative min-w-[12rem] flex-1`,children:[d(x,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),d(W,{value:f,placeholder:e(`system.notificationTexts.searchAKeyOrA`,`Search a key or a sentence…`),onChange:e=>p(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),i(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[w.length,` of `,C.entries.length]}),i(q,{className:`ml-auto`,disabled:O||A===0,onClick:()=>S.mutate({language:T,overrides:k}),"data-testid":`texts-save`,children:[O?d(E,{className:`h-3.5 w-3.5 animate-spin`}):null,A===0?e(`common.save`,`Save`):e(`system.notificationTexts.save`,`Save {{pending}}`,{pending:A})]})]}),d(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?d(`p`,{className:`text-sm text-foreground-subtle`,children:e(`system.notificationTexts.noTextMatchesThatSearch`,`No text matches that search.`)}):w.map(e=>d(Ch,{entry:e,value:Il(e,m),busy:O,onChange:t=>N(e.key,t),onReset:()=>P(e)},e.key))})]})})}e();var Th=`simulate`,Eh=`rules`,Dh=new Set([`targets`,Eh,`sequences`]);function Oh(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function kh(e,t,n){if(e===`mixed`)return;if(e===`all`)return i(q,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:t,children:[d(w,{className:`h-3.5 w-3.5`}),J.t(`systemPage.notifications.newRule`,`New rule`)]});if(yf(e)){let t=xf(e),r=Oh(e);return r===null?void 0:i(q,{size:`sm`,type:`button`,onClick:()=>n(r),"data-testid":e===`summaries`?`summary-new`:e===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[d(w,{className:`h-3.5 w-3.5`}),t.newLabel]})}let r=sr.find(t=>t.key===e);if(!(r===void 0||!r.creatable))return i(q,{size:`sm`,type:`button`,onClick:()=>n(e),"data-testid":`rules-new-${e}`,children:[d(w,{className:`h-3.5 w-3.5`}),r.newRuleLabel]})}function Ah(){let{t:e}=Y(),[n,a]=Qr(),[o,s]=r(!1),[c,l]=r(null);t(()=>{let e=n.get(`tab`);if(e===null||!yf(e))return;let t=new URLSearchParams(n);t.set(`tab`,Eh),t.set(`section`,e),a(t,{replace:!0})},[n,a]);let u=n.get(`tab`)??`targets`,[f]=kt(`section`),p=bf(f)??`all`,m=e=>{Qp(Xp(e));let t=new URLSearchParams(n);t.set(`tab`,Th),a(t,{replace:!0})},h=e=>{a(Ha(n,e.id),{replace:!0})},g=Xr(`/system/notifications`,{t:e,isAdmin:!0})??{icon:v,title:e(`system.notifications`,`Notifications`)},_=()=>s(!1),y=(()=>{if(u===`targets`)return i(q,{size:`sm`,type:`button`,"data-testid":`notifications-add-target`,onClick:()=>s(!0),children:[d(w,{className:`h-3.5 w-3.5`}),e(`systemPage.notifications.addTarget`,`Add target`)]});if(u===`sequences`)return i(q,{size:`sm`,type:`button`,"data-testid":`notifications-add-sequence`,onClick:()=>s(!0),children:[d(w,{className:`h-3.5 w-3.5`}),e(`systemPage.notifications.newSequence`,`New sequence`)]});if(u===Eh)return kh(p,()=>s(!0),e=>l(e))})();return t(()=>{Dh.has(u)||(s(!1),l(null))},[u]),d($r,{icon:g.icon,title:g.title,defaultSection:`targets`,sectionsLabel:`${g.title} sections`,actions:y,sections:[{id:`targets`,label:e(`systemPage.notifications.targets`,`Targets`),content:d(vh,{headerOwnsCreate:!0,createRequested:u===`targets`&&o,onCreateConsumed:_}),ownedParams:lh},{id:Eh,label:e(`systemPage.notifications.rules`,`Rules`),content:d(fp,{onSimulateRule:m,onOpenHistory:h,headerOwnsCreate:!0,createRequested:u===Eh&&o,onCreateConsumed:_,createTypeRequested:u===Eh?c:null,onCreateTypeConsumed:()=>l(null)}),ownedParams:[`section`,`rule`,`editTab`]},{id:`sequences`,label:e(`systemPage.notifications.sequences`,`Sequences`),content:d(Op,{headerOwnsCreate:!0,createRequested:u===`sequences`&&o,onCreateConsumed:_}),ownedParams:xp},{id:Th,label:e(`systemPage.notifications.simulate`,`Simulate`),content:d(Sm,{})},{id:Ia,label:e(`systemPage.notifications.history`,`History`),content:d($a,{}),ownedParams:Ra},{id:`alarm`,label:e(`systemPage.notifications.alarm`,`Alarm`),content:d(Fa,{})},{id:`texts`,label:e(`systemPage.notifications.texts`,`Texts`),content:d(wh,{})},{id:`settings`,label:e(`systemPage.notifications.settings`,`Settings`),content:d(jp,{})}]})}export{Ah as NotificationsPage,Ah as default};
|