@camstack/addon-admin-ui 1.2.473 → 1.2.475

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 (174) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +19 -0
  3. package/dist/assets/AddonAssetIcon-BNfqkJPr.js +1 -0
  4. package/dist/assets/Addons-BQclhgQv.js +5 -0
  5. package/dist/assets/AdminPage-UX2_-EVb.js +1 -0
  6. package/dist/assets/AdminSectionedPage-CJhCo7eS.js +1 -0
  7. package/dist/assets/AiProfiles-zhlwR2_B.js +3 -0
  8. package/dist/assets/BrokerForm-B1b0ZQq_.js +1 -0
  9. package/dist/assets/Build-DMVYWc57.js +40 -0
  10. package/dist/assets/Calendars-CPP5G4iE.js +1 -0
  11. package/dist/assets/Cluster-DxeRVsUO.js +1 -0
  12. package/dist/assets/CompositionCreateForm-ZntjBNdS.js +1 -0
  13. package/dist/assets/{CompositionEditorPage-B_ERZESY.js → CompositionEditorPage-CpvZY109.js} +1 -1
  14. package/dist/assets/Data-NzOvsB8O.js +2 -0
  15. package/dist/assets/DeviceDetail-DKGhhLVK.js +2 -0
  16. package/dist/assets/DeviceDoActionFields-CVBUVXjq.js +1 -0
  17. package/dist/assets/Devices-D9OmxxCE.js +1 -0
  18. package/dist/assets/EmbedPlayerPage-u5jZuoCz.js +1 -0
  19. package/dist/assets/HelperWizard-Dape3GuD.js +2 -0
  20. package/dist/assets/History-D-T-XA80.js +1 -0
  21. package/dist/assets/Identity-DmBhBZsL.js +1 -0
  22. package/dist/assets/IntegrationDetail-0C2a7iSq.js +1 -0
  23. package/dist/assets/IntegrationHub-DdxMGRIt.js +1 -0
  24. package/dist/assets/Integrations-aOO9hE39.js +1 -0
  25. package/dist/assets/Integrations-eKDwugCV.js +1 -0
  26. package/dist/assets/Library-DUWYOPjU.js +1 -0
  27. package/dist/assets/Locations-D4YphIdu.js +3 -0
  28. package/dist/assets/Logs-CPgxOarw.js +1 -0
  29. package/dist/assets/MaskShapeCanvas-Cmq6IidK.js +1 -0
  30. package/dist/assets/MotionZonesSettings-CnZg9FTF.js +1 -0
  31. package/dist/assets/MyAccess-BKLOlMok.js +2 -0
  32. package/dist/assets/Network-BT4UeK8H.js +1 -0
  33. package/dist/assets/NodeAddonsSettingsPanel-75hJ0AJM.js +1 -0
  34. package/dist/assets/Notifications-B7JOfwPI.js +1 -0
  35. package/dist/assets/Pipeline-DKfkLPEM.js +1 -0
  36. package/dist/assets/PrivacyMaskSettings-BFWSAVsy.js +1 -0
  37. package/dist/assets/Recordings-OmewxCzq.js +1 -0
  38. package/dist/assets/ScanNetworkModal-hCwvBDMd.js +1 -0
  39. package/dist/assets/SceneMonitorEditor-BVdAyhJk.js +1 -0
  40. package/dist/assets/SessionsList-CTsz8qck.js +2 -0
  41. package/dist/assets/Showroom-DlUMfmmX.js +1 -0
  42. package/dist/assets/System-xDNpG66Z.js +1 -0
  43. package/dist/assets/{Terminal-DYLSrpsL.js → Terminal-BKTT8qvq.js} +3 -3
  44. package/dist/assets/{Viewer-GqkHpMmf.js → Viewer-Cu8oX6VE.js} +1 -1
  45. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BlUFdak1.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-20B8V9NZ.js} +1 -1
  46. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js} +1 -1
  47. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.js-DzoL8nR8.js +1 -0
  48. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.js-BPba2g2p.js +1 -0
  49. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-Cb2QlpvS.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-ZBKFTPET.js} +1 -1
  50. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.js-Cyj0Xie_.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.js-BjdR__nc.js} +3 -3
  51. package/dist/assets/addon-icons-context-BuuVE9Wr.js +1 -0
  52. package/dist/assets/{archive-Bs9ToeWK.js → archive-CfJx72Ya.js} +1 -1
  53. package/dist/assets/{assignment-candidates-e6s6JtrJ.js → assignment-candidates-B51c4fCG.js} +1 -1
  54. package/dist/assets/authed-media-iyqNF0CO.js +1 -0
  55. package/dist/assets/{bell-off-CosUv2Rj.js → bell-off-D1QNHdBJ.js} +1 -1
  56. package/dist/assets/{board-model-BtdRuNBI.js → board-model-4EY3kgfH.js} +1 -1
  57. package/dist/assets/{boxes-CA7Sh4JV.js → boxes-DomeSuUE.js} +1 -1
  58. package/dist/assets/circle-slash-CPzLe6ak.js +1 -0
  59. package/dist/assets/client-fa7ANI4X.js +358 -0
  60. package/dist/assets/{cloud-upload-olZ1M2tJ.js → cloud-upload-J0OXIjbZ.js} +1 -1
  61. package/dist/assets/crop-4oyysRxn.js +1 -0
  62. package/dist/assets/{device-integration-icon-656UPgnE.js → device-integration-icon-BQEjbsKG.js} +1 -1
  63. package/dist/assets/device-picker-model-CsITnnp7.js +1 -0
  64. package/dist/assets/dist-Cwk0eIEi.js +358 -0
  65. package/dist/assets/{dist-G4Cxki3p.js → dist-DcarhQ77.js} +1 -1
  66. package/dist/assets/{eraser-CABcfjb2.js → eraser-DdaeWuQ6.js} +1 -1
  67. package/dist/assets/{format-BYDOzxSv.js → format-Bq6kzos8.js} +1 -1
  68. package/dist/assets/{hard-drive-download-ClcxzAVo.js → hard-drive-download-YerwrGPA.js} +1 -1
  69. package/dist/assets/{hostInit-DXWqqcl-.js → hostInit-B6UQXYd9.js} +1 -1
  70. package/dist/assets/i18n-l_m6iBJW.js +1 -0
  71. package/dist/assets/{icons-BmpL14Dq.js → icons-BBOyPCCy.js} +1 -1
  72. package/dist/assets/{index-BvsP28fN.css → index-B4dcSKZt.css} +1 -1
  73. package/dist/assets/index-Ctkts88E.js +4 -0
  74. package/dist/assets/{key-CURebvKJ.js → key-CunS-V0Z.js} +1 -1
  75. package/dist/assets/{key-round-BTmR8Ca5.js → key-round-DcVl91E5.js} +1 -1
  76. package/dist/assets/{layers-BCzFIxnd.js → layers-BC3a28BZ.js} +1 -1
  77. package/dist/assets/{linked-devices-model-Uzvgx-iv.js → linked-devices-model-CWqnVKj5.js} +1 -1
  78. package/dist/assets/{list-ordered-BpmnL-Ze.js → list-ordered-B_2hLh_-.js} +1 -1
  79. package/dist/assets/location-owned-usage-C3ukxAgd.js +1 -0
  80. package/dist/assets/{log-in-hW2oGppQ.js → log-in-IPEzbjqk.js} +1 -1
  81. package/dist/assets/{memory-stick-DJEnjf6G.js → memory-stick-CUBeuzQu.js} +1 -1
  82. package/dist/assets/{message-square-plus-CZ2oQ3Vr.js → message-square-plus-DHiayOOs.js} +1 -1
  83. package/dist/assets/{mf-entry-bootstrap-0-0c9682e8.js → mf-entry-bootstrap-0-976d3c1a.js} +2 -2
  84. package/dist/assets/{mic-off-KFKpp3gz.js → mic-off-DX_Buyxi.js} +1 -1
  85. package/dist/assets/{monitor-off-Cn5TAK6N.js → monitor-off-Czk3uiUL.js} +1 -1
  86. package/dist/assets/{monitor-smartphone-Jvu4UJGi.js → monitor-smartphone-DhnI06Vd.js} +1 -1
  87. package/dist/assets/mount-CsITnnp7.js +1 -0
  88. package/dist/assets/player-overlays-DfIXPXfC.js +1 -0
  89. package/dist/assets/{recycle-BDm5DJUQ.js → recycle-CIxCuRlw.js} +1 -1
  90. package/dist/assets/remoteEntry-isS_YRZd.js +1 -0
  91. package/dist/assets/{scan-eye-C7MTwcP4.js → scan-eye-CNch-kOQ.js} +1 -1
  92. package/dist/assets/{scissors-BQnPBcjw.js → scissors-DAqmNijF.js} +1 -1
  93. package/dist/assets/{search-x-DEyDFvNT.js → search-x-Bam8bduF.js} +1 -1
  94. package/dist/assets/{send-B3qo7thK.js → send-DTxEr1U2.js} +1 -1
  95. package/dist/assets/{settings-2-C0X8oPpn.js → settings-2-Gykf_Jj2.js} +1 -1
  96. package/dist/assets/{speaker-pcRBhz9y.js → speaker-vU_58Q4N.js} +1 -1
  97. package/dist/assets/src-Cy_bal4g.js +67 -0
  98. package/dist/assets/step-inspector-model-COSP18Eo.js +1 -0
  99. package/dist/assets/{timer-reset-CCky8ePa.js → timer-reset-BfVqeFHK.js} +1 -1
  100. package/dist/assets/{ungroup-iaoDNnXe.js → ungroup-BzhYEwYi.js} +1 -1
  101. package/dist/assets/{unlink-8OutaYJL.js → unlink-DcrSLSGi.js} +1 -1
  102. package/dist/assets/{usb-DL2I9kcC.js → usb-CCxf9eVL.js} +1 -1
  103. package/dist/assets/{use-scenes-feed-4lpCQaI1.js → use-scenes-feed-CCy-Tx5-.js} +1 -1
  104. package/dist/assets/{use-stationary-objects-P_tT9TQq.js → use-stationary-objects-rfvEUY5Q.js} +1 -1
  105. package/dist/assets/useEventInvalidation-CsITnnp7.js +1 -0
  106. package/dist/assets/useNodeUrlSelection-BDqOR0oD.js +1 -0
  107. package/dist/assets/useTranslation-BJr-n0es.js +1 -0
  108. package/dist/assets/user-round-D6lnAuWE.js +1 -0
  109. package/dist/assets/{user-x-DYn__Nok.js → user-x-DNQnP84p.js} +1 -1
  110. package/dist/assets/{video-BcVXMTle.js → video-FHJCba2c.js} +1 -1
  111. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CXWzeD1i.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BBtNcF2c.js} +2 -2
  112. package/dist/index.html +11 -11
  113. package/dist/server/addon.js +145 -8
  114. package/package.json +4 -2
  115. package/dist/assets/AddonAssetIcon-DmwaRNVP.js +0 -1
  116. package/dist/assets/Addons-Ch5dCeth.js +0 -4
  117. package/dist/assets/AdminPage-B-1YjUaD.js +0 -1
  118. package/dist/assets/AdminSectionedPage-DCas2jUy.js +0 -1
  119. package/dist/assets/AiProfiles-ChvfjsXv.js +0 -3
  120. package/dist/assets/BrokerForm-x5UJk9ci.js +0 -1
  121. package/dist/assets/Build-CUVwS9XA.js +0 -40
  122. package/dist/assets/Calendars-BMLzvBb6.js +0 -1
  123. package/dist/assets/Cluster-DaFXU71S.js +0 -1
  124. package/dist/assets/CompositionCreateForm-BxelZLtf.js +0 -1
  125. package/dist/assets/Data-CMHfgMXt.js +0 -2
  126. package/dist/assets/DeviceDetail-CAtDRoZZ.js +0 -2
  127. package/dist/assets/DeviceDoActionFields-BETAvCYe.js +0 -1
  128. package/dist/assets/Devices-C1DTPVnZ.js +0 -1
  129. package/dist/assets/EmbedPlayerPage-Bw6TIHbX.js +0 -1
  130. package/dist/assets/History-BXTYUTxj.js +0 -1
  131. package/dist/assets/Identity-DTOixhZS.js +0 -1
  132. package/dist/assets/IntegrationDetail-CnINeomo.js +0 -1
  133. package/dist/assets/IntegrationHub-DahW4X5K.js +0 -1
  134. package/dist/assets/Integrations-Dex6zRMx.js +0 -1
  135. package/dist/assets/Integrations-HN2iCOqd.js +0 -1
  136. package/dist/assets/Library-gaMbp-Fr.js +0 -1
  137. package/dist/assets/Locations-haT1EJbm.js +0 -3
  138. package/dist/assets/Logs-CtH4NMql.js +0 -1
  139. package/dist/assets/MaskShapeCanvas-Byp9XgNC.js +0 -1
  140. package/dist/assets/MotionZonesSettings-C35beRsS.js +0 -1
  141. package/dist/assets/MyAccess-Dj5hcaLN.js +0 -2
  142. package/dist/assets/Network-D-v-cA54.js +0 -1
  143. package/dist/assets/NodeAddonsSettingsPanel-CW_M8Xge.js +0 -1
  144. package/dist/assets/Notifications-r5w4Ne2O.js +0 -1
  145. package/dist/assets/Pipeline-C85hColk.js +0 -1
  146. package/dist/assets/PrivacyMaskSettings-SPaH91xV.js +0 -1
  147. package/dist/assets/Recordings-ZYwRaSrC.js +0 -1
  148. package/dist/assets/ScanNetworkModal-ClvLQ-ol.js +0 -1
  149. package/dist/assets/SceneMonitorEditor-BvqnlZ2i.js +0 -1
  150. package/dist/assets/SessionsList-BCDysQfs.js +0 -2
  151. package/dist/assets/Showroom-jPZcBd6K.js +0 -1
  152. package/dist/assets/System-B5Ny1ozj.js +0 -1
  153. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.js-DdJYWyu3.js +0 -1
  154. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.js-DPkvGqVU.js +0 -1
  155. package/dist/assets/addon-icons-context-BUi2hqSA.js +0 -1
  156. package/dist/assets/authed-media-BWhmwHt2.js +0 -1
  157. package/dist/assets/circle-slash-0Ca1BMK0.js +0 -1
  158. package/dist/assets/client-DIBstlq5.js +0 -358
  159. package/dist/assets/crop-BZM3UFyT.js +0 -1
  160. package/dist/assets/device-picker-model-yjEyEWyS.js +0 -1
  161. package/dist/assets/dist-D6Fj77pb.js +0 -358
  162. package/dist/assets/event-targets-CHOtaC2B.js +0 -2
  163. package/dist/assets/i18n-D3CF2V_j.js +0 -1
  164. package/dist/assets/index-Cskol4XA.js +0 -4
  165. package/dist/assets/location-owned-usage-ChLz8liX.js +0 -1
  166. package/dist/assets/mount-yjEyEWyS.js +0 -1
  167. package/dist/assets/player-overlays-B_ZfVBiA.js +0 -1
  168. package/dist/assets/remoteEntry-7WZh94sn.js +0 -1
  169. package/dist/assets/src-BVr0SnD-.js +0 -67
  170. package/dist/assets/step-inspector-model-DjRSZkVO.js +0 -1
  171. package/dist/assets/useEventInvalidation-yjEyEWyS.js +0 -1
  172. package/dist/assets/useNodeUrlSelection-CiraZrDp.js +0 -1
  173. package/dist/assets/useTranslation-D3Is_4B6.js +0 -1
  174. package/dist/assets/user-round-4ZziAKb6.js +0 -1
@@ -1 +0,0 @@
1
- import{$ as e,B as t,G as n,J as r,S as i,a,b as o,o as s,p as c,q as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{Fr as f,It as p,Li as m,Nt as h,Q as g,Ri as _,Zr as v,bn as y,fn as b,hi as x,kn as S,mi as C,mr as w,or as T,ot as E,sa as D,sn as O,xn as k,yn as A,yr as j,z as M}from"./player-overlays-B_ZfVBiA.js";import{A as N,B as P,C as F,Ct as I,D as ee,E as te,H as L,J as ne,K as R,M as re,Mt as ie,O as z,Ot as ae,P as oe,Q as se,R as ce,S as le,Sn as ue,St as de,Tt as fe,U as pe,V as me,X as he,Y as ge,_t as _e,bt as ve,dn as ye,ft as be,gt as B,hr as xe,jt as Se,ki as Ce,lt as we,mt as Te,q as Ee,st as De,ut as Oe,vr as ke,w as Ae,xt as je,yr as Me,yt as Ne,z as Pe}from"./client-DIBstlq5.js";import{D as Fe,F as Ie,M as Le,O as Re,j as ze,v as Be,y as Ve}from"./__vite-browser-external-BlMfPwfH.js";import{t as He}from"./bell-off-CosUv2Rj.js";import{h as Ue}from"./video-BcVXMTle.js";import{n as We,t as Ge}from"./send-B3qo7thK.js";import{n as Ke,r as qe,t as Je}from"./list-ordered-BpmnL-Ze.js";import{B as Ye,Bn as Xe,Cn as Ze,G as Qe,Gu as V,H as $e,Hn as et,Hr as tt,I as nt,K as rt,Kr as it,L as at,R as ot,Rn as st,Sn as ct,Tr as H,V as lt,Vn as ut,Wr as U,Xu as W,Zr as G,_r as dt,ar as ft,br as pt,dr as mt,fr as ht,ft as gt,gr as _t,ha as vt,hr as yt,ic as bt,kt as xt,lo as St,mt as Ct,nc as wt,oc as Tt,or as Et,pr as Dt,pt as Ot,qr as kt,tc as At,tn as jt,xt as Mt,z as Nt,zn as K}from"./src-BVr0SnD-.js";import{t as q}from"./i18n-D3CF2V_j.js";import{t as J}from"./useTranslation-D3Is_4B6.js";import"./mount-yjEyEWyS.js";import{$ as Pt,$t as Ft,An as It,At as Lt,B as Rt,Bn as zt,Bt,C as Vt,Cn as Ht,Ct as Ut,Dn as Wt,Dt as Gt,En as Kt,Et as qt,F as Jt,Fn as Yt,Ft as Xt,G as Zt,Gn as Qt,Gt as $t,H as en,Hn as tn,Ht as nn,I as rn,In as an,It as on,J as sn,Jn as cn,Jt as ln,K as Y,Kn as un,Kt as dn,L as fn,Ln as pn,Lt as mn,Mn as hn,Mt as gn,Nn as _n,Nt as vn,On as yn,Ot as bn,Pn as xn,Pt as Sn,Q as Cn,Qt as wn,R as Tn,Rn as En,Rt as Dn,S as On,Sn as kn,St as An,Tn as jn,Tt as Mn,U as Nn,Un as Pn,Ut as Fn,V as In,Vn as Ln,Vt as Rn,W as zn,Wn as Bn,Wt as Vn,X as Hn,Xn as Un,Xt as Wn,Y as Gn,Yn as Kn,Yt as qn,Z as Jn,Zn as Yn,Zt as Xn,_n as Zn,_t as Qn,an as $n,at as er,bn as tr,bt as nr,cn as rr,ct as ir,dn as ar,dt as or,en as sr,et as cr,fn as lr,ft as ur,gn as dr,gt as fr,hn as pr,ht as mr,in as hr,it as gr,jn as _r,jt as vr,kn as yr,kt as br,ln as xr,lr as Sr,lt as Cr,mn as wr,mr as Tr,mt as Er,nn as Dr,nt as Or,on as kr,ot as Ar,pn as jr,pt as Mr,q as Nr,qn as Pr,qt as Fr,rn as Ir,rt as Lr,sn as Rr,st as zr,tn as Br,tt as Vr,un as Hr,ur as Ur,ut as Wr,vn as Gr,vt as Kr,wn as qr,wt as Jr,x as Yr,xn as Xr,xt as Zr,yn as Qr,yt as $r,z as ei,zn as ti,zt as ni}from"./index-Cskol4XA.js";import{t as ri}from"./AdminSectionedPage-DCas2jUy.js";import{t as ii}from"./DeviceDoActionFields-BETAvCYe.js";import"./device-picker-model-yjEyEWyS.js";import{t as ai}from"./AdminPage-B-1YjUaD.js";import{n as oi}from"./format-BYDOzxSv.js";import{t as si}from"./use-scenes-feed-4lpCQaI1.js";e();var ci=[`contact`,`cover`,`lock-control`,`switch`];function li(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 ui(e){let t=new Set(li(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 di(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function fi(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=>lt([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?q.t(`uiLibrary.devicePicker.deviceId`,{id:e}):Nt(t,`device`,Vt))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function pi(e){let t=e.name.trim();return t===``?q.t(`uiLibrary.devicePicker.deviceId`,{id:e.deviceId}):t}function mi(e){return e===0?q.t(`helpers.alarmNonblocking.refusedNoName`):q.t(`helpers.alarmNonblocking.refusedOpen`)}var hi={home:`Home`,away:`Away`,night:`Night`};function gi(e){return hi[e]??e}function _i(e,t){if(e<=0)return t;if(e<60)return`${e} s`;let n=Math.floor(e/60),r=e%60;return r===0?q.t(`helpers.notificationAlarm.delayMin`,{minutes:n}):q.t(`helpers.notificationAlarm.delayMinSec`,{minutes:n,seconds:r})}function vi(e,t){if(e.ruleCount===0)return q.t(`helpers.notificationAlarm.armsNothing`);if(e.allDevices&&e.allDevicesExcept.length>0){let n=e.allDevicesExcept.map(t);return q.t(`helpers.notificationAlarm.allExcept`,{count:n.length,names:n.join(`, `)})}return e.allDevices?q.t(`helpers.notificationAlarm.everyDevice`,{count:e.ruleCount}):e.deviceIds.length===0?q.t(`helpers.notificationAlarm.noRestriction`,{count:e.ruleCount}):e.deviceIds.map(t).join(`, `)}function yi(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${bi[e.reason]})`);return q.t(`helpers.notificationAlarm.skipped`,{count:e.length,parts:n.join(`, `)})}var bi={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function xi(e){return e.ruleCount===0}function Si(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 Ci=2e3,wi=15e3,Ti=new Set([`arming`,`pending`,`triggered`]);function Ei(e){return e!==void 0&&Ti.has(e)?Ci:wi}var Di={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 Oi(e){let t=Di[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${gi(e.targetMode)}`}function ki(e){return e!==`disarmed`}function Ai(e){return e===`open`?q.t(`helpers.notificationAlarm.phaseOpen`):q.t(`helpers.notificationAlarm.phaseClosed`)}function ji(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Mi(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Ni(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function Pi(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 Fi(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 Ii(e,t,n,r){let i=Pi(e,t,n);return r==="default"?i===void 0?null:Fi(t,n,null):i===r?null:Fi(t,n,r)}function Li(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=Ee(e,t),a=r!==n,o=n!==`doNothing`&&i.triggeredDurationSec===0;return!a&&!o?null:{mode:t,...a?{postTriggeredAction:n}:{},...o?{triggeredDurationSec:30}:{}}}function Ri(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 zi=[`unknown-refusal`,`stale`,`expired`,`used`];function Bi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vi(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Bi(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 Hi(e){if(!Bi(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Vi(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Vi(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=zi.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var Ui={"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 Wi(e){return Ui[e]}function Gi(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 Ki=`pipeline-analytics`,qi=`The hub answered something this build cannot read — refresh after updating.`;function Ji(e){return e instanceof Error?e.message:String(e)}function Yi(e){return e.map(e=>`${pi(e)} (${e.state})`).join(`, `)}function Xi({live:e,onChanged:t}){let{t:n}=J(),a=E(),[o,s]=r(null),[c,l]=r(null),[f,p]=r(null),m=(e,t)=>a.trpcClient.addons.custom.mutate({addonId:Ki,action:e,input:t}),h=e=>{if(e===null){l(qi);return}if(e.outcome===`refused`){s({refusalId:e.refusalId,blocking:e.blocking});return}if(s(null),e.outcome===`rejected`){l(`Arm anyway was not accepted: ${Wi(e.reason)}.`);return}if(e.outcome===`outside-schedule`){l(`Outside this mode's activation schedule — arm during an allowed window.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;p(e.excluded.length===0?`${t}.`:`${t} — excluded: ${Yi(e.excluded)}.`)},g=()=>{l(null),p(null)},_=u({mutationFn:async e=>Hi(await m(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>l(Ji(e)),onSettled:t}),v=u({mutationFn:async e=>Hi(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>l(Ji(e)),onSettled:t}),y=u({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{g(),s(null)},onSuccess:()=>p(`Disarmed.`),onError:e=>l(Ji(e)),onSettled:t});if(e===void 0)return i(pt,{className:`p-4`,children:[d(`h3`,{className:`text-sm font-semibold mb-1`,children:n(`system.alarmLiveCard.panel`,`Panel`)}),d(`p`,{className:`text-sm text-foreground-subtle`,children:n(`system.alarmLiveCard.thisHubDoesNotReport`,`This hub does not report the panel's live state yet — update it to arm from here.`)})]});let b=_.isPending||v.isPending||y.isPending;return i(pt,{className:`p-4`,children:[i(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[i(`div`,{children:[d(`h3`,{className:`text-sm font-semibold`,children:n(`system.alarmLiveCard.panel`,`Panel`)}),d(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:Oi(e)})]}),i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?d(T,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>d(U,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:n(`system.alarmLiveCard.arm`,{mode:gi(e)})},e)),d(U,{type:`button`,size:`md`,variant:ki(e.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:n(`system.alarmLiveCard.disarm`,`Disarm`)})]})]}),c===null?null:d(`div`,{className:`mt-3`,children:d(H,{title:n(`system.alarmLiveCard.thePanelDidNotDo`,`The panel did not do that`),message:c})}),f===null?null:d(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:f}),o===null?null:i(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[d(`p`,{className:`text-sm font-medium`,children:mi(o.blocking.length)}),o.blocking.length>0?d(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:o.blocking.map(e=>i(`li`,{children:[pi(e),` `,i(`span`,{className:`text-foreground-subtle`,children:[`(`,e.state,`)`]})]},e.deviceId))}):null,i(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[d(U,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(o.refusalId),children:n(`system.alarmLiveCard.armAnyway`,`Arm anyway`)}),d(`span`,{className:`text-xs text-foreground-subtle`,children:n(`system.alarmLiveCard.eachOpenDeviceIsIgnored`,`Each open device is ignored until it closes, then monitored again.`)})]})]}),i(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[d(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:n(`system.alarmLiveCard.excludedSensors`,`Excluded sensors`)}),e.exclusions.length===0?d(`p`,{className:`text-sm text-foreground-subtle`,children:n(`system.alarmLiveCard.noSensorIsExcluded`,`No sensor is excluded.`)}):d(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:e.exclusions.map(e=>i(`li`,{children:[pi(e),` —`,` `,d(`span`,{className:`text-foreground-subtle`,children:Ai(e.phase)})]},e.deviceId))})]})]})}e();var Zi=[{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:xe,zeroMeansKey:`system.alarmDelay.sirenZero`}];function Qi(e){return q.t(`system.alarmDelay.rangeError`,{max:e})}function $i(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${Qi(t)}`}function ea({label:e,value:t,max:n,zeroMeans:a,disabled:o,testId:s,hint:c,adornment:l,onCommit:u}){let[f,p]=r(null),[m,h]=r(null),g=f??String(t),_=f!==null&&f.trim()!==``&&Si(f,n)===null,v=_i(t,a),y=()=>{let e=f===null?null:Si(f,n);p(null),e===null?f!==null&&h(f):(h(null),u(e))};return i(Mt,{label:e,...c===void 0?{}:{description:c},..._?{error:Qi(n)}:m===null?{}:{error:$i(m,n)},children:[i(`div`,{className:`flex items-center gap-2`,children:[d(W,{type:`number`,min:0,max:n,value:g,disabled:o,state:_||m!==null?`error`:`default`,"aria-label":e,onChange:e=>{h(null),p(e.target.value)},onBlur:y,className:`w-20`,"data-testid":s}),d(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),l]}),v===`${t} s`?null:d(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function ta(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=rt(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function na(e){switch(e.kind){case`checking`:return{word:q.t(`system.alarmSensorTable.cellChecking`),note:null};case`hub-too-old`:return{word:q.t(`system.alarmSensorTable.cellUnknown`),note:q.t(`system.alarmSensorTable.cellHubTooOld`)};case`read-failed`:return{word:q.t(`system.alarmSensorTable.cellUnknown`),note:q.t(`system.alarmSensorTable.cellReadFailedError`,{error:e.error})};case`open`:case`closed`:return{word:e.word,note:e.offline?q.t(`system.alarmSensorTable.cellOfflineLastKnown`):null};case`unknown`:return{word:q.t(`system.alarmSensorTable.cellUnknown`),note:e.why===`not-answered`?q.t(`system.alarmSensorTable.cellNotAnswered`):e.why===`read-failed`?q.t(`system.alarmSensorTable.cellReadFailed`):q.t(`system.alarmSensorTable.cellNoState`)};case`not-opening`:return{word:q.t(`system.alarmSensorTable.cellNotOpening`),note:null};case`removed`:return{word:q.t(`system.alarmSensorTable.cellRemoved`),note:q.t(`system.alarmSensorTable.cellRemovedNote`)}}}function ra(){return q.t(`system.alarmSensorTable.listedUncovered`)}function ia(e){return e.listedUncovered?{word:q.t(`system.alarmSensorTable.cellNo`),note:ra()}:aa(e.coverage)}function aa(e){switch(e.kind){case`arm-checked`:return{word:q.t(`system.alarmSensorTable.cellYes`),note:null};case`arm-checked-skipped`:{let t=e.reason===`detection-off`?q.t(`system.alarmSensorTable.detectionOff`):e.reason;return{word:q.t(`system.alarmSensorTable.cellSkipped`),note:q.t(`system.alarmSensorTable.cellSkippedNote`,{why:t})}}case`unscoped`:return{word:q.t(`system.alarmSensorTable.cellAllDevices`),note:q.t(`system.alarmSensorTable.cellNeverBlocks`)};case`not-covered`:return{word:q.t(`system.alarmSensorTable.cellNo`),note:q.t(`system.alarmSensorTable.cellNeverBlocks`)}}}function oa(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 sa(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 ca({name:e,variant:t,words:n}){return i(`span`,{"data-testid":`alarm-cell-${e}`,className:`flex flex-col items-start gap-0.5`,children:[d(G,{variant:t,"data-testid":`alarm-cell-${e}-badge`,children:n.word}),n.note===null?null:d(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${e}-note`,children:n.note})]})}var la=`hidden sm:table-cell`;function ua(e){let{mode:t,inFlight:n,onSwitch:r,zones:a,disabled:o}=e;return[{key:`name`,header:q.t(`system.alarmSensorTable.name`,`Name`),cell:e=>{let t=ta(e.device.location,a);return i(`span`,{className:`flex min-w-0 flex-col`,"data-testid":`alarm-cell-name`,"data-muted":e.listedUncovered?`true`:void 0,children:[d(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.device.name}),t===``?null:d(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:t})]})}},{key:`type`,header:q.t(`system.alarmSensorTable.type`,`Type`),headerClassName:la,cellClassName:`${la} text-[11px] text-foreground-subtle`,cell:e=>Qe(e.device.type??null,Vt)},{key:`state`,header:q.t(`system.alarmSensorTable.state`,`State`),cell:e=>d(ca,{name:`state`,variant:oa(e.cell),words:na(e.cell)})},{key:`coverage`,header:q.t(`system.alarmSensorTable.checkedWhenArming`,`Checked when arming`),headerClassName:la,cellClassName:la,cell:e=>d(ca,{name:`coverage`,variant:sa(e),words:ia(e)})},{key:`blocks`,header:q.t(`system.alarmSensorTable.blocksArming`,`Blocks arming`),headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{let a=n!==null&&n.mode===t&&n.deviceId===e.device.id&&n.kind===`blocks`,s=n!==null&&!a;return i(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?d(T,{className:`h-3 w-3 animate-spin`}):null,d(et,{checked:e.blocks,onCheckedChange:t=>r(e,`blocks`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-blocks`,"aria-label":q.t(`system.alarmSensorTable.blocksArming2`,`Blocks arming: {{name}}`,{name:e.device.name}),"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}},{key:`secure`,header:d(`span`,{title:q.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),children:q.t(`system.alarmSensorTable.secureOnArm`,`Secure on arm`)}),headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{if(!e.controllable)return d(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let a=n!==null&&n.mode===t&&n.deviceId===e.device.id&&n.kind===`secureOnArm`,s=n!==null&&!a;return i(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?d(T,{className:`h-3 w-3 animate-spin`}):null,d(et,{checked:e.secureOnArm,onCheckedChange:t=>r(e,`secureOnArm`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-secure`,"aria-label":q.t(`system.alarmSensorTable.secureOnArmCloseLock`,`Secure on arm (close/lock/off): {{name}}`,{name:e.device.name}),title:q.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}}]}function da(e){let{t}=J(),n=D(),{mode:r,rows:a,sensorsRetry:o,zones:s}=e;return i(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${r}`,children:[o===null?null:i(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[d(`span`,{children:t(`system.alarmSensorTable.couldNotReadTheSensor`,`Could not read the sensor states.`)}),d(U,{type:`button`,size:`sm`,variant:`outline`,onClick:o,children:t(`common.retry`,`Retry`)})]}),d(xt,{mode:`generic`,items:a,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,ta(e.device.location,s),Qe(e.device.type??null,n)].join(` `),getFilterType:e=>Qe(e.device.type??null,n),columns:ua(e),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:t(`system.alarmSensorTable.searchSensors`,`Search sensors`),emptyLabel:`No sensor matches.`})]})}var fa=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function pa(e){return fa.some(t=>t.test(e))}function ma(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return pa(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 ha(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 ga(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 _a(e){return e.kind===`unscoped`||e.kind===`not-covered`}function va(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=ga(e.coverage,r.id),a=ha(e.sensors,r.id,t,r.type),o=ge({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=he({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&&_a(i)&&(!o||c)&&c;!t&&_a(i)&&!c||n.push({device:r,removed:t,cell:ma(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function ya(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function ba(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 xa(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 Sa(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 Ca(e,t){return R(Sa(e),t)?{kind:`landed`}:{kind:`not-landed`}}var wa=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function Ta({coverage:e,settings:t,disabled:n,onNotifyEdit:r}){let{t:a}=J(),o=ne(t,e.mode);return i(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${e.mode}`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:a(`notificationRules.alarmNotify.title`)}),wa.map(({field:t,key:s})=>i(`div`,{className:`flex items-start justify-between gap-3`,children:[i(`div`,{className:`min-w-0`,children:[d(`p`,{className:`text-xs text-foreground`,children:a(`notificationRules.alarmNotify.${s}`)}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:a(`notificationRules.alarmNotify.${s}Hint`)})]}),d(et,{checked:o[t],onCheckedChange:e=>r(t,e),disabled:n,"data-testid":`alarm-notify-${e.mode}-${t}`,"aria-label":a(`notificationRules.alarmNotify.${s}`)})]},t))]})}function Ea({coverage:e,rows:t,names:n}){let{t:r}=J(),a=t.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,o=vi(e,n.nameOf);return i(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${e.mode}`,children:[xi(e)?d(G,{variant:`warning`,title:o,"data-testid":`alarm-arms-nothing`,children:r(`system.alarmModeCard.armsNothingNoEnabledRule`,`Arms nothing — no enabled rule is gated on this mode`)}):d(G,{variant:`default`,title:o,"data-testid":`alarm-covers`,children:r(`system.alarmModeCard.checksSensors`,{count:a})}),e.skippedDevices.length>0?d(G,{variant:`warning`,title:yi(e.skippedDevices,n.nameOf),"data-testid":`alarm-skipped`,children:r(`system.alarmModeCard.notNotified`,{count:e.skippedDevices.length})}):null]})}function Da(e){return e.status===`answered`?e.openingIds:null}function Oa({check:e,view:t}){let{t:n}=J();return t.unresolved?e.status===`pending`?i(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[d(T,{className:`h-3 w-3 animate-spin`}),n(`system.alarmModeCard.checkingWhichDevicesAreOpenings`,`Checking which devices are openings…`)]}):e.status===`failed`?i(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[d(`span`,{children:n(`system.alarmModeCard.openingsCheckFailed`,{error:e.error})}),d(U,{type:`button`,size:`sm`,variant:`outline`,onClick:e.retry,children:n(`common.retry`,`Retry`)})]}):null:null}var ka=[{value:`rearmAfter`,labelKey:`system.alarmModeCard.postRearm`},{value:`disableAfter`,labelKey:`system.alarmModeCard.postDisarm`},{value:`doNothing`,labelKey:`system.alarmModeCard.postNothing`}];function Aa({coverage:e,settings:t,disabled:n,onDelayEdit:r,onPostTriggeredEdit:a,onScheduleEdit:o}){let{t:s}=J(),c=e.mode,l=Ee(t,c),u=l.source.postTriggeredAction==="default",f=l.postTriggeredAction!==`doNothing`,p=(t.modeDelays??[]).find(e=>e.mode===c)?.schedule;return i(`div`,{className:`space-y-3`,"data-testid":`alarm-delays-${c}`,children:[i(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:[Zi.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let i=l.source[e.field]==="default";return d(ea,{label:s(e.labelKey),value:l[e.field],max:e.max,zeroMeans:s(e.zeroMeansKey),disabled:n,testId:`alarm-delay-${c}-${e.key}`,onCommit:t=>r(e.field,t),adornment:i?d(G,{variant:`default`,title:s(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:t[e.field]}),children:s(`system.alarmModeCard.default`,`Default`)}):d(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:s(e.labelKey)}),onClick:()=>r(e.field,`default`),"data-testid":`alarm-delay-${c}-${e.key}-default`,children:d(A,{className:`h-3.5 w-3.5`})})},e.field)}),i(`div`,{children:[i(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:[s(`system.alarmModeCard.afterTrigger`,`After trigger`),u?d(G,{variant:`default`,className:`ml-1.5 align-middle`,title:s(`system.alarmModeCard.usesTheSystemDefault`,`Uses the system default`),children:s(`system.alarmModeCard.default`,`Default`)}):d(U,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:n,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.afterTriggerUseTheDefault`,`After trigger: use the default`),onClick:()=>a(`default`),"data-testid":`alarm-delay-${c}-post-default`,children:d(A,{className:`h-3.5 w-3.5`})})]}),d(`select`,{className:`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:l.postTriggeredAction,disabled:n,"data-testid":`alarm-delay-${c}-post`,onChange:e=>{let t=ke.safeParse(e.target.value);t.success&&a(t.data)},children:ka.map(e=>d(`option`,{value:e.value,children:s(e.labelKey)},e.value))})]}),f?Zi.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let i=l.source[e.field]==="default";return d(ea,{label:s(e.labelKey),value:l[e.field],max:e.max,zeroMeans:s(e.zeroMeansKey),disabled:n,testId:`alarm-delay-${c}-${e.key}`,onCommit:t=>r(e.field,t),adornment:i?d(G,{variant:`default`,title:s(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:t[e.field]}),children:s(`system.alarmModeCard.default`,`Default`)}):d(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:s(e.labelKey)}),onClick:()=>r(e.field,`default`),"data-testid":`alarm-delay-${c}-${e.key}-default`,children:d(A,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),i(`div`,{"data-testid":`alarm-schedule-${c}`,children:[d(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:s(`system.alarmModeCard.activationSchedule`,`Activation schedule`)}),d(`p`,{className:`mb-1 text-[10px] text-foreground-subtle`,children:s(`system.alarmModeCard.whenThisModeMayBe`,`When this mode may be armed. Empty means any day and time.`)}),d(`fieldset`,{disabled:n,className:`min-w-0 border-0 p-0`,children:d(Jt,{value:p,onChange:o,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var ja={"no-opening":`This household has no contact, cover or lock.`};function Ma({coverage:e,live:t,settings:n,names:r,openingsCheck:a,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:u,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m,onNotifyEdit:h,disabled:g}){let{t:_}=J(),v=ui({live:t,listed:ji(n,e.mode),openingIds:Da(a)}),y=di(v),b=ya({rowCount:o.length,candidatesComplete:!v.unresolved});return i(`div`,{className:`flex flex-col gap-3`,"data-mode":e.mode,"data-empty":xi(e)?`true`:`false`,children:[d(Ea,{coverage:e,rows:o,names:r}),d(Aa,{coverage:e,settings:n,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:_(`system.alarmModeCard.delaysHint`,{seconds:30})}),d(Ta,{coverage:e,settings:n,disabled:g,onNotifyEdit:h}),i(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[d(Oa,{check:a,view:v}),y===null?null:d(`p`,{className:`text-xs text-foreground-subtle`,children:ja[y]}),b===`none`&&y===null?d(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`alarm-sensors-none`,children:_(`system.alarmModeCard.noSensorIsCoveredBy`,`No sensor is covered by a rule of this mode.`)}):null,b===`rows`?d(da,{mode:e.mode,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:u,disabled:g}):null]})]})}e();function Na({profiles:e,busy:t,onActivate:n,onCreate:a,onClone:s,onRename:c,onDelete:l}){let{t:u}=J(),[f,m]=r(``),[h,g]=r(!1),_=e.items.find(t=>t.id===e.activeId)??e.items[0],y=_!==void 0&&!_.isDefault,b=f.trim(),x=()=>{b.length!==0&&(a(b),m(``))},C=()=>{b.length===0||_===void 0||(s(_.id,b),m(``))},w=()=>{b.length===0||_===void 0||(c(_.id,b),m(``),g(!1))};return i(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface-1 p-3`,"data-testid":`alarm-profiles`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:u(`system.alarmProfileBar.profile`,`Profile`)}),d(`select`,{id:`alarm-profile-select`,className:`h-8 min-w-[10rem] rounded-md border border-border bg-background px-2 text-sm`,"data-testid":`alarm-profile-select`,disabled:t,value:e.activeId,onChange:e=>n(e.target.value),children:e.items.map(e=>i(`option`,{value:e.id,children:[e.name,e.isDefault?` (${u(`system.alarmProfileBar.defaultSuffix`)})`:``]},e.id))}),y?d(U,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-delete`,title:u(`system.alarmProfileBar.deleteThisProfile`,`Delete this profile`),onClick:()=>{_!==void 0&&l(_.id)},children:d(p,{className:`h-3.5 w-3.5`})}):null]}),i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(W,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:h?u(`system.alarmProfileBar.newName`,`New name`):u(`system.alarmProfileBar.newProfileName`,`New profile name`),value:f,disabled:t,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(h?w():x())}}),h?i(o,{children:[d(U,{type:`button`,size:`sm`,disabled:t||b.length===0,"data-testid":`alarm-profile-rename-save`,onClick:w,children:u(`system.alarmProfileBar.rename`,`Rename`)}),d(U,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{g(!1),m(``)},children:u(`common.cancel`,`Cancel`)})]}):i(o,{children:[i(U,{type:`button`,size:`sm`,disabled:t||b.length===0,"data-testid":`alarm-profile-create`,title:u(`system.alarmProfileBar.createWithSystemDefaults`,`Create with system defaults`),onClick:x,children:[d(S,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.create`,`Create`)]}),i(U,{type:`button`,size:`sm`,variant:`secondary`,disabled:t||b.length===0||_===void 0,"data-testid":`alarm-profile-clone`,title:u(`system.alarmProfileBar.cloneTheSelectedProfile`,`Clone the selected profile`),onClick:C,children:[d(v,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.clone`,`Clone`)]}),d(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:t||_===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{g(!0),m(_?.name??``)},children:u(`system.alarmProfileBar.rename`,`Rename`)})]})]}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`system.alarmProfileBar.createStartsFromSystemDefaults`,`Create starts from system defaults. Clone copies the selected profile (sensors, secure-on-arm, delays). Switching applies that profile for the next arm.`)})]})}e();var Pa=[`notificationRules`,`getAlarmConfig`],Fa=[`notificationRules`,`getAlarmSensors`],Ia=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],La=6e4;function Ra(e){return e instanceof Error?e.message:String(e)}function za({notice:e}){let{t}=J();switch(e.kind){case`refused`:return d(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:t(`system.notificationAlarm.refused`,{name:e.inFlight.name,mode:gi(e.inFlight.mode)})});case`not-landed`:return d(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:t(`system.notificationAlarm.notLanded`,{name:e.write.name,mode:gi(e.write.mode)})});case`failed`:return d(`p`,{className:`text-xs text-danger`,role:`alert`,"data-testid":`alarm-switch-failed`,children:t(`system.notificationAlarm.couldNotChangeFor`,`Could not change {{name}} for {{value2}}: {{error}}`,{name:e.write.name,value2:gi(e.write.mode),error:e.error})})}}function Ba(){let{t:e}=J(),t=E(),o=s(),f=a({queryKey:Pa,queryFn:async()=>t.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>Ei(e.state.data?.live?.state)}),p=St({projection:`slim`}),[m,h]=r(!1),g=u({mutationFn:e=>t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{o.setQueryData(Pa,e),h(!R(t,e.settings))}}),_=u({mutationFn:async e=>{switch(e.kind){case`activate`:return t.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return t.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return t.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{o.setQueryData(Pa,e),h(!1)}}),v=()=>o.invalidateQueries({queryKey:Pa}),y=n(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),b=f.data?.live,x=a({queryKey:Ia,staleTime:La,queryFn:async()=>new Set(await t.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...ci]}))}),S=n(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),C=n(()=>new Map(S.map(e=>[e.id,e])),[S]),w=x.isError?{status:`failed`,error:x.error instanceof Error?x.error.message:String(x.error),retry:()=>void x.refetch()}:x.data===void 0?{status:`pending`}:{status:`answered`,openingIds:x.data},D=n(()=>{let e=new Map;for(let t of b?.openings??[])for(let n of t.devices)e.set(n.deviceId,pi(n));return fi(y,Ye(p),e)},[b,y,p]),k=$e(!0),[A,j]=r(null),M=n(()=>{let e=new Map,t=f.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,ui({live:t.live,listed:ji(t.settings,n.mode),openingIds:x.data??null}).ids);return e},[f.data,x.data]),N=n(()=>{let e=new Set;for(let t of M.values())for(let n of t)D.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[M,D]),P=a({queryKey:[...Fa,N],enabled:N.length>0,placeholderData:c,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&pa(Ra(e.state.error))?!1:b!==void 0&&ki(b.state)?5e3:15e3,retry:(e,t)=>!pa(Ra(t))&&e<2,queryFn:async()=>{let e=[];for(let n of ba(N,500))e.push(await t.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...n]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),F=P.isError?{status:`failed`,error:Ra(P.error)}:P.data===void 0?{status:`pending`}:{status:`answered`,sensors:P.data.sensors},I=l(null),[ee,te]=r(null),[L,ne]=r(null),re=async e=>{try{let n=await t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:Sa(e)});Ca(e,n.settings).kind===`landed`?o.setQueryData(Pa,n):(ne({kind:`not-landed`,write:e}),o.invalidateQueries({queryKey:Pa}))}catch(t){ne({kind:`failed`,write:e,error:Ra(t)}),o.invalidateQueries({queryKey:Pa})}finally{I.current=null,te(null),ne(e=>e?.kind===`refused`?null:e)}},ie=(e,t,n,r)=>{let i=xa(I.current,e,t,n,r);if(i.kind===`refused`){ne({kind:`refused`,inFlight:i.inFlight});return}I.current=i.write,te(i.write),ne(null),re(i.write)};if(f.isLoading)return d(ai,{embedded:!0,icon:O,title:e(`system.notificationAlarm.alarm`,`Alarm`),subtitle:e(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:d(T,{className:`h-5 w-5 animate-spin`})});let z=f.data;if(z===void 0||f.isError)return d(ai,{embedded:!0,icon:O,title:e(`system.notificationAlarm.alarm`,`Alarm`),subtitle:e(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:d(H,{title:e(`system.notificationAlarm.alarmSettingsAreNotAvailable`,`Alarm settings are not available`),message:e(`system.notificationAlarm.thisHubHasNotBeen`,`This hub has not been updated to serve the alarm configuration yet.`)})});if(z.deviceId===null)return d(ai,{embedded:!0,icon:O,title:e(`system.notificationAlarm.alarm`,`Alarm`),subtitle:e(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:d(pt,{className:`p-4`,children:d(`p`,{className:`text-sm text-foreground-subtle`,children:e(`system.notificationAlarm.thisInstallationHasNoAlarm`,`This installation has no alarm panel. The panel is created by the Notification Center on the hub — if this is the hub, its creation failed and the server log says why.`)})})});let ae=z.settings,oe=g.isPending||_.isPending,se=e=>{h(!1),g.mutate(e)},ce=(e,t,n)=>{let r=Ii(ae,e,t,n);r!==null&&se({modeDelays:[r]})},le=(e,t)=>{let n=Li(ae,e,t);n!==null&&se({modeDelays:[n]})},ue=(e,t)=>{let n=Ri(ae,e,t);n!==null&&se({modeDelays:[n]})},de=(e,t,n)=>{let r=Gi(ae,e,t,n);r!==null&&se({modeDelays:[r]})},fe=new Map(z.coverage.map(e=>[e.mode,va({candidates:(M.get(e.mode)??[]).map(e=>({...C.get(e),id:e,name:D.nameOf(e)})),removedIds:new Set((M.get(e.mode)??[]).filter(D.isRemoved)),coverage:e,nonBlocking:ji(ae,e.mode),blocking:Mi(ae,e.mode),secureOnArmOff:Ni(ae,e.mode),sensors:F})])),pe=z.coverage.find(e=>e.mode===A)??z.coverage.find(e=>(fe.get(e.mode)?.length??0)>0)??z.coverage[0],me=pe?.mode??``;return i(ai,{embedded:!0,icon:O,title:e(`system.notificationAlarm.alarm`,`Alarm`),subtitle:e(`system.notificationAlarm.thePanelWhatEachMode`,`The panel, what each mode arms, and who hears about it.`),children:[g.isError?d(H,{title:e(`system.notificationAlarm.couldNotSave`,`Could not save`),message:String(g.error)}):null,_.isError?d(H,{title:e(`system.notificationAlarm.couldNotUpdateProfile`,`Could not update profile`),message:String(_.error)}):null,m?d(`div`,{"data-testid":`alarm-save-not-landed`,children:d(H,{variant:`warning`,title:e(`system.notificationAlarm.notApplied`,`Not applied`),message:e(`system.notificationAlarm.theHubDidNotApply`,`The hub did not apply this change — another editor may have changed it, or the hub needs an update`)})}):null,z.profiles===void 0?null:d(Na,{profiles:z.profiles,busy:oe,onActivate:e=>_.mutate({kind:`activate`,id:e}),onCreate:e=>_.mutate({kind:`create`,name:e}),onClone:(e,t)=>_.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>_.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>_.mutate({kind:`delete`,id:e})}),d(Xi,{live:z.live,onChanged:v}),i(pt,{className:`p-4`,"data-testid":`alarm-coverage`,children:[d(st,{value:me,onValueChange:e=>{let t=z.coverage.find(t=>t.mode===e);t!==void 0&&j(t.mode)},children:d(Xe,{className:`mb-3`,children:z.coverage.map(e=>i(ut,{value:e.mode,"data-testid":`alarm-tab-${e.mode}`,children:[gi(e.mode),d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:fe.get(e.mode)?.length??0})]},e.mode))})}),L===null?null:d(za,{notice:L}),pe===void 0?null:d(Ma,{coverage:pe,live:z.live,settings:ae,names:D,openingsCheck:w,rows:fe.get(pe.mode)??[],sensorsRetry:F.status===`failed`&&!pa(F.error)?()=>void P.refetch():null,inFlight:ee,onSwitch:(e,t,n)=>ie(pe.mode,e,t,n),zones:k,onDelayEdit:(e,t)=>ce(pe.mode,e,t),onPostTriggeredEdit:e=>le(pe.mode,e),onScheduleEdit:e=>ue(pe.mode,e),onNotifyEdit:(e,t)=>de(pe.mode,e,t),disabled:oe},pe.mode)]})]})}var Va=`history`,Ha=`ruleId`,Ua=[Ha],Wa=24,Ga=0,Ka=100;function qa(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Va),n.set(Ha,t),n}function Ja(e,t){let n=new URLSearchParams(e);return t===``?n.delete(Ha):n.set(Ha,t),n}function Ya(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Wa:Ga,limit:Ka}}function Xa(e){let t=e.rules.map(e=>({value:e.id,label:e.name})),n=e.selected!==``&&!e.rules.some(t=>t.id===e.selected)?[{value:e.selected,label:e.answered?q.t(`helpers.notificationHistory.deletedRule`,{id:e.selected}):e.selected}]:[];return[{value:``,label:q.t(`helpers.notificationHistory.allRules`)},...t,...n]}e();var Za=[{value:1,labelKey:`system.notificationHistory.windowLastHour`},{value:24,labelKey:`system.notificationHistory.windowLast24h`},{value:168,labelKey:`system.notificationHistory.windowLast7d`},{value:0,labelKey:`system.notificationHistory.windowAllTime`}],Qa=[{value:``,labelKey:`system.notificationHistory.statusAny`},{value:`pending`,labelKey:`system.notificationHistory.statusPending`},{value:`sent`,labelKey:`system.notificationHistory.statusSent`},{value:`dead`,labelKey:`system.notificationHistory.statusDead`}],$a=[50,100,250,500];function eo(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function to(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function no(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 ro({entry:e,cameraName:t,onClose:n}){let{t:r}=J(),a=no(e),o=e.subject.systemEvent;return d(mt,{open:!0,onOpenChange:e=>!e&&n(),children:i(Dt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[d(_t,{children:d(dt,{className:`min-w-0 break-words`,children:a.title||e.ruleName})}),d(ht,{children:i(`dl`,{className:`space-y-3`,children:[i(`div`,{children:[d(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:r(`system.notificationHistory.body`,`Body`)}),d(`dd`,{className:`mt-1 whitespace-pre-wrap text-sm text-foreground`,children:a.body.length>0?a.body:`—`})]}),i(`div`,{className:`grid grid-cols-2 gap-3 text-[11px]`,children:[i(`div`,{children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.when`,`When`)}),d(`dd`,{className:`text-foreground`,children:new Date(e.createdAt).toLocaleString()})]}),i(`div`,{children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.status`,`Status`)}),d(`dd`,{className:`text-foreground`,children:e.status})]}),i(`div`,{children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.rule`,`Rule`)}),d(`dd`,{className:`text-foreground`,children:e.ruleName})]}),i(`div`,{children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.device`,`Device`)}),d(`dd`,{className:`text-foreground`,children:t})]}),o===void 0?null:i(`div`,{className:`col-span-2`,children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`system.notificationHistory.kind`,`Kind`)}),d(`dd`,{className:`text-foreground`,children:o.kind})]}),e.error===void 0?null:i(`div`,{className:`col-span-2`,children:[d(`dt`,{className:`font-medium text-foreground-subtle`,children:r(`common.error`,`Error`)}),d(`dd`,{className:`text-danger`,children:e.error})]})]})]})}),d(yt,{children:d(U,{type:`button`,size:`sm`,variant:`secondary`,onClick:n,children:r(`common.close`,`Close`)})})]})})}function io(){let{t:e}=J(),t=E(),[o,s]=Tr(),[c,l]=r(()=>Ya(o)),[u,f]=r(null),p=e=>l(t=>({...t,...e})),m=e=>{p({ruleId:e}),s(Ja(o,e),{replace:!0})},h=a({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await t.trpcClient.notificationRules.listRules.query({})).rules}),g=St({projection:`slim`}),_=Date.now(),v=a({queryKey:[`notificationRules`,`getHistory`,c],retry:!1,queryFn:async()=>{let e=c.windowHours>0?_-c.windowHours*36e5:void 0;return(await t.trpcClient.notificationRules.getHistory.query({filter:{limit:c.limit,...c.ruleId?{ruleId:c.ruleId}:{},...c.deviceId?{deviceId:Number(c.deviceId)}:{},...eo(c.status)?{status:eo(c.status)}:{},...e===void 0?{}:{since:e}}})).entries}}),b=n(()=>{let e=new Map;for(let t of g.data??[])t.type===Ce.Camera&&e.set(t.id,t.name);return e},[g.data]),x=t=>b.get(t)??e(`system.notificationHistory.cameraFallback`,{deviceId:t}),S=v.data??[],C=v.isError;return i(ai,{embedded:!0,icon:j,title:e(`system.notificationHistory.deliveryHistory`,`Delivery history`),subtitle:e(`system.notificationHistory.aSearchableLogOfEvery`,`A searchable log of every notification the rules delivered (or failed to deliver).`),children:[i(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.rule`,`Rule`)}),d(V,{"data-testid":`history-rule-filter`,value:c.ruleId,onChange:e=>m(e.target.value),options:[...Xa({rules:h.data??[],answered:h.isSuccess,selected:c.ruleId})]})]}),i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.camera`,`Camera`)}),d(V,{value:c.deviceId,onChange:e=>p({deviceId:e.target.value}),options:[{value:``,label:e(`system.notificationHistory.allCameras`,`All cameras`)},...(g.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.status`,`Status`)}),d(V,{value:c.status,onChange:e=>p({status:e.target.value}),options:Qa.map(t=>({value:t.value,label:e(t.labelKey)}))})]}),i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.window`,`Window`)}),d(V,{value:String(c.windowHours),onChange:e=>p({windowHours:Number(e.target.value)}),options:Za.map(t=>({value:String(t.value),label:e(t.labelKey)}))})]}),i(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.limit`,`Limit`)}),d(V,{value:String(c.limit),onChange:e=>p({limit:Number(e.target.value)}),options:$a.map(e=>({value:String(e),label:String(e)}))})]})]}),v.isLoading&&d(`div`,{className:`flex items-center justify-center py-16`,children:d(T,{className:`h-6 w-6 animate-spin text-primary`})}),C&&!v.isLoading&&d(pt,{children:i(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[d(j,{className:`h-6 w-6 text-foreground-subtle`}),d(`div`,{className:`text-sm font-medium text-foreground`,children:e(`system.notificationHistory.deliveryHistoryRequiresAServer`,`Delivery history requires a server update`)}),d(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:e(`system.notificationHistory.theHistoryQueryIsNot`,`The history query is not available on this hub yet. It becomes queryable after the next server update ships the notification-center history endpoint. Rules still deliver and record their outcome in the meantime.`)}),i(`button`,{type:`button`,onClick:()=>void v.refetch(),className:`mt-1 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:[d(y,{className:`h-3 w-3`}),` `,e(`common.retry`)]})]})}),!C&&!v.isLoading&&S.length===0&&d(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`system.notificationHistory.noDeliveriesMatchTheseFilters`,`No deliveries match these filters.`)}),!C&&S.length>0&&d(pt,{children:d(ct,{columns:ao(x),rows:S,rowKey:e=>e.id,minWidthPx:720,bordered:!1,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>f(e)})}),u!==null&&d(ro,{entry:u,cameraName:x(u.deviceId),onClose:()=>f(null)})]})}function ao(e){return[{key:`when`,header:q.t(`system.notificationHistory.when`,`When`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:q.t(`system.notificationHistory.rule`,`Rule`),render:e=>d(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:q.t(`system.notificationHistory.camera`,`Camera`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:q.t(`system.notificationHistory.notification`,`Notification`),render:e=>{let t=no(e);return i(`span`,{className:`block max-w-[18rem]`,children:[d(`span`,{className:`block truncate text-[11px] font-medium text-foreground`,children:t.title.length>0?t.title:e.subject.label??e.subject.className}),t.body.length>0?d(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:t.body}):null]})}},{key:`status`,header:q.t(`system.notificationHistory.status`,`Status`),nowrap:!0,render:e=>i(`span`,{className:`flex items-center gap-1.5`,children:[d(G,{variant:to(e.status),children:e.status}),e.attempts>1?i(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:q.t(`system.notificationHistory.detail`,`Detail`),render:e=>e.error?d(`span`,{className:`text-[11px] text-danger`,children:e.error}):d(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var oo=/\{\{\s*(\w+)\s*\}\}/g,so=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function co(e,t,n){let r=Math.min(Math.max(t.start,0),e.length),i=Math.min(Math.max(t.end,r),e.length);return{value:e.slice(0,r)+n+e.slice(i),cursor:r+n.length}}function lo(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function uo(e){return[...e.matchAll(oo)].map(e=>e[1]??``).filter(e=>e.length>0)}function fo(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function po(e,t){return[...new Set(uo(e))].filter(e=>!fo(e,t))}var mo={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function ho(e){return e.map(e=>{let t=Pe.find(t=>t.name===e.name),n=e.systemEventKinds;if(t?.systemEventKinds===void 0||n===void 0)return e;let r=t.systemEventKinds.filter(e=>n.includes(e)||ce.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function go(e){let t=new Set(e.map(e=>e.name)),n=Pe.filter(e=>P(e)&&!t.has(e.name));return[...e,...n]}function _o(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=mo[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)||!L(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:pe(e,t)&&me(e,t))}function vo(e){return so.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var yo=[`nc`,`template-catalog`],bo=400;function xo(){let e=E();return a({queryKey:yo,staleTime:5*6e4,queryFn:async()=>go(ho((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function So(e,t,n){let r=E(),i=jt(t.title??``,bo),o=jt(t.body??``,bo);return a({queryKey:[`nc`,`template-preview`,e,i,o],enabled:n&&(i.length>0||o.length>0),staleTime:3e4,queryFn:()=>r.trpcClient.notificationRules.previewTemplate.mutate({context:e,template:{...i?{title:i}:{},...o?{body:o}:{}}})})}e();var Co={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},wo=`block text-[11px] font-medium text-foreground mb-1`,To=`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`;function Eo({label:e,value:t,onChange:n,vars:r,multiline:a=!1,placeholder:o,disabled:s=!1,testId:c}){let{t:u}=J(),f=l(null),p=l(null),m=r?po(t,r):[],g=e=>{let r=a?p.current:f.current,i={start:r?.selectionStart??t.length,end:r?.selectionEnd??t.length},o=lo(e),s=co(t,i,o.text);n(s.value);let c=s.cursor-o.text.length+o.cursorOffset;requestAnimationFrame(()=>{r?.focus(),r?.setSelectionRange(c,c)})},_=e=>n(e.target.value);return i(`div`,{className:`space-y-1`,children:[d(`label`,{className:wo,children:e}),a?d(`textarea`,{ref:p,value:t,rows:2,disabled:s,placeholder:o,onChange:_,className:To,"data-testid":`${c}-input`}):d(W,{ref:f,value:t,disabled:s,placeholder:o,onChange:_,"data-testid":`${c}-input`}),r&&r.length===0?d(`p`,{className:`text-[10px] text-foreground-subtle`,children:u(`notifications.templateField.noVariablesForThisField`,`No variables for this field.`)}):null,r&&r.length>0?d(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:vo(r).map(e=>i(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${c}-group-${e.group}`,children:[d(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:Co[e.group]}),e.vars.map(e=>d(`button`,{type:`button`,disabled:s,onMouseDown:e=>e.preventDefault(),onClick:()=>g(e),title:`${e.description??e.label} — e.g. "${e.example}"`,className:`rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-foreground hover:bg-surface-hover`,"data-testid":`${c}-chip-${e.name}`,children:e.dynamic?u(`notifications.templateField.class`,`{{name}}<class>`,{name:e.name}):e.name},e.name))]},e.group))}):null,m.length>0?i(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${c}-unknown`,children:[d(h,{className:`h-3 w-3`}),u(`notifications.templateField.willBeEmpty`,{names:m.map(e=>`{{${e}}}`).join(` `)})]}):null]})}function Do({context:e,title:t,body:n,testId:r}){let{t:a}=J(),o=So(e,{title:t,body:n},!0);return o.data?i(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":r,children:[d(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:a(`notifications.templateField.previewExampleValues`,`Preview (example values)`)}),o.data.title===null?null:d(`p`,{className:`font-medium`,children:o.data.title}),o.data.body===null?null:d(`p`,{className:`whitespace-pre-wrap`,children:o.data.body})]}):null}var Oo=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,ko=`block text-[11px] font-medium text-foreground`;function Ao({title:e,description:t,children:n}){return i(`div`,{className:`flex flex-col gap-2`,children:[i(`div`,{children:[d(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:t})]}),n!==void 0&&d(`div`,{className:`flex flex-wrap items-center gap-1`,children:n})]})}function jo(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function Mo(e,t){return{kind:`cap`,deviceId:t,cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}}}function No(e){let t=jo(e.deviceId);return t.length===0?[Mo(e,0)]:t.map(t=>Mo(e,t))}function Po(e){return No(e).map(e=>({kind:`do`,action:e}))}function Fo(e,t){let n=e[t];if(n===void 0||n.kind!==`cap`)return{wire:{deviceId:0,cap:``,method:``},length:1};let r=n.deviceId>0?[n.deviceId]:[],i=1;for(let a=t+1;a<e.length;a+=1){let t=e[a];if(t===void 0||t.kind!==`cap`||t.cap!==n.cap||t.method!==n.method||JSON.stringify(t.args??{})!==JSON.stringify(n.args??{}))break;t.deviceId>0&&r.push(t.deviceId),i+=1}return{wire:{deviceId:r.length===0?0:r.length===1?r[0]:[...r],cap:n.cap,method:n.method,...n.args===void 0?{}:{args:{...n.args}}},length:i}}function Io(e,t){let n=e[t];return n===void 0||n.kind!==`do`?{wire:{deviceId:0,cap:``,method:``},length:1}:Fo(e.slice(t).map(e=>e.kind===`do`?e.action:{kind:`wait`,seconds:0}),0)}function Lo({value:e,onChange:t,devices:n,devicesState:r,sequences:a=[],showProblems:o=!0}){let{t:s}=J(),c=gn(e,new Set(a.map(e=>e.id))),l=(n,r)=>t({...e,[n]:r}),u=(n,r)=>t({...e,buttons:e.buttons.map((e,t)=>t===n?r:e)});return i(`div`,{className:`space-y-4`,children:[o&&c.length>0?d(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:c.map(e=>d(`p`,{children:e.message},e.message))}):null,Mn.map(t=>d(Ro,{hookKey:t,bindings:e[t],sequences:a,devices:n,devicesState:r,onChange:e=>l(t,e)},t)),i(`section`,{className:`space-y-2`,children:[d(Ao,{title:s(`system.notificationRuleActions.buttonsOnTheNotification`,`Buttons on the notification`),description:s(`system.notificationRuleActions.eachButtonRunsOneShared`,`Each button runs one shared sequence when tapped.`),children:i(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:a.length===0,onClick:()=>t({...e,buttons:[...e.buttons,bn(e.buttons.length,a[0]?.id??``)]}),children:[d(S,{className:`h-3.5 w-3.5 shrink-0`}),` `,s(`system.notificationRuleActions.button`)]})}),e.buttons.length>0&&i(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:[d(h,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),d(`span`,{children:d(Sr,{i18nKey:`system.notificationRuleActions.buttonLinkNote`,components:{b:d(`strong`,{})}})})]}),a.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:s(`system.notificationRuleActions.createASequenceOnThe`,`Create a sequence on the Sequences tab first — a button runs one, it does not define its own steps.`)}):e.buttons.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:s(`system.notificationRuleActions.noButtonsTheNotificationArrives`,`No buttons. The notification arrives with nothing to tap.`)}):e.buttons.map((n,r)=>d(zo,{button:n,sequences:a,onChange:e=>u(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function Ro({hookKey:e,bindings:t,sequences:n,devices:r,devicesState:a,onChange:o}){let{t:s}=J(),c=qt[e],l=[],u=0;for(;u<t.length;){if(t[u].kind===`sequence`){l.push({start:u,kind:`sequence`,length:1}),u+=1;continue}let e=Io(t,u);l.push({start:u,kind:`do`,length:e.length}),u+=e.length}return i(`section`,{className:`space-y-2`,children:[i(Ao,{title:c.title,description:c.hint,children:[i(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4||n.length===0,onClick:()=>o([...t,Lt(n[0]?.id??``)]),children:[d(S,{className:`h-3.5 w-3.5`}),` `,s(`system.notificationRuleActions.sequence`)]}),i(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4,onClick:()=>o([...t,br()]),children:[d(S,{className:`h-3.5 w-3.5`}),` `,s(`system.notificationRuleActions.singleAction`)]})]}),t.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:s(`system.notificationRuleActions.nothingOnThisEdge`,`Nothing on this edge.`)}):l.map(e=>{if(e.kind===`sequence`){let r=t[e.start];return r.kind===`sequence`?i(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:ko,children:s(`system.notificationRuleActions.sequence`,`Sequence`)}),d(`select`,{className:Oo,value:r.sequenceId,onChange:n=>{let r=[...t];r[e.start]={kind:`sequence`,sequenceId:n.target.value},o(r)},children:n.map(e=>d(`option`,{value:e.id,children:e.name},e.id))})]}),d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o(t.filter((t,n)=>n!==e.start)),title:s(`common.remove`,`Remove`),children:d(p,{className:`h-3.5 w-3.5`})})]},`seq-${String(e.start)}`):null}return d(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:i(`div`,{className:`flex items-start justify-between gap-2`,children:[d(`div`,{className:`min-w-0 flex-1`,children:d(ii,{value:Io(t,e.start).wire,devices:r,listState:a,allowMultiSameFamily:!0,onChange:n=>{let r=Po(n);o([...t.slice(0,e.start),...r,...t.slice(e.start+e.length)])}})}),d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o([...t.slice(0,e.start),...t.slice(e.start+e.length)]),title:s(`common.remove`,`Remove`),children:d(p,{className:`h-3.5 w-3.5`})})]})},`do-${String(e.start)}`)})]})}function zo({button:e,sequences:t,onChange:n,onRemove:r}){let{t:a}=J();return i(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[i(`div`,{className:`w-28`,children:[d(`label`,{className:ko,children:a(`system.notificationRuleActions.id`,`Id`)}),d(W,{className:`mt-1`,value:e.id,onChange:t=>n({...e,id:t.target.value})})]}),i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:ko,children:a(`system.notificationRuleActions.label`,`Label`)}),d(W,{className:`mt-1`,value:e.label,onChange:t=>n({...e,label:t.target.value})})]}),i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:ko,children:a(`system.notificationRuleActions.sequence`,`Sequence`)}),d(`select`,{className:Oo,value:e.sequenceId,onChange:t=>n({...e,sequenceId:t.target.value}),children:t.map(e=>d(`option`,{value:e.id,children:e.name},e.id))})]}),i(`div`,{className:`w-32`,children:[d(`label`,{className:ko,children:a(`system.notificationRuleActions.icon`,`Icon`)}),i(`select`,{className:Oo,value:e.icon??``,onChange:t=>{let r={...e};t.target.value===``?delete r.icon:r.icon=t.target.value,n(r)},children:[d(`option`,{value:``,children:`—`}),Jr.map(e=>d(`option`,{value:e.value,children:e.label},e.value))]})]}),d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:a(`common.remove`,`Remove`),children:d(p,{className:`h-3.5 w-3.5`})})]})}var Bo=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Vo=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],Ho={minConfidence:`class`},Uo=[{id:`system`,get label(){return q.t(`notificationRules.groups.system`)}},{id:`class`,get label(){return q.t(`notificationRules.groups.class`)}},{id:`zones`,get label(){return q.t(`notificationRules.groups.zones`)}},{id:`label`,get label(){return q.t(`notificationRules.groups.label`)}},{id:`quality`,get label(){return q.t(`notificationRules.groups.quality`)}},{id:`scope`,get label(){return q.t(`notificationRules.groups.scope`)}},{id:`device`,get label(){return q.t(`notificationRules.groups.device`)}},{id:`package`,get label(){return q.t(`notificationRules.groups.package`)}},{id:`occupancy`,get label(){return q.t(`notificationRules.groups.occupancy`)}},{id:`audio`,get label(){return q.t(`notificationRules.groups.audio`)}},{id:`schedule`,get label(){return q.t(`notificationRules.groups.schedule`)}}];function Wo(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Vo)t.has(e)&&n.add(r);return n}function Go(e){return Ho[e.id]??e.group}function Ko(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function qo(e){let t=Wo(e),n=e.filter(e=>!Bo.has(e.id)&&!t.has(e.id)),r=new Set(Uo.map(e=>e.id)),i=[],a=e=>n.filter(t=>Go(t)===e);for(let e of Uo){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=Go(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Ko(e),descriptors:a(e)});return i}function Jo(e,t){switch(e){case`zones`:return mn(t.zones?.ids,t.zonesExclude);case`labels`:return mn(t.labelEquals,void 0);case`identities`:return Yo(t)}}function Yo(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?mn(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function Xo(e,t,n){switch(e){case`zones`:return Zo(t,n);case`labels`:return Qo(t,n);case`identities`:return $o(t,n)}}function Zo(e,t){let{zones:n,zonesExclude:r,...i}=e,a=Sn(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function Qo(e,t){let{labelEquals:n,...r}=e,i=Sn(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function $o(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=Dn(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=Sn(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var es={all:`All`,only:`Only these`,except:`All except these`},ts={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 ns({draft:e,onChange:t,exceptOffered:n,plural:r,renderPicker:a,describe:o,testId:s}){let{t:c}=J(),l=(e,t,n)=>c(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),u=c(`ruleScope.items.${r}`,ts[r].items),f=vn.filter(t=>t!==`except`||n||e.mode===`except`),p=Dn(e),m=on(e),h=e.mode===`all`?null:e.mode;return i(`div`,{className:`mt-1 space-y-1.5`,"data-testid":s,children:[d(`div`,{role:`radiogroup`,"aria-label":l(`ruleScope.which`,`Which {{items}}`,u),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(n=>{let r=n===e.mode;return d(`button`,{type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${n}`,onClick:()=>t(Rn(e,n)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,children:c(`ruleScope.mode.${n}`,es[n])},n)})}),h===null?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(`ruleScope.every.${r}`,ts[r].every)}):a(ni(e),n=>t(Bt(e,n)),h),p.length>0&&i(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[l(`ruleScope.legacy`,`This rule also excludes {{items}} — kept when you save.`,p.map(o).join(`, `)),` `,d(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>t(Xt(e)),children:c(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:l(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(o).join(`, `))})]})}function 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 is(e){return e.map(e=>e.hint===void 0?{id:e.value,name:e.label}:{id:e.value,name:`${e.hint}:${e.label}`,type:e.hint})}e();function as(e,t,n){let[i,a]=r(()=>Jo(e,t));return[i,r=>{a(r),n(Xo(e,t,r))}]}function os(e,t){return t?`failed`:e?`pending`:`answered`}function ss({conditions:e,onConditionsChange:t,exceptOffered:r,cameraIds:i,cameras:a}){let{t:o}=J(),[s,c]=as(`zones`,e,t),{options:l,loading:u,failed:f}=Yt(i,a),p=n(()=>is(l),[l]),m=os(u,!1),h=f?{state:`failed`,devices:void 0}:{state:m,devices:m===`answered`?p:void 0},g=n(()=>new Map(p.map(e=>[e.id,e.name])),[p]);return d(ns,{draft:s,onChange:c,exceptOffered:r,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>i.length===0?d(`p`,{className:Zt,children:o(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):d(at,{devices:p,listState:m,fleet:h,value:e,onChange:t,emptyMeansAll:!0,noun:`zone`,groupTitle:e=>e.type??o(`notificationRules.zones.group`,`Zones`),testId:`zone-picker`},n)})}function cs({conditions:e,onConditionsChange:t,exceptOffered:r}){let{t:i}=J(),[a,o]=as(`identities`,e,t),{options:s,loading:c,failed:l}=xn(),u=n(()=>s.map(e=>({id:e.value,name:e.label})),[s]),f=n(()=>new Map(u.map(e=>[e.id,e.name])),[u]);return d(ns,{draft:a,onChange:o,exceptOffered:r,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>d(at,{devices:u,listState:os(c,l),value:e,onChange:t,emptyMeansAll:n===`except`,...n===`only`?{emptyLabel:i(`notificationRules.faces.anyKnown`,`Any known face — nobody in particular`)}:{},noun:`face`,groupTitle:()=>i(`notificationRules.faces.group`,`Known faces`),testId:`identity-picker`},n)})}function ls({conditions:e,onConditionsChange:t}){let{t:n}=J(),[r,i]=as(`labels`,e,t);return d(ns,{draft:r,onChange:i,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>d(Jn,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function us(e){let t=ie(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function ds(e){return e.type??q.t(`helpers.classPickerItems.other`)}e();function fs({taxonomy:e,scope:t,onChange:r,exceptOffered:i}){let{t:a}=J(),o=n(()=>us(e),[e]),s=n(()=>new Map((o??[]).map(e=>[e.id,e.name])),[o]);return d(ns,{draft:t,onChange:r,exceptOffered:i,plural:`classes`,describe:e=>s.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>o===null?d(Jn,{value:e,placeholder:a(`system.notificationClassScopeField.addValue`,`Add value…`),onChange:t}):d(at,{devices:o,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:ds,testId:`class-picker`},n)})}function ps(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function ms({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return d(at,{devices:e.map(ps),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`,showAll:!0})}function hs({devices:e,scope:t,onChange:n,listState:r,savedScope:i,exceptOffered:a}){let o=new Map(e.map(e=>[e.id,e.name]));return d(ns,{draft:t,onChange:n,exceptOffered:a,plural:`devices`,describe:e=>o.get(e)??q.t(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`rule-device-scope`,renderPicker:(t,n,a)=>d(ms,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function gs(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function _s(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function vs(e){let t=gs(e),n=e.data===void 0?[]:te(e.data.nodes),r=_s(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function ys(e){let t=gs(e),n=e.data===void 0?[]:ee(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var bs=[`nc-pickers`,`node-directory`],xs=[`nc-pickers`,`package-list`],Ss=6e4,Cs={get hub(){return q.t(`system.scopePickers.roleHub`)},get agent(){return q.t(`system.scopePickers.roleAgents`)}},ws={get server(){return q.t(`system.scopePickers.pkgServer`)},get framework(){return q.t(`system.scopePickers.pkgFramework`)},get wrapper(){return q.t(`system.scopePickers.pkgWrapper`)},get addon(){return q.t(`system.scopePickers.pkgAddons`)}};function Ts(e){let t=Cs[e.type??``]??q.t(`system.scopePickers.roleNodes`);return e.location===`offline`?q.t(`system.scopePickers.offlineSuffix`,{role:t}):t}function Es(e){return ws[e.type??``]??q.t(`system.scopePickers.pkgPackages`)}function Ds({value:e,onChange:t,testId:n}){let{t:r}=J(),o=E().trpcClient,s=a({queryKey:bs,staleTime:Ss,queryFn:()=>o.nodes.directory.query()}),c=vs(s);return i(`div`,{children:[d(at,{devices:c.items,listState:c.listState,fleet:c.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:Ts,...n===void 0?{}:{testId:n}}),s.data?.complete===!1&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:r(`system.scopePickers.theNodeHistoryCouldNot`,`The node history could not be read — offline nodes may be missing from this list.`)})]})}function Os({value:e,onChange:t,testId:n}){let r=E().trpcClient,i=ys(a({queryKey:xs,staleTime:Ss,queryFn:()=>r.addons.listPackages.query()}));return d(at,{devices:i.items,listState:i.listState,fleet:i.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:Es,...n===void 0?{}:{testId:n}})}var ks={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-consumable-low`]},template:{body:`{{deviceName}}`}};function As(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 js(e,t){return e===`pending`?`pending`:e===`success`?`current`:As(t)===`BAD_REQUEST`?`outdated`:`unknown`}function Ms(e){let t=E(),n=a({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(ks)});return e?js(n.status,n.error):`pending`}e();var Ns=`/system/settings`,Ps=`/system/notifications?tab=alarm`,Fs=`text-primary underline-offset-2 hover:underline`;function Is(e,t){let n=Sn(t);return dn(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function Ls({family:e,value:t,cameras:a,allDevices:o,fleet:s,savedHadDevices:c,onChange:l,summary:u=!1}){let{t:f}=J(),p=n(()=>t?.kinds??[],[t]),m=n(()=>o===void 0?a:o.map(ps),[o,a]),h=n(()=>a.map(e=>({id:e.id,name:e.name,type:`camera`})),[a]),g=qn(e,p),_=Ms(e===`device-events`),v=e===`alarm`,[y,b]=r(()=>mn(t?.deviceIds,t?.excludeDeviceIds)),[x]=r(()=>mn(t?.deviceIds,t?.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 i(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[d(`p`,{className:Zt,"data-testid":`system-event-class-hint`,children:u?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.`)}),Xn(e).map(n=>i(`div`,{children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:n.label}),d(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:Wn(n,u).map(n=>{let r=Ft(p,n),i=n.noSnapshot===!0?`${n.label} — ${f(`system.notificationSystemEventField.noSnapshot`,`no state snapshot, reports nothing`)}`:n.label;return d(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":i,onClick:()=>l(sr(t,n,e)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-1 text-[11px] text-primary`:`rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:i},n.key)})})]},n.id)),e===`device-events`&&i(`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):`),` `,d(Ur,{to:Ns,target:`_blank`,rel:`noreferrer`,className:Fs,children:f(`system.notificationSystemEventField.settingsBatteryOfflineAlerts`,`Settings → Battery & offline alerts`)}),`.`]}),e===`alarm`&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[d(Ur,{to:Ps,target:`_blank`,rel:`noreferrer`,className:Fs,children:f(`system.notificationSystemEventField.alarmSettings`,`Alarm settings`)}),p.includes(`alarm-triggered`)&&d(`span`,{className:`ml-1`,children:f(`system.notificationSystemEventField.alarmPictures`)})]}),_===`outdated`&&d(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-hub-outdated`,children:f(`system.notificationSystemEventField.hubOutdated`,{percent:15})}),_===`unknown`&&d(`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&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:f(`system.notificationSystemEventField.consumableLowAt`,`Consumable low at (%)`)}),d(W,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:nn,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=$t(e.target.value);n.kind!==`invalid`&&l(dn(t,{consumableLowPercent:n.kind===`set`?n.value:void 0}))}})]}),g.deviceTypes&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.deviceTypes`,`Device types`)}),d(_n,{options:Fn,value:t?.deviceTypes??[],onChange:e=>l(dn(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:f(`system.notificationSystemEventField.deviceType`,`Device type…`)})]}),Vn(t)&&d(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`battery-device-types-warning`,children: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&&i(`div`,{children:[d(ns,{draft:y,onChange:e=>{b(e),l(Is(t,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)=>d(at,{devices:v?h:m,listState:s.state,fleet:s,emptyMeansAll:!0,savedHadDevices:(n===`only`?x.include:x.exclude).length>0||n===`only`&&c,noun:v?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),c&&y.mode===`all`&&d(ot,{noun:v?`camera`:`device`})]}),g.nodes&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.nodes`,`Nodes`)}),d(Ds,{value:t?.nodeIds??[],onChange:e=>l(dn(t,{nodeIds:e})),testId:`system-event-nodes`})]}),g.packages&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.packages`,`Packages`)}),d(Os,{value:t?.packageNames??[],onChange:e=>l(dn(t,{packageNames:e})),testId:`system-event-packages`})]})]})}function Rs({value:e}){let{t}=J(),n=e?.kinds??[];return i(`div`,{className:`mt-1 rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-mixed`,children:[d(`p`,{children:t(`system.notificationSystemEventField.thisRuleIsNotOne`,`This rule is not one kind of system rule — its events span device events, system and alarm, or it names none. It keeps firing as it is, but it cannot be edited here: recreate it as one rule per kind.`)}),n.length>0&&d(`p`,{className:`mt-1 text-foreground`,children:n.map(wn).join(`, `)})]})}function zs({family:e,onChange:t}){let{t:n}=J();return i(`div`,{"data-testid":`system-family-select`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:n(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`)}),d(V,{value:e,"aria-label":n(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`),onChange:e=>{let n=e.target.value;ae(n)&&t(n)},options:fe.map(e=>({value:e,label:ve(e).label}))}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:n(`system.notificationSystemEventField.oneRuleAnswersOneQuestion`,`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`)})]})}e();function Bs({catalog:e,taxonomy:t,delivery:r,conditions:a,classScope:o,onClassScopeChange:s,actions:c,sequenceActionsOf:l,savedConditions:u,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x,summary:S}){let{t:C}=J(),w=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,b(n)},T=Ne({delivery:r,conditions:a}),E=n(()=>e.filter(e=>be(e,r,T)&&wr(e.id,a)),[e,r,T,a]),D=n(()=>qo(E),[E]),O=e=>E.some(t=>t.id===e),k=e=>Vs.has(e.id)?d(fs,{taxonomy:t,scope:o,onChange:s,exceptOffered:O(`classesExclude`)}):Hs.has(e.id)?d(ss,{conditions:a,onConditionsChange:b,exceptOffered:O(`zonesExclude`),cameraIds:m??p,cameras:h}):Us.has(e.id)?d(cs,{conditions:a,onConditionsChange:b,exceptOffered:O(`identitiesExclude`)}):e.id===`labelEquals`?d(ls,{conditions:a,onConditionsChange:b}):null;return d(`div`,{className:`space-y-4`,children:D.map(e=>i(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${e.id}`,children:[d(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:C(`notificationRules.groups.${e.id}`,e.label)}),e.descriptors.map(e=>{let n=k(e);return i(`div`,{"data-testid":`condition-${e.id}`,children:[d(`label`,{className:Y,children:Ws(e,C)}),n??d(qs,{descriptor:e,kind:T,summary:S===!0,taxonomy:t,conditions:a,actions:c,sequenceActionsOf:l,savedConditions:u,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:w,onScheduleChange:x}),Gs(e,C)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Gs(e,C)})]},e.id)})]},e.id))})}var Vs=new Set([`classes`,`classesExclude`]),Hs=new Set([`zones`,`zonesExclude`]),Us=new Set([`identities`,`identitiesExclude`]);function Ws(e,t){return Vs.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):Hs.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):Us.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 Gs(e,t){if(!Ks.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var Ks=new Set([...Vs,...Hs,...Us,`labelEquals`,`crossing`]);function qs({descriptor:e,kind:t,taxonomy:n,conditions:r,actions:a,sequenceActionsOf:s,savedConditions:c,schedule:l,deviceIds:u,cameras:f,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v,summary:y}){let{t:b}=J();switch(e.valueType){case`deviceIdList`:{if(!En(e.id))break;let t=e.id,n=r[t]??[];return d(en,{cameras:f,fleet:p,emptyMeansAll:!0,savedHadDevices:(c?.[t]?.length??0)>0,value:n,onChange:e=>_(t,e.length>0?e:void 0)})}case`stringList`:{if(!cn(e.id))break;let t=e.id,i=e=>_(t,e.length>0?e:void 0);if(t===`eventTypeTokens`)return d(zn,{deviceIds:u,value:Yn(r,t),onChange:i});let a=Se(t,n);return a===null?d(Jn,{value:Yn(r,t),placeholder:b(`system.notificationRuleConditions.addValue`,`Add value…`),onChange:i}):d(Cn,{picker:a,value:Yn(r,t),onChange:i})}case`number01`:{if(!zt(e.id))break;let t=e.id;return d(Nr,{value:Un(r,t),min:0,max:1,step:.05,onChange:e=>_(t,e)})}case`number`:{if(!Ln(e.id))break;let t=e.id;return d(Nr,{value:Un(r,t),min:0,step:1,onChange:e=>_(t,e)})}case`sourceSelect`:{if(!Pr(e.id))break;let t=e.id;return Qs(e,r[t],e=>_(t,e))}case`systemEvent`:{if(!Kn(e.id))break;let n=e.id,i=I(t);return i===void 0?d(Rs,{value:r[n]}):d(Ls,{family:i,value:r[n],cameras:f,fleet:p,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[n]?.deviceIds?.length??0)>0,onChange:e=>_(n,e),summary:y===!0})}case`deviceState`:if(!ti(e.id))break;return d(Nn,{gateable:h,value:r.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!Qt(e.id))break;return d(Hn,{scenes:g,value:r.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!pn(e.id))break;let t=e.id;return $s(e,r[t],e=>_(t,e))}case`packagePhase`:{if(!Pn(e.id))break;let t=e.id;return d(V,{value:r[t]??``,options:[{value:``,label:b(`system.notificationRuleConditions.anyPhase`,`— any phase —`)},...Gr(e,xr).map(e=>({value:e.value,label:e.label}))],onChange:e=>_(t,Zs(e.target.value))})}case`sensorTransition`:{if(!un(e.id))break;let t=e.id,n=se({conditions:r,...a===void 0?{}:{actions:a},...s===void 0?{}:{sequenceActionsOf:s}});return i(o,{children:[d(V,{value:r[t]??``,options:Gr(e,lr).map(e=>({value:e.value,label:e.label})),onChange:e=>_(t,_r(e.target.value))}),n&&d(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`nc-sensor-transition-never-fires`,children:`This rule belongs to the alarm, and an alarm rule fires only when an opening OPENS. Set to “only when it clears”, it can never fire.`})]})}case`plateMatcher`:{if(!Bn(e.id))break;let t=e.id;return d(Gn,{value:r[t],onChange:e=>_(t,e)})}case`occupancy`:{if(!tn(e.id))break;let t=e.id;return d(sn,{deviceIds:u,cameras:f,classOptions:Js(n),value:r[t],onChange:e=>_(t,e)})}case`audio`:{if(!an(e.id))break;let t=e.id;return d(Rt,{taxonomy:n,value:r[t],onChange:e=>_(t,e)})}case`schedule`:return d(Jt,{value:l,onChange:v});default:break}return d(Ys,{descriptor:e,conditions:r})}function Js(e){let t=Se(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Ys({descriptor:e,conditions:t}){let{t:n}=J(),r=Object.entries(t).find(([t])=>t===e.id);return i(`p`,{className:Zt,children:[r!==void 0&&r[1]!==void 0?n(`system.notificationRuleConditions.authoredElsewhereAndPreservedThis`,`Authored elsewhere and preserved — this admin editor cannot change it yet.`):n(`system.notificationRuleConditions.notEditableHereYetThis`,`Not editable here yet — this condition has no admin editor.`),` `,i(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function Xs(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Zs(e){return xr.find(t=>t.value===e)?.value}function Qs(e,t,n){return d(V,{value:t??`any`,options:Gr(e,jr).map(e=>({value:e.value,label:e.label})),onChange:e=>n(Xs(e.target.value))})}function $s(e,t,n){return d(In,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function ec({catalog:e,delivery:t,conditions:n,onConditionsChange:r}){let{t:a}=J(),o=Ne({delivery:t,conditions:n}),s=(e,t)=>{let i={...n};t===void 0?delete i[e]:i[e]=t,r(i)},c=r=>e.find(e=>e.id===r&&be(e,t,o)&&wr(r,n)),l=c(`source`),u=c(`crossing`);return l===void 0&&u===void 0?null:i(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[l&&Pr(l.id)&&i(`div`,{"data-testid":`condition-source`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Ws(l,a)}),Qs(l,n.source,e=>s(`source`,e)),Gs(l,a)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Gs(l,a)})]}),u&&pn(u.id)&&i(`div`,{"data-testid":`condition-crossing`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Ws(u,a)}),$s(u,n.crossing,e=>s(`crossing`,e)),Gs(u,a)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Gs(u,a)})]})]})}var tc=[`notificationRules`,`getRuleLastRuns`],nc=3e4;function rc(){let e=E(),t=a({queryKey:tc,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:nc});return{status:t.status,data:t.data,error:t.error}}var ic={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function ac({cell:e}){let{t}=J();switch(e.kind){case`pending`:return d(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":t(`system.notificationRuleLastRun.lastRunLoading`,`Last run loading`),className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return d(`span`,{"data-testid":`rule-last-run-failed`,title:t(`system.notificationRuleLastRun.lastRunCouldNotBe`,`Last run could not be read: {{reason}}`,{reason:e.reason}),className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.phrase});case`ran`:return i(`span`,{className:`flex items-center gap-1.5`,title:new Date(e.lastAt).toLocaleString(),children:[d(`span`,{"data-testid":`rule-last-run-dot`,title:e.status,className:`inline-block h-2 w-2 rounded-full ${ic[e.status]}`}),d(`span`,{className:`text-[11px] text-foreground-subtle`,children:oi(e.lastAt)})]})}}function oc({rule:e,onOpenHistory:t}){let{t:n}=J();return d(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:d(j,{className:`h-3.5 w-3.5`})})}e();var sc=[`notificationRules`,`listSnoozes`],cc=[10,30,60,120];function lc({ruleId:e,ruleName:t,exempt:n=!1,variant:a=`icon`}){let{t:o}=J(),c=E(),l=s(),[f,p]=r(30),[m,h]=r(null),g=u({mutationFn:t=>c.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>l.invalidateQueries({queryKey:sc}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return n?a===`icon`?null:d(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`system.notificationRuleSnoozeControl.thisRuleConcernsOrTriggers`,`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`)}):a===`icon`?d(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:o(`system.notificationRuleSnoozeControl.silenceThisRuleForIt`,`Silence this rule for {{value1}} — it appears under "Silenced right now"`,{value1:An(30)}),"aria-label":o(`system.notificationRuleSnoozeControl.snooze`,`snooze {{ruleName}}`,{ruleName:t}),"data-testid":`nc-rule-snooze-now`,children:g.isPending?d(T,{className:`h-3.5 w-3.5 animate-spin`}):d(He,{className:`h-3.5 w-3.5`})}):i(`div`,{className:`space-y-1`,children:[i(`div`,{className:`flex items-end gap-2`,children:[d(`div`,{className:`w-32`,children:d(V,{value:String(f),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:cc.map(e=>({value:String(e),label:An(e)}))})}),i(U,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(f),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?d(T,{className:`h-3.5 w-3.5 animate-spin`}):d(He,{className:`h-3.5 w-3.5`}),o(`system.notificationRuleSnoozeControl.silenceThisRuleNow`,`Silence this rule now`)]})]}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`system.notificationRuleSnoozeControl.opensARealSnoozeWindow`,`Opens a real snooze window right now — distinct from the buttons above, which only choose the durations this rule's NOTIFICATION offers. It appears under "Silenced right now" and can be ended from there.`)}),m!==null&&d(`p`,{className:`text-[10px] text-danger`,children:m})]})}e();function uc(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function dc(e,t,n){let r=e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n<e.expiresAt).map(e=>e.expiresAt);return r.length===0?null:Math.min(...r)}function fc(e,n){let[,i]=r(0);t(()=>{let t=dc(e,n,Date.now());if(t===null)return;let r=setTimeout(()=>i(e=>e+1),Math.max(0,t-Date.now())+50);return()=>clearTimeout(r)},[e,n])}function pc(){let e=E();return a({queryKey:sc,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function mc({rule:e,snoozes:t,exempt:n}){let{t:r}=J(),a=E(),o=s();fc(t,e.id);let c=uc(t,e.id,Date.now()),l=()=>o.invalidateQueries({queryKey:sc}),f=u({mutationFn:()=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e.id,durationMinutes:30}}),onSuccess:l}),p=u({mutationFn:async e=>{for(let t of e)await a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:l});if(n)return null;let m=f.isError||p.isError;return i(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[d(et,{checked:c.length>0,disabled:!e.enabled||f.isPending||p.isPending,onCheckedChange:e=>e?f.mutate():p.mutate(c),"aria-label":r(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,e.name),title:r(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),m&&d(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:r(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var hc=`pipeline-analytics`,gc=`nc.getRuleStatus`,_c=`nc.testRule`;function vc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function yc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function bc(e){if(!vc(e))return;let t=yc(e,`id`),n=yc(e,`downloadPath`),r=X(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:yc(e,`mediaType`)??`video`,sizeBytes:X(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function xc(e){if(!vc(e))return;let t=X(e,`startMs`),n=X(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function Sc(e){if(!vc(e))return null;let t=X(e,`deviceId`);if(t===void 0)return null;let n=X(e,`lastGeneratedAt`),r=bc(e.lastArtifact),i=e.rendering,a=vc(i)?{startedAt:X(i,`startedAt`)??0,windowStartMs:X(i,`windowStartMs`)??0,windowEndMs:X(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function Cc(e){if(!vc(e))return null;let t=X(e,`deviceId`),n=yc(e,`windowKey`),r=X(e,`openedAt`),i=X(e,`closesAt`),a=X(e,`members`),o=X(e,`pending`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0?null:{deviceId:t,windowKey:n,openedAt:r,closesAt:i,members:a,pending:o}}function wc(e){if(!vc(e))return null;let t=yc(e,`kind`);if(t===`none`)return{kind:`none`,reason:yc(e,`reason`)??``};if(t===`occupancy`){let t=X(e,`deviceId`),n=X(e,`threshold`),r=X(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=yc(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=X(e,`count`),s=X(e,`observedAt`),c=X(e,`since`),l=yc(e,`scope`),u=yc(e,`className`),d=yc(e,`warning`);return{kind:`occupancy`,deviceId:t,threshold:n,sustainSeconds:r,...l===void 0?{}:{scope:l},...u===void 0?{}:{className:u},...o===void 0?{}:{count:o},...typeof e.occupied==`boolean`?{occupied:e.occupied}:{},...s===void 0?{}:{observedAt:s},...c===void 0?{}:{since:c},...a===void 0?{}:{unavailable:a},...d===void 0?{}:{warning:d}}}if(t===`grouped`){let t=X(e,`groupingSec`);if(t===void 0)return null;if(e.openWindows===null){let n=yc(e,`reason`);return{kind:`grouped`,groupingSec:t,openWindows:null,...n===void 0?{}:{reason:n}}}if(!Array.isArray(e.openWindows))return null;let n=[];for(let t of e.openWindows){let e=Cc(t);if(e===null)return null;n.push(e)}return{kind:`grouped`,groupingSec:t,openWindows:n}}if(t===`timelapse`){let t=Array.isArray(e.devices)?e.devices:[],n=[];for(let e of t){let t=Sc(e);t!==null&&n.push(t)}let r=xc(e.lastWindow),i=e.nextWindow,a=vc(i)?{startMs:X(i,`startMs`)??0,endMs:X(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:X(e,`settleMs`)??0}}return null}function Tc(e){let t=Math.max(0,Math.floor(e/6e4));if(t<1)return q.t(`helpers.notificationRuleStatus.lessThanMinute`);if(t<60)return q.t(`helpers.notificationRuleStatus.durMin`,{count:t});let n=Math.floor(t/60),r=t%60;if(n<24)return r===0?q.t(`helpers.notificationRuleStatus.durH`,{count:n}):q.t(`helpers.notificationRuleStatus.durHMin`,{hours:n,minutes:r});let i=Math.floor(n/24),a=n%24;return a===0?q.t(`helpers.notificationRuleStatus.durD`,{count:i}):q.t(`helpers.notificationRuleStatus.durDH`,{days:i,hours:a})}function Ec(e){if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return q.t(`helpers.notificationRuleStatus.sizeKb`,{value:t.toFixed(0)});let n=t/1024;return n<1024?q.t(`helpers.notificationRuleStatus.sizeMb`,{value:n.toFixed(1)}):q.t(`helpers.notificationRuleStatus.sizeGb`,{value:(n/1024).toFixed(2)})}function Dc(e,t){let n=e.scope??`the whole frame`,r=e.className??`objects`;if(e.unavailable!==void 0){let t=e.unavailable===`no-snapshot`?`no live count for this camera yet — the condition fails closed until one arrives`:`“${n}” is not in this camera’s current snapshot — the condition fails closed (deleted zone?)`;return e.warning===void 0?t:`${e.warning} · ${t}`}let i=[`Now: ${String(e.count??0)}/${String(e.threshold)} ${r} in ${n}`,e.occupied===!0?`condition TRUE`:`condition false`];e.since!==void 0&&i.push(`for ${Tc(Math.max(0,t-e.since))}`),i.push(`holds ${String(e.sustainSeconds)} s before firing`);let a=i.join(` · `);return e.warning===void 0?a:`${e.warning} · ${a}`}function Oc(e,t,n){if(e.rendering!==void 0)return q.t(`helpers.notificationRuleStatus.tlRendering`,{camera:t,duration:Tc(Math.max(0,n-e.rendering.startedAt)),from:new Date(e.rendering.windowStartMs).toLocaleString(),to:new Date(e.rendering.windowEndMs).toLocaleString()});if(e.lastGeneratedAt===void 0)return q.t(`helpers.notificationRuleStatus.tlNever`,{camera:t});let r=new Date(e.lastGeneratedAt).toLocaleString(),i=e.lastArtifact;return i===void 0?q.t(`helpers.notificationRuleStatus.tlGone`,{camera:t,when:r}):q.t(`helpers.notificationRuleStatus.tlLast`,{camera:t,when:r,size:Ec(i.sizeBytes)})}function kc(e){return{windows:e.length,waiting:e.reduce((e,t)=>e+t.pending,0)}}var Ac=`nc.listPrunes`;function jc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Mc=new Set([`rule`,`timelapse`,`summary`]),Nc=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function Pc(e){return typeof e==`string`&&Mc.has(e)}function Fc(e){return typeof e==`string`&&Nc.has(e)}function Ic(e){return e===`device`||e===`target`}function Lc(e){if(!jc(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!Pc(t)||!Ic(r)||!Fc(o)||typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||typeof s!=`number`?null:{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}}function Rc(e){return!jc(e)||!Array.isArray(e.prunes)?null:e.prunes.map(Lc).filter(e=>e!==null)}function zc(e,t,n,r,i){if(r)return null;let a=e.filter(e=>e.kind===t&&e.ruleId===n);return i>a.reduce((e,t)=>Math.max(e,t.at),-1/0)?null:a.filter(e=>e.outcome===`kept-disabled`).reduce((e,t)=>e===null||t.at>e.at?t:e,null)}function Bc(e,t){let n=t(e.at);return e.subjectKind===`device`?q.t(`helpers.notificationPrunes.lastDevice`,{when:n,subject:e.subject}):q.t(`helpers.notificationPrunes.lastTarget`,{when:n,subject:e.subject})}function Vc(e){return new Date(e).toLocaleDateString()}function Hc({kind:e,ruleId:t,enabled:n,updatedAt:r}){let o=E(),s=a({queryKey:[`pipelineAnalytics`,Ac],enabled:!n,staleTime:3e4,retry:!1,queryFn:async()=>Rc(await o.trpcClient.addons.custom.mutate({addonId:hc,action:Ac,input:{}}))}).data;if(s==null)return null;let c=zc(s,e,t,n,r);return c===null?null:i(`div`,{"data-testid":`nc-prune-banner`,className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-foreground`,children:[d(w,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),d(`span`,{children:Bc(c,Vc)})]})}var Uc=5e3;function Wc({status:e,now:t,name:n}){let{t:r}=J();if(e.openWindows===null)return i(`p`,{className:`flex items-start gap-1.5`,children:[d(k,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),d(`span`,{"data-testid":`nc-grouped-status-headline`,children:r(`notificationRules.status.grouped.unknown`,{reason:e.reason??``,defaultValue:`Open windows unknown — {{reason}}`})})]});let a=e.openWindows,{windows:s,waiting:c}=kc(a);return i(o,{children:[i(`p`,{className:`flex items-start gap-1.5`,children:[d(k,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),d(`span`,{"data-testid":`nc-grouped-status-headline`,children:s===0?r(`notificationRules.status.grouped.none`,`No window open`):`${r(`notificationRules.status.grouped.windows`,{count:s,defaultValue_one:`{{count}} open window`,defaultValue_other:`{{count}} open windows`})} · ${r(`notificationRules.status.grouped.waiting`,{count:c,defaultValue:`{{count}} waiting`})}`})]}),a.map(e=>i(`p`,{className:`flex items-start gap-1.5`,children:[d(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),d(`span`,{children:r(`notificationRules.status.grouped.windowLine`,{camera:n(e.deviceId),members:e.members,pending:e.pending,seconds:Math.max(0,Math.ceil((e.closesAt-t)/1e3)),defaultValue:`{{camera}} · {{members}} in the window · {{pending}} waiting · closes within {{seconds}} s`})})]},e.windowKey))]})}function Gc({ruleId:e,cameraName:t}){let{t:n}=J(),r=E(),s=a({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:Uc,queryFn:async()=>wc(await r.trpcClient.addons.custom.mutate({addonId:hc,action:gc,input:{ruleId:e}}))}).data;if(s==null||s.kind===`none`)return null;let c=Date.now(),l=e=>t?.(e)??n(`system.notificationRuleStatus.cameraFallback`,{deviceId:e});return i(`div`,{"data-testid":`nc-rule-status`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[s.kind===`occupancy`&&i(`p`,{className:`flex items-start gap-1.5`,children:[s.unavailable!==void 0||s.warning!==void 0?d(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):d(k,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),i(`span`,{children:[d(`span`,{className:`text-foreground`,children:l(s.deviceId)}),` —`,` `,Dc(s,c)]})]}),s.kind===`grouped`&&d(Wc,{status:s,now:c,name:l}),s.kind===`timelapse`&&i(o,{children:[s.devices.map(e=>i(`p`,{className:`flex items-start gap-1.5`,children:[d(k,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),i(`span`,{children:[Oc(e,l(e.deviceId),c),e.lastArtifact!==void 0&&i(o,{children:[` · `,d(`a`,{className:`text-primary hover:underline`,href:`/${e.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:n(`common.open`)})]})]})]},e.deviceId)),i(`p`,{className:`flex items-start gap-1.5`,children:[d(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),i(`span`,{children:[s.nextWindow===void 0?n(`system.notificationRuleStatus.noFurtherWindowOpensIn`,`No further window opens in the next nine days`):n(`system.notificationRuleStatus.nextWindowOpens`,`Next window opens {{value1}}`,{value1:new Date(s.nextWindow.startMs).toLocaleString()}),s.settleMs>0&&` · ${n(`system.notificationRuleStatus.settled`,{minutes:Math.round(s.settleMs/6e4)})}`]})]})]})]})}function Kc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Jc(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Yc(e){if(!Kc(e))return null;let t=qc(e,`ruleId`),n=qc(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=qc(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:qc(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Jc(e,`targetIds`)}}function Xc(e){if(!Kc(e))return null;let t=qc(e,`conditionId`),n=qc(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Zc(e){if(!Kc(e))return;let t=e.split;if(t!==`rule`&&t!==`section`||typeof e.nothingToReport!=`boolean`)return;let n=[];for(let t of Array.isArray(e.sections)?e.sections:[]){if(!Kc(t))continue;let e=qc(t,`id`),r=t.status;e===void 0||r!==`read`&&r!==`unavailable`||n.push({id:e,status:r,items:typeof t.items==`number`?t.items:0})}let r=[];for(let t of Array.isArray(e.rows)?e.rows:[]){if(!Kc(t))continue;let e=qc(t,`section`);r.push({...e===void 0?{}:{section:e},enqueued:typeof t.enqueued==`number`?t.enqueued:0})}return{split:t,nothingToReport:e.nothingToReport,sections:n,rows:r}}function Qc(e){if(!Kc(e))return null;let t=qc(e,`recordId`),n=qc(e,`delivery`);if(t===void 0||n===void 0||e.origin!==`synthetic`)return null;let r=[];for(let t of Array.isArray(e.outcomes)?e.outcomes:[]){let e=Yc(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Xc(t);e!==null&&i.push(e)}let a=qc(e,`droppedBy`),o=Zc(e.stateSummary);return{recordId:t,delivery:n,trigger:qc(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:qc(e,`still`)??`none`,notes:Jc(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function $c(e){if(e.stateSummary!==void 0)return el(e,e.stateSummary);if(e.droppedBy!==void 0)return q.t(`helpers.notificationRuleTest.dropped`,{reason:e.droppedBy});let t=e.outcomes[0];if(t===void 0)return q.t(`helpers.notificationRuleTest.notCandidate`,{trigger:e.trigger});if(!t.matched)return t.failedCondition===void 0?q.t(`helpers.notificationRuleTest.noMatchOwn`):q.t(`helpers.notificationRuleTest.noMatchCond`,{condition:t.failedCondition});if(t.enqueued===0)return q.t(`helpers.notificationRuleTest.matchedNoQueue`);let n=e.still===`live`?` ${q.t(`helpers.notificationRuleTest.stillLive`)}`:e.still===`unavailable`?` ${q.t(`helpers.notificationRuleTest.stillUnavailable`)}`:e.still===`unattachable`?` ${q.t(`helpers.notificationRuleTest.stillUnattachable`)}`:``;return q.t(`helpers.notificationRuleTest.matched`,{queued:t.enqueued,targets:t.targetIds.length,still:n})}function el(e,t){if(t.nothingToReport){let e=t.sections.map(e=>`${e.id}: ${e.status===`unavailable`?q.t(`helpers.notificationRuleTest.unavailable`):q.t(`helpers.notificationRuleTest.noneOpen`)}`).join(`, `);return q.t(`helpers.notificationRuleTest.nothingToReport`,{reads:e})}let n=t.rows.reduce((e,t)=>e+t.enqueued,0),r=e.outcomes[0]?.targetIds.length??0;if(n===0)return q.t(`helpers.notificationRuleTest.summaryNoQueue`);let i=t.rows.flatMap(e=>e.section===void 0?[]:[e.section]).map(e=>`${e} (${String(t.sections.find(t=>t.id===e)?.items??0)})`),a=t.split===`section`?` (${q.t(`helpers.notificationRuleTest.perCategory`,{sections:i.join(`, `)})})`:``;return q.t(`helpers.notificationRuleTest.summaryBuilt`,{queued:n,perCategory:a,targets:r})}e();function tl({ruleId:e,ruleName:t,fallbackDeviceId:n,variant:a=`icon`,showResult:s=!1}){let{t:c}=J(),l=E(),[f,p]=r(null),[m,g]=r(null),_=u({mutationFn:async()=>Qc(await l.trpcClient.addons.custom.mutate({addonId:hc,action:_c,input:{ruleId:e,...n===void 0?{}:{deviceId:n}}})),onMutate:()=>{p(null),g(null)},onSuccess:e=>p(e),onError:e=>g(e instanceof Error?e.message:`The test could not be run.`)}),v=f===null?m===null?void 0:m:$c(f);return i(o,{children:[i(U,{size:`sm`,variant:a===`icon`?`ghost`:`outline`,type:`button`,disabled:_.isPending,onClick:()=>_.mutate(),title:v??c(`system.notificationRuleTestButton.testNowFiresThisRule`,`Test now — fires this rule and really sends the notification`),"aria-label":c(`system.notificationRuleTestButton.testNow`,`test {{ruleName}} now`,{ruleName:t}),"data-testid":`nc-rule-test-now`,children:[_.isPending?d(T,{className:`h-3.5 w-3.5 animate-spin`}):d(Ge,{className:`h-3.5 w-3.5`}),a===`full`&&c(`system.notificationRuleTestButton.testNow2`,`Test now`)]}),s&&m!==null&&d(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:m}),s&&f!==null&&i(`div`,{"data-testid":`nc-rule-test-result`,className:`mt-2 space-y-1 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[d(`p`,{className:`text-foreground`,children:$c(f)}),f.planNotes.map(e=>i(`p`,{className:`flex gap-1.5`,children:[d(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),d(`span`,{children:e.note})]},e.conditionId)),f.notes.map(e=>i(`p`,{children:[`· `,e]},e))]})]})}e();var nl=[`notificationRules`,`listSnoozes`],rl=3e4;function il(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function al(e){if(e===0)return q.t(`system.notificationSnoozes.remEnding`);if(e<60)return q.t(`system.notificationSnoozes.remMin`,{count:e});let t=Math.floor(e/60),n=e%60;return n===0?q.t(`system.notificationSnoozes.remHour`,{count:t}):q.t(`system.notificationSnoozes.remHourMin`,{hours:t,minutes:n})}function ol({rules:e}){let{t}=J(),r=E(),o=s(),c=a({queryKey:nl,refetchInterval:rl,queryFn:async()=>(await r.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),l=u({mutationFn:e=>r.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>o.invalidateQueries({queryKey:nl})}),f=n(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),p=Date.now(),m=(c.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return i(pt,{className:`p-4`,children:[i(`div`,{className:`flex items-center gap-2 mb-3`,children:[d(He,{className:`h-4 w-4 text-foreground-subtle`}),d(`h3`,{className:`text-sm font-medium text-foreground`,children:t(`system.notificationSnoozes.silencedRightNow`,`Silenced right now`)})]}),m.length===0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`system.notificationSnoozes.nothingIsSilencedASnooze`,`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`)}),d(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:m.map(e=>i(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`min-w-0`,children:[i(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:f.get(e.ruleId??``)??`A rule`}),e.global&&d(G,{variant:`warning`,className:`text-[10px]`,children:t(`common.everyone`)}),e.classes!==void 0&&e.classes.length>0&&d(G,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&d(G,{variant:`default`,className:`text-[10px]`,children:t(`system.notificationSnoozes.noSummary`,`no summary`)})]}),d(`span`,{className:`text-[10px] text-foreground-subtle`,children:t(`system.notificationSnoozes.setBy`,{user:e.userId,remaining:al(il(e,p))})})]}),d(U,{size:`sm`,variant:`outline`,disabled:l.isPending,onClick:()=>l.mutate(e.id),children:t(`system.notificationSnoozes.endNow`,`End now`)})]},e.id))})]})}var Z=`block text-[11px] font-medium text-foreground mb-1`,sl=`mt-1 text-[10px] text-foreground-subtle`;function Q({title:e,hint:t,children:n}){return i(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),d(`div`,{className:`space-y-3`,children:n})]})}function cl({problems:e,testId:t=`digest-problems`}){let{t:n}=J();return e.length===0?null:i(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":t,children:[i(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[d(h,{className:`h-3.5 w-3.5`}),n(`system.notificationDigestFields.thisRuleCouldNeverProduce`,`This rule could never produce anything, so it cannot be saved:`)]}),d(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>d(`li`,{children:e},e))})]})}function ll({warnings:e,testId:t=`digest-warnings`}){let{t:n}=J();return e.length===0?null:i(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":t,children:[i(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[d(w,{className:`h-3.5 w-3.5`}),n(`system.notificationDigestFields.worthKnowing`,`Worth knowing:`)]}),d(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>d(`li`,{children:e},e))})]})}function ul({cameras:e,value:t,onChange:n,fleet:r,hint:a}){return i(`div`,{className:`space-y-1`,children:[d(at,{devices:e,listState:r.state,fleet:r,value:t,onChange:n,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),a!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function dl(e){let{t}=J();return d(it,{...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 fl({label:e,value:t,onChange:n,min:r,max:a,step:o,hint:s,emptyPlaceholder:c,testId:l,disabled:u=!1}){return i(`div`,{children:[d(`label`,{className:Z,children:e}),d(W,{type:`number`,value:t===void 0?``:String(t),disabled:u,...r===void 0?{}:{min:r},...a===void 0?{}:{max:a},...o===void 0?{}:{step:o},...c===void 0?{}:{placeholder:c},...l===void 0?{}:{"data-testid":l},onChange:e=>{let t=e.target.value.trim();if(t.length===0){n(void 0);return}let r=Number(t);Number.isFinite(r)&&n(r)}}),s!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function pl({label:e,checked:t,onChange:n,hint:r,testId:a}){return i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(et,{checked:t,onCheckedChange:n,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),r!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:r})]})}function ml({title:e,body:t,onTitleChange:n,onBodyChange:r,family:a,testIdPrefix:o}){let{t:s}=J(),c=xo(),l=e=>c.data?_o(c.data,{family:a,field:e}):void 0;return i(`div`,{className:`space-y-2`,children:[d(Eo,{label:s(`system.notificationDigestFields.notificationTitle`,`Notification title`),value:e,onChange:n,vars:l(`title`),testId:`${o}-title`}),d(Eo,{label:s(`system.notificationDigestFields.notificationBody`,`Notification body`),value:t,onChange:r,vars:l(`body`),multiline:!0,testId:`${o}-body`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`system.notificationDigestFields.leaveBothBlankToUse`,`Leave both blank to use the hub's own wording (editable on the Texts tab).`)}),d(Do,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function hl({open:e,ruleName:t,windowDescription:n,targetDescription:r,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){let{t:u}=J();return e?d(mt,{open:!0,onOpenChange:e=>!e&&s(),children:d(Dt,{width:`sm`,children:i(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[i(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[d(Ge,{className:`h-4 w-4 text-warning`}),u(`system.notificationDigestFields.sendARealNotificationNow`,`Send a real notification now?`)]}),d(`p`,{className:`text-xs text-foreground-subtle`,children:u(`system.notificationDigestFields.confirmSend`,{rule:t,window:n,target:r})}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`system.notificationDigestFields.itDoesNotConsumeThe`,`It does not consume the schedule: the next scheduled run still happens.`)}),c,i(`div`,{className:`flex justify-end gap-2`,children:[d(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:u(`common.cancel`,`Cancel`)}),d(U,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?u(`system.notificationDigestFields.sending`,`Sending…`):u(`system.notificationDigestFields.produceAndSend`,`Produce and send`)})]})]})})}):null}function gl(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 _l=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function vl(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function yl(e){let t=e.windows[0];if(t===void 0)return q.t(`helpers.notificationDigest.noWindow`);let n=t.days.toSorted((e,t)=>e-t).map(e=>_l[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${vl(t.startMinute)}–${vl(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function bl(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return q.t(`helpers.notificationDigest.ago`,{duration:gl(Math.round(r/1e3))})}function xl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sl(e){return Array.isArray(e)?`[${e.map(Sl).join(`,`)}]`:xl(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${Sl(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function Cl(e,t){return Sl(e)===Sl(t)}function wl(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,Tl=`nc.getTexts`,El=`nc.setLanguage`,Dl=`nc.setTextOverrides`,Ol={en:`English`,it:`Italiano`};function kl(e){return e===`en`||e===`it`}function Al(e){return e===`override`||e===`shipped`||e===`fallback`}function jl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ml(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 Nl(e){if(!jl(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`||!kl(r)||!Al(o)||i!==null&&typeof i!=`string`)return null;let s=Ml(e.placeholders),c=Ml(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 Pl(e){if(!jl(e))return null;let{language:t,activeLanguage:n}=e;if(!kl(t)||!kl(n))return null;let r=Ml(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)kl(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=Nl(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Fl(e,t){return t.get(e.key)??e.override??e.shipped}function Il(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 Ll(e,t){return Object.keys(Il(e,t)).length}function Rl(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 zl(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Bl(e){return e.pluralCategories.length===0?null:q.t(`helpers.notificationTexts.pluralWarning`,{categories:e.pluralCategories.join(`, `)})}var Vl=[`notificationCalendarEvents`,`list`],Hl=`nc.listCalendarEventsRules`,Ul=`nc.upsertCalendarEventsRule`,Wl=`nc.deleteCalendarEventsRule`,Gl=Re({timezone:Le().min(1),windows:Be(Re({days:Be(Fe().int().min(0).max(6)).min(1),startMinute:Fe().int().min(0).max(1439),endMinute:Fe().int().min(0).max(1439)})).min(1),invert:Ve().optional()}),Kl=Re({targetId:Le().min(1),params:ze(Le(),Ie()).optional()}),ql=Re({rules:Be(Re({id:Le().min(1),name:Le().min(1),enabled:Ve(),schedule:Gl,calendars:Be(Le().min(1)).max(64).optional(),calendarsExclude:Be(Le().min(1)).max(64).optional(),horizonDays:Fe().int(),deliverEmpty:Ve(),targets:Be(Kl).min(1),template:Re({title:Le().optional(),body:Le().optional()}).optional(),priority:Fe().int(),generatedAt:Fe().optional(),readOnly:Ve().optional()}))});function Jl(e){let t=ql.safeParse(e);return t.success?t.data.rules:null}function Yl(e){return e.readOnly!==!0}var Xl=[{key:`basics`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_basics`)}},{key:`schedule`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_schedule`)}},{key:`calendars`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_calendars`)}},{key:`targets`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_targets`)}},{key:`template`,get label(){return q.t(`helpers.notificationCalendarEvents.tab_template`)}}],Zl=`basics`;function Ql(){return N([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function $l(e){let t=re(e);if(t===null||t.length===0)return yl(e);let n=t[0];if(n===void 0)return yl(e);let r=String(Math.floor(n.minute/60)).padStart(2,`0`),i=String(n.minute%60).padStart(2,`0`),a=t.length>1?` +${t.length-1}`:``;return q.t(`helpers.notificationCalendarEvents.scheduleAt`,{time:`${r}:${i}`,more:a})}function eu(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:Ql(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``}}function tu(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 nu(e){return e.name.trim().length>0&&e.targetIds.length>0&&e.horizonDays>=1&&e.horizonDays<=30&&e.schedule.windows.length>0}function ru(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 iu(e,t){let n=ru(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 au(e){return q.t(`helpers.notificationCalendarEvents.horizon`,{count:e})}function ou(e){return e.calendars!==void 0&&e.calendars.length>0?q.t(`helpers.notificationCalendarEvents.calendars`,{count:e.calendars.length}):e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?q.t(`helpers.notificationCalendarEvents.allExcept`,{count:e.calendarsExclude.length}):q.t(`helpers.notificationCalendarEvents.allCalendars`)}e();function su({rule:e,targets:t,onSaved:n,onCancel:a}){let{t:o}=J(),s=E(),c=vt(),[l,f]=r(()=>e===null?eu():tu(e)),[p,m]=r(()=>mn(e===null?void 0:e.calendars,e===null?void 0:e.calendarsExclude)),[h,g]=r(Zl),[_,v]=r(null),y=e=>f(t=>({...t,...e})),b=u({mutationFn:async()=>{let t=Sn(p),n={...l,calendars:t.include??[],calendarsExclude:t.exclude??[]};if(!nu(n))throw Error(`Name, at least one target, and a schedule are required`);let r=e===null?{rule:ru(n)}:{ruleId:e.id,patch:iu(n,e)};await s.trpcClient.addons.custom.mutate({addonId:$,action:Ul,input:r})},onSuccess:()=>n(),onError:e=>{v(e instanceof Error?e.message:String(e))}}),x=(c.data??[]).map(e=>({id:e.id,name:e.name}));return d(mt,{open:!0,onOpenChange:e=>!e&&a(),children:i(Dt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendar-events-editor`,children:[i(`div`,{className:`mb-3 flex shrink-0 items-center justify-between gap-2 pr-10`,children:[i(`div`,{className:`flex min-w-0 items-center gap-2`,children:[d(Ue,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:e===null?o(`system.notificationCalendarEventsEditor.newCalendarEvents`,`New calendar events`):l.name})]}),d(U,{size:`sm`,type:`button`,disabled:b.isPending,onClick:()=>{v(null),b.mutateAsync()},"data-testid":`calendar-events-save`,children:b.isPending?d(T,{className:`h-3.5 w-3.5 animate-spin`}):o(`common.save`,`Save`)})]}),i(st,{value:h,onValueChange:e=>{let t=Xl.find(t=>t.key===e);t!==void 0&&g(t.key)},children:[d(Xe,{className:`mb-3`,children:Xl.map(e=>d(ut,{value:e.key,children:e.label},e.key))}),i(ht,{className:`space-y-4 pr-1`,children:[_===null?null:d(`p`,{className:`text-sm text-destructive`,children:_}),d(K,{value:`basics`,className:`space-y-3`,children:i(Q,{title:o(`system.notificationCalendarEventsEditor.basics`,`Basics`),children:[i(`label`,{className:`block text-sm`,children:[o(`system.notificationCalendarEventsEditor.name`,`Name`),d(W,{className:`mt-1`,value:l.name,onChange:e=>y({name:e.target.value}),"data-testid":`calendar-events-name`})]}),d(fl,{label:o(`system.notificationCalendarEventsEditor.horizonDays`,`Horizon (days)`),value:l.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&y({horizonDays:e})}}),d(fl,{label:o(`system.notificationCalendarEventsEditor.priority`,`Priority`),value:l.priority,min:1,max:5,onChange:e=>{e!==void 0&&y({priority:e})}}),d(pl,{label:o(`system.notificationCalendarEventsEditor.enabled`,`Enabled`),checked:l.enabled,onChange:e=>y({enabled:e})}),d(pl,{label:o(`system.notificationCalendarEventsEditor.deliverWhenEmpty`,`Deliver when empty`),checked:l.deliverEmpty,onChange:e=>y({deliverEmpty:e})})]})}),d(K,{value:`schedule`,className:`space-y-3`,children:i(Q,{title:o(`system.notificationCalendarEventsEditor.schedule`,`Schedule`),children:[d(Jt,{mode:`times`,value:l.schedule,onChange:e=>y({schedule:e})}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`system.notificationCalendarEventsEditor.oneSendTimePerRow`,`One send time per row. The digest fires at that minute.`)})]})}),d(K,{value:`calendars`,className:`space-y-3`,children:d(Q,{title:o(`system.notificationCalendarEventsEditor.calendars`,`Calendars`),children:d(ns,{draft:p,onChange:m,exceptOffered:!0,plural:`calendars`,describe:e=>x.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>d(at,{devices:x,listState:c.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),d(K,{value:`targets`,className:`space-y-3`,children:d(Q,{title:o(`system.notificationCalendarEventsEditor.targets`,`Targets`),children:d(dl,{targets:t,value:l.targetIds,onChange:e=>y({targetIds:e})})})}),d(K,{value:`template`,className:`space-y-3`,children:i(Q,{title:o(`system.notificationCalendarEventsEditor.template`,`Template`),children:[i(`p`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationCalendarEventsEditor.optionalLeaveBlankForThe`,`Optional. Leave blank for the default digest body (tomorrow highlighted, then later days). Variables:`),` `,o(`system.notificationCalendarEventsEditor.templateVars`,{ruleVar:`{{rule}}`,countVar:`{{count}}`,horizonVar:`{{horizonDays}}`,eventsVar:`{{events}}`})]}),i(`label`,{className:`block text-sm`,children:[o(`system.notificationCalendarEventsEditor.title`,`Title`),d(W,{className:`mt-1`,value:l.templateTitle,onChange:e=>y({templateTitle:e.target.value})})]}),i(`label`,{className:`block text-sm`,children:[o(`system.notificationCalendarEventsEditor.body`,`Body`),d(`textarea`,{className:`mt-1 min-h-[8rem] w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:l.templateBody,onChange:e=>y({templateBody:e.target.value})})]})]})})]})]})]})})}var cu=`nc.listSummaryRules`,lu=`nc.upsertSummaryRule`,uu=`nc.deleteSummaryRule`,du=`nc.testSummaryRule`,fu=3600,pu=86400,mu=3600,hu=3600,gu=3*36e5,_u=[`importance`,`recency`,`dwell`],vu={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},yu=[`none`,`tiles`,`all`],bu=`none`,xu={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},Su=[`en`,`it`],Cu=[`deliver-without-text`,`skip`],wu=2048,Tu=2e3;function Eu(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Du(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ou(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 ku(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 Au(e){if(e!==void 0)return typeof e==`string`?e:null}function ju(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function Mu(e){return _u.some(t=>t===e)}function Nu(e){return e===void 0?bu:yu.find(t=>t===e)??null}function Pu(e){if(!Du(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Du(n))return null;let e=Ou(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=Au(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 Fu(e){if(!Du(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=Pu(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 Iu(e){if(e==null)return;if(!Du(e))return null;let t=e.classes===void 0?void 0:ku(e.classes),n=e.classesExclude===void 0?void 0:ku(e.classesExclude),r=e.zones===void 0?void 0:ku(e.zones);if(t===null||n===null||r===null)return null;let i=ju(e.minImportance),a=ju(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 Lu(e){if(e==null)return;if(!Du(e))return null;let t=Au(e.title),n=Au(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function Ru(e){return Su.some(t=>t===e)}function zu(e){return Cu.some(t=>t===e)}function Bu(e){if(e==null)return;if(!Du(e)||typeof e.enabled!=`boolean`)return null;let t=Au(e.profileId),n=Au(e.prompt);if(t===null||n===null)return null;let r=ju(e.maxImagePx),i=ju(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!Ru(a))return null;let o=e.onFailure;return o!==void 0&&!zu(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 Vu(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Du(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Du(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function Hu(e){if(!Du(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`||!Mu(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Ou(e.deviceIds),u=Fu(e.window),d=Vu(e.targets);if(l===null||u===null||d===null)return null;let f=Iu(e.filters),p=Lu(e.template);if(f===null||p===null)return null;let m=Au(e.captionText),h=ju(e.generatedAt),g=ju(e.updatedAt);if(m===null||h===null||g===null)return null;let _=Nu(e.captions);if(_===null)return null;let v=Bu(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 Uu(e){if(!Du(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=Hu(n);if(e===null)return null;t.push(e)}return t}function Wu(e){if(!Du(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=ju(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=ju(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Au(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 Gu(){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:bu,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function Ku(e){let t=Gu(),n=e.window.kind===`motion`?e.window:null;return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],windowKind:e.window.kind,schedule:e.window.kind===`schedule`?e.window.schedule:void 0,quietSeconds:n?.quietSeconds??t.quietSeconds,maxWindowSeconds:n?.maxWindowSeconds??t.maxWindowSeconds,classes:[...e.filters?.classes??[]],classesExclude:[...e.filters?.classesExclude??[]],zones:[...e.filters?.zones??[]],minImportance:e.filters?.minImportance,minDwellSeconds:e.filters?.minDwellSeconds,includeStationary:e.filters?.includeStationary===!0,maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,mosaicCaptions:e.captions,captionText:e.captionText??``,deliverEmpty:e.deliverEmpty,priority:e.priority,aiEnabled:e.ai?.enabled??t.aiEnabled,aiProfileId:e.ai?.profileId??``,aiPrompt:e.ai?.prompt??``,aiLanguage:e.ai?.language??``,aiMaxImagePx:e.ai?.maxImagePx,aiTimeoutSeconds:e.ai?.timeoutMs===void 0?void 0:Math.round(e.ai.timeoutMs/1e3),aiOnFailure:e.ai?.onFailure??t.aiOnFailure}}function qu(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Ju(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 Yu(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 Xu(e){return wl(e.targetIds)}function Zu(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 Qu(e){let t=Ju(e),n=Yu(e),r=Zu(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:qu(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Xu(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 $u(e,t){let n=Qu(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),Cl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),Cl(n.window,t.window)||(r.window=n.window),Cl(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),Cl(n.targets,t.targets)||(r.targets=n.targets),Cl(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),Cl(n.ai,t.ai)||(r.ai=n.ai??null),r}function ed(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 ${fu}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 ${mu}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 ${hu}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 ${Tu} 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 ${wu} 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 td(e){return ed(e).length===0}function nd(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 rd=[{key:`rule`,get label(){return q.t(`helpers.notificationSummaries.tab_rule`)},fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,get label(){return q.t(`helpers.notificationSummaries.tab_window`)},fields:[`windowKind`,`schedule`,`quietSeconds`,`maxWindowSeconds`,`barrierSeconds`]},{key:`content`,get label(){return q.t(`helpers.notificationSummaries.tab_content`)},fields:[`classes`,`classesExclude`,`zones`,`minImportance`,`minDwellSeconds`,`includeStationary`]},{key:`mosaic`,get label(){return q.t(`helpers.notificationSummaries.tab_mosaic`)},fields:[`maxTiles`,`rank`,`mosaicCaptions`,`captionText`]},{key:`ai`,label:`AI`,fields:[`aiEnabled`,`aiProfileId`,`aiPrompt`,`aiLanguage`,`aiMaxImagePx`,`aiTimeoutSeconds`,`aiOnFailure`,`maxAiImages`]},{key:`delivery`,get label(){return q.t(`helpers.notificationSummaries.tab_delivery`)},fields:[`targetIds`,`priority`,`deliverEmpty`,`templateTitle`,`templateBody`]}],id=`rule`;function ad(e){return rd.find(t=>t.key===e)?.key}function od(e){return e.kind===`motion`?q.t(`helpers.notificationSummaries.winMotion`,{quiet:gl(e.quietSeconds),max:gl(e.maxWindowSeconds)}):e.kind===`unsupported`?q.t(`helpers.notificationSummaries.winUnsupported`,{raw:e.raw}):q.t(`helpers.notificationSummaries.winSchedule`,{schedule:yl(e.schedule)})}function sd(e,t){return bl(e,t,`Never run`)}function cd(e){if(e===void 0)return q.t(`helpers.notificationSummaries.allPassages`);let t=[];return e.classes!==void 0&&e.classes.length>0&&t.push(e.classes.join(`, `)),e.classesExclude!==void 0&&e.classesExclude.length>0&&t.push(q.t(`helpers.notificationSummaries.filterNot`,{classes:e.classesExclude.join(`, `)})),e.zones!==void 0&&e.zones.length>0&&t.push(q.t(`helpers.notificationSummaries.filterZones`,{count:e.zones.length})),e.minImportance!==void 0&&t.push(q.t(`helpers.notificationSummaries.filterImportance`,{value:e.minImportance})),e.minDwellSeconds!==void 0&&t.push(q.t(`helpers.notificationSummaries.filterStay`,{value:gl(e.minDwellSeconds)})),e.includeStationary===!0&&t.push(q.t(`helpers.notificationSummaries.filterParked`)),t.length===0?q.t(`helpers.notificationSummaries.allPassages`):t.join(` · `)}function ld(e){return{windowStartMs:e-gu,windowEndMs:e}}e();var ud={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},dd={en:`English`,it:`Italiano`};function fd(e){return _u.find(t=>t===e)}function pd(e){return yu.find(t=>t===e)}function md(e){return Su.find(t=>t===e)??``}function hd(e){return Cu.find(t=>t===e)}function gd({rule:e,cameras:t,fleet:o,targets:s,taxonomy:c,onSaved:l,onCancel:f}){let{t:p}=J(),m=E(),[h,g]=r(()=>e===null?Gu():Ku(e)),[_,v]=r(null),[y,b]=r(e!==null),[x,S]=r(id),C=e=>g(t=>({...t,...e})),w=n(()=>{let e=Se(`occupancy`,c);return e===null?[]:e.groups.flatMap(e=>e.options)},[c]),{options:D,loading:O}=Yt(h.deviceIds,t.map(e=>({id:e.id,name:e.name}))),k=a({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>m.trpcClient.llm.listProfiles.query({}),retry:!1}),A=(k.data??[]).filter(e=>e.supportsVision),j=u({mutationFn:async()=>{let t=e===null?{rule:Qu(h)}:{ruleId:e.id,patch:$u(h,e)};await m.trpcClient.addons.custom.mutate({addonId:$,action:lu,input:t})},onSuccess:l,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),M=xo(),N=M.data?_o(M.data,{family:`summary`,field:`captionText`}):void 0,P=h.mosaicCaptions===`all`,F=ed(h),I=nd(h),ee=rd.some(e=>e.key===x)?x:id;return d(mt,{open:!0,onOpenChange:e=>!e&&f(),children:i(Dt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[d(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:i(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[d(qe,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:e===null?p(`system.notificationSummaryEditor.newSummary`,`New summary`):p(`system.notificationSummaryEditor.edit`,`Edit {{name}}`,{name:e.name})})]})}),_!==null&&d(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),i(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&d(Hc,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),y?d(cl,{problems:F,testId:`summary-problems`}):null,d(ll,{warnings:I,testId:`summary-warnings`})]}),i(st,{value:ee,onValueChange:e=>S(ad(e)??x),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[d(Xe,{className:`mb-3 shrink-0`,children:rd.map(e=>d(ut,{value:e.key,children:e.label},e.key))}),i(ht,{className:`pr-1`,children:[i(K,{value:`rule`,className:`space-y-3`,children:[d(Q,{title:p(`system.notificationSummaryEditor.whatItIs`,`What it is`),hint:p(`system.notificationSummaryEditor.oneWindowOnePictureThe`,`One window, one picture: the best shot of every track the window held, laid out as one mosaic and delivered once.`),children:i(`div`,{className:`flex items-end gap-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.name`,`Name`)}),d(W,{value:h.name,onChange:e=>C({name:e.target.value}),placeholder:p(`system.notificationSummaryEditor.eGOvernightSweep`,`e.g. Overnight sweep`),"data-testid":`summary-name`})]}),d(`div`,{className:`pb-1.5`,children:d(pl,{label:p(`system.notificationSummaryEditor.enabled`,`Enabled`),checked:h.enabled,onChange:e=>C({enabled:e}),testId:`summary-enabled`})})]})}),d(Q,{title:p(`system.notificationSummaryEditor.cameras`,`Cameras`),hint:p(`system.notificationSummaryEditor.everyCameraInTheDigest`,`Every camera in the digest gets at least one tile when it contributed anything — a digest in which two of six cameras never appear is not multi-camera.`),children:d(ul,{cameras:t,value:h.deviceIds,fleet:o,onChange:e=>C({deviceIds:e}),hint:p(`system.notificationSummaryEditor.theFirstCameraSelectedOwns`,`The first camera selected owns the delivered notification.`)})})]}),d(K,{value:`window`,className:`space-y-3`,children:i(Q,{title:p(`system.notificationSummaryEditor.whenTheWindowCloses`,`When the window closes`),children:[i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.window`,`Window`)}),d(V,{value:h.windowKind,options:[{value:`motion`,label:p(`system.notificationSummaryEditor.motionOpenedAndClosedBy`,`Motion — opened and closed by activity`)},{value:`schedule`,label:p(`system.notificationSummaryEditor.scheduleFixedWeeklyWindows`,`Schedule — fixed weekly windows`)}],onChange:e=>C({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),h.windowKind===`motion`?i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(fl,{label:p(`system.notificationSummaryEditor.quietPeriodSeconds`,`Quiet period (seconds)`),value:h.quietSeconds,min:30,max:fu,onChange:e=>C({quietSeconds:e??0}),hint:p(`system.notificationSummaryEditor.theWindowOpensOnThe`,`The window opens on the first motion on any of these cameras and stays open while more arrives. This much silence closes it.`),testId:`summary-quiet`}),d(fl,{label:p(`system.notificationSummaryEditor.longestWindowSeconds`,`Longest window (seconds)`),value:h.maxWindowSeconds,min:60,max:pu,onChange:e=>C({maxWindowSeconds:e??0}),hint:p(`system.notificationSummaryEditor.aPermanentlyBusyDrivewayWould`,`A permanently busy driveway would otherwise never deliver. At this bound the window closes with whatever it holds.`),testId:`summary-max-window`})]}):i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.weeklyWindows`,`Weekly windows`)}),d(Jt,{value:h.schedule,onChange:e=>C({schedule:e})}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.theDigestIsProducedWhen`,`The digest is produced when a window CLOSES, and covers exactly that window. The first one is the first window that closes after you save — nothing is backfilled.`)})]}),d(fl,{label:p(`system.notificationSummaryEditor.waitForOpenTracksSeconds`,`Wait for open tracks (seconds)`),value:h.barrierSeconds,min:0,max:mu,onChange:e=>C({barrierSeconds:e??0}),hint:p(`system.notificationSummaryEditor.aTrackSBestShot`,`A track's best shot is written when the track ENDS. Rendering the instant the window closes would show every still-moving subject with no picture. 0 disables the wait.`),testId:`summary-barrier`})]})}),d(K,{value:`content`,className:`space-y-3`,children:i(Q,{title:p(`system.notificationSummaryEditor.whatGoesIn`,`What goes in`),hint:p(`system.notificationSummaryEditor.evaluatedOnTracksOnePassage`,`Evaluated on tracks: one passage is one tile.`),children:[i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.classes`,`Classes`)}),d(_n,{options:w,value:h.classes,onChange:e=>C({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.emptyEveryClassOnlyThe`,`Empty = every class. Only the macro classes are offered: a digest matches the class stored on the track, and tracks store macros — a sub-type would match nothing, forever.`)})]}),i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.excludedClasses`,`Excluded classes`)}),d(_n,{options:w,value:h.classesExclude,onChange:e=>C({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.zones`,`Zones`)}),d(_n,{options:D,value:h.zones,onChange:e=>C({zones:e}),loading:O,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.zonesAreScopedPerCamera`,`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`)})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(fl,{label:p(`system.notificationSummaryEditor.minimumImportance`,`Minimum importance`),value:h.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>C({minImportance:e}),hint:p(`system.notificationSummaryEditor.thePipelineSOwnScore`,`The pipeline's own score, 0–1. Empty keeps everything.`),testId:`summary-min-importance`}),d(fl,{label:p(`system.notificationSummaryEditor.minimumStaySeconds`,`Minimum stay (seconds)`),value:h.minDwellSeconds,min:0,max:hu,emptyPlaceholder:`any`,onChange:e=>C({minDwellSeconds:e}),hint:p(`system.notificationSummaryEditor.dropsThePassagesTooBrief`,`Drops the passages too brief to be worth a tile.`),testId:`summary-min-dwell`})]}),d(pl,{label:p(`system.notificationSummaryEditor.includeParkedObjects`,`Include parked objects`),checked:h.includeStationary,onChange:e=>C({includeStationary:e}),hint:p(`system.notificationSummaryEditor.offByDefaultACar`,`Off by default. A car left in the drive is tracked until it is recognised as parked, and it stays parked for as long as it is there — with this on, a digest fills up with the same stationary object instead of the passages. Parked objects remain on the Events page either way.`),testId:`summary-include-stationary`})]})}),d(K,{value:`mosaic`,className:`space-y-3`,children:i(Q,{title:p(`system.notificationSummaryEditor.theMosaic`,`The mosaic`),children:[i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(fl,{label:p(`system.notificationSummaryEditor.tiles`,`Tiles`),value:h.maxTiles,min:1,max:24,onChange:e=>C({maxTiles:e??1}),hint:p(`system.notificationSummaryEditor.9A33Grid`,`9 (a 3×3 grid) is the most a phone lock-screen thumbnail can carry and still be read.`),testId:`summary-max-tiles`}),i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.whenThereAreMoreTracks`,`When there are more tracks than tiles`)}),d(V,{value:h.rank,options:_u.map(e=>({value:e,label:vu[e]})),onChange:e=>{let t=fd(e.target.value);t!==void 0&&C({rank:t})},"data-testid":`summary-rank`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.everyContributingCameraKeepsIts`,`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`)})]})]}),i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.textOnTheMosaic`,`Text on the mosaic`)}),d(V,{value:h.mosaicCaptions,options:yu.map(e=>({value:e,label:xu[e]})),onChange:e=>{let t=pd(e.target.value);t!==void 0&&C({mosaicCaptions:t})},"data-testid":`summary-captions`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.imagesOnlyIsTheDefault`,`Images only is the default, and it is what a rule with nothing set here does. Anything drawn is burnt into the picture for good — a label covers the bottom of the tile, which is where feet, wheels and parcels are, and a caption from a detection that was wrong cannot be un-drawn. Nothing downstream needs the words: the written summary reads the frames themselves and is told the camera, the class and the time in its prompt.`)})]}),i(`div`,{children:[d(Eo,{label:p(`system.notificationSummaryEditor.captionBurnedOntoTheMosaic`,`Caption burned onto the mosaic`),value:h.captionText,disabled:!P,onChange:e=>C({captionText:e}),placeholder:p(`system.notificationSummaryEditor.leaveEmptyForNoCaption`,`Leave empty for no caption`),vars:N,testId:`summary-caption`}),d(`p`,{className:sl,children:P?p(`system.notificationSummaryEditor.acrossTheTopBand`,`Across the top band.`):p(`system.notificationSummaryEditor.onlyDrawnWithTileLabels`,`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`)})]})]})}),d(K,{value:`ai`,className:`space-y-3`,children:i(Q,{title:p(`system.notificationSummaryEditor.writtenSummary`,`Written summary`),hint:p(`system.notificationSummaryEditor.oneVisionCallOverThe`,`One vision call over the window's best frames TOGETHER, so the answer is an account of what happened rather than a list of pictures. The sentence goes in the notification body.`),children:[d(pl,{label:p(`system.notificationSummaryEditor.haveAModelDescribeThe`,`Have a model describe the window`),checked:h.aiEnabled,onChange:e=>C({aiEnabled:e}),hint:p(`system.notificationSummaryEditor.offByDefaultTheMosaic`,`Off by default. The mosaic and the counts are delivered either way.`),testId:`summary-ai-enabled`}),!h.aiEnabled&&d(`p`,{className:`rounded-md border border-border bg-surface px-2.5 py-1.5 text-[10px] text-foreground-muted`,"data-testid":`summary-ai-off-note`,children:p(`system.notificationSummaryEditor.theSwitchAboveIsOff`,`The switch above is off, so nothing below it can be edited. Everything you already set is kept — turning it on hands the fields back exactly as you left them.`)}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.visionProfile`,`Vision profile`)}),d(V,{value:h.aiProfileId,disabled:!h.aiEnabled,options:[{value:``,label:p(`system.notificationSummaryEditor.theHubSDefaultVision`,`The hub's default vision profile`)},...A.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>C({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),d(`p`,{className:sl,children:k.isError?p(`system.notificationSummaryEditor.thisHubDidNotAnswer`,`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`):A.length===0?p(`system.notificationSummaryEditor.noVisionCapableProfileOn`,`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`):p(`system.notificationSummaryEditor.onlyVisionCapableProfilesAre`,`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`)})]}),i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.answerIn`,`Answer in`)}),d(V,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:p(`system.notificationSummaryEditor.donTAskForA`,`Don’t ask for a language`)},...Su.map(e=>({value:e,label:dd[e]}))],onChange:e=>C({aiLanguage:md(e.target.value)}),"data-testid":`summary-ai-language`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.nothingIsAddedToThe`,`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`)})]})]}),i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.yourQuestionOptional`,`Your question (optional)`)}),d(`textarea`,{value:h.aiPrompt,rows:3,maxLength:Tu,disabled:!h.aiEnabled,onChange:e=>C({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:p(`system.notificationSummaryEditor.eGTellMeWhether`,`e.g. Tell me whether anybody approached the gate, and whether a parcel was left.`),className:`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.leaveBlankForWhatHappened`,`Leave blank for “what happened during this period?”. Your words are the only free text the model is given: what the cameras are called and what the pipeline classified are reduced to plain labels first, and anything written INSIDE a frame — a sign, a plate, an overlay — is treated as scenery, never as an instruction.`)})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(fl,{label:p(`system.notificationSummaryEditor.framesTheModelMayLook`,`Frames the model may look at`),value:h.maxAiImages,min:1,max:8,disabled:!h.aiEnabled,onChange:e=>C({maxAiImages:e??1}),hint:p(`system.notificationSummaryEditor.theHighestRankedTilesSent`,`The highest-ranked tiles, sent as ONE question. Bounded separately from the tile budget — one is bounded by pixels, the other by the model's time — and never larger than it.`),testId:`summary-max-ai-images`}),d(fl,{label:p(`system.notificationSummaryEditor.timeLimitSeconds`,`Time limit (seconds)`),value:h.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!h.aiEnabled,onChange:e=>C({aiTimeoutSeconds:e}),hint:p(`system.notificationSummaryEditor.nobodyIsWaitingOnA`,`Nobody is waiting on a phone for a digest, so this is generous. At the bound the generation is cancelled, not merely abandoned.`),testId:`summary-ai-timeout`})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(fl,{label:p(`system.notificationSummaryEditor.frameSizeSentPixels`,`Frame size sent (pixels)`),value:h.aiMaxImagePx,min:64,max:wu,emptyPlaceholder:`448`,disabled:!h.aiEnabled,onChange:e=>C({aiMaxImagePx:e}),hint:p(`system.notificationSummaryEditor.longestEdge448IsThe`,`Longest edge. 448 is the native tile size of these vision encoders — larger costs tokens and latency without adding detail the encoder can see.`),testId:`summary-ai-max-px`}),i(`div`,{children:[d(`label`,{className:Z,children:p(`system.notificationSummaryEditor.ifTheModelGivesNo`,`If the model gives no answer`)}),d(V,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:Cu.map(e=>({value:e,label:ud[e]})),onChange:e=>{let t=hd(e.target.value);t!==void 0&&C({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),d(`p`,{className:sl,children:p(`system.notificationSummaryEditor.aColdModelAnUnreachable`,`A cold model, an unreachable endpoint or an answer the hub cannot parse are all this case. The default delivers: the mosaic and the counts are worth more than silence, and a closed window does not come back.`)})]})]})]})}),d(K,{value:`delivery`,className:`space-y-3`,children:i(Q,{title:p(`system.notificationSummaryEditor.delivery`,`Delivery`),children:[d(dl,{targets:s,value:h.targetIds,onChange:e=>C({targetIds:e})}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(fl,{label:p(`system.notificationSummaryEditor.priority`,`Priority`),value:h.priority,min:1,max:5,onChange:e=>C({priority:e??3}),testId:`summary-priority`}),d(pl,{label:p(`system.notificationSummaryEditor.deliverAWindowThatMatched`,`Deliver a window that matched nothing`),checked:h.deliverEmpty,onChange:e=>C({deliverEmpty:e}),hint:p(`system.notificationSummaryEditor.offByDefaultANightly`,`Off by default: a nightly '0 events' is a line nobody reads, and it costs the lines beside it their reader.`),testId:`summary-deliver-empty`})]}),d(ml,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>C({templateTitle:e}),onBodyChange:e=>C({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),d(`p`,{className:sl,children:d(Sr,{i18nKey:`system.notificationSummaryEditor.aiToken`,values:{token:`{{ai}}`},components:{code:d(`code`,{})}})})]})})]})]}),i(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[d(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:p(`common.cancel`,`Cancel`)}),i(U,{size:`sm`,type:`button`,disabled:j.isPending,onClick:()=>{b(!0),!(!td(h)||j.isPending)&&j.mutate()},children:[j.isPending&&d(T,{className:`h-3.5 w-3.5 animate-spin`}),e===null?p(`system.notificationSummaryEditor.create`,`Create`):p(`common.save`,`Save`)]})]})]})})}var _d=`nc.listTimelapseRules`,vd=`nc.upsertTimelapseRule`,yd=`nc.deleteTimelapseRule`,bd=`nc.testTimelapseRule`,xd=3600,Sd=3600,Cd=30,wd=1,Td=[`image`,`gif`],Ed={image:`Still frame`,gif:`Short animation (GIF)`},Dd=Re({rules:Be(Ae.extend({readOnly:Ve().optional()}))});function Od(e){let t=Dd.safeParse(e);return t.success?t.data.rules:null}function kd(e){return e.readOnly!==!0}var Ad=Re({produced:Fe(),exportId:Le().optional(),coveragePercent:Fe().optional(),enqueued:Fe().optional(),windowStartMs:Fe().optional(),windowEndMs:Fe().optional(),error:Le().optional()});function jd(e){let t=Ad.safeParse(e);return t.success?t.data:null}function Md(){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 Nd(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 Pd={windows:[{days:[1],startMinute:0,endMinute:60}]};function Fd(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 Id(e){let t=Fd(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??Pd,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:wl(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 Ld(e,t){let n=Id(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),Cl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),Cl(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??Rd(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),Cl(n.targets,t.targets)||(r.targets=n.targets),Cl(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),Cl(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function Rd(e){return Math.max(wd,e/Cd)}function zd(e,t,n){return t<=0||n<=0?0:e/t/n}function Bd(e,t){return e*t*F}function Vd(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 ${xd}.`),(!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 ${F}s and ${Sd}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 Hd(e){return Vd(e).length===0}function Ud(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=Bd(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 Wd(e){return yl(e)}function Gd(e,t){return bl(e,t,`Never run`)}function Kd(e){return e.denseCadenceSec===void 0?{seconds:Rd(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var qd=[{key:`rule`,get label(){return q.t(`helpers.notificationTimelapse.tab_rule`)},fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,get label(){return q.t(`helpers.notificationTimelapse.tab_window`)},fields:[`schedule`]},{key:`sampling`,get label(){return q.t(`helpers.notificationTimelapse.tab_sampling`)},fields:[`cadenceSec`,`framerate`,`denseCadenceSec`,`minDwellSec`]},{key:`delivery`,get label(){return q.t(`helpers.notificationTimelapse.tab_delivery`)},fields:[`targetIds`,`priority`,`previewMode`,`previewText`,`previewTextSet`,`templateTitle`,`templateBody`,`reportClasses`]}],Jd=`rule`;function Yd(e){return qd.find(t=>t.key===e)?.key}e();var Xd=7;function Zd(e){return Td.find(t=>t===e)}function Qd({rule:e,cameras:t,fleet:n,targets:a,onSaved:s,onCancel:c}){let{t:l}=J(),p=E(),[m,h]=r(()=>e===null?Md():Nd(e)),[g,_]=r(null),[v,y]=r(e!==null),[b,x]=r(Jd),S=e=>h(t=>({...t,...e})),C=xo(),w=C.data?_o(C.data,{family:`timelapse`,field:`previewText`}):void 0,D=u({mutationFn:async()=>{let t=e===null?{rule:Id(m)}:{ruleId:e.id,patch:Ld(m,e)};await p.trpcClient.addons.custom.mutate({addonId:$,action:vd,input:t})},onSuccess:s,onError:e=>_(e instanceof Error?e.message:`Save failed`)}),O=Vd(m),k=Ud(m),A=Kd(m),j=zd(Xd,A.seconds,m.framerate),M=qd.some(e=>e.key===b)?b:Jd;return d(mt,{open:!0,onOpenChange:e=>!e&&c(),children:i(Dt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[d(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:i(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[d(f,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:e===null?l(`system.notificationTimelapseEditor.newTimelapse`,`New timelapse`):l(`system.notificationTimelapseEditor.edit`,`Edit {{name}}`,{name:e.name})})]})}),g!==null&&d(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:g}),i(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&d(Hc,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),v?d(cl,{problems:O,testId:`timelapse-problems`}):null,d(ll,{warnings:k,testId:`timelapse-warnings`})]}),i(st,{value:M,onValueChange:e=>x(Yd(e)??b),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[d(Xe,{className:`mb-3 shrink-0`,children:qd.map(e=>d(ut,{value:e.key,children:e.label},e.key))}),i(ht,{className:`pr-1`,children:[i(K,{value:`rule`,className:`space-y-3`,children:[d(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:i(`div`,{className:`flex items-end gap-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.name`,`Name`)}),d(W,{value:m.name,onChange:e=>S({name:e.target.value}),placeholder:l(`system.notificationTimelapseEditor.eGNightDriveway`,`e.g. Night driveway`),"data-testid":`timelapse-name`})]}),d(`div`,{className:`pb-1.5`,children:d(pl,{label:l(`system.notificationTimelapseEditor.enabled`,`Enabled`),checked:m.enabled,onChange:e=>S({enabled:e}),testId:`timelapse-enabled`})})]})}),d(Q,{title:l(`system.notificationTimelapseEditor.cameras`,`Cameras`),children:d(ul,{cameras:t,value:m.deviceIds,fleet:n,onChange:e=>S({deviceIds:e}),hint:l(`system.notificationTimelapseEditor.eachCameraRendersAndDelivers`,`Each camera renders and delivers its own video. Recording must be ON for a camera — a timelapse is cut from recorded footage, and the hub refuses a rule for a camera that does not record.`)})})]}),d(K,{value:`window`,className:`space-y-3`,children:d(Q,{title:l(`system.notificationTimelapseEditor.when`,`When`),children:i(`div`,{children:[d(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.weeklyWindows`,`Weekly windows`)}),d(Jt,{value:m.schedule,onChange:e=>S({schedule:e})}),d(`p`,{className:sl,children:l(`system.notificationTimelapseEditor.theVideoCoversExactlyOne`,`The video covers exactly one window and is delivered when it CLOSES. A window that crosses midnight (21:00 → 07:00) is the ordinary case for a night timelapse.`)})]})})}),d(K,{value:`sampling`,className:`space-y-3`,children:i(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:[i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(fl,{label:l(`system.notificationTimelapseEditor.baseCadenceSeconds`,`Base cadence (seconds)`),value:m.cadenceSec,min:2,max:xd,onChange:e=>S({cadenceSec:e??0}),hint:l(`system.notificationTimelapseEditor.oneFrameEveryNSeconds`,`One frame every N seconds across the quiet parts of the window.`),testId:`timelapse-cadence`}),d(fl,{label:l(`system.notificationTimelapseEditor.outputFrameRateFps`,`Output frame rate (fps)`),value:m.framerate,min:1,max:60,onChange:e=>S({framerate:e??0}),hint:l(`system.notificationTimelapseEditor.howFastTheAssembledVideo`,`How fast the assembled video plays.`),testId:`timelapse-framerate`})]}),i(`div`,{children:[d(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.denseCadenceNearTheDetections`,`Dense cadence, near the detections`)}),i(`div`,{className:`flex items-center gap-2`,children:[d(V,{value:m.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:l(`system.notificationTimelapseEditor.automaticS`,`Automatic ({{seconds}}s)`,{seconds:A.seconds})},{value:`explicit`,label:l(`system.notificationTimelapseEditor.setItMyself`,`Set it myself`)}],onChange:e=>S({denseCadenceSec:e.target.value===`auto`?void 0:Kd(m).seconds}),"data-testid":`timelapse-dense-mode`}),m.denseCadenceSec!==void 0&&d(W,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(m.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&S({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),i(`p`,{className:sl,"data-testid":`timelapse-dense-hint`,children:[l(`system.notificationTimelapseEditor.denseHint`,{seconds:A.seconds,fps:m.framerate,passage:Xd,onScreen:j.toFixed(2)}),` `,A.derived?l(`system.notificationTimelapseEditor.denseDerived`):l(`system.notificationTimelapseEditor.denseFixed`,{seconds:Kd({...m,denseCadenceSec:void 0}).seconds})]})]}),d(fl,{label:l(`system.notificationTimelapseEditor.minimumSecondsOfVideoPer`,`Minimum seconds of video per detection (optional)`),value:m.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>S({minDwellSec:e}),hint:l(`system.notificationTimelapseEditor.stateTheStayAndLet`,`State the stay and let the renderer solve for the cadence. It only ever samples DENSER, down to the recording's own frame interval — a passage too short to reach it is rendered with every frame that exists and no more.`),testId:`timelapse-min-dwell`})]})}),d(K,{value:`delivery`,className:`space-y-3`,children:i(Q,{title:l(`system.notificationTimelapseEditor.theNotification`,`The notification`),children:[d(dl,{targets:a,value:m.targetIds,onChange:e=>S({targetIds:e})}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.preview`,`Preview`)}),d(V,{value:m.previewMode,options:Td.map(e=>({value:e,label:Ed[e]})),onChange:e=>{let t=Zd(e.target.value);t!==void 0&&S({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),d(fl,{label:l(`system.notificationTimelapseEditor.priority`,`Priority`),value:m.priority,min:1,max:5,onChange:e=>S({priority:e??3}),testId:`timelapse-priority`})]}),i(`div`,{children:[d(Eo,{label:l(`system.notificationTimelapseEditor.captionOnThePreviewFrame`,`Caption on the preview frame`),value:m.previewTextSet?m.previewText:``,placeholder:l(`system.notificationTimelapseEditor.shippedDefault`,`{{DEFAULT_TIMELAPSE_PREVIEW_TEXT}} (shipped default)`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:le}),onChange:e=>S({previewText:e,previewTextSet:!0}),vars:w,testId:`timelapse-preview-text`}),i(`p`,{className:sl,children:[m.previewTextSet&&m.previewText.length===0?l(`system.notificationTimelapseEditor.emptyAndSetThePreview`,`Empty and set: the preview frame carries NO caption.`):l(`system.notificationTimelapseEditor.leaveUntouchedForTheShipped`,`Leave untouched for the shipped caption ({{DEFAULT_TIMELAPSE_PREVIEW_TEXT}}).`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:le}),m.previewTextSet&&i(o,{children:[` `,d(`button`,{type:`button`,className:`underline`,onClick:()=>S({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:l(`system.notificationTimelapseEditor.backToTheShippedCaption`,`Back to the shipped caption`)})]})]})]}),d(ml,{title:m.templateTitle,body:m.templateBody,onTitleChange:e=>S({templateTitle:e}),onBodyChange:e=>S({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(Sr,{i18nKey:`system.notificationTimelapseEditor.detectionSummaryNote`,values:{token:`{{detectionSummary}}`},components:{code:d(`code`,{})}})})]})})]})]}),i(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[d(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:l(`common.cancel`,`Cancel`)}),i(U,{size:`sm`,type:`button`,disabled:D.isPending,onClick:()=>{y(!0),!(!Hd(m)||D.isPending)&&D.mutate()},children:[D.isPending&&d(T,{className:`h-3.5 w-3.5 animate-spin`}),e===null?l(`system.notificationTimelapseEditor.create`,`Create`):l(`common.save`,`Save`)]})]})]})})}function $d({children:e,className:t}){return d(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function ef(){return d(`div`,{className:`flex items-center justify-center py-16`,children:d(T,{className:`h-6 w-6 animate-spin text-primary`})})}function tf({children:e,testId:t}){return d(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function nf({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:i}){return d(pt,{children:d(ct,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,maxBodyHeight:Ze,...i===void 0?{}:{onRowClick:i}})})}function rf({name:e,enabled:t,onOpen:n,badges:r,openTestId:a}){let{t:o}=J();return i(`span`,{className:`flex flex-wrap items-center gap-2`,children:[n===void 0?d(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e}):d($d,{children:d(`button`,{type:`button`,onClick:n,className:`truncate rounded text-left text-sm font-medium text-foreground hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,...a===void 0?{}:{"data-testid":a},children:e})}),!t&&d(G,{variant:`warning`,children:o(`common.disabled`)}),r]})}function af({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:i=`Delete`,cancelLabel:a=`Cancel`,ariaLabel:o,testId:s,onConfirm:c}){let l=tt(),u=async()=>{await l({title:n,message:r,confirmLabel:i,cancelLabel:a,variant:`danger`})&&c()};return d(`button`,{type:`button`,title:i,"aria-label":o,disabled:e||t,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void u(),...s===void 0?{}:{"data-testid":s},children:d(p,{className:`h-3.5 w-3.5 text-danger`})})}e();var of=[`notificationSummaries`,`listSummaryRules`];function sf(e){return[{key:`name`,header:q.t(`system.notificationSummaries.digest`,`Digest`),render:t=>d(rf,{name:t.name,enabled:t.enabled,...Eu(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`summary-edit-${t.id}`,badges:i(o,{children:[!Eu(t)&&d(G,{variant:`warning`,children:`read-only`}),t.ai?.enabled===!0&&d(G,{variant:`info`,children:`AI`}),t.ai!==void 0&&!t.ai.enabled&&d(G,{variant:`default`,children:q.t(`system.notificationSummaries.aiOff`,`AI off`)})]})})},{key:`cameras`,header:q.t(`system.notificationSummaries.cameras`,`Cameras`),align:`center`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:q.t(`system.notificationSummaries.window`,`Window`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:od(e.window)})},{key:`filters`,header:q.t(`system.notificationSummaries.keeps`,`Keeps`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:cd(e.filters)})},{key:`mosaic`,header:q.t(`system.notificationSummaries.mosaic`,`Mosaic`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:q.t(`system.notificationSummaries.tilesRank`,{count:e.maxTiles,rank:e.rank})})},{key:`targets`,header:q.t(`system.notificationSummaries.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:q.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:q.t(`system.notificationSummaries.lastRun`,`Last run`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:sd(t.generatedAt,e.nowMs)})},{key:`enabled`,header:q.t(`system.notificationSummaries.on`,`On`),align:`center`,nowrap:!0,render:t=>d($d,{children:d(et,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":q.t(`system.notificationSummaries.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>i($d,{className:`flex items-center justify-end gap-1`,children:[d(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onTest(t),title:q.t(`system.notificationSummaries.produceThisDigestNowAnd`,`Produce this digest now and DELIVER it`),"aria-label":q.t(`system.notificationSummaries.test`,`test {{name}}`,{name:t.name}),"data-testid":`summary-test-${t.id}`,children:d(We,{className:`h-3.5 w-3.5`})}),d(af,{disabled:t.readOnly,pending:e.deletePending,title:q.t(`system.notificationSummaries.deleteThisSummary`,`Delete this summary?`),message:q.t(`system.notificationSummaries.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:q.t(`system.notificationSummaries.delete`,`delete {{name}}`,{name:t.name}),testId:`summary-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}e();var cf=[`notificationTimelapses`,`listTimelapseRules`];function lf(e){return[{key:`name`,header:q.t(`system.notificationTimelapses.timelapse`,`Timelapse`),render:t=>d(rf,{name:t.name,enabled:t.enabled,...kd(t)?{onOpen:()=>e.onOpen(t),openTestId:`timelapse-edit-${t.id}`}:{},badges:kd(t)?null:d(G,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:q.t(`system.notificationTimelapses.cameras`,`Cameras`),render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.deviceIds.length===1?e.cameraNameById.get(t.deviceIds[0]??-1)??`#${t.deviceIds[0]}`:q.t(`system.notificationTimelapses.cameras2`,`{{length}} cameras`,{length:t.deviceIds.length})})},{key:`schedule`,header:q.t(`system.notificationTimelapses.window`,`Window`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Wd(e.schedule)})},{key:`sampling`,header:q.t(`system.notificationTimelapses.sampling`,`Sampling`),nowrap:!0,render:e=>{let t=Kd(Nd(e));return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:[q.t(t.derived?`system.notificationTimelapses.ruleSummaryAuto`:`system.notificationTimelapses.ruleSummary`,{cadence:e.cadenceSec,fps:e.framerate,dense:t.seconds}),e.minDwellSec===void 0?``:` · ${q.t(`system.notificationTimelapses.ruleDwell`,{sec:e.minDwellSec})}`]})}},{key:`targets`,header:q.t(`system.notificationTimelapses.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:q.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:q.t(`system.notificationTimelapses.lastRun`,`Last run`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:Gd(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:q.t(`system.notificationTimelapses.on`,`On`),align:`center`,nowrap:!0,render:t=>d($d,{children:d(et,{checked:t.enabled,disabled:!kd(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":q.t(`system.notificationTimelapses.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>i($d,{className:`flex items-center justify-end gap-1`,children:[d(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:!kd(t),onClick:()=>e.onTest(t),title:q.t(`system.notificationTimelapses.renderThisRuleSLast`,`Render this rule's last closed window now and DELIVER it`),"aria-label":q.t(`system.notificationTimelapses.test`,`test {{name}}`,{name:t.name}),"data-testid":`timelapse-test-${t.id}`,children:d(We,{className:`h-3.5 w-3.5`})}),d(af,{disabled:!kd(t),pending:e.deletePending,title:q.t(`system.notificationTimelapses.deleteThisTimelapse`,`Delete this timelapse?`),message:q.t(`system.notificationTimelapses.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:q.t(`system.notificationTimelapses.delete`,`delete {{name}}`,{name:t.name}),testId:`timelapse-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}e();var uf={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`}},df=`system.notificationProducerRules.unreadableMessage`;function ff(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function pf({cameras:e,fleet:t,targets:n,taxonomy:s}){let{t:c}=J(),l=E(),[f,p]=r({mode:`closed`}),[m,h]=r(null),[g,_]=r(null),[v,y]=r(null),[b,x]=r(null),S=a({queryKey:of,queryFn:async()=>Uu(await l.trpcClient.addons.custom.mutate({addonId:$,action:cu,input:{}}))}),C=a({queryKey:cf,queryFn:async()=>Od(await l.trpcClient.addons.custom.mutate({addonId:$,action:_d,input:{}}))}),w=a({queryKey:Vl,queryFn:async()=>Jl(await l.trpcClient.addons.custom.mutate({addonId:$,action:Hl,input:{}}))}),T=S.data??[],D=C.data??[],O=w.data??[],k=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:lu,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),A=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:uu,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),j=u({mutationFn:async e=>Wu(await l.trpcClient.addons.custom.mutate({addonId:$,action:du,input:{ruleId:e,...ld(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),M=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:vd,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),N=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:yd,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),P=u({mutationFn:async e=>jd(await l.trpcClient.addons.custom.mutate({addonId:$,action:bd,input:e})),onSuccess:e=>{y(null),x(e)}}),F=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Ul,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void w.refetch()}),I=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Wl,input:{ruleId:e}}),onSuccess:()=>void w.refetch()}),ee=e.toSorted((e,t)=>e.name.localeCompare(t.name)),te=n.map(e=>({id:e.id,name:e.name,enabled:e.enabled})),L=new Map(te.map(e=>[e.id,e.name])),ne=new Map(ee.map(e=>[e.id,e.name])),R=Date.now(),re={summary:{nowMs:R,targetNameById:L,deletePending:A.isPending,onToggle:(e,t)=>k.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Eu(e)&&p({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>A.mutate(e.id)},timelapse:{nowMs:R,cameraNameById:ne,targetNameById:L,deletePending:N.isPending,onToggle:(e,t)=>M.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{kd(e)&&p({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>N.mutate(e.id)},calendar:{nowMs:R,targetNameById:L,deletePending:I.isPending,onToggle:(e,t)=>F.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Yl(e)&&p({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>I.mutate(e.id)}},ie=e=>{switch(e.family){case`summary`:re.summary.onOpen(e.rule);return;case`timelapse`:re.timelapse.onOpen(e.rule);return;case`calendar-events`:re.calendar.onOpen(e.rule);return}},z=e=>{p(e===`summary`?{mode:`summary`,rule:null}:e===`timelapse`?{mode:`timelapse`,rule:null}:{mode:`calendar-events`,rule:null})},ae=e=>{let t=e===`summary`?S:e===`timelapse`?C:w;return t.isLoading?null:t.isError?{unreadable:!1}:t.data===null?{unreadable:!0}:null},oe=e=>{e===`summary`?S.refetch():e===`timelapse`?C.refetch():w.refetch()},se=e=>{let t=ff(e);return t!==null&&ae(t)!==null},ce=e=>{let t=ff(e),n=t===null?null:ae(t);return i(o,{children:[t!==null&&n!==null&&d(H,{title:c(uf[t].titleKey),message:c(n.unreadable?df:uf[t].messageKey),onRetry:()=>oe(t)}),A.isError&&d(H,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(A.error)}),N.isError&&d(H,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(N.error)}),I.isError&&d(H,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(I.error)}),j.isError&&d(H,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(j.error)}),P.isError&&d(H,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(P.error)}),g!==null&&d(mf,{outcome:g,onDismiss:()=>_(null)}),b!==null&&d(hf,{outcome:b,onDismiss:()=>x(null)})]})},le=()=>p({mode:`closed`}),ue=i(o,{children:[f.mode===`summary`&&d(gd,{rule:f.rule,cameras:ee,fleet:t,targets:te,taxonomy:s,onCancel:le,onSaved:()=>{le(),S.refetch()}}),f.mode===`timelapse`&&d(Qd,{rule:f.rule,cameras:ee,fleet:t,targets:te,onCancel:le,onSaved:()=>{le(),C.refetch()}}),f.mode===`calendar-events`&&d(su,{rule:f.rule,targets:te,onCancel:le,onSaved:()=>{le(),w.refetch()}}),d(hl,{open:m!==null,ruleName:m?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${m?.targets.length??0} target${(m?.targets.length??0)===1?``:`s`}`,pending:j.isPending,onCancel:()=>h(null),onConfirm:()=>{m!==null&&j.mutate(m.id)}}),d(hl,{open:v!==null,ruleName:v?.rule.name??``,windowDescription:`its last closed window`,targetDescription:`${v?.rule.targets.length??0} target${(v?.rule.targets.length??0)===1?``:`s`}`,pending:P.isPending,confirmDisabled:v?.deviceId===null,extra:v===null?null:i(`div`,{children:[d(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.notificationProducerRules.whichCamera`,`Which camera`)}),d(V,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:ne.get(e)??`#${e}`})),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&y({rule:v.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>y(null),onConfirm:()=>{v!==null&&v.deviceId!==null&&P.mutate({ruleId:v.rule.id,deviceId:v.deviceId})}})]});return{summaries:T,timelapses:D,calendarEvents:O,loading:S.isLoading||C.isLoading||w.isLoading,columnDeps:re,open:ie,create:z,notices:ce,listFailed:se,overlays:ue}}function mf({outcome:e,onDismiss:t}){let{t:n}=J();return i(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[e.error===void 0?i(`span`,{children:[n(`system.notificationProducerRules.summaryProduced`,{digests:n(`system.notificationProducerRules.digestCount`,{count:e.produced}),tiles:n(`system.notificationProducerRules.tileCount`,{count:e.tiles??0}),cameras:n(`system.notificationProducerRules.cameraCount`,{count:e.cameras??0}),matched:n(`system.notificationProducerRules.tracksMatched`,{count:e.matched??0}),sent:n(`system.notificationProducerRules.notificationsSent`,{count:e.enqueued??0})}),(e.droppedStationary??0)>0&&d(`span`,{"data-testid":`summary-test-dropped-stationary`,className:`ml-1`,children:n(`system.notificationProducerRules.droppedStationary`,{count:e.droppedStationary})})]}):i(`span`,{className:`text-warning`,children:[n(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,e.error]}),d(U,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:n(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}function hf({outcome:e,onDismiss:t}){let{t:n}=J();return i(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[e.error===void 0?d(`span`,{children:n(e.coveragePercent===void 0?`system.notificationProducerRules.timelapseProduced`:`system.notificationProducerRules.timelapseProducedCoverage`,{videos:n(`system.notificationProducerRules.videoCount`,{count:e.produced}),percent:Math.round(e.coveragePercent??0),sent:n(`system.notificationProducerRules.notificationsSent`,{count:e.enqueued??0})})}):i(`span`,{className:`text-warning`,children:[n(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,e.error]}),d(U,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:n(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}var gf=[{key:`summaries`,get label(){return q.t(`helpers.notificationRulesArea.sumLabel`)},get blurb(){return q.t(`helpers.notificationRulesArea.sumBlurb`)},get newLabel(){return q.t(`helpers.notificationRulesArea.sumNew`)},get emptyHint(){return q.t(`helpers.notificationRulesArea.sumEmpty`)}},{key:`timelapses`,get label(){return q.t(`helpers.notificationRulesArea.tlLabel`)},get blurb(){return q.t(`helpers.notificationRulesArea.tlBlurb`)},get newLabel(){return q.t(`helpers.notificationRulesArea.tlNew`)},get emptyHint(){return q.t(`helpers.notificationRulesArea.tlEmpty`)}},{key:`calendar-events`,get label(){return q.t(`helpers.notificationRulesArea.calLabel`)},get blurb(){return q.t(`helpers.notificationRulesArea.calBlurb`)},get newLabel(){return q.t(`helpers.notificationRulesArea.calNew`)},get emptyHint(){return q.t(`helpers.notificationRulesArea.calEmpty`)}}],_f=[{type:`detection`,get label(){return q.t(`helpers.notificationRulesArea.opt_detection_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_detection_hint`)}},{type:`sensor`,get label(){return q.t(`helpers.notificationRulesArea.opt_sensor_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_sensor_hint`)}},{type:`audio`,get label(){return q.t(`helpers.notificationRulesArea.opt_audio_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_audio_hint`)}},{type:`occupancy`,get label(){return q.t(`helpers.notificationRulesArea.opt_occupancy_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_occupancy_hint`)}},{type:`device-events`,get label(){return q.t(`helpers.notificationRulesArea.opt_deviceEvents_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_deviceEvents_hint`)}},{type:`system`,get label(){return q.t(`helpers.notificationRulesArea.opt_system_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_system_hint`)}},{type:`alarm`,get label(){return q.t(`helpers.notificationRulesArea.opt_alarm_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_alarm_hint`)}},{type:`summary`,get label(){return q.t(`helpers.notificationRulesArea.opt_summary_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_summary_hint`)}},{type:`timelapse`,get label(){return q.t(`helpers.notificationRulesArea.opt_timelapse_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_timelapse_hint`)}},{type:`calendar-events`,get label(){return q.t(`helpers.notificationRulesArea.opt_calendarEvents_label`)},get hint(){return q.t(`helpers.notificationRulesArea.opt_calendarEvents_hint`)}}];function vf(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function yf(e){if(!(e==null||e.length===0))return vf(e)?e:B(e)}function bf(e){let t=gf.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function xf(e){return[...ar.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...gf]}function Sf(e){return!vf(e)}function Cf(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}e();function wf(e){return[{key:`name`,header:q.t(`system.notificationCalendarEventsPage.rule`,`Rule`),render:t=>d(rf,{name:t.name,enabled:t.enabled,...Yl(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:Yl(t)?null:d(G,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:q.t(`system.notificationCalendarEventsPage.when`,`When`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:$l(e.schedule)})},{key:`horizon`,header:q.t(`system.notificationCalendarEventsPage.horizon`,`Horizon`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:au(e.horizonDays)})},{key:`calendars`,header:q.t(`system.notificationCalendarEventsPage.calendars`,`Calendars`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:ou(e)})},{key:`targets`,header:q.t(`system.notificationCalendarEventsPage.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:q.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:q.t(`system.notificationCalendarEventsPage.lastRun`,`Last run`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:sd(t.generatedAt,e.nowMs)})},{key:`enabled`,header:q.t(`system.notificationCalendarEventsPage.on`,`On`),align:`center`,nowrap:!0,render:t=>d($d,{children:d(et,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":q.t(`system.notificationCalendarEventsPage.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>d($d,{className:`flex items-center justify-end gap-1`,children:d(af,{disabled:t.readOnly,pending:e.deletePending,title:q.t(`system.notificationCalendarEventsPage.deleteThisCalendarEventsRule`,`Delete this calendar-events rule?`),message:q.t(`system.notificationCalendarEventsPage.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:q.t(`system.notificationCalendarEventsPage.delete`,`delete {{name}}`,{name:t.name}),testId:`calendar-events-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})})}]}function Tf(e,t){return e.replaceAll(`{{name}}`,t)}function Ef(e){return[{key:`name`,header:q.t(`system.notificationRuleColumns.rule`,`Rule`),render:t=>d(rf,{name:t.name,enabled:t.enabled,...tr(t)?{onOpen:()=>e.onOpen(t)}:{}})},{key:`trigger`,header:q.t(`system.notificationRuleColumns.trigger`,`Trigger`),nowrap:!0,render:t=>i(`span`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`text-[11px] text-foreground-subtle`,children:hn(t,e.t(`notificationRules.grouping.choice`,kr))}),!Qr(t.delivery)&&d(G,{variant:`warning`,children:q.t(`common.readOnly`)})]})},{key:`targets`,header:q.t(`system.notificationRuleColumns.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:q.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:q.t(`system.notificationRuleColumns.lastRun`,`Last run`),nowrap:!0,render:t=>d(ac,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:q.t(`system.notificationRuleColumns.priority`,`Priority`),align:`center`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:e.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:t=>d($d,{children:d(mc,{rule:t,snoozes:e.snoozes,exempt:Qn(t.conditions,mr({onActivation:t.actions?.onActivation??[],onDeactivation:t.actions?.onDeactivation??[],onTrigger:t.actions?.onTrigger??[],onTriggerOff:t.actions?.onTriggerOff??[],buttons:t.actions?.buttons??[]},e.sequences))})})},{key:`enabled`,header:q.t(`system.notificationRuleColumns.on`,`On`),align:`center`,nowrap:!0,render:t=>d($d,{children:d(et,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":q.t(`system.notificationRuleColumns.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>tr(t)?i($d,{className:`flex items-center justify-end gap-1`,children:[d(tl,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&d(oc,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:q.t(`system.notificationRuleColumns.openInTheSimulatorDescribe`,`Open in the simulator — describe an event and tune it before injecting`),"aria-label":q.t(`system.notificationRuleColumns.simulate`,`simulate {{name}}`,{name:t.name}),children:d(We,{className:`h-3.5 w-3.5`})}),d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:q.t(`system.notificationRuleColumns.duplicate`,`Duplicate`),children:d(v,{className:`h-3.5 w-3.5`})}),d(Of,{rule:t,deps:e})]}):d(Df,{rule:t,deps:e})}]}function Df({rule:e,deps:t}){let{t:n}=J();return i($d,{className:`flex items-center justify-end gap-1`,children:[d(`span`,{title:ve(Ne(e)).blurb,children:d(G,{variant:`warning`,children:n(`system.notificationRuleColumns.recreateAsOneRulePer`,`Recreate as one rule per family`)})}),t.onOpenHistory&&d(oc,{rule:e,onOpenHistory:t.onOpenHistory}),d(Of,{rule:e,deps:t})]})}function Of({rule:e,deps:t}){let{t:n}=J();return d(af,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:Tf(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:Tf(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function kf(e){let t=Ef(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:q.t(`system.notificationRuleColumns.events`,`Events`),render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Fr(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:q.t(`system.notificationRuleColumns.scope`,`Scope`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:ln(e.conditions.systemEvent)})},{key:`targets`,header:q.t(`system.notificationRuleColumns.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:q.t(`common.targetCount`,{count:t.targets.length})})}},{key:`cooldown`,header:q.t(`system.notificationRuleColumns.cooldown`,`Cooldown`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:pr(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function Af(e){switch(e){case`detection`:return q.t(`helpers.unifiedRulesModel.kind_detection`);case`sensor`:return q.t(`helpers.unifiedRulesModel.kind_sensor`);case`sound`:return q.t(`helpers.unifiedRulesModel.kind_sound`);case`occupancy`:return q.t(`helpers.unifiedRulesModel.kind_occupancy`);case`device-events`:return q.t(`helpers.unifiedRulesModel.kind_device_events`);case`system`:return q.t(`helpers.unifiedRulesModel.kind_system`);case`alarm`:return q.t(`helpers.unifiedRulesModel.kind_alarm`);case`mixed`:return q.t(`helpers.unifiedRulesModel.kind_mixed`);case`summary`:return q.t(`helpers.unifiedRulesModel.kind_summary`);case`timelapse`:return q.t(`helpers.unifiedRulesModel.kind_timelapse`);case`calendar-events`:return q.t(`helpers.unifiedRulesModel.kind_calendar_events`)}}function jf(e){return{family:`event`,kind:Ne(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Mf(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Nf(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Pf(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Ff(e){return[...e.events.map(jf),...e.summaries.map(Mf),...e.timelapses.map(Nf),...e.calendarEvents.map(Pf)]}function If(e,t){return t===`all`?!0:vf(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:Sf(t)&&e.family===`event`?je(e.rule,t):!1}function Lf(e,t){return Ff(t).filter(t=>If(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function Rf(e,t){return Lf(e,t).length}function zf(e){return e===`all`?900:860}function Bf(e){return e.family===`event`?e.rule:null}function Vf(e){return e.family===`summary`?e.rule:null}function Hf(e){return e.family===`timelapse`?e.rule:null}function Uf(e){return e.family===`calendar-events`?e.rule:null}function Wf(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 Gf(e,t){return e.map(e=>Wf(e,t))}function Kf(e,t){return e.find(e=>e.key===t)}function qf(e,t,n){let r=Kf(Ef(n.event),e),i=Kf(sf(n.summary),e),a=Kf(lf(n.timelapse),e),o=Kf(wf(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 Jf(e){switch(e.family){case`event`:return null;case`summary`:return od(e.rule.window);case`timelapse`:return Wd(e.rule.schedule);case`calendar-events`:return $l(e.rule.schedule)}}function Yf(e){let t=Kf(Ef(e.event),`trigger`);return{key:`when`,header:q.t(`system.unifiedRulesColumns.when`,`When`),render:(e,n)=>{let r=Jf(e);return r===null?e.family===`event`?t?.render(e.rule,n)??null:null:d(`span`,{className:`text-[11px] text-foreground-subtle`,children:r})}}}function Xf(e){return[qf(`name`,`Name`,e),{key:`type`,header:q.t(`system.unifiedRulesColumns.type`,`Type`),nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:Af(e.kind)})},Yf(e),qf(`targets`,`Targets`,e),qf(`lastRun`,`Last run`,e),qf(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),qf(`enabled`,`On`,e),qf(`actions`,``,e)]}function Zf(e,t){return e===`all`?Xf(t):e===`summaries`?Gf(sf(t.summary),Vf):e===`timelapses`?Gf(lf(t.timelapse),Hf):e===`calendar-events`?Gf(wf(t.calendar),Uf):Sf(e)&&Xr(e)?Gf(kf(t.event),Bf):Gf(Ef(t.event),Bf)}function Qf({value:e,family:t,onChange:n,draft:r}){let{t:a}=J();if(t===void 0||!z.includes(t))return null;let o=e?.mode===`summary`?e:null;return i(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:a(`system.notificationSystemEventDelivery.delivery`,`Delivery`)}),i(`div`,{className:`flex flex-wrap gap-3 text-xs`,children:[i(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-delivery`,checked:o===null,onChange:()=>n({mode:`instant`}),"data-testid":`rule-delivery-instant`}),a(`system.notificationSystemEventDelivery.instantANotificationPerEvent`,`Instant — a notification per event`)]}),i(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-delivery`,checked:o!==null,onChange:()=>n({mode:`summary`,schedule:N([rn])}),"data-testid":`rule-delivery-summary`}),a(`system.notificationSystemEventDelivery.summaryOnScheduleTheCurrent`,`Summary on schedule — the current state, at set times`)]})]}),o!==null&&d($f,{value:o,onChange:n,draft:r})]})}function $f({value:e,onChange:t,draft:n}){let{t:r}=J(),a=e.schedule.timezone,o=oe({systemEventDelivery:e});return i(`div`,{className:`mt-2 space-y-2`,children:[i(`p`,{className:Zt,children:[r(`system.notificationSystemEventDelivery.nothingIsSentPerEvent`,`Nothing is sent per event. At each time below, one notification lists what is still true for the kinds and filters of this rule — low batteries, consumables, devices or streams offline, updates available — or one notification per category, if you choose so below. Nothing to report sends nothing. Time zone:`),` `,a??r(`system.notificationSystemEventDelivery.theHubS`,`the hub’s`),`.`]}),d(Jt,{mode:`times`,value:e.schedule,onChange:n=>{n!==void 0&&t(Tn(e,n))}}),i(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[d(`legend`,{className:`sr-only`,children:r(`system.notificationSystemEventDelivery.howTheSummaryIsSent`,`How the summary is sent`)}),i(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-summary-split`,checked:o===`rule`,onChange:()=>t(ei(e,`rule`)),"data-testid":`rule-delivery-split-rule`}),r(`system.notificationSystemEventDelivery.oneMessageWithEveryCategory`,`One message with every category`)]}),i(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-summary-split`,checked:o===`section`,onChange:()=>t(ei(e,`section`)),"data-testid":`rule-delivery-split-section`}),r(`system.notificationSystemEventDelivery.oneNotificationPerCategoryBatteries`,`One notification per category (batteries, consumables, devices…)`)]})]}),d(ep,{draft:n,split:o})]})}function ep({draft:e,split:t}){let{t:n}=J(),r=E(),a=u({mutationFn:e=>r.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),o=fn(a.status,a.data,a.error,t);return i(`div`,{className:`space-y-1.5`,children:[d(U,{size:`sm`,variant:`secondary`,onClick:()=>a.mutate(e()),disabled:a.isPending,"data-testid":`rule-delivery-preview`,children:a.isPending?n(`system.notificationSystemEventDelivery.readingTheState`,`Reading the state…`):n(`system.notificationSystemEventDelivery.previewTheSummaryNow`,`Preview the summary now`)}),o!==null&&d(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:o.lines.map((e,t)=>d(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function tp(e,t){if(e.status===`error`)return{kind:`failed`,reason:e.error instanceof Error?e.error.message:q.t(`helpers.notificationRuleLastRun.unknownError`)};if(e.status!==`success`||e.data===void 0)return{kind:`pending`};let n=e.data.runs.find(e=>e.ruleId===t);return n===void 0?{kind:`absent`,phrase:ap(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var np=6e4,rp=60*np,ip=24*rp;function ap(e){return e===null?q.t(`helpers.notificationRuleLastRun.noDelivery`):e>=ip?q.t(`helpers.notificationRuleLastRun.notInDay`,{count:Math.floor(e/ip)}):e>=rp?q.t(`helpers.notificationRuleLastRun.notInHour`,{count:Math.floor(e/rp)}):e>=np?q.t(`helpers.notificationRuleLastRun.notInMinute`,{count:Math.floor(e/np)}):q.t(`helpers.notificationRuleLastRun.notInWindow`)}e();var op=[`notificationRules`,`listRules`],sp=[`notificationOutput`,`listTargets`,`forRules`],cp=[`notificationRules`,`getConditionCatalog`],lp=[`deviceManager`,`gateableDevices`],up=Me.options;function dp({onSimulateRule:e,onOpenHistory:o,createRequested:s=!1,onCreateConsumed:c,createTypeRequested:f=null,onCreateTypeConsumed:p,headerOwnsCreate:m=!1}={}){let h=E(),{t:g}=J(),{state:v,openEdit:y,close:b}=gt({editKey:`rule`}),[x,C]=Ot(`section`),[w,T]=Ot(`editTab`),[D,O]=r({mode:`closed`}),[k,A]=r(!1),j=yf(x)??`all`,M=e=>{C(e===`all`?null:e)},N=a({queryKey:op,queryFn:async()=>(await h.trpcClient.notificationRules.listRules.query({})).rules}),P=l(null);t(()=>{if(D.mode!==`closed`)return;if(v.mode!==`edit`){v.mode===`closed`&&(P.current=null);return}let e=v.id;if(e===`new`||P.current===e)return;let t=N.data?.find(t=>t.id===e);t===void 0||!tr(t)||(P.current=e,O({mode:`form`,rule:t}))},[D.mode,v,N.data]);let F=a({queryKey:sp,queryFn:()=>h.trpcClient.notificationOutput.listTargets.query({})}),I=a({queryKey:cp,queryFn:()=>h.trpcClient.notificationRules.getConditionCatalog.query({})}),ee=St({projection:`slim`}),te=rc(),L=n(()=>ee.data??[],[ee.data]),ne=nt(ee),R=n(()=>L.map(e=>e.id),[L]),re=a({queryKey:[...lp,R],enabled:R.length>0,queryFn:async()=>{let e=[];for(let t of L){let n=ue(await h.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),up);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),ie=n(()=>{let e=On(L);return L.filter(e=>ye(String(e.type))).map(t=>{let n=e.get(t.id);return{id:t.id,name:t.name,type:String(t.type),location:t.location??null,...n===void 0?{}:{parentName:n}}}).sort((e,t)=>e.name.localeCompare(t.name))},[L]),z=n(()=>L.filter(e=>e.type===Ce.Camera).map(e=>({id:e.id,name:e.name})),[L]),ae=si(n(()=>z.map(e=>e.id),[z])),oe=n(()=>{let e=new Map(z.map(e=>[e.id,e.name]));return ae.results.flatMap(t=>t.monitors.map(n=>({sceneId:n.id,deviceId:t.deviceId,cameraName:e.get(t.deviceId)??`#${String(t.deviceId)}`,label:n.label,verdict:n.verdict,latched:n.latched,emit:n.emit})))},[ae.results,z]),se=n(()=>{let e=new Map;for(let t of F.data??[])e.set(t.id,t.name);return e},[F.data]),ce=u({mutationFn:e=>h.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void N.refetch()}),le=u({mutationFn:e=>h.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void N.refetch()}),fe=pc(),pe=bt({}),me=pe.data?.sequences??[],he=At(),ge=N.data??[],_e=pf({cameras:z,fleet:ne,targets:F.data??[],taxonomy:I.data?.taxonomy}),ve={events:ge,summaries:_e.summaries,timelapses:_e.timelapses,calendarEvents:_e.calendarEvents},be=xf(new Map(ar.map(e=>[e.key,Rf(e.key,ve)]))),B=be.find(e=>e.key===j)??be[0]??ar[0],xe=vf(B.key)?bf(B.key):void 0;Sf(B.key)&&B.key;let Se=Lf(B.key,ve),we=()=>{v.mode===`edit`&&(P.current=v.id),O({mode:`closed`}),b(),T(null)},Te=e=>{if(!tr(e))return;let t=e.id.length>0?e.id:`new`;P.current=t,O({mode:`form`,rule:e}),y(t),T(null)},Ee=e=>{if(Cf(e)){P.current=`new`,O({mode:`form`,rule:null,seed:de(e)}),y(`new`),T(null);return}_e.create(e)};t(()=>{f!==null&&(Ee(f),p?.())},[f]),t(()=>{s&&(A(!0),c?.())},[s]);let De=e=>{if(e.family===`event`){Te(e.rule);return}_e.open(e)},Oe={targetNameById:se,snoozes:fe,sequences:me,deletePending:le.isPending,onToggle:(e,t)=>ce.mutate({ruleId:e.id,enabled:t}),onOpen:Te,t:g,onDuplicate:e=>Te({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>le.mutate(e.id),...e?{onTest:e}:{},lastRunOf:e=>tp(te,e),...o?{onOpenHistory:o}:{}},ke=Zf(B.key,{event:Oe,summary:_e.columnDeps.summary,timelapse:_e.columnDeps.timelapse,calendar:_e.columnDeps.calendar}),Ae=xe?.blurb??(`blurb`in B?B.blurb:``),je=xe===void 0?`creatable`in B?B.creatable:!1:!0,Me=m||!je?null:j===`all`?i(U,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:()=>A(!0),children:[d(S,{className:`h-3.5 w-3.5`}),g(`system.notificationRules.newRule`,`New rule`)]}):xe===void 0?i(U,{size:`sm`,type:`button`,onClick:()=>Ee(B.key),"data-testid":`rules-new-${B.key}`,children:[d(S,{className:`h-3.5 w-3.5`}),`newRuleLabel`in B?B.newRuleLabel:g(`system.notificationRules.newRule`,`New rule`)]}):i(U,{size:`sm`,type:`button`,onClick:()=>Ee(xe.key===`summaries`?`summary`:xe.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":xe.key===`summaries`?`summary-new`:xe.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[d(S,{className:`h-3.5 w-3.5`}),xe.newLabel]});return d(ai,{embedded:!0,icon:_,title:g(`system.notificationRules.rules`,`Rules`),subtitle:Ae,children:i(`div`,{className:`flex flex-col gap-3`,children:[Me===null?null:d(`div`,{className:`flex justify-end`,children:Me}),d(st,{appearance:`pills`,value:B.key,onValueChange:e=>M(yf(e)??j),children:d(Xe,{children:be.map(e=>i(ut,{value:e.key,children:[e.label,d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:Rf(e.key,ve)})]},e.key))})}),d(ol,{rules:ge}),_e.notices(B.key),(N.isLoading||_e.loading)&&d(ef,{}),N.isError&&!N.isLoading&&d(H,{title:g(`system.notificationRules.failedToLoadRules`,`Failed to load rules`),message:N.error instanceof Error?N.error.message:g(`system.notificationRules.unknownError`,`Unknown error`),onRetry:()=>void N.refetch()}),!N.isLoading&&!_e.loading&&!N.isError&&!_e.listFailed(B.key)&&Se.length===0&&d(tf,{children:xe?.emptyHint??(`emptyHint`in B?B.emptyHint:g(`system.notificationRules.noRulesYet`,`No rules yet.`))}),Se.length>0&&d(nf,{columns:ke,rows:Se,rowKey:e=>`${e.family}:${e.id}`,onRowClick:De,minWidthPx:zf(B.key)}),D.mode===`form`&&d(pp,{rule:D.rule,...D.seed?{seed:D.seed}:{},targets:F.data??[],actuatable:ie,fleet:ne,sequences:me,onCreateSequence:async e=>{let t=await he.mutateAsync({sequence:{name:e.name,...e.minDelaySec===void 0?{}:{minDelaySec:e.minDelaySec},actions:[...e.actions]}});return await pe.refetch(),t.sequence.id},catalog:ir(I.data?.catalog??[]),taxonomy:I.data?.taxonomy,cameras:z,gateable:re.data??[],gateableScenes:oe,initialEditTab:Lr(w??``)??`rule`,onEditTabChange:e=>T(e===`rule`?null:e),onCancel:we,onSaved:()=>{we(),N.refetch()}}),_e.overlays,k?d(fp,{onCancel:()=>A(!1),onPick:e=>{A(!1),Ee(e)}}):null]})})}function fp({onPick:e,onCancel:t}){let{t:n}=J();return d(Ct,{open:!0,onClose:t,title:n(`system.notificationRules.chooseARuleType`,`Choose a rule type`),width:`lg`,children:d(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:_f.map(t=>i(`button`,{type:`button`,"data-testid":`rules-new-${t.type}`,title:t.hint,onClick:()=>e(t.type),className:`flex flex-col items-start gap-1 rounded-lg border border-border bg-surface px-3 py-3 text-left text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[d(`span`,{className:`font-medium text-foreground`,children:t.label}),d(`span`,{className:`text-[10px] font-normal text-foreground-subtle`,children:t.hint})]},t.type))})})}function pp({rule:e,seed:t,targets:s,catalog:c,taxonomy:l,cameras:f,gateable:p,gateableScenes:m,actuatable:h,fleet:g,sequences:v,onCreateSequence:y,initialEditTab:b=cr,onEditTabChange:x,onSaved:S,onCancel:C}){let w=E(),{t:D}=J(),O=e!=null&&e.id.length>0,[k]=r(()=>e?Zr(e):Mr(t?.delivery,t?.conditions)),[A,j]=r(k),[M,N]=r(null),[P,F]=r(O),[ee,te]=r(null),[L,ne]=r(b),R=e=>j(t=>({...t,...e})),re=e?zr(e):void 0,ie=u({mutationFn:async()=>{let t=Ar(A,re,c);if(O&&e){let n=er(A,c);await w.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await w.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:S,onError:e=>N(e instanceof Error?e.message:`Save failed`)}),z=u({mutationFn:async()=>{let e=Ar(A,re,c);return(await w.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>te(null),onSuccess:e=>te(e),onError:e=>N(e instanceof Error?e.message:`Test failed`)}),ae=A.targetIds.map(e=>s.find(t=>t.id===e)?.name??e),oe=a({queryKey:[`userManagement`,`listUsers`],queryFn:()=>w.trpcClient.userManagement.listUsers.query()}).data,se=n(()=>(oe??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[oe]),ce=dr(A),le=ce===`immediate-grouped`,ue=String(A.groupingSec??20),de=Zn(A).map(e=>({...e,label:e.value===`immediate-grouped`?D(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?D(`notificationRules.grouping.hint`,{n:ue,defaultValue:`Immediate, grouped — waits up to {{n}} s for subjects to be recognised, then sends one message with a mosaic, one picture per subject. Closes earlier when every subject is final.`}).replaceAll(`{{n}}`,ue):e.hint})),fe=de.find(e=>e.value===ce)?.hint,pe=$r(A,re),me=Te(A.delivery),he=Ne(A),ge=ve(he),ye=De(he),be=Rr.filter(e=>ye.includes(e.value)),B=we(A.conditions).length>0,xe=I(he),Se=_e(he),Ce=a({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,Se??[]],enabled:Se!==null,queryFn:async()=>{let e=await Promise.all((Se??[]).map(e=>w.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),Ee=n(()=>{if(Se===null||Ce.data===void 0)return h;let e=Ce.data,t=new Set(ni(A.deviceScope));return h.filter(n=>e.has(n.id)||t.has(n.id))},[h,Se,Ce.data,A.deviceScope]),ke=Se!==null&&Ce.isLoading,Ae=Se!==null&&Ce.isError,je=xo(),Me=e=>({family:`rule`,field:e,kind:he,delivery:A.delivery,...Kr(A)?{systemEventDelivery:`summary`}:{},...A.conditions.systemEvent?{systemEventKinds:[...A.conditions.systemEvent.kinds]}:{}}),Pe=e=>je.data?_o(je.data,Me(e)):void 0,Fe=Or(A),Ie=Qn(A.conditions,mr(A.actions,v)),Le=A.conditions.identities!==void 0||A.conditions.plates!==void 0,Re=gr(A.delivery,A.conditions),ze=Re.some(e=>e.key===L)?L:cr;return Qr(A.delivery)?d(st,{value:ze,onValueChange:e=>{let t=Lr(e);t!==void 0&&(ne(t),x?.(t))},children:i(Ct,{open:!0,onClose:C,title:O?D(`system.notificationRules.edit`,`Edit {{name}}`,{name:e?.name}):D(`system.notificationRules.newNotificationRule`,`New notification rule`),icon:_,error:M,width:`lg`,testId:`rule-form-dialog`,beforeBody:i(o,{children:[O&&e&&i(`div`,{className:`mb-3 space-y-2`,children:[d(Hc,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),d(Gc,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??D(`system.notificationRuleStatus.cameraFallback`,{deviceId:e})})]}),d(Xe,{className:`mb-3`,children:Re.map(e=>d(ut,{value:e.key,children:e.label},e.key))})]}),footer:i(`div`,{className:`flex w-full flex-col gap-3`,children:[Fe.length>0&&i(`div`,{"data-testid":`rule-form-dropped`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1 text-left`,children:[d(`p`,{className:`text-foreground`,children:D(`system.notificationRules.savingDrops`,{count:Fe.length})}),Fe.map(e=>i(`p`,{children:[d(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),P&&pe.length>0?d(`div`,{"data-testid":`rule-form-problems`,className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1 text-left`,children:pe.map(e=>d(`p`,{children:e},e))}):null,d(`div`,{className:`flex justify-end gap-2`,children:i(U,{size:`sm`,type:`button`,disabled:ie.isPending,onClick:()=>{F(!0),N(null),!(!fr(A,re,new Set(v.map(e=>e.id)))||ie.isPending)&&ie.mutate()},children:[ie.isPending&&d(T,{className:`h-3.5 w-3.5 animate-spin`}),O?D(`system.notificationRules.saveChanges`,`Save changes`):D(`system.notificationRules.createRule`,`Create rule`)]})})]}),children:[i(K,{value:`rule`,className:`space-y-4`,children:[i(`div`,{className:`flex items-end gap-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.name`,`Name`)}),d(W,{value:A.name,onChange:e=>R({name:e.target.value}),placeholder:D(`system.notificationRules.eGFrontDoorPackage`,`e.g. Front door package`)})]}),i(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[d(et,{checked:A.enabled,onCheckedChange:e=>R({enabled:e}),"aria-label":D(`system.notificationRules.enabled`,`Enabled`)}),D(`system.notificationRules.enabled`,`Enabled`)]})]}),i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.trigger`,`Trigger`)}),d(V,{value:ce,onChange:e=>{let t=Wt(e.target.value);t&&j(e=>or(e,t))},options:de.map(e=>({value:e.value,label:e.label}))}),fe&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:fe}),le&&i(`div`,{className:`mt-2`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),d(W,{type:`number`,min:5,max:60,step:1,value:ue,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=yn(e.target.value);t!==void 0&&R({groupingSec:t})}}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),Le&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`notificationRules.grouping.scopedHint`,{n:ue,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,ue)})]}),ce===`immediate`&&Le&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!O&&xe!==void 0&&d(zs,{family:xe,onChange:e=>j(t=>ur(t,e))}),d(it,{label:D(`system.notificationRules.deliveryTargets`,`Delivery targets`),targets:s,value:A.targetIds,onChange:e=>j(t=>({...t,targetIds:e})),emptyMessage:D(`system.notificationRules.noDeliveryTargetsConfiguredAdd`,`No delivery targets configured. Add one under the Targets tab first.`),testIdPrefix:`rule-target`}),d(kt,{mode:`multi`,options:se,value:A.targetUsers,onChange:e=>R({targetUsers:e}),searchable:!0,creatable:!1,label:D(`system.notificationRules.notifyUsers`,`Notify users`),description:D(`system.notificationRules.deliversToTheTargetsEach`,`Delivers to the targets each user owns, only for cameras that user can access.`),emptyMessage:D(`system.notificationRules.noUsersToNotify`,`No users to notify.`),placeholder:D(`system.notificationRules.searchUsers`,`Search users…`),testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),i(K,{value:`devices`,className:`space-y-4`,children:[ke&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:D(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Ae&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:D(`notificationRules.devices.compatFailed`,`Couldn't check which devices this rule's kind can use — every device is listed. The hub still refuses an incompatible one on save.`)}),d(hs,{devices:Ee,scope:A.deviceScope,onChange:e=>R({deviceScope:e}),listState:g.state,savedScope:k.deviceScope,exceptOffered:nr(c,`devicesExclude`,A)})]}),d(K,{value:`actions`,className:`space-y-4`,children:d(Lo,{value:A.actions,onChange:e=>R({actions:e}),devices:h,devicesState:g.state,sequences:v,onCreateSequence:y,showProblems:P})}),i(K,{value:`advanced`,className:`space-y-4`,children:[d(ec,{catalog:c,delivery:A.delivery,conditions:A.conditions,onConditionsChange:e=>R({conditions:e})}),i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.cooldownSeconds`,`Cooldown (seconds)`)}),d(W,{type:`number`,min:0,max:hr,step:1,value:String(A.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=qr(e.target.value);t!==void 0&&R({cooldownSec:t})}}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[me?D(`system.notificationRules.aCameraThatFlapsOr`,`A camera that flaps, or a node that reconnects every minute, would otherwise send one notification per flap. The cooldown is the shortest gap between two deliveries of this rule.`):D(`system.notificationRules.theShortestGapBetweenTwo`,`The shortest gap between two deliveries of this rule, counted as chosen below.`),` `,D(`system.notificationRules.cooldownRange`,{max:String(hr)})]})]}),i(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.cooldownCounted`,`Cooldown counted`)}),d(V,{value:A.cooldownScope,onChange:e=>{let t=Kt(e.target.value);t!==void 0&&R({cooldownScope:t})},options:$n.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`system.notificationRules.perDeviceADeliveryAbout`,`Per device: a delivery about one camera (or node) does not hold back another. Whole rule: one delivery per cooldown, whichever device matched.`)})]}),i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.acrossObjectClasses`,`Across object classes`)}),d(V,{value:A.cooldownGranularity??`per-class`,onChange:e=>R({cooldownGranularity:jn(e.target.value)}),options:Ir.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`system.notificationRules.separateDefaultADogAfter`,`Separate (default): a dog after a cat is delivered at once, a second cat still waits. Shared: a cat holds back the next dog for the cooldown. Sounds always count per class.`)})]})]}),i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(et,{checked:A.snoozeAllowGlobal,onCheckedChange:e=>R({snoozeAllowGlobal:e}),"aria-label":D(`system.notificationRules.allowGlobalSnooze`,`allow global snooze`),disabled:Ie}),D(`system.notificationRules.anyoneMaySnoozeThisRule`,`Anyone may snooze this rule for everyone`)]}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`system.notificationRules.aSnoozeIsPersonalBy`,`A snooze is personal by default — it silences only the person who set it. Turn this on for a rule where silencing the whole household is legitimate (the gardener is here all afternoon). Admins can always do it.`)})]}),!Ie&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.snoozeButtons`,`Snooze buttons`)}),i(o,{children:[d(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Wr.map(e=>{let t=A.snoozeOptions??Cr,n=t.includes(e);return d(U,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>R({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:An(e)},e)})}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:A.snoozeOptions===void 0?D(`system.notificationRules.notSetTheNotificationOffers`,`Not set — the notification offers the defaults ({{value1}}). A pause opened from a button silences this camera for this class of subject, only for whoever received the notification, and sends no summary.`,{value1:Cr.map(An).join(`, `)}):A.snoozeOptions.length===0?D(`system.notificationRules.noSnoozeButtonsOnThis`,`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`):D(`system.notificationRules.fourAtMostEverySnooze`,`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`)}),A.snoozeOptions!==void 0&&d(U,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>R({snoozeOptions:void 0}),children:D(`system.notificationRules.backToTheDefaults`,`Back to the defaults`)})]})]}),O&&e&&!Ie&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.silenceItNow`,`Silence it now`)}),d(lc,{ruleId:e.id,ruleName:e.name,exempt:Ie,variant:`full`})]})]}),i(K,{value:`notification`,className:`space-y-4`,children:[i(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.priority`,`Priority`)}),d(V,{value:String(A.priority),onChange:e=>R({priority:Number(e.target.value)}),options:Hr.map(e=>({value:String(e.value),label:e.label}))})]}),!ge.carriesMedia&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:ge.mediaBlurb??D(`system.notificationRules.aSystemEventCarriesNo`,`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`)}),ge.carriesMedia&&ge.mediaBlurb!==void 0&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:ge.mediaBlurb}),ge.carriesMedia&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.notificationImage`,`Image`)}),d(V,{value:A.mediaImage,onChange:e=>{let t=It(e.target.value);t&&R({mediaImage:t})},options:be.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-image`}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:be.find(e=>e.value===A.mediaImage)?.description}),i(`div`,{className:`mt-2 space-y-1`,children:[B&&A.mediaImage!==`crop`&&A.mediaImage!==`none`&&i(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:A.mediaShowTriggerZone,onChange:e=>R({mediaShowTriggerZone:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-trigger-zone`}),i(`span`,{children:[D(`system.notificationRules.showTriggerZone`,`Draw the zone that triggered the rule`),d(`span`,{className:`block text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.showTriggerZoneHelp`,`Outlines the zone on the scene. Not drawn on a subject crop.`)})]})]}),Oe(he)&&A.mediaImage!==`none`&&i(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:A.mediaShowSubjectPath,onChange:e=>R({mediaShowSubjectPath:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-subject-path`}),i(`span`,{children:[D(`system.notificationRules.showSubjectPath`,`Show the subject's path`),d(`span`,{className:`block text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.showSubjectPathHelp`,`Draws the line the subject walked, up to the moment of the picture. On a crop, only the part inside it.`)})]})]}),i(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:A.mediaGif,onChange:e=>R({mediaGif:e.target.checked}),className:`accent-primary`}),D(`system.notificationRules.attachAGifAroundThe`,`Attach a GIF around the event`)]}),i(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:A.mediaClip,onChange:e=>R({mediaClip:e.target.checked}),className:`accent-primary`}),D(`system.notificationRules.attachAnMp4ClipAround`,`Attach an MP4 clip around the event`)]})]}),(A.mediaGif||A.mediaClip)&&i(`div`,{className:`mt-2`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.videoQuality`,`Video quality`)}),d(V,{value:A.mediaProfile??``,onChange:e=>R({mediaProfile:kn(e.target.value)}),options:Br.map(e=>({value:e.value,label:e.label}))}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.aNotificationIsWatchedOn`,`A notification is watched on a phone — the cheapest stream is normally the right one, and the high profile only costs CPU to render.`)}),d(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.playbackSpeed`,`Playback speed`)}),d(V,{value:A.mediaClipSpeed===void 0?``:String(A.mediaClipSpeed),onChange:e=>R({mediaClipSpeed:Ht(e.target.value)}),options:Dr.map(e=>({value:e.value,label:e.label}))}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.aNotificationClipIsGlanced`,`A notification clip is glanced at, not watched: at 2× the recipient sees the whole passage in half the time and the file is half the size. Real time is there when the detail matters more than the glance.`)})]})]}),he===`sensor`&&ge.carriesMedia&&A.mediaImage!==`none`&&i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.linkedCameras`,`Linked cameras`)}),d(V,{value:A.mediaLinkedCameras??``,onChange:e=>R({mediaLinkedCameras:yr(e.target.value)}),options:rr.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.whenTheSensorIsLinked`,`When the sensor is linked to several cameras, all of them are photographed the moment it fires. Cameras that are offline or asleep are left out.`)})]})]}),i(`div`,{className:`space-y-2`,children:[d(Eo,{label:D(`system.notificationRules.notificationTitle`,`Notification title`),value:A.templateTitle,onChange:e=>R({templateTitle:e}),vars:Pe(`title`),testId:`rule-template-title`}),d(Eo,{label:D(`system.notificationRules.notificationBody`,`Notification body`),value:A.templateBody,onChange:e=>R({templateBody:e}),vars:Pe(`body`),multiline:!0,testId:`rule-template-body`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.leaveBothBlankForThe`,`Leave both blank for the hub's own wording (editable on the Texts tab).`)}),Ut(A)!==null&&d(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:Ut(A)}),d(Do,{context:Me(`body`),title:A.templateTitle,body:A.templateBody,testId:`rule-template-preview`})]})]}),i(K,{value:`conditions`,className:`space-y-4`,children:[i(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:me?D(`system.notificationRules.whichSystemEvents`,`Which system events`):Vr(A.conditions)??D(`system.notificationRules.conditions`,`Conditions`)}),A.conditions.audio!==void 0&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.thisIsASoundRule`,`This is a SOUND rule: it fires on a confirmed sampling window of audio, never on a picture. Name the sounds and/or keep a level threshold — with neither it can never match. Everything else below still composes (a camera scope, a schedule).`)}),A.conditions.occupancy!==void 0&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.thisIsAnOccupancyRule`,`This is an OCCUPANCY rule: it fires when the count in a camera frame or a zone crosses your threshold and holds. Pick the camera on the Devices tab first — the zone list is that camera's.`)}),me&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.pickTheEventsThisRule`,`Pick the events this rule reacts to, then narrow them if you want. Nothing else on a system rule is a condition — there is no detection behind it.`)}),c.length===0?d(`p`,{className:`text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.conditionCatalogUnavailableThisRule`,`Condition catalog unavailable — this rule matches on its trigger and targets alone.`)}):d(Bs,{catalog:Kr(A)?c.filter(e=>e.id!==`schedule`):c,taxonomy:l,delivery:A.delivery,conditions:A.conditions,classScope:A.classScope,onClassScopeChange:e=>R({classScope:e}),actions:Gt(A.actions),sequenceActionsOf:e=>v.find(t=>t.id===e)?.actions,savedConditions:k.conditions,schedule:A.schedule,deviceIds:Er(A),zoneCameraIds:rs(A.deviceScope,f),cameras:f,fleet:g,allDevices:h,gateable:p,gateableScenes:m,onConditionsChange:e=>R({conditions:e}),onScheduleChange:e=>R({schedule:e}),summary:Kr(A)})]}),me&&d(Qf,{value:A.systemEventDelivery,family:xe,onChange:e=>R({systemEventDelivery:e}),draft:()=>Ar(A,re,c)}),O&&e&&i(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:D(`system.notificationRules.testThisRuleForReal`,`Test this rule for real`)}),d(tl,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...Er(A)[0]===void 0?{}:{fallbackDeviceId:Er(A)[0]}})]}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.buildsTheEventThisRule`,`Builds the event this rule is about, runs the REAL evaluation and delivery, and sends the notification to every target — marked [TEST] in the body. The cooldown and the camera mute are bypassed (neither window is consumed); the rule's actions are never run. Saved conditions only: save first to test an edit.`)})]}),!me&&i(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:D(`system.notificationRules.testRule`,`Test rule`)}),i(U,{size:`sm`,variant:`outline`,type:`button`,disabled:z.isPending||!fr(A,re,new Set(v.map(e=>e.id))),onClick:()=>{N(null),z.mutate()},children:[z.isPending?d(T,{className:`h-3.5 w-3.5 animate-spin`}):d(We,{className:`h-3.5 w-3.5`}),D(`system.notificationRules.dryRunLast60Min`,`Dry-run (last 60 min)`)]})]}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.evaluateTheCurrentUnsavedRule`,`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`)}),ee!==null&&d(hp,{delivery:A.delivery,results:ee,targetNames:ae})]})]})]})}):d(mp,{rule:e,onCancel:C})}function mp({rule:e,onCancel:t}){let{t:n}=J(),r=Object.keys(e?.conditions??{});return i(Ct,{open:!0,onClose:t,title:e?.name??n(`system.notificationRules.rule`,`Rule`),icon:_,width:`lg`,children:[d(G,{variant:`warning`,className:`mb-3`,children:`read-only`}),d(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,"data-testid":`unsupported-trigger-notice`,children:d(Sr,{i18nKey:`system.notificationRules.unsupportedTrigger`,values:{trigger:e?.delivery},components:{code:d(`code`,{})}})}),i(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[i(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:n(`system.notificationRules.trigger`,`Trigger`)}),d(`dd`,{className:`text-foreground`,children:e?.delivery})]}),i(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:n(`system.notificationRules.enabled`,`Enabled`)}),d(`dd`,{className:`text-foreground`,children:e?.enabled?n(`common.yes`):n(`common.no`)})]}),i(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:n(`system.notificationRules.targets`,`Targets`)}),d(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),i(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:n(`system.notificationRules.conditions`,`Conditions`)}),d(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):n(`common.none`)})]})]})]})}function hp({delivery:e,results:t,targetNames:n}){let{t:r}=J();if(e===`device-event`)return d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:r(`system.notificationRules.deviceEventRulesCannotBe`,`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`)});if(t.length===0)return d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:r(`system.notificationRules.noRecordsInTheLast`,`No records in the last 60 minutes matched — nothing to evaluate.`)});let a=t.filter(e=>e.wouldFire).length;return i(`div`,{className:`mt-2 space-y-1.5`,children:[d(`div`,{className:`text-[11px] text-foreground-subtle`,children:r(`system.notificationRules.wouldFire`,{firing:a,count:t.length})}),d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>i(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?d(C,{className:`h-3.5 w-3.5 shrink-0 text-success`}):d(x,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),i(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),d(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??r(`system.notificationRules.objectFallback`)}),e.wouldFire?i(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,n.join(`, `)||r(`system.notificationRules.targetsFallback`)]}):e.failedCondition&&i(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}e();var gp=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,_p=`block text-[11px] font-medium text-foreground`,vp=[{value:`cap`,labelKey:`system.notificationSequences.stepDo`},{value:`wait`,labelKey:`system.notificationSequences.stepWait`}],yp=[[`notificationRules`,`listSequences`]],bp=[`sequence`,`new`];function xp(){return{name:``,minDelaySec:``,actions:[vr()]}}function Sp(e){return{id:e.id,name:e.name,minDelaySec:e.minDelaySec===void 0?``:String(e.minDelaySec),actions:[...e.actions]}}function Cp(e){return e instanceof Error?e.message:String(e)}function wp(e){let t=[],n=0;for(;n<e.length;){if(e[n].kind===`wait`){t.push({start:n,kind:`wait`,length:1}),n+=1;continue}let r=Fo(e,n);t.push({start:n,kind:`cap`,length:r.length}),n+=r.length}return t}function Tp(e){let t=e.actions.length;return e.minDelaySec===void 0?q.t(`system.notificationSequences.stepsLabel`,{count:t}):q.t(`system.notificationSequences.stepsDelay`,{count:t,delay:e.minDelaySec})}function Ep({draft:e,devices:t,fleetView:n,onChange:r}){let{t:a}=J(),o=wp(e.actions);return i(`div`,{className:`space-y-3`,children:[i(`div`,{className:`flex flex-wrap items-end gap-2`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:_p,children:a(`system.notificationSequences.name`,`Name`)}),d(W,{className:`mt-1`,value:e.name,onChange:t=>r({...e,name:t.target.value})})]}),i(`div`,{className:`w-28`,children:[d(`label`,{className:_p,children:a(`system.notificationSequences.minDelayS`,`Min delay (s)`)}),d(`input`,{type:`number`,min:0,className:gp,value:e.minDelaySec,onChange:t=>r({...e,minDelaySec:t.target.value})})]})]}),i(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[o.map(o=>{let s=e.actions[o.start];if(o.kind===`wait`&&s.kind===`wait`)return d(Op,{step:s,devices:t,listState:n.state,fleet:n,onChange:t=>r({...e,actions:e.actions.map((e,n)=>n===o.start?t:e)}),onRemove:()=>r({...e,actions:e.actions.filter((e,t)=>t!==o.start)})},`s-${String(o.start)}`);let c=Fo(e.actions,o.start);return i(`div`,{className:`flex flex-wrap items-start gap-2`,children:[i(`div`,{className:`w-24`,children:[d(`label`,{className:_p,children:a(`system.notificationSequences.step`,`Step`)}),d(V,{className:gp,value:`cap`,options:vp.map(e=>({value:e.value,label:a(e.labelKey)})),onChange:t=>{t.target.value===`wait`&&r({...e,actions:[...e.actions.slice(0,o.start),{kind:`wait`,seconds:5},...e.actions.slice(o.start+o.length)]})}})]}),d(ii,{value:c.wire,devices:t,listState:n.state,fleet:n,allowMultiSameFamily:!0,onChange:t=>{let n=No(t);r({...e,actions:[...e.actions.slice(0,o.start),...n,...e.actions.slice(o.start+o.length)]})}}),d(U,{size:`sm`,variant:`ghost`,type:`button`,title:a(`common.remove`,`Remove`),onClick:()=>r({...e,actions:[...e.actions.slice(0,o.start),...e.actions.slice(o.start+o.length)]}),children:d(p,{className:`h-3.5 w-3.5`})})]},`s-${String(o.start)}`)}),i(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({...e,actions:[...e.actions,vr()]}),children:[d(S,{className:`h-3.5 w-3.5`}),` `,a(`common.step`)]})]})]})}function Dp({createRequested:e=!1,onCreateConsumed:a,headerOwnsCreate:o=!1}={}){let{t:c}=J(),l=s(),u=bt({}),f=At(),p=Tt(),m=wt(),{state:h,openNew:g,openEdit:_,close:v}=gt({editKey:`sequence`,newKey:`new`}),[y,b]=r(null),[x,C]=r(null);t(()=>{e&&(C(null),g(),a?.())},[e]);let w=St({projection:`slim`}),T=nt(w),E=n(()=>(w.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[w.data]),D=u.data?.sequences??[],O=u.data!==void 0&&D.length===0,k=h.mode!==`closed`,A=f.isPending||p.isPending;t(()=>{if(h.mode===`closed`){b(null),C(null);return}if(h.mode===`new`){b(e=>e!==null&&e.id===void 0?e:xp());return}let e=D.find(e=>e.id===h.id);e!==void 0&&b(t=>t?.id===h.id?t:Sp(e))},[h,D]);let j=()=>{l.invalidateQueries({queryKey:yp})},M=()=>{f.reset(),p.reset(),C(null),b(null),v()},N=async()=>{if(y===null||y.name.trim()===``||y.actions.length===0)return;let e={name:y.name.trim(),...y.minDelaySec===``?{}:{minDelaySec:Number(y.minDelaySec)},actions:y.actions};try{y.id===void 0?await f.mutateAsync({sequence:e}):await p.mutateAsync({sequenceId:y.id,sequence:e}),M(),j()}catch(e){C(Cp(e))}},P=n(()=>[{key:`name`,header:c(`system.notificationSequences.name`,`Name`),nowrap:!1,sortValue:e=>e.name,render:e=>d(rf,{name:e.name,enabled:!0,onOpen:()=>_(e.id),openTestId:`sequence-open-${e.id}`})},{key:`steps`,header:c(`system.notificationSequences.steps`,`Steps`),nowrap:!0,sortValue:e=>e.actions.length,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Tp(e)})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:e=>i($d,{className:`flex items-center justify-end gap-1`,children:[d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>_(e.id),children:c(`common.edit`,`Edit`)}),d(af,{pending:m.isPending,title:c(`system.notificationSequences.deleteThisSequence`,`Delete this sequence?`),message:c(`system.notificationSequences.willBeRemovedRulesAnd`,`“{{name}}” will be removed. Rules and buttons that bind to it keep the id until you re-point them.`,{name:e.name}),ariaLabel:c(`system.notificationSequences.delete`,`Delete {{name}}`,{name:e.name}),testId:`sequence-delete-${e.id}`,onConfirm:()=>{m.mutateAsync({sequenceId:e.id}).then(j)}})]})}],[m,_,c]);return i(ai,{embedded:!0,icon:Je,title:c(`system.notificationSequences.sequences`,`Sequences`),subtitle:c(`system.notificationSequences.namedStepListsSharedBy`,`Named step lists shared by notification rules and buttons. A rule binds to one by id; two rules sharing a gate share its throttle.`),children:[o?null:d(`div`,{className:`mb-3 flex justify-end`,children:i(U,{size:`sm`,type:`button`,onClick:()=>{C(null),g()},children:[d(S,{className:`h-3.5 w-3.5`}),` `,c(`system.notificationSequences.newSequence`)]})}),u.error!=null&&d(H,{title:c(`system.notificationSequences.couldNotReadSequences`,`Could not read sequences`),message:Cp(u.error),onRetry:()=>void u.refetch()}),u.isPending&&d(ef,{}),O&&d(tf,{testId:`sequences-empty`,children:c(`system.notificationSequences.noSequencesYetCreateOne`,`No sequences yet. Create one, then bind it from a rule's Actions tab.`)}),D.length>0&&d(nf,{columns:P,rows:D,rowKey:e=>e.id,minWidthPx:480,onRowClick:e=>_(e.id)}),d(Ct,{open:k&&y!==null,onClose:M,title:y?.id===void 0?c(`system.notificationSequences.newSequence`,`New sequence`):c(`system.notificationSequences.edit`,`Edit {{value1}}`,{value1:y.name||`sequence`}),icon:Je,width:`xl`,error:x,testId:`sequence-editor-panel`,footer:d(U,{size:`sm`,type:`button`,disabled:A||y===null||y.name.trim()===``||y.actions.length===0,onClick:()=>void N(),children:A?c(`system.notificationSequences.saving`,`Saving…`):c(`common.save`,`Save`)}),children:y!==null&&d(Ep,{draft:y,devices:E,fleetView:T,onChange:b})}),m.error!=null&&d(H,{message:Cp(m.error)})]})}function Op({step:e,devices:t,listState:n,fleet:r,onChange:a,onRemove:o}){let{t:s}=J();return i(`div`,{className:`flex flex-wrap items-start gap-2`,children:[i(`div`,{className:`w-24`,children:[d(`label`,{className:_p,children:s(`system.notificationSequences.step`,`Step`)}),d(V,{className:gp,value:`wait`,options:vp.map(e=>({value:e.value,label:s(e.labelKey)})),onChange:n=>a(n.target.value===`wait`?{kind:`wait`,seconds:e.seconds}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``})})]}),i(`div`,{className:`w-28`,children:[d(`label`,{className:_p,children:s(`system.notificationSequences.seconds`,`Seconds`)}),d(`input`,{type:`number`,min:0,max:300,className:gp,value:e.seconds,onChange:e=>a({kind:`wait`,seconds:Number(e.target.value)})})]}),d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:s(`common.remove`,`Remove`),children:d(p,{className:`h-3.5 w-3.5`})})]})}var kp=`alert-center`;function Ap(){let{t:e}=J(),t=E();return i(`div`,{className:`space-y-3`,"data-testid":`notification-settings`,children:[d(`p`,{className:M,children:e(`systemPage.notifications.settingsHint`,`Alert storage and retention. Alerts are notified only through notification rules on the alert kinds.`)}),d(ft,{trpc:t.trpcClient,addonId:kp,nodeId:`hub`,bare:!0})]})}var jp=[{value:`object-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.objectLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.objectHint`)}},{value:`track-end`,get label(){return q.t(`helpers.notificationSimulateHelpers.trackEndLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.trackEndHint`)}},{value:`device-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.deviceEventLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.deviceEventHint`)}},{value:`package-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.packageEventLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.packageEventHint`)}},{value:`audio-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.audioEventLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.audioEventHint`)}},{value:`occupancy-event`,get label(){return q.t(`helpers.notificationSimulateHelpers.occupancyEdgeLabel`)},get hint(){return q.t(`helpers.notificationSimulateHelpers.occupancyEdgeHint`)}}];function Mp(e){return jp.find(t=>t.value===e)?.value}function Np(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Pp(e){return``}var Fp={x:.25,y:.25,w:.5,h:.5},Ip={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Lp(){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:Fp,occupancy:Ip,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function Rp(e){return e.deviceId!==null}function zp(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Bp(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Vp(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 Hp(e){if(e.deviceId===null)return null;let t=e.trigger,n=Bp(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:Up(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 Up(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 Wp(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Gp(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 Kp(e){let t=Lp(),n=e.conditions,r=Gp(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:Wp(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Wp(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Wp(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:Pp(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:qp(n.occupancy)},onlyRuleId:e.id}}function qp(e){let t=Math.max(1,Math.round(e.count)),n={zoneId:e.zoneId??``,zoneName:``,className:e.className??``,threshold:t};if(e.op===`became-free`)return{...n,count:0,previousCount:t,occupied:!1};if(e.op===`<=`){let t=Math.max(0,Math.round(e.count));return{...n,count:t,previousCount:t+1,occupied:t>0}}return{...n,count:t,previousCount:Math.max(0,t-1),occupied:!0}}function Jp(e){let t=[];return e.conditions.deviceState!==void 0&&t.push({conditionId:`deviceState`,note:q.t(`helpers.notificationSimulateHelpers.caveatDevice`,{deviceId:e.conditions.deviceState.deviceId})}),e.conditions.scene!==void 0&&t.push({conditionId:`scene`,note:q.t(`helpers.notificationSimulateHelpers.caveatScene`,{state:e.conditions.scene.requiredState})}),e.conditions.customZones!==void 0&&e.conditions.customZones.length>0&&t.push({conditionId:`customZones`,note:q.t(`helpers.notificationSimulateHelpers.caveatZones`)}),t}function Yp(e){return{form:Kp(e),caveats:Jp(e),ruleName:e.name}}var Xp=null;function Zp(e){Xp=e}function Qp(){return Xp}function $p(){Xp=null}var em=[`n/a`,`clear`,`suppressed`,`bypassed`],tm=[`live`,`none`,`unavailable`,`unattachable`];function nm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rm(e,t){let n=e[t];return typeof n==`string`?n:void 0}function im(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function am(e){if(!nm(e))return null;let t=rm(e,`ruleId`),n=rm(e,`ruleName`),r=rm(e,`cooldown`),i=em.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=rm(e,`failedCondition`),o=Array.isArray(e.matchedOn)?im(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:im(e,`targetIds`)}}function om(e){if(!nm(e))return null;let t=rm(e,`recordId`),n=rm(e,`delivery`),r=rm(e,`still`),i=tm.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=am(e);t!==null&&o.push(t)}let s=rm(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:im(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function sm(e){if(e.droppedBy!==void 0)return q.t(`helpers.notificationSimulateHelpers.dropped`,{reason:e.droppedBy});if(e.candidates===0)return q.t(`helpers.notificationSimulateHelpers.noCandidates`,{delivery:e.delivery});let t=e.outcomes.filter(e=>e.matched).length,n=e.outcomes.reduce((e,t)=>e+t.enqueued,0);return t===0?q.t(`helpers.notificationSimulateHelpers.noneMatched`,{count:e.candidates}):q.t(`helpers.notificationSimulateHelpers.matchedSummary`,{matched:t,candidates:e.candidates,enqueued:n})}var cm=new Set([`sensor`,`control`,`custom`]);function lm({form:e,cameras:t,taxonomy:n,kinds:r,kindsLoading:a,onPatch:o}){let{t:s}=J(),c=e.deviceId===null?[]:[e.deviceId],l=Se(`classes`,n);if(e.trigger===`device-event`)return i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),d(um,{form:e,kinds:r,loading:a,onPatch:o})]});if(e.trigger===`audio-event`){let n=r.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(`div`,{children:[d(`label`,{className:Y,children:s(`system.notificationSimulateFields.audioClasses`,`Audio classes`)}),d(_n,{options:n,value:e.classNames,onChange:e=>o({classNames:e}),loading:a,emptyHint:e.deviceId===null?`Pick a camera first — the audio vocabulary is per camera.`:`This camera advertises no audio kinds. The audio classifier is probably off for it.`,placeholder:s(`system.notificationSimulateFields.audioClassId`,`Audio class id…`)})]}),i(`div`,{children:[d(`label`,{className:Y,children:s(`system.notificationSimulateFields.zones`,`Zones`)}),d(Pt,{deviceIds:c,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]})]})}return e.trigger===`occupancy-event`?i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),d(dm,{form:e,cameras:t,taxonomy:n,onPatch:o})]}):i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(`div`,{children:[d(`label`,{className:Y,children:s(`system.notificationSimulateFields.detectedClasses`,`Detected classes`)}),l===null?d(Jn,{value:e.classNames,placeholder:s(`system.notificationSimulateFields.classIdPersonCar`,`Class id (person, car…)`),onChange:e=>o({classNames:e})}):d(Cn,{picker:l,value:e.classNames,onChange:e=>o({classNames:e})})]}),i(`div`,{children:[d(`label`,{className:Y,children:s(`system.notificationSimulateFields.zonesTheSubjectIsIn`,`Zones the subject is in`)}),d(Pt,{deviceIds:c,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&i(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:s(`system.notificationSimulateFields.packagePhase`,`Package phase`)}),d(V,{value:e.packagePhase,options:[{value:``,label:s(`system.notificationSimulateFields.none`,`— none —`)},{value:`delivered`,label:s(`system.notificationSimulateFields.delivered`,`Delivered`)},{value:`picked-up`,label:s(`system.notificationSimulateFields.pickedUp`,`Picked up`)}],onChange:e=>o({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function um({form:e,kinds:t,loading:n,onPatch:r}){let{t:a}=J(),s=t.filter(e=>cm.has(e.category)),c=s.find(t=>t.kind===e.sensorKind);return i(o,{children:[i(`div`,{children:[d(`label`,{className:Y,children:a(`system.notificationSimulateFields.eventKind`,`Event kind`)}),d(V,{value:e.sensorKind,options:[{value:``,label:n?a(`system.notificationSimulateFields.loadingKinds`,`Loading kinds…`):a(`system.notificationSimulateFields.pickAKind`,`— pick a kind —`)},...s.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=s.find(t=>t.kind===e.target.value);r({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!n&&s.length===0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.deviceId===null?a(`system.notificationSimulateFields.pickACameraFirstSensor`,`Pick a camera first — sensor and control kinds come from the devices linked to it.`):a(`system.notificationSimulateFields.thisCameraHasNoLinked`,`This camera has no linked sensor or control device, so it can produce no device event. Link one on the camera page first.`)})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:Y,children:a(`system.notificationSimulateFields.sourceDevice`,`Source device`)}),d(W,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:a(`system.notificationSimulateFields.theCameraItself`,`the camera itself`),onChange:e=>r({sourceDeviceId:zp(e.target.value)??null})}),d(`p`,{className:Zt,children:c===void 0?a(`system.notificationSimulateFields.theLinkedDeviceWhoseState`,`The linked device whose state changed. Filled in for you when you pick a kind.`):a(`system.notificationSimulateFields.filledInFromContributedBy`,`Filled in from "{{label}}" — contributed by device #{{deviceId}} via the {{capName}} capability.`,{label:c.label,deviceId:c.source.deviceId,capName:c.source.capName})})]}),i(`div`,{children:[d(`label`,{className:Y,children:a(`system.notificationSimulateFields.eventTypeToken`,`Event type token`)}),d(W,{value:e.eventType,placeholder:a(`system.notificationSimulateFields.pressPressLong`,`press, press_long…`),onChange:e=>r({eventType:e.target.value})}),d(`p`,{className:Zt,children:a(`system.notificationSimulateFields.onlyEventEmitterSourcesCarry`,`Only event-emitter sources carry one. A passive sensor emits none, and a rule gating on a token would fail closed for it.`)})]})]})]})}function dm({form:e,cameras:t,taxonomy:n,onPatch:r}){let{t:a}=J(),s=e.deviceId===null?[]:[e.deviceId],c=Se(`occupancy`,n),l=c===null?[]:c.groups.flatMap(e=>e.options),u=e.occupancy,f=e=>r({occupancy:{...u,...e}});return i(o,{children:[i(`div`,{children:[d(`label`,{className:Y,children:a(`system.notificationSimulateFields.zone`,`Zone`)}),d(Pt,{deviceIds:s,cameras:t,value:u.zoneId===``?[]:[u.zoneId],onChange:e=>f({zoneId:e[e.length-1]??``})}),d(`p`,{className:Zt,children:a(`system.notificationSimulateFields.leaveEmptyForTheWhole`,`Leave empty for the whole frame.`)})]}),i(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:Y,children:a(`system.notificationSimulateFields.class`,`Class`)}),d(V,{value:u.className,options:[{value:``,label:a(`system.notificationSimulateFields.anyClass`,`— any class —`)},...l.map(e=>({value:e.value,label:e.label}))],onChange:e=>f({className:e.target.value})})]}),i(`div`,{className:`flex flex-wrap items-end gap-3`,children:[i(`label`,{className:`text-[11px] text-foreground-subtle`,children:[a(`system.notificationSimulateFields.countNow`,`Count now`),d(W,{type:`number`,min:0,className:`w-20`,value:String(u.count),onChange:e=>f({count:zp(e.target.value)??0})})]}),i(`label`,{className:`text-[11px] text-foreground-subtle`,children:[a(`system.notificationSimulateFields.countBefore`,`Count before`),d(W,{type:`number`,min:0,className:`w-20`,value:String(u.previousCount),onChange:e=>f({previousCount:zp(e.target.value)??0})})]}),i(`label`,{className:`text-[11px] text-foreground-subtle`,children:[a(`system.notificationSimulateFields.threshold`,`Threshold`),d(W,{type:`number`,min:1,className:`w-20`,value:String(u.threshold),onChange:e=>f({threshold:zp(e.target.value)??1})})]}),i(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[d(et,{checked:u.occupied,onCheckedChange:e=>f({occupied:e}),"aria-label":a(`system.notificationSimulateFields.occupiedLabel`)}),a(`system.notificationSimulateFields.occupiedLabel`,`Occupied`)]})]})]})}function fm({form:e,cameras:t,onPatch:n}){let{t:r}=J(),a=e.deviceId===null?[]:[e.deviceId];return i(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[d(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:r(`system.notificationSimulateFields.advanced`,`Advanced`)}),i(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(et,{checked:e.crossingEnabled,onCheckedChange:e=>n({crossingEnabled:e}),"aria-label":r(`system.notificationSimulateFields.zoneCrossing`,`zone crossing`)}),r(`system.notificationSimulateFields.thisEventIsAConfirmed`,`This event is a confirmed zone crossing`)]}),e.crossingEnabled&&i(`div`,{className:`mt-1 space-y-1.5`,children:[d(`div`,{className:`max-w-[12rem]`,children:d(V,{value:e.crossingDirection,options:[{value:`enter`,label:r(`system.notificationSimulateFields.enteredTheZone`,`Entered the zone`)},{value:`exit`,label:r(`system.notificationSimulateFields.leftTheZone`,`Left the zone`)}],onChange:e=>n({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),d(Pt,{deviceIds:a,cameras:t,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>n({crossingZoneId:e[e.length-1]??``})})]})]}),i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(et,{checked:e.bboxEnabled,onCheckedChange:e=>n({bboxEnabled:e}),"aria-label":r(`system.notificationSimulateFields.boundingBox`,`bounding box`)}),r(`system.notificationSimulateFields.carryABoundingBox`,`Carry a bounding box`)]}),d(`p`,{className:Zt,children:r(`system.notificationSimulateFields.normalized01TopLeft`,"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed.")}),e.bboxEnabled&&d(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>i(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,d(W,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:r=>n({bbox:{...e.bbox,[t]:zp(r.target.value)??0}})})]},t))})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:Y,children:r(`system.notificationSimulateFields.happenedAt`,`Happened at`)}),i(`div`,{className:`flex items-center gap-2`,children:[d(W,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>n({timestampLocal:e.target.value})}),e.timestampLocal===``?d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:Vp(Date.now())}),children:r(`system.notificationSimulateFields.set`,`Set`)}):d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:``}),children:r(`system.notificationSimulateFields.now`,`Now`)})]}),d(`p`,{className:Zt,children:r(`system.notificationSimulateFields.emptyNowSetItTo`,`Empty = now. Set it to a time inside (or outside) a rule's schedule window to test the schedule without waiting for the hour.`)})]}),i(`div`,{children:[d(`label`,{className:Y,children:r(`system.notificationSimulateFields.detectionSource`,`Detection source`)}),d(V,{value:e.source,options:[{value:``,label:r(`system.notificationSimulateFields.unsetReadsAsPipeline`,`— unset (reads as pipeline) —`)},{value:`pipeline`,label:r(`system.notificationSimulateFields.pipeline`,`Pipeline`)},{value:`onboard`,label:r(`system.notificationSimulateFields.onboardCamera`,`Onboard (camera)`)},{value:`sensor`,label:r(`system.notificationSimulateFields.sensor`,`Sensor`)},{value:`audio`,label:r(`system.notificationSimulateFields.audio`,`Audio`)}],onChange:e=>{let t=e.target.value;n({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function pm({checked:e,label:t,hint:n,danger:r=!1,onChange:a}){let{t:o}=J();return i(`div`,{children:[i(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(et,{checked:e,onCheckedChange:a,"aria-label":t}),t,r&&d(G,{variant:`danger`,children:o(`system.notificationSimulateFields.actuatesDevices`,`actuates devices`)})]}),d(`p`,{className:Zt,children:n})]})}e();var mm={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.`},hm={"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 gm({result:e,targetName:t}){let{t:n}=J();return i(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[d(`p`,{className:`text-xs font-medium text-foreground`,children:sm(e)}),i(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[d(_m,{recordId:e.recordId}),d(`span`,{children:d(Sr,{i18nKey:`system.notificationSimulateResult.delivery`,values:{value:e.delivery},components:{b:d(`span`,{className:`text-foreground`})}})}),d(`span`,{children:d(Sr,{i18nKey:`system.notificationSimulateResult.candidates`,values:{value:e.candidates},components:{b:d(`span`,{className:`text-foreground`})}})}),d(`span`,{title:mm[e.still],children:d(Sr,{i18nKey:`system.notificationSimulateResult.still`,values:{value:e.still},components:{b:d(`span`,{className:`text-foreground`})}})}),e.droppedBy!==void 0&&d(G,{variant:`warning`,children:n(`system.notificationSimulateResult.droppedBy`,{by:e.droppedBy})})]}),e.notes.length>0&&d(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>d(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:d(Sr,{i18nKey:`system.notificationSimulateResult.noRuleEvaluated`,values:{delivery:e.delivery},components:{b:d(`span`,{className:`text-foreground`})}})}):d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>d(vm,{outcome:e,targetName:t},e.ruleId))})]})}function _m({recordId:e}){let{t}=J(),[n,a]=r(!1);return i(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[d(`code`,{className:`text-[10px] text-foreground`,children:e}),d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),1500)},()=>a(!1))},title:t(`system.notificationSimulateResult.copyRecordId`,`Copy record id`),children:d(v,{className:`h-3 w-3`})}),n&&d(`span`,{className:`text-[10px] text-success`,children:t(`common.copiedLower`)})]})}function vm({outcome:e,targetName:t}){let{t:n}=J();return i(`li`,{className:`space-y-1 px-2.5 py-2`,children:[i(`div`,{className:`flex items-center gap-2`,children:[e.matched?d(C,{className:`h-3.5 w-3.5 shrink-0 text-success`}):d(x,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),i(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:hm[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&d(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?n(`system.notificationSimulateResult.didNotMatchTheEngine`,`Did not match. The engine reported no failing condition id.`):d(Sr,{i18nKey:`system.notificationSimulateResult.failingCondition`,values:{condition:e.failedCondition},components:{code:d(`code`,{className:`text-foreground`})}})}),e.matched&&i(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[n(`system.notificationSimulateResult.enqueued`,{count:e.enqueued}),e.targetIds.length>0?` → ${e.targetIds.map(t).join(`, `)}`:` — ${n(`system.notificationSimulateResult.noTargetResolved`)}`,`.`]}),e.matchedOn!==void 0&&e.matchedOn.length>0&&d(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:n(`system.notificationSimulateResult.matchedOn`,{on:e.matchedOn.join(`, `)})})]})}e();var ym=`pipeline-analytics`,bm=`nc.injectTestEvent`;function xm(){let{t:e}=J(),o=E(),[s,c]=r(()=>Qp()?.form??Lp()),[l,f]=r(()=>Qp()?.caveats??[]),[p,m]=r(()=>Qp()?.ruleName??null);t(()=>$p(),[]);let[g,_]=r(null),[v,y]=r(!1),[b,x]=r(null),S=e=>c(t=>({...t,...e})),C=St({projection:`slim`}),w=a({queryKey:cp,queryFn:()=>o.trpcClient.notificationRules.getConditionCatalog.query({})}),D=a({queryKey:op,queryFn:async()=>(await o.trpcClient.notificationRules.listRules.query({})).rules}),O=a({queryKey:sp,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),k=s.deviceId,A=a({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:k}],enabled:k!==null,staleTime:6e4,queryFn:async()=>k===null?[]:(await o.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[k]})).flatMap(e=>[...e.kinds])}),j=n(()=>(C.data??[]).filter(e=>e.type===Ce.Camera).map(e=>({id:e.id,name:e.name})),[C.data]),M=w.data?.taxonomy,N=A.data??[],P=n(()=>{let e=new Map;for(let t of O.data??[])e.set(t.id,t.name);return e},[O.data]),F=u({mutationFn:async()=>{let e=Hp(s);if(e===null)throw Error(`Pick a camera first.`);return o.trpcClient.addons.custom.mutate({addonId:ym,action:bm,input:e})},onMutate:()=>{_(null),y(!1),x(null)},onSuccess:e=>{let t=om(e);_(t),y(t===null)},onError:e=>x(e instanceof Error?e.message:`The simulation failed.`)}),I=Np(s.trigger),ee=D.data?.find(e=>e.id===s.onlyRuleId);return i(ai,{embedded:!0,icon:We,title:e(`system.notificationSimulate.simulateAnEvent`,`Simulate an event`),subtitle:e(`system.notificationSimulate.injectASyntheticDetectionDoorbell`,`Inject a synthetic detection, doorbell press or occupancy edge and see exactly which rules match it, which condition each one fails on, and what would be delivered. Nothing is persisted — no track, no event row, no media.`),children:[C.isError&&d(H,{title:e(`system.notificationSimulate.failedToLoadCameras`,`Failed to load cameras`),message:C.error instanceof Error?C.error.message:e(`system.notificationSimulate.unknownError`,`Unknown error`),onRetry:()=>void C.refetch()}),p!==null&&d(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:d(Sr,{i18nKey:`system.notificationSimulate.seededFrom`,values:{rule:p},components:{b:d(`span`,{className:`font-medium`})}})}),l.length>0&&d(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:l.map(e=>i(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[d(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),d(`span`,{children:e.note})]},e.conditionId))}),i(pt,{className:`space-y-4`,children:[i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.ruleToSimulate`,`Rule to simulate`)}),d(V,{"data-testid":`simulate-seed-rule`,value:s.onlyRuleId,options:[{value:``,label:e(`system.notificationSimulate.pickARuleToPrefill`,`— pick a rule to prefill trigger + conditions —`)},...(D.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.delivery}`}))],onChange:e=>{let t=e.target.value;if(t.length===0){c(Lp()),f([]),m(null);return}let n=D.data?.find(e=>e.id===t);if(n===void 0){S({onlyRuleId:t});return}c(Kp(n)),f(Jp(n)),m(n.name)}}),d(`p`,{className:Zt,children:e(`system.notificationSimulate.picksTheTriggerThatRule`,`Picks the trigger that rule listens for and fills the fields from its conditions. Edit any value below, then inject.`)})]}),i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.camera`,`Camera`)}),d(V,{"data-testid":`simulate-camera`,value:s.deviceId===null?``:String(s.deviceId),options:[{value:``,label:j.length===0?e(`system.notificationSimulate.loadingCameras`,`Loading cameras…`):e(`system.notificationSimulate.pickACamera`,`— pick a camera —`)},...j.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{S({deviceId:zp(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...s.occupancy,zoneId:``}})}}),d(`p`,{className:Zt,children:e(`system.notificationSimulate.theCameraTheEventIs`,`The camera the event is attributed to — what a notification shows.`)})]}),i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.trigger`,`Trigger`)}),d(V,{"data-testid":`simulate-trigger`,value:s.trigger,options:jp.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Mp(e.target.value);if(!t)return;let n=Pp(s.trigger);S({trigger:t,source:s.source===``||s.source===n?Pp(t):s.source})}}),i(`p`,{className:Zt,children:[jp.find(e=>e.value===s.trigger)?.hint,` `,d(Sr,{i18nKey:`system.notificationSimulate.onlyRulesWhoseTrigger`,values:{delivery:I},components:{b:d(`span`,{className:`text-foreground`})}})]})]}),d(lm,{form:s,cameras:j,taxonomy:M,kinds:N,kindsLoading:A.isLoading,onPatch:S}),i(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[d(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:e(`system.notificationSimulate.quality`,`Quality`)}),i(`div`,{className:`mt-2 space-y-3`,children:[d(`p`,{className:Zt,children:e(`system.notificationSimulate.everyFieldHereCanBe`,`Every field here can be left EMPTY, and empty is a real state: a rule with a minimum confidence FAILS on a subject that carries none. Leave one blank to reproduce exactly that.`)}),i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.labelIdentityNamePlateSubclass`,`Label (identity name / plate / subclass)`)}),d(W,{value:s.label,placeholder:e(`system.notificationSimulate.eGMarcoAb123cd`,`e.g. Marco, AB123CD`),onChange:e=>S({label:e.target.value})})]}),i(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.detectionConfidence`,`Detection confidence`)}),d(Nr,{value:s.confidence,min:0,max:1,step:.05,onChange:e=>S({confidence:e})})]}),i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.labelMatchConfidence`,`Label-match confidence`)}),d(Nr,{value:s.labelConfidence,min:0,max:1,step:.05,onChange:e=>S({labelConfidence:e})})]}),i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.importance`,`Importance`)}),d(Nr,{value:s.importance,min:0,max:1,step:.05,onChange:e=>S({importance:e})})]}),i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.dwellSeconds`,`Dwell (seconds)`)}),d(Nr,{value:s.dwellSeconds,min:0,step:1,onChange:e=>S({dwellSeconds:e})})]})]})]})]}),d(fm,{form:s,cameras:j,onPatch:S}),i(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:e(`system.notificationSimulate.howToRunIt`,`How to run it`)}),d(pm,{checked:s.bypassCooldown,label:e(`system.notificationSimulate.ignoreTheCooldown`,`Ignore the cooldown`),hint:e(`system.notificationSimulate.aRuleThatAlreadyFired`,`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`),onChange:e=>S({bypassCooldown:e})}),d(pm,{checked:s.bypassMute,label:e(`system.notificationSimulate.ignoreMutesAndSnoozes`,`Ignore mutes and snoozes`),hint:e(`system.notificationSimulate.aMutedCameraOrA`,`A muted camera or a snoozed rule drops the event before any rule is consulted.`),onChange:e=>S({bypassMute:e})}),d(pm,{checked:s.runActions,danger:!0,label:e(`system.notificationSimulate.runTheRuleSActions`,`Run the rule's actions — this actuates real devices`),hint:e(`system.notificationSimulate.aMatchedRuleSOntrigger`,`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`),onChange:e=>S({runActions:e})}),i(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.stillImage`,`Still image`)}),d(V,{value:s.still,options:[{value:`live`,label:e(`system.notificationSimulate.liveSnapshotOfTheCamera`,`Live snapshot of the camera`)},{value:`none`,label:e(`system.notificationSimulate.noImage`,`No image`)}],onChange:e=>S({still:e.target.value===`none`?`none`:`live`})})]}),i(`div`,{children:[d(`label`,{className:Y,children:e(`system.notificationSimulate.evaluateOnlyOneRule`,`Evaluate only one rule`)}),d(V,{value:s.onlyRuleId,options:[{value:``,label:e(`system.notificationSimulate.everyEnabledRule`,`— every enabled rule —`)},...(D.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>S({onlyRuleId:e.target.value})}),s.onlyRuleId.length>0&&ee===void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:d(Sr,{i18nKey:`system.notificationSimulate.ruleNotInList`,values:{id:s.onlyRuleId},components:{code:d(`code`,{})}})})]})]}),b!==null&&d(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:b}),i(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[d(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:e(`system.notificationSimulate.nothingIsPersistedNoTrack`,`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`)}),i(U,{size:`sm`,type:`button`,disabled:F.isPending||!Rp(s),onClick:()=>F.mutate(),children:[F.isPending?d(T,{className:`h-3.5 w-3.5 animate-spin`}):d(We,{className:`h-3.5 w-3.5`}),e(`system.notificationSimulate.injectEvent`,`Inject event`)]})]})]}),v&&d(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:e(`system.notificationSimulate.theHubAnsweredButThis`,`The hub answered, but this build could not read the answer. That is what a hub older than the simulator looks like — update the server, then re-run.`)}),g!==null&&d(gm,{result:g,targetName:e=>P.get(e)??e})]})}var Sm=e=>typeof e==`string`&&e.length>0;function Cm(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 wm(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Tm(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Sm(i)&&n.push({mediaType:r,url:i})}return n}function Em(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Sm(r.label),i=Sm(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:q.t(`helpers.notificationTestComposer.actionN`,{n:n.length+1}),...i?{url:r.url}:{}})}return n}function Dm(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Tm(e,t.attachmentUrls),i=Em(e,t.actions),a=e.ttl&&Sm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:wm(e,t.format),priority:Om(t.priority),...Sm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Sm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Sm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Sm(t.tag)?{tag:t.tag}:{}}}function Om(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function km(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 Am(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var jm={image:g(`/addon/notifiers/samples/image`),video:g(`/addon/notifiers/samples/video`),gif:g(`/addon/notifiers/samples/gif`),audio:g(`/addon/notifiers/samples/audio`),icon:g(`/addon/notifiers/samples/icon`)};function Mm(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function Nm(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])Mm(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function Pm(e,t,n){let r=Am(e);return Mm(e,t)?{...r,body:n,attachmentUrls:{[t]:jm[t]}}:{...r,body:n}}function Fm(e,t){let n=Am(e);switch(t){case`text`:return{...n,title:`CamStack`,body:q.t(`helpers.notificationTestComposer.presetText`)};case`image`:return Pm(e,`image`,q.t(`helpers.notificationTestComposer.presetImage`));case`gif`:return Pm(e,`gif`,q.t(`helpers.notificationTestComposer.presetGif`));case`video`:return Pm(e,`video`,q.t(`helpers.notificationTestComposer.presetVideo`));case`audio`:return Pm(e,`audio`,q.t(`helpers.notificationTestComposer.presetAudio`));case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:q.t(`helpers.notificationTestComposer.actionN`,{n:t+1}),url:`/`}));return{...n,title:`CamStack`,body:q.t(`helpers.notificationTestComposer.presetActions`),actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=km(e);return{...n,title:`CamStack`,body:q.t(`helpers.notificationTestComposer.presetCritical`),priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}e();var Im={get text(){return q.t(`system.notificationTestPanel.presetText`)},get image(){return q.t(`system.notificationTestPanel.presetImage`)},get gif(){return q.t(`system.notificationTestPanel.presetGif`)},get video(){return q.t(`system.notificationTestPanel.presetVideo`)},get audio(){return q.t(`system.notificationTestPanel.presetAudio`)},get actions(){return q.t(`system.notificationTestPanel.presetActions`)},get critical(){return q.t(`system.notificationTestPanel.presetCritical`)},get overflow(){return q.t(`system.notificationTestPanel.presetOverflow`)}},Lm=`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`,Rm=`block text-[11px] font-medium text-foreground mb-1`;function zm({target:e,kind:t,open:a,onClose:o}){let{t:s}=J(),c=E(),l=n(()=>Cm(t.caps),[t.caps]),f=n(()=>Nm(t.caps),[t.caps]),[p,m]=r(()=>Am(t.caps)),[h,g]=r(null),_=n(()=>Dm(t.caps,p),[t.caps,p]),v=p.body.length,y=v>l.bodyMaxLen,b=e=>m(t=>({...t,...e})),x=u({mutationFn:()=>c.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:Dm(t.caps,p)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:q.t(`system.notificationTestPanel.testFailed`)})}),S=e=>{m(Fm(t.caps,e)),g(null)},C=(e,t,n)=>{let r=p.actions.length>0?[...p.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},b({actions:r})};return d(mt,{open:a,onOpenChange:e=>!e&&o(),children:i(Dt,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[d(_t,{children:d(dt,{children:s(`system.notificationTestPanel.testTitle`,{name:e.name,kind:t.label})})}),i(ht,{className:`space-y-4 pr-1`,children:[d(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map(e=>d(U,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>S(e),children:Im[e]},e))}),i(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[l.levels.length>0&&i(`div`,{children:[d(`label`,{className:Rm,children:s(`system.notificationTestPanel.level`,`Level`)}),i(`select`,{className:Lm,value:p.level,onChange:e=>b({level:e.target.value}),children:[d(`option`,{value:``,children:s(`system.notificationTestPanel.deriveFromPriority`,`— derive from priority —`)}),l.levels.map(e=>i(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (${s(`system.notificationTestPanel.qualitative`)})`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=l.levels.find(e=>e.id===p.level);return e?i(`div`,{className:`mt-1 space-y-1`,children:[e.description&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),i(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&d(G,{variant:`danger`,"data-testid":`flag-critical`,children:s(`system.notificationTestPanel.critical`)}),e.flags?.silent&&d(G,{variant:`info`,children:s(`system.notificationTestPanel.silent`)}),e.flags?.noPush&&d(G,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&i(`p`,{className:`text-[10px] text-warning`,children:[s(`system.notificationTestPanel.requiresTargetConfig`,`Requires target config:`),` `,e.requires.join(`, `)]})]}):null})()]}),i(`div`,{children:[i(`label`,{className:Rm,children:[s(`system.notificationTestPanel.priorityOrdinal`,`Priority (ordinal):`),` `,p.priority]}),d(`input`,{type:`range`,min:1,max:5,step:1,value:p.priority,onChange:e=>b({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":s(`system.notificationTestPanel.priority`)})]})]}),l.formats.length>0&&i(`div`,{children:[d(`label`,{className:Rm,children:s(`system.notificationTestPanel.format`,`Format`)}),d(`div`,{className:`flex flex-wrap gap-2`,children:l.formats.map(e=>i(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:p.format===e,onChange:()=>b({format:e})}),e]},e))})]}),i(`div`,{children:[d(`label`,{className:Rm,children:s(`system.notificationTestPanel.testTitle`,`Title`)}),d(`input`,{className:Lm,value:p.title,onChange:e=>b({title:e.target.value})})]}),i(`div`,{children:[i(`label`,{className:Rm,children:[s(`system.notificationTestPanel.body`),` `,i(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,l.bodyMaxLen,y?` — ${s(`system.notificationTestPanel.overflow`)}`:``,`)`]})]}),d(`textarea`,{className:`${Lm} min-h-[80px] resize-y`,value:p.body,onChange:e=>b({body:e.target.value})})]}),l.attachmentSlots.length>0&&i(`div`,{children:[i(`label`,{className:Rm,children:[s(`system.notificationTestPanel.attachments`),` `,d(`span`,{className:`text-foreground-subtle`,children:l.attachmentMaxBytes?s(`system.notificationTestPanel.attachmentsMetaMb`,{mode:l.attachmentMode,max:l.attachmentMax,mb:Math.round(l.attachmentMaxBytes/1024/1024)}):s(`system.notificationTestPanel.attachmentsMeta`,{mode:l.attachmentMode,max:l.attachmentMax})})]}),d(`div`,{className:`space-y-1.5`,children:l.attachmentSlots.map(e=>i(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),d(`input`,{className:Lm,placeholder:s(`system.notificationTestPanel.url`,`{{mt}} URL`,{mt:e}),value:p.attachmentUrls[e]??``,onChange:t=>b({attachmentUrls:{...p.attachmentUrls,[e]:t.target.value}})})]},e))})]}),l.showActions&&i(`div`,{children:[d(`label`,{className:Rm,children:s(`system.notificationTestPanel.actionsUpTo`,{max:l.maxActions})}),d(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(l.maxActions,3)},(e,t)=>i(`div`,{className:`flex items-center gap-2`,children:[d(`input`,{className:Lm,placeholder:s(`system.notificationTestPanel.actionLabelPlaceholder`),value:p.actions[t]?.label??``,onChange:e=>C(t,`label`,e.target.value)}),d(`input`,{className:Lm,placeholder:s(`system.notificationTestPanel.actionUrlPlaceholder`),value:p.actions[t]?.url??``,onChange:e=>C(t,`url`,e.target.value)})]},t))})]}),i(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[l.showClickUrl&&i(`div`,{children:[d(`label`,{className:Rm,children:s(`system.notificationTestPanel.clickUrl`,`Click URL`)}),d(`input`,{className:Lm,value:p.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),l.showSound&&i(`div`,{children:[d(`label`,{className:Rm,children:s(`system.notificationTestPanel.sound`,`Sound`)}),d(`input`,{className:Lm,value:p.sound,onChange:e=>b({sound:e.target.value})})]}),l.showTtl&&i(`div`,{children:[d(`label`,{className:Rm,children:s(`system.notificationTestPanel.ttlSeconds`,`TTL (seconds)`)}),d(`input`,{className:Lm,type:`number`,value:p.ttl,onChange:e=>b({ttl:e.target.value})})]}),l.showTag&&i(`div`,{children:[d(`label`,{className:Rm,children:s(`system.notificationTestPanel.tag`,`Tag`)}),d(`input`,{className:Lm,value:p.tag,onChange:e=>b({tag:e.target.value})})]})]}),h&&d(Bm,{result:h}),i(`details`,{className:`text-[10px]`,children:[d(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:s(`system.notificationTestPanel.payloadPreview`,`Payload preview`)}),d(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),i(yt,{children:[d(U,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:s(`common.close`,`Close`)}),i(U,{size:`sm`,type:`button`,disabled:x.isPending||p.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?d(T,{className:`h-3.5 w-3.5 animate-spin`}):d(Ge,{className:`h-3.5 w-3.5`}),s(`system.notificationTestPanel.sendTest`,`Send test`)]})]})]})})}function Bm({result:e}){let{t}=J(),n=e.renderedAs;return i(`div`,{className:`rounded-md border px-3 py-2 text-xs ${e.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[i(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?d(C,{className:`h-3.5 w-3.5 text-success`}):d(x,{className:`h-3.5 w-3.5 text-danger`}),d(`span`,{children:e.success?t(`system.notificationTestPanel.delivered`,`Delivered`):t(`system.notificationTestPanel.failed`,`Failed`)})]}),e.error&&d(`p`,{className:`mt-1 text-danger`,children:e.error}),n&&i(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[d(`dt`,{children:t(`system.notificationTestPanel.resolvedLevel`,`Resolved level`)}),d(`dd`,{className:`text-foreground`,children:n.level}),d(`dt`,{children:t(`system.notificationTestPanel.formatSent`,`Format sent`)}),d(`dd`,{className:`text-foreground`,children:n.format}),d(`dt`,{children:t(`system.notificationTestPanel.attachmentsSent`,`Attachments sent`)}),d(`dd`,{className:`text-foreground`,children:n.attachmentsSent}),d(`dt`,{children:t(`system.notificationTestPanel.actionsSent`,`Actions sent`)}),d(`dd`,{className:`text-foreground`,children:n.actionsSent}),d(`dt`,{children:t(`system.notificationTestPanel.truncated`,`Truncated`)}),d(`dd`,{className:`text-foreground`,children:n.truncated?t(`common.yes`):t(`common.no`)}),d(`dt`,{children:t(`system.notificationTestPanel.dropped`,`Dropped`)}),d(`dd`,{className:`text-foreground`,children:n.dropped.length>0?n.dropped.join(`, `):`—`})]})]})}function Vm(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.addonId);e?e.push(r):(n.set(r.addonId,[r]),t.push(r.addonId))}return t.map(e=>({addonId:e,kinds:n.get(e)??[]}))}function Hm(e){let t=[],n=e=>{for(let r of e){if(r.type===`password`){t.push(r.key);continue}if(r.type===`group`){n(r.fields);continue}if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields)}};for(let t of e.sections)n(t.fields);return t}function Um(e){let t=new Map,n=e=>{for(let r of e)if(r.type===`group`)n(r.fields);else if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields);else r.type!==`separator`&&t.set(r.key,r.label)};for(let t of e.sections)n(t.fields);return t}var Wm=`••••••••`;function Gm(e){return e===`••••••••`||e===`__redacted__`}function Km(e,t,n){let r=new Set(n),i={};for(let[t,n]of Object.entries(e)){if(!r.has(t)){i[t]=n;continue}n==null||n===``||Gm(n)||(i[t]=n)}return i}function qm(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e)){if(!n.has(t)){r[t]=i;continue}r[t]=i!=null&&i!==``?Wm:``}return r}function Jm(e){return{...e}}var Ym=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function Xm(e){return Ym.some(t=>e.includes(t))}function Zm(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function Qm(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&Zm(e[n])!==Zm(t[n]))}function $m(e,t,n,r){if(r===void 0)return Qm(e,t,n);let i=new Set(n),a=Km(e,t,n);return r.filter(n=>i.has(n)?n in a:Zm(e[n])!==Zm(t[n]))}function eh(e,t,n){let r=Km(e,t,n);return n.filter(e=>!(e in r))}function th(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:th(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:th(e.fields,t)}))}:e)}function nh(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:th(e.fields,n)}))}}function rh(e){let t=e.trim();return t.length===0?q.t(`common.copy`):q.t(`helpers.notificationTargets.copyOf`,{name:t})}function ih(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,placeholder:e.placeholder??q.t(`helpers.notificationTargets.keepSecret`)}:e.type===`group`?{...e,fields:ih(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:ih(e.fields,t)}))}:e)}function ah(e,t,n){let r=new Set(n.filter(e=>{let n=t[e];return n!=null&&n!==``}));return r.size===0?e:{...e,sections:e.sections.map(e=>({...e,fields:ih(e.fields,r)}))}}var oh=`target`,sh=`kind`,ch=[oh,sh];function lh({refusal:e,edited:t,reenter:n}){let{t:r}=J(),a=n.length>0?`Re-type: ${n.join(`, `)}.`:null;return e===null?t.length===0||a===null?null:d(`p`,{className:`text-[11px] text-warning`,"data-testid":`target-secret-reenter`,children:r(`system.targetSecretNotice.changed`,{fields:t.join(`, `),toType:a})}):i(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-secret-refusal`,role:`alert`,children:[d(`p`,{className:`font-semibold`,children:r(`system.targetSecretNotice.theHubNeedsTheSecret`,`The hub needs the secret again — nothing was saved.`)}),d(`p`,{className:`mt-1`,children:e}),a===null?null:d(`p`,{className:`mt-1 font-medium`,children:a})]})}e();var uh=[`notificationOutput`,`listTargets`],dh=[`notificationOutput`,`listTargetKinds`],fh=[`userManagement`,`listUsers`],ph=`ownerUserId`;function mh(e){let t=e.config[ph];return typeof t==`string`&&t.length>0?t:null}function hh(e){return[{key:`name`,header:q.t(`system.notificationTargets.target`,`Target`),render:t=>{let n=e.kindByKey.get(t.kind);return i(`span`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:n?.label??t.kind,children:d(gh,{kind:n,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),d(rf,{name:t.name,enabled:t.enabled,...n===void 0?{}:{onOpen:()=>e.onOpen(t,n)}})]})}},{key:`kind`,header:q.t(`system.notificationTargets.kind`,`Kind`),nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByKey.get(t.kind)?.label??t.kind})},{key:`owner`,header:q.t(`system.notificationTargets.owner`,`Owner`),nowrap:!0,render:t=>{let n=mh(t);return n===null?d(G,{variant:`default`,children:q.t(`common.systemWord`)}):d(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:q.t(`system.notificationTargets.on`,`On`),align:`center`,nowrap:!0,render:t=>d($d,{children:d(et,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":q.t(`system.notificationTargets.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let n=e.kindByKey.get(t.kind);return i($d,{className:`flex items-center justify-end gap-1`,children:[d(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>e.onTest(t),title:q.t(`system.notificationTargets.test`,`Test`),children:d(Ge,{className:`h-3.5 w-3.5`})}),d(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>n&&e.onDuplicate(t,n),title:q.t(`system.notificationTargets.duplicate`,`Duplicate`),children:d(v,{className:`h-3.5 w-3.5`})}),d(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:q.t(`common.delete`,`Delete`),children:d(p,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function gh({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?d(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):d(`span`,{className:n,children:e?.icon??`🔔`})}function _h({createRequested:e=!1,onCreateConsumed:o,headerOwnsCreate:s=!1}={}){let{t:c}=J(),f=E(),{state:p,openEdit:h,close:g}=gt({editKey:`target`}),[_,v]=Ot(sh),[y,b]=r({mode:`closed`}),[x,C]=r(null),w=l(null),T=a({queryKey:uh,queryFn:()=>f.trpcClient.notificationOutput.listTargets.query({})}),D=a({queryKey:dh,queryFn:async()=>(await f.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),O=n(()=>D.data??[],[D.data]),k=n(()=>{let e=new Map;for(let t of O)e.set(t.kind,t);return e},[O]),A=a({queryKey:fh,queryFn:()=>f.trpcClient.userManagement.listUsers.query()}),j=n(()=>{let e=new Map;for(let t of A.data??[])e.set(t.id,t.username);return e},[A.data]),M=u({mutationFn:e=>f.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:e.target.addonId,targetId:e.target.id,enabled:e.enabled}),onSuccess:()=>void T.refetch()}),N=u({mutationFn:e=>f.trpcClient.notificationOutput.deleteTarget.mutate({addonId:e.addonId,targetId:e.id}),onSuccess:()=>void T.refetch()}),P=x?k.get(x.kind):void 0,F=()=>{p.mode===`edit`&&(w.current=p.id),b({mode:`closed`}),g(),v(null)},I=()=>{w.current=`new`,b({mode:`pick-kind`}),h(`new`),v(null)};t(()=>{e&&(I(),o?.())},[e]);let ee=e=>{w.current=`new:${e.kind}`,b({mode:`form`,kind:e,target:null,cloneFrom:null}),h(`new`),v(e.kind)},te=(e,t)=>{w.current=e.id,b({mode:`form`,kind:t,target:e,cloneFrom:null}),h(e.id),v(null)};return t(()=>{if(y.mode!==`closed`)return;if(p.mode!==`edit`){p.mode===`closed`&&(w.current=null);return}let e=p.id;if(w.current===e)return;if(e===`new`){if(_===null||_.length===0){w.current=`new`,b({mode:`pick-kind`});return}let e=k.get(_);if(e===void 0)return;w.current=`new:${_}`,b({mode:`form`,kind:e,target:null,cloneFrom:null});return}let t=T.data?.find(t=>t.id===e);if(t===void 0)return;let n=k.get(t.kind);n!==void 0&&(w.current=e,b({mode:`form`,kind:n,target:t,cloneFrom:null}))},[y.mode,p,_,T.data,k]),i(ai,{embedded:!0,icon:m,title:c(`system.notificationTargets.notificationTargets`,`Notification Targets`),subtitle:c(`system.notificationTargets.deliverNotificationsToNtfyPushover`,`Deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more. Each target's kind declares its capabilities; the test panel shows exactly what a message degrades to.`),children:[s?null:d(`div`,{className:`mb-3 flex justify-end`,children:i(U,{size:`sm`,type:`button`,onClick:I,children:[d(S,{className:`h-3.5 w-3.5`}),c(`system.notificationTargets.addTarget`,`Add target`)]})}),T.isLoading&&d(ef,{}),T.isError&&!T.isLoading&&d(H,{title:c(`system.notificationTargets.failedToLoadTargets`,`Failed to load targets`),message:T.error instanceof Error?T.error.message:c(`system.notificationTargets.unknownError`,`Unknown error`),onRetry:()=>void T.refetch()}),!T.isLoading&&!T.isError&&(T.data??[]).length===0&&d(tf,{children:c(`system.notificationTargets.noNotificationTargetsYetClick`,`No notification targets yet. Click "Add target" to configure one.`)}),(T.data??[]).length>0&&d(nf,{columns:hh({kindByKey:k,userNameById:j,onToggle:(e,t)=>M.mutate({target:e,enabled:t}),onTest:C,onOpen:te,onDuplicate:(e,t)=>{w.current=`new:${t.kind}`,b({mode:`form`,kind:t,target:null,cloneFrom:e}),h(`new`),v(t.kind)},onDelete:e=>N.mutate(e)}),rows:T.data??[],rowKey:e=>e.id,minWidthPx:720,onRowClick:e=>{let t=k.get(e.kind);t!==void 0&&te(e,t)}}),y.mode===`pick-kind`&&d(vh,{kinds:O,onCancel:F,onPick:ee}),y.mode===`form`&&d(yh,{kind:y.kind,target:y.target,cloneFrom:y.cloneFrom,users:A.data??[],onCancel:F,onSaved:()=>{F(),T.refetch()}},y.target?.id??(y.cloneFrom===null?`new:${y.kind.kind}`:`dup:${y.cloneFrom.id}`)),x&&P&&d(zm,{target:x,kind:P,open:!0,onClose:()=>C(null)})]})}function vh({kinds:e,onPick:t,onCancel:r}){let{t:a}=J(),o=n(()=>Vm(e),[e]);return d(Ct,{open:!0,onClose:r,title:a(`system.notificationTargets.chooseANotificationKind`,`Choose a notification kind`),width:`lg`,children:i(`div`,{className:`space-y-4`,children:[o.length===0&&d(`p`,{className:`text-xs text-foreground-subtle`,children:a(`system.notificationTargets.noNotificationProvidersAreInstalled`,`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`)}),o.map(e=>i(`div`,{children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),d(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(n=>i(`button`,{type:`button`,onClick:()=>t(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[d(gh,{kind:n,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),d(`span`,{className:`font-medium text-foreground`,children:n.label})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})})}function yh({kind:e,target:a,cloneFrom:s,users:c,onSaved:l,onCancel:f}){let{t:p}=J(),h=E(),g=n(()=>Hm(e.configSchema),[e.configSchema]),_=a??s,v=a?.id??s?.id,[y,b]=r(()=>s===null?a?.name??e.label:rh(s.name)),[x,S]=r(()=>_?.config??{}),[C,w]=r(()=>_?qm(_.config,g):{}),[D,O]=r(v===void 0),[k,A]=r(null),[j,M]=r(null),[N,P]=r(_?mh(_)??``:``);t(()=>{if(v===void 0)return;let t=!1;return h.trpcClient.notificationOutput.getTarget.query({addonId:e.addonId,targetId:v}).then(e=>{if(t)return;let n=Jm(e.config);S(n),w(n),P(mh(e)??``),O(!0)}).catch(e=>{t||(A(e instanceof Error?e.message:`Failed to load target secrets`),O(!0))}),()=>{t=!0}},[v,e.addonId,h.trpcClient]);let F=()=>Km(C,x,g),[I,ee]=r(null),te=e.kind===`whatsapp`,L=u({mutationFn:()=>h.trpcClient.notificationOutput.probeTargetConfig.mutate({addonId:e.addonId,kind:e.kind,config:F(),...v===void 0?{}:{targetId:v}}),onSuccess:e=>ee(e),onError:e=>{ee(null),A(e instanceof Error?e.message:`Connection test failed`)}}),ne=u({mutationFn:()=>{let{[ph]:t,...n}=Km(C,x,g),r=N===``?n:{...n,[ph]:N},i={id:a?.id??`${e.kind}-${Date.now()}`,name:y,kind:e.kind,addonId:e.addonId,enabled:a?.enabled??!0,config:r};return h.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:i,...s===null?{}:{cloneSecretsFrom:s.id}})},onSuccess:l,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;Xm(t)?M(t):A(t)}}),R=n(()=>Um(e.configSchema),[e.configSchema]),re=n(()=>v===void 0?[]:$m(C,x,g,e.destinationKeys),[v,C,x,g,e.destinationKeys]),ie=n(()=>v!==void 0&&(j!==null||re.length>0)?eh(C,x,g):[],[v,j,re,C,x,g]),z=n(()=>ah(nh(e.configSchema,ie),x,g),[e.configSchema,ie,x,g]),ae=e=>R.get(e)??e;return d(Ct,{open:!0,onClose:f,title:a?`Edit ${a.name}`:s?`Duplicate ${s.name}`:`Add ${e.label} target`,icon:m,width:`lg`,testId:`target-form-dialog`,beforeBody:i(o,{children:[k!=null&&k!==``&&d(`div`,{className:`mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-form-error`,children:k}),i(`div`,{className:`mb-3 flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(gh,{kind:e,imgClassName:`h-5 w-5 object-contain shrink-0`,fallbackClassName:`text-lg leading-5`}),d(`span`,{children:e.label})]})]}),footer:i(U,{size:`sm`,type:`button`,disabled:ne.isPending||!D||y.trim().length===0,onClick:()=>{A(null),M(null),ne.mutate()},children:[ne.isPending||!D?d(T,{className:`h-3.5 w-3.5 animate-spin`}):null,a?p(`system.notificationTargets.saveChanges`,`Save changes`):p(`system.notificationTargets.createTarget`,`Create target`)]}),children:i(`div`,{className:`space-y-4`,children:[i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:p(`system.notificationTargets.name`,`Name`)}),d(`input`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,value:y,onChange:e=>b(e.target.value)})]}),i(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:p(`system.notificationTargets.owner`,`Owner`)}),d(V,{value:N,options:[{value:``,label:p(`system.notificationTargets.systemSharedAdminManaged`,`System (shared, admin-managed)`)},...c.map(e=>({value:e.id,label:e.username}))],onChange:e=>P(e.target.value)}),d(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:p(`system.notificationTargets.aUserOwnedTargetBelongs`,`A user-owned target belongs to that user: it shows in their viewer and their own rules may deliver to it. System targets stay admin-managed.`)})]}),g.length>0&&v!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:p(`system.notificationTargets.storedSecretsLoadIntoThe`,`Stored secrets load into the masked fields (eye to reveal). Clear a field to leave the stored value unchanged on save; type a new value to replace it.`)}),d(lh,{refusal:j,edited:re.map(ae),reenter:ie.map(ae)}),d(Et,{schema:z,values:C,onChange:w}),te&&i(`div`,{className:`space-y-2`,children:[i(U,{size:`sm`,variant:`outline`,type:`button`,disabled:L.isPending,onClick:()=>{A(null),ee(null),L.mutate()},children:[L.isPending?d(T,{className:`h-3.5 w-3.5 animate-spin`}):d(Ge,{className:`h-3.5 w-3.5`}),p(`system.notificationTargets.testConnection`,`Test connection`)]}),I!==null&&i(`p`,{className:I.ok?`text-[11px] text-success`:`text-[11px] text-danger`,"data-testid":`target-probe-result`,children:[I.ok?p(`system.notificationTargets.connected`,`Connected — {{value1}}`,{value1:I.stateInstance??`authorized`}):I.error??p(`system.notificationTargets.connectionFailed`,`Connection failed`),I.resolvedUrl.length>0?` · ${I.resolvedUrl}`:``]})]})]})})}e();var bh=`notificationTexts`,xh=`Every sentence the Notification Center can print — and your wording for it.`;function Sh({entry:e,value:t,busy:n,onChange:r,onReset:a}){let{t:o}=J(),s=Bl(e),c=e.override!==null;return i(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${e.key}`,"data-source":e.source,children:[i(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[d(`code`,{className:`text-xs font-medium`,children:e.key}),c?d(G,{variant:`info`,children:o(`common.customised`)}):null,e.source===`fallback`?d(G,{variant:`warning`,children:o(`system.notificationTexts.englishFallback`,`English fallback`)}):null]}),i(`div`,{className:`flex items-start gap-2`,children:[d(`div`,{className:`flex-1`,children:d(Eo,{label:``,value:t,onChange:r,vars:zl(e),disabled:n,testId:`text-input-${e.key}`})}),d(U,{variant:`ghost`,size:`sm`,disabled:n||!c&&t===e.shipped,onClick:a,title:o(`system.notificationTexts.resetToTheShippedWording`,`Reset to the shipped wording`),"data-testid":`text-reset-${e.key}`,children:d(A,{className:`h-3.5 w-3.5`})})]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:[d(`span`,{className:`font-medium`,children:o(`system.notificationTexts.shipped`,`Shipped:`)}),` `,d(`span`,{className:`font-mono`,children:e.shipped})]}),s===null?null:d(`p`,{className:`text-xs text-warning`,children:s})]})}function Ch(){let{t:e}=J(),t=E(),o=s(),[c,l]=r(null),[f,p]=r(``),[m,h]=r(new Map),[g,_]=r(!1),v=a({queryKey:[bh,c??`hub`],queryFn:async()=>{let e=Pl(await t.trpcClient.addons.custom.mutate({addonId:$,action:Tl,input:c===null?{}:{language:c}}));return _(e===null),e}}),y=()=>{h(new Map),o.invalidateQueries({queryKey:[bh]})},x=u({mutationFn:e=>t.trpcClient.addons.custom.mutate({addonId:$,action:El,input:{language:e}}),onSuccess:y}),S=u({mutationFn:e=>t.trpcClient.addons.custom.mutate({addonId:$,action:Dl,input:e}),onSuccess:y}),C=v.data??null,w=n(()=>C===null?[]:Rl(C.entries,f),[C,f]);if(v.isLoading)return d(ai,{embedded:!0,icon:Ke,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:xh,children:d(T,{className:`h-5 w-5 animate-spin`})});if(v.isError||C===null)return d(ai,{embedded:!0,icon:Ke,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:xh,children:d(H,{title:e(`system.notificationTexts.theNotificationTextCatalogIs`,`The notification text catalog is not available on this hub`),message:g?e(`system.notificationTexts.theHubAnsweredSomethingThis`,`The hub answered something this admin build does not understand. Update both and reload.`):e(`system.notificationTexts.thisHubHasNotBeen`,`This hub has not been updated to serve the notification text catalog yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime: notifications keep using the shipped wording.`)})});let D=C.language,O=x.isPending||S.isPending,k=Il(C.entries,m),A=Ll(C.entries,m),j=C.entries.filter(e=>e.override!==null).length,M=C.languages.map(e=>({value:e,label:Ol[e]})),N=(e,t)=>h(n=>new Map(n).set(e,t)),P=e=>N(e.key,e.shipped);return d(ai,{embedded:!0,icon:Ke,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:xh,children:i(`div`,{className:`flex flex-col gap-4`,children:[x.isError?d(H,{title:e(`system.notificationTexts.couldNotChangeTheLanguage`,`Could not change the language`),message:String(x.error)}):null,S.isError?d(H,{title:e(`system.notificationTexts.couldNotSave`,`Could not save`),message:String(S.error)}):null,i(pt,{className:`p-4`,children:[i(`div`,{className:`flex flex-wrap items-end gap-6`,children:[i(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:e(`system.notificationTexts.hubLanguage`,`Hub language`)}),d(`div`,{className:`w-44`,children:d(V,{value:C.activeLanguage,disabled:O,options:M,onChange:e=>{let t=e.target.value;kl(t)&&x.mutate(t)},"data-testid":`texts-hub-language`})}),d(`p`,{className:`text-xs text-foreground-subtle`,children:e(`system.notificationTexts.everyNotificationIsWrittenIn`,`Every notification is written in this language.`)})]}),i(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:e(`system.notificationTexts.editing`,`Editing`)}),d(`div`,{className:`w-44`,children:d(V,{value:D,disabled:O,options:M,onChange:e=>{let t=e.target.value;kl(t)&&(h(new Map),l(t))},"data-testid":`texts-editing-language`})}),d(`p`,{className:`text-xs text-foreground-subtle`,children:D===C.activeLanguage?e(`system.notificationTexts.ofTextsCustomised`,`{{overriddenCount}} of {{length}} texts customised.`,{overriddenCount:j,length:C.entries.length}):e(`system.notificationTexts.thisHubDoesNotSpeak`,`This hub does not speak this language — these words are not in use yet.`)})]})]}),d(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:e(`system.notificationTexts.aRuleThatWritesIts`,`A rule that writes its own title or body still overrides everything here — this page is the wording used when a rule does not.`)})]}),i(`div`,{className:`flex flex-wrap items-center gap-3`,children:[i(`div`,{className:`relative min-w-[12rem] flex-1`,children:[d(b,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),d(W,{value:f,placeholder:e(`system.notificationTexts.searchAKeyOrA`,`Search a key or a sentence…`),onChange:e=>p(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),i(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[w.length,` of `,C.entries.length]}),i(U,{className:`ml-auto`,disabled:O||A===0,onClick:()=>S.mutate({language:D,overrides:k}),"data-testid":`texts-save`,children:[O?d(T,{className:`h-3.5 w-3.5 animate-spin`}):null,A===0?e(`common.save`,`Save`):e(`system.notificationTexts.save`,`Save {{pending}}`,{pending:A})]})]}),d(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?d(`p`,{className:`text-sm text-foreground-subtle`,children:e(`system.notificationTexts.noTextMatchesThatSearch`,`No text matches that search.`)}):w.map(e=>d(Sh,{entry:e,value:Fl(e,m),busy:O,onChange:t=>N(e.key,t),onReset:()=>P(e)},e.key))})]})})}e();var wh=`simulate`,Th=`rules`,Eh=new Set([`targets`,Th,`sequences`]);function Dh(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function Oh(e,t,n){if(e===`mixed`)return;if(e===`all`)return i(U,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:t,children:[d(S,{className:`h-3.5 w-3.5`}),q.t(`systemPage.notifications.newRule`,`New rule`)]});if(vf(e)){let t=bf(e),r=Dh(e);return r===null?void 0:i(U,{size:`sm`,type:`button`,onClick:()=>n(r),"data-testid":e===`summaries`?`summary-new`:e===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[d(S,{className:`h-3.5 w-3.5`}),t.newLabel]})}let r=ar.find(t=>t.key===e);if(!(r===void 0||!r.creatable))return i(U,{size:`sm`,type:`button`,onClick:()=>n(e),"data-testid":`rules-new-${e}`,children:[d(S,{className:`h-3.5 w-3.5`}),r.newRuleLabel]})}function kh(){let{t:e}=J(),[n,a]=Tr(),[o,s]=r(!1),[c,l]=r(null);t(()=>{let e=n.get(`tab`);if(e===null||!vf(e))return;let t=new URLSearchParams(n);t.set(`tab`,Th),t.set(`section`,e),a(t,{replace:!0})},[n,a]);let u=n.get(`tab`)??`targets`,[f]=Ot(`section`),p=yf(f)??`all`,h=e=>{Zp(Yp(e));let t=new URLSearchParams(n);t.set(`tab`,wh),a(t,{replace:!0})},g=e=>{a(qa(n,e.id),{replace:!0})},_=Yr(`/system/notifications`,{t:e,isAdmin:!0})??{icon:m,title:e(`system.notifications`,`Notifications`)},v=()=>s(!1),y=(()=>{if(u===`targets`)return i(U,{size:`sm`,type:`button`,"data-testid":`notifications-add-target`,onClick:()=>s(!0),children:[d(S,{className:`h-3.5 w-3.5`}),e(`systemPage.notifications.addTarget`,`Add target`)]});if(u===`sequences`)return i(U,{size:`sm`,type:`button`,"data-testid":`notifications-add-sequence`,onClick:()=>s(!0),children:[d(S,{className:`h-3.5 w-3.5`}),e(`systemPage.notifications.newSequence`,`New sequence`)]});if(u===Th)return Oh(p,()=>s(!0),e=>l(e))})();return t(()=>{Eh.has(u)||(s(!1),l(null))},[u]),d(ri,{icon:_.icon,title:_.title,defaultSection:`targets`,sectionsLabel:`${_.title} sections`,actions:y,sections:[{id:`targets`,label:e(`systemPage.notifications.targets`,`Targets`),content:d(_h,{headerOwnsCreate:!0,createRequested:u===`targets`&&o,onCreateConsumed:v}),ownedParams:ch},{id:Th,label:e(`systemPage.notifications.rules`,`Rules`),content:d(dp,{onSimulateRule:h,onOpenHistory:g,headerOwnsCreate:!0,createRequested:u===Th&&o,onCreateConsumed:v,createTypeRequested:u===Th?c:null,onCreateTypeConsumed:()=>l(null)}),ownedParams:[`section`,`rule`,`editTab`]},{id:`sequences`,label:e(`systemPage.notifications.sequences`,`Sequences`),content:d(Dp,{headerOwnsCreate:!0,createRequested:u===`sequences`&&o,onCreateConsumed:v}),ownedParams:bp},{id:wh,label:e(`systemPage.notifications.simulate`,`Simulate`),content:d(xm,{})},{id:Va,label:e(`systemPage.notifications.history`,`History`),content:d(io,{}),ownedParams:Ua},{id:`alarm`,label:e(`systemPage.notifications.alarm`,`Alarm`),content:d(Ba,{})},{id:`texts`,label:e(`systemPage.notifications.texts`,`Texts`),content:d(Ch,{})},{id:`settings`,label:e(`systemPage.notifications.settings`,`Settings`),content:d(Ap,{})}]})}export{kh as NotificationsPage,kh as default};