@camstack/addon-admin-ui 1.2.632 → 1.2.634

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.
Files changed (141) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/assets/{Addons-BT7bHTan.js → Addons-Cng9jF6c.js} +3 -3
  3. package/dist/assets/{AdminPage-DukjVgyy.js → AdminPage-CPPoleZA.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-BJPMt494.js → AdminSectionedPage-C_DLslGH.js} +1 -1
  5. package/dist/assets/{AiProfiles-BEzTAEwr.js → AiProfiles-B6Xt0CM1.js} +2 -2
  6. package/dist/assets/{Authentication-A0rZl8n_.js → Authentication-CkLg9Az9.js} +1 -1
  7. package/dist/assets/Build-DMEXJqf9.js +39 -0
  8. package/dist/assets/{Calendars-Cp3QTvHZ.js → Calendars-BHc1dbvk.js} +1 -1
  9. package/dist/assets/{CameraGrids-F-c0rQnS.js → CameraGrids-CIJubNTN.js} +1 -1
  10. package/dist/assets/{Cluster-BPubGaV-.js → Cluster-CSTB-np5.js} +1 -1
  11. package/dist/assets/CompositionBlockEditor-B4WN_aXq.js +2 -0
  12. package/dist/assets/{CompositionEditorPage-CtND1Icl.js → CompositionEditorPage-jP0e8vX8.js} +1 -1
  13. package/dist/assets/{Data-CcpoZfHM.js → Data-DJFzG2dC.js} +2 -2
  14. package/dist/assets/DeviceDetail-3P3i5bd9.js +2 -0
  15. package/dist/assets/{Devices-Dg1sA-xP.js → Devices-Ddhmovvw.js} +1 -1
  16. package/dist/assets/{EmbedPlayerPage-BenDk7Gh.js → EmbedPlayerPage-B9wkgcPc.js} +1 -1
  17. package/dist/assets/{History-aloN-aqn.js → History-Cv6TryZt.js} +1 -1
  18. package/dist/assets/{Identity-B_yFjW2V.js → Identity-Dmwp8J7o.js} +1 -1
  19. package/dist/assets/{InstanceSwitchCell-BboEA1K9.js → InstanceSwitchCell-xSu6VGOy.js} +1 -1
  20. package/dist/assets/{InstancesTable-DXUpAcJZ.js → InstancesTable-dSeWjA48.js} +1 -1
  21. package/dist/assets/IntegrationDetail-oEpvT757.js +1 -0
  22. package/dist/assets/{IntegrationHub-B5bQNj_0.js → IntegrationHub-CIVmSeKd.js} +1 -1
  23. package/dist/assets/{Integrations-vpeNxy4B.js → Integrations-C5BzsIy2.js} +2 -2
  24. package/dist/assets/{Integrations-DVHLLuX5.js → Integrations-zlHqQ0X9.js} +1 -1
  25. package/dist/assets/{Library-CrnrNYJv.js → Library-COZVDG1J.js} +1 -1
  26. package/dist/assets/{Locations-OJ7ibNjp.js → Locations-CpG6tIMC.js} +1 -1
  27. package/dist/assets/{Logs-BxPxV1qL.js → Logs-_Lymv-hK.js} +1 -1
  28. package/dist/assets/{MaskShapeCanvas-f8Ot4FwU.js → MaskShapeCanvas-Dkn9mTx5.js} +1 -1
  29. package/dist/assets/{MotionZonesSettings-CNCPmAdx.js → MotionZonesSettings-DbJd1q0y.js} +1 -1
  30. package/dist/assets/{MyAccess-BFE8d6ZR.js → MyAccess-3IH5sTuq.js} +1 -1
  31. package/dist/assets/{Network-Cg63gJCR.js → Network-DNJ2W_md.js} +1 -1
  32. package/dist/assets/{NodeAddonsSettingsPanel-CJ9Q5NFQ.js → NodeAddonsSettingsPanel-BleYmajR.js} +1 -1
  33. package/dist/assets/Notifications-C5S8_cBI.js +1 -0
  34. package/dist/assets/{Pipeline-gEdCbMYl.js → Pipeline-CBIucM6P.js} +1 -1
  35. package/dist/assets/{PrivacyMaskSettings-CJ1adeiq.js → PrivacyMaskSettings-B7mOaiDG.js} +1 -1
  36. package/dist/assets/{Recordings-BXEOwON0.js → Recordings-Dzfu0JHh.js} +1 -1
  37. package/dist/assets/{ScanSubnetEditor-GZYgp4WY.js → ScanSubnetEditor-g4rMYaaa.js} +1 -1
  38. package/dist/assets/{SceneMonitorEditor-CdOav4NE.js → SceneMonitorEditor-B99BtkWG.js} +1 -1
  39. package/dist/assets/{SessionsList-CM7QkwsQ.js → SessionsList-DB9t5c5h.js} +1 -1
  40. package/dist/assets/{Showroom-ChgpRtnE.js → Showroom-BlMJHK6P.js} +1 -1
  41. package/dist/assets/{StorageLocationsTable-Ch9fTls7.js → StorageLocationsTable-BCc20Y-P.js} +1 -1
  42. package/dist/assets/{System-BrbYsqjP.js → System-_om1Qy_Z.js} +1 -1
  43. package/dist/assets/{Templates-BPPPDyxv.js → Templates-ClUtf6zo.js} +1 -1
  44. package/dist/assets/{Terminal-D1wU2v2O.js → Terminal-CK-OPJi8.js} +1 -1
  45. package/dist/assets/{TrainingProviders-Dmz54UM4.js → TrainingProviders-CMfEG1p0.js} +1 -1
  46. package/dist/assets/{Viewer-C9Ny-xX5.js → Viewer-D8ErfEDa.js} +1 -1
  47. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BvfhnhUm.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-D5EjGbog.js} +1 -1
  48. package/dist/assets/{action-draft-Rt5OrTBb.js → action-draft-BF1Yv5wJ.js} +1 -1
  49. package/dist/assets/{ai-page.helpers-D9kjLVBH.js → ai-page.helpers-7-YKMWA7.js} +1 -1
  50. package/dist/assets/{archive-DQhBHdGb.js → archive-WByIhorf.js} +1 -1
  51. package/dist/assets/{assignment-candidates-D_WnsDC9.js → assignment-candidates-CerZJluZ.js} +1 -1
  52. package/dist/assets/{authed-media-Ctq5fLNa.js → authed-media-vTZUQ8BO.js} +1 -1
  53. package/dist/assets/{bell-off-CQw8KePi.js → bell-off-HUbueWAa.js} +1 -1
  54. package/dist/assets/{board-model-pkgjhYhn.js → board-model-BeY6U40R.js} +1 -1
  55. package/dist/assets/{boxes-DLyI_XjT.js → boxes-Sn1wqpgK.js} +1 -1
  56. package/dist/assets/{calendar-clock-D3y-UzBd.js → calendar-clock-TWIEL7Fd.js} +1 -1
  57. package/dist/assets/{circle-arrow-up-CrgC-GoF.js → circle-arrow-up-BZb1tft0.js} +1 -1
  58. package/dist/assets/circle-slash-Yb1HMMEU.js +1 -0
  59. package/dist/assets/client-BT1qTuWk.js +839 -0
  60. package/dist/assets/create-composition-BCz5rteK.js +2 -0
  61. package/dist/assets/crop-Rp-pMXj8.js +1 -0
  62. package/dist/assets/{database-zap-ebRczSES.js → database-zap-DDQJWo1I.js} +1 -1
  63. package/dist/assets/{device-integration-icon-D1SlG8pf.js → device-integration-icon-BEojiV6j.js} +1 -1
  64. package/dist/assets/device-picker-model-DxRFIJt2.js +1 -0
  65. package/dist/assets/{dist-1IPGakxD.js → dist-BAkSt7-o.js} +1 -1
  66. package/dist/assets/dist-MZVzWw2Y.js +839 -0
  67. package/dist/assets/{eraser-CrU_ylHX.js → eraser-BXfY9g0S.js} +1 -1
  68. package/dist/assets/{file-up-C83TYV5g.js → file-up-CGHZOKg0.js} +1 -1
  69. package/dist/assets/{format-DZv3Xcae.js → format-C6WZEo_1.js} +1 -1
  70. package/dist/assets/{hard-drive-download-DY8-G97Q.js → hard-drive-download-B12jnOmz.js} +1 -1
  71. package/dist/assets/{hostInit-CFIHZoF5.js → hostInit-DvgZnKz2.js} +1 -1
  72. package/dist/assets/i18n-DO003gOw.js +1 -0
  73. package/dist/assets/{icons-H9CAnhlN.js → icons-CSB91nWL.js} +1 -1
  74. package/dist/assets/index-BtIAcMod.js +4 -0
  75. package/dist/assets/index-W6guS92q.css +2 -0
  76. package/dist/assets/{key-Daxu-jCc.js → key-C7vcpiqV.js} +1 -1
  77. package/dist/assets/{key-square-Cf7qU2ZZ.js → key-square-wAKOa45w.js} +1 -1
  78. package/dist/assets/{languages-CLBA0iF5.js → languages-NIG6fIsC.js} +1 -1
  79. package/dist/assets/{layers-B40flYJz.js → layers-igKznkhu.js} +1 -1
  80. package/dist/assets/{link-2-off-BAaoRwqF.js → link-2-off-ViXG09ia.js} +1 -1
  81. package/dist/assets/{linked-devices-model-YbEDMapY.js → linked-devices-model-Coihabk7.js} +1 -1
  82. package/dist/assets/{memory-stick-DrFcuZNk.js → memory-stick-Cb3rfsma.js} +1 -1
  83. package/dist/assets/{message-square-plus-CRRBCpat.js → message-square-plus-MY_vmmYC.js} +1 -1
  84. package/dist/assets/{mf-entry-bootstrap-0-701864ce.js → mf-entry-bootstrap-0-bf765b1e.js} +2 -2
  85. package/dist/assets/{mic-off-DahXL35O.js → mic-off-DQbHj0Dp.js} +1 -1
  86. package/dist/assets/{monitor-off-BHpXVdMV.js → monitor-off-KvLmRgXm.js} +1 -1
  87. package/dist/assets/{monitor-smartphone-Cg7zkb3G.js → monitor-smartphone-wbkRUoUy.js} +1 -1
  88. package/dist/assets/mount-DxRFIJt2.js +1 -0
  89. package/dist/assets/{notification-rule-status-B2ehhYuJ.js → notification-rule-status-DSPA2LGi.js} +1 -1
  90. package/dist/assets/{player-overlays-C-LR1t7f.js → player-overlays-D2iM_dnq.js} +1 -1
  91. package/dist/assets/remoteEntry-CjzR4ng6.js +1 -0
  92. package/dist/assets/{ruler-BD7pcHku.js → ruler-Cnh0qH1K.js} +1 -1
  93. package/dist/assets/{scan-eye-Dml5chSK.js → scan-eye-B57MjUsN.js} +1 -1
  94. package/dist/assets/{scissors-DTLZipNa.js → scissors-jk6_pSRI.js} +1 -1
  95. package/dist/assets/{search-x-DwLc6xe6.js → search-x-KiZ1cgFX.js} +1 -1
  96. package/dist/assets/{send-5UFl-2T3.js → send-DAC8bZ9x.js} +1 -1
  97. package/dist/assets/{settings-2-BJUbGqt2.js → settings-2-B5Wblm0D.js} +1 -1
  98. package/dist/assets/{shapes-B-j95JHo.js → shapes-C877FMvu.js} +1 -1
  99. package/dist/assets/{sigma-5DS4fXRu.js → sigma-48mqbKtS.js} +1 -1
  100. package/dist/assets/src-Djs5D3BM.js +169 -0
  101. package/dist/assets/{sso-popup-BlGNnn2N.js → sso-popup-zJECU9yL.js} +1 -1
  102. package/dist/assets/{step-inspector-model-CqZ7Al9q.js → step-inspector-model-flcREGWU.js} +1 -1
  103. package/dist/assets/{table-2-CuiUfVZm.js → table-2-Dcc8x9NW.js} +1 -1
  104. package/dist/assets/{timer-reset-CVNI_AD_.js → timer-reset-DPB7Vi_P.js} +1 -1
  105. package/dist/assets/{ungroup-3yNBWxK2.js → ungroup-CaRYV5oo.js} +1 -1
  106. package/dist/assets/{unlink-B4jJ0_4g.js → unlink-B1jawH2n.js} +1 -1
  107. package/dist/assets/{usb-Bwbj9iy6.js → usb-B566yDR8.js} +1 -1
  108. package/dist/assets/{use-scenes-feed-B9WLQRks.js → use-scenes-feed-Cv3Lv9tp.js} +1 -1
  109. package/dist/assets/{use-stationary-objects-BGK7EW6B.js → use-stationary-objects-DPdFLI4G.js} +1 -1
  110. package/dist/assets/{useAdminDeviceRemoval-Be9ZUjP5.js → useAdminDeviceRemoval-CK79vXvY.js} +1 -1
  111. package/dist/assets/useEventInvalidation-DxRFIJt2.js +1 -0
  112. package/dist/assets/{useNodeUrlSelection-BtSZ8rlx.js → useNodeUrlSelection-B4V72DKj.js} +1 -1
  113. package/dist/assets/useTemplateSave-sDhvqUj4.js +1 -0
  114. package/dist/assets/user-round-gyXn4SEe.js +1 -0
  115. package/dist/assets/{user-x-DD7eWvk5.js → user-x-Dalx5dz-.js} +1 -1
  116. package/dist/assets/{variable-BsLCDfoM.js → variable-CxFXQLx9.js} +1 -1
  117. package/dist/assets/{video-BkZKS0Zo.js → video-DFWp1_fo.js} +1 -1
  118. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Byutlh7W.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Dbfg8wPM.js} +2 -2
  119. package/dist/index.html +10 -10
  120. package/dist/server/addon.js +188 -179
  121. package/package.json +2 -2
  122. package/dist/assets/Build-DbU7PhfN.js +0 -39
  123. package/dist/assets/CompositionBlockEditor-CZ4dd1Rg.js +0 -2
  124. package/dist/assets/DeviceDetail-DV6x3JB9.js +0 -2
  125. package/dist/assets/IntegrationDetail-Dt0JMO5X.js +0 -1
  126. package/dist/assets/Notifications-DVMvQvKq.js +0 -1
  127. package/dist/assets/circle-slash-DKDb5qiu.js +0 -1
  128. package/dist/assets/client-CTS6i8uH.js +0 -839
  129. package/dist/assets/create-composition-DqVl0ikx.js +0 -2
  130. package/dist/assets/crop-CPkFD20y.js +0 -1
  131. package/dist/assets/device-picker-model-nucY7hW2.js +0 -1
  132. package/dist/assets/dist-UoPJIOk2.js +0 -839
  133. package/dist/assets/i18n-DQKduBul.js +0 -1
  134. package/dist/assets/index-CYCJ_V8d.css +0 -2
  135. package/dist/assets/index-DWkBV3yo.js +0 -4
  136. package/dist/assets/mount-nucY7hW2.js +0 -1
  137. package/dist/assets/remoteEntry-Dap0eXDy.js +0 -1
  138. package/dist/assets/src-BjGJ_toP.js +0 -169
  139. package/dist/assets/useEventInvalidation-nucY7hW2.js +0 -1
  140. package/dist/assets/useTemplateSave-BfJqrrQS.js +0 -1
  141. package/dist/assets/user-round-rhUA6kJq.js +0 -1
@@ -1 +0,0 @@
1
- import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,o as l,p as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Bn as p,Cn as m,Fi as h,In as g,Jn as _,Kt as v,Nr as y,Oa as b,On as x,Pi as S,Q as C,Rr as w,Tr as T,Yt as E,_i as D,aa as O,ai as k,b as A,ct as ee,dt as j,ei as M,gt as N,ia as te,ut as P,v as ne,y as re,z as F,zn as ie}from"./player-overlays-C-LR1t7f.js";import{$ as I,A as ae,At as oe,Bt as L,Ct as se,D as ce,Ds as le,Dt as ue,E as de,Et as fe,Ft as pe,G as me,Gr as R,Ho as he,I as z,J as ge,K as _e,Ka as B,L as V,Ln as ve,M as ye,Mt as be,Ot as xe,P as Se,Rt as Ce,T as we,U as Te,Vt as Ee,W as De,X as Oe,Y as ke,Yr as Ae,_t as je,at as Me,bn as Ne,et as Pe,gt as Fe,k as Ie,kt as Le,mt as Re,nt as ze,q as Be,rt as Ve,tt as He,w as Ue,wt as We,xt as Ge,yt as Ke}from"./client-CTS6i8uH.js";import{D as qe,I as Je,N as Ye,O as Xe,j as Ze,v as Qe,y as $e}from"./__vite-browser-external-BCAtXlNQ.js";import{t as et}from"./bell-off-CQw8KePi.js";import{y as tt}from"./video-BkZKS0Zo.js";import{n as nt,t as rt}from"./send-5UFl-2T3.js";import{n as it,t as at}from"./languages-CLBA0iF5.js";import{$ as ot,$o as st,$r as ct,Ai as lt,Dt as ut,Fr as dt,Gr as ft,Ii as H,Jn as pt,Jr as mt,Kr as ht,Kt as gt,Lt as _t,Oi as U,Ot as vt,Q as yt,Ri as bt,Wr as xt,Xi as St,Xr as Ct,Yn as wt,Yr as Tt,_ as Et,_r as Dt,at as Ot,df as kt,dr as W,et as At,ff as jt,fr as Mt,gr as Nt,hf as Pt,hi as Ft,ii as G,it as It,ji as Lt,kt as Rt,mf as K,mr as q,no as zt,nt as Bt,ot as Vt,pf as Ht,pr as Ut,rt as Wt,si as Gt,st as Kt,tt as qt,ur as Jt,vr as Yt,yr as Xt,zr as Zt}from"./src-BjGJ_toP.js";import{t as J}from"./i18n-DQKduBul.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import"./mount-nucY7hW2.js";import{$n as Qt,$t,An as en,Ar as tn,At as nn,Bn as rn,Br as an,Bt as on,C as sn,Cn as cn,Cr as ln,Ct as un,Dn as dn,Dr as fn,Dt as pn,En as mn,Er as hn,Et as gn,Fn as _n,Fr as vn,Ft as yn,Gn as bn,Gt as xn,Hn as Sn,Ht as Cn,In as wn,It as Tn,Jn as En,Jt as Dn,Kn as On,Kt as kn,Ln as An,Lt as jn,Mn,Mt as Nn,Nn as Pn,Nt as Fn,On as In,Or as Ln,Ot as Rn,Pn as zn,Pr as Bn,Pt as Vn,Qn as Hn,Qt as Un,Rn as Wn,Rt as Gn,S as Kn,Sn as qn,Sr as Jn,St as Yn,Tn as Xn,Tr as Zn,Tt as Qn,Un as $n,Ut as er,Vn as tr,Vt as nr,Wn as rr,Wt as ir,Xn as ar,Xt as or,Yn as sr,Yt as cr,Zn as lr,Zt as ur,_n as dr,_r as fr,_t as pr,an as mr,ar as hr,bn as gr,br as _r,bt as X,cn as vr,cr as yr,dn as br,dr as xr,en as Sr,er as Cr,fn as wr,fr as Tr,gn as Er,gr as Dr,gt as Or,hn as kr,hr as Ar,ht as jr,in as Mr,ir as Nr,jn as Pr,jr as Fr,jt as Ir,kn as Lr,kr as Rr,kt as zr,ln as Br,lr as Vr,mn as Hr,mr as Ur,mt as Wr,nn as Gr,nr as Kr,on as qr,or as Jr,pn as Yr,pr as Xr,pt as Zr,qn as Qr,qt as $r,rn as ei,rr as ti,sn as ni,sr as ri,tn as ii,tr as ai,un as oi,ur as si,vn as ci,vr as li,vt as ui,wn as di,wr as fi,wt as pi,xn as mi,xr as hi,xt as gi,yn as _i,yr as vi,yt as yi,zn as bi,zt as xi}from"./index-DWkBV3yo.js";import{t as Si}from"./AdminSectionedPage-BJPMt494.js";import{n as Ci}from"./format-DZv3Xcae.js";import"./device-picker-model-nucY7hW2.js";import{t as wi}from"./action-draft-Rt5OrTBb.js";import{t as Ti}from"./AdminPage-DukjVgyy.js";import{c as Ei,i as Di,n as Oi,o as ki,r as Ai,s as ji,t as Mi}from"./notification-rule-status-B2ehhYuJ.js";import{t as Ni}from"./use-scenes-feed-B9WLQRks.js";import{t as Pi}from"./InstancesTable-DXUpAcJZ.js";import{l as Fi,s as Ii}from"./ai-page.helpers-D9kjLVBH.js";c();var Li=[`contact`,`cover`,`lock-control`,`switch`];function Ri(e){let t=new Set;for(let n of e?.openings??[]){for(let e of n.devices)t.add(e.deviceId);for(let e of n.unknown)t.add(e)}return t}function zi(e){let t=new Set(Ri(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 Bi(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function Vi(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=>Wt([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?J.t(`uiLibrary.devicePicker.deviceId`,{id:e}):qt(t,`device`,sn))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function Hi(e){let t=e.name.trim();return t===``?J.t(`uiLibrary.devicePicker.deviceId`,{id:e.deviceId}):t}function Ui(e){return e===0?J.t(`helpers.alarmNonblocking.refusedNoName`):J.t(`helpers.alarmNonblocking.refusedOpen`)}var Wi={home:`Home`,away:`Away`,night:`Night`};function Gi(e){return Wi[e]??e}function Ki(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 qi(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 Ji(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${Yi[e.reason]})`);return J.t(`helpers.notificationAlarm.skipped`,{count:e.length,parts:n.join(`, `)})}var Yi={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function Xi(e){return e.ruleCount===0}function Zi(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 Qi=2e3,$i=15e3,ea=new Set([`arming`,`pending`,`triggered`]);function ta(e){return e!==void 0&&ea.has(e)?Qi:$i}var na={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 ra(e){let t=na[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${Gi(e.targetMode)}`}function ia(e){return e!==`disarmed`}function aa(e){return e===`open`?J.t(`helpers.notificationAlarm.phaseOpen`):J.t(`helpers.notificationAlarm.phaseClosed`)}function oa(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function sa(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function ca(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function la(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 ua(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 da(e,t,n,r){let i=la(e,t,n);return r==="default"?i===void 0?null:ua(t,n,null):i===r?null:ua(t,n,r)}function fa(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=Pe(e,t),a=r!==n,o=n!==`doNothing`&&i.triggeredDurationSec===0;return!a&&!o?null:{mode:t,...a?{postTriggeredAction:n}:{},...o?{triggeredDurationSec:30}:{}}}function pa(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 ma=[`unknown-refusal`,`stale`,`expired`,`used`];function ha(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ga(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!ha(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 _a(e){if(!ha(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=ga(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=ga(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=ma.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var va={"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 ya(e){return va[e]}function ba(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 xa=`pipeline-analytics`,Sa=`The hub answered something this build cannot read — refresh after updating.`;function Ca(e){return e instanceof Error?e.message:String(e)}function wa(e){return e.map(e=>`${Hi(e)} (${e.state})`).join(`, `)}function Ta({live:t,onChanged:n}){let{t:r}=Y(),a=N(),[s,c]=o(null),[l,u]=o(null),[f,p]=o(null),m=(e,t)=>a.trpcClient.addons.custom.mutate({addonId:xa,action:e,input:t}),h=e=>{if(e===null){u(Sa);return}if(e.outcome===`refused`){c({refusalId:e.refusalId,blocking:e.blocking});return}if(c(null),e.outcome===`rejected`){u(`Arm anyway was not accepted: ${ya(e.reason)}.`);return}if(e.outcome===`outside-schedule`){u(`Outside this mode's activation schedule — arm during an allowed window.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;p(e.excluded.length===0?`${t}.`:`${t} — excluded: ${wa(e.excluded)}.`)},g=()=>{u(null),p(null)},_=d({mutationFn:async e=>_a(await m(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>u(Ca(e)),onSettled:n}),v=d({mutationFn:async e=>_a(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>u(Ca(e)),onSettled:n}),y=d({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{g(),c(null)},onSuccess:()=>p(`Disarmed.`),onError:e=>u(Ca(e)),onSettled:n});if(t===void 0)return e(ct,{className:`p-4`,children:[i(`h3`,{className:`text-sm font-semibold mb-1`,children:r(`system.alarmLiveCard.panel`,`Panel`)}),i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.alarmLiveCard.thisHubDoesNotReport`,`This hub does not report the panel's live state yet — update it to arm from here.`)})]});let b=_.isPending||v.isPending||y.isPending;return e(ct,{className:`p-4`,children:[e(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[e(`div`,{children:[i(`h3`,{className:`text-sm font-semibold`,children:r(`system.alarmLiveCard.panel`,`Panel`)}),i(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:ra(t)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?i(T,{className:`h-4 w-4 animate-spin`}):null,t.availableModes.map(e=>i(U,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:r(`system.alarmLiveCard.arm`,{mode:Gi(e)})},e)),i(U,{type:`button`,size:`md`,variant:ia(t.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:r(`system.alarmLiveCard.disarm`,`Disarm`)})]})]}),l===null?null:i(`div`,{className:`mt-3`,children:i(G,{title:r(`system.alarmLiveCard.thePanelDidNotDo`,`The panel did not do that`),message:l})}),f===null?null:i(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:f}),s===null?null:e(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[i(`p`,{className:`text-sm font-medium`,children:Ui(s.blocking.length)}),s.blocking.length>0?i(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:s.blocking.map(t=>e(`li`,{children:[Hi(t),` `,e(`span`,{className:`text-foreground-subtle`,children:[`(`,t.state,`)`]})]},t.deviceId))}):null,e(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[i(U,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(s.refusalId),children:r(`system.alarmLiveCard.armAnyway`,`Arm anyway`)}),i(`span`,{className:`text-xs text-foreground-subtle`,children:r(`system.alarmLiveCard.eachOpenDeviceIsIgnored`,`Each open device is ignored until it closes, then monitored again.`)})]})]}),e(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[i(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:r(`system.alarmLiveCard.excludedSensors`,`Excluded sensors`)}),t.exclusions.length===0?i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.alarmLiveCard.noSensorIsExcluded`,`No sensor is excluded.`)}):i(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:t.exclusions.map(t=>e(`li`,{children:[Hi(t),` —`,` `,i(`span`,{className:`text-foreground-subtle`,children:aa(t.phase)})]},t.deviceId))})]})]})}c();var Ea=[{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 Da(e){return J.t(`system.alarmDelay.rangeError`,{max:e})}function Oa(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${Da(t)}`}function ka({label:t,value:n,max:r,zeroMeans:a,disabled:s,testId:c,hint:l,adornment:u,onCommit:d}){let[f,p]=o(null),[m,h]=o(null),g=f??String(n),_=f!==null&&f.trim()!==``&&Zi(f,r)===null,v=Ki(n,a),y=()=>{let e=f===null?null:Zi(f,r);p(null),e===null?f!==null&&h(f):(h(null),d(e))};return e(_t,{label:t,...l===void 0?{}:{description:l},..._?{error:Da(r)}:m===null?{}:{error:Oa(m,r)},children:[e(`div`,{className:`flex items-center gap-2`,children:[i(K,{type:`number`,min:0,max:r,value:g,disabled:s,state:_||m!==null?`error`:`default`,"aria-label":t,onChange:e=>{h(null),p(e.target.value)},onBlur:y,className:`w-20`,"data-testid":c}),i(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),u]}),v===`${n} s`?null:i(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function Aa(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=Kt(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function ja(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 Ma(){return J.t(`system.alarmSensorTable.listedUncovered`)}function Na(e){return e.listedUncovered?{word:J.t(`system.alarmSensorTable.cellNo`),note:Ma()}:Pa(e.coverage)}function Pa(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 Fa(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 Ia(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 La({name:t,variant:n,words:r}){return e(`span`,{"data-testid":`alarm-cell-${t}`,className:`flex flex-col items-start gap-0.5`,children:[i(H,{variant:n,"data-testid":`alarm-cell-${t}-badge`,children:r.word}),r.note===null?null:i(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${t}-note`,children:r.note})]})}var Ra=`hidden sm:table-cell`;function za({id:e,stored:t}){return i(`span`,{className:`truncate text-xs font-medium text-foreground`,children:Ft(e,`compact`,t)})}function Ba(e){let t=Ft(e.deviceId,`compact`,e.storedName);return i(q,{checked:e.checked,onCheckedChange:e.onCheckedChange,disabled:e.disabled,"data-device-id":String(e.deviceId),"data-testid":e.testId,"aria-label":J.t(e.phraseKey,e.phraseFallback,{name:t}),"aria-busy":e.busy?!0:void 0,"aria-disabled":e.waiting?!0:void 0,className:e.waiting?`opacity-50`:void 0,...e.title===void 0?{}:{title:e.title}})}function Va(t){let{mode:n,inFlight:r,onSwitch:a,zones:o,disabled:s}=t;return[{key:`name`,header:J.t(`system.alarmSensorTable.name`,`Name`),cell:t=>{let n=Aa(t.device.location,o);return e(`span`,{className:`flex min-w-0 flex-col`,"data-testid":`alarm-cell-name`,"data-muted":t.listedUncovered?`true`:void 0,children:[i(za,{id:t.device.id,stored:t.device.name}),n===``?null:i(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:n})]})}},{key:`type`,header:J.t(`system.alarmSensorTable.type`,`Type`),headerClassName:Ra,cellClassName:`${Ra} text-[11px] text-foreground-subtle`,cell:e=>Vt(e.device.type??null,sn)},{key:`state`,header:J.t(`system.alarmSensorTable.state`,`State`),cell:e=>i(La,{name:`state`,variant:Fa(e.cell),words:ja(e.cell)})},{key:`coverage`,header:J.t(`system.alarmSensorTable.checkedWhenArming`,`Checked when arming`),headerClassName:Ra,cellClassName:Ra,cell:e=>i(La,{name:`coverage`,variant:Ia(e),words:Na(e)})},{key:`blocks`,header:J.t(`system.alarmSensorTable.blocksArming`,`Blocks arming`),headerClassName:`text-right`,cellClassName:`text-right`,cell:t=>{let o=r!==null&&r.mode===n&&r.deviceId===t.device.id&&r.kind===`blocks`,c=r!==null&&!o;return e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[o?i(T,{className:`h-3 w-3 animate-spin`}):null,i(Ba,{deviceId:t.device.id,storedName:t.device.name,phraseKey:`system.alarmSensorTable.blocksArming2`,phraseFallback:`Blocks arming: {{name}}`,checked:t.blocks,onCheckedChange:e=>a(t,`blocks`,e),disabled:s,testId:`alarm-switch-blocks`,busy:o,waiting:c})]})}},{key:`secure`,header:i(`span`,{title:J.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),children:J.t(`system.alarmSensorTable.secureOnArm`,`Secure on arm`)}),headerClassName:`text-right`,cellClassName:`text-right`,cell:t=>{if(!t.controllable)return i(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let o=r!==null&&r.mode===n&&r.deviceId===t.device.id&&r.kind===`secureOnArm`,c=r!==null&&!o;return e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[o?i(T,{className:`h-3 w-3 animate-spin`}):null,i(Ba,{deviceId:t.device.id,storedName:t.device.name,phraseKey:`system.alarmSensorTable.secureOnArmCloseLock`,phraseFallback:`Secure on arm (close/lock/off): {{name}}`,checked:t.secureOnArm,onCheckedChange:e=>a(t,`secureOnArm`,e),disabled:s,testId:`alarm-switch-secure`,busy:o,waiting:c,title:J.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`)})]})}}]}function Ha(t){let{t:n}=Y(),r=b(),{mode:a,rows:o,sensorsRetry:s,zones:c}=t;return e(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${a}`,children:[s===null?null:e(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[i(`span`,{children:n(`system.alarmSensorTable.couldNotReadTheSensor`,`Could not read the sensor states.`)}),i(U,{type:`button`,size:`sm`,variant:`outline`,onClick:s,children:n(`common.retry`,`Retry`)})]}),i(gt,{mode:`generic`,items:o,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,Aa(e.device.location,c),Vt(e.device.type??null,r)].join(` `),getFilterType:e=>Vt(e.device.type??null,r),columns:Va(t),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:n(`system.alarmSensorTable.searchSensors`,`Search sensors`),emptyLabel:`No sensor matches.`})]})}var Ua=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function Wa(e){return Ua.some(t=>t.test(e))}function Ga(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return Wa(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 Ka(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 qa(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 Ja(e){return e.kind===`unscoped`||e.kind===`not-covered`}function Ya(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=qa(e.coverage,r.id),a=Ka(e.sensors,r.id,t,r.type),o=ze({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=Ve({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&&Ja(i)&&(!o||c)&&c;!t&&Ja(i)&&!c||n.push({device:r,removed:t,cell:Ga(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function Xa(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function Za(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 Qa(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 eo(e,t){return I($a(e),t)?{kind:`landed`}:{kind:`not-landed`}}var to=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function no({coverage:t,settings:n,disabled:r,onNotifyEdit:a}){let{t:o}=Y(),s=He(n,t.mode);return e(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${t.mode}`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:o(`notificationRules.alarmNotify.title`)}),to.map(({field:n,key:c})=>e(`div`,{className:`flex items-start justify-between gap-3`,children:[e(`div`,{className:`min-w-0`,children:[i(`p`,{className:`text-xs text-foreground`,children:o(`notificationRules.alarmNotify.${c}`)}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`notificationRules.alarmNotify.${c}Hint`)})]}),i(q,{checked:s[n],onCheckedChange:e=>a(n,e),disabled:r,"data-testid":`alarm-notify-${t.mode}-${n}`,"aria-label":o(`notificationRules.alarmNotify.${c}`)})]},n))]})}function ro({coverage:t,rows:n,names:r}){let{t:a}=Y(),o=n.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,s=qi(t,r.nameOf);return e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${t.mode}`,children:[Xi(t)?i(H,{variant:`warning`,title:s,"data-testid":`alarm-arms-nothing`,children:a(`system.alarmModeCard.armsNothingNoEnabledRule`,`Arms nothing — no enabled rule is gated on this mode`)}):i(H,{variant:`default`,title:s,"data-testid":`alarm-covers`,children:a(`system.alarmModeCard.checksSensors`,{count:o})}),t.skippedDevices.length>0?i(H,{variant:`warning`,title:Ji(t.skippedDevices,r.nameOf),"data-testid":`alarm-skipped`,children:a(`system.alarmModeCard.notNotified`,{count:t.skippedDevices.length})}):null]})}function io(e){return e.status===`answered`?e.openingIds:null}function ao({check:t,view:n}){let{t:r}=Y();return n.unresolved?t.status===`pending`?e(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[i(T,{className:`h-3 w-3 animate-spin`}),r(`system.alarmModeCard.checkingWhichDevicesAreOpenings`,`Checking which devices are openings…`)]}):t.status===`failed`?e(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[i(`span`,{children:r(`system.alarmModeCard.openingsCheckFailed`,{error:t.error})}),i(U,{type:`button`,size:`sm`,variant:`outline`,onClick:t.retry,children:r(`common.retry`,`Retry`)})]}):null:null}var oo=[{value:`rearmAfter`,labelKey:`system.alarmModeCard.postRearm`},{value:`disableAfter`,labelKey:`system.alarmModeCard.postDisarm`},{value:`doNothing`,labelKey:`system.alarmModeCard.postNothing`}];function so({coverage:t,settings:n,disabled:r,onDelayEdit:a,onPostTriggeredEdit:o,onScheduleEdit:s}){let{t:c}=Y(),l=t.mode,u=Pe(n,l),d=u.source.postTriggeredAction==="default",f=u.postTriggeredAction!==`doNothing`,p=(n.modeDelays??[]).find(e=>e.mode===l)?.schedule;return e(`div`,{className:`space-y-3`,"data-testid":`alarm-delays-${l}`,children:[e(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:[Ea.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let t=u.source[e.field]==="default";return i(ka,{label:c(e.labelKey),value:u[e.field],max:e.max,zeroMeans:c(e.zeroMeansKey),disabled:r,testId:`alarm-delay-${l}-${e.key}`,onCommit:t=>a(e.field,t),adornment:t?i(H,{variant:`default`,title:c(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:n[e.field]}),children:c(`system.alarmModeCard.default`,`Default`)}):i(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:c(e.labelKey)}),onClick:()=>a(e.field,`default`),"data-testid":`alarm-delay-${l}-${e.key}-default`,children:i(g,{className:`h-3.5 w-3.5`})})},e.field)}),e(`div`,{children:[e(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:[c(`system.alarmModeCard.afterTrigger`,`After trigger`),d?i(H,{variant:`default`,className:`ml-1.5 align-middle`,title:c(`system.alarmModeCard.usesTheSystemDefault`,`Uses the system default`),children:c(`system.alarmModeCard.default`,`Default`)}):i(U,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:r,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.afterTriggerUseTheDefault`,`After trigger: use the default`),onClick:()=>o(`default`),"data-testid":`alarm-delay-${l}-post-default`,children:i(g,{className:`h-3.5 w-3.5`})})]}),i(P,{className:`mt-1 w-full`,value:u.postTriggeredAction,disabled:r,"data-testid":`alarm-delay-${l}-post`,onChange:e=>{let t=Ae.safeParse(e.target.value);t.success&&o(t.data)},children:oo.map(e=>i(`option`,{value:e.value,children:c(e.labelKey)},e.value))})]}),f?Ea.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let t=u.source[e.field]==="default";return i(ka,{label:c(e.labelKey),value:u[e.field],max:e.max,zeroMeans:c(e.zeroMeansKey),disabled:r,testId:`alarm-delay-${l}-${e.key}`,onCommit:t=>a(e.field,t),adornment:t?i(H,{variant:`default`,title:c(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:n[e.field]}),children:c(`system.alarmModeCard.default`,`Default`)}):i(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:c(e.labelKey)}),onClick:()=>a(e.field,`default`),"data-testid":`alarm-delay-${l}-${e.key}-default`,children:i(g,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),e(`div`,{"data-testid":`alarm-schedule-${l}`,children:[i(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.alarmModeCard.activationSchedule`,`Activation schedule`)}),i(`p`,{className:`mb-1 text-[10px] text-foreground-subtle`,children:c(`system.alarmModeCard.whenThisModeMayBe`,`When this mode may be armed. Empty means any day and time.`)}),i(`fieldset`,{disabled:r,className:`min-w-0 border-0 p-0`,children:i(Zr,{value:p,onChange:s,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var co={"no-opening":`This household has no contact, cover or lock.`};function lo({coverage:t,live:n,settings:r,names:a,openingsCheck:o,rows:s,sensorsRetry:c,inFlight:l,onSwitch:u,zones:d,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m,onNotifyEdit:h,disabled:g}){let{t:_}=Y(),v=zi({live:n,listed:oa(r,t.mode),openingIds:io(o)}),y=Bi(v),b=Xa({rowCount:s.length,candidatesComplete:!v.unresolved});return e(`div`,{className:`flex flex-col gap-3`,"data-mode":t.mode,"data-empty":Xi(t)?`true`:`false`,children:[i(ro,{coverage:t,rows:s,names:a}),i(so,{coverage:t,settings:r,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:_(`system.alarmModeCard.delaysHint`,{seconds:30})}),i(no,{coverage:t,settings:r,disabled:g,onNotifyEdit:h}),e(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${t.mode}`,children:[i(ao,{check:o,view:v}),y===null?null:i(`p`,{className:`text-xs text-foreground-subtle`,children:co[y]}),b===`none`&&y===null?i(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`alarm-sensors-none`,children:_(`system.alarmModeCard.noSensorIsCoveredBy`,`No sensor is covered by a rule of this mode.`)}):null,b===`rows`?i(Ha,{mode:t.mode,rows:s,sensorsRetry:c,inFlight:l,onSwitch:u,zones:d,disabled:g}):null]})]})}c();function uo({profiles:t,busy:n,onActivate:r,onCreate:a,onClone:s,onRename:c,onDelete:l}){let{t:u}=Y(),[d,p]=o(``),[m,h]=o(!1),g=t.items.find(e=>e.id===t.activeId)??t.items[0],v=g!==void 0&&!g.isDefault,y=d.trim(),b=()=>{y.length!==0&&(a(y),p(``))},x=()=>{y.length===0||g===void 0||(s(g.id,y),p(``))},S=()=>{y.length===0||g===void 0||(c(g.id,y),p(``),h(!1))};return e(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface p-3`,"data-testid":`alarm-profiles`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:u(`system.alarmProfileBar.profile`,`Profile`)}),i(P,{wrapperClassName:`inline-block w-auto`,id:`alarm-profile-select`,className:`min-w-[10rem]`,"data-testid":`alarm-profile-select`,disabled:n,value:t.activeId,onChange:e=>r(e.target.value),children:t.items.map(t=>e(`option`,{value:t.id,children:[t.name,t.isDefault?` (${u(`system.alarmProfileBar.defaultSuffix`)})`:``]},t.id))}),v?i(U,{type:`button`,variant:`ghost`,size:`sm`,disabled:n,"data-testid":`alarm-profile-delete`,title:u(`system.alarmProfileBar.deleteThisProfile`,`Delete this profile`),onClick:()=>{g!==void 0&&l(g.id)},children:i(E,{className:`h-3.5 w-3.5`})}):null]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(K,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:m?u(`system.alarmProfileBar.newName`,`New name`):u(`system.alarmProfileBar.newProfileName`,`New profile name`),value:d,disabled:n,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(m?S():b())}}),m?e(f,{children:[i(U,{type:`button`,size:`sm`,disabled:n||y.length===0,"data-testid":`alarm-profile-rename-save`,onClick:S,children:u(`system.alarmProfileBar.rename`,`Rename`)}),i(U,{type:`button`,variant:`ghost`,size:`sm`,disabled:n,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{h(!1),p(``)},children:u(`common.cancel`,`Cancel`)})]}):e(f,{children:[e(U,{type:`button`,size:`sm`,disabled:n||y.length===0,"data-testid":`alarm-profile-create`,title:u(`system.alarmProfileBar.createWithSystemDefaults`,`Create with system defaults`),onClick:b,children:[i(_,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.create`,`Create`)]}),e(U,{type:`button`,size:`sm`,variant:`secondary`,disabled:n||y.length===0||g===void 0,"data-testid":`alarm-profile-clone`,title:u(`system.alarmProfileBar.cloneTheSelectedProfile`,`Clone the selected profile`),onClick:x,children:[i(D,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.clone`,`Clone`)]}),i(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:n||g===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{h(!0),p(g?.name??``)},children:u(`system.alarmProfileBar.rename`,`Rename`)})]})]}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`system.alarmProfileBar.createStartsFromSystemDefaults`,`Create starts from system defaults. Clone copies the selected profile (sensors, secure-on-arm, delays). Switching applies that profile for the next arm.`)})]})}c();var fo=[`notificationRules`,`getAlarmConfig`],po=[`notificationRules`,`getAlarmSensors`],mo=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],ho=6e4;function go(e){return e instanceof Error?e.message:String(e)}function _o({notice:e}){let{t}=Y();switch(e.kind){case`refused`:return i(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:t(`system.notificationAlarm.refused`,{name:e.inFlight.name,mode:Gi(e.inFlight.mode)})});case`not-landed`:return i(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:t(`system.notificationAlarm.notLanded`,{name:e.write.name,mode:Gi(e.write.mode)})});case`failed`:return i(`p`,{className:`text-xs text-danger`,role:`alert`,"data-testid":`alarm-switch-failed`,children:t(`system.notificationAlarm.couldNotChangeFor`,`Could not change {{name}} for {{value2}}: {{error}}`,{name:e.write.name,value2:Gi(e.write.mode),error:e.error})})}}function vo(){let{t:r}=Y(),a=N(),c=l(),f=s({queryKey:fo,queryFn:async()=>a.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>ta(e.state.data?.live?.state)}),p=st({projection:`slim`}),[h,g]=o(!1),_=d({mutationFn:e=>a.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{c.setQueryData(fo,e),g(!I(t,e.settings))}}),v=d({mutationFn:async e=>{switch(e.kind){case`activate`:return a.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return a.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return a.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return a.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return a.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{c.setQueryData(fo,e),g(!1)}}),y=()=>c.invalidateQueries({queryKey:fo}),b=n(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),x=f.data?.live,S=s({queryKey:mo,staleTime:ho,queryFn:async()=>new Set(await a.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...Li]}))}),C=n(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),w=n(()=>new Map(C.map(e=>[e.id,e])),[C]),E=S.isError?{status:`failed`,error:S.error instanceof Error?S.error.message:String(S.error),retry:()=>void S.refetch()}:S.data===void 0?{status:`pending`}:{status:`answered`,openingIds:S.data},D=n(()=>{let e=new Map;for(let t of x?.openings??[])for(let n of t.devices)e.set(n.deviceId,Hi(n));return Vi(b,Bt(p),e)},[x,b,p]),O=It(!0),[k,A]=o(null),ee=n(()=>{let e=new Map,t=f.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,zi({live:t.live,listed:oa(t.settings,n.mode),openingIds:S.data??null}).ids);return e},[f.data,S.data]),j=n(()=>{let e=new Set;for(let t of ee.values())for(let n of t)D.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[ee,D]),M=s({queryKey:[...po,j],enabled:j.length>0,placeholderData:u,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&Wa(go(e.state.error))?!1:x!==void 0&&ia(x.state)?5e3:15e3,retry:(e,t)=>!Wa(go(t))&&e<2,queryFn:async()=>{let e=[];for(let t of Za(j,500))e.push(await a.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...t]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),te=M.isError?{status:`failed`,error:go(M.error)}:M.data===void 0?{status:`pending`}:{status:`answered`,sensors:M.data.sensors},P=t(null),[ne,re]=o(null),[F,ie]=o(null),ae=async e=>{try{let t=await a.trpcClient.notificationRules.setAlarmConfig.mutate({patch:$a(e)});eo(e,t.settings).kind===`landed`?c.setQueryData(fo,t):(ie({kind:`not-landed`,write:e}),c.invalidateQueries({queryKey:fo}))}catch(t){ie({kind:`failed`,write:e,error:go(t)}),c.invalidateQueries({queryKey:fo})}finally{P.current=null,re(null),ie(e=>e?.kind===`refused`?null:e)}},oe=(e,t,n,r)=>{let i=Qa(P.current,e,t,n,r);if(i.kind===`refused`){ie({kind:`refused`,inFlight:i.inFlight});return}P.current=i.write,re(i.write),ie(null),ae(i.write)};if(f.isLoading)return i(Ti,{embedded:!0,icon:m,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(T,{className:`h-5 w-5 animate-spin`})});let L=f.data;if(L===void 0||f.isError)return i(Ti,{embedded:!0,icon:m,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(G,{title:r(`system.notificationAlarm.alarmSettingsAreNotAvailable`,`Alarm settings are not available`),message:r(`system.notificationAlarm.thisHubHasNotBeen`,`This hub has not been updated to serve the alarm configuration yet.`)})});if(L.deviceId===null)return i(Ti,{embedded:!0,icon:m,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(ct,{className:`p-4`,children:i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.notificationAlarm.thisInstallationHasNoAlarm`,`This installation has no alarm panel. The panel is created by the Notification Center on the hub — if this is the hub, its creation failed and the server log says why.`)})})});let se=L.settings,ce=_.isPending||v.isPending,le=e=>{g(!1),_.mutate(e)},ue=(e,t,n)=>{let r=da(se,e,t,n);r!==null&&le({modeDelays:[r]})},de=(e,t)=>{let n=fa(se,e,t);n!==null&&le({modeDelays:[n]})},fe=(e,t)=>{let n=pa(se,e,t);n!==null&&le({modeDelays:[n]})},pe=(e,t,n)=>{let r=ba(se,e,t,n);r!==null&&le({modeDelays:[r]})},me=new Map(L.coverage.map(e=>[e.mode,Ya({candidates:(ee.get(e.mode)??[]).map(e=>({...w.get(e),id:e,name:D.nameOf(e)})),removedIds:new Set((ee.get(e.mode)??[]).filter(D.isRemoved)),coverage:e,nonBlocking:oa(se,e.mode),blocking:sa(se,e.mode),secureOnArmOff:ca(se,e.mode),sensors:te})])),R=L.coverage.find(e=>e.mode===k)??L.coverage.find(e=>(me.get(e.mode)?.length??0)>0)??L.coverage[0],he=R?.mode??``;return e(Ti,{embedded:!0,icon:m,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.thePanelWhatEachMode`,`The panel, what each mode arms, and who hears about it.`),children:[_.isError?i(G,{title:r(`system.notificationAlarm.couldNotSave`,`Could not save`),message:String(_.error)}):null,v.isError?i(G,{title:r(`system.notificationAlarm.couldNotUpdateProfile`,`Could not update profile`),message:String(v.error)}):null,h?i(`div`,{"data-testid":`alarm-save-not-landed`,children:i(G,{variant:`warning`,title:r(`system.notificationAlarm.notApplied`,`Not applied`),message:r(`system.notificationAlarm.theHubDidNotApply`,`The hub did not apply this change — another editor may have changed it, or the hub needs an update`)})}):null,L.profiles===void 0?null:i(uo,{profiles:L.profiles,busy:ce,onActivate:e=>v.mutate({kind:`activate`,id:e}),onCreate:e=>v.mutate({kind:`create`,name:e}),onClone:(e,t)=>v.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>v.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>v.mutate({kind:`delete`,id:e})}),i(Ta,{live:L.live,onChanged:y}),e(ct,{className:`p-4`,"data-testid":`alarm-coverage`,children:[i(Jt,{value:he,onValueChange:e=>{let t=L.coverage.find(t=>t.mode===e);t!==void 0&&A(t.mode)},children:i(Mt,{className:`mb-3`,children:L.coverage.map(t=>e(Ut,{value:t.mode,"data-testid":`alarm-tab-${t.mode}`,children:[Gi(t.mode),i(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:me.get(t.mode)?.length??0})]},t.mode))})}),F===null?null:i(_o,{notice:F}),R===void 0?null:i(lo,{coverage:R,live:L.live,settings:se,names:D,openingsCheck:E,rows:me.get(R.mode)??[],sensorsRetry:te.status===`failed`&&!Wa(te.error)?()=>void M.refetch():null,inFlight:ne,onSwitch:(e,t,n)=>oe(R.mode,e,t,n),zones:O,onDelayEdit:(e,t)=>ue(R.mode,e,t),onPostTriggeredEdit:e=>de(R.mode,e),onScheduleEdit:e=>fe(R.mode,e),onNotifyEdit:(e,t)=>pe(R.mode,e,t),disabled:ce},R.mode)]})]})}var yo=`history`,bo=`ruleId`,xo=[bo],So=24,Co=0,wo=100;function To(e,t){let n=new URLSearchParams(e);return n.set(`tab`,yo),n.set(bo,t),n}function Eo(e,t){let n=new URLSearchParams(e);return t===``?n.delete(bo):n.set(bo,t),n}function Do(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?So:Co,limit:wo}}function Oo(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]}c();var ko=[{value:1,labelKey:`system.notificationHistory.windowLastHour`},{value:24,labelKey:`system.notificationHistory.windowLast24h`},{value:168,labelKey:`system.notificationHistory.windowLast7d`},{value:0,labelKey:`system.notificationHistory.windowAllTime`}],Ao=[{value:``,labelKey:`system.notificationHistory.statusAny`},{value:`pending`,labelKey:`system.notificationHistory.statusPending`},{value:`sent`,labelKey:`system.notificationHistory.statusSent`},{value:`dead`,labelKey:`system.notificationHistory.statusDead`}],jo=[50,100,250,500];function Mo(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function No(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Po(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 Fo({entry:t,cameraName:n,onClose:r}){let{t:a}=Y(),o=Po(t),s=t.subject.systemEvent;return i(xt,{open:!0,onOpenChange:e=>!e&&r(),children:e(ht,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[i(Tt,{children:i(Ct,{className:`min-w-0 break-words`,children:o.title||t.ruleName})}),i(ft,{children:e(`dl`,{className:`space-y-3`,children:[e(`div`,{children:[i(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:a(`system.notificationHistory.body`,`Body`)}),i(`dd`,{className:`mt-1 whitespace-pre-wrap text-sm text-foreground`,children:o.body.length>0?o.body:`—`})]}),e(`div`,{className:`grid grid-cols-2 gap-3 text-[11px]`,children:[e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.when`,`When`)}),i(`dd`,{className:`text-foreground`,children:new Date(t.createdAt).toLocaleString()})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.status`,`Status`)}),i(`dd`,{className:`text-foreground`,children:t.status})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.rule`,`Rule`)}),i(`dd`,{className:`text-foreground`,children:t.ruleName})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.device`,`Device`)}),i(`dd`,{className:`text-foreground`,children:n})]}),s===void 0?null:e(`div`,{className:`col-span-2`,children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.kind`,`Kind`)}),i(`dd`,{className:`text-foreground`,children:s.kind})]}),t.error===void 0?null:e(`div`,{className:`col-span-2`,children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`common.error`,`Error`)}),i(`dd`,{className:`text-danger`,children:t.error})]})]})]})}),i(mt,{children:i(U,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:a(`common.close`,`Close`)})})]})})}function Io(){let{t}=Y(),r=N(),[a,c]=an(),[l,u]=o(()=>Do(a)),[d,f]=o(null),p=e=>u(t=>({...t,...e})),m=e=>{p({ruleId:e}),c(Eo(a,e),{replace:!0})},h=s({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await r.trpcClient.notificationRules.listRules.query({})).rules}),g=st({projection:`slim`}),_=Date.now(),v=s({queryKey:[`notificationRules`,`getHistory`,l],retry:!1,queryFn:async()=>{let e=l.windowHours>0?_-l.windowHours*36e5:void 0;return(await r.trpcClient.notificationRules.getHistory.query({filter:{limit:l.limit,...l.ruleId?{ruleId:l.ruleId}:{},...l.deviceId?{deviceId:Number(l.deviceId)}:{},...Mo(l.status)?{status:Mo(l.status)}:{},...e===void 0?{}:{since:e}}})).entries}}),y=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]),b=e=>y.get(e)??t(`system.notificationHistory.cameraFallback`,{deviceId:e}),x=v.data??[],S=v.isError;return e(Ti,{embedded:!0,icon:w,title:t(`system.notificationHistory.deliveryHistory`,`Delivery history`),subtitle:t(`system.notificationHistory.aSearchableLogOfEvery`,`A searchable log of every notification the rules delivered (or failed to deliver).`),children:[e(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.rule`,`Rule`)}),i(P,{"data-testid":`history-rule-filter`,value:l.ruleId,onChange:e=>m(e.target.value),options:[...Oo({rules:h.data??[],answered:h.isSuccess,selected:l.ruleId})]})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.camera`,`Camera`)}),i(P,{value:l.deviceId,onChange:e=>p({deviceId:e.target.value}),options:[{value:``,label:t(`system.notificationHistory.allCameras`,`All cameras`)},...(g.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.status`,`Status`)}),i(P,{value:l.status,onChange:e=>p({status:e.target.value}),options:Ao.map(e=>({value:e.value,label:t(e.labelKey)}))})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.window`,`Window`)}),i(P,{value:String(l.windowHours),onChange:e=>p({windowHours:Number(e.target.value)}),options:ko.map(e=>({value:String(e.value),label:t(e.labelKey)}))})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.limit`,`Limit`)}),i(P,{value:String(l.limit),onChange:e=>p({limit:Number(e.target.value)}),options:jo.map(e=>({value:String(e),label:String(e)}))})]})]}),v.isLoading&&i(`div`,{className:`flex items-center justify-center py-16`,children:i(T,{className:`h-6 w-6 animate-spin text-primary`})}),S&&!v.isLoading&&i(ct,{children:e(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[i(w,{className:`h-6 w-6 text-foreground-subtle`}),i(`div`,{className:`text-sm font-medium text-foreground`,children:t(`system.notificationHistory.deliveryHistoryRequiresAServer`,`Delivery history requires a server update`)}),i(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:t(`system.notificationHistory.theHistoryQueryIsNot`,`The history query is not available on this hub yet. It becomes queryable after the next server update ships the notification-center history endpoint. Rules still deliver and record their outcome in the meantime.`)}),e(U,{variant:`unstyled`,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:[i(ie,{className:`h-3 w-3`}),` `,t(`common.retry`)]})]})}),!S&&!v.isLoading&&x.length===0&&i(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:t(`system.notificationHistory.noDeliveriesMatchTheseFilters`,`No deliveries match these filters.`)}),!S&&x.length>0&&i(ct,{children:i(pt,{columns:Lo(b),rows:x,rowKey:e=>e.id,minWidthPx:720,bordered:!1,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>f(e)})}),d!==null&&i(Fo,{entry:d,cameraName:b(d.deviceId),onClose:()=>f(null)})]})}function Lo(t){return[{key:`when`,header:J.t(`system.notificationHistory.when`,`When`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:J.t(`system.notificationHistory.rule`,`Rule`),render:e=>i(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:J.t(`system.notificationHistory.camera`,`Camera`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t(e.deviceId)})},{key:`subject`,header:J.t(`system.notificationHistory.notification`,`Notification`),render:t=>{let n=Po(t);return e(`span`,{className:`block max-w-[18rem]`,children:[i(`span`,{className:`block truncate text-[11px] font-medium text-foreground`,children:n.title.length>0?n.title:t.subject.label??t.subject.className}),n.body.length>0?i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:n.body}):null]})}},{key:`status`,header:J.t(`system.notificationHistory.status`,`Status`),nowrap:!0,render:t=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(H,{variant:No(t.status),children:t.status}),t.attempts>1?e(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,t.attempts]}):null]})},{key:`error`,header:J.t(`system.notificationHistory.detail`,`Detail`),render:e=>e.error?i(`span`,{className:`text-[11px] text-danger`,children:e.error}):i(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var Ro=/\{\{\s*(\w+)\s*\}\}/g,zo=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function Bo(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function Vo(e){return[...e.matchAll(Ro)].map(e=>e[1]??``).filter(e=>e.length>0)}function Ho(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function Uo(e,t){return[...new Set(Vo(e))].filter(e=>!Ho(e,t))}var Wo={previewText:[`device`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function Go(e){return e.map(e=>{let t=me.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)||De.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function Ko(e){let t=new Set(e.map(e=>e.name)),n=me.filter(e=>_e(e)&&!t.has(e.name));return[...e,...n]}function qo(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=Wo[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)||!ge(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:ke(e,t)&&Be(e,t))}function Jo(e){return zo.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var Yo=[`nc`,`template-catalog`],Xo=400;function Zo(){let e=N();return s({queryKey:Yo,staleTime:5*6e4,queryFn:async()=>Ko(Go((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function Qo(e,t,n){let r=N(),i=Zt(t.title??``,Xo),a=Zt(t.body??``,Xo);return s({queryKey:[`nc`,`template-preview`,e,i,a],enabled:n&&(i.length>0||a.length>0),staleTime:3e4,queryFn:()=>r.trpcClient.notificationRules.previewTemplate.mutate({context:e,template:{...i?{title:i}:{},...a?{body:a}:{}}})})}c();var $o={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},es=`block text-[11px] font-medium text-foreground mb-1`;function ts({label:n,value:r,onChange:a,vars:o,multiline:s=!1,placeholder:c,disabled:l=!1,testId:u}){let{t:d}=Y(),f=t(null),p=o?Uo(r,o):[],m=e=>{let t=Bo(e);f.current?.insertText(t.text,t.cursorOffset)};return e(`div`,{className:`space-y-1`,children:[i(`label`,{className:es,children:n}),i(Et,{label:n,value:r,onChange:a,multiline:s,placeholder:c,disabled:l,handle:f,testId:u}),o&&o.length===0?i(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(`notifications.templateField.noVariablesForThisField`,`No variables for this field.`)}):null,o&&o.length>0?i(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:Jo(o).map(t=>e(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${u}-group-${t.group}`,children:[i(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:$o[t.group]}),t.vars.map(e=>i(U,{variant:`unstyled`,type:`button`,disabled:l,onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),title:`${e.description??e.label} — e.g. "${e.example}"`,className:`rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-foreground hover:bg-surface-hover`,"data-testid":`${u}-chip-${e.name}`,children:e.dynamic?d(`notifications.templateField.class`,`{{name}}<class>`,{name:e.name}):e.name},e.name))]},t.group))}):null,p.length>0?e(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${u}-unknown`,children:[i(v,{className:`h-3 w-3`}),d(`notifications.templateField.willBeEmpty`,{names:p.map(e=>`{{${e}}}`).join(` `)})]}):null]})}function ns({context:t,title:n,body:r,testId:a}){let{t:o}=Y(),s=Qo(t,{title:n,body:r},!0);return s.data?e(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":a,children:[i(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:o(`notifications.templateField.previewExampleValues`,`Preview (example values)`)}),s.data.title===null?null:i(`p`,{className:`font-medium`,children:s.data.title}),s.data.body===null?null:i(`p`,{className:`whitespace-pre-wrap`,children:s.data.body})]}):null}var rs=`/build?tab=actions&create=1`,is=`/build?tab=actions&create=1&preset=${wi}`,as=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,os=`block text-[11px] font-medium text-foreground`;function ss({title:t,description:n,children:r}){return e(`div`,{className:`flex flex-col gap-2`,children:[e(`div`,{children:[i(`h4`,{className:`text-xs font-semibold text-foreground`,children:t}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:n})]}),r!==void 0&&i(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function cs(){let{t}=Y();return e(vn,{to:rs,target:`_blank`,rel:`noopener noreferrer`,title:t(`system.notificationRuleActions.createActionHint`,`Opens the Actions page in a new tab. Reopen the list here afterwards.`),className:`inline-flex items-center gap-1 text-[11px] font-medium text-primary hover:underline`,children:[i(k,{className:`h-3.5 w-3.5 shrink-0`}),t(`system.notificationRuleActions.createActionLink`,`Create a new Action`)]})}function ls(){let{t:e}=Y();return i(vn,{to:is,target:`_blank`,rel:`noopener noreferrer`,title:e(`system.notificationRuleActions.presetAlarmHint`,`Presses the alarm panel. The panel's entry delay still runs, and a disarm during it cancels the alarm.`),className:`inline-flex items-center gap-1 text-[11px] font-medium text-primary hover:underline`,children:e(`system.notificationRuleActions.presetAlarm`,`Trigger the alarm`)})}function us({value:t,actions:n,onChange:r}){let{t:a}=Y(),o=t!==``&&!n.some(e=>e.id===t);return e(P,{wrapperClassName:`block w-full`,className:as,value:t,onChange:e=>r(e.target.value),children:[t===``&&i(`option`,{value:``,children:a(`system.notificationRuleActions.pickAction`,`Pick an Action`)}),o&&i(`option`,{value:t,children:a(`system.notificationRuleActions.missingAction`,`Missing Action ({{id}})`,{id:t})}),n.map(e=>i(`option`,{value:e.id,children:e.name},e.id))]})}function ds({value:t,onChange:n,actions:r,showProblems:a=!0}){let{t:o}=Y(),s=mr(t,new Set(r.map(e=>e.id))),c=(e,r)=>n({...t,[e]:r}),l=(e,r)=>n({...t,buttons:t.buttons.map((t,n)=>n===e?r:t)});return e(`div`,{className:`space-y-4`,children:[a&&s.length>0?i(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:s.map(e=>i(`p`,{children:e.message},e.message))}):null,r.length===0&&e(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[o(`system.notificationRuleActions.noActionsYet`,`There are no Actions yet. Create one on the Actions page — a rule or a button runs an Action, it does not define its own steps.`),` `,i(cs,{}),` `,i(ls,{})]}),Sr.map(e=>i(fs,{hookKey:e,actionIds:t[e],actions:r,onChange:t=>c(e,t)},e)),e(`section`,{className:`space-y-2`,children:[e(ss,{title:o(`system.notificationRuleActions.buttonsOnTheNotification`,`Buttons on the notification`),description:o(`system.notificationRuleActions.eachButtonRunsOneAction`,`Each button runs one Action when tapped.`),children:[e(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:r.length===0,onClick:()=>n({...t,buttons:[...t.buttons,ei(t.buttons.length,r[0]?.id??``)]}),children:[i(_,{className:`h-3.5 w-3.5 shrink-0`}),` `,o(`system.notificationRuleActions.button`)]}),i(cs,{}),i(ls,{})]}),t.buttons.length>0&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:[i(v,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),i(`span`,{children:i(Bn,{i18nKey:`system.notificationRuleActions.buttonLinkNote`,components:{b:i(`strong`,{})}})})]}),t.buttons.length===0?i(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:o(`system.notificationRuleActions.noButtonsTheNotificationArrives`,`No buttons. The notification arrives with nothing to tap.`)}):t.buttons.map((e,a)=>i(ps,{button:e,actions:r,onChange:e=>l(a,e),onRemove:()=>n({...t,buttons:t.buttons.filter((e,t)=>t!==a)})},`btn-${String(a)}`))]})]})}function fs({hookKey:t,actionIds:n,actions:r,onChange:a}){let{t:o}=Y(),s=ii[t];return e(`section`,{className:`space-y-2`,children:[i(ss,{title:s.title,description:s.hint,children:e(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.length>=4||r.length===0,onClick:()=>a([...n,r[0]?.id??``]),children:[i(_,{className:`h-3.5 w-3.5`}),` `,o(`system.notificationRuleActions.addAction`)]})}),n.length===0?i(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:o(`system.notificationRuleActions.nothingOnThisEdge`,`Nothing on this edge.`)}):n.map((s,c)=>e(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:os,children:o(`system.notificationRuleActions.action`,`Action`)}),i(us,{value:s,actions:r,onChange:e=>a(n.map((t,n)=>n===c?e:t))})]}),i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>a(n.filter((e,t)=>t!==c)),title:o(`common.remove`,`Remove`),children:i(E,{className:`h-3.5 w-3.5`})})]},`${t}-${String(c)}`))]})}function ps({button:t,actions:n,onChange:r,onRemove:a}){let{t:o}=Y();return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[e(`div`,{className:`w-28`,children:[i(`label`,{className:os,children:o(`system.notificationRuleActions.id`,`Id`)}),i(K,{className:`mt-1`,value:t.id,onChange:e=>r({...t,id:e.target.value})})]}),e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:os,children:o(`system.notificationRuleActions.label`,`Label`)}),i(K,{className:`mt-1`,value:t.label,onChange:e=>r({...t,label:e.target.value})})]}),e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:os,children:o(`system.notificationRuleActions.action`,`Action`)}),i(us,{value:t.actionId,actions:n,onChange:e=>r({...t,actionId:e})})]}),e(`div`,{className:`w-32`,children:[i(`label`,{className:os,children:o(`system.notificationRuleActions.icon`,`Icon`)}),e(P,{wrapperClassName:`inline-block w-auto`,className:as,value:t.icon??``,onChange:e=>{let{icon:n,...i}=t,a=$t.find(t=>t.value===e.target.value);r(a===void 0?i:{...i,icon:a.value})},children:[i(`option`,{value:``,children:`—`}),$t.map(e=>i(`option`,{value:e.value,children:e.label},e.value))]})]}),i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,title:o(`common.remove`,`Remove`),children:i(E,{className:`h-3.5 w-3.5`})})]})}function ms({param:e,value:t,onChange:n}){let{t:r}=Y(),a=e.default===void 0?void 0:String(e.default);return e.type===`enum`?i(P,{value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`system.notificationRules.deliveryOptions.useDefault`,`Use the target setting`)},...e.options??[]]}):e.type===`boolean`?i(q,{checked:t===!0,onCheckedChange:e=>n(e),label:e.label}):i(K,{type:e.type===`number`?`number`:`text`,value:typeof t==`number`||typeof t==`string`?String(t):``,placeholder:a,min:e.min,max:e.max,onChange:t=>{let r=t.target.value;if(r===``)return n(void 0);if(e.type===`string`)return n(r);let i=Number(r);n(Number.isFinite(i)?i:void 0)}})}function hs({params:t,valueOf:n,onChange:r}){let{t:a}=Y();return t.length===0?null:e(`div`,{className:`flex flex-col gap-3`,"data-testid":`rule-delivery-options`,children:[i(`p`,{className:`text-sm font-medium text-foreground`,children:a(`system.notificationRules.deliveryOptions.title`,`Delivery options`)}),t.map(e=>i(_t,{label:e.label,children:i(ms,{param:e,value:n(e.key),onChange:t=>r(e.key,t)})},e.key))]})}function gs(e,t){return t.find(t=>t.kind===e.kind&&t.addonId===e.addonId)}function _s(e,t,n){let r=t.find(t=>t.id===e);return(r===void 0?void 0:gs(r,n)?.deliveryParams)??[]}function vs(e,t,n){return Ce(e.map(e=>_s(e,t,n)))}function ys(e,t,n){for(let r of e){let e=t[r]?.[n];if(e!==void 0)return e}}function bs(e,t,n){let r={...e.targetParams};for(let i of e.targetIds){if(!_s(i,e.targets,e.kinds).some(e=>e.key===t))continue;let{[t]:a,...o}=r[i]??{},s=n===void 0?o:{...o,[t]:n};Object.keys(s).length===0?delete r[i]:r[i]=s}return r}var xs=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Ss=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],Cs={minConfidence:`class`},ws=[{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 Ts(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Ss)t.has(e)&&n.add(r);return n}function Es(e){return Cs[e.id]??e.group}function Ds(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Os(e){let t=Ts(e),n=e.filter(e=>!xs.has(e.id)&&!t.has(e.id)),r=new Set(ws.map(e=>e.id)),i=[],a=e=>n.filter(t=>Es(t)===e);for(let e of ws){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=Es(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Ds(e),descriptors:a(e)});return i}function ks(e,t){switch(e){case`zones`:return oi(t.zones?.ids,t.zonesExclude);case`labels`:return oi(t.labelEquals,void 0);case`identities`:return As(t)}}function As(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?oi(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function js(e,t,n){switch(e){case`zones`:return Ms(t,n);case`labels`:return Ns(t,n);case`identities`:return Ps(t,n)}}function Ms(e,t){let{zones:n,zonesExclude:r,...i}=e,a=ni(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function Ns(e,t){let{labelEquals:n,...r}=e,i=ni(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function Ps(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=br(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=ni(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var Fs={all:`All`,only:`Only these`,except:`All except these`},Is={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 Ls({draft:t,onChange:n,exceptOffered:r,plural:a,renderPicker:o,describe:s,testId:c}){let{t:l}=Y(),u=(e,t,n)=>l(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),d=l(`ruleScope.items.${a}`,Is[a].items),f=qr.filter(e=>e!==`except`||r||t.mode===`except`),p=br(t),m=Br(t),h=t.mode===`all`?null:t.mode;return e(`div`,{className:`mt-1 space-y-1.5`,"data-testid":c,children:[i(`div`,{role:`radiogroup`,"aria-label":u(`ruleScope.which`,`Which {{items}}`,d),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(e=>{let r=e===t.mode;return i(U,{variant:`unstyled`,type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${e}`,onClick:()=>n(Hr(t,e)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,children:l(`ruleScope.mode.${e}`,Fs[e])},e)})}),h===null?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:l(`ruleScope.every.${a}`,Is[a].every)}):o(wr(t),e=>n(Yr(t,e)),h),p.length>0&&e(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[u(`ruleScope.legacy`,`This rule also excludes {{items}} — kept when you save.`,p.map(s).join(`, `)),` `,i(U,{variant:`unstyled`,type:`button`,className:`underline hover:no-underline`,onClick:()=>n(vr(t)),children:l(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:u(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(s).join(`, `))})]})}function Rs(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 zs(e){return e.map(e=>e.hint===void 0?{id:e.value,name:e.label}:{id:e.value,name:`${e.hint}:${e.label}`,type:e.hint})}c();function Bs(e,t,n){let[r,i]=o(()=>ks(e,t));return[r,r=>{i(r),n(js(e,t,r))}]}function Vs(e,t){return t?`failed`:e?`pending`:`answered`}function Hs({conditions:e,onConditionsChange:t,exceptOffered:r,cameraIds:a,cameras:o}){let{t:s}=Y(),[c,l]=Bs(`zones`,e,t),{options:u,loading:d,failed:f}=Ar(a,o),p=n(()=>zs(u),[u]),m=Vs(d,!1),h=f?{state:`failed`,devices:void 0}:{state:m,devices:m===`answered`?p:void 0},g=n(()=>new Map(p.map(e=>[e.id,e.name])),[p]);return i(Ls,{draft:c,onChange:l,exceptOffered:r,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>a.length===0?i(`p`,{className:yi,children:s(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):i(ot,{devices:p,listState:m,fleet:h,value:e,onChange:t,emptyMeansAll:!0,noun:`zone`,groupTitle:e=>e.type??s(`notificationRules.zones.group`,`Zones`),testId:`zone-picker`},n)})}function Us({conditions:e,onConditionsChange:t,exceptOffered:r}){let{t:a}=Y(),[o,s]=Bs(`identities`,e,t),{options:c,loading:l,failed:u}=Ur(),d=n(()=>c.map(e=>({id:e.value,name:e.label})),[c]),f=n(()=>new Map(d.map(e=>[e.id,e.name])),[d]);return i(Ls,{draft:o,onChange:s,exceptOffered:r,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>i(ot,{devices:d,listState:Vs(l,u),value:e,onChange:t,emptyMeansAll:n===`except`,...n===`only`?{emptyLabel:a(`notificationRules.faces.anyKnown`,`Any known face — nobody in particular`)}:{},noun:`face`,groupTitle:()=>a(`notificationRules.faces.group`,`Known faces`),testId:`identity-picker`},n)})}function Ws({conditions:e,onConditionsChange:t}){let{t:n}=Y(),[r,a]=Bs(`labels`,e,t);return i(Ls,{draft:r,onChange:a,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>i(Qn,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function Gs(e){let t=Ee(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function Ks(e){return e.type??J.t(`helpers.classPickerItems.other`)}c();function qs({taxonomy:e,scope:t,onChange:r,exceptOffered:a}){let{t:o}=Y(),s=n(()=>Gs(e),[e]),c=n(()=>new Map((s??[]).map(e=>[e.id,e.name])),[s]);return i(Ls,{draft:t,onChange:r,exceptOffered:a,plural:`classes`,describe:e=>c.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>s===null?i(Qn,{value:e,placeholder:o(`system.notificationClassScopeField.addValue`,`Add value…`),onChange:t}):i(ot,{devices:s,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:Ks,testId:`class-picker`},n)})}function Js(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function Ys({devices:e,value:t,onChange:n,listState:r,savedHadDevices:a}){return i(ot,{devices:e.map(Js),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:a,noun:`device`,showAll:!0})}function Xs({devices:e,scope:t,onChange:n,listState:r,savedScope:a,exceptOffered:o}){let s=new Map(e.map(e=>[e.id,e.name]));return i(Ls,{draft:t,onChange:n,exceptOffered:o,plural:`devices`,describe:e=>s.get(e)??J.t(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`rule-device-scope`,renderPicker:(t,n,o)=>i(Ys,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(o===`only`?a.include:a.exclude).length>0},o)})}function Zs(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function Qs(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function $s(e){let t=Zs(e),n=e.data===void 0?[]:Ie(e.data.nodes),r=Qs(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function ec(e){let t=Zs(e),n=e.data===void 0?[]:ae(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var tc=[`nc-pickers`,`node-directory`],nc=[`nc-pickers`,`package-list`],rc=6e4,ic={get hub(){return J.t(`system.scopePickers.roleHub`)},get agent(){return J.t(`system.scopePickers.roleAgents`)}},ac={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 oc(e){let t=ic[e.type??``]??J.t(`system.scopePickers.roleNodes`);return e.location===`offline`?J.t(`system.scopePickers.offlineSuffix`,{role:t}):t}function sc(e){return ac[e.type??``]??J.t(`system.scopePickers.pkgPackages`)}function cc({value:t,onChange:n,testId:r}){let{t:a}=Y(),o=N().trpcClient,c=s({queryKey:tc,staleTime:rc,queryFn:()=>o.nodes.directory.query()}),l=$s(c);return e(`div`,{children:[i(ot,{devices:l.items,listState:l.listState,fleet:l.fleet,value:t,onChange:n,emptyMeansAll:!0,noun:`node`,groupTitle:oc,...r===void 0?{}:{testId:r}}),c.data?.complete===!1&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:a(`system.scopePickers.theNodeHistoryCouldNot`,`The node history could not be read — offline nodes may be missing from this list.`)})]})}function lc({value:e,onChange:t,testId:n}){let r=N().trpcClient,a=ec(s({queryKey:nc,staleTime:rc,queryFn:()=>r.addons.listPackages.query()}));return i(ot,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:sc,...n===void 0?{}:{testId:n}})}var uc={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-consumable-low`]},template:{body:`{{deviceName}}`}};function dc(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 fc(e,t){return e===`pending`?`pending`:e===`success`?`current`:dc(t)===`BAD_REQUEST`?`outdated`:`unknown`}function pc(e){let t=N(),n=s({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(uc)});return e?fc(n.status,n.error):`pending`}c();var mc=`/system/settings`,hc=`/system/notifications?tab=alarm`,gc=`text-primary underline-offset-2 hover:underline`;function _c(e,t){let n=ni(t);return _i(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function vc({family:t,value:r,cameras:a,allDevices:s,fleet:c,savedHadDevices:l,onChange:u,scheduleOnly:d=!1}){let{t:f}=Y(),p=n(()=>r?.kinds??[],[r]),m=n(()=>s===void 0?a:s.map(Js),[s,a]),h=n(()=>a.map(e=>({id:e.id,name:e.name,type:`camera`})),[a]),g=qn(t,p),_=pc(t===`device-events`),v=t===`alarm`,[y,b]=o(()=>oi(r?.deviceIds,r?.excludeDeviceIds)),[x]=o(()=>oi(r?.deviceIds,r?.excludeDeviceIds)),S=n(()=>{let e=new Map;for(let t of v?h:m)e.set(t.id,t.name);return e},[h,v,m]);return e(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[i(`p`,{className:yi,"data-testid":`system-event-class-hint`,children:d?f(`system.notificationSystemEventField.summaryClassHint`,`At the scheduled time you get the list of what is in the bad state, not each change.`):f(`system.notificationSystemEventField.instantClassHint`,`A paired event tells you both when it goes wrong and when it comes back.`)}),di(t).map(n=>e(`div`,{children:[i(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:n.label}),i(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:cn(n,d).map(e=>{let n=mn(p,e),a=e.noSnapshot===!0?`${e.label} — ${f(`system.notificationSystemEventField.noSnapshot`,`no state snapshot, reports nothing`)}`:e.label;return i(U,{variant:`unstyled`,type:`button`,role:`checkbox`,"aria-checked":n,"aria-label":a,onClick:()=>u(dn(r,e,t)),className:n?`rounded-md border border-primary bg-primary/10 px-2 py-1 text-[11px] text-primary`:`rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:a},e.key)})})]},n.id)),t===`device-events`&&e(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-device-alert-settings`,children:[f(`system.notificationSystemEventField.theBatteryThresholdAndThe`,`The battery threshold and the reminder interval are cluster settings (the consumable threshold is this rule’s own, below):`),` `,i(vn,{to:mc,target:`_blank`,rel:`noreferrer`,className:gc,children:f(`system.notificationSystemEventField.settingsBatteryOfflineAlerts`,`Settings → Battery & offline alerts`)}),`.`]}),t===`alarm`&&e(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[i(vn,{to:hc,target:`_blank`,rel:`noreferrer`,className:gc,children:f(`system.notificationSystemEventField.alarmSettings`,`Alarm settings`)}),p.includes(`alarm-triggered`)&&i(`span`,{className:`ml-1`,children:f(`system.notificationSystemEventField.alarmPictures`)})]}),_===`outdated`&&i(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-hub-outdated`,children:f(`system.notificationSystemEventField.hubOutdated`,{percent:15})}),_===`unknown`&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:f(`system.notificationSystemEventField.couldNotCheckWhetherThis`,`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`)}),g.consumableThreshold&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:f(`system.notificationSystemEventField.consumableLowAt`,`Consumable low at (%)`)}),i(K,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:kr,step:1,placeholder:`15`,value:r?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let t=ci(e.target.value);t.kind!==`invalid`&&u(_i(r,{consumableLowPercent:t.kind===`set`?t.value:void 0}))}})]}),g.deviceTypes&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.deviceTypes`,`Device types`)}),i(Xr,{options:Er,value:r?.deviceTypes??[],onChange:e=>u(_i(r,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:f(`system.notificationSystemEventField.deviceType`,`Device type…`)})]}),dr(r)&&i(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`battery-device-types-warning`,children:f(`system.notificationSystemEventField.batteryAndConsumableAlertsAre`,`Battery and consumable alerts are narrowed by device type here. Batteries and consumables belong to sensors, containers, vacuums and mowers — rarely to a camera — so a type filter meant for liveness silences them. Leave the types empty, or put these kinds in a rule of their own.`)}),g.devices&&e(`div`,{children:[i(Ls,{draft:y,onChange:e=>{b(e),u(_c(r,e))},exceptOffered:g.excludeDevices,plural:`devices`,describe:e=>S.get(e)??f(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`system-event-device-scope`,renderPicker:(e,t,n)=>i(ot,{devices:v?h:m,listState:c.state,fleet:c,emptyMeansAll:!0,savedHadDevices:(n===`only`?x.include:x.exclude).length>0||n===`only`&&l,noun:v?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),l&&y.mode===`all`&&i(At,{noun:v?`camera`:`device`})]}),g.nodes&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.nodes`,`Nodes`)}),i(cc,{value:r?.nodeIds??[],onChange:e=>u(_i(r,{nodeIds:e})),testId:`system-event-nodes`})]}),g.packages&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.packages`,`Packages`)}),i(lc,{value:r?.packageNames??[],onChange:e=>u(_i(r,{packageNames:e})),testId:`system-event-packages`})]})]})}function yc({value:t}){let{t:n}=Y(),r=t?.kinds??[];return e(`div`,{className:`mt-1 rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-mixed`,children:[i(`p`,{children:n(`system.notificationSystemEventField.thisRuleIsNotOne`,`This rule is not one kind of system rule — its events span device events, system and alarm, or it names none. It keeps firing as it is, but it cannot be edited here: recreate it as one rule per kind.`)}),r.length>0&&i(`p`,{className:`mt-1 text-foreground`,children:r.map(Xn).join(`, `)})]})}function bc({family:t,onChange:n}){let{t:r}=Y();return e(`div`,{"data-testid":`system-family-select`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:r(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`)}),i(P,{value:t,"aria-label":r(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`),onChange:e=>{let t=e.target.value;pe(t)&&n(t)},options:be.map(e=>({value:e,label:ue(e).label}))}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:r(`system.notificationSystemEventField.oneRuleAnswersOneQuestion`,`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`)})]})}c();function xc({catalog:t,taxonomy:r,delivery:a,conditions:o,classScope:s,onClassScopeChange:c,actions:l,actionStepsOf:u,savedConditions:d,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x,scheduleOnly:S}){let{t:C}=Y(),w=(e,t)=>{let n={...o};t===void 0?delete n[e]:n[e]=t,b(n)},T=fe({delivery:a,conditions:o}),E=n(()=>t.filter(e=>Ke(e,a,T)&&En(e.id,o)),[t,a,T,o]),D=n(()=>Os(E),[E]),O=e=>E.some(t=>t.id===e),k=e=>Cc.has(e.id)?i(qs,{taxonomy:r,scope:s,onChange:c,exceptOffered:O(`classesExclude`)}):wc.has(e.id)?i(Hs,{conditions:o,onConditionsChange:b,exceptOffered:O(`zonesExclude`),cameraIds:m??p,cameras:h}):Tc.has(e.id)?i(Us,{conditions:o,onConditionsChange:b,exceptOffered:O(`identitiesExclude`)}):e.id===`labelEquals`?i(Ws,{conditions:o,onConditionsChange:b}):null;return i(`div`,{className:`space-y-4`,children:D.map(t=>e(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${t.id}`,children:[i(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:C(`notificationRules.groups.${t.id}`,t.label)}),t.descriptors.map(t=>{let n=k(t);return e(`div`,{"data-testid":`condition-${t.id}`,children:[i(`label`,{className:X,children:Ec(t,C)}),n??i(kc,{descriptor:t,kind:T,scheduleOnly:S===!0,taxonomy:r,conditions:o,actions:l,actionStepsOf:u,savedConditions:d,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:w,onScheduleChange:x}),Dc(t,C)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Dc(t,C)})]},t.id)})]},t.id))})}function Sc({kinds:t}){let{t:n,i18n:r}=Y(),a=r.language.startsWith(`it`)?`it`:`en`,o=t.flatMap(e=>{let t=Oe(e);return t===void 0?[]:[{kind:e,text:n(`system.notificationRuleConditions.transitionMeaning`,`{{kind}}: starts = {{starts}} · finishes = {{finishes}}`,{kind:ce(e,a),starts:t.starts[a],finishes:t.finishes[a],interpolation:{escapeValue:!1}})}]});return o.length===0?null:e(kt,{className:`inline-block`,children:[i(Ht,{tabIndex:0,children:i(y,{className:`h-4 w-4 cursor-help text-foreground-subtle`,"aria-label":n(`system.notificationRuleConditions.transitionInfo`,`What start and finish mean`),"data-testid":`nc-sensor-transition-info`})}),i(jt,{className:`left-auto right-0 translate-x-0`,children:i(`ul`,{className:`w-60 space-y-1 whitespace-normal text-left text-[11px]`,children:o.map(e=>i(`li`,{children:e.text},e.kind))})})]})}var Cc=new Set([`classes`,`classesExclude`]),wc=new Set([`zones`,`zonesExclude`]),Tc=new Set([`identities`,`identitiesExclude`]);function Ec(e,t){return Cc.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):wc.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):Tc.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 Dc(e,t){if(!Oc.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.id===`schedule`?t(`notificationRules.schedule.hint`,`Only fire inside these weekly windows. Leave it empty to fire at any time.`):e.description}var Oc=new Set([...Cc,...wc,...Tc,`labelEquals`,`crossing`]);function kc({descriptor:t,kind:n,taxonomy:r,conditions:a,actions:o,actionStepsOf:s,savedConditions:c,schedule:l,deviceIds:u,cameras:d,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v,scheduleOnly:y}){let{t:b}=Y();switch(t.valueType){case`deviceIdList`:{if(!li(t.id))break;let e=t.id,n=a[e]??[];return i(Or,{cameras:d,fleet:p,emptyMeansAll:!0,savedHadDevices:(c?.[e]?.length??0)>0,value:n,onChange:t=>_(e,t.length>0?t:void 0)})}case`stringList`:{if(!Ln(t.id))break;let e=t.id,n=t=>_(e,t.length>0?t:void 0);if(e===`eventTypeTokens`)return i(ui,{deviceIds:u,value:Fr(a,e),onChange:n});let o=L(e,r);return o===null?i(Qn,{value:Fr(a,e),placeholder:b(`system.notificationRuleConditions.addValue`,`Add value…`),onChange:n}):i(gn,{picker:o,value:Fr(a,e),onChange:n})}case`number01`:{if(!_r(t.id))break;let e=t.id;return i(gi,{value:tn(a,e),min:0,max:1,step:.05,onChange:t=>_(e,t)})}case`number`:{if(!hi(t.id))break;let e=t.id;return i(gi,{value:tn(a,e),min:0,step:1,onChange:t=>_(e,t)})}case`sourceSelect`:{if(!fn(t.id))break;let e=t.id;return Pc(t,a[e],t=>_(e,t))}case`systemEvent`:{if(!Rr(t.id))break;let e=t.id,r=oe(n);return r===void 0?i(yc,{value:a[e]}):i(vc,{family:r,value:a[e],cameras:d,fleet:p,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[e]?.deviceIds?.length??0)>0,onChange:t=>_(e,t),scheduleOnly:y===!0})}case`deviceState`:if(!vi(t.id))break;return i(pr,{gateable:h,value:a.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!Zn(t.id))break;return i(pi,{scenes:g,value:a.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!fr(t.id))break;let e=t.id;return Fc(t,a[e],t=>_(e,t))}case`packagePhase`:{if(!ln(t.id))break;let e=t.id;return i(P,{value:a[e]??``,options:[{value:``,label:b(`system.notificationRuleConditions.anyPhase`,`— any phase —`)},...Hn(t,$n).map(e=>({value:e.value,label:e.label}))],onChange:t=>_(e,Nc(t.target.value))})}case`sensorTransition`:{if(!hn(t.id))break;let n=t.id,r=Me({conditions:a,...o===void 0?{}:{actions:o},...s===void 0?{}:{actionStepsOf:s}});return e(f,{children:[e(`div`,{className:`flex items-center gap-2`,children:[i(P,{value:a[n]??``,options:Hn(t,On).map(e=>({value:e.value,label:e.label})),onChange:e=>_(n,xr(e.target.value))}),i(Sc,{kinds:a.sensorKinds??[]})]}),r&&i(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`nc-sensor-transition-never-fires`,children:`This rule belongs to the alarm, and an alarm rule fires only when an opening OPENS. Set to “only when it clears”, it can never fire.`})]})}case`plateMatcher`:{if(!fi(t.id))break;let e=t.id;return i(un,{value:a[e],onChange:t=>_(e,t)})}case`occupancy`:{if(!Jn(t.id))break;let e=t.id;return i(Yn,{deviceIds:u,cameras:d,classOptions:Ac(r),value:a[e],onChange:t=>_(e,t)})}case`audio`:{if(!Dr(t.id))break;let e=t.id;return i(Wr,{taxonomy:r,value:a[e],onChange:t=>_(e,t)})}case`schedule`:return i(Zr,{value:l,onChange:v});default:break}return i(jc,{descriptor:t,conditions:a})}function Ac(e){let t=L(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function jc({descriptor:t,conditions:n}){let{t:r}=Y(),i=Object.entries(n).find(([e])=>e===t.id);return e(`p`,{className:yi,children:[i!==void 0&&i[1]!==void 0?r(`system.notificationRuleConditions.authoredElsewhereAndPreservedThis`,`Authored elsewhere and preserved — this admin editor cannot change it yet.`):r(`system.notificationRuleConditions.notEditableHereYetThis`,`Not editable here yet — this condition has no admin editor.`),` `,e(`span`,{className:`text-foreground-muted`,children:[`(`,t.valueType,`)`]})]})}function Mc(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Nc(e){return $n.find(t=>t.value===e)?.value}function Pc(e,t,n){return i(P,{value:t??`any`,options:Hn(e,Qr).map(e=>({value:e.value,label:e.label})),onChange:e=>n(Mc(e.target.value))})}function Fc(e,t,n){return i(jr,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function Ic({catalog:t,delivery:n,conditions:r,onConditionsChange:a}){let{t:o}=Y(),s=fe({delivery:n,conditions:r}),c=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,a(n)},l=e=>t.find(t=>t.id===e&&Ke(t,n,s)&&En(e,r)),u=l(`source`),d=l(`crossing`);return u===void 0&&d===void 0?null:e(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[u&&fn(u.id)&&e(`div`,{"data-testid":`condition-source`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Ec(u,o)}),Pc(u,r.source,e=>c(`source`,e)),Dc(u,o)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Dc(u,o)})]}),d&&fr(d.id)&&e(`div`,{"data-testid":`condition-crossing`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Ec(d,o)}),Fc(d,r.crossing,e=>c(`crossing`,e)),Dc(d,o)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Dc(d,o)})]})]})}var Lc=[`notificationRules`,`getRuleLastRuns`],Rc=3e4;function zc(){let e=N(),t=s({queryKey:Lc,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:Rc});return{status:t.status,data:t.data,error:t.error}}var Bc={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function Vc({cell:t}){let{t:n}=Y();switch(t.kind){case`pending`:return i(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":n(`system.notificationRuleLastRun.lastRunLoading`,`Last run loading`),className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return i(`span`,{"data-testid":`rule-last-run-failed`,title:n(`system.notificationRuleLastRun.lastRunCouldNotBe`,`Last run could not be read: {{reason}}`,{reason:t.reason}),className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.phrase});case`ran`:return e(`span`,{className:`flex items-center gap-1.5`,title:new Date(t.lastAt).toLocaleString(),children:[i(`span`,{"data-testid":`rule-last-run-dot`,title:t.status,className:`inline-block h-2 w-2 rounded-full ${Bc[t.status]}`}),i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Ci(t.lastAt)})]})}}function Hc({rule:e,onOpenHistory:t}){let{t:n}=Y();return i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t(e),title:n(`system.notificationRuleLastRun.historyThisRuleSDeliveries`,`History — this rule's deliveries`),"aria-label":n(`system.notificationRuleLastRun.historyOf`,`history of {{name}}`,{name:e.name}),children:i(w,{className:`h-3.5 w-3.5`})})}c();var Uc=[`notificationRules`,`listSnoozes`],Wc=[10,30,60,120];function Gc({ruleId:t,ruleName:n,exempt:r=!1,variant:a=`icon`}){let{t:s}=Y(),c=N(),u=l(),[f,p]=o(30),[m,h]=o(null),g=d({mutationFn:e=>c.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:t,durationMinutes:e}}),onMutate:()=>h(null),onSuccess:()=>u.invalidateQueries({queryKey:Uc}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?a===`icon`?null:i(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`system.notificationRuleSnoozeControl.thisRuleConcernsOrTriggers`,`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`)}):a===`icon`?i(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:s(`system.notificationRuleSnoozeControl.silenceThisRuleForIt`,`Silence this rule for {{value1}} — it appears under "Silenced right now"`,{value1:or(30)}),"aria-label":s(`system.notificationRuleSnoozeControl.snooze`,`snooze {{ruleName}}`,{ruleName:n}),"data-testid":`nc-rule-snooze-now`,children:g.isPending?i(T,{className:`h-3.5 w-3.5 animate-spin`}):i(et,{className:`h-3.5 w-3.5`})}):e(`div`,{className:`space-y-1`,children:[e(`div`,{className:`flex items-end gap-2`,children:[i(`div`,{className:`w-32`,children:i(P,{value:String(f),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:Wc.map(e=>({value:String(e),label:or(e)}))})}),e(U,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(f),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?i(T,{className:`h-3.5 w-3.5 animate-spin`}):i(et,{className:`h-3.5 w-3.5`}),s(`system.notificationRuleSnoozeControl.silenceThisRuleNow`,`Silence this rule now`)]})]}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`system.notificationRuleSnoozeControl.opensARealSnoozeWindow`,`Opens a real snooze window right now — distinct from the buttons above, which only choose the durations this rule's NOTIFICATION offers. It appears under "Silenced right now" and can be ended from there.`)}),m!==null&&i(`p`,{className:`text-[10px] text-danger`,children:m})]})}c();function Kc(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function qc(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 Jc(e,t){let[,n]=o(0);a(()=>{let r=qc(e,t,Date.now());if(r===null)return;let i=setTimeout(()=>n(e=>e+1),Math.max(0,r-Date.now())+50);return()=>clearTimeout(i)},[e,t])}function Yc(){let e=N();return s({queryKey:Uc,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function Xc({rule:t,snoozes:n,exempt:r}){let{t:a}=Y(),o=N(),s=l();Jc(n,t.id);let c=Kc(n,t.id,Date.now()),u=()=>s.invalidateQueries({queryKey:Uc}),f=d({mutationFn:()=>o.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:t.id,durationMinutes:30}}),onSuccess:u}),p=d({mutationFn:async e=>{for(let t of e)await o.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:u});if(r)return null;let m=f.isError||p.isError;return e(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[i(q,{checked:c.length>0,disabled:!t.enabled||f.isPending||p.isPending,onCheckedChange:e=>e?f.mutate():p.mutate(c),"aria-label":a(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,t.name),title:a(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),m&&i(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:a(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var Zc=`nc.listPrunes`;function Qc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var $c=new Set([`rule`,`timelapse`,`summary`]),el=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function tl(e){return typeof e==`string`&&$c.has(e)}function nl(e){return typeof e==`string`&&el.has(e)}function rl(e){return e===`device`||e===`target`}function il(e){if(!Qc(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!tl(t)||!rl(r)||!nl(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 al(e){return!Qc(e)||!Array.isArray(e.prunes)?null:e.prunes.map(il).filter(e=>e!==null)}function ol(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 sl(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 cl(e){return new Date(e).toLocaleDateString()}function ll({kind:t,ruleId:n,enabled:r,updatedAt:a}){let o=N(),c=s({queryKey:[`pipelineAnalytics`,Zc],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>al(await o.trpcClient.addons.custom.mutate({addonId:Mi,action:Zc,input:{}}))}).data;if(c==null)return null;let l=ol(c,t,n,r,a);return l===null?null:e(`div`,{"data-testid":`nc-prune-banner`,className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-foreground`,children:[i(y,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),i(`span`,{children:sl(l,cl)})]})}var ul=5e3;function dl({status:t,now:n,name:r}){let{t:a}=Y();if(t.openWindows===null)return e(`p`,{className:`flex items-start gap-1.5`,children:[i(p,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),i(`span`,{"data-testid":`nc-grouped-status-headline`,children:a(`notificationRules.status.grouped.unknown`,{reason:t.reason??``,defaultValue:`Open windows unknown — {{reason}}`})})]});let o=t.openWindows,{windows:s,waiting:c}=Di(o);return e(f,{children:[e(`p`,{className:`flex items-start gap-1.5`,children:[i(p,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),i(`span`,{"data-testid":`nc-grouped-status-headline`,children:s===0?a(`notificationRules.status.grouped.none`,`No window open`):`${a(`notificationRules.status.grouped.windows`,{count:s,defaultValue_one:`{{count}} open window`,defaultValue_other:`{{count}} open windows`})} · ${a(`notificationRules.status.grouped.waiting`,{count:c,defaultValue:`{{count}} waiting`})}`})]}),o.map(t=>e(`p`,{className:`flex items-start gap-1.5`,children:[i(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),i(`span`,{children:a(`notificationRules.status.grouped.windowLine`,{camera:r(t.deviceId),members:t.members,pending:t.pending,seconds:Math.max(0,Math.ceil((t.closesAt-n)/1e3)),defaultValue:`{{camera}} · {{members}} in the window · {{pending}} waiting · closes within {{seconds}} s`})})]},t.windowKey))]})}function fl({ruleId:t,cameraName:n}){let{t:r}=Y(),a=N(),o=s({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,t],refetchInterval:ul,queryFn:async()=>ji(await a.trpcClient.addons.custom.mutate({addonId:Mi,action:Oi,input:{ruleId:t}}))}).data;if(o==null||o.kind===`none`)return null;let c=Date.now(),l=e=>n?.(e)??r(`system.notificationRuleStatus.cameraFallback`,{deviceId:e});return e(`div`,{"data-testid":`nc-rule-status`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[o.kind===`occupancy`&&e(`p`,{className:`flex items-start gap-1.5`,children:[o.unavailable!==void 0||o.warning!==void 0?i(v,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):i(p,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),e(`span`,{children:[i(`span`,{className:`text-foreground`,children:l(o.deviceId)}),` —`,` `,ki(o,c)]})]}),o.kind===`grouped`&&i(dl,{status:o,now:c,name:l}),o.kind===`timelapse`&&e(f,{children:[o.devices.map(t=>e(`p`,{className:`flex items-start gap-1.5`,children:[i(p,{className:`mt-0.5 h-3 w-3 shrink-0 ${t.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),e(`span`,{children:[Ei(t,l(t.deviceId),c),t.lastArtifact!==void 0&&e(f,{children:[` · `,i(`a`,{className:`text-primary hover:underline`,href:`/${t.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:r(`common.open`)})]})]})]},t.deviceId)),e(`p`,{className:`flex items-start gap-1.5`,children:[i(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),e(`span`,{children:[o.nextWindow===void 0?r(`system.notificationRuleStatus.noFurtherWindowOpensIn`,`No further window opens in the next nine days`):r(`system.notificationRuleStatus.nextWindowOpens`,`Next window opens {{value1}}`,{value1:new Date(o.nextWindow.startMs).toLocaleString()}),o.settleMs>0&&` · ${r(`system.notificationRuleStatus.settled`,{minutes:Math.round(o.settleMs/6e4)})}`]})]})]})]})}function pl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ml(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function hl(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function gl(e){if(!pl(e))return null;let t=ml(e,`ruleId`),n=ml(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=ml(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:ml(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:hl(e,`targetIds`)}}function _l(e){if(!pl(e))return null;let t=ml(e,`conditionId`),n=ml(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function vl(e){if(!pl(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(!pl(t))continue;let e=ml(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(!pl(t))continue;let e=ml(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 yl(e){if(!pl(e))return null;let t=ml(e,`recordId`),n=ml(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=gl(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=_l(t);e!==null&&i.push(e)}let a=ml(e,`droppedBy`),o=vl(e.stateSummary);return{recordId:t,delivery:n,trigger:ml(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:ml(e,`still`)??`none`,notes:hl(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function bl(e){if(e.stateSummary!==void 0)return xl(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 xl(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})}c();function Sl({ruleId:t,ruleName:n,fallbackDeviceId:r,variant:a=`icon`,showResult:s=!1,summary:c=!1}){let{t:l}=Y(),u=N(),[p,m]=o(null),[h,g]=o(null),_=d({mutationFn:async()=>yl(await u.trpcClient.addons.custom.mutate({addonId:Mi,action:Ai,input:{ruleId:t,...c?{summary:!0}:{},...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{m(null),g(null)},onSuccess:e=>m(e),onError:e=>g(e instanceof Error?e.message:`The test could not be run.`)}),y=p===null?h===null?void 0:h:bl(p);return e(f,{children:[e(U,{size:`sm`,variant:a===`icon`?`ghost`:`outline`,type:`button`,disabled:_.isPending,onClick:()=>_.mutate(),title:y??(c?l(`system.notificationRuleTestButton.sendSummaryTitle`,`Sends this rule’s state summary now, to every target`):l(`system.notificationRuleTestButton.testNowFiresThisRule`,`Test now — fires this rule and really sends the notification`)),"aria-label":c?l(`system.notificationRuleTestButton.sendSummaryAria`,`send the summary of {{ruleName}} now`,{ruleName:n}):l(`system.notificationRuleTestButton.testNow`,`test {{ruleName}} now`,{ruleName:n}),"data-testid":c?`nc-rule-test-summary`:`nc-rule-test-now`,children:[_.isPending?i(T,{className:`h-3.5 w-3.5 animate-spin`}):i(rt,{className:`h-3.5 w-3.5`}),a===`full`&&(c?l(`system.notificationRuleTestButton.sendSummaryNow`,`Send the summary now`):l(`system.notificationRuleTestButton.testNow2`,`Test now`))]}),s&&h!==null&&i(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:h}),s&&p!==null&&e(`div`,{"data-testid":`nc-rule-test-result`,className:`mt-2 space-y-1 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[i(`p`,{className:`text-foreground`,children:bl(p)}),p.planNotes.map(t=>e(`p`,{className:`flex gap-1.5`,children:[i(v,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),i(`span`,{children:t.note})]},t.conditionId)),p.notes.map(t=>e(`p`,{children:[`· `,t]},t))]})]})}c();var Cl=[`notificationRules`,`listSnoozes`],wl=3e4;function Tl(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function El(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 Dl({rules:t}){let{t:r}=Y(),a=N(),o=l(),c=s({queryKey:Cl,refetchInterval:wl,queryFn:async()=>(await a.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),u=d({mutationFn:e=>a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>o.invalidateQueries({queryKey:Cl})}),f=n(()=>{let e=new Map;for(let n of t)e.set(n.id,n.name);return e},[t]),p=Date.now(),m=(c.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return e(ct,{className:`p-4`,children:[e(`div`,{className:`flex items-center gap-2 mb-3`,children:[i(et,{className:`h-4 w-4 text-foreground-subtle`}),i(`h3`,{className:`text-sm font-medium text-foreground`,children:r(`system.notificationSnoozes.silencedRightNow`,`Silenced right now`)})]}),m.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`system.notificationSnoozes.nothingIsSilencedASnooze`,`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`)}),i(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:m.map(t=>e(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`text-xs text-foreground truncate`,children:t.scope===`all`?`Everything`:t.scope===`device`?`Camera ${t.deviceId??`?`}`:f.get(t.ruleId??``)??`A rule`}),t.global&&i(H,{variant:`warning`,className:`text-[10px]`,children:r(`common.everyone`)}),t.classes!==void 0&&t.classes.length>0&&i(H,{variant:`info`,className:`text-[10px]`,children:t.classes.join(`, `)}),!t.summary&&i(H,{variant:`default`,className:`text-[10px]`,children:r(`system.notificationSnoozes.noSummary`,`no summary`)})]}),i(`span`,{className:`text-[10px] text-foreground-subtle`,children:r(`system.notificationSnoozes.setBy`,{user:t.userId,remaining:El(Tl(t,p))})})]}),i(U,{size:`sm`,variant:`outline`,disabled:u.isPending,onClick:()=>u.mutate(t.id),children:r(`system.notificationSnoozes.endNow`,`End now`)})]},t.id))})]})}var Z=`block text-[11px] font-medium text-foreground mb-1`,Ol=`mt-1 text-[10px] text-foreground-subtle`;function Q({title:t,hint:n,children:r}){return e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:t}),n!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:n}),i(`div`,{className:`space-y-3`,children:r})]})}function kl({problems:t,testId:n=`digest-problems`}){let{t:r}=Y();return t.length===0?null:e(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":n,children:[e(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[i(v,{className:`h-3.5 w-3.5`}),r(`system.notificationDigestFields.thisRuleCouldNeverProduce`,`This rule could never produce anything, so it cannot be saved:`)]}),i(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:t.map(e=>i(`li`,{children:e},e))})]})}function Al({warnings:t,testId:n=`digest-warnings`}){let{t:r}=Y();return t.length===0?null:e(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":n,children:[e(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[i(y,{className:`h-3.5 w-3.5`}),r(`system.notificationDigestFields.worthKnowing`,`Worth knowing:`)]}),i(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:t.map(e=>i(`li`,{children:e},e))})]})}function jl({cameras:t,value:n,onChange:r,fleet:a,hint:o}){return e(`div`,{className:`space-y-1`,children:[i(ot,{devices:t,listState:a.state,fleet:a,value:n,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),o!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:o})]})}function Ml(e){let{t}=Y();return i(lt,{...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 Nl({label:t,value:n,onChange:r,min:a,max:o,step:s,hint:c,emptyPlaceholder:l,testId:u,disabled:d=!1}){return e(`div`,{children:[i(`label`,{className:Z,children:t}),i(K,{type:`number`,value:n===void 0?``:String(n),disabled:d,...a===void 0?{}:{min:a},...o===void 0?{}:{max:o},...s===void 0?{}:{step:s},...l===void 0?{}:{placeholder:l},...u===void 0?{}:{"data-testid":u},onChange:e=>{let t=e.target.value.trim();if(t.length===0){r(void 0);return}let n=Number(t);Number.isFinite(n)&&r(n)}}),c!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:c})]})}function Pl({label:t,checked:n,onChange:r,hint:a,testId:o}){return e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(q,{checked:n,onCheckedChange:r,"aria-label":t,...o===void 0?{}:{"data-testid":o}}),t]}),a!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function Fl({title:t,body:n,onTitleChange:r,onBodyChange:a,family:o,testIdPrefix:s}){let{t:c}=Y(),l=Zo(),u=e=>l.data?qo(l.data,{family:o,field:e}):void 0;return e(`div`,{className:`space-y-2`,children:[i(ts,{label:c(`system.notificationDigestFields.notificationTitle`,`Notification title`),value:t,onChange:r,vars:u(`title`),testId:`${s}-title`}),i(ts,{label:c(`system.notificationDigestFields.notificationBody`,`Notification body`),value:n,onChange:a,vars:u(`body`),multiline:!0,testId:`${s}-body`}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`system.notificationDigestFields.leaveBothBlankToUse`,`Leave both blank to use the hub's own wording (editable on the Texts tab).`)}),i(ns,{context:{family:o,field:`body`},title:t,body:n,testId:`${s}-preview`})]})}function Il({open:t,ruleName:n,windowDescription:r,targetDescription:a,pending:o,onConfirm:s,onCancel:c,extra:l,confirmDisabled:u=!1}){let{t:d}=Y();return t?i(xt,{open:!0,onOpenChange:e=>!e&&c(),children:i(ht,{width:`sm`,children:e(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[i(rt,{className:`h-4 w-4 text-warning`}),d(`system.notificationDigestFields.sendARealNotificationNow`,`Send a real notification now?`)]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:d(`system.notificationDigestFields.confirmSend`,{rule:n,window:r,target:a})}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:d(`system.notificationDigestFields.itDoesNotConsumeThe`,`It does not consume the schedule: the next scheduled run still happens.`)}),l,e(`div`,{className:`flex justify-end gap-2`,children:[i(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:d(`common.cancel`,`Cancel`)}),i(U,{size:`sm`,type:`button`,disabled:o||u,onClick:s,"data-testid":`digest-test-confirm-send`,children:o?d(`system.notificationDigestFields.sending`,`Sending…`):d(`system.notificationDigestFields.produceAndSend`,`Produce and send`)})]})]})})}):null}function Ll(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 Rl=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function zl(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function 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=>Rl[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${zl(t.startMinute)}–${zl(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function Vl(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:Ll(Math.round(r/1e3))})}function Hl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ul(e){return Array.isArray(e)?`[${e.map(Ul).join(`,`)}]`:Hl(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${Ul(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function Wl(e,t){return Ul(e)===Ul(t)}function Gl(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,Kl=`nc.getTexts`,ql=`nc.setLanguage`,Jl=`nc.setTextOverrides`,Yl={en:`English`,it:`Italiano`};function Xl(e){return e===`en`||e===`it`}function Zl(e){return e===`override`||e===`shipped`||e===`fallback`}function Ql(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $l(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 eu(e){if(!Ql(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`||!Xl(r)||!Zl(o)||i!==null&&typeof i!=`string`)return null;let s=$l(e.placeholders),c=$l(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 tu(e){if(!Ql(e))return null;let{language:t,activeLanguage:n}=e;if(!Xl(t)||!Xl(n))return null;let r=$l(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Xl(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=eu(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function nu(e,t){return t.get(e.key)??e.override??e.shipped}function ru(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 iu(e,t){return Object.keys(ru(e,t)).length}function au(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 ou(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function su(e){return e.pluralCategories.length===0?null:J.t(`helpers.notificationTexts.pluralWarning`,{categories:e.pluralCategories.join(`, `)})}var cu=[`notificationCalendarEvents`,`list`],lu=`nc.listCalendarEventsRules`,uu=`nc.upsertCalendarEventsRule`,du=`nc.deleteCalendarEventsRule`,fu=Xe({timezone:Ye().min(1),windows:Qe(Xe({days:Qe(qe().int().min(0).max(6)).min(1),startMinute:qe().int().min(0).max(1439),endMinute:qe().int().min(0).max(1439)})).min(1),invert:$e().optional()}),pu=Xe({targetId:Ye().min(1),params:Ze(Ye(),Je()).optional()}),mu=Xe({rules:Qe(Xe({id:Ye().min(1),name:Ye().min(1),enabled:$e(),schedule:fu,calendars:Qe(Ye().min(1)).max(64).optional(),calendarsExclude:Qe(Ye().min(1)).max(64).optional(),horizonDays:qe().int(),deliverEmpty:$e(),targets:Qe(pu).min(1),template:Xe({title:Ye().optional(),body:Ye().optional()}).optional(),priority:qe().int(),generatedAt:qe().optional(),readOnly:$e().optional()}))});function hu(e){let t=mu.safeParse(e);return t.success?t.data.rules:null}function gu(e){return e.readOnly!==!0}var _u=[{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`)}}],vu=`basics`;function yu(){return Se([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function bu(e){let t=z(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 xu(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:yu(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``}}function Su(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 Cu(e){return e.name.trim().length>0&&e.targetIds.length>0&&e.horizonDays>=1&&e.horizonDays<=30&&e.schedule.windows.length>0}function wu(e){let t=e.targetIds.map(e=>({targetId:e}));return{name:e.name.trim(),enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,...e.calendars.length>0?{calendars:[...e.calendars]}:{},...e.calendarsExclude.length>0&&e.calendars.length===0?{calendarsExclude:[...e.calendarsExclude]}:{},targets:t,...e.templateTitle.trim().length>0||e.templateBody.trim().length>0?{template:{...e.templateTitle.trim().length>0?{title:e.templateTitle.trim()}:{},...e.templateBody.trim().length>0?{body:e.templateBody.trim()}:{}}}:{}}}function Tu(e,t){let n=wu(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 Eu(e){return J.t(`helpers.notificationCalendarEvents.horizon`,{count:e})}function Du(e){return e.calendars!==void 0&&e.calendars.length>0?J.t(`helpers.notificationCalendarEvents.calendars`,{count:e.calendars.length}):e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?J.t(`helpers.notificationCalendarEvents.allExcept`,{count:e.calendarsExclude.length}):J.t(`helpers.notificationCalendarEvents.allCalendars`)}c();function Ou({rule:t,targets:n,onSaved:r,onCancel:a}){let{t:s}=Y(),c=N(),l=zt(),[u,f]=o(()=>t===null?xu():Su(t)),[p,m]=o(()=>oi(t===null?void 0:t.calendars,t===null?void 0:t.calendarsExclude)),[h,g]=o(vu),[_,v]=o(null),y=e=>f(t=>({...t,...e})),b=d({mutationFn:async()=>{let e=ni(p),n={...u,calendars:e.include??[],calendarsExclude:e.exclude??[]};if(!Cu(n))throw Error(`Name, at least one target, and a schedule are required`);let r=t===null?{rule:wu(n)}:{ruleId:t.id,patch:Tu(n,t)};await c.trpcClient.addons.custom.mutate({addonId:$,action:uu,input:r})},onSuccess:()=>r(),onError:e=>{v(e instanceof Error?e.message:String(e))}}),x=(l.data??[]).map(e=>({id:e.id,name:e.name}));return i(xt,{open:!0,onOpenChange:e=>!e&&a(),children:e(ht,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendar-events-editor`,children:[e(`div`,{className:`mb-3 flex shrink-0 items-center justify-between gap-2 pr-10`,children:[e(`div`,{className:`flex min-w-0 items-center gap-2`,children:[i(tt,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:t===null?s(`system.notificationCalendarEventsEditor.newCalendarEvents`,`New calendar events`):u.name})]}),i(U,{size:`sm`,type:`button`,disabled:b.isPending,onClick:()=>{v(null),b.mutateAsync()},"data-testid":`calendar-events-save`,children:b.isPending?i(T,{className:`h-3.5 w-3.5 animate-spin`}):s(`common.save`,`Save`)})]}),e(Jt,{value:h,onValueChange:e=>{let t=_u.find(t=>t.key===e);t!==void 0&&g(t.key)},children:[i(Mt,{className:`mb-3`,children:_u.map(e=>i(Ut,{value:e.key,children:e.label},e.key))}),e(ft,{className:`space-y-4 pr-1`,children:[_===null?null:i(`p`,{className:`text-sm text-destructive`,children:_}),i(W,{value:`basics`,className:`space-y-3`,children:e(Q,{title:s(`system.notificationCalendarEventsEditor.basics`,`Basics`),children:[e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.name`,`Name`),i(K,{className:`mt-1`,value:u.name,onChange:e=>y({name:e.target.value}),"data-testid":`calendar-events-name`})]}),i(Nl,{label:s(`system.notificationCalendarEventsEditor.horizonDays`,`Horizon (days)`),value:u.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&y({horizonDays:e})}}),i(Nl,{label:s(`system.notificationCalendarEventsEditor.priority`,`Priority`),value:u.priority,min:1,max:5,onChange:e=>{e!==void 0&&y({priority:e})}}),i(Pl,{label:s(`system.notificationCalendarEventsEditor.enabled`,`Enabled`),checked:u.enabled,onChange:e=>y({enabled:e})}),i(Pl,{label:s(`system.notificationCalendarEventsEditor.deliverWhenEmpty`,`Deliver when empty`),checked:u.deliverEmpty,onChange:e=>y({deliverEmpty:e})})]})}),i(W,{value:`schedule`,className:`space-y-3`,children:e(Q,{title:s(`system.notificationCalendarEventsEditor.schedule`,`Schedule`),children:[i(Zr,{mode:`times`,value:u.schedule,onChange:e=>y({schedule:e})}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:s(`system.notificationCalendarEventsEditor.oneSendTimePerRow`,`One send time per row. The digest fires at that minute.`)})]})}),i(W,{value:`calendars`,className:`space-y-3`,children:i(Q,{title:s(`system.notificationCalendarEventsEditor.calendars`,`Calendars`),children:i(Ls,{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)=>i(ot,{devices:x,listState:l.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),i(W,{value:`targets`,className:`space-y-3`,children:i(Q,{title:s(`system.notificationCalendarEventsEditor.targets`,`Targets`),children:i(Ml,{targets:n,value:u.targetIds,onChange:e=>y({targetIds:e})})})}),i(W,{value:`template`,className:`space-y-3`,children:e(Q,{title:s(`system.notificationCalendarEventsEditor.template`,`Template`),children:[e(`p`,{className:`text-[11px] text-foreground-subtle`,children:[s(`system.notificationCalendarEventsEditor.optionalLeaveBlankForThe`,`Optional. Leave blank for the default digest body (tomorrow highlighted, then later days). Variables:`),` `,s(`system.notificationCalendarEventsEditor.templateVars`,{ruleVar:`{{rule}}`,countVar:`{{count}}`,horizonVar:`{{horizonDays}}`,eventsVar:`{{events}}`})]}),e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.title`,`Title`),i(K,{className:`mt-1`,value:u.templateTitle,onChange:e=>y({templateTitle:e.target.value})})]}),e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.body`,`Body`),i(Yt,{className:`mt-1 min-h-[8rem] w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:u.templateBody,onChange:e=>y({templateBody:e.target.value})})]})]})})]})]})]})})}var ku=`nc.listSummaryRules`,Au=`nc.upsertSummaryRule`,ju=`nc.deleteSummaryRule`,Mu=`nc.testSummaryRule`,Nu=3600,Pu=86400,Fu=3600,Iu=3600,Lu=3*36e5,Ru=[`importance`,`recency`,`dwell`],zu={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},Bu=[`none`,`tiles`,`all`],Vu=`none`,Hu={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},Uu=[`en`,`it`],Wu=[`deliver-without-text`,`skip`],Gu=2048,Ku=2e3;function qu(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Ju(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yu(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 Xu(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 Zu(e){if(e!==void 0)return typeof e==`string`?e:null}function Qu(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function $u(e){return Ru.some(t=>t===e)}function ed(e){return e===void 0?Vu:Bu.find(t=>t===e)??null}function td(e){if(!Ju(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Ju(n))return null;let e=Yu(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=Zu(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 nd(e){if(!Ju(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=td(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 rd(e){if(e==null)return;if(!Ju(e))return null;let t=e.classes===void 0?void 0:Xu(e.classes),n=e.classesExclude===void 0?void 0:Xu(e.classesExclude),r=e.zones===void 0?void 0:Xu(e.zones);if(t===null||n===null||r===null)return null;let i=Qu(e.minImportance),a=Qu(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 id(e){if(e==null)return;if(!Ju(e))return null;let t=Zu(e.title),n=Zu(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function ad(e){return Uu.some(t=>t===e)}function od(e){return Wu.some(t=>t===e)}function sd(e){if(e==null)return;if(!Ju(e)||typeof e.enabled!=`boolean`)return null;let t=Zu(e.profileId),n=Zu(e.prompt);if(t===null||n===null)return null;let r=Qu(e.maxImagePx),i=Qu(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!ad(a))return null;let o=e.onFailure;return o!==void 0&&!od(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 cd(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Ju(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Ju(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function ld(e){if(!Ju(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`||!$u(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Yu(e.deviceIds),u=nd(e.window),d=cd(e.targets);if(l===null||u===null||d===null)return null;let f=rd(e.filters),p=id(e.template);if(f===null||p===null)return null;let m=Zu(e.captionText),h=Qu(e.generatedAt),g=Qu(e.updatedAt);if(m===null||h===null||g===null)return null;let _=ed(e.captions);if(_===null)return null;let v=sd(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 ud(e){if(!Ju(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=ld(n);if(e===null)return null;t.push(e)}return t}function dd(e){if(!Ju(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=Qu(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=Qu(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Zu(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 fd(){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:Vu,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function pd(e){let t=fd(),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 md(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function hd(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 gd(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 _d(e){return Gl(e.targetIds)}function vd(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 yd(e){let t=hd(e),n=gd(e),r=vd(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:md(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:_d(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 bd(e,t){let n=yd(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 xd(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 ${Nu}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${Pu}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 ${Fu}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 ${Iu}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 ${Ku} 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 ${Gu} 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 Sd(e){return xd(e).length===0}function Cd(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 wd=[{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`]}],Td=`rule`;function Ed(e){return wd.find(t=>t.key===e)?.key}function Dd(e){return e.kind===`motion`?J.t(`helpers.notificationSummaries.winMotion`,{quiet:Ll(e.quietSeconds),max:Ll(e.maxWindowSeconds)}):e.kind===`unsupported`?J.t(`helpers.notificationSummaries.winUnsupported`,{raw:e.raw}):J.t(`helpers.notificationSummaries.winSchedule`,{schedule:Bl(e.schedule)})}function Od(e,t){return Vl(e,t,`Never run`)}function kd(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:Ll(e.minDwellSeconds)})),e.includeStationary===!0&&t.push(J.t(`helpers.notificationSummaries.filterParked`)),t.length===0?J.t(`helpers.notificationSummaries.allPassages`):t.join(` · `)}function Ad(e){return{windowStartMs:e-Lu,windowEndMs:e}}c();var jd={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},Md={en:`English`,it:`Italiano`};function Nd(e){return Ru.find(t=>t===e)}function Pd(e){return Bu.find(t=>t===e)}function Fd(e){return Uu.find(t=>t===e)??``}function Id(e){return Wu.find(t=>t===e)}function Ld({rule:t,cameras:r,fleet:a,targets:s,taxonomy:c,onSaved:l,onCancel:u}){let{t:f}=Y(),p=N(),[m,h]=o(()=>t===null?fd():pd(t)),[g,_]=o(null),[v,y]=o(t!==null),[b,x]=o(Td),S=e=>h(t=>({...t,...e})),C=n(()=>{let e=L(`occupancy`,c);return e===null?[]:e.groups.flatMap(e=>e.options)},[c]),{options:w,loading:E}=Ar(m.deviceIds,r.map(e=>({id:e.id,name:e.name}))),D=bt({functionCap:`llm`}),O=(D.data??[]).filter(Fi),k=d({mutationFn:async()=>{let e=t===null?{rule:yd(m)}:{ruleId:t.id,patch:bd(m,t)};await p.trpcClient.addons.custom.mutate({addonId:$,action:Au,input:e})},onSuccess:l,onError:e=>_(e instanceof Error?e.message:`Save failed`)}),A=Zo(),ee=A.data?qo(A.data,{family:`summary`,field:`captionText`}):void 0,j=m.mosaicCaptions===`all`,M=xd(m),te=Cd(m),ne=wd.some(e=>e.key===b)?b:Td;return i(xt,{open:!0,onOpenChange:e=>!e&&u(),children:e(ht,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:e(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[i(it,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`span`,{className:`truncate`,children:t===null?f(`system.notificationSummaryEditor.newSummary`,`New summary`):f(`system.notificationSummaryEditor.edit`,`Edit {{name}}`,{name:t.name})})]})}),g!==null&&i(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:g}),e(`div`,{className:`shrink-0 space-y-2`,children:[t!==null&&i(ll,{kind:`summary`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt??1/0}),v?i(kl,{problems:M,testId:`summary-problems`}):null,i(Al,{warnings:te,testId:`summary-warnings`})]}),e(Jt,{value:ne,onValueChange:e=>x(Ed(e)??b),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[i(Mt,{className:`mb-3 shrink-0`,children:wd.map(e=>i(Ut,{value:e.key,children:e.label},e.key))}),e(ft,{className:`pr-1`,children:[e(W,{value:`rule`,className:`space-y-3`,children:[i(Q,{title:f(`system.notificationSummaryEditor.whatItIs`,`What it is`),hint:f(`system.notificationSummaryEditor.oneWindowOnePictureThe`,`One window, one picture: the best shot of every track the window held, laid out as one mosaic and delivered once.`),children:e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.name`,`Name`)}),i(K,{value:m.name,onChange:e=>S({name:e.target.value}),placeholder:f(`system.notificationSummaryEditor.eGOvernightSweep`,`e.g. Overnight sweep`),"data-testid":`summary-name`})]}),i(`div`,{className:`pb-1.5`,children:i(Pl,{label:f(`system.notificationSummaryEditor.enabled`,`Enabled`),checked:m.enabled,onChange:e=>S({enabled:e}),testId:`summary-enabled`})})]})}),i(Q,{title:f(`system.notificationSummaryEditor.cameras`,`Cameras`),hint:f(`system.notificationSummaryEditor.everyCameraInTheDigest`,`Every camera in the digest gets at least one tile when it contributed anything — a digest in which two of six cameras never appear is not multi-camera.`),children:i(jl,{cameras:r,value:m.deviceIds,fleet:a,onChange:e=>S({deviceIds:e}),hint:f(`system.notificationSummaryEditor.theFirstCameraSelectedOwns`,`The first camera selected owns the delivered notification.`)})})]}),i(W,{value:`window`,className:`space-y-3`,children:e(Q,{title:f(`system.notificationSummaryEditor.whenTheWindowCloses`,`When the window closes`),children:[e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.window`,`Window`)}),i(P,{value:m.windowKind,options:[{value:`motion`,label:f(`system.notificationSummaryEditor.motionOpenedAndClosedBy`,`Motion — opened and closed by activity`)},{value:`schedule`,label:f(`system.notificationSummaryEditor.scheduleFixedWeeklyWindows`,`Schedule — fixed weekly windows`)}],onChange:e=>S({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),m.windowKind===`motion`?e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Nl,{label:f(`system.notificationSummaryEditor.quietPeriodSeconds`,`Quiet period (seconds)`),value:m.quietSeconds,min:30,max:Nu,onChange:e=>S({quietSeconds:e??0}),hint:f(`system.notificationSummaryEditor.theWindowOpensOnThe`,`The window opens on the first motion on any of these cameras and stays open while more arrives. This much silence closes it.`),testId:`summary-quiet`}),i(Nl,{label:f(`system.notificationSummaryEditor.longestWindowSeconds`,`Longest window (seconds)`),value:m.maxWindowSeconds,min:60,max:Pu,onChange:e=>S({maxWindowSeconds:e??0}),hint:f(`system.notificationSummaryEditor.aPermanentlyBusyDrivewayWould`,`A permanently busy driveway would otherwise never deliver. At this bound the window closes with whatever it holds.`),testId:`summary-max-window`})]}):e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.weeklyWindows`,`Weekly windows`)}),i(Zr,{value:m.schedule,onChange:e=>S({schedule:e})}),i(`p`,{className:Ol,children:f(`system.notificationSummaryEditor.theDigestIsProducedWhen`,`The digest is produced when a window CLOSES, and covers exactly that window. The first one is the first window that closes after you save — nothing is backfilled.`)})]}),i(Nl,{label:f(`system.notificationSummaryEditor.waitForOpenTracksSeconds`,`Wait for open tracks (seconds)`),value:m.barrierSeconds,min:0,max:Fu,onChange:e=>S({barrierSeconds:e??0}),hint:f(`system.notificationSummaryEditor.aTrackSBestShot`,`A track's best shot is written when the track ENDS. Rendering the instant the window closes would show every still-moving subject with no picture. 0 disables the wait.`),testId:`summary-barrier`})]})}),i(W,{value:`content`,className:`space-y-3`,children:e(Q,{title:f(`system.notificationSummaryEditor.whatGoesIn`,`What goes in`),hint:f(`system.notificationSummaryEditor.evaluatedOnTracksOnePassage`,`Evaluated on tracks: one passage is one tile.`),children:[e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.classes`,`Classes`)}),i(Xr,{options:C,value:m.classes,onChange:e=>S({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),i(`p`,{className:Ol,children:f(`system.notificationSummaryEditor.emptyEveryClassOnlyThe`,`Empty = every class. Only the macro classes are offered: a digest matches the class stored on the track, and tracks store macros — a sub-type would match nothing, forever.`)})]}),e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.excludedClasses`,`Excluded classes`)}),i(Xr,{options:C,value:m.classesExclude,onChange:e=>S({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.zones`,`Zones`)}),i(Xr,{options:w,value:m.zones,onChange:e=>S({zones:e}),loading:E,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),i(`p`,{className:Ol,children:f(`system.notificationSummaryEditor.zonesAreScopedPerCamera`,`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Nl,{label:f(`system.notificationSummaryEditor.minimumImportance`,`Minimum importance`),value:m.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>S({minImportance:e}),hint:f(`system.notificationSummaryEditor.thePipelineSOwnScore`,`The pipeline's own score, 0–1. Empty keeps everything.`),testId:`summary-min-importance`}),i(Nl,{label:f(`system.notificationSummaryEditor.minimumStaySeconds`,`Minimum stay (seconds)`),value:m.minDwellSeconds,min:0,max:Iu,emptyPlaceholder:`any`,onChange:e=>S({minDwellSeconds:e}),hint:f(`system.notificationSummaryEditor.dropsThePassagesTooBrief`,`Drops the passages too brief to be worth a tile.`),testId:`summary-min-dwell`})]}),i(Pl,{label:f(`system.notificationSummaryEditor.includeParkedObjects`,`Include parked objects`),checked:m.includeStationary,onChange:e=>S({includeStationary:e}),hint:f(`system.notificationSummaryEditor.offByDefaultACar`,`Off by default. A car left in the drive is tracked until it is recognised as parked, and it stays parked for as long as it is there — with this on, a digest fills up with the same stationary object instead of the passages. Parked objects remain on the Events page either way.`),testId:`summary-include-stationary`})]})}),i(W,{value:`mosaic`,className:`space-y-3`,children:e(Q,{title:f(`system.notificationSummaryEditor.theMosaic`,`The mosaic`),children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Nl,{label:f(`system.notificationSummaryEditor.tiles`,`Tiles`),value:m.maxTiles,min:1,max:24,onChange:e=>S({maxTiles:e??1}),hint:f(`system.notificationSummaryEditor.9A33Grid`,`9 (a 3×3 grid) is the most a phone lock-screen thumbnail can carry and still be read.`),testId:`summary-max-tiles`}),e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.whenThereAreMoreTracks`,`When there are more tracks than tiles`)}),i(P,{value:m.rank,options:Ru.map(e=>({value:e,label:zu[e]})),onChange:e=>{let t=Nd(e.target.value);t!==void 0&&S({rank:t})},"data-testid":`summary-rank`}),i(`p`,{className:Ol,children:f(`system.notificationSummaryEditor.everyContributingCameraKeepsIts`,`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`)})]})]}),e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.textOnTheMosaic`,`Text on the mosaic`)}),i(P,{value:m.mosaicCaptions,options:Bu.map(e=>({value:e,label:Hu[e]})),onChange:e=>{let t=Pd(e.target.value);t!==void 0&&S({mosaicCaptions:t})},"data-testid":`summary-captions`}),i(`p`,{className:Ol,children:f(`system.notificationSummaryEditor.imagesOnlyIsTheDefault`,`Images only is the default, and it is what a rule with nothing set here does. Anything drawn is burnt into the picture for good — a label covers the bottom of the tile, which is where feet, wheels and parcels are, and a caption from a detection that was wrong cannot be un-drawn. Nothing downstream needs the words: the written summary reads the frames themselves and is told the camera, the class and the time in its prompt.`)})]}),e(`div`,{children:[i(ts,{label:f(`system.notificationSummaryEditor.captionBurnedOntoTheMosaic`,`Caption burned onto the mosaic`),value:m.captionText,disabled:!j,onChange:e=>S({captionText:e}),placeholder:f(`system.notificationSummaryEditor.leaveEmptyForNoCaption`,`Leave empty for no caption`),vars:ee,testId:`summary-caption`}),i(`p`,{className:Ol,children:j?f(`system.notificationSummaryEditor.acrossTheTopBand`,`Across the top band.`):f(`system.notificationSummaryEditor.onlyDrawnWithTileLabels`,`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`)})]})]})}),i(W,{value:`ai`,className:`space-y-3`,children:e(Q,{title:f(`system.notificationSummaryEditor.writtenSummary`,`Written summary`),hint:f(`system.notificationSummaryEditor.oneVisionCallOverThe`,`One vision call over the window's best frames TOGETHER, so the answer is an account of what happened rather than a list of pictures. The sentence goes in the notification body.`),children:[i(Pl,{label:f(`system.notificationSummaryEditor.haveAModelDescribeThe`,`Have a model describe the window`),checked:m.aiEnabled,onChange:e=>S({aiEnabled:e}),hint:f(`system.notificationSummaryEditor.offByDefaultTheMosaic`,`Off by default. The mosaic and the counts are delivered either way.`),testId:`summary-ai-enabled`}),!m.aiEnabled&&i(`p`,{className:`rounded-md border border-border bg-surface px-2.5 py-1.5 text-[10px] text-foreground-muted`,"data-testid":`summary-ai-off-note`,children:f(`system.notificationSummaryEditor.theSwitchAboveIsOff`,`The switch above is off, so nothing below it can be edited. Everything you already set is kept — turning it on hands the fields back exactly as you left them.`)}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.visionProfile`,`Vision profile`)}),i(P,{value:m.aiProfileId,disabled:!m.aiEnabled,options:[{value:``,label:f(`system.notificationSummaryEditor.theHubSDefaultVision`,`The hub's default vision profile`)},...O.map(e=>({value:e.id,label:`${e.name} · ${Ii(e)}${e.enabled?``:` · disabled`}`}))],onChange:e=>S({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),i(`p`,{className:Ol,children:D.isError?f(`system.notificationSummaryEditor.thisHubDidNotAnswer`,`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`):O.length===0?f(`system.notificationSummaryEditor.noVisionCapableProfileOn`,`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`):f(`system.notificationSummaryEditor.onlyVisionCapableProfilesAre`,`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`)})]}),e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.answerIn`,`Answer in`)}),i(P,{value:m.aiLanguage,disabled:!m.aiEnabled,options:[{value:``,label:f(`system.notificationSummaryEditor.donTAskForA`,`Don’t ask for a language`)},...Uu.map(e=>({value:e,label:Md[e]}))],onChange:e=>S({aiLanguage:Fd(e.target.value)}),"data-testid":`summary-ai-language`}),i(`p`,{className:Ol,children:f(`system.notificationSummaryEditor.nothingIsAddedToThe`,`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`)})]})]}),e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.yourQuestionOptional`,`Your question (optional)`)}),i(Yt,{value:m.aiPrompt,rows:3,maxLength:Ku,disabled:!m.aiEnabled,onChange:e=>S({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:f(`system.notificationSummaryEditor.eGTellMeWhether`,`e.g. Tell me whether anybody approached the gate, and whether a parcel was left.`),className:`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50`}),i(`p`,{className:Ol,children:f(`system.notificationSummaryEditor.leaveBlankForWhatHappened`,`Leave blank for “what happened during this period?”. Your words are the only free text the model is given: what the cameras are called and what the pipeline classified are reduced to plain labels first, and anything written INSIDE a frame — a sign, a plate, an overlay — is treated as scenery, never as an instruction.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Nl,{label:f(`system.notificationSummaryEditor.framesTheModelMayLook`,`Frames the model may look at`),value:m.maxAiImages,min:1,max:8,disabled:!m.aiEnabled,onChange:e=>S({maxAiImages:e??1}),hint:f(`system.notificationSummaryEditor.theHighestRankedTilesSent`,`The highest-ranked tiles, sent as ONE question. Bounded separately from the tile budget — one is bounded by pixels, the other by the model's time — and never larger than it.`),testId:`summary-max-ai-images`}),i(Nl,{label:f(`system.notificationSummaryEditor.timeLimitSeconds`,`Time limit (seconds)`),value:m.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!m.aiEnabled,onChange:e=>S({aiTimeoutSeconds:e}),hint:f(`system.notificationSummaryEditor.nobodyIsWaitingOnA`,`Nobody is waiting on a phone for a digest, so this is generous. At the bound the generation is cancelled, not merely abandoned.`),testId:`summary-ai-timeout`})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Nl,{label:f(`system.notificationSummaryEditor.frameSizeSentPixels`,`Frame size sent (pixels)`),value:m.aiMaxImagePx,min:64,max:Gu,emptyPlaceholder:`448`,disabled:!m.aiEnabled,onChange:e=>S({aiMaxImagePx:e}),hint:f(`system.notificationSummaryEditor.longestEdge448IsThe`,`Longest edge. 448 is the native tile size of these vision encoders — larger costs tokens and latency without adding detail the encoder can see.`),testId:`summary-ai-max-px`}),e(`div`,{children:[i(`label`,{className:Z,children:f(`system.notificationSummaryEditor.ifTheModelGivesNo`,`If the model gives no answer`)}),i(P,{value:m.aiOnFailure,disabled:!m.aiEnabled,options:Wu.map(e=>({value:e,label:jd[e]})),onChange:e=>{let t=Id(e.target.value);t!==void 0&&S({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),i(`p`,{className:Ol,children:f(`system.notificationSummaryEditor.aColdModelAnUnreachable`,`A cold model, an unreachable endpoint or an answer the hub cannot parse are all this case. The default delivers: the mosaic and the counts are worth more than silence, and a closed window does not come back.`)})]})]})]})}),i(W,{value:`delivery`,className:`space-y-3`,children:e(Q,{title:f(`system.notificationSummaryEditor.delivery`,`Delivery`),children:[i(Ml,{targets:s,value:m.targetIds,onChange:e=>S({targetIds:e})}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Nl,{label:f(`system.notificationSummaryEditor.priority`,`Priority`),value:m.priority,min:1,max:5,onChange:e=>S({priority:e??3}),testId:`summary-priority`}),i(Pl,{label:f(`system.notificationSummaryEditor.deliverAWindowThatMatched`,`Deliver a window that matched nothing`),checked:m.deliverEmpty,onChange:e=>S({deliverEmpty:e}),hint:f(`system.notificationSummaryEditor.offByDefaultANightly`,`Off by default: a nightly '0 events' is a line nobody reads, and it costs the lines beside it their reader.`),testId:`summary-deliver-empty`})]}),i(Fl,{title:m.templateTitle,body:m.templateBody,onTitleChange:e=>S({templateTitle:e}),onBodyChange:e=>S({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),i(`p`,{className:Ol,children:i(Bn,{i18nKey:`system.notificationSummaryEditor.aiToken`,values:{token:`{{ai}}`},components:{code:i(`code`,{})}})})]})})]})]}),e(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[i(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:u,children:f(`common.cancel`,`Cancel`)}),e(U,{size:`sm`,type:`button`,disabled:k.isPending,onClick:()=>{y(!0),!(!Sd(m)||k.isPending)&&k.mutate()},children:[k.isPending&&i(T,{className:`h-3.5 w-3.5 animate-spin`}),t===null?f(`system.notificationSummaryEditor.create`,`Create`):f(`common.save`,`Save`)]})]})]})})}var Rd=`nc.listTimelapseRules`,zd=`nc.upsertTimelapseRule`,Bd=`nc.deleteTimelapseRule`,Vd=`nc.testTimelapseRule`,Hd=3600,Ud=3600,Wd=30,Gd=1,Kd=[`image`,`gif`],qd={image:`Still frame`,gif:`Short animation (GIF)`},Jd=Xe({rules:Qe(de.extend({readOnly:$e().optional()}))});function Yd(e){let t=Jd.safeParse(e);return t.success?t.data.rules:null}function Xd(e){return e.readOnly!==!0}var Zd=Xe({produced:qe(),exportId:Ye().optional(),coveragePercent:qe().optional(),enqueued:qe().optional(),windowStartMs:qe().optional(),windowEndMs:qe().optional(),error:Ye().optional()});function Qd(e){let t=Zd.safeParse(e);return t.success?t.data:null}function $d(){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 ef(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 tf={windows:[{days:[1],startMinute:0,endMinute:60}]};function nf(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 rf(e){let t=nf(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??tf,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Gl(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 af(e,t){let n=rf(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??of(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 of(e){return Math.max(Gd,e/Wd)}function sf(e,t,n){return t<=0||n<=0?0:e/t/n}function cf(e,t){return e*t*we}function lf(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 ${Hd}.`),(!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 ${we}s and ${Ud}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 uf(e){return lf(e).length===0}function df(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=cf(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 ff(e){return Bl(e)}function pf(e,t){return Vl(e,t,`Never run`)}function mf(e){return e.denseCadenceSec===void 0?{seconds:of(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var hf=[{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`]}],gf=`rule`;function _f(e){return hf.find(t=>t.key===e)?.key}c();var vf=7;function yf(e){return Kd.find(t=>t===e)}function bf({rule:t,cameras:n,fleet:r,targets:a,onSaved:s,onCancel:c}){let{t:l}=Y(),u=N(),[p,m]=o(()=>t===null?$d():ef(t)),[h,g]=o(null),[_,v]=o(t!==null),[y,b]=o(gf),x=e=>m(t=>({...t,...e})),S=Zo(),C=S.data?qo(S.data,{family:`timelapse`,field:`previewText`}):void 0,w=d({mutationFn:async()=>{let e=t===null?{rule:rf(p)}:{ruleId:t.id,patch:af(p,t)};await u.trpcClient.addons.custom.mutate({addonId:$,action:zd,input:e})},onSuccess:s,onError:e=>g(e instanceof Error?e.message:`Save failed`)}),E=lf(p),D=df(p),O=mf(p),k=sf(vf,O.seconds,p.framerate),A=hf.some(e=>e.key===y)?y:gf;return i(xt,{open:!0,onOpenChange:e=>!e&&c(),children:e(ht,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:e(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[i(M,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`span`,{className:`truncate`,children:t===null?l(`system.notificationTimelapseEditor.newTimelapse`,`New timelapse`):l(`system.notificationTimelapseEditor.edit`,`Edit {{name}}`,{name:t.name})})]})}),h!==null&&i(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:h}),e(`div`,{className:`shrink-0 space-y-2`,children:[t!==null&&i(ll,{kind:`timelapse`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt}),_?i(kl,{problems:E,testId:`timelapse-problems`}):null,i(Al,{warnings:D,testId:`timelapse-warnings`})]}),e(Jt,{value:A,onValueChange:e=>b(_f(e)??y),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[i(Mt,{className:`mb-3 shrink-0`,children:hf.map(e=>i(Ut,{value:e.key,children:e.label},e.key))}),e(ft,{className:`pr-1`,children:[e(W,{value:`rule`,className:`space-y-3`,children:[i(Q,{title:l(`system.notificationTimelapseEditor.whatItIs`,`What it is`),hint:l(`system.notificationTimelapseEditor.oneVideoPerCameraAssembled`,`One video per camera, assembled from that camera's RECORDED footage when the window closes.`),children:e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.name`,`Name`)}),i(K,{value:p.name,onChange:e=>x({name:e.target.value}),placeholder:l(`system.notificationTimelapseEditor.eGNightDriveway`,`e.g. Night driveway`),"data-testid":`timelapse-name`})]}),i(`div`,{className:`pb-1.5`,children:i(Pl,{label:l(`system.notificationTimelapseEditor.enabled`,`Enabled`),checked:p.enabled,onChange:e=>x({enabled:e}),testId:`timelapse-enabled`})})]})}),i(Q,{title:l(`system.notificationTimelapseEditor.cameras`,`Cameras`),children:i(jl,{cameras:n,value:p.deviceIds,fleet:r,onChange:e=>x({deviceIds:e}),hint:l(`system.notificationTimelapseEditor.eachCameraRendersAndDelivers`,`Each camera renders and delivers its own video. Recording must be ON for a camera — a timelapse is cut from recorded footage, and the hub refuses a rule for a camera that does not record.`)})})]}),i(W,{value:`window`,className:`space-y-3`,children:i(Q,{title:l(`system.notificationTimelapseEditor.when`,`When`),children:e(`div`,{children:[i(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.weeklyWindows`,`Weekly windows`)}),i(Zr,{value:p.schedule,onChange:e=>x({schedule:e})}),i(`p`,{className:Ol,children:l(`system.notificationTimelapseEditor.theVideoCoversExactlyOne`,`The video covers exactly one window and is delivered when it CLOSES. A window that crosses midnight (21:00 → 07:00) is the ordinary case for a night timelapse.`)})]})})}),i(W,{value:`sampling`,className:`space-y-3`,children:e(Q,{title:l(`system.notificationTimelapseEditor.sampling`,`Sampling`),hint:l(`system.notificationTimelapseEditor.twoRatesABaseRate`,`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`),children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(Nl,{label:l(`system.notificationTimelapseEditor.baseCadenceSeconds`,`Base cadence (seconds)`),value:p.cadenceSec,min:2,max:Hd,onChange:e=>x({cadenceSec:e??0}),hint:l(`system.notificationTimelapseEditor.oneFrameEveryNSeconds`,`One frame every N seconds across the quiet parts of the window.`),testId:`timelapse-cadence`}),i(Nl,{label:l(`system.notificationTimelapseEditor.outputFrameRateFps`,`Output frame rate (fps)`),value:p.framerate,min:1,max:60,onChange:e=>x({framerate:e??0}),hint:l(`system.notificationTimelapseEditor.howFastTheAssembledVideo`,`How fast the assembled video plays.`),testId:`timelapse-framerate`})]}),e(`div`,{children:[i(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.denseCadenceNearTheDetections`,`Dense cadence, near the detections`)}),e(`div`,{className:`flex items-center gap-2`,children:[i(P,{value:p.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:l(`system.notificationTimelapseEditor.automaticS`,`Automatic ({{seconds}}s)`,{seconds:O.seconds})},{value:`explicit`,label:l(`system.notificationTimelapseEditor.setItMyself`,`Set it myself`)}],onChange:e=>x({denseCadenceSec:e.target.value===`auto`?void 0:mf(p).seconds}),"data-testid":`timelapse-dense-mode`}),p.denseCadenceSec!==void 0&&i(K,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(p.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&x({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),e(`p`,{className:Ol,"data-testid":`timelapse-dense-hint`,children:[l(`system.notificationTimelapseEditor.denseHint`,{seconds:O.seconds,fps:p.framerate,passage:vf,onScreen:k.toFixed(2)}),` `,O.derived?l(`system.notificationTimelapseEditor.denseDerived`):l(`system.notificationTimelapseEditor.denseFixed`,{seconds:mf({...p,denseCadenceSec:void 0}).seconds})]})]}),i(Nl,{label:l(`system.notificationTimelapseEditor.minimumSecondsOfVideoPer`,`Minimum seconds of video per detection (optional)`),value:p.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>x({minDwellSec:e}),hint:l(`system.notificationTimelapseEditor.stateTheStayAndLet`,`State the stay and let the renderer solve for the cadence. It only ever samples DENSER, down to the recording's own frame interval — a passage too short to reach it is rendered with every frame that exists and no more.`),testId:`timelapse-min-dwell`})]})}),i(W,{value:`delivery`,className:`space-y-3`,children:e(Q,{title:l(`system.notificationTimelapseEditor.theNotification`,`The notification`),children:[i(Ml,{targets:a,value:p.targetIds,onChange:e=>x({targetIds:e})}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.preview`,`Preview`)}),i(P,{value:p.previewMode,options:Kd.map(e=>({value:e,label:qd[e]})),onChange:e=>{let t=yf(e.target.value);t!==void 0&&x({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),i(Nl,{label:l(`system.notificationTimelapseEditor.priority`,`Priority`),value:p.priority,min:1,max:5,onChange:e=>x({priority:e??3}),testId:`timelapse-priority`})]}),e(`div`,{children:[i(ts,{label:l(`system.notificationTimelapseEditor.captionOnThePreviewFrame`,`Caption on the preview frame`),value:p.previewTextSet?p.previewText:``,placeholder:l(`system.notificationTimelapseEditor.shippedDefault`,`{{DEFAULT_TIMELAPSE_PREVIEW_TEXT}} (shipped default)`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:Ue}),onChange:e=>x({previewText:e,previewTextSet:!0}),vars:C,testId:`timelapse-preview-text`}),e(`p`,{className:Ol,children:[p.previewTextSet&&p.previewText.length===0?l(`system.notificationTimelapseEditor.emptyAndSetThePreview`,`Empty and set: the preview frame carries NO caption.`):l(`system.notificationTimelapseEditor.leaveUntouchedForTheShipped`,`Leave untouched for the shipped caption ({{DEFAULT_TIMELAPSE_PREVIEW_TEXT}}).`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:Ue}),p.previewTextSet&&e(f,{children:[` `,i(U,{variant:`unstyled`,type:`button`,className:`underline`,onClick:()=>x({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:l(`system.notificationTimelapseEditor.backToTheShippedCaption`,`Back to the shipped caption`)})]})]})]}),i(Fl,{title:p.templateTitle,body:p.templateBody,onTitleChange:e=>x({templateTitle:e}),onBodyChange:e=>x({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:i(Bn,{i18nKey:`system.notificationTimelapseEditor.detectionSummaryNote`,values:{token:`{{detectionSummary}}`},components:{code:i(`code`,{})}})})]})})]})]}),e(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[i(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:l(`common.cancel`,`Cancel`)}),e(U,{size:`sm`,type:`button`,disabled:w.isPending,onClick:()=>{v(!0),!(!uf(p)||w.isPending)&&w.mutate()},children:[w.isPending&&i(T,{className:`h-3.5 w-3.5 animate-spin`}),t===null?l(`system.notificationTimelapseEditor.create`,`Create`):l(`common.save`,`Save`)]})]})]})})}c();var xf=`notification-output`;function Sf(e){return e.map(e=>({id:e.id,name:e.name,kind:le(e.recordKind),addonId:e.addonId,enabled:e.enabled,config:{...e.formValues}}))}function Cf(){let e=bt({functionCap:xf});return{data:n(()=>e.data===void 0?void 0:Sf(e.data),[e.data]),isError:e.isError}}function wf({children:e,className:t}){return i(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function Tf(){return i(`div`,{className:`flex items-center justify-center py-16`,children:i(T,{className:`h-6 w-6 animate-spin text-primary`})})}function Ef({children:e,testId:t}){return i(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function Df({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:a}){return i(ct,{children:i(pt,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,maxBodyHeight:wt,...a===void 0?{}:{onRowClick:a}})})}function Of({name:t,enabled:n,onOpen:r,badges:a,openTestId:o}){let{t:s}=Y();return e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[r===void 0?i(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t}):i(wf,{children:i(U,{variant:`unstyled`,type:`button`,onClick:r,className:`truncate rounded text-left text-sm font-medium text-foreground hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,...o===void 0?{}:{"data-testid":o},children:t})}),!n&&i(H,{variant:`warning`,children:s(`common.disabled`)}),a]})}function kf({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:a=`Delete`,cancelLabel:o=`Cancel`,ariaLabel:s,testId:c,onConfirm:l}){let u=ee(),d=async()=>{await u({title:n,message:r,confirmLabel:a,cancelLabel:o,variant:`danger`})&&l()};return i(U,{variant:`unstyled`,type:`button`,title:a,"aria-label":s,disabled:e||t,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void d(),...c===void 0?{}:{"data-testid":c},children:i(E,{className:`h-3.5 w-3.5 text-danger`})})}c();var Af=[`notificationSummaries`,`listSummaryRules`];function jf(t){return[{key:`name`,header:J.t(`system.notificationSummaries.digest`,`Digest`),render:n=>i(Of,{name:n.name,enabled:n.enabled,...qu(n)?{onOpen:()=>t.onOpen(n)}:{},openTestId:`summary-edit-${n.id}`,badges:e(f,{children:[!qu(n)&&i(H,{variant:`warning`,children:`read-only`}),n.ai?.enabled===!0&&i(H,{variant:`info`,children:`AI`}),n.ai!==void 0&&!n.ai.enabled&&i(H,{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=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:J.t(`system.notificationSummaries.window`,`Window`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Dd(e.window)})},{key:`filters`,header:J.t(`system.notificationSummaries.keeps`,`Keeps`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:kd(e.filters)})},{key:`mosaic`,header:J.t(`system.notificationSummaries.mosaic`,`Mosaic`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:J.t(`system.notificationSummaries.tilesRank`,{count:e.maxTiles,rank:e.rank})})},{key:`targets`,header:J.t(`system.notificationSummaries.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationSummaries.lastRun`,`Last run`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${e.id}`,children:Od(e.generatedAt,t.nowMs)})},{key:`enabled`,header:J.t(`system.notificationSummaries.on`,`On`),align:`center`,nowrap:!0,render:e=>i(wf,{children:i(q,{checked:e.enabled,disabled:e.readOnly,onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationSummaries.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(wf,{className:`flex items-center justify-end gap-1`,children:[i(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.readOnly,onClick:()=>t.onTest(n),title:J.t(`system.notificationSummaries.produceThisDigestNowAnd`,`Produce this digest now and DELIVER it`),"aria-label":J.t(`system.notificationSummaries.test`,`test {{name}}`,{name:n.name}),"data-testid":`summary-test-${n.id}`,children:i(nt,{className:`h-3.5 w-3.5`})}),i(kf,{disabled:n.readOnly,pending:t.deletePending,title:J.t(`system.notificationSummaries.deleteThisSummary`,`Delete this summary?`),message:J.t(`system.notificationSummaries.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:n.name}),ariaLabel:J.t(`system.notificationSummaries.delete`,`delete {{name}}`,{name:n.name}),testId:`summary-delete-${n.id}`,onConfirm:()=>t.onConfirmDelete(n)})]})}]}c();var Mf=[`notificationTimelapses`,`listTimelapseRules`];function Nf(t){return[{key:`name`,header:J.t(`system.notificationTimelapses.timelapse`,`Timelapse`),render:e=>i(Of,{name:e.name,enabled:e.enabled,...Xd(e)?{onOpen:()=>t.onOpen(e),openTestId:`timelapse-edit-${e.id}`}:{},badges:Xd(e)?null:i(H,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:J.t(`system.notificationTimelapses.cameras`,`Cameras`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length===1?t.cameraNameById.get(e.deviceIds[0]??-1)??`#${e.deviceIds[0]}`:J.t(`system.notificationTimelapses.cameras2`,`{{length}} cameras`,{length:e.deviceIds.length})})},{key:`schedule`,header:J.t(`system.notificationTimelapses.window`,`Window`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:ff(e.schedule)})},{key:`sampling`,header:J.t(`system.notificationTimelapses.sampling`,`Sampling`),nowrap:!0,render:t=>{let n=mf(ef(t));return e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[J.t(n.derived?`system.notificationTimelapses.ruleSummaryAuto`:`system.notificationTimelapses.ruleSummary`,{cadence:t.cadenceSec,fps:t.framerate,dense:n.seconds}),t.minDwellSec===void 0?``:` · ${J.t(`system.notificationTimelapses.ruleDwell`,{sec:t.minDwellSec})}`]})}},{key:`targets`,header:J.t(`system.notificationTimelapses.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationTimelapses.lastRun`,`Last run`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${e.id}`,children:pf(e.lastGeneratedAt,t.nowMs)})},{key:`enabled`,header:J.t(`system.notificationTimelapses.on`,`On`),align:`center`,nowrap:!0,render:e=>i(wf,{children:i(q,{checked:e.enabled,disabled:!Xd(e),onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationTimelapses.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(wf,{className:`flex items-center justify-end gap-1`,children:[i(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Xd(n),onClick:()=>t.onTest(n),title:J.t(`system.notificationTimelapses.renderThisRuleSLast`,`Render this rule's last closed window now and DELIVER it`),"aria-label":J.t(`system.notificationTimelapses.test`,`test {{name}}`,{name:n.name}),"data-testid":`timelapse-test-${n.id}`,children:i(nt,{className:`h-3.5 w-3.5`})}),i(kf,{disabled:!Xd(n),pending:t.deletePending,title:J.t(`system.notificationTimelapses.deleteThisTimelapse`,`Delete this timelapse?`),message:J.t(`system.notificationTimelapses.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:n.name}),ariaLabel:J.t(`system.notificationTimelapses.delete`,`delete {{name}}`,{name:n.name}),testId:`timelapse-delete-${n.id}`,onConfirm:()=>t.onConfirmDelete(n)})]})}]}c();var Pf={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 If(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function Lf({cameras:t,fleet:n,targets:r,taxonomy:a}){let{t:c}=Y(),l=N(),[u,p]=o({mode:`closed`}),[m,h]=o(null),[g,_]=o(null),[v,y]=o(null),[b,x]=o(null),S=s({queryKey:Af,queryFn:async()=>ud(await l.trpcClient.addons.custom.mutate({addonId:$,action:ku,input:{}}))}),C=s({queryKey:Mf,queryFn:async()=>Yd(await l.trpcClient.addons.custom.mutate({addonId:$,action:Rd,input:{}}))}),w=s({queryKey:cu,queryFn:async()=>hu(await l.trpcClient.addons.custom.mutate({addonId:$,action:lu,input:{}}))}),T=S.data??[],E=C.data??[],D=w.data??[],O=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Au,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),k=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:ju,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),A=d({mutationFn:async e=>dd(await l.trpcClient.addons.custom.mutate({addonId:$,action:Mu,input:{ruleId:e,...Ad(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),ee=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:zd,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),j=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Bd,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),M=d({mutationFn:async e=>Qd(await l.trpcClient.addons.custom.mutate({addonId:$,action:Vd,input:e})),onSuccess:e=>{y(null),x(e)}}),te=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:uu,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void w.refetch()}),ne=d({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:du,input:{ruleId:e}}),onSuccess:()=>void w.refetch()}),re=t.toSorted((e,t)=>e.name.localeCompare(t.name)),F=r.map(e=>({id:e.id,name:e.name,enabled:e.enabled})),ie=new Map(F.map(e=>[e.id,e.name])),I=new Map(re.map(e=>[e.id,e.name])),ae=Date.now(),oe={summary:{nowMs:ae,targetNameById:ie,deletePending:k.isPending,onToggle:(e,t)=>O.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{qu(e)&&p({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>k.mutate(e.id)},timelapse:{nowMs:ae,cameraNameById:I,targetNameById:ie,deletePending:j.isPending,onToggle:(e,t)=>ee.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Xd(e)&&p({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>j.mutate(e.id)},calendar:{nowMs:ae,targetNameById:ie,deletePending:ne.isPending,onToggle:(e,t)=>te.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{gu(e)&&p({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>ne.mutate(e.id)}},L=e=>{switch(e.family){case`summary`:oe.summary.onOpen(e.rule);return;case`timelapse`:oe.timelapse.onOpen(e.rule);return;case`calendar-events`:oe.calendar.onOpen(e.rule);return}},se=e=>{p(e===`summary`?{mode:`summary`,rule:null}:e===`timelapse`?{mode:`timelapse`,rule:null}:{mode:`calendar-events`,rule:null})},ce=e=>{let t=e===`summary`?S:e===`timelapse`?C:w;return t.isLoading?null:t.isError?{unreadable:!1}:t.data===null?{unreadable:!0}:null},le=e=>{e===`summary`?S.refetch():e===`timelapse`?C.refetch():w.refetch()},ue=e=>{let t=If(e);return t!==null&&ce(t)!==null},de=t=>{let n=If(t),r=n===null?null:ce(n);return e(f,{children:[n!==null&&r!==null&&i(G,{title:c(Pf[n].titleKey),message:c(r.unreadable?Ff:Pf[n].messageKey),onRetry:()=>le(n)}),k.isError&&i(G,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(k.error)}),j.isError&&i(G,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(j.error)}),ne.isError&&i(G,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(ne.error)}),A.isError&&i(G,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(A.error)}),M.isError&&i(G,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(M.error)}),g!==null&&i(Rf,{outcome:g,onDismiss:()=>_(null)}),b!==null&&i(zf,{outcome:b,onDismiss:()=>x(null)})]})},fe=()=>p({mode:`closed`}),pe=e(f,{children:[u.mode===`summary`&&i(Ld,{rule:u.rule,cameras:re,fleet:n,targets:F,taxonomy:a,onCancel:fe,onSaved:()=>{fe(),S.refetch()}}),u.mode===`timelapse`&&i(bf,{rule:u.rule,cameras:re,fleet:n,targets:F,onCancel:fe,onSaved:()=>{fe(),C.refetch()}}),u.mode===`calendar-events`&&i(Ou,{rule:u.rule,targets:F,onCancel:fe,onSaved:()=>{fe(),w.refetch()}}),i(Il,{open:m!==null,ruleName:m?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${m?.targets.length??0} target${(m?.targets.length??0)===1?``:`s`}`,pending:A.isPending,onCancel:()=>h(null),onConfirm:()=>{m!==null&&A.mutate(m.id)}}),i(Il,{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:M.isPending,confirmDisabled:v?.deviceId===null,extra:v===null?null:e(`div`,{children:[i(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.notificationProducerRules.whichCamera`,`Which camera`)}),i(P,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:I.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&&M.mutate({ruleId:v.rule.id,deviceId:v.deviceId})}})]});return{summaries:T,timelapses:E,calendarEvents:D,loading:S.isLoading||C.isLoading||w.isLoading,columnDeps:oe,open:L,create:se,notices:de,listFailed:ue,overlays:pe}}function Rf({outcome:t,onDismiss:n}){let{t:r}=Y();return e(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[t.error===void 0?e(`span`,{children:[r(`system.notificationProducerRules.summaryProduced`,{digests:r(`system.notificationProducerRules.digestCount`,{count:t.produced}),tiles:r(`system.notificationProducerRules.tileCount`,{count:t.tiles??0}),cameras:r(`system.notificationProducerRules.cameraCount`,{count:t.cameras??0}),matched:r(`system.notificationProducerRules.tracksMatched`,{count:t.matched??0}),sent:r(`system.notificationProducerRules.notificationsSent`,{count:t.enqueued??0})}),(t.droppedStationary??0)>0&&i(`span`,{"data-testid":`summary-test-dropped-stationary`,className:`ml-1`,children:r(`system.notificationProducerRules.droppedStationary`,{count:t.droppedStationary})})]}):e(`span`,{className:`text-warning`,children:[r(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,t.error]}),i(U,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:n,children:r(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}function zf({outcome:t,onDismiss:n}){let{t:r}=Y();return e(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[t.error===void 0?i(`span`,{children:r(t.coveragePercent===void 0?`system.notificationProducerRules.timelapseProduced`:`system.notificationProducerRules.timelapseProducedCoverage`,{videos:r(`system.notificationProducerRules.videoCount`,{count:t.produced}),percent:Math.round(t.coveragePercent??0),sent:r(`system.notificationProducerRules.notificationsSent`,{count:t.enqueued??0})})}):e(`span`,{className:`text-warning`,children:[r(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,t.error]}),i(U,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:n,children:r(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}var Bf=[{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 Hf(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function Uf(e){if(!(e==null||e.length===0))return Hf(e)?e:se(e)}function Wf(e){let t=Bf.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function Gf(e){return[...bn.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...Bf]}function Kf(e){return!Hf(e)}function qf(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}c();function Jf(e){return[{key:`name`,header:J.t(`system.notificationCalendarEventsPage.rule`,`Rule`),render:t=>i(Of,{name:t.name,enabled:t.enabled,...gu(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:gu(t)?null:i(H,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:J.t(`system.notificationCalendarEventsPage.when`,`When`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:bu(e.schedule)})},{key:`horizon`,header:J.t(`system.notificationCalendarEventsPage.horizon`,`Horizon`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Eu(e.horizonDays)})},{key:`calendars`,header:J.t(`system.notificationCalendarEventsPage.calendars`,`Calendars`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Du(e)})},{key:`targets`,header:J.t(`system.notificationCalendarEventsPage.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationCalendarEventsPage.lastRun`,`Last run`),nowrap:!0,render:t=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:Od(t.generatedAt,e.nowMs)})},{key:`enabled`,header:J.t(`system.notificationCalendarEventsPage.on`,`On`),align:`center`,nowrap:!0,render:t=>i(wf,{children:i(q,{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=>i(wf,{className:`flex items-center justify-end gap-1`,children:i(kf,{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 Yf(e,t){return e.replaceAll(`{{name}}`,t)}function Xf(t){return[{key:`name`,header:J.t(`system.notificationRuleColumns.rule`,`Rule`),render:e=>i(Of,{name:e.name,enabled:e.enabled,...Cr(e)?{onOpen:()=>t.onOpen(e)}:{}})},{key:`trigger`,header:J.t(`system.notificationRuleColumns.trigger`,`Trigger`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Tr(n,t.t(`notificationRules.grouping.choice`,rn))}),!Qt(n.delivery)&&i(H,{variant:`warning`,children:J.t(`common.readOnly`)})]})},{key:`targets`,header:J.t(`system.notificationRuleColumns.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r?r:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationRuleColumns.lastRun`,`Last run`),nowrap:!0,render:e=>i(Vc,{cell:t.lastRunOf(e.id)})},{key:`priority`,header:J.t(`system.notificationRuleColumns.priority`,`Priority`),align:`center`,nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:t.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:e=>i(wf,{children:i(Xc,{rule:e,snoozes:t.snoozes,exempt:xn(e.conditions,er({onActivation:e.actions?.onActivation??[],onDeactivation:e.actions?.onDeactivation??[],onTrigger:e.actions?.onTrigger??[],onTriggerOff:e.actions?.onTriggerOff??[],buttons:e.actions?.buttons??[]},t.actions))})})},{key:`enabled`,header:J.t(`system.notificationRuleColumns.on`,`On`),align:`center`,nowrap:!0,render:e=>i(wf,{children:i(q,{checked:e.enabled,onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationRuleColumns.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>Cr(n)?e(wf,{className:`flex items-center justify-end gap-1`,children:[i(Sl,{ruleId:n.id,ruleName:n.name,...n.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:n.conditions.devices[0]}}),t.onOpenHistory&&i(Hc,{rule:n,onOpenHistory:t.onOpenHistory}),t.onTest&&i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest?.(n),title:J.t(`system.notificationRuleColumns.openInTheSimulatorDescribe`,`Open in the simulator — describe an event and tune it before injecting`),"aria-label":J.t(`system.notificationRuleColumns.simulate`,`simulate {{name}}`,{name:n.name}),children:i(nt,{className:`h-3.5 w-3.5`})}),i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDuplicate(n),title:J.t(`system.notificationRuleColumns.duplicate`,`Duplicate`),children:i(D,{className:`h-3.5 w-3.5`})}),i(Qf,{rule:n,deps:t})]}):i(Zf,{rule:n,deps:t})}]}function Zf({rule:t,deps:n}){let{t:r}=Y();return e(wf,{className:`flex items-center justify-end gap-1`,children:[i(`span`,{title:ue(fe(t)).blurb,children:i(H,{variant:`warning`,children:r(`system.notificationRuleColumns.recreateAsOneRulePer`,`Recreate as one rule per family`)})}),n.onOpenHistory&&i(Hc,{rule:t,onOpenHistory:n.onOpenHistory}),i(Qf,{rule:t,deps:n})]})}function Qf({rule:e,deps:t}){let{t:n}=Y();return i(kf,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:Yf(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:Yf(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function $f(e){let t=Xf(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:J.t(`system.notificationRuleColumns.events`,`Events`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:gr(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:J.t(`system.notificationRuleColumns.scope`,`Scope`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:mi(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 i(`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=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:sr(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function ep(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 tp(e){return{family:`event`,kind:fe(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function np(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function rp(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function ip(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function ap(e){return[...e.events.map(tp),...e.summaries.map(np),...e.timelapses.map(rp),...e.calendarEvents.map(ip)]}function op(e,t){return t===`all`?!0:Hf(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:Kf(t)&&e.family===`event`?xe(e.rule,t):!1}function sp(e,t){return ap(t).filter(t=>op(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function cp(e,t){return sp(e,t).length}function lp(e){return e===`all`?900:860}function up(e){return e.family===`event`?e.rule:null}function dp(e){return e.family===`summary`?e.rule:null}function fp(e){return e.family===`timelapse`?e.rule:null}function pp(e){return e.family===`calendar-events`?e.rule:null}function mp(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 hp(e,t){return e.map(e=>mp(e,t))}function gp(e,t){return e.find(e=>e.key===t)}function _p(e,t,n){let r=gp(Xf(n.event),e),i=gp(jf(n.summary),e),a=gp(Nf(n.timelapse),e),o=gp(Jf(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 vp(e){switch(e.family){case`event`:return null;case`summary`:return Dd(e.rule.window);case`timelapse`:return ff(e.rule.schedule);case`calendar-events`:return bu(e.rule.schedule)}}function yp(e){let t=gp(Xf(e.event),`trigger`);return{key:`when`,header:J.t(`system.unifiedRulesColumns.when`,`When`),render:(e,n)=>{let r=vp(e);return r===null?e.family===`event`?t?.render(e.rule,n)??null:null:i(`span`,{className:`text-[11px] text-foreground-subtle`,children:r})}}}function bp(e){return[_p(`name`,`Name`,e),{key:`type`,header:J.t(`system.unifiedRulesColumns.type`,`Type`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:ep(e.kind)})},yp(e),_p(`targets`,`Targets`,e),_p(`lastRun`,`Last run`,e),_p(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),_p(`enabled`,`On`,e),_p(`actions`,``,e)]}function xp(e,t){return e===`all`?bp(t):e===`summaries`?hp(jf(t.summary),dp):e===`timelapses`?hp(Nf(t.timelapse),fp):e===`calendar-events`?hp(Jf(t.calendar),pp):Kf(e)&&ai(e)?hp($f(t.event),up):hp(Xf(t.event),up)}function Sp({value:t,family:n,kinds:r,onChange:a,draft:o}){let{t:s}=Y();if(!Lr(n))return null;let c=en(t,r),l=[{id:`activation`,on:c.onActivation,label:s(`system.notificationSystemEventDelivery.whenItStarts`,`When it starts`)},{id:`deactivation`,on:c.onDeactivation,label:s(`system.notificationSystemEventDelivery.whenItClears`,`When it clears`)},{id:`schedule`,on:c.onSchedule!==void 0,label:s(`system.notificationSystemEventDelivery.onASchedule`,`On a schedule`)}],u=V({delivery:`system-event`,conditions:r.length>0?{systemEvent:{kinds:[...r]}}:{},systemEventDelivery:c}).filter(e=>e.code===`no-mode`||e.code===`no-instant-kind`).map(ye);return e(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:s(`system.notificationSystemEventDelivery.delivery`,`Delivery`)}),i(`div`,{className:`flex flex-wrap gap-1.5`,role:`group`,children:l.map(t=>e(`label`,{className:j(re,`cursor-pointer`,t.on?ne:A),children:[i(Xt,{checked:t.on,onChange:e=>a(Mn(c,t.id,e.target.checked)),"data-testid":`rule-delivery-${t.id}`}),t.label]},t.id))}),i(Cp,{modes:c,kinds:r}),u.map(e=>i(`p`,{className:`mt-2 text-[11px] text-danger`,"data-testid":`rule-delivery-problem`,children:e},e)),c.onSchedule!==void 0&&i(wp,{value:c,onChange:a,draft:o})]})}function Cp({modes:t,kinds:n}){let{t:r}=Y(),a=In(n),o=!t.onActivation&&!t.onDeactivation;return e(`div`,{className:`mt-2 space-y-1`,"data-testid":`rule-delivery-hints`,children:[t.onDeactivation&&a.adds.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-clears-hint`,children:r(`system.notificationSystemEventDelivery.clearsAdds`,`When it clears also reports the recovery of: {{what}}.`,{what:a.adds.join(` · `)})}),t.onDeactivation&&a.without>0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-no-clearing-hint`,children:r(`system.notificationSystemEventDelivery.noClearingEvent`,{count:a.without})}),t.onSchedule!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-schedule-hint`,children:o?r(`system.notificationSystemEventDelivery.scheduleOnlyHint`,`Only on a schedule: nothing is sent per event, and the active hours and actions of this rule do not apply.`):r(`system.notificationSystemEventDelivery.scheduleBesideHint`,`The summary is sent at the times below whatever the active hours of this rule say, and runs no actions.`)})]})}function wp({value:t,onChange:n,draft:r}){let{t:a}=Y(),o=t.onSchedule;return o===void 0?null:e(`div`,{className:`mt-2 space-y-2`,children:[i(`p`,{className:yi,children:a(`system.notificationSystemEventDelivery.summaryExplain`,`At each time below, one notification lists what is still true for the kinds and filters of this rule — low batteries, consumables, devices or streams offline, updates available. Nothing to report sends nothing. Time zone: {{timezone}}.`,{timezone:o.schedule.timezone??a(`system.notificationSystemEventDelivery.theHubS`,`the hub’s`)})}),i(Zr,{mode:`times`,value:o.schedule,onChange:e=>{e!==void 0&&n(zn(t,e))}}),i(q,{checked:o.grouping===`section`,onCheckedChange:e=>n(Pn(t,e?`section`:`rule`)),label:a(`system.notificationSystemEventDelivery.onePerCategory`,`One notification per category`),"data-testid":`rule-delivery-grouping`}),i(Tp,{draft:r,split:o.grouping})]})}function Tp({draft:t,split:n}){let{t:r}=Y(),a=N(),o=d({mutationFn:e=>a.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),s=Pr(o.status,o.data,o.error,n);return e(`div`,{className:`space-y-1.5`,children:[i(U,{size:`sm`,variant:`secondary`,onClick:()=>o.mutate(t()),disabled:o.isPending,"data-testid":`rule-delivery-preview`,children:o.isPending?r(`system.notificationSystemEventDelivery.readingTheState`,`Reading the state…`):r(`system.notificationSystemEventDelivery.previewTheSummaryNow`,`Preview the summary now`)}),s!==null&&i(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:s.lines.map((e,t)=>i(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function Ep(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:Ap(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var Dp=6e4,Op=60*Dp,kp=24*Op;function Ap(e){return e===null?J.t(`helpers.notificationRuleLastRun.noDelivery`):e>=kp?J.t(`helpers.notificationRuleLastRun.notInDay`,{count:Math.floor(e/kp)}):e>=Op?J.t(`helpers.notificationRuleLastRun.notInHour`,{count:Math.floor(e/Op)}):e>=Dp?J.t(`helpers.notificationRuleLastRun.notInMinute`,{count:Math.floor(e/Dp)}):J.t(`helpers.notificationRuleLastRun.notInWindow`)}c();var jp=[`notificationRules`,`listRules`],Mp=[`notificationRules`,`getConditionCatalog`],Np=[`deviceManager`,`gateableDevices`],Pp=B.options;function Fp({onSimulateRule:r,onOpenHistory:c,createRequested:l=!1,onCreateConsumed:u,createTypeRequested:f=null,onCreateTypeConsumed:p,headerOwnsCreate:m=!1}={}){let h=N(),{t:g}=Y(),{state:v,openEdit:y,close:b}=ut({editKey:`rule`}),[x,S]=vt(`section`),[C,w]=vt(`editTab`),[T,E]=o({mode:`closed`}),[D,k]=o(!1),A=Uf(x)??`all`,ee=e=>{S(e===`all`?null:e)},j=s({queryKey:jp,queryFn:async()=>(await h.trpcClient.notificationRules.listRules.query({})).rules}),M=t(null);a(()=>{if(T.mode!==`closed`)return;if(v.mode!==`edit`){v.mode===`closed`&&(M.current=null);return}let e=v.id;if(e===`new`||M.current===e)return;let t=j.data?.find(t=>t.id===e);t===void 0||!Cr(t)||(M.current=e,E({mode:`form`,rule:t}))},[T.mode,v,j.data]);let te=Cf(),P=s({queryKey:Mp,queryFn:()=>h.trpcClient.notificationRules.getConditionCatalog.query({})}),ne=st({projection:`slim`}),re=zc(),F=n(()=>ne.data??[],[ne.data]),ie=yt(ne),I=n(()=>F.map(e=>e.id),[F]),ae=s({queryKey:[...Np,I],enabled:I.length>0,queryFn:async()=>{let e=[];for(let t of F){let n=ve(await h.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),Pp);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),oe=n(()=>{let e=Ot(F);return F.filter(e=>Ne(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))},[F]),L=n(()=>F.filter(e=>e.type===he.Camera).map(e=>({id:e.id,name:e.name})),[F]),se=Ni(n(()=>L.map(e=>e.id),[L])),ce=n(()=>{let e=new Map(L.map(e=>[e.id,e.name]));return se.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})))},[se.results,L]),le=n(()=>{let e=new Map;for(let t of te.data??[])e.set(t.id,t.name);return e},[te.data]),ue=d({mutationFn:e=>h.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void j.refetch()}),de=d({mutationFn:e=>h.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void j.refetch()}),fe=Yc(),pe=St({},{refetchInterval:Lp}),me=pe.data??[],R=j.data??[],z=Lf({cameras:L,fleet:ie,targets:te.data??[],taxonomy:P.data?.taxonomy}),ge={events:R,summaries:z.summaries,timelapses:z.timelapses,calendarEvents:z.calendarEvents},_e=Gf(new Map(bn.map(e=>[e.key,cp(e.key,ge)]))),B=_e.find(e=>e.key===A)??_e[0]??bn[0],V=Hf(B.key)?Wf(B.key):void 0;Kf(B.key)&&B.key;let ye=sp(B.key,ge),be=()=>{v.mode===`edit`&&(M.current=v.id),E({mode:`closed`}),b(),w(null)},xe=e=>{if(!Cr(e))return;let t=e.id.length>0?e.id:`new`;M.current=t,E({mode:`form`,rule:e}),y(t),w(null)},Se=e=>{if(qf(e)){M.current=`new`,E({mode:`form`,rule:null,seed:Le(e)}),y(`new`),w(null);return}z.create(e)};a(()=>{f!==null&&(Se(f),p?.())},[f]),a(()=>{l&&(k(!0),u?.())},[l]);let Ce=e=>{if(e.family===`event`){xe(e.rule);return}z.open(e)},we={targetNameById:le,snoozes:fe,actions:me,deletePending:de.isPending,onToggle:(e,t)=>ue.mutate({ruleId:e.id,enabled:t}),onOpen:xe,t:g,onDuplicate:e=>xe({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>de.mutate(e.id),...r?{onTest:r}:{},lastRunOf:e=>Ep(re,e),...c?{onOpenHistory:c}:{}},Te=xp(B.key,{event:we,summary:z.columnDeps.summary,timelapse:z.columnDeps.timelapse,calendar:z.columnDeps.calendar}),Ee=V?.blurb??(`blurb`in B?B.blurb:``),De=V===void 0?`creatable`in B?B.creatable:!1:!0,Oe=m||!De?null:A===`all`?e(U,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:()=>k(!0),children:[i(_,{className:`h-3.5 w-3.5`}),g(`system.notificationRules.newRule`,`New rule`)]}):V===void 0?e(U,{size:`sm`,type:`button`,onClick:()=>Se(B.key),"data-testid":`rules-new-${B.key}`,children:[i(_,{className:`h-3.5 w-3.5`}),`newRuleLabel`in B?B.newRuleLabel:g(`system.notificationRules.newRule`,`New rule`)]}):e(U,{size:`sm`,type:`button`,onClick:()=>Se(V.key===`summaries`?`summary`:V.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":V.key===`summaries`?`summary-new`:V.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[i(_,{className:`h-3.5 w-3.5`}),V.newLabel]});return i(Ti,{embedded:!0,icon:O,title:g(`system.notificationRules.rules`,`Rules`),subtitle:Ee,children:e(`div`,{className:`flex flex-col gap-3`,children:[Oe===null?null:i(`div`,{className:`flex justify-end`,children:Oe}),i(Jt,{appearance:`pills`,value:B.key,onValueChange:e=>ee(Uf(e)??A),children:i(Mt,{children:_e.map(t=>e(Ut,{value:t.key,children:[t.label,i(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:cp(t.key,ge)})]},t.key))})}),i(Dl,{rules:R}),z.notices(B.key),(j.isLoading||z.loading)&&i(Tf,{}),j.isError&&!j.isLoading&&i(G,{title:g(`system.notificationRules.failedToLoadRules`,`Failed to load rules`),message:j.error instanceof Error?j.error.message:g(`system.notificationRules.unknownError`,`Unknown error`),onRetry:()=>void j.refetch()}),!j.isLoading&&!z.loading&&!j.isError&&!z.listFailed(B.key)&&ye.length===0&&i(Ef,{children:V?.emptyHint??(`emptyHint`in B?B.emptyHint:g(`system.notificationRules.noRulesYet`,`No rules yet.`))}),ye.length>0&&i(Df,{columns:Te,rows:ye,rowKey:e=>`${e.family}:${e.id}`,onRowClick:Ce,minWidthPx:lp(B.key)}),T.mode===`form`&&i(Rp,{rule:T.rule,...T.seed?{seed:T.seed}:{},targets:te.data??[],actuatable:oe,fleet:ie,actions:me,actionsAnswered:pe.data!==void 0,catalog:Tn(P.data?.catalog??[]),taxonomy:P.data?.taxonomy,cameras:L,gateable:ae.data??[],gateableScenes:ce,initialEditTab:Ir(C??``)??`rule`,onEditTabChange:e=>w(e===`rule`?null:e),onCancel:be,onSaved:()=>{be(),j.refetch()}}),z.overlays,D?i(Ip,{onCancel:()=>k(!1),onPick:e=>{k(!1),Se(e)}}):null]})})}function Ip({onPick:t,onCancel:n}){let{t:r}=Y();return i(Rt,{open:!0,onClose:n,title:r(`system.notificationRules.chooseARuleType`,`Choose a rule type`),width:`lg`,children:i(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:Vf.map(n=>e(`button`,{type:`button`,"data-testid":`rules-new-${n.type}`,title:n.hint,onClick:()=>t(n.type),className:`flex flex-col items-start gap-1 rounded-lg border border-border bg-surface px-3 py-3 text-left text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[i(`span`,{className:`font-medium text-foreground`,children:n.label}),i(`span`,{className:`text-[10px] font-normal text-foreground-subtle`,children:n.hint})]},n.type))})})}var Lp=1e4;function Rp({rule:t,seed:r,targets:a,catalog:c,taxonomy:l,cameras:u,gateable:p,gateableScenes:m,actuatable:h,fleet:g,actions:_,actionsAnswered:v,initialEditTab:y=Rn,onEditTabChange:b,onSaved:x,onCancel:S}){let C=N(),{t:w}=Y(),E=t!=null&&t.id.length>0,[D]=o(()=>t?cr(t):nr(r?.delivery,r?.conditions)),[k,A]=o(D),[ee,j]=o(null),[M,te]=o(E),[ne,re]=o(null),[F,ie]=o(y),I=e=>A(t=>({...t,...e})),ae=t?yn(t):void 0,L=d({mutationFn:async()=>{let e=Vn(k,ae,c);if(E&&t){let n=Fn(k,c);await C.trpcClient.notificationRules.updateRule.mutate({ruleId:t.id,patch:e,...n.length>0?{clear:n}:{}})}else await C.trpcClient.notificationRules.createRule.mutate({rule:e})},onSuccess:x,onError:e=>j(e instanceof Error?e.message:`Save failed`)}),se=d({mutationFn:async()=>{let e=Vn(k,ae,c);return(await C.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>re(null),onSuccess:e=>re(e),onError:e=>j(e instanceof Error?e.message:`Test failed`)}),ce=k.targetIds.map(e=>a.find(t=>t.id===e)?.name??e),le=s({queryKey:[`notificationOutput`,`listTargetKinds`,`forRuleDelivery`],queryFn:()=>C.trpcClient.notificationOutput.listTargetKinds.query({})}).data??[],de=vs(k.targetIds,a,le),pe=s({queryKey:[`userManagement`,`listUsers`],queryFn:()=>C.trpcClient.userManagement.listUsers.query()}).data,me=n(()=>(pe??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[pe]),R=ar(k),he=R===`immediate-grouped`,z=String(k.groupingSec??20),ge=lr(k).map(e=>({...e,label:e.value===`immediate-grouped`?w(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?w(`notificationRules.grouping.hint`,{n:z,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}}`,z):e.hint})),_e=ge.find(e=>e.value===R)?.hint,B=$r(k,ae),V=Ge(k.delivery),ve=Te({...k.systemEventDelivery===void 0?{}:{systemEventDelivery:k.systemEventDelivery}}),ye=V&&ve.schedule!==null&&!kn(k),be=fe(k),xe=ue(be),Se=Re(be),Ce=tr.filter(e=>Se.includes(e.value)),we=Fe(k.conditions).length>0,Ee=oe(be),De=We(be),Oe=s({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,De??[]],enabled:De!==null,queryFn:async()=>{let e=await Promise.all((De??[]).map(e=>C.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),ke=n(()=>{if(De===null||Oe.data===void 0)return h;let e=Oe.data,t=new Set(wr(k.deviceScope));return h.filter(n=>e.has(n.id)||t.has(n.id))},[h,De,Oe.data,k.deviceScope]),Ae=De!==null&&Oe.isLoading,Me=De!==null&&Oe.isError,Ne=Zo(),Pe=e=>({family:`rule`,field:e,kind:be,delivery:k.delivery,...kn(k)?{systemEventDelivery:`summary`}:{},...k.conditions.systemEvent?{systemEventKinds:[...k.conditions.systemEvent.kinds]}:{}}),Ie=e=>Ne.data?qo(Ne.data,Pe(e)):void 0,Le=nn(k),ze=v?new Set(_.map(e=>e.id)):Mr(k.actions),Be=xn(k.conditions,er(k.actions,_)),Ve=k.conditions.identities!==void 0||k.conditions.plates!==void 0,He=Nn(k.delivery,k.conditions),Ue=He.some(e=>e.key===F)?F:Rn;return Qt(k.delivery)?i(Jt,{value:Ue,onValueChange:e=>{let t=Ir(e);t!==void 0&&(ie(t),b?.(t))},children:e(Rt,{open:!0,onClose:S,title:E?w(`system.notificationRules.edit`,`Edit {{name}}`,{name:t?.name}):w(`system.notificationRules.newNotificationRule`,`New notification rule`),icon:O,error:ee,width:`lg`,testId:`rule-form-dialog`,beforeBody:e(f,{children:[E&&t&&e(`div`,{className:`mb-3 space-y-2`,children:[i(ll,{kind:`rule`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt}),i(fl,{ruleId:t.id,cameraName:e=>u.find(t=>t.id===e)?.name??w(`system.notificationRuleStatus.cameraFallback`,{deviceId:e})})]}),i(Mt,{className:`mb-3`,children:He.map(e=>i(Ut,{value:e.key,children:e.label},e.key))})]}),footer:e(`div`,{className:`flex w-full flex-col gap-3`,children:[Le.length>0&&e(`div`,{"data-testid":`rule-form-dropped`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1 text-left`,children:[i(`p`,{className:`text-foreground`,children:w(`system.notificationRules.savingDrops`,{count:Le.length})}),Le.map(t=>e(`p`,{children:[i(`span`,{className:`text-foreground`,children:t.conditionId}),` — `,t.reason]},t.conditionId))]}),M&&B.length>0?i(`div`,{"data-testid":`rule-form-problems`,className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1 text-left`,children:B.map(e=>i(`p`,{children:e},e))}):null,i(`div`,{className:`flex justify-end gap-2`,children:e(U,{size:`sm`,type:`button`,disabled:L.isPending,onClick:()=>{te(!0),j(null),!(!ir(k,ae,ze)||L.isPending)&&L.mutate()},children:[L.isPending&&i(T,{className:`h-3.5 w-3.5 animate-spin`}),E?w(`system.notificationRules.saveChanges`,`Save changes`):w(`system.notificationRules.createRule`,`Create rule`)]})})]}),children:[e(W,{value:`rule`,className:`space-y-4`,children:[e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.name`,`Name`)}),i(K,{value:k.name,onChange:e=>I({name:e.target.value}),placeholder:w(`system.notificationRules.eGFrontDoorPackage`,`e.g. Front door package`)})]}),e(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[i(q,{checked:k.enabled,onCheckedChange:e=>I({enabled:e}),"aria-label":w(`system.notificationRules.enabled`,`Enabled`)}),w(`system.notificationRules.enabled`,`Enabled`)]})]}),e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.trigger`,`Trigger`)}),i(P,{value:R,onChange:e=>{let t=ri(e.target.value);t&&A(e=>xi(e,t))},options:ge.map(e=>({value:e.value,label:e.label}))}),_e&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:_e}),he&&e(`div`,{className:`mt-2`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),i(K,{type:`number`,min:5,max:60,step:1,value:z,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=yr(e.target.value);t!==void 0&&I({groupingSec:t})}}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),Ve&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`notificationRules.grouping.scopedHint`,{n:z,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,z)})]}),R===`immediate`&&Ve&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!E&&Ee!==void 0&&i(bc,{family:Ee,onChange:e=>A(t=>on(t,e))}),i(lt,{label:w(`system.notificationRules.deliveryTargets`,`Delivery targets`),targets:a,value:k.targetIds,onChange:e=>A(t=>({...t,targetIds:e})),emptyMessage:w(`system.notificationRules.noDeliveryTargetsConfiguredAdd`,`No delivery targets configured. Add one under the Targets tab first.`),testIdPrefix:`rule-target`}),i(hs,{params:de,valueOf:e=>ys(k.targetIds,k.targetParams,e),onChange:(e,t)=>A(n=>({...n,targetParams:bs({targetIds:n.targetIds,targets:a,kinds:le,targetParams:n.targetParams},e,t)}))}),i(Lt,{mode:`multi`,options:me,value:k.targetUsers,onChange:e=>I({targetUsers:e}),searchable:!0,creatable:!1,label:w(`system.notificationRules.notifyUsers`,`Notify users`),description:w(`system.notificationRules.deliversToTheTargetsEach`,`Delivers to the targets each user owns, only for cameras that user can access.`),emptyMessage:w(`system.notificationRules.noUsersToNotify`,`No users to notify.`),placeholder:w(`system.notificationRules.searchUsers`,`Search users…`),testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),e(W,{value:`devices`,className:`space-y-4`,children:[Ae&&i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:w(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Me&&i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:w(`notificationRules.devices.compatFailed`,`Couldn't check which devices this rule's kind can use — every device is listed. The hub still refuses an incompatible one on save.`)}),i(Xs,{devices:ke,scope:k.deviceScope,onChange:e=>I({deviceScope:e}),listState:g.state,savedScope:D.deviceScope,exceptOffered:Dn(c,`devicesExclude`,k)})]}),i(W,{value:`actions`,className:`space-y-4`,children:i(ds,{value:k.actions,onChange:e=>I({actions:e}),actions:_,showProblems:M})}),e(W,{value:`advanced`,className:`space-y-4`,children:[i(Ic,{catalog:c,delivery:k.delivery,conditions:k.conditions,onConditionsChange:e=>I({conditions:e})}),e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.cooldownSeconds`,`Cooldown (seconds)`)}),i(K,{type:`number`,min:0,max:Wn,step:1,value:String(k.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=Nr(e.target.value);t!==void 0&&I({cooldownSec:t})}}),e(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[V?w(`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.`):w(`system.notificationRules.theShortestGapBetweenTwo`,`The shortest gap between two deliveries of this rule, counted as chosen below.`),` `,w(`system.notificationRules.cooldownRange`,{max:String(Wn)})]})]}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.cooldownCounted`,`Cooldown counted`)}),i(P,{value:k.cooldownScope,onChange:e=>{let t=Jr(e.target.value);t!==void 0&&I({cooldownScope:t})},options:bi.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`system.notificationRules.perDeviceADeliveryAbout`,`Per device: a delivery about one camera (or node) does not hold back another. Whole rule: one delivery per cooldown, whichever device matched.`)})]}),e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.acrossObjectClasses`,`Across object classes`)}),i(P,{value:k.cooldownGranularity??`per-class`,onChange:e=>I({cooldownGranularity:hr(e.target.value)}),options:An.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`system.notificationRules.separateDefaultADogAfter`,`Separate (default): a dog after a cat is delivered at once, a second cat still waits. Shared: a cat holds back the next dog for the cooldown. Sounds always count per class.`)})]})]}),e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(q,{checked:k.snoozeAllowGlobal,onCheckedChange:e=>I({snoozeAllowGlobal:e}),"aria-label":w(`system.notificationRules.allowGlobalSnooze`,`allow global snooze`),disabled:Be}),w(`system.notificationRules.anyoneMaySnoozeThisRule`,`Anyone may snooze this rule for everyone`)]}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`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.`)})]}),Un(k)&&e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(q,{checked:k.askVerdict===!0,onCheckedChange:e=>I({askVerdict:e}),"aria-label":w(`system.notificationRules.askVerdictAria`,`ask me to confirm detections`),"data-testid":`rule-ask-verdict`}),w(`system.notificationRules.askVerdict`,`Ask me to confirm detections`)]}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`system.notificationRules.askVerdictHint`,`The notification carries Correct and Wrong. A tap marks the detection for retraining, the same mark as in the Library, and records who was asked and when. Channels with no buttons (email, Pushover, Gotify, WhatsApp, Discord) get the same two choices as links.`)})]}),!Be&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.snoozeButtons`,`Snooze buttons`)}),e(f,{children:[i(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Gn.map(e=>{let t=k.snoozeOptions??jn,n=t.includes(e);return i(U,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>I({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:or(e)},e)})}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:k.snoozeOptions===void 0?w(`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:jn.map(or).join(`, `)}):k.snoozeOptions.length===0?w(`system.notificationRules.noSnoozeButtonsOnThis`,`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`):w(`system.notificationRules.fourAtMostEverySnooze`,`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`)}),k.snoozeOptions!==void 0&&i(U,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>I({snoozeOptions:void 0}),children:w(`system.notificationRules.backToTheDefaults`,`Back to the defaults`)})]})]}),E&&t&&!Be&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.silenceItNow`,`Silence it now`)}),i(Gc,{ruleId:t.id,ruleName:t.name,exempt:Be,variant:`full`})]})]}),e(W,{value:`notification`,className:`space-y-4`,children:[e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.priority`,`Priority`)}),i(P,{value:String(k.priority),onChange:e=>I({priority:Number(e.target.value)}),options:rr.map(e=>({value:String(e.value),label:e.label}))})]}),!xe.carriesMedia&&i(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:xe.mediaBlurb??w(`system.notificationRules.aSystemEventCarriesNo`,`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`)}),xe.carriesMedia&&xe.mediaBlurb!==void 0&&i(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:xe.mediaBlurb}),xe.carriesMedia&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.notificationImage`,`Image`)}),i(P,{value:k.mediaImage,onChange:e=>{let t=si(e.target.value);t&&I({mediaImage:t})},options:Ce.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-image`}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Ce.find(e=>e.value===k.mediaImage)?.description}),e(`div`,{className:`mt-2 space-y-1`,children:[we&&k.mediaImage!==`crop`&&k.mediaImage!==`none`&&e(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(Xt,{checked:k.mediaShowTriggerZone,onChange:e=>I({mediaShowTriggerZone:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-trigger-zone`}),e(`span`,{children:[w(`system.notificationRules.showTriggerZone`,`Draw the zone that triggered the rule`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.showTriggerZoneHelp`,`Outlines the zone on the scene. Not drawn on a subject crop.`)})]})]}),je(be)&&k.mediaImage!==`none`&&e(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(Xt,{checked:k.mediaShowSubjectPath,onChange:e=>I({mediaShowSubjectPath:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-subject-path`}),e(`span`,{children:[w(`system.notificationRules.showSubjectPath`,`Show the subject's path`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.showSubjectPathHelp`,`Draws the line the subject walked, up to the moment of the picture. On a crop, only the part inside it.`)})]})]}),e(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[i(Xt,{checked:k.mediaGif,onChange:e=>I({mediaGif:e.target.checked}),className:`accent-primary`}),w(`system.notificationRules.attachAGifAroundThe`,`Attach a GIF around the event`)]}),e(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[i(Xt,{checked:k.mediaClip,onChange:e=>I({mediaClip:e.target.checked}),className:`accent-primary`}),w(`system.notificationRules.attachAnMp4ClipAround`,`Attach an MP4 clip around the event`)]})]}),(k.mediaGif||k.mediaClip)&&e(`div`,{className:`mt-2`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.videoQuality`,`Video quality`)}),i(P,{value:k.mediaProfile??``,onChange:e=>I({mediaProfile:Kr(e.target.value)}),options:_n.map(e=>({value:e.value,label:e.label}))}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.aNotificationIsWatchedOn`,`A notification is watched on a phone — the cheapest stream is normally the right one, and the high profile only costs CPU to render.`)}),i(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.playbackSpeed`,`Playback speed`)}),i(P,{value:k.mediaClipSpeed===void 0?``:String(k.mediaClipSpeed),onChange:e=>I({mediaClipSpeed:ti(e.target.value)}),options:wn.map(e=>({value:e.value,label:e.label}))}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:w(`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.`)})]})]}),be===`sensor`&&xe.carriesMedia&&k.mediaImage!==`none`&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:w(`system.notificationRules.linkedCameras`,`Linked cameras`)}),i(P,{value:k.mediaLinkedCameras??``,onChange:e=>I({mediaLinkedCameras:Vr(e.target.value)}),options:Sn.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.whenTheSensorIsLinked`,`When the sensor is linked to several cameras, all of them are photographed the moment it fires. Cameras that are offline or asleep are left out.`)}),e(`label`,{className:`mt-2 flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(Xt,{checked:k.mediaWakeSleepingCamera!==!1,onChange:e=>I({mediaWakeSleepingCamera:e.target.checked?void 0:!1}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-wake-sleeping-camera`}),e(`span`,{children:[w(`system.notificationRules.wakeSleepingCamera`,`Wake a sleeping battery camera for the picture`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.wakeSleepingCameraHelp`,`Costs battery and waits up to 15 s before the notification is sent.`)})]})]})]})]}),e(`div`,{className:`space-y-2`,children:[i(ts,{label:w(`system.notificationRules.notificationTitle`,`Notification title`),value:k.templateTitle,onChange:e=>I({templateTitle:e}),vars:Ie(`title`),testId:`rule-template-title`}),i(ts,{label:w(`system.notificationRules.notificationBody`,`Notification body`),value:k.templateBody,onChange:e=>I({templateBody:e}),vars:Ie(`body`),multiline:!0,testId:`rule-template-body`}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.leaveBothBlankForThe`,`Leave both blank for the hub's own wording (editable on the Texts tab).`)}),ur(k)!==null&&i(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:ur(k)}),i(ns,{context:Pe(`body`),title:k.templateTitle,body:k.templateBody,testId:`rule-template-preview`})]}),V&&i(Sp,{value:k.systemEventDelivery,family:Ee,kinds:k.conditions.systemEvent?.kinds??[],onChange:e=>I({systemEventDelivery:e}),draft:()=>Vn(k,ae,c)})]}),e(W,{value:`conditions`,className:`space-y-4`,children:[e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:V?w(`system.notificationRules.whichSystemEvents`,`Which system events`):zr(k.conditions)??w(`system.notificationRules.conditions`,`Conditions`)}),k.conditions.audio!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.thisIsASoundRule`,`This is a SOUND rule: it fires on a confirmed sampling window of audio, never on a picture. Name the sounds and/or keep a level threshold — with neither it can never match. Everything else below still composes (a camera scope, a schedule).`)}),k.conditions.occupancy!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:w(`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.`)}),V&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.pickTheEventsThisRule`,`Pick the events this rule reacts to, then narrow them if you want. Nothing else on a system rule is a condition — there is no detection behind it.`)}),c.length===0?i(`p`,{className:`text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.conditionCatalogUnavailableThisRule`,`Condition catalog unavailable — this rule matches on its trigger and targets alone.`)}):i(xc,{catalog:kn(k)?c.filter(e=>e.id!==`schedule`):c,taxonomy:l,delivery:k.delivery,conditions:k.conditions,classScope:k.classScope,onClassScopeChange:e=>I({classScope:e}),actions:Gr(k.actions),actionStepsOf:e=>_.find(t=>t.id===e)?.steps,savedConditions:D.conditions,schedule:k.schedule,deviceIds:Cn(k),zoneCameraIds:Rs(k.deviceScope,u),cameras:u,fleet:g,allDevices:h,gateable:p,gateableScenes:m,onConditionsChange:e=>I({conditions:e}),onScheduleChange:e=>I({schedule:e}),scheduleOnly:kn(k)})]}),E&&t&&e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:w(`system.notificationRules.testThisRuleForReal`,`Test this rule for real`)}),i(Sl,{ruleId:t.id,ruleName:t.name,variant:`full`,showResult:!0,...Cn(k)[0]===void 0?{}:{fallbackDeviceId:Cn(k)[0]}})]}),ye&&e(`div`,{className:`mt-2 flex items-center justify-between gap-2`,children:[i(`span`,{className:`text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.sendSummaryHint`,`The scheduled summary is sent on its own: to every target, now.`)}),i(Sl,{ruleId:t.id,ruleName:t.name,variant:`full`,showResult:!0,summary:!0})]}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:w(`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.`)})]}),!V&&e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:w(`system.notificationRules.testRule`,`Test rule`)}),e(U,{size:`sm`,variant:`outline`,type:`button`,disabled:se.isPending||!ir(k,ae,ze),onClick:()=>{j(null),se.mutate()},children:[se.isPending?i(T,{className:`h-3.5 w-3.5 animate-spin`}):i(nt,{className:`h-3.5 w-3.5`}),w(`system.notificationRules.dryRunLast60Min`,`Dry-run (last 60 min)`)]})]}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:w(`system.notificationRules.evaluateTheCurrentUnsavedRule`,`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`)}),ne!==null&&i(Bp,{delivery:k.delivery,results:ne,targetNames:ce})]})]})]})}):i(zp,{rule:t,onCancel:S})}function zp({rule:t,onCancel:n}){let{t:r}=Y(),a=Object.keys(t?.conditions??{});return e(Rt,{open:!0,onClose:n,title:t?.name??r(`system.notificationRules.rule`,`Rule`),icon:O,width:`lg`,children:[i(H,{variant:`warning`,className:`mb-3`,children:`read-only`}),i(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,"data-testid":`unsupported-trigger-notice`,children:i(Bn,{i18nKey:`system.notificationRules.unsupportedTrigger`,values:{trigger:t?.delivery},components:{code:i(`code`,{})}})}),e(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.trigger`,`Trigger`)}),i(`dd`,{className:`text-foreground`,children:t?.delivery})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.enabled`,`Enabled`)}),i(`dd`,{className:`text-foreground`,children:t?.enabled?r(`common.yes`):r(`common.no`)})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.targets`,`Targets`)}),i(`dd`,{className:`text-foreground`,children:t?.targets.length??0})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.conditions`,`Conditions`)}),i(`dd`,{className:`text-foreground`,children:a.length>0?a.join(`, `):r(`common.none`)})]})]})]})}function Bp({delivery:t,results:n,targetNames:r}){let{t:a}=Y();if(t===`device-event`)return i(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.deviceEventRulesCannotBe`,`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`)});if(n.length===0)return i(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.noRecordsInTheLast`,`No records in the last 60 minutes matched — nothing to evaluate.`)});let o=n.filter(e=>e.wouldFire).length;return e(`div`,{className:`mt-2 space-y-1.5`,children:[i(`div`,{className:`text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.wouldFire`,{firing:o,count:n.length})}),i(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:n.slice(0,50).map(t=>e(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[t.wouldFire?i(S,{className:`h-3.5 w-3.5 shrink-0 text-success`}):i(h,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(t.timestamp).toLocaleString()}),e(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,t.deviceId]}),i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:t.label??t.className??a(`system.notificationRules.objectFallback`)}),t.wouldFire?e(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,r.join(`, `)||a(`system.notificationRules.targetsFallback`)]}):t.failedCondition&&e(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,t.failedCondition]})]},t.recordId))})]})}var Vp=`alert-center`,Hp=`alerts`;function Up(){let{t}=Y(),n=N();return e(`div`,{className:`space-y-3`,"data-testid":`notification-settings`,children:[i(`p`,{className:F,children:t(`systemPage.notifications.settingsHint`,`Alert storage and retention. Alerts are notified only through notification rules on the alert kinds.`)}),i(dt,{trpc:n.trpcClient,addonId:Vp,cap:Hp,scope:`cluster`,bare:!0})]})}var Wp=[{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 Gp(e){return Wp.find(t=>t.value===e)?.value}function Kp(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function qp(e){return``}var Jp={x:.25,y:.25,w:.5,h:.5},Yp={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Xp(){return{trigger:`object-event`,deviceId:null,sourceDeviceId:null,classNames:[],label:``,confidence:void 0,labelConfidence:void 0,importance:void 0,dwellSeconds:void 0,zones:[],crossingEnabled:!1,crossingZoneId:``,crossingDirection:`enter`,sensorKind:``,eventType:``,packagePhase:``,source:``,bboxEnabled:!1,bbox:Jp,occupancy:Yp,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function Zp(e){return e.deviceId!==null}function Qp(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function $p(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function em(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 tm(e){if(e.deviceId===null)return null;let t=e.trigger,n=$p(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:nm(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 nm(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 rm(e){return Math.min(1,Math.round((e+.05)*100)/100)}function im(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 am(e){let t=Xp(),n=e.conditions,r=im(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:rm(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:rm(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:rm(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:qp(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:om(n.occupancy)},onlyRuleId:e.id}}function om(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 sm(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 cm(e){return{form:am(e),caveats:sm(e),ruleName:e.name}}var lm=null;function um(e){lm=e}function dm(){return lm}function fm(){lm=null}var pm=[`n/a`,`clear`,`suppressed`,`bypassed`],mm=[`live`,`none`,`unavailable`,`unattachable`];function hm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gm(e,t){let n=e[t];return typeof n==`string`?n:void 0}function _m(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function vm(e){if(!hm(e))return null;let t=gm(e,`ruleId`),n=gm(e,`ruleName`),r=gm(e,`cooldown`),i=pm.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=gm(e,`failedCondition`),o=Array.isArray(e.matchedOn)?_m(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:_m(e,`targetIds`)}}function ym(e){if(!hm(e))return null;let t=gm(e,`recordId`),n=gm(e,`delivery`),r=gm(e,`still`),i=mm.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=vm(e);t!==null&&o.push(t)}let s=gm(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:_m(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function bm(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 xm=new Set([`sensor`,`control`,`custom`]);function Sm({form:t,cameras:n,taxonomy:r,kinds:a,kindsLoading:o,onPatch:s}){let{t:c}=Y(),l=t.deviceId===null?[]:[t.deviceId],u=L(`classes`,r);if(t.trigger===`device-event`)return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(Cm,{form:t,kinds:a,loading:o,onPatch:s})]});if(t.trigger===`audio-event`){let r=a.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),e(`div`,{children:[i(`label`,{className:X,children:c(`system.notificationSimulateFields.audioClasses`,`Audio classes`)}),i(Xr,{options:r,value:t.classNames,onChange:e=>s({classNames:e}),loading:o,emptyHint:t.deviceId===null?`Pick a camera first — the audio vocabulary is per camera.`:`This camera advertises no audio kinds. The audio classifier is probably off for it.`,placeholder:c(`system.notificationSimulateFields.audioClassId`,`Audio class id…`)})]}),e(`div`,{children:[i(`label`,{className:X,children:c(`system.notificationSimulateFields.zones`,`Zones`)}),i(pn,{deviceIds:l,cameras:n,value:t.zones,onChange:e=>s({zones:e})})]})]})}return t.trigger===`occupancy-event`?e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(wm,{form:t,cameras:n,taxonomy:r,onPatch:s})]}):e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),e(`div`,{children:[i(`label`,{className:X,children:c(`system.notificationSimulateFields.detectedClasses`,`Detected classes`)}),u===null?i(Qn,{value:t.classNames,placeholder:c(`system.notificationSimulateFields.classIdPersonCar`,`Class id (person, car…)`),onChange:e=>s({classNames:e})}):i(gn,{picker:u,value:t.classNames,onChange:e=>s({classNames:e})})]}),e(`div`,{children:[i(`label`,{className:X,children:c(`system.notificationSimulateFields.zonesTheSubjectIsIn`,`Zones the subject is in`)}),i(pn,{deviceIds:l,cameras:n,value:t.zones,onChange:e=>s({zones:e})})]}),t.trigger===`package-event`&&e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:c(`system.notificationSimulateFields.packagePhase`,`Package phase`)}),i(P,{value:t.packagePhase,options:[{value:``,label:c(`system.notificationSimulateFields.none`,`— none —`)},{value:`delivered`,label:c(`system.notificationSimulateFields.delivered`,`Delivered`)},{value:`picked-up`,label:c(`system.notificationSimulateFields.pickedUp`,`Picked up`)}],onChange:e=>s({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function Cm({form:t,kinds:n,loading:r,onPatch:a}){let{t:o}=Y(),s=n.filter(e=>xm.has(e.category)),c=s.find(e=>e.kind===t.sensorKind);return e(f,{children:[e(`div`,{children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.eventKind`,`Event kind`)}),i(P,{value:t.sensorKind,options:[{value:``,label:r?o(`system.notificationSimulateFields.loadingKinds`,`Loading kinds…`):o(`system.notificationSimulateFields.pickAKind`,`— pick a kind —`)},...s.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=s.find(t=>t.kind===e.target.value);a({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!r&&s.length===0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:t.deviceId===null?o(`system.notificationSimulateFields.pickACameraFirstSensor`,`Pick a camera first — sensor and control kinds come from the devices linked to it.`):o(`system.notificationSimulateFields.thisCameraHasNoLinked`,`This camera has no linked sensor or control device, so it can produce no device event. Link one on the camera page first.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.sourceDevice`,`Source device`)}),i(K,{type:`number`,value:t.sourceDeviceId===null?``:String(t.sourceDeviceId),placeholder:o(`system.notificationSimulateFields.theCameraItself`,`the camera itself`),onChange:e=>a({sourceDeviceId:Qp(e.target.value)??null})}),i(`p`,{className:yi,children:c===void 0?o(`system.notificationSimulateFields.theLinkedDeviceWhoseState`,`The linked device whose state changed. Filled in for you when you pick a kind.`):o(`system.notificationSimulateFields.filledInFromContributedBy`,`Filled in from "{{label}}" — contributed by device #{{deviceId}} via the {{capName}} capability.`,{label:c.label,deviceId:c.source.deviceId,capName:c.source.capName})})]}),e(`div`,{children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.eventTypeToken`,`Event type token`)}),i(K,{value:t.eventType,placeholder:o(`system.notificationSimulateFields.pressPressLong`,`press, press_long…`),onChange:e=>a({eventType:e.target.value})}),i(`p`,{className:yi,children:o(`system.notificationSimulateFields.onlyEventEmitterSourcesCarry`,`Only event-emitter sources carry one. A passive sensor emits none, and a rule gating on a token would fail closed for it.`)})]})]})]})}function wm({form:t,cameras:n,taxonomy:r,onPatch:a}){let{t:o}=Y(),s=t.deviceId===null?[]:[t.deviceId],c=L(`occupancy`,r),l=c===null?[]:c.groups.flatMap(e=>e.options),u=t.occupancy,d=e=>a({occupancy:{...u,...e}});return e(f,{children:[e(`div`,{children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.zone`,`Zone`)}),i(pn,{deviceIds:s,cameras:n,value:u.zoneId===``?[]:[u.zoneId],onChange:e=>d({zoneId:e[e.length-1]??``})}),i(`p`,{className:yi,children:o(`system.notificationSimulateFields.leaveEmptyForTheWhole`,`Leave empty for the whole frame.`)})]}),e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.class`,`Class`)}),i(P,{value:u.className,options:[{value:``,label:o(`system.notificationSimulateFields.anyClass`,`— any class —`)},...l.map(e=>({value:e.value,label:e.label}))],onChange:e=>d({className:e.target.value})})]}),e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countNow`,`Count now`),i(K,{type:`number`,min:0,className:`w-20`,value:String(u.count),onChange:e=>d({count:Qp(e.target.value)??0})})]}),e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countBefore`,`Count before`),i(K,{type:`number`,min:0,className:`w-20`,value:String(u.previousCount),onChange:e=>d({previousCount:Qp(e.target.value)??0})})]}),e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.threshold`,`Threshold`),i(K,{type:`number`,min:1,className:`w-20`,value:String(u.threshold),onChange:e=>d({threshold:Qp(e.target.value)??1})})]}),e(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[i(q,{checked:u.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":o(`system.notificationSimulateFields.occupiedLabel`)}),o(`system.notificationSimulateFields.occupiedLabel`,`Occupied`)]})]})]})}function Tm({form:t,cameras:n,onPatch:r}){let{t:a}=Y(),o=t.deviceId===null?[]:[t.deviceId];return e(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[i(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:a(`system.notificationSimulateFields.advanced`,`Advanced`)}),e(`div`,{className:`mt-2 space-y-3`,children:[t.trigger===`object-event`&&e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(q,{checked:t.crossingEnabled,onCheckedChange:e=>r({crossingEnabled:e}),"aria-label":a(`system.notificationSimulateFields.zoneCrossing`,`zone crossing`)}),a(`system.notificationSimulateFields.thisEventIsAConfirmed`,`This event is a confirmed zone crossing`)]}),t.crossingEnabled&&e(`div`,{className:`mt-1 space-y-1.5`,children:[i(`div`,{className:`max-w-[12rem]`,children:i(P,{value:t.crossingDirection,options:[{value:`enter`,label:a(`system.notificationSimulateFields.enteredTheZone`,`Entered the zone`)},{value:`exit`,label:a(`system.notificationSimulateFields.leftTheZone`,`Left the zone`)}],onChange:e=>r({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),i(pn,{deviceIds:o,cameras:n,value:t.crossingZoneId===``?[]:[t.crossingZoneId],onChange:e=>r({crossingZoneId:e[e.length-1]??``})})]})]}),e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(q,{checked:t.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":a(`system.notificationSimulateFields.boundingBox`,`bounding box`)}),a(`system.notificationSimulateFields.carryABoundingBox`,`Carry a bounding box`)]}),i(`p`,{className:yi,children:a(`system.notificationSimulateFields.normalized01TopLeft`,"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed.")}),t.bboxEnabled&&i(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(n=>e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[n,i(K,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(t.bbox[n]),onChange:e=>r({bbox:{...t.bbox,[n]:Qp(e.target.value)??0}})})]},n))})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:X,children:a(`system.notificationSimulateFields.happenedAt`,`Happened at`)}),e(`div`,{className:`flex items-center gap-2`,children:[i(K,{type:`datetime-local`,value:t.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),t.timestampLocal===``?i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:em(Date.now())}),children:a(`system.notificationSimulateFields.set`,`Set`)}):i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:a(`system.notificationSimulateFields.now`,`Now`)})]}),i(`p`,{className:yi,children:a(`system.notificationSimulateFields.emptyNowSetItTo`,`Empty = now. Set it to a time inside (or outside) a rule's schedule window to test the schedule without waiting for the hour.`)})]}),e(`div`,{children:[i(`label`,{className:X,children:a(`system.notificationSimulateFields.detectionSource`,`Detection source`)}),i(P,{value:t.source,options:[{value:``,label:a(`system.notificationSimulateFields.unsetReadsAsPipeline`,`— unset (reads as pipeline) —`)},{value:`pipeline`,label:a(`system.notificationSimulateFields.pipeline`,`Pipeline`)},{value:`onboard`,label:a(`system.notificationSimulateFields.onboardCamera`,`Onboard (camera)`)},{value:`sensor`,label:a(`system.notificationSimulateFields.sensor`,`Sensor`)},{value:`audio`,label:a(`system.notificationSimulateFields.audio`,`Audio`)}],onChange:e=>{let t=e.target.value;r({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function Em({checked:t,label:n,hint:r,danger:a=!1,onChange:o}){let{t:s}=Y();return e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(q,{checked:t,onCheckedChange:o,"aria-label":n}),n,a&&i(H,{variant:`danger`,children:s(`system.notificationSimulateFields.actuatesDevices`,`actuates devices`)})]}),i(`p`,{className:yi,children:r})]})}c();var Dm={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.`},Om={"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 km({result:t,targetName:n}){let{t:r}=Y();return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[i(`p`,{className:`text-xs font-medium text-foreground`,children:bm(t)}),e(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[i(Am,{recordId:t.recordId}),i(`span`,{children:i(Bn,{i18nKey:`system.notificationSimulateResult.delivery`,values:{value:t.delivery},components:{b:i(`span`,{className:`text-foreground`})}})}),i(`span`,{children:i(Bn,{i18nKey:`system.notificationSimulateResult.candidates`,values:{value:t.candidates},components:{b:i(`span`,{className:`text-foreground`})}})}),i(`span`,{title:Dm[t.still],children:i(Bn,{i18nKey:`system.notificationSimulateResult.still`,values:{value:t.still},components:{b:i(`span`,{className:`text-foreground`})}})}),t.droppedBy!==void 0&&i(H,{variant:`warning`,children:r(`system.notificationSimulateResult.droppedBy`,{by:t.droppedBy})})]}),t.notes.length>0&&i(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:t.notes.map(e=>i(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),t.outcomes.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:i(Bn,{i18nKey:`system.notificationSimulateResult.noRuleEvaluated`,values:{delivery:t.delivery},components:{b:i(`span`,{className:`text-foreground`})}})}):i(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.outcomes.map(e=>i(jm,{outcome:e,targetName:n},e.ruleId))})]})}function Am({recordId:t}){let{t:n}=Y(),[r,a]=o(!1);return e(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[i(`code`,{className:`text-[10px] text-foreground`,children:t}),i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let e=navigator.clipboard;e!==void 0&&e.writeText(t).then(()=>{a(!0),setTimeout(()=>a(!1),1500)},()=>a(!1))},title:n(`system.notificationSimulateResult.copyRecordId`,`Copy record id`),children:i(D,{className:`h-3 w-3`})}),r&&i(`span`,{className:`text-[10px] text-success`,children:n(`common.copiedLower`)})]})}function jm({outcome:t,targetName:n}){let{t:r}=Y();return e(`li`,{className:`space-y-1 px-2.5 py-2`,children:[e(`div`,{className:`flex items-center gap-2`,children:[t.matched?i(S,{className:`h-3.5 w-3.5 shrink-0 text-success`}):i(h,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:t.ruleName}),e(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:Om[t.cooldown],children:[`cooldown: `,t.cooldown]})]}),!t.matched&&i(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:t.failedCondition===void 0?r(`system.notificationSimulateResult.didNotMatchTheEngine`,`Did not match. The engine reported no failing condition id.`):i(Bn,{i18nKey:`system.notificationSimulateResult.failingCondition`,values:{condition:t.failedCondition},components:{code:i(`code`,{className:`text-foreground`})}})}),t.matched&&e(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[r(`system.notificationSimulateResult.enqueued`,{count:t.enqueued}),t.targetIds.length>0?` → ${t.targetIds.map(n).join(`, `)}`:` — ${r(`system.notificationSimulateResult.noTargetResolved`)}`,`.`]}),t.matchedOn!==void 0&&t.matchedOn.length>0&&i(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:r(`system.notificationSimulateResult.matchedOn`,{on:t.matchedOn.join(`, `)})})]})}c();var Mm=`pipeline-analytics`,Nm=`nc.injectTestEvent`;function Pm(){let{t}=Y(),r=N(),[c,l]=o(()=>dm()?.form??Xp()),[u,f]=o(()=>dm()?.caveats??[]),[p,m]=o(()=>dm()?.ruleName??null);a(()=>fm(),[]);let[h,g]=o(null),[_,y]=o(!1),[b,x]=o(null),S=e=>l(t=>({...t,...e})),C=st({projection:`slim`}),w=s({queryKey:Mp,queryFn:()=>r.trpcClient.notificationRules.getConditionCatalog.query({})}),E=s({queryKey:jp,queryFn:async()=>(await r.trpcClient.notificationRules.listRules.query({})).rules}),D=Cf(),O=c.deviceId,k=s({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:O}],enabled:O!==null,staleTime:6e4,queryFn:async()=>O===null?[]:(await r.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[O]})).flatMap(e=>[...e.kinds])}),A=n(()=>(C.data??[]).filter(e=>e.type===he.Camera).map(e=>({id:e.id,name:e.name})),[C.data]),ee=w.data?.taxonomy,j=k.data??[],M=n(()=>{let e=new Map;for(let t of D.data??[])e.set(t.id,t.name);return e},[D.data]),te=d({mutationFn:async()=>{let e=tm(c);if(e===null)throw Error(`Pick a camera first.`);return r.trpcClient.addons.custom.mutate({addonId:Mm,action:Nm,input:e})},onMutate:()=>{g(null),y(!1),x(null)},onSuccess:e=>{let t=ym(e);g(t),y(t===null)},onError:e=>x(e instanceof Error?e.message:`The simulation failed.`)}),ne=Kp(c.trigger),re=E.data?.find(e=>e.id===c.onlyRuleId);return e(Ti,{embedded:!0,icon:nt,title:t(`system.notificationSimulate.simulateAnEvent`,`Simulate an event`),subtitle:t(`system.notificationSimulate.injectASyntheticDetectionDoorbell`,`Inject a synthetic detection, doorbell press or occupancy edge and see exactly which rules match it, which condition each one fails on, and what would be delivered. Nothing is persisted — no track, no event row, no media.`),children:[C.isError&&i(G,{title:t(`system.notificationSimulate.failedToLoadCameras`,`Failed to load cameras`),message:C.error instanceof Error?C.error.message:t(`system.notificationSimulate.unknownError`,`Unknown error`),onRetry:()=>void C.refetch()}),p!==null&&i(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:i(Bn,{i18nKey:`system.notificationSimulate.seededFrom`,values:{rule:p},components:{b:i(`span`,{className:`font-medium`})}})}),u.length>0&&i(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:u.map(t=>e(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[i(v,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),i(`span`,{children:t.note})]},t.conditionId))}),e(ct,{className:`space-y-4`,children:[e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.ruleToSimulate`,`Rule to simulate`)}),i(P,{"data-testid":`simulate-seed-rule`,value:c.onlyRuleId,options:[{value:``,label:t(`system.notificationSimulate.pickARuleToPrefill`,`— pick a rule to prefill trigger + conditions —`)},...(E.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.delivery}`}))],onChange:e=>{let t=e.target.value;if(t.length===0){l(Xp()),f([]),m(null);return}let n=E.data?.find(e=>e.id===t);if(n===void 0){S({onlyRuleId:t});return}l(am(n)),f(sm(n)),m(n.name)}}),i(`p`,{className:yi,children:t(`system.notificationSimulate.picksTheTriggerThatRule`,`Picks the trigger that rule listens for and fills the fields from its conditions. Edit any value below, then inject.`)})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.camera`,`Camera`)}),i(P,{"data-testid":`simulate-camera`,value:c.deviceId===null?``:String(c.deviceId),options:[{value:``,label:A.length===0?t(`system.notificationSimulate.loadingCameras`,`Loading cameras…`):t(`system.notificationSimulate.pickACamera`,`— pick a camera —`)},...A.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{S({deviceId:Qp(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...c.occupancy,zoneId:``}})}}),i(`p`,{className:yi,children:t(`system.notificationSimulate.theCameraTheEventIs`,`The camera the event is attributed to — what a notification shows.`)})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.trigger`,`Trigger`)}),i(P,{"data-testid":`simulate-trigger`,value:c.trigger,options:Wp.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Gp(e.target.value);if(!t)return;let n=qp(c.trigger);S({trigger:t,source:c.source===``||c.source===n?qp(t):c.source})}}),e(`p`,{className:yi,children:[Wp.find(e=>e.value===c.trigger)?.hint,` `,i(Bn,{i18nKey:`system.notificationSimulate.onlyRulesWhoseTrigger`,values:{delivery:ne},components:{b:i(`span`,{className:`text-foreground`})}})]})]}),i(Sm,{form:c,cameras:A,taxonomy:ee,kinds:j,kindsLoading:k.isLoading,onPatch:S}),e(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[i(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:t(`system.notificationSimulate.quality`,`Quality`)}),e(`div`,{className:`mt-2 space-y-3`,children:[i(`p`,{className:yi,children:t(`system.notificationSimulate.everyFieldHereCanBe`,`Every field here can be left EMPTY, and empty is a real state: a rule with a minimum confidence FAILS on a subject that carries none. Leave one blank to reproduce exactly that.`)}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.labelIdentityNamePlateSubclass`,`Label (identity name / plate / subclass)`)}),i(K,{value:c.label,placeholder:t(`system.notificationSimulate.eGMarcoAb123cd`,`e.g. Marco, AB123CD`),onChange:e=>S({label:e.target.value})})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.detectionConfidence`,`Detection confidence`)}),i(gi,{value:c.confidence,min:0,max:1,step:.05,onChange:e=>S({confidence:e})})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.labelMatchConfidence`,`Label-match confidence`)}),i(gi,{value:c.labelConfidence,min:0,max:1,step:.05,onChange:e=>S({labelConfidence:e})})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.importance`,`Importance`)}),i(gi,{value:c.importance,min:0,max:1,step:.05,onChange:e=>S({importance:e})})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.dwellSeconds`,`Dwell (seconds)`)}),i(gi,{value:c.dwellSeconds,min:0,step:1,onChange:e=>S({dwellSeconds:e})})]})]})]})]}),i(Tm,{form:c,cameras:A,onPatch:S}),e(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:t(`system.notificationSimulate.howToRunIt`,`How to run it`)}),i(Em,{checked:c.bypassCooldown,label:t(`system.notificationSimulate.ignoreTheCooldown`,`Ignore the cooldown`),hint:t(`system.notificationSimulate.aRuleThatAlreadyFired`,`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`),onChange:e=>S({bypassCooldown:e})}),i(Em,{checked:c.bypassMute,label:t(`system.notificationSimulate.ignoreMutesAndSnoozes`,`Ignore mutes and snoozes`),hint:t(`system.notificationSimulate.aMutedCameraOrA`,`A muted camera or a snoozed rule drops the event before any rule is consulted.`),onChange:e=>S({bypassMute:e})}),i(Em,{checked:c.runActions,danger:!0,label:t(`system.notificationSimulate.runTheRuleSActions`,`Run the rule's actions — this actuates real devices`),hint:t(`system.notificationSimulate.aMatchedRuleSOntrigger`,`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`),onChange:e=>S({runActions:e})}),e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:X,children:t(`system.notificationSimulate.stillImage`,`Still image`)}),i(P,{value:c.still,options:[{value:`live`,label:t(`system.notificationSimulate.liveSnapshotOfTheCamera`,`Live snapshot of the camera`)},{value:`none`,label:t(`system.notificationSimulate.noImage`,`No image`)}],onChange:e=>S({still:e.target.value===`none`?`none`:`live`})})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.evaluateOnlyOneRule`,`Evaluate only one rule`)}),i(P,{value:c.onlyRuleId,options:[{value:``,label:t(`system.notificationSimulate.everyEnabledRule`,`— every enabled rule —`)},...(E.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>S({onlyRuleId:e.target.value})}),c.onlyRuleId.length>0&&re===void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:i(Bn,{i18nKey:`system.notificationSimulate.ruleNotInList`,values:{id:c.onlyRuleId},components:{code:i(`code`,{})}})})]})]}),b!==null&&i(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:b}),e(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[i(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:t(`system.notificationSimulate.nothingIsPersistedNoTrack`,`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`)}),e(U,{size:`sm`,type:`button`,disabled:te.isPending||!Zp(c),onClick:()=>te.mutate(),children:[te.isPending?i(T,{className:`h-3.5 w-3.5 animate-spin`}):i(nt,{className:`h-3.5 w-3.5`}),t(`system.notificationSimulate.injectEvent`,`Inject event`)]})]})]}),_&&i(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:t(`system.notificationSimulate.theHubAnsweredButThis`,`The hub answered, but this build could not read the answer. That is what a hub older than the simulator looks like — update the server, then re-run.`)}),h!==null&&i(km,{result:h,targetName:e=>M.get(e)??e})]})}var Fm=e=>typeof e==`string`&&e.length>0;function Im(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 Lm(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Rm(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Fm(i)&&n.push({mediaType:r,url:i})}return n}function zm(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Fm(r.label),i=Fm(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 Bm(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Rm(e,t.attachmentUrls),i=zm(e,t.actions),a=e.ttl&&Fm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:Lm(e,t.format),priority:Vm(t.priority),...Fm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Fm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Fm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Fm(t.tag)?{tag:t.tag}:{}}}function Vm(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function Hm(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 Um(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Wm={image:C(`/addon/notifiers/samples/image`),video:C(`/addon/notifiers/samples/video`),gif:C(`/addon/notifiers/samples/gif`),audio:C(`/addon/notifiers/samples/audio`),icon:C(`/addon/notifiers/samples/icon`)};function Gm(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function Km(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])Gm(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function qm(e,t,n){let r=Um(e);return Gm(e,t)?{...r,body:n,attachmentUrls:{[t]:Wm[t]}}:{...r,body:n}}function Jm(e,t){let n=Um(e);switch(t){case`text`:return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetText`)};case`image`:return qm(e,`image`,J.t(`helpers.notificationTestComposer.presetImage`));case`gif`:return qm(e,`gif`,J.t(`helpers.notificationTestComposer.presetGif`));case`video`:return qm(e,`video`,J.t(`helpers.notificationTestComposer.presetVideo`));case`audio`:return qm(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=Hm(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)}}}c();var Ym={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`)}},Xm=`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 Qm({target:t,kind:r,open:a,onClose:s}){let{t:c}=Y(),l=N(),u=n(()=>Im(r.caps),[r.caps]),f=n(()=>Km(r.caps),[r.caps]),[p,m]=o(()=>Um(r.caps)),[h,g]=o(null),_=n(()=>Bm(r.caps,p),[r.caps,p]),v=p.body.length,y=v>u.bodyMaxLen,b=e=>m(t=>({...t,...e})),x=d({mutationFn:()=>l.trpcClient.notificationOutput.testTarget.mutate({addonId:t.addonId,targetId:t.id,sample:Bm(r.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(Jm(r.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 i(xt,{open:a,onOpenChange:e=>!e&&s(),children:e(ht,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[i(Tt,{children:i(Ct,{children:c(`system.notificationTestPanel.testTitle`,{name:t.name,kind:r.label})})}),e(ft,{className:`space-y-4 pr-1`,children:[i(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map(e=>i(U,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>S(e),children:Ym[e]},e))}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[u.levels.length>0&&e(`div`,{children:[i(`label`,{className:Zm,children:c(`system.notificationTestPanel.level`,`Level`)}),e(P,{wrapperClassName:`inline-block w-auto`,className:Xm,value:p.level,onChange:e=>b({level:e.target.value}),children:[i(`option`,{value:``,children:c(`system.notificationTestPanel.deriveFromPriority`,`— derive from priority —`)}),u.levels.map(t=>e(`option`,{value:t.id,children:[t.label,t.ordinal===null?` (${c(`system.notificationTestPanel.qualitative`)})`:` (p${t.ordinal})`]},t.id))]}),(()=>{let t=u.levels.find(e=>e.id===p.level);return t?e(`div`,{className:`mt-1 space-y-1`,children:[t.description&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:t.description}),e(`div`,{className:`flex flex-wrap gap-1`,children:[t.flags?.critical&&i(H,{variant:`danger`,"data-testid":`flag-critical`,children:c(`system.notificationTestPanel.critical`)}),t.flags?.silent&&i(H,{variant:`info`,children:c(`system.notificationTestPanel.silent`)}),t.flags?.noPush&&i(H,{variant:`warning`,children:`no-push`})]}),t.requires&&t.requires.length>0&&e(`p`,{className:`text-[10px] text-warning`,children:[c(`system.notificationTestPanel.requiresTargetConfig`,`Requires target config:`),` `,t.requires.join(`, `)]})]}):null})()]}),e(`div`,{children:[e(`label`,{className:Zm,children:[c(`system.notificationTestPanel.priorityOrdinal`,`Priority (ordinal):`),` `,p.priority]}),i(Dt,{min:1,max:5,step:1,value:p.priority,onChange:e=>b({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":c(`system.notificationTestPanel.priority`)})]})]}),u.formats.length>0&&e(`div`,{children:[i(`label`,{className:Zm,children:c(`system.notificationTestPanel.format`,`Format`)}),i(`div`,{className:`flex flex-wrap gap-2`,children:u.formats.map(t=>e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[i(Nt,{name:`format`,className:`accent-primary`,checked:p.format===t,onChange:()=>b({format:t})}),t]},t))})]}),e(`div`,{children:[i(`label`,{className:Zm,children:c(`system.notificationTestPanel.testTitle`,`Title`)}),i(K,{className:Xm,value:p.title,onChange:e=>b({title:e.target.value})})]}),e(`div`,{children:[e(`label`,{className:Zm,children:[c(`system.notificationTestPanel.body`),` `,e(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,u.bodyMaxLen,y?` — ${c(`system.notificationTestPanel.overflow`)}`:``,`)`]})]}),i(Yt,{className:`${Xm} min-h-[80px] resize-y`,value:p.body,onChange:e=>b({body:e.target.value})})]}),u.attachmentSlots.length>0&&e(`div`,{children:[e(`label`,{className:Zm,children:[c(`system.notificationTestPanel.attachments`),` `,i(`span`,{className:`text-foreground-subtle`,children:u.attachmentMaxBytes?c(`system.notificationTestPanel.attachmentsMetaMb`,{mode:u.attachmentMode,max:u.attachmentMax,mb:Math.round(u.attachmentMaxBytes/1024/1024)}):c(`system.notificationTestPanel.attachmentsMeta`,{mode:u.attachmentMode,max:u.attachmentMax})})]}),i(`div`,{className:`space-y-1.5`,children:u.attachmentSlots.map(t=>e(`div`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:t}),i(K,{className:Xm,placeholder:c(`system.notificationTestPanel.url`,`{{mt}} URL`,{mt:t}),value:p.attachmentUrls[t]??``,onChange:e=>b({attachmentUrls:{...p.attachmentUrls,[t]:e.target.value}})})]},t))})]}),u.showActions&&e(`div`,{children:[i(`label`,{className:Zm,children:c(`system.notificationTestPanel.actionsUpTo`,{max:u.maxActions})}),i(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(u.maxActions,3)},(t,n)=>e(`div`,{className:`flex items-center gap-2`,children:[i(K,{className:Xm,placeholder:c(`system.notificationTestPanel.actionLabelPlaceholder`),value:p.actions[n]?.label??``,onChange:e=>C(n,`label`,e.target.value)}),i(K,{className:Xm,placeholder:c(`system.notificationTestPanel.actionUrlPlaceholder`),value:p.actions[n]?.url??``,onChange:e=>C(n,`url`,e.target.value)})]},n))})]}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[u.showClickUrl&&e(`div`,{children:[i(`label`,{className:Zm,children:c(`system.notificationTestPanel.clickUrl`,`Click URL`)}),i(K,{className:Xm,value:p.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),u.showSound&&e(`div`,{children:[i(`label`,{className:Zm,children:c(`system.notificationTestPanel.sound`,`Sound`)}),i(K,{className:Xm,value:p.sound,onChange:e=>b({sound:e.target.value})})]}),u.showTtl&&e(`div`,{children:[i(`label`,{className:Zm,children:c(`system.notificationTestPanel.ttlSeconds`,`TTL (seconds)`)}),i(K,{className:Xm,type:`number`,value:p.ttl,onChange:e=>b({ttl:e.target.value})})]}),u.showTag&&e(`div`,{children:[i(`label`,{className:Zm,children:c(`system.notificationTestPanel.tag`,`Tag`)}),i(K,{className:Xm,value:p.tag,onChange:e=>b({tag:e.target.value})})]})]}),h&&i($m,{result:h}),e(`details`,{className:`text-[10px]`,children:[i(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:c(`system.notificationTestPanel.payloadPreview`,`Payload preview`)}),i(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),e(mt,{children:[i(U,{variant:`secondary`,size:`sm`,type:`button`,onClick:s,children:c(`common.close`,`Close`)}),e(U,{size:`sm`,type:`button`,disabled:x.isPending||p.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?i(T,{className:`h-3.5 w-3.5 animate-spin`}):i(rt,{className:`h-3.5 w-3.5`}),c(`system.notificationTestPanel.sendTest`,`Send test`)]})]})]})})}function $m({result:t}){let{t:n}=Y(),r=t.renderedAs;return e(`div`,{className:`rounded-md border px-3 py-2 text-xs ${t.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[e(`div`,{className:`flex items-center gap-2 font-medium`,children:[t.success?i(S,{className:`h-3.5 w-3.5 text-success`}):i(h,{className:`h-3.5 w-3.5 text-danger`}),i(`span`,{children:t.success?n(`system.notificationTestPanel.delivered`,`Delivered`):n(`system.notificationTestPanel.failed`,`Failed`)})]}),t.error&&i(`p`,{className:`mt-1 text-danger`,children:t.error}),r&&e(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[i(`dt`,{children:n(`system.notificationTestPanel.resolvedLevel`,`Resolved level`)}),i(`dd`,{className:`text-foreground`,children:r.level}),i(`dt`,{children:n(`system.notificationTestPanel.formatSent`,`Format sent`)}),i(`dd`,{className:`text-foreground`,children:r.format}),i(`dt`,{children:n(`system.notificationTestPanel.attachmentsSent`,`Attachments sent`)}),i(`dd`,{className:`text-foreground`,children:r.attachmentsSent}),i(`dt`,{children:n(`system.notificationTestPanel.actionsSent`,`Actions sent`)}),i(`dd`,{className:`text-foreground`,children:r.actionsSent}),i(`dt`,{children:n(`system.notificationTestPanel.truncated`,`Truncated`)}),i(`dd`,{className:`text-foreground`,children:r.truncated?n(`common.yes`):n(`common.no`)}),i(`dt`,{children:n(`system.notificationTestPanel.dropped`,`Dropped`)}),i(`dd`,{className:`text-foreground`,children:r.dropped.length>0?r.dropped.join(`, `):`—`})]})]})}c();var eh=`ownerUserId`,th=`notification-output`;function nh(e){let t=e.formValues[eh];return typeof t==`string`&&t.length>0?t:null}function rh({row:e}){let{t}=Y(),n=N(),r=bt({functionCap:th}),a=s({queryKey:[`userManagement`,`listUsers`],queryFn:()=>n.trpcClient.userManagement.listUsers.query()});if(e.kind!==`instance`)return null;let o=(r.data??[]).find(t=>t.id===e.id),c=o===void 0?null:nh(o);if(c===null)return i(H,{variant:`default`,children:t(`common.systemWord`,`system`)});if(a.data===void 0&&!a.isError)return i(Gt,{className:`h-3 w-16`});let l=(a.data??[]).find(e=>e.id===c)?.username;return i(`span`,{className:`text-xs text-foreground`,children:l??t(`system.notificationTargets.unknownUser`,`unknown user`)})}function ih(e){return{key:`owner`,header:e,nowrap:!0,notSortableReason:e,render:e=>i(rh,{row:e})}}function ah(){let{t}=Y(),n=N(),a=s({queryKey:[`notificationOutput`,`listTargetKinds`],queryFn:()=>n.trpcClient.notificationOutput.listTargetKinds.query({})}),[c,l]=o(null),u=c===null||c.kindId===void 0?void 0:(a.data??[]).find(e=>e.kind===le(c.kindId??``)&&e.addonId===c.addonId),d=r(e=>i(Pt,{icon:rt,variant:`ghost`,size:`sm`,"aria-label":t(`system.notificationTargets.testTarget`,`Send a test to {{name}}`,{name:e.name}),onClick:()=>l(e)}),[t]),p=c===null||u===void 0?null:{id:c.id,name:c.name,kind:u.kind,addonId:c.addonId,enabled:c.enabled,config:{}};return e(f,{children:[i(Pi,{functionCap:th,icon:te,title:t(`system.notificationTargets.notificationTargets`,`Notification Targets`),subtitle:t(`system.notificationTargets.deliverNotificationsToNtfyPushover`,`Deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more. Each target's kind declares its capabilities; the test panel shows exactly what a message degrades to.`),emptyTitle:t(`system.notificationTargets.emptyTitle`,`No notification targets yet`),emptyDescription:t(`system.notificationTargets.emptyDescription`,`Add a target to deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more.`),addLabel:t(`system.notificationTargets.addTarget`,`Add target`),extraColumns:[ih(t(`system.notificationTargets.owner`,`Owner`))],rowActions:d}),p!==null&&u!==void 0&&i(Qm,{target:p,kind:u,open:!0,onClose:()=>l(null)})]})}c();var oh=`notificationTexts`,sh=`Every sentence the Notification Center can print — and your wording for it.`;function ch({entry:t,value:n,busy:r,onChange:a,onReset:o}){let{t:s}=Y(),c=su(t),l=t.override!==null;return e(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${t.key}`,"data-source":t.source,children:[e(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[i(`code`,{className:`text-xs font-medium`,children:t.key}),l?i(H,{variant:`info`,children:s(`common.customised`)}):null,t.source===`fallback`?i(H,{variant:`warning`,children:s(`system.notificationTexts.englishFallback`,`English fallback`)}):null]}),e(`div`,{className:`flex items-start gap-2`,children:[i(`div`,{className:`flex-1`,children:i(ts,{label:``,value:n,onChange:a,vars:ou(t),disabled:r,testId:`text-input-${t.key}`})}),i(U,{variant:`ghost`,size:`sm`,disabled:r||!l&&n===t.shipped,onClick:o,title:s(`system.notificationTexts.resetToTheShippedWording`,`Reset to the shipped wording`),"data-testid":`text-reset-${t.key}`,children:i(g,{className:`h-3.5 w-3.5`})})]}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[i(`span`,{className:`font-medium`,children:s(`system.notificationTexts.shipped`,`Shipped:`)}),` `,i(`span`,{className:`font-mono`,children:t.shipped})]}),c===null?null:i(`p`,{className:`text-xs text-warning`,children:c})]})}function lh(){let{t}=Y(),r=N(),a=l(),[c,u]=o(null),[f,p]=o(``),[m,h]=o(new Map),[g,_]=o(!1),v=s({queryKey:[oh,c??`hub`],queryFn:async()=>{let e=tu(await r.trpcClient.addons.custom.mutate({addonId:$,action:Kl,input:c===null?{}:{language:c}}));return _(e===null),e}}),y=()=>{h(new Map),a.invalidateQueries({queryKey:[oh]})},b=d({mutationFn:e=>r.trpcClient.addons.custom.mutate({addonId:$,action:ql,input:{language:e}}),onSuccess:y}),S=d({mutationFn:e=>r.trpcClient.addons.custom.mutate({addonId:$,action:Jl,input:e}),onSuccess:y}),C=v.data??null,w=n(()=>C===null?[]:au(C.entries,f),[C,f]);if(v.isLoading)return i(Ti,{embedded:!0,icon:at,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:sh,children:i(T,{className:`h-5 w-5 animate-spin`})});if(v.isError||C===null)return i(Ti,{embedded:!0,icon:at,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:sh,children:i(G,{title:t(`system.notificationTexts.theNotificationTextCatalogIs`,`The notification text catalog is not available on this hub`),message:g?t(`system.notificationTexts.theHubAnsweredSomethingThis`,`The hub answered something this admin build does not understand. Update both and reload.`):t(`system.notificationTexts.thisHubHasNotBeen`,`This hub has not been updated to serve the notification text catalog yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime: notifications keep using the shipped wording.`)})});let E=C.language,D=b.isPending||S.isPending,O=ru(C.entries,m),k=iu(C.entries,m),A=C.entries.filter(e=>e.override!==null).length,ee=C.languages.map(e=>({value:e,label:Yl[e]})),j=(e,t)=>h(n=>new Map(n).set(e,t)),M=e=>j(e.key,e.shipped);return i(Ti,{embedded:!0,icon:at,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:sh,children:e(`div`,{className:`flex flex-col gap-4`,children:[b.isError?i(G,{title:t(`system.notificationTexts.couldNotChangeTheLanguage`,`Could not change the language`),message:String(b.error)}):null,S.isError?i(G,{title:t(`system.notificationTexts.couldNotSave`,`Could not save`),message:String(S.error)}):null,e(ct,{className:`p-4`,children:[e(`div`,{className:`flex flex-wrap items-end gap-6`,children:[e(`div`,{className:`flex flex-col gap-1`,children:[i(`label`,{className:`text-sm font-medium`,children:t(`system.notificationTexts.hubLanguage`,`Hub language`)}),i(`div`,{className:`w-44`,children:i(P,{value:C.activeLanguage,disabled:D,options:ee,onChange:e=>{let t=e.target.value;Xl(t)&&b.mutate(t)},"data-testid":`texts-hub-language`})}),i(`p`,{className:`text-xs text-foreground-subtle`,children:t(`system.notificationTexts.everyNotificationIsWrittenIn`,`Every notification is written in this language.`)})]}),e(`div`,{className:`flex flex-col gap-1`,children:[i(`label`,{className:`text-sm font-medium`,children:t(`system.notificationTexts.editing`,`Editing`)}),i(`div`,{className:`w-44`,children:i(P,{value:E,disabled:D,options:ee,onChange:e=>{let t=e.target.value;Xl(t)&&(h(new Map),u(t))},"data-testid":`texts-editing-language`})}),i(`p`,{className:`text-xs text-foreground-subtle`,children:E===C.activeLanguage?t(`system.notificationTexts.ofTextsCustomised`,`{{overriddenCount}} of {{length}} texts customised.`,{overriddenCount:A,length:C.entries.length}):t(`system.notificationTexts.thisHubDoesNotSpeak`,`This hub does not speak this language — these words are not in use yet.`)})]})]}),i(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:t(`system.notificationTexts.aRuleThatWritesIts`,`A rule that writes its own title or body still overrides everything here — this page is the wording used when a rule does not.`)})]}),e(`div`,{className:`flex flex-wrap items-center gap-3`,children:[e(`div`,{className:`relative min-w-[12rem] flex-1`,children:[i(x,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),i(K,{searchHotkey:!0,value:f,placeholder:t(`system.notificationTexts.searchAKeyOrA`,`Search a key or a sentence…`),onChange:e=>p(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),e(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[w.length,` of `,C.entries.length]}),e(U,{className:`ml-auto`,disabled:D||k===0,onClick:()=>S.mutate({language:E,overrides:O}),"data-testid":`texts-save`,children:[D?i(T,{className:`h-3.5 w-3.5 animate-spin`}):null,k===0?t(`common.save`,`Save`):t(`system.notificationTexts.save`,`Save {{pending}}`,{pending:k})]})]}),i(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?i(`p`,{className:`text-sm text-foreground-subtle`,children:t(`system.notificationTexts.noTextMatchesThatSearch`,`No text matches that search.`)}):w.map(e=>i(ch,{entry:e,value:nu(e,m),busy:D,onChange:t=>j(e.key,t),onReset:()=>M(e)},e.key))})]})})}c();var uh=`simulate`,dh=`rules`,fh=[`instance`,`instance-new`],ph=new Set([dh]);function mh(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function hh(t,n,r){if(t===`mixed`)return;if(t===`all`)return e(U,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:n,children:[i(_,{className:`h-3.5 w-3.5`}),J.t(`systemPage.notifications.newRule`,`New rule`)]});if(Hf(t)){let n=Wf(t),a=mh(t);return a===null?void 0:e(U,{size:`sm`,type:`button`,onClick:()=>r(a),"data-testid":t===`summaries`?`summary-new`:t===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[i(_,{className:`h-3.5 w-3.5`}),n.newLabel]})}let a=bn.find(e=>e.key===t);if(!(a===void 0||!a.creatable))return e(U,{size:`sm`,type:`button`,onClick:()=>r(t),"data-testid":`rules-new-${t}`,children:[i(_,{className:`h-3.5 w-3.5`}),a.newRuleLabel]})}function gh(){let{t:e}=Y(),[t,n]=an(),[r,s]=o(!1),[c,l]=o(null);a(()=>{let e=t.get(`tab`);if(e===null||!Hf(e))return;let r=new URLSearchParams(t);r.set(`tab`,dh),r.set(`section`,e),n(r,{replace:!0})},[t,n]);let u=t.get(`tab`)??`targets`,[d]=vt(`section`),f=Uf(d)??`all`,p=e=>{um(cm(e));let r=new URLSearchParams(t);r.set(`tab`,uh),n(r,{replace:!0})},m=e=>{n(To(t,e.id),{replace:!0})},h=Kn(`/system/notifications`,{t:e,isAdmin:!0})??{icon:te,title:e(`system.notifications`,`Notifications`)},g=()=>s(!1),_=(()=>{if(u===dh)return hh(f,()=>s(!0),e=>l(e))})();return a(()=>{ph.has(u)||(s(!1),l(null))},[u]),i(Si,{icon:h.icon,title:h.title,defaultSection:`targets`,sectionsLabel:`${h.title} sections`,actions:_,sections:[{id:`targets`,label:e(`systemPage.notifications.targets`,`Targets`),content:i(ah,{}),ownedParams:fh},{id:dh,label:e(`systemPage.notifications.rules`,`Rules`),content:i(Fp,{onSimulateRule:p,onOpenHistory:m,headerOwnsCreate:!0,createRequested:u===dh&&r,onCreateConsumed:g,createTypeRequested:u===dh?c:null,onCreateTypeConsumed:()=>l(null)}),ownedParams:[`section`,`rule`,`editTab`]},{id:uh,label:e(`systemPage.notifications.simulate`,`Simulate`),content:i(Pm,{})},{id:yo,label:e(`systemPage.notifications.history`,`History`),content:i(Io,{}),ownedParams:xo},{id:`alarm`,label:e(`systemPage.notifications.alarm`,`Alarm`),content:i(vo,{})},{id:`texts`,label:e(`systemPage.notifications.texts`,`Texts`),content:i(lh,{})},{id:`settings`,label:e(`systemPage.notifications.settings`,`Settings`),content:i(Up,{})}]})}export{gh as NotificationsPage,gh as default};