@camstack/addon-admin-ui 1.2.720 → 1.2.721

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 (90) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/assets/{AccessSection-DLcqIdIE.js → AccessSection-BpjpAjNz.js} +1 -1
  3. package/dist/assets/{Addons-Cqy437m_.js → Addons-DQmt0Ooo.js} +3 -3
  4. package/dist/assets/{AdminPage-B8wrcNpW.js → AdminPage-hTuLnd-r.js} +1 -1
  5. package/dist/assets/{AdminSectionedPage-BshPvazW.js → AdminSectionedPage-I8w-RKOX.js} +1 -1
  6. package/dist/assets/{AiProfiles-Bcs-HN_u.js → AiProfiles-D5mox51D.js} +1 -1
  7. package/dist/assets/{Archive-Dg-8ZFEk.js → Archive-BybXwp2U.js} +1 -1
  8. package/dist/assets/{BootstrapSettingsForm-DrZ2Qxpr.js → BootstrapSettingsForm-CkIVFPS4.js} +1 -1
  9. package/dist/assets/{Build-DCEyOlh3.js → Build-BOFfr0LN.js} +4 -4
  10. package/dist/assets/{Calendars-CLOqo_A9.js → Calendars-Bq5DGcQP.js} +1 -1
  11. package/dist/assets/{Cluster-CWjdu2SA.js → Cluster-BK2TpQRr.js} +1 -1
  12. package/dist/assets/{CompositionBlockEditor-BcAg9cd1.js → CompositionBlockEditor-H-8a3aI3.js} +2 -2
  13. package/dist/assets/CompositionEditorPage-BIlL1yWk.js +1 -0
  14. package/dist/assets/{Data-CjK1CJ6a.js → Data-XeR9O62q.js} +2 -2
  15. package/dist/assets/{DeviceDetail-9JbRREF0.js → DeviceDetail-DMMfhhXg.js} +1 -1
  16. package/dist/assets/{Devices-Khov-G-p.js → Devices-BOAjqM3g.js} +1 -1
  17. package/dist/assets/{EmbedDevicePage-BEgkFa13.js → EmbedDevicePage-NNQC9LT5.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-yq9ib_WG.js → EmbedPlayerPage-DbTrlaxs.js} +1 -1
  19. package/dist/assets/{History-BDzN5PSp.js → History-YHrViKWf.js} +1 -1
  20. package/dist/assets/{Identity-CQaHQdfp.js → Identity-CvICMopq.js} +1 -1
  21. package/dist/assets/InstancesTable-BbiLAMar.js +1 -0
  22. package/dist/assets/{IntegrationDetail-H5iG4cp4.js → IntegrationDetail-DezaWr05.js} +1 -1
  23. package/dist/assets/{Integrations-CIQ1TTLm.js → Integrations-Bu1l2IAE.js} +1 -1
  24. package/dist/assets/{Integrations-JSq4q6Yk.js → Integrations-GQeBWUAG.js} +1 -1
  25. package/dist/assets/{Library-D4AldvQF.js → Library-Bll-Ei-R.js} +1 -1
  26. package/dist/assets/{Locations-DWOOuQIu.js → Locations-Dll9bnKr.js} +2 -2
  27. package/dist/assets/{Logs-5nXs4_ea.js → Logs-C4pDJHbc.js} +1 -1
  28. package/dist/assets/{MaskShapeCanvas-BuhGkMAd.js → MaskShapeCanvas-Djh-gUZ_.js} +1 -1
  29. package/dist/assets/{MotionZonesSettings-taxdtueq.js → MotionZonesSettings-DsnJDcer.js} +1 -1
  30. package/dist/assets/{MyAccess-HwIUJzaA.js → MyAccess-BtJtrLzk.js} +1 -1
  31. package/dist/assets/{Network-B75AEe4T.js → Network-CJ_p4GzA.js} +1 -1
  32. package/dist/assets/{NewExportModal-4pbJXUN7.js → NewExportModal-36tmSMNC.js} +1 -1
  33. package/dist/assets/{NodeAddonsSettingsPanel-BWKFONDO.js → NodeAddonsSettingsPanel-CQZlw_J4.js} +1 -1
  34. package/dist/assets/Notifications-BSy66Xaa.js +1 -0
  35. package/dist/assets/{PanelContent-CjTOcp45.js → PanelContent-BAG_QFjr.js} +1 -1
  36. package/dist/assets/{Pipeline-dzujvaiX.js → Pipeline-DgZVwbXe.js} +1 -1
  37. package/dist/assets/{PrivacyMaskSettings-CUn9ND-1.js → PrivacyMaskSettings-Dczm79Oa.js} +1 -1
  38. package/dist/assets/{SceneMonitorEditor-BmIPmhsF.js → SceneMonitorEditor-BAVUmKgL.js} +1 -1
  39. package/dist/assets/{SessionsList-BJMw8pbD.js → SessionsList-BhmGfCn7.js} +1 -1
  40. package/dist/assets/{Showroom-oEYjHOaZ.js → Showroom-DoFluNdO.js} +1 -1
  41. package/dist/assets/{StorageLocationsTable-BWV3gXtd.js → StorageLocationsTable-BWMtkuR2.js} +1 -1
  42. package/dist/assets/{System-YDUueTZD.js → System-Dki0JmeO.js} +2 -2
  43. package/dist/assets/{TemplateEditorDialog-BACs8PgY.js → TemplateEditorDialog-CQh8V5sL.js} +1 -1
  44. package/dist/assets/{Terminal-C-szbt5x.js → Terminal-CTlud8bc.js} +1 -1
  45. package/dist/assets/{TrainingProviders-CslXBK7R.js → TrainingProviders-CVU-i8TE.js} +1 -1
  46. package/dist/assets/{Viewer-DjhhF28L.js → Viewer-BGxa_J7i.js} +1 -1
  47. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CPbbpoxt.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BQvHZ6v6.js} +1 -1
  48. package/dist/assets/{ai-page.helpers-DTU60-gO.js → ai-page.helpers-CpBIuIa2.js} +1 -1
  49. package/dist/assets/{assignment-candidates-Su99quoq.js → assignment-candidates-BFMlq0Fq.js} +1 -1
  50. package/dist/assets/{authed-media-D2JT3vve.js → authed-media-Bwbgp7-z.js} +1 -1
  51. package/dist/assets/{board-model-C35BJaTl.js → board-model-Bv-awJc0.js} +1 -1
  52. package/dist/assets/{camera-block-model-D7ROcocN.js → camera-block-model-DOMPFMSg.js} +1 -1
  53. package/dist/assets/{client-CPPa5guW.js → client-BhzNLMP4.js} +38 -38
  54. package/dist/assets/{command-vocab-ByChDwV9.js → command-vocab-D06EMZRc.js} +1 -1
  55. package/dist/assets/{device-integration-icon-CH2i6Msq.js → device-integration-icon-9Jbubm6S.js} +1 -1
  56. package/dist/assets/device-picker-model-BlP9PPlf.js +1 -0
  57. package/dist/assets/{dist-Dhkg8AWn.js → dist-AgmqllWm.js} +1 -1
  58. package/dist/assets/{dist-Bi72cwT_.js → dist-Bfs3greN.js} +8 -8
  59. package/dist/assets/{format-Cr5Z7hEa.js → format-aPBsTncn.js} +1 -1
  60. package/dist/assets/{hostInit-DqW1fxc7.js → hostInit-BUikS_hx.js} +1 -1
  61. package/dist/assets/i18n-BUKFCtSg.js +1 -0
  62. package/dist/assets/{icons-CICuugQ1.js → icons-BhSxe4cn.js} +1 -1
  63. package/dist/assets/index-CAPEivfW.js +6 -0
  64. package/dist/assets/{linked-devices-model-nwfi8vH4.js → linked-devices-model-DqlTf5i1.js} +1 -1
  65. package/dist/assets/{mf-entry-bootstrap-0-6a8a6c87.js → mf-entry-bootstrap-0-645f2f77.js} +2 -2
  66. package/dist/assets/mount-BlP9PPlf.js +1 -0
  67. package/dist/assets/{notification-rule-status-Di4wqTIA.js → notification-rule-status-CYysmU-W.js} +1 -1
  68. package/dist/assets/{player-overlays-Doz3g2Qx.js → player-overlays-1ac_FwhY.js} +1 -1
  69. package/dist/assets/remoteEntry-d0Agt0Jj.js +1 -0
  70. package/dist/assets/{src-DmQ7Cv69.js → src-BlIunjO3.js} +3 -3
  71. package/dist/assets/{sso-popup-B-tqkFkc.js → sso-popup-DJf61Pgc.js} +1 -1
  72. package/dist/assets/{step-inspector-model-BSL8kZ_q.js → step-inspector-model-CetQO3gf.js} +1 -1
  73. package/dist/assets/{use-notification-targets-8N18acum.js → use-notification-targets-ByxpMDkV.js} +1 -1
  74. package/dist/assets/{use-scenes-feed-4hfR1es_.js → use-scenes-feed-3IgjDPxL.js} +1 -1
  75. package/dist/assets/{useAdminDeviceRemoval-Do1Lkxt-.js → useAdminDeviceRemoval-C0Mhda_a.js} +1 -1
  76. package/dist/assets/useEventInvalidation-BlP9PPlf.js +1 -0
  77. package/dist/assets/{useNodeUrlSelection-BsRfsDk3.js → useNodeUrlSelection-DzaZKhUG.js} +1 -1
  78. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-AMUX_sNo.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Br0FnzBD.js} +2 -2
  79. package/dist/index.html +8 -8
  80. package/dist/server/addon.js +18 -1
  81. package/package.json +2 -2
  82. package/dist/assets/CompositionEditorPage-BkISVE7J.js +0 -1
  83. package/dist/assets/InstancesTable-d_ArcJzn.js +0 -1
  84. package/dist/assets/Notifications-Dir45cKh.js +0 -1
  85. package/dist/assets/device-picker-model-DQ7GTxXG.js +0 -1
  86. package/dist/assets/i18n-OcaOH-Ge.js +0 -1
  87. package/dist/assets/index-BzUvVt-V.js +0 -6
  88. package/dist/assets/mount-DQ7GTxXG.js +0 -1
  89. package/dist/assets/remoteEntry-CZJPvesV.js +0 -1
  90. package/dist/assets/useEventInvalidation-DQ7GTxXG.js +0 -1
@@ -0,0 +1 @@
1
+ import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,i as l,o as u,p as d,t as f,x as p}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$r as m,Bn as h,Br as g,Da as _,Jr as v,Ni as y,Oa as b,Pn as x,Q as S,Qi as C,Qt as w,Vn as T,Xn as E,Yn as D,Zn as O,ar as k,b as A,bi as ee,bt as j,co as M,ct as N,ea as P,eo as F,ft as I,gi as te,ka as L,ma as ne,nn as re,no as R,to as z,v as B,y as ie,z as ae}from"./player-overlays-1ac_FwhY.js";import{$ as oe,$t as se,A as ce,B as le,Bt as ue,Ct as de,Dt as fe,F as V,Ft as pe,H as me,I as H,It as he,Lo as ge,Lt as _e,M as ve,Mt as ye,N as be,Pt as xe,Q as Se,Qt as Ce,R as we,Rn as Te,Rt as Ee,U as De,Ut as Oe,X as ke,Xn as Ae,Y as je,Z as Me,_i as Ne,al as Pe,at as Fe,ct as Ie,dt as Le,et as Re,fi as ze,gi as Be,j as Ve,jt as He,kt as Ue,lt as We,nt as Ge,ot as Ke,qt as qe,sc as Je,st as Ye,tt as Xe,vi as Ze,wt as Qe,xc as $e,xt as et}from"./client-BhzNLMP4.js";import{A as tt,I as nt,P as rt,b as it,j as at,y as ot,z as st}from"./__vite-browser-external-DIbVKiho.js";import{t as ct}from"./flask-conical-D7tbJQpj.js";import{n as lt,t as ut}from"./languages-Du_pOBpX.js";import{Aa as dt,Ap as ft,Ba as pt,Ca as mt,Dp as ht,Ea as gt,Ei as _t,Ep as vt,F as yt,Fa as bt,Gi as xt,I as St,Ia as Ct,Ki as wt,La as Tt,M as Et,Ma as U,N as Dt,Na as Ot,Ni as kt,Nn as At,Op as jt,P as Mt,Pa as Nt,Vr as Pt,Xa as Ft,Xi as It,Yi as Lt,Zi as Rt,_i as zt,ci as W,dt as Bt,ec as Vt,g as Ht,h as Ut,hi as G,j as Wt,ja as Gt,kp as K,li as Kt,ns as qt,nt as Jt,oa as Yt,qi as Xt,rt as Zt,si as Qt,ui as $t,v as en,wa as tn,xp as q,xt as nn,zi as rn}from"./src-BlIunjO3.js";import{t as J}from"./i18n-BUKFCtSg.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import"./mount-BlP9PPlf.js";import{$n as an,$r as on,$t as sn,An as cn,Ar as ln,Bn as un,Br as dn,Bt as fn,Ci as pn,Cn as mn,Cr as hn,Dn as gn,Dr as _n,En as vn,Er as yn,Fn as bn,Fr as xn,Gn as Sn,Gr as Cn,Gt as wn,Hn as Tn,Hr as En,Ht as Dn,In as On,Ir as kn,Jn as An,Jr as jn,Jt as Mn,Kn as Nn,Kr as Pn,Kt as Fn,L as In,Ln,Lr as Rn,Mn as zn,Mr as Bn,Nn as Vn,Nr as Hn,On as Un,Or as Wn,Pn as Gn,Pr as Kn,Qn as qn,Qr as Jn,Qt as Yn,Rn as Xn,Rr as Zn,Sn as Qn,Sr as $n,Tn as er,Tr as tr,Un as nr,Ur as rr,Ut as ir,Vn as ar,Vr as or,Vt as sr,Wn as cr,Wr as lr,Wt as ur,Xn as dr,Xr as fr,Xt as pr,Yn as mr,Yr as hr,Yt as gr,Zn as _r,Zr as vr,Zt as yr,_i as br,_n as xr,_r as Sr,ai as Cr,an as wr,ar as Tr,b as Er,bn as Dr,br as Or,ci as kr,cn as Ar,cr as jr,di as Mr,dn as Nr,dr as Pr,ei as Fr,en as Ir,er as Lr,fi as Rr,fn as zr,fr as Br,gn as Vr,gr as Hr,hn as Ur,hr as Wr,ii as Gr,in as Kr,ir as qr,jn as Jr,jr as Yr,kn as Xr,kr as Zr,li as Qr,ln as $r,lr as ei,mi as ti,mn as ni,mr as ri,ni as ii,nn as ai,nr as oi,oi as si,on as ci,or as li,pi as ui,pn as di,pr as fi,qn as pi,qr as mi,qt as X,ri as hi,rn as gi,rr as _i,si as vi,sn as yi,sr as bi,ti as xi,tn as Si,tr as Ci,ui as wi,un as Ti,ur as Ei,vi as Di,vn as Oi,vr as ki,wn as Ai,wr as ji,xn as Mi,xr as Ni,yn as Pi,yr as Fi,zn as Ii,zr as Li}from"./index-CAPEivfW.js";import{t as Ri}from"./AdminSectionedPage-I8w-RKOX.js";import{t as zi}from"./InstancesTable-BbiLAMar.js";import{n as Bi}from"./format-aPBsTncn.js";import{n as Vi,t as Hi}from"./use-notification-targets-ByxpMDkV.js";import"./device-picker-model-BlP9PPlf.js";import{t as Ui}from"./AdminPage-hTuLnd-r.js";import{c as Wi,i as Gi,n as Ki,o as qi,r as Ji,s as Yi,t as Xi}from"./notification-rule-status-CYysmU-W.js";import{t as Zi}from"./use-scenes-feed-3IgjDPxL.js";import{l as Qi,s as $i}from"./ai-page.helpers-CpBIuIa2.js";c();var ea=[`contact`,`cover`,`lock-control`,`switch`];function ta(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 na(e){let t=new Set(ta(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 ra(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function ia(e,t,n=new Map){let r=[...e].map(([e,t])=>({id:e,name:t})),i=e=>{let t=n.get(e)?.trim();return t===void 0||t===``?null:t},a=e=>Tt([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?J.t(`uiLibrary.devicePicker.deviceId`,{id:e}):bt(t,`device`,In))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function aa(e){let t=e.name.trim();return t===``?J.t(`uiLibrary.devicePicker.deviceId`,{id:e.deviceId}):t}function oa(e){return e===0?J.t(`helpers.alarmNonblocking.refusedNoName`):J.t(`helpers.alarmNonblocking.refusedOpen`)}var sa={home:`Home`,away:`Away`,night:`Night`};function ca(e){return sa[e]??e}function la(e,t){if(e<=0)return t;if(e<60)return`${e} s`;let n=Math.floor(e/60),r=e%60;return r===0?J.t(`helpers.notificationAlarm.delayMin`,{minutes:n}):J.t(`helpers.notificationAlarm.delayMinSec`,{minutes:n,seconds:r})}function ua(e,t){if(e.ruleCount===0)return J.t(`helpers.notificationAlarm.armsNothing`);if(e.allDevices&&e.allDevicesExcept.length>0){let n=e.allDevicesExcept.map(t);return J.t(`helpers.notificationAlarm.allExcept`,{count:n.length,names:n.join(`, `)})}return e.allDevices?J.t(`helpers.notificationAlarm.everyDevice`,{count:e.ruleCount}):e.deviceIds.length===0?J.t(`helpers.notificationAlarm.noRestriction`,{count:e.ruleCount}):e.deviceIds.map(t).join(`, `)}function da(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${fa[e.reason]})`);return J.t(`helpers.notificationAlarm.skipped`,{count:e.length,parts:n.join(`, `)})}var fa={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function pa(e){return e.ruleCount===0}function ma(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 ha=2e3,ga=15e3,_a=new Set([`arming`,`pending`,`triggered`]);function va(e){return e!==void 0&&_a.has(e)?ha:ga}var ya={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 ba(e){let t=ya[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${ca(e.targetMode)}`}function xa(e){return e!==`disarmed`}function Sa(e){return e===`open`?J.t(`helpers.notificationAlarm.phaseOpen`):J.t(`helpers.notificationAlarm.phaseClosed`)}function Ca(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function wa(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Ta(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function Ea(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 Da(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 Oa(e,t,n,r){let i=Ea(e,t,n);return r==="default"?i===void 0?null:Da(t,n,null):i===r?null:Da(t,n,r)}function ka(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=Ke(e,t),a=r!==n,o=n!==`doNothing`&&i.triggeredDurationSec===0;return!a&&!o?null:{mode:t,...a?{postTriggeredAction:n}:{},...o?{triggeredDurationSec:30}:{}}}function Aa(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 ja=[`unknown-refusal`,`stale`,`expired`,`used`];function Ma(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Na(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Ma(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 Pa(e){if(!Ma(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Na(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Na(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=ja.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var Fa={"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 Ia(e){return Fa[e]}function La(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 Ra=`pipeline-analytics`,za=`The hub answered something this build cannot read — refresh after updating.`;function Ba(e){return e instanceof Error?e.message:String(e)}function Va(e){return e.map(e=>`${aa(e)} (${e.state})`).join(`, `)}function Ha({live:t,onChanged:n}){let{t:r}=Y(),a=j(),[s,c]=o(null),[l,u]=o(null),[d,p]=o(null),m=(e,t)=>a.trpcClient.addons.custom.mutate({addonId:Ra,action:e,input:t}),h=e=>{if(e===null){u(za);return}if(e.outcome===`refused`){c({refusalId:e.refusalId,blocking:e.blocking});return}if(c(null),e.outcome===`rejected`){u(`Arm anyway was not accepted: ${Ia(e.reason)}.`);return}if(e.outcome===`outside-schedule`){u(`Outside this mode's activation schedule — arm during an allowed window.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;p(e.excluded.length===0?`${t}.`:`${t} — excluded: ${Va(e.excluded)}.`)},_=()=>{u(null),p(null)},v=f({mutationFn:async e=>Pa(await m(`nc.armAlarm`,{mode:e})),onMutate:_,onSuccess:h,onError:e=>u(Ba(e)),onSettled:n}),y=f({mutationFn:async e=>Pa(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:_,onSuccess:h,onError:e=>u(Ba(e)),onSettled:n}),b=f({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{_(),c(null)},onSuccess:()=>p(`Disarmed.`),onError:e=>u(Ba(e)),onSettled:n});if(t===void 0)return e(Yt,{className:`p-4`,children:[i(`h3`,{className:`text-sm font-semibold mb-1`,children:r(`system.alarmLiveCard.panel`,`Panel`)}),i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.alarmLiveCard.thisHubDoesNotReport`,`This hub does not report the panel's live state yet — update it to arm from here.`)})]});let x=v.isPending||y.isPending||b.isPending;return e(Yt,{className:`p-4`,children:[e(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[e(`div`,{children:[i(`h3`,{className:`text-sm font-semibold`,children:r(`system.alarmLiveCard.panel`,`Panel`)}),i(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:ba(t)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[x?i(g,{className:`h-4 w-4 animate-spin`}):null,t.availableModes.map(e=>i(q,{type:`button`,size:`md`,variant:`outline`,disabled:x,onClick:()=>v.mutate(e),"data-testid":`alarm-arm-${e}`,children:r(`system.alarmLiveCard.arm`,{mode:ca(e)})},e)),i(q,{type:`button`,size:`md`,variant:xa(t.state)?`danger`:`secondary`,disabled:x,onClick:()=>b.mutate(),"data-testid":`alarm-disarm`,children:r(`system.alarmLiveCard.disarm`,`Disarm`)})]})]}),l===null?null:i(`div`,{className:`mt-3`,children:i(dt,{title:r(`system.alarmLiveCard.thePanelDidNotDo`,`The panel did not do that`),message:l})}),d===null?null:i(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:d}),s===null?null:e(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[i(`p`,{className:`text-sm font-medium`,children:oa(s.blocking.length)}),s.blocking.length>0?i(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:s.blocking.map(t=>e(`li`,{children:[aa(t),` `,e(`span`,{className:`text-foreground-subtle`,children:[`(`,t.state,`)`]})]},t.deviceId))}):null,e(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[i(q,{type:`button`,size:`md`,variant:`danger`,disabled:x,onClick:()=>y.mutate(s.refusalId),children:r(`system.alarmLiveCard.armAnyway`,`Arm anyway`)}),i(`span`,{className:`text-xs text-foreground-subtle`,children:r(`system.alarmLiveCard.eachOpenDeviceIsIgnored`,`Each open device is ignored until it closes, then monitored again.`)})]})]}),e(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[i(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:r(`system.alarmLiveCard.excludedSensors`,`Excluded sensors`)}),t.exclusions.length===0?i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.alarmLiveCard.noSensorIsExcluded`,`No sensor is excluded.`)}):i(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:t.exclusions.map(t=>e(`li`,{children:[aa(t),` —`,` `,i(`span`,{className:`text-foreground-subtle`,children:Sa(t.phase)})]},t.deviceId))})]})]})}c();var Ua=[{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:ze,zeroMeansKey:`system.alarmDelay.sirenZero`}];function Wa(e){return J.t(`system.alarmDelay.rangeError`,{max:e})}function Ga(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${Wa(t)}`}function Ka({label:t,value:n,max:r,zeroMeans:a,disabled:s,testId:c,hint:l,adornment:u,onCommit:d}){let[f,p]=o(null),[m,h]=o(null),g=f??String(n),_=f!==null&&f.trim()!==``&&ma(f,r)===null,v=la(n,a),y=()=>{let e=f===null?null:ma(f,r);p(null),e===null?f!==null&&h(f):(h(null),d(e))};return e(Bt,{label:t,...l===void 0?{}:{description:l},..._?{error:Wa(r)}:m===null?{}:{error:Ga(m,r)},children:[e(`div`,{className:`flex items-center gap-2`,children:[i(K,{type:`number`,min:0,max:r,value:g,disabled:s,state:_||m!==null?`error`:`default`,"aria-label":t,onChange:e=>{h(null),p(e.target.value)},onBlur:y,className:`w-20`,"data-testid":c}),i(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),u]}),v===`${n} s`?null:i(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function qa(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=St(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function Ja(e){switch(e.kind){case`checking`:return{word:J.t(`system.alarmSensorTable.cellChecking`),note:null};case`hub-too-old`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:J.t(`system.alarmSensorTable.cellHubTooOld`)};case`read-failed`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:J.t(`system.alarmSensorTable.cellReadFailedError`,{error:e.error})};case`open`:case`closed`:return{word:e.word,note:e.offline?J.t(`system.alarmSensorTable.cellOfflineLastKnown`):null};case`unknown`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:e.why===`not-answered`?J.t(`system.alarmSensorTable.cellNotAnswered`):e.why===`read-failed`?J.t(`system.alarmSensorTable.cellReadFailed`):J.t(`system.alarmSensorTable.cellNoState`)};case`not-opening`:return{word:J.t(`system.alarmSensorTable.cellNotOpening`),note:null};case`removed`:return{word:J.t(`system.alarmSensorTable.cellRemoved`),note:J.t(`system.alarmSensorTable.cellRemovedNote`)}}}function Ya(){return J.t(`system.alarmSensorTable.listedUncovered`)}function Xa(e){return e.listedUncovered?{word:J.t(`system.alarmSensorTable.cellNo`),note:Ya()}:Za(e.coverage)}function Za(e){switch(e.kind){case`arm-checked`:return{word:J.t(`system.alarmSensorTable.cellYes`),note:null};case`arm-checked-skipped`:{let t=e.reason===`detection-off`?J.t(`system.alarmSensorTable.detectionOff`):e.reason;return{word:J.t(`system.alarmSensorTable.cellSkipped`),note:J.t(`system.alarmSensorTable.cellSkippedNote`,{why:t})}}case`unscoped`:return{word:J.t(`system.alarmSensorTable.cellAllDevices`),note:J.t(`system.alarmSensorTable.cellNeverBlocks`)};case`not-covered`:return{word:J.t(`system.alarmSensorTable.cellNo`),note:J.t(`system.alarmSensorTable.cellNeverBlocks`)}}}function Qa(e){switch(e.kind){case`open`:case`read-failed`:case`hub-too-old`:case`removed`:return`warning`;case`closed`:case`checking`:case`unknown`:case`not-opening`:return`default`}}function $a(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 eo({name:t,variant:n,words:r}){return e(`span`,{"data-testid":`alarm-cell-${t}`,className:`flex flex-col items-start gap-0.5`,children:[i(U,{variant:n,"data-testid":`alarm-cell-${t}-badge`,children:r.word}),r.note===null?null:i(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${t}-note`,children:r.note})]})}var to=`hidden sm:table-cell`;function no({id:e,stored:t}){return i(`span`,{className:`truncate text-xs font-medium text-foreground`,children:pt(e,`compact`,t)})}function ro(e){let t=pt(e.deviceId,`compact`,e.storedName);return i(G,{checked:e.checked,onCheckedChange:e.onCheckedChange,disabled:e.disabled,"data-device-id":String(e.deviceId),"data-testid":e.testId,"aria-label":J.t(e.phraseKey,e.phraseFallback,{name:t}),"aria-busy":e.busy?!0:void 0,"aria-disabled":e.waiting?!0:void 0,className:e.waiting?`opacity-50`:void 0,...e.title===void 0?{}:{title:e.title}})}function io(t){let{mode:n,inFlight:r,onSwitch:a,zones:o,disabled:s}=t;return[{key:`name`,header:J.t(`system.alarmSensorTable.name`,`Name`),cell:t=>{let n=qa(t.device.location,o);return e(`span`,{className:`flex min-w-0 flex-col`,"data-testid":`alarm-cell-name`,"data-muted":t.listedUncovered?`true`:void 0,children:[i(no,{id:t.device.id,stored:t.device.name}),n===``?null:i(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:n})]})}},{key:`type`,header:J.t(`system.alarmSensorTable.type`,`Type`),headerClassName:to,cellClassName:`${to} text-[11px] text-foreground-subtle`,cell:e=>yt(e.device.type??null,In)},{key:`state`,header:J.t(`system.alarmSensorTable.state`,`State`),cell:e=>i(eo,{name:`state`,variant:Qa(e.cell),words:Ja(e.cell)})},{key:`coverage`,header:J.t(`system.alarmSensorTable.checkedWhenArming`,`Checked when arming`),headerClassName:to,cellClassName:to,cell:e=>i(eo,{name:`coverage`,variant:$a(e),words:Xa(e)})},{key:`blocks`,header:J.t(`system.alarmSensorTable.blocksArming`,`Blocks arming`),headerClassName:`text-right`,cellClassName:`text-right`,cell:t=>{let o=r!==null&&r.mode===n&&r.deviceId===t.device.id&&r.kind===`blocks`,c=r!==null&&!o;return e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[o?i(g,{className:`h-3 w-3 animate-spin`}):null,i(ro,{deviceId:t.device.id,storedName:t.device.name,phraseKey:`system.alarmSensorTable.blocksArming2`,phraseFallback:`Blocks arming: {{name}}`,checked:t.blocks,onCheckedChange:e=>a(t,`blocks`,e),disabled:s,testId:`alarm-switch-blocks`,busy:o,waiting:c})]})}},{key:`secure`,header:i(`span`,{title:J.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),children:J.t(`system.alarmSensorTable.secureOnArm`,`Secure on arm`)}),headerClassName:`text-right`,cellClassName:`text-right`,cell:t=>{if(!t.controllable)return i(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let o=r!==null&&r.mode===n&&r.deviceId===t.device.id&&r.kind===`secureOnArm`,c=r!==null&&!o;return e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[o?i(g,{className:`h-3 w-3 animate-spin`}):null,i(ro,{deviceId:t.device.id,storedName:t.device.name,phraseKey:`system.alarmSensorTable.secureOnArmCloseLock`,phraseFallback:`Secure on arm (close/lock/off): {{name}}`,checked:t.secureOnArm,onCheckedChange:e=>a(t,`secureOnArm`,e),disabled:s,testId:`alarm-switch-secure`,busy:o,waiting:c,title:J.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`)})]})}}]}function ao(t){let{t:n}=Y(),r=M(),{mode:a,rows:o,sensorsRetry:s,zones:c}=t;return e(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${a}`,children:[s===null?null:e(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[i(`span`,{children:n(`system.alarmSensorTable.couldNotReadTheSensor`,`Could not read the sensor states.`)}),i(q,{type:`button`,size:`sm`,variant:`outline`,onClick:s,children:n(`common.retry`,`Retry`)})]}),i(nn,{mode:`generic`,items:o,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,qa(e.device.location,c),yt(e.device.type??null,r)].join(` `),getFilterType:e=>yt(e.device.type??null,r),columns:io(t),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:n(`system.alarmSensorTable.searchSensors`,`Search sensors`),emptyLabel:`No sensor matches.`})]})}var oo=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function so(e){return oo.some(t=>t.test(e))}function co(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return so(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 lo(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 uo(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 fo(e){return e.kind===`unscoped`||e.kind===`not-covered`}function po(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=uo(e.coverage,r.id),a=lo(e.sensors,r.id,t,r.type),o=Ie({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=We({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&&fo(i)&&(!o||c)&&c;!t&&fo(i)&&!c||n.push({device:r,removed:t,cell:co(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function mo(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function ho(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 go(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 _o(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 vo(e,t){return Fe(_o(e),t)?{kind:`landed`}:{kind:`not-landed`}}var yo=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function bo({coverage:t,settings:n,disabled:r,onNotifyEdit:a}){let{t:o}=Y(),s=Ye(n,t.mode);return e(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${t.mode}`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:o(`notificationRules.alarmNotify.title`)}),yo.map(({field:n,key:c})=>e(`div`,{className:`flex items-start justify-between gap-3`,children:[e(`div`,{className:`min-w-0`,children:[i(`p`,{className:`text-xs text-foreground`,children:o(`notificationRules.alarmNotify.${c}`)}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`notificationRules.alarmNotify.${c}Hint`)})]}),i(G,{checked:s[n],onCheckedChange:e=>a(n,e),disabled:r,"data-testid":`alarm-notify-${t.mode}-${n}`,"aria-label":o(`notificationRules.alarmNotify.${c}`)})]},n))]})}function xo({coverage:t,rows:n,names:r}){let{t:a}=Y(),o=n.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,s=ua(t,r.nameOf);return e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${t.mode}`,children:[pa(t)?i(U,{variant:`warning`,title:s,"data-testid":`alarm-arms-nothing`,children:a(`system.alarmModeCard.armsNothingNoEnabledRule`,`Arms nothing — no enabled rule is gated on this mode`)}):i(U,{variant:`default`,title:s,"data-testid":`alarm-covers`,children:a(`system.alarmModeCard.checksSensors`,{count:o})}),t.skippedDevices.length>0?i(U,{variant:`warning`,title:da(t.skippedDevices,r.nameOf),"data-testid":`alarm-skipped`,children:a(`system.alarmModeCard.notNotified`,{count:t.skippedDevices.length})}):null]})}function So(e){return e.status===`answered`?e.openingIds:null}function Co({check:t,view:n}){let{t:r}=Y();return n.unresolved?t.status===`pending`?e(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[i(g,{className:`h-3 w-3 animate-spin`}),r(`system.alarmModeCard.checkingWhichDevicesAreOpenings`,`Checking which devices are openings…`)]}):t.status===`failed`?e(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[i(`span`,{children:r(`system.alarmModeCard.openingsCheckFailed`,{error:t.error})}),i(q,{type:`button`,size:`sm`,variant:`outline`,onClick:t.retry,children:r(`common.retry`,`Retry`)})]}):null:null}var wo=[{value:`rearmAfter`,labelKey:`system.alarmModeCard.postRearm`},{value:`disableAfter`,labelKey:`system.alarmModeCard.postDisarm`},{value:`doNothing`,labelKey:`system.alarmModeCard.postNothing`}];function To({coverage:t,settings:n,disabled:r,onDelayEdit:a,onPostTriggeredEdit:o,onScheduleEdit:s}){let{t:c}=Y(),l=t.mode,u=Ke(n,l),d=u.source.postTriggeredAction==="default",f=u.postTriggeredAction!==`doNothing`,p=(n.modeDelays??[]).find(e=>e.mode===l)?.schedule;return e(`div`,{className:`space-y-3`,"data-testid":`alarm-delays-${l}`,children:[e(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:[Ua.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let t=u.source[e.field]==="default";return i(Ka,{label:c(e.labelKey),value:u[e.field],max:e.max,zeroMeans:c(e.zeroMeansKey),disabled:r,testId:`alarm-delay-${l}-${e.key}`,onCommit:t=>a(e.field,t),adornment:t?i(U,{variant:`default`,title:c(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:n[e.field]}),children:c(`system.alarmModeCard.default`,`Default`)}):i(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:c(e.labelKey)}),onClick:()=>a(e.field,`default`),"data-testid":`alarm-delay-${l}-${e.key}-default`,children:i(D,{className:`h-3.5 w-3.5`})})},e.field)}),e(`div`,{children:[e(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:[c(`system.alarmModeCard.afterTrigger`,`After trigger`),d?i(U,{variant:`default`,className:`ml-1.5 align-middle`,title:c(`system.alarmModeCard.usesTheSystemDefault`,`Uses the system default`),children:c(`system.alarmModeCard.default`,`Default`)}):i(q,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:r,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.afterTriggerUseTheDefault`,`After trigger: use the default`),onClick:()=>o(`default`),"data-testid":`alarm-delay-${l}-post-default`,children:i(D,{className:`h-3.5 w-3.5`})})]}),i(I,{className:`mt-1 w-full`,value:u.postTriggeredAction,disabled:r,"data-testid":`alarm-delay-${l}-post`,onChange:e=>{let t=Be.safeParse(e.target.value);t.success&&o(t.data)},children:wo.map(e=>i(`option`,{value:e.value,children:c(e.labelKey)},e.value))})]}),f?Ua.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let t=u.source[e.field]==="default";return i(Ka,{label:c(e.labelKey),value:u[e.field],max:e.max,zeroMeans:c(e.zeroMeansKey),disabled:r,testId:`alarm-delay-${l}-${e.key}`,onCommit:t=>a(e.field,t),adornment:t?i(U,{variant:`default`,title:c(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:n[e.field]}),children:c(`system.alarmModeCard.default`,`Default`)}):i(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:c(e.labelKey)}),onClick:()=>a(e.field,`default`),"data-testid":`alarm-delay-${l}-${e.key}-default`,children:i(D,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),e(`div`,{"data-testid":`alarm-schedule-${l}`,children:[i(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.alarmModeCard.activationSchedule`,`Activation schedule`)}),i(`p`,{className:`mb-1 text-[10px] text-foreground-subtle`,children:c(`system.alarmModeCard.whenThisModeMayBe`,`When this mode may be armed. Empty means any day and time.`)}),i(`fieldset`,{disabled:r,className:`min-w-0 border-0 p-0`,children:i(fn,{value:p,onChange:s,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var Eo={"no-opening":`This household has no contact, cover or lock.`};function Do({coverage:t,live:n,settings:r,names:a,openingsCheck:o,rows:s,sensorsRetry:c,inFlight:l,onSwitch:u,zones:d,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m,onNotifyEdit:h,disabled:g}){let{t:_}=Y(),v=na({live:n,listed:Ca(r,t.mode),openingIds:So(o)}),y=ra(v),b=mo({rowCount:s.length,candidatesComplete:!v.unresolved});return e(`div`,{className:`flex flex-col gap-3`,"data-mode":t.mode,"data-empty":pa(t)?`true`:`false`,children:[i(xo,{coverage:t,rows:s,names:a}),i(To,{coverage:t,settings:r,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:_(`system.alarmModeCard.delaysHint`,{seconds:30})}),i(bo,{coverage:t,settings:r,disabled:g,onNotifyEdit:h}),e(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${t.mode}`,children:[i(Co,{check:o,view:v}),y===null?null:i(`p`,{className:`text-xs text-foreground-subtle`,children:Eo[y]}),b===`none`&&y===null?i(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`alarm-sensors-none`,children:_(`system.alarmModeCard.noSensorIsCoveredBy`,`No sensor is covered by a rule of this mode.`)}):null,b===`rows`?i(ao,{mode:t.mode,rows:s,sensorsRetry:c,inFlight:l,onSwitch:u,zones:d,disabled:g}):null]})]})}c();function Oo({profiles:t,busy:n,onActivate:r,onCreate:a,onClone:s,onRename:c,onDelete:l}){let{t:u}=Y(),[d,f]=o(``),[m,h]=o(!1),g=t.items.find(e=>e.id===t.activeId)??t.items[0],_=g!==void 0&&!g.isDefault,v=d.trim(),b=()=>{v.length!==0&&(a(v),f(``))},x=()=>{v.length===0||g===void 0||(s(g.id,v),f(``))},S=()=>{v.length===0||g===void 0||(c(g.id,v),f(``),h(!1))};return e(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface p-3`,"data-testid":`alarm-profiles`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:u(`system.alarmProfileBar.profile`,`Profile`)}),i(I,{wrapperClassName:`inline-block w-auto`,id:`alarm-profile-select`,className:`min-w-[10rem]`,"data-testid":`alarm-profile-select`,disabled:n,value:t.activeId,onChange:e=>r(e.target.value),children:t.items.map(t=>e(`option`,{value:t.id,children:[t.name,t.isDefault?` (${u(`system.alarmProfileBar.defaultSuffix`)})`:``]},t.id))}),_?i(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:n,"data-testid":`alarm-profile-delete`,title:u(`system.alarmProfileBar.deleteThisProfile`,`Delete this profile`),onClick:()=>{g!==void 0&&l(g.id)},children:i(re,{className:`h-3.5 w-3.5`})}):null]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(K,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:m?u(`system.alarmProfileBar.newName`,`New name`):u(`system.alarmProfileBar.newProfileName`,`New profile name`),value:d,disabled:n,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(m?S():b())}}),m?e(p,{children:[i(q,{type:`button`,size:`sm`,disabled:n||v.length===0,"data-testid":`alarm-profile-rename-save`,onClick:S,children:u(`system.alarmProfileBar.rename`,`Rename`)}),i(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:n,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{h(!1),f(``)},children:u(`common.cancel`,`Cancel`)})]}):e(p,{children:[e(q,{type:`button`,size:`sm`,disabled:n||v.length===0,"data-testid":`alarm-profile-create`,title:u(`system.alarmProfileBar.createWithSystemDefaults`,`Create with system defaults`),onClick:b,children:[i(k,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.create`,`Create`)]}),e(q,{type:`button`,size:`sm`,variant:`secondary`,disabled:n||v.length===0||g===void 0,"data-testid":`alarm-profile-clone`,title:u(`system.alarmProfileBar.cloneTheSelectedProfile`,`Clone the selected profile`),onClick:x,children:[i(y,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.clone`,`Clone`)]}),i(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:n||g===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{h(!0),f(g?.name??``)},children:u(`system.alarmProfileBar.rename`,`Rename`)})]})]}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`system.alarmProfileBar.createStartsFromSystemDefaults`,`Create starts from system defaults. Clone copies the selected profile (sensors, secure-on-arm, delays). Switching applies that profile for the next arm.`)})]})}c();var ko=[`notificationRules`,`getAlarmConfig`],Ao=[`notificationRules`,`getAlarmSensors`],jo=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],Mo=6e4;function No(e){return e instanceof Error?e.message:String(e)}function Po({notice:e}){let{t}=Y();switch(e.kind){case`refused`:return i(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:t(`system.notificationAlarm.refused`,{name:e.inFlight.name,mode:ca(e.inFlight.mode)})});case`not-landed`:return i(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:t(`system.notificationAlarm.notLanded`,{name:e.write.name,mode:ca(e.write.mode)})});case`failed`:return i(`p`,{className:`text-xs text-danger`,role:`alert`,"data-testid":`alarm-switch-failed`,children:t(`system.notificationAlarm.couldNotChangeFor`,`Could not change {{name}} for {{value2}}: {{error}}`,{name:e.write.name,value2:ca(e.write.mode),error:e.error})})}}function Fo(){let{t:r}=Y(),a=j(),c=u(),l=s({queryKey:ko,queryFn:async()=>a.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>va(e.state.data?.live?.state)}),p=Vt({projection:`slim`}),[m,h]=o(!1),_=f({mutationFn:e=>a.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{c.setQueryData(ko,e),h(!Fe(t,e.settings))}}),v=f({mutationFn:async e=>{switch(e.kind){case`activate`:return a.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return a.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return a.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return a.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return a.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{c.setQueryData(ko,e),h(!1)}}),y=()=>c.invalidateQueries({queryKey:ko}),b=n(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),S=l.data?.live,C=s({queryKey:jo,staleTime:Mo,queryFn:async()=>new Set(await a.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...ea]}))}),w=n(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),T=n(()=>new Map(w.map(e=>[e.id,e])),[w]),E=C.isError?{status:`failed`,error:C.error instanceof Error?C.error.message:String(C.error),retry:()=>void C.refetch()}:C.data===void 0?{status:`pending`}:{status:`answered`,openingIds:C.data},D=n(()=>{let e=new Map;for(let t of S?.openings??[])for(let n of t.devices)e.set(n.deviceId,aa(n));return ia(b,Ct(p),e)},[S,b,p]),O=Dt(!0),[k,A]=o(null),ee=n(()=>{let e=new Map,t=l.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,na({live:t.live,listed:Ca(t.settings,n.mode),openingIds:C.data??null}).ids);return e},[l.data,C.data]),M=n(()=>{let e=new Set;for(let t of ee.values())for(let n of t)D.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[ee,D]),N=s({queryKey:[...Ao,M],enabled:M.length>0,placeholderData:d,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&so(No(e.state.error))?!1:S!==void 0&&xa(S.state)?5e3:15e3,retry:(e,t)=>!so(No(t))&&e<2,queryFn:async()=>{let e=[];for(let t of ho(M,500))e.push(await a.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...t]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),P=N.isError?{status:`failed`,error:No(N.error)}:N.data===void 0?{status:`pending`}:{status:`answered`,sensors:N.data.sensors},F=t(null),[I,te]=o(null),[L,ne]=o(null),re=async e=>{try{let t=await a.trpcClient.notificationRules.setAlarmConfig.mutate({patch:_o(e)});vo(e,t.settings).kind===`landed`?c.setQueryData(ko,t):(ne({kind:`not-landed`,write:e}),c.invalidateQueries({queryKey:ko}))}catch(t){ne({kind:`failed`,write:e,error:No(t)}),c.invalidateQueries({queryKey:ko})}finally{F.current=null,te(null),ne(e=>e?.kind===`refused`?null:e)}},R=(e,t,n,r)=>{let i=go(F.current,e,t,n,r);if(i.kind===`refused`){ne({kind:`refused`,inFlight:i.inFlight});return}F.current=i.write,te(i.write),ne(null),re(i.write)};if(l.isLoading)return i(Ui,{embedded:!0,icon:x,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(g,{className:`h-5 w-5 animate-spin`})});let z=l.data;if(z===void 0||l.isError)return i(Ui,{embedded:!0,icon:x,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(dt,{title:r(`system.notificationAlarm.alarmSettingsAreNotAvailable`,`Alarm settings are not available`),message:r(`system.notificationAlarm.thisHubHasNotBeen`,`This hub has not been updated to serve the alarm configuration yet.`)})});if(z.deviceId===null)return i(Ui,{embedded:!0,icon:x,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:i(Yt,{className:`p-4`,children:i(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.notificationAlarm.thisInstallationHasNoAlarm`,`This installation has no alarm panel. The panel is created by the Notification Center on the hub — if this is the hub, its creation failed and the server log says why.`)})})});let B=z.settings,ie=_.isPending||v.isPending,ae=e=>{h(!1),_.mutate(e)},oe=(e,t,n)=>{let r=Oa(B,e,t,n);r!==null&&ae({modeDelays:[r]})},se=(e,t)=>{let n=ka(B,e,t);n!==null&&ae({modeDelays:[n]})},ce=(e,t)=>{let n=Aa(B,e,t);n!==null&&ae({modeDelays:[n]})},le=(e,t,n)=>{let r=La(B,e,t,n);r!==null&&ae({modeDelays:[r]})},ue=new Map(z.coverage.map(e=>[e.mode,po({candidates:(ee.get(e.mode)??[]).map(e=>({...T.get(e),id:e,name:D.nameOf(e)})),removedIds:new Set((ee.get(e.mode)??[]).filter(D.isRemoved)),coverage:e,nonBlocking:Ca(B,e.mode),blocking:wa(B,e.mode),secureOnArmOff:Ta(B,e.mode),sensors:P})])),de=z.coverage.find(e=>e.mode===k)??z.coverage.find(e=>(ue.get(e.mode)?.length??0)>0)??z.coverage[0],fe=de?.mode??``;return e(Ui,{embedded:!0,icon:x,title:r(`system.notificationAlarm.alarm`,`Alarm`),subtitle:r(`system.notificationAlarm.thePanelWhatEachMode`,`The panel, what each mode arms, and who hears about it.`),children:[_.isError?i(dt,{title:r(`system.notificationAlarm.couldNotSave`,`Could not save`),message:String(_.error)}):null,v.isError?i(dt,{title:r(`system.notificationAlarm.couldNotUpdateProfile`,`Could not update profile`),message:String(v.error)}):null,m?i(`div`,{"data-testid":`alarm-save-not-landed`,children:i(dt,{variant:`warning`,title:r(`system.notificationAlarm.notApplied`,`Not applied`),message:r(`system.notificationAlarm.theHubDidNotApply`,`The hub did not apply this change — another editor may have changed it, or the hub needs an update`)})}):null,z.profiles===void 0?null:i(Oo,{profiles:z.profiles,busy:ie,onActivate:e=>v.mutate({kind:`activate`,id:e}),onCreate:e=>v.mutate({kind:`create`,name:e}),onClone:(e,t)=>v.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>v.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>v.mutate({kind:`delete`,id:e})}),i(Ha,{live:z.live,onChanged:y}),e(Yt,{className:`p-4`,"data-testid":`alarm-coverage`,children:[i(Qt,{value:fe,onValueChange:e=>{let t=z.coverage.find(t=>t.mode===e);t!==void 0&&A(t.mode)},children:i(Kt,{className:`mb-3`,children:z.coverage.map(t=>e($t,{value:t.mode,"data-testid":`alarm-tab-${t.mode}`,children:[ca(t.mode),i(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:ue.get(t.mode)?.length??0})]},t.mode))})}),L===null?null:i(Po,{notice:L}),de===void 0?null:i(Do,{coverage:de,live:z.live,settings:B,names:D,openingsCheck:E,rows:ue.get(de.mode)??[],sensorsRetry:P.status===`failed`&&!so(P.error)?()=>void N.refetch():null,inFlight:I,onSwitch:(e,t,n)=>R(de.mode,e,t,n),zones:O,onDelayEdit:(e,t)=>oe(de.mode,e,t),onPostTriggeredEdit:e=>se(de.mode,e),onScheduleEdit:e=>ce(de.mode,e),onNotifyEdit:(e,t)=>le(de.mode,e,t),disabled:ie},de.mode)]})]})}var Io=`history`,Lo=`ruleId`,Ro=[Lo],zo=24,Bo=0,Vo=100;function Ho(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Io),n.set(Lo,t),n}function Uo(e,t){let n=new URLSearchParams(e);return t===``?n.delete(Lo):n.set(Lo,t),n}function Wo(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?zo:Bo,limit:Vo}}function Go(e){let t=e.rules.map(e=>({value:e.id,label:e.name})),n=e.selected!==``&&!e.rules.some(t=>t.id===e.selected)?[{value:e.selected,label:e.answered?J.t(`helpers.notificationHistory.deletedRule`,{id:e.selected}):e.selected}]:[];return[{value:``,label:J.t(`helpers.notificationHistory.allRules`)},...t,...n]}c();var Ko=[{value:1,labelKey:`system.notificationHistory.windowLastHour`},{value:24,labelKey:`system.notificationHistory.windowLast24h`},{value:168,labelKey:`system.notificationHistory.windowLast7d`},{value:0,labelKey:`system.notificationHistory.windowAllTime`}],qo=[{value:``,labelKey:`system.notificationHistory.statusAny`},{value:`pending`,labelKey:`system.notificationHistory.statusPending`},{value:`sent`,labelKey:`system.notificationHistory.statusSent`},{value:`dead`,labelKey:`system.notificationHistory.statusDead`}],Jo=[50,100,250,500];function Yo(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Xo(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Zo(e){let t=e.subject.systemEvent;if(t!==void 0)return{title:t.title,body:t.body};let n=e.subject.label??e.subject.className,r=e.subject.zones.length>0?` in ${e.subject.zones.join(`, `)}`:``;return{title:e.ruleName,body:`${n}${r}`}}function Qo({entry:t,cameraName:n,onClose:r}){let{t:a}=Y(),o=Zo(t),s=t.subject.systemEvent;return i(xt,{open:!0,onOpenChange:e=>!e&&r(),children:e(Xt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[i(It,{children:i(Rt,{className:`min-w-0 break-words`,children:o.title||t.ruleName})}),i(wt,{children:e(`dl`,{className:`space-y-3`,children:[e(`div`,{children:[i(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:a(`system.notificationHistory.body`,`Body`)}),i(`dd`,{className:`mt-1 whitespace-pre-wrap text-sm text-foreground`,children:o.body.length>0?o.body:`—`})]}),e(`div`,{className:`grid grid-cols-2 gap-3 text-[11px]`,children:[e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.when`,`When`)}),i(`dd`,{className:`text-foreground`,children:new Date(t.createdAt).toLocaleString()})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.status`,`Status`)}),i(`dd`,{className:`text-foreground`,children:t.status})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.rule`,`Rule`)}),i(`dd`,{className:`text-foreground`,children:t.ruleName})]}),e(`div`,{children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.device`,`Device`)}),i(`dd`,{className:`text-foreground`,children:n})]}),s===void 0?null:e(`div`,{className:`col-span-2`,children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.kind`,`Kind`)}),i(`dd`,{className:`text-foreground`,children:s.kind})]}),t.error===void 0?null:e(`div`,{className:`col-span-2`,children:[i(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`common.error`,`Error`)}),i(`dd`,{className:`text-danger`,children:t.error})]})]})]})}),i(Lt,{children:i(q,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:a(`common.close`,`Close`)})})]})})}function $o(){let{t}=Y(),r=j(),[a,c]=pn(),[l,u]=o(()=>Wo(a)),[d,f]=o(null),p=e=>u(t=>({...t,...e})),h=e=>{p({ruleId:e}),c(Uo(a,e),{replace:!0})},_=s({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await r.trpcClient.notificationRules.listRules.query({})).rules}),v=Vt({projection:`slim`}),y=Date.now(),b=s({queryKey:[`notificationRules`,`getHistory`,l],retry:!1,queryFn:async()=>{let e=l.windowHours>0?y-l.windowHours*36e5:void 0;return(await r.trpcClient.notificationRules.getHistory.query({filter:{limit:l.limit,...l.ruleId?{ruleId:l.ruleId}:{},...l.deviceId?{deviceId:Number(l.deviceId)}:{},...Yo(l.status)?{status:Yo(l.status)}:{},...e===void 0?{}:{since:e}}})).entries}}),x=n(()=>{let e=new Map;for(let t of v.data??[])t.type===Je.Camera&&e.set(t.id,t.name);return e},[v.data]),S=e=>x.get(e)??t(`system.notificationHistory.cameraFallback`,{deviceId:e}),C=b.data??[],w=b.isError;return e(Ui,{embedded:!0,icon:m,title:t(`system.notificationHistory.deliveryHistory`,`Delivery history`),subtitle:t(`system.notificationHistory.aSearchableLogOfEvery`,`A searchable log of every notification the rules delivered (or failed to deliver).`),children:[e(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.rule`,`Rule`)}),i(I,{"data-testid":`history-rule-filter`,value:l.ruleId,onChange:e=>h(e.target.value),options:[...Go({rules:_.data??[],answered:_.isSuccess,selected:l.ruleId})]})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.camera`,`Camera`)}),i(I,{value:l.deviceId,onChange:e=>p({deviceId:e.target.value}),options:[{value:``,label:t(`system.notificationHistory.allCameras`,`All cameras`)},...(v.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.status`,`Status`)}),i(I,{value:l.status,onChange:e=>p({status:e.target.value}),options:qo.map(e=>({value:e.value,label:t(e.labelKey)}))})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.window`,`Window`)}),i(I,{value:String(l.windowHours),onChange:e=>p({windowHours:Number(e.target.value)}),options:Ko.map(e=>({value:String(e.value),label:t(e.labelKey)}))})]}),e(`div`,{children:[i(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.limit`,`Limit`)}),i(I,{value:String(l.limit),onChange:e=>p({limit:Number(e.target.value)}),options:Jo.map(e=>({value:String(e),label:String(e)}))})]})]}),b.isLoading&&i(`div`,{className:`flex items-center justify-center py-16`,children:i(g,{className:`h-6 w-6 animate-spin text-primary`})}),w&&!b.isLoading&&i(Yt,{children:e(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[i(m,{className:`h-6 w-6 text-foreground-subtle`}),i(`div`,{className:`text-sm font-medium text-foreground`,children:t(`system.notificationHistory.deliveryHistoryRequiresAServer`,`Delivery history requires a server update`)}),i(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:t(`system.notificationHistory.theHistoryQueryIsNot`,`The history query is not available on this hub yet. It becomes queryable after the next server update ships the notification-center history endpoint. Rules still deliver and record their outcome in the meantime.`)}),e(q,{variant:`unstyled`,type:`button`,onClick:()=>void b.refetch(),className:`mt-1 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:[i(E,{className:`h-3 w-3`}),` `,t(`common.retry`)]})]})}),!w&&!b.isLoading&&C.length===0&&i(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:t(`system.notificationHistory.noDeliveriesMatchTheseFilters`,`No deliveries match these filters.`)}),!w&&C.length>0&&i(Yt,{children:i(Pt,{columns:es(S),rows:C,rowKey:e=>e.id,minWidthPx:720,bordered:!1,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>f(e)})}),d!==null&&i(Qo,{entry:d,cameraName:S(d.deviceId),onClose:()=>f(null)})]})}function es(t){return[{key:`when`,header:J.t(`system.notificationHistory.when`,`When`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:J.t(`system.notificationHistory.rule`,`Rule`),render:e=>i(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:J.t(`system.notificationHistory.camera`,`Camera`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t(e.deviceId)})},{key:`subject`,header:J.t(`system.notificationHistory.notification`,`Notification`),render:t=>{let n=Zo(t);return e(`span`,{className:`block max-w-[18rem]`,children:[i(`span`,{className:`block truncate text-[11px] font-medium text-foreground`,children:n.title.length>0?n.title:t.subject.label??t.subject.className}),n.body.length>0?i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:n.body}):null]})}},{key:`status`,header:J.t(`system.notificationHistory.status`,`Status`),nowrap:!0,render:t=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(U,{variant:Xo(t.status),children:t.status}),t.attempts>1?e(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,t.attempts]}):null]})},{key:`error`,header:J.t(`system.notificationHistory.detail`,`Detail`),render:e=>e.error?i(`span`,{className:`text-[11px] text-danger`,children:e.error}):i(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var ts=/\{\{\s*(\w+)\s*\}\}/g,ns=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function rs(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function is(e){return[...e.matchAll(ts)].map(e=>e[1]??``).filter(e=>e.length>0)}function as(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function os(e,t){return[...new Set(is(e))].filter(e=>!as(e,t))}var ss={previewText:[`device`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function cs(e){return e.map(e=>{let t=Me.find(t=>t.name===e.name),n=e.systemEventKinds;if(t?.systemEventKinds===void 0||n===void 0)return e;let r=t.systemEventKinds.filter(e=>n.includes(e)||ke.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function ls(e){let t=new Set(e.map(e=>e.name)),n=Me.filter(e=>Se(e)&&!t.has(e.name));return[...e,...n]}function us(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=ss[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)||!Re(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:Xe(e,t)&&oe(e,t))}function ds(e){return ns.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var fs=[`nc`,`template-catalog`],ps=400;function ms(){let e=j();return s({queryKey:fs,staleTime:5*6e4,queryFn:async()=>ls(cs((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function hs(e,t,n){let r=j(),i=rn(t.title??``,ps),a=rn(t.body??``,ps);return s({queryKey:[`nc`,`template-preview`,e,i,a],enabled:n&&(i.length>0||a.length>0),staleTime:3e4,queryFn:()=>r.trpcClient.notificationRules.previewTemplate.mutate({context:e,template:{...i?{title:i}:{},...a?{body:a}:{}}})})}c();var gs={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},_s=`block text-[11px] font-medium text-foreground mb-1`;function vs({label:n,value:r,onChange:a,vars:o,multiline:s=!1,placeholder:c,disabled:l=!1,deviceValues:u=!0,testId:d}){let{t:f}=Y(),p=t(null),m=t(null),h=o?os(r,o):[],g=e=>{let t=rs(e);if(u){p.current?.insertText(t.text,t.cursorOffset);return}let n=m.current,i=n?.selectionStart??r.length,o=n?.selectionEnd??r.length;a(r.slice(0,i)+t.text+r.slice(o));let s=i+t.cursorOffset;requestAnimationFrame(()=>{n?.focus(),n?.setSelectionRange(s,s)})},_=e=>a(e.target.value);return e(`div`,{className:`space-y-1`,children:[i(`label`,{className:_s,children:n}),u?i(en,{label:n,value:r,onChange:a,multiline:s,placeholder:c,disabled:l,handle:p,heldSlots:`placeholders`,testId:d}):s?i(zt,{ref:m,"aria-label":n,value:r,rows:2,disabled:l,placeholder:c,onChange:_,"data-testid":`${d}-input`}):i(K,{ref:m,"aria-label":n,value:r,disabled:l,placeholder:c,onChange:_,"data-testid":`${d}-input`}),o&&o.length===0?i(`p`,{className:`text-[10px] text-foreground-subtle`,children:f(`notifications.templateField.noVariablesForThisField`,`No variables for this field.`)}):null,o&&o.length>0?i(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:ds(o).map(t=>e(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${d}-group-${t.group}`,children:[i(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:gs[t.group]}),t.vars.map(e=>i(q,{variant:`unstyled`,type:`button`,disabled:l,onMouseDown:e=>e.preventDefault(),onClick:()=>g(e),title:`${e.description??e.label} — e.g. "${e.example}"`,className:`rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-foreground hover:bg-surface-hover`,"data-testid":`${d}-chip-${e.name}`,children:e.dynamic?f(`notifications.templateField.class`,`{{name}}<class>`,{name:e.name}):e.name},e.name))]},t.group))}):null,h.length>0?e(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${d}-unknown`,children:[i(w,{className:`h-3 w-3`}),f(`notifications.templateField.willBeEmpty`,{names:h.map(e=>`{{${e}}}`).join(` `)})]}):null]})}function ys({context:t,title:n,body:r,testId:a}){let{t:o}=Y(),s=hs(t,{title:n,body:r},!0);return s.data?e(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":a,children:[i(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:o(`notifications.templateField.previewExampleValues`,`Preview (example values)`)}),s.data.title===null?null:i(`p`,{className:`font-medium`,children:s.data.title}),s.data.body===null?null:i(`p`,{className:`whitespace-pre-wrap`,children:s.data.body})]}):null}var bs=`/build?tab=actions&create=1`,xs=`/build?tab=actions&create=1&preset=${Vi}`,Ss=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,Cs=`block text-[11px] font-medium text-foreground`;function ws({title:t,description:n,children:r}){return e(`div`,{className:`flex flex-col gap-2`,children:[e(`div`,{children:[i(`h4`,{className:`text-xs font-semibold text-foreground`,children:t}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:n})]}),r!==void 0&&i(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function Ts(){let{t}=Y();return e(Di,{to:bs,target:`_blank`,rel:`noopener noreferrer`,title:t(`system.notificationRuleActions.createActionHint`,`Opens the Actions page in a new tab. Reopen the list here afterwards.`),className:`inline-flex items-center gap-1 text-[11px] font-medium text-primary hover:underline`,children:[i(ee,{className:`h-3.5 w-3.5 shrink-0`}),t(`system.notificationRuleActions.createActionLink`,`Create a new Action`)]})}function Es(){let{t:e}=Y();return i(Di,{to:xs,target:`_blank`,rel:`noopener noreferrer`,title:e(`system.notificationRuleActions.presetAlarmHint`,`Presses the alarm panel. The panel's entry delay still runs, and a disarm during it cancels the alarm.`),className:`inline-flex items-center gap-1 text-[11px] font-medium text-primary hover:underline`,children:e(`system.notificationRuleActions.presetAlarm`,`Trigger the alarm`)})}function Ds({value:t,actions:n,onChange:r}){let{t:a}=Y(),o=t!==``&&!n.some(e=>e.id===t);return e(I,{wrapperClassName:`block w-full`,className:Ss,value:t,onChange:e=>r(e.target.value),children:[t===``&&i(`option`,{value:``,children:a(`system.notificationRuleActions.pickAction`,`Pick an Action`)}),o&&i(`option`,{value:t,children:a(`system.notificationRuleActions.missingAction`,`Missing Action ({{id}})`,{id:t})}),n.map(e=>i(`option`,{value:e.id,children:e.name},e.id))]})}function Os({value:t,onChange:n,actions:r,showProblems:a=!0}){let{t:o}=Y(),s=Tn(t,new Set(r.map(e=>e.id))),c=(e,r)=>n({...t,[e]:r}),l=(e,r)=>n({...t,buttons:t.buttons.map((t,n)=>n===e?r:t)});return e(`div`,{className:`space-y-4`,children:[a&&s.length>0?i(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:s.map(e=>i(`p`,{children:e.message},e.message))}):null,r.length===0&&e(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[o(`system.notificationRuleActions.noActionsYet`,`There are no Actions yet. Create one on the Actions page — a rule or a button runs an Action, it does not define its own steps.`),` `,i(Ts,{}),` `,i(Es,{})]}),Ln.map(e=>i(ks,{hookKey:e,actionIds:t[e],actions:r,onChange:t=>c(e,t)},e)),e(`section`,{className:`space-y-2`,children:[e(ws,{title:o(`system.notificationRuleActions.buttonsOnTheNotification`,`Buttons on the notification`),description:o(`system.notificationRuleActions.eachButtonRunsOneAction`,`Each button runs one Action when tapped.`),children:[e(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:r.length===0,onClick:()=>n({...t,buttons:[...t.buttons,un(t.buttons.length,r[0]?.id??``)]}),children:[i(k,{className:`h-3.5 w-3.5 shrink-0`}),` `,o(`system.notificationRuleActions.button`)]}),i(Ts,{}),i(Es,{})]}),t.buttons.length>0&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:[i(w,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),i(`span`,{children:i(br,{i18nKey:`system.notificationRuleActions.buttonLinkNote`,components:{b:i(`strong`,{})}})})]}),t.buttons.length===0?i(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:o(`system.notificationRuleActions.noButtonsTheNotificationArrives`,`No buttons. The notification arrives with nothing to tap.`)}):t.buttons.map((e,a)=>i(As,{button:e,actions:r,onChange:e=>l(a,e),onRemove:()=>n({...t,buttons:t.buttons.filter((e,t)=>t!==a)})},`btn-${String(a)}`))]})]})}function ks({hookKey:t,actionIds:n,actions:r,onChange:a}){let{t:o}=Y(),s=Xn[t];return e(`section`,{className:`space-y-2`,children:[i(ws,{title:s.title,description:s.hint,children:e(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.length>=4||r.length===0,onClick:()=>a([...n,r[0]?.id??``]),children:[i(k,{className:`h-3.5 w-3.5`}),` `,o(`system.notificationRuleActions.addAction`)]})}),n.length===0?i(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:o(`system.notificationRuleActions.nothingOnThisEdge`,`Nothing on this edge.`)}):n.map((s,c)=>e(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:Cs,children:o(`system.notificationRuleActions.action`,`Action`)}),i(Ds,{value:s,actions:r,onChange:e=>a(n.map((t,n)=>n===c?e:t))})]}),i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>a(n.filter((e,t)=>t!==c)),title:o(`common.remove`,`Remove`),children:i(re,{className:`h-3.5 w-3.5`})})]},`${t}-${String(c)}`))]})}function As({button:t,actions:n,onChange:r,onRemove:a}){let{t:o}=Y();return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[e(`div`,{className:`w-28`,children:[i(`label`,{className:Cs,children:o(`system.notificationRuleActions.id`,`Id`)}),i(K,{className:`mt-1`,value:t.id,onChange:e=>r({...t,id:e.target.value})})]}),e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:Cs,children:o(`system.notificationRuleActions.label`,`Label`)}),i(K,{className:`mt-1`,value:t.label,onChange:e=>r({...t,label:e.target.value})})]}),e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:Cs,children:o(`system.notificationRuleActions.action`,`Action`)}),i(Ds,{value:t.actionId,actions:n,onChange:e=>r({...t,actionId:e})})]}),e(`div`,{className:`w-32`,children:[i(`label`,{className:Cs,children:o(`system.notificationRuleActions.icon`,`Icon`)}),e(I,{wrapperClassName:`inline-block w-auto`,className:Ss,value:t.icon??``,onChange:e=>{let{icon:n,...i}=t,a=On.find(t=>t.value===e.target.value);r(a===void 0?i:{...i,icon:a.value})},children:[i(`option`,{value:``,children:`—`}),On.map(e=>i(`option`,{value:e.value,children:e.label},e.value))]})]}),i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,title:o(`common.remove`,`Remove`),children:i(re,{className:`h-3.5 w-3.5`})})]})}function js({param:e,value:t,onChange:n}){let{t:r}=Y(),a=e.default===void 0?void 0:String(e.default);return e.type===`enum`?i(I,{value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`system.notificationRules.deliveryOptions.useDefault`,`Use the target setting`)},...e.options??[]]}):e.type===`boolean`?i(G,{checked:t===!0,onCheckedChange:e=>n(e),label:e.label}):i(K,{type:e.type===`number`?`number`:`text`,value:typeof t==`number`||typeof t==`string`?String(t):``,placeholder:a,min:e.min,max:e.max,onChange:t=>{let r=t.target.value;if(r===``)return n(void 0);if(e.type===`string`)return n(r);let i=Number(r);n(Number.isFinite(i)?i:void 0)}})}function Ms(e,t){return t.find(t=>t.kind===e.kind&&t.addonId===e.addonId)}function Ns(e,t,n){let r=t.find(t=>t.id===e);return(r===void 0?void 0:Ms(r,n)?.deliveryParams)??[]}c();function Ps(t){let{t:n}=Y(),[r,a]=o(()=>new Set(t.targetIds.filter(e=>t.overrides[e]!==void 0)));if(t.targetIds.length===0)return null;let s=Ur(t.targets,t.kinds),c=(e,t)=>a(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r});return e(`div`,{className:`flex flex-col gap-2`,"data-testid":`rule-target-settings`,children:[i(`p`,{className:`text-sm font-medium text-foreground`,children:n(`system.notificationRules.targetSettings.title`,`Per-target settings`)}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:n(`system.notificationRules.targetSettings.help`,`Each target follows the rule unless you change it here. A target offers only what its notifier can deliver.`)}),t.targetIds.map(e=>i(Fs,{...t,targetId:e,name:t.targets.find(t=>t.id===e)?.name??e,fields:s(e),expanded:r.has(e),onExpandedChange:t=>c(e,t)},e))]})}function Fs(t){let{t:n}=Y(),{targetId:r,fields:a}=t,o=t.overrides[r]??{},s=t.surface??`rule`,c=e=>di(s,e)&&(a===void 0||a.includes(e)),l=t.onTargetParamsChange,u=t.targetParams??{},d=l===void 0?[]:Ns(r,t.targets,t.kinds),f=Object.keys(o).length>0||u[r]!==void 0,p=e=>t.onOverridesChange(xr(t.overrides,r,Object.keys(e).length>0?e:void 0)),m=(e,t)=>{let{[e]:n,...r}=o.template??{},i=t===``?r:{...r,[e]:t},{template:a,...s}=o;p(Object.keys(i).length>0?{...s,template:i}:s)},h=e=>{let{priority:t,...n}=o;p(e===``?n:{...n,priority:Number(e)})},g=e=>{let{schedule:t,...n}=o;p(e===void 0?n:{...n,schedule:e})},_=e=>{let{attachment:t,...n}=o,r=Ne.safeParse(e);p(r.success?{...n,attachment:r.data}:n)},v=e=>{let{actions:t,...n}=o;p(e?{...n,actions:!1}:n)},y=ni(r,t.targets,t.kinds),b=y===void 0?void 0:{...y,attachmentKinds:zr(s,y.attachmentKinds)},x=b!==void 0&&b.levels.length>0?b.levels.map(e=>({value:e.ordinal??0,label:e.label})):_n,S=x.find(e=>e.value===t.rulePriority)?.label;return i(_t,{expanded:t.expanded,onExpandedChange:t.onExpandedChange,header:e(`span`,{className:`flex items-center gap-2 text-xs`,"data-testid":`rule-target-settings-${r}`,children:[i(`span`,{className:`font-medium text-foreground`,children:t.name}),i(`span`,{className:`text-foreground-subtle`,children:f?n(`system.notificationRules.targetSettings.customised`,`Own settings`):n(`system.notificationRules.targetSettings.followsRule`,`Follows the rule`)})]}),children:e(`div`,{className:`flex flex-col gap-3`,children:[c(`title`)&&i(vs,{label:n(`system.notificationRules.targetSettings.titleOverride`,`Title for this target`),value:o.template?.title??``,onChange:e=>m(`title`,e),vars:t.varsFor(`title`),placeholder:n(`system.notificationRules.targetSettings.useRuleText`,`The rule's text`),testId:`rule-target-${r}-title`}),c(`body`)&&i(vs,{label:n(`system.notificationRules.targetSettings.bodyOverride`,`Body for this target`),value:o.template?.body??``,onChange:e=>m(`body`,e),vars:t.varsFor(`body`),placeholder:n(`system.notificationRules.targetSettings.useRuleText`,`The rule's text`),multiline:!0,testId:`rule-target-${r}-body`}),c(`priority`)&&i(Bt,{label:n(`system.notificationRules.priority`,`Priority`),children:i(I,{value:o.priority===void 0?``:String(o.priority),onChange:e=>h(e.target.value),options:[{value:``,label:n(`system.notificationRules.targetSettings.rulePriority`,{defaultValue:`The rule's priority ({{priority}})`,priority:S??String(t.rulePriority)})},...x.map(e=>({value:String(e.value),label:e.label}))],"data-testid":`rule-target-${r}-priority`})}),c(`attachments`)&&b!==void 0&&b.attachmentKinds.length>0&&i(Bt,{label:n(`system.notificationRules.targetSettings.attachment`,`Picture`),children:i(I,{value:o.attachment??``,onChange:e=>_(e.target.value),options:[{value:``,label:n(`system.notificationRules.targetSettings.attachmentRule`,`Whatever the rule produces`)},...b.attachmentKinds.map(e=>({value:e,label:n(`system.notificationRules.targetSettings.attachmentKind.${e}`,e)}))],"data-testid":`rule-target-${r}-attachment`})}),c(`actions`)&&i(G,{checked:o.actions===!1,onCheckedChange:v,label:n(`system.notificationRules.targetSettings.noButtons`,`No action buttons`),"data-testid":`rule-target-${r}-no-buttons`}),i(Bt,{label:n(`system.notificationRules.targetSettings.schedule`,`When this target is notified`),children:i(fn,{value:o.schedule,onChange:g,emptyHint:n(`system.notificationRules.targetSettings.scheduleEmpty`,`Whenever the rule fires.`)})}),d.map(e=>i(Bt,{label:e.label,children:i(js,{param:e,value:u[r]?.[e.key],onChange:t=>l?.(Oi(u,r,e.key,t))})},e.key))]})})}function Is({support:e}){let{t}=Y();return e===void 0||e.droppedBy.length===0?null:i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-field-dropped-${e.field}`,children:t(`system.notificationRules.targetSettings.droppedBy`,{defaultValue:`Not delivered to: {{targets}}`,targets:e.droppedBy.join(`, `)})})}c();function Ls(){let e=j();return s({queryKey:[`notificationOutput`,`listTargetKinds`,`forRuleDelivery`],queryFn:()=>e.trpcClient.notificationOutput.listTargetKinds.query({})}).data??[]}function Rs(e){let t=Ls(),r=ms(),a=n(()=>Vr(e.targets),[e.targets]),o=e.templateFamily;return i(Ps,{surface:e.surface,targetIds:e.targetIds,targets:a,kinds:t,overrides:e.overrides,rulePriority:e.rulePriority,onOverridesChange:e.onChange,varsFor:e=>r.data!==void 0&&o!==void 0?us(r.data,{family:o,field:e}):void 0})}var zs=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Bs=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],Vs={minConfidence:`class`},Hs=[{id:`system`,get label(){return J.t(`notificationRules.groups.system`)}},{id:`class`,get label(){return J.t(`notificationRules.groups.class`)}},{id:`zones`,get label(){return J.t(`notificationRules.groups.zones`)}},{id:`label`,get label(){return J.t(`notificationRules.groups.label`)}},{id:`quality`,get label(){return J.t(`notificationRules.groups.quality`)}},{id:`scope`,get label(){return J.t(`notificationRules.groups.scope`)}},{id:`device`,get label(){return J.t(`notificationRules.groups.device`)}},{id:`package`,get label(){return J.t(`notificationRules.groups.package`)}},{id:`occupancy`,get label(){return J.t(`notificationRules.groups.occupancy`)}},{id:`audio`,get label(){return J.t(`notificationRules.groups.audio`)}},{id:`schedule`,get label(){return J.t(`notificationRules.groups.schedule`)}}];function Us(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Bs)t.has(e)&&n.add(r);return n}function Ws(e){return Vs[e.id]??e.group}function Gs(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Ks(e){let t=Us(e),n=e.filter(e=>!zs.has(e.id)&&!t.has(e.id)),r=new Set(Hs.map(e=>e.id)),i=[],a=e=>n.filter(t=>Ws(t)===e);for(let e of Hs){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=Ws(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Gs(e),descriptors:a(e)});return i}function qs(e,t){switch(e){case`zones`:return pi(t.zones?.ids,t.zonesExclude);case`labels`:return pi(t.labelEquals,void 0);case`identities`:return Js(t)}}function Js(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?pi(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function Ys(e,t,n){switch(e){case`zones`:return Xs(t,n);case`labels`:return Zs(t,n);case`identities`:return Qs(t,n)}}function Xs(e,t){let{zones:n,zonesExclude:r,...i}=e,a=cr(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function Zs(e,t){let{labelEquals:n,...r}=e,i=cr(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function Qs(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=An(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=cr(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var $s={all:`All`,only:`Only these`,except:`All except these`},ec={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 tc({draft:t,onChange:n,exceptOffered:r,plural:a,renderPicker:o,describe:s,testId:c}){let{t:l}=Y(),u=(e,t,n)=>l(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),d=l(`ruleScope.items.${a}`,ec[a].items),f=nr.filter(e=>e!==`except`||r||t.mode===`except`),p=An(t),m=Nn(t),h=t.mode===`all`?null:t.mode;return e(`div`,{className:`mt-1 space-y-1.5`,"data-testid":c,children:[i(`div`,{role:`radiogroup`,"aria-label":u(`ruleScope.which`,`Which {{items}}`,d),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(e=>{let r=e===t.mode;return i(q,{variant:`unstyled`,type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${e}`,onClick:()=>n(_r(t,e)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,children:l(`ruleScope.mode.${e}`,$s[e])},e)})}),h===null?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:l(`ruleScope.every.${a}`,ec[a].every)}):o(mr(t),e=>n(dr(t,e)),h),p.length>0&&e(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[u(`ruleScope.legacy`,`This rule also excludes {{items}} — kept when you save.`,p.map(s).join(`, `)),` `,i(q,{variant:`unstyled`,type:`button`,className:`underline hover:no-underline`,onClick:()=>n(Sn(t)),children:l(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:u(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(s).join(`, `))})]})}function nc(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 rc(e){return e.map(e=>e.hint===void 0?{id:e.value,name:e.label}:{id:e.value,name:`${e.hint}:${e.label}`,type:e.hint})}c();function ic(e,t,n){let[r,i]=o(()=>qs(e,t));return[r,r=>{i(r),n(Ys(e,t,r))}]}function ac(e,t){return t?`failed`:e?`pending`:`answered`}function oc({conditions:e,onConditionsChange:t,exceptOffered:r,cameraIds:a,cameras:o}){let{t:s}=Y(),[c,l]=ic(`zones`,e,t),{options:u,loading:d,failed:f}=Jn(a,o),p=n(()=>rc(u),[u]),m=ac(d,!1),h=f?{state:`failed`,devices:void 0}:{state:m,devices:m===`answered`?p:void 0},g=n(()=>new Map(p.map(e=>[e.id,e.name])),[p]);return i(tc,{draft:c,onChange:l,exceptOffered:r,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>a.length===0?i(`p`,{className:Fn,children:s(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):i(Et,{devices:p,listState:m,fleet:h,value:e,onChange:t,emptyMeansAll:!0,noun:`zone`,groupTitle:e=>e.type??s(`notificationRules.zones.group`,`Zones`),testId:`zone-picker`},n)})}function sc({conditions:e,onConditionsChange:t,exceptOffered:r}){let{t:a}=Y(),[o,s]=ic(`identities`,e,t),{options:c,loading:l,failed:u}=vr(),d=n(()=>c.map(e=>({id:e.value,name:e.label})),[c]),f=n(()=>new Map(d.map(e=>[e.id,e.name])),[d]);return i(tc,{draft:o,onChange:s,exceptOffered:r,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>i(Et,{devices:d,listState:ac(l,u),value:e,onChange:t,emptyMeansAll:n===`except`,...n===`only`?{emptyLabel:a(`notificationRules.faces.anyKnown`,`Any known face — nobody in particular`)}:{},noun:`face`,groupTitle:()=>a(`notificationRules.faces.group`,`Known faces`),testId:`identity-picker`},n)})}function cc({conditions:e,onConditionsChange:t}){let{t:n}=Y(),[r,a]=ic(`labels`,e,t);return i(tc,{draft:r,onChange:a,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>i(Yn,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function lc(e){let t=se(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function uc(e){return e.type??J.t(`helpers.classPickerItems.other`)}c();function dc({taxonomy:e,scope:t,onChange:r,exceptOffered:a}){let{t:o}=Y(),s=n(()=>lc(e),[e]),c=n(()=>new Map((s??[]).map(e=>[e.id,e.name])),[s]);return i(tc,{draft:t,onChange:r,exceptOffered:a,plural:`classes`,describe:e=>c.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>s===null?i(Yn,{value:e,placeholder:o(`system.notificationClassScopeField.addValue`,`Add value…`),onChange:t}):i(Et,{devices:s,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:uc,testId:`class-picker`},n)})}function fc(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function pc({devices:e,value:t,onChange:n,listState:r,savedHadDevices:a}){return i(Et,{devices:e.map(fc),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:a,noun:`device`,showAll:!0})}function mc({devices:e,scope:t,onChange:n,listState:r,savedScope:a,exceptOffered:o}){let s=new Map(e.map(e=>[e.id,e.name]));return i(tc,{draft:t,onChange:n,exceptOffered:o,plural:`devices`,describe:e=>s.get(e)??J.t(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`rule-device-scope`,renderPicker:(t,n,o)=>i(pc,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(o===`only`?a.include:a.exclude).length>0},o)})}function hc(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function gc(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function _c(e){let t=hc(e),n=e.data===void 0?[]:V(e.data.nodes),r=gc(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function vc(e){let t=hc(e),n=e.data===void 0?[]:H(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var yc=[`nc-pickers`,`node-directory`],bc=[`nc-pickers`,`package-list`],xc=6e4,Sc={get hub(){return J.t(`system.scopePickers.roleHub`)},get agent(){return J.t(`system.scopePickers.roleAgents`)}},Cc={get server(){return J.t(`system.scopePickers.pkgServer`)},get framework(){return J.t(`system.scopePickers.pkgFramework`)},get wrapper(){return J.t(`system.scopePickers.pkgWrapper`)},get addon(){return J.t(`system.scopePickers.pkgAddons`)}};function wc(e){let t=Sc[e.type??``]??J.t(`system.scopePickers.roleNodes`);return e.location===`offline`?J.t(`system.scopePickers.offlineSuffix`,{role:t}):t}function Tc(e){return Cc[e.type??``]??J.t(`system.scopePickers.pkgPackages`)}function Ec({value:t,onChange:n,testId:r}){let{t:a}=Y(),o=j().trpcClient,c=s({queryKey:yc,staleTime:xc,queryFn:()=>o.nodes.directory.query()}),l=_c(c);return e(`div`,{children:[i(Et,{devices:l.items,listState:l.listState,fleet:l.fleet,value:t,onChange:n,emptyMeansAll:!0,noun:`node`,groupTitle:wc,...r===void 0?{}:{testId:r}}),c.data?.complete===!1&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:a(`system.scopePickers.theNodeHistoryCouldNot`,`The node history could not be read — offline nodes may be missing from this list.`)})]})}function Dc({value:e,onChange:t,testId:n}){let r=j().trpcClient,a=vc(s({queryKey:bc,staleTime:xc,queryFn:()=>r.addons.listPackages.query()}));return i(Et,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:Tc,...n===void 0?{}:{testId:n}})}var Oc={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-consumable-low`]},template:{body:`{{deviceName}}`}};function kc(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 Ac(e,t){return e===`pending`?`pending`:e===`success`?`current`:kc(t)===`BAD_REQUEST`?`outdated`:`unknown`}function jc(e){let t=j(),n=s({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(Oc)});return e?Ac(n.status,n.error):`pending`}function Mc(e){let t=new Map;for(let n of e)for(let e of n??[])t.has(e.code)||t.set(e.code,{value:e.code,label:e.label,hint:e.severity});return[...t.values()].sort((e,t)=>e.label.localeCompare(t.label))}var Nc=`error`;function Pc(e,t){let n=j(),r=e!==void 0&&e.length>0,i=s({queryKey:[[`deviceManager`,`listDeviceIdsByCaps`],{capNames:[Nc]}],enabled:t&&!r,staleTime:6e4,retry:!1,queryFn:()=>n.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[Nc]})}),a=l({queries:(r?e:i.data??[]).map(e=>({queryKey:[[`error`,`listFaultTypes`],{deviceId:e}],enabled:t,staleTime:6e4,retry:!1,queryFn:async()=>(await n.trpcClient.error.listFaultTypes.query({deviceId:e})).types}))});return{options:Mc(a.map(e=>e.data)),loading:i.isLoading||a.some(e=>e.isLoading)}}c();var Fc=`/system/settings`,Ic=`/system/notifications?tab=alarm`,Lc=`text-primary underline-offset-2 hover:underline`;function Rc(e,t){let n=cr(t);return oi(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function zc({family:t,value:r,cameras:a,allDevices:s,fleet:c,savedHadDevices:l,onChange:u,scheduleOnly:d=!1}){let{t:f}=Y(),p=n(()=>r?.kinds??[],[r]),m=n(()=>s===void 0?a:s.map(fc),[s,a]),h=n(()=>a.map(e=>({id:e.id,name:e.name,type:`camera`})),[a]),g=Tr(t,p),_=Pc(r?.deviceIds,g.faultCodes),v=jc(t===`device-events`),y=t===`alarm`,[b,x]=o(()=>pi(r?.deviceIds,r?.excludeDeviceIds)),[S]=o(()=>pi(r?.deviceIds,r?.excludeDeviceIds)),C=n(()=>{let e=new Map;for(let t of y?h:m)e.set(t.id,t.name);return e},[h,y,m]);return e(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[i(`p`,{className:Fn,"data-testid":`system-event-class-hint`,children:d?f(`system.notificationSystemEventField.summaryClassHint`,`At the scheduled time you get the list of what is in the bad state, not each change.`):f(`system.notificationSystemEventField.instantClassHint`,`A paired event tells you both when it goes wrong and when it comes back.`)}),bi(t).map(n=>e(`div`,{children:[i(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:n.label}),i(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:li(n,d).map(e=>{let n=ei(p,e),a=e.noSnapshot===!0?`${e.label} — ${f(`system.notificationSystemEventField.noSnapshot`,`no state snapshot, reports nothing`)}`:e.label;return i(q,{variant:`unstyled`,type:`button`,role:`checkbox`,"aria-checked":n,"aria-label":a,onClick:()=>u(Ei(r,e,t)),className:n?`rounded-md border border-primary bg-primary/10 px-2 py-1 text-[11px] text-primary`:`rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:a},e.key)})})]},n.id)),t===`device-events`&&e(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-device-alert-settings`,children:[f(`system.notificationSystemEventField.theBatteryThresholdAndThe`,`The battery threshold and the reminder interval are cluster settings (the consumable threshold is this rule’s own, below):`),` `,i(Di,{to:Fc,target:`_blank`,rel:`noreferrer`,className:Lc,children:f(`system.notificationSystemEventField.settingsBatteryOfflineAlerts`,`Settings → Battery & offline alerts`)}),`.`]}),t===`alarm`&&e(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[i(Di,{to:Ic,target:`_blank`,rel:`noreferrer`,className:Lc,children:f(`system.notificationSystemEventField.alarmSettings`,`Alarm settings`)}),p.includes(`alarm-triggered`)&&i(`span`,{className:`ml-1`,children:f(`system.notificationSystemEventField.alarmPictures`)})]}),v===`outdated`&&i(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-hub-outdated`,children:f(`system.notificationSystemEventField.hubOutdated`,{percent:15})}),v===`unknown`&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:f(`system.notificationSystemEventField.couldNotCheckWhetherThis`,`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`)}),g.consumableThreshold&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:f(`system.notificationSystemEventField.consumableLowAt`,`Consumable low at (%)`)}),i(K,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:qn,step:1,placeholder:`15`,value:r?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let t=Ci(e.target.value);t.kind!==`invalid`&&u(oi(r,{consumableLowPercent:t.kind===`set`?t.value:void 0}))}})]}),g.faultCodes&&e(`div`,{"data-testid":`system-event-fault-codes`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.faultCodes`,`Fault codes`)}),i(fr,{options:_.options,value:r?.faultCodes??[],loading:_.loading,onChange:e=>u(oi(r,{faultCodes:e})),emptyHint:f(`system.notificationSystemEventField.faultCodesEmpty`,`No fault codes declared — type one, or leave empty for any fault.`),placeholder:f(`system.notificationSystemEventField.faultCodePlaceholder`,`Fault code… (empty = any fault)`)})]}),g.deviceTypes&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.deviceTypes`,`Device types`)}),i(fr,{options:an,value:r?.deviceTypes??[],onChange:e=>u(oi(r,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:f(`system.notificationSystemEventField.deviceType`,`Device type…`)})]}),Lr(r)&&i(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`battery-device-types-warning`,children:f(`system.notificationSystemEventField.batteryAndConsumableAlertsAre`,`Battery and consumable alerts are narrowed by device type here. Batteries and consumables belong to sensors, containers, vacuums and mowers — rarely to a camera — so a type filter meant for liveness silences them. Leave the types empty, or put these kinds in a rule of their own.`)}),g.devices&&e(`div`,{children:[i(tc,{draft:b,onChange:e=>{x(e),u(Rc(r,e))},exceptOffered:g.excludeDevices,plural:`devices`,describe:e=>C.get(e)??f(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`system-event-device-scope`,renderPicker:(e,t,n)=>i(Et,{devices:y?h:m,listState:c.state,fleet:c,emptyMeansAll:!0,savedHadDevices:(n===`only`?S.include:S.exclude).length>0||n===`only`&&l,noun:y?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),l&&b.mode===`all`&&i(Nt,{noun:y?`camera`:`device`})]}),g.nodes&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.nodes`,`Nodes`)}),i(Ec,{value:r?.nodeIds??[],onChange:e=>u(oi(r,{nodeIds:e})),testId:`system-event-nodes`})]}),g.packages&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.packages`,`Packages`)}),i(Dc,{value:r?.packageNames??[],onChange:e=>u(oi(r,{packageNames:e})),testId:`system-event-packages`})]})]})}function Bc({value:t}){let{t:n}=Y(),r=t?.kinds??[];return e(`div`,{className:`mt-1 rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-mixed`,children:[i(`p`,{children:n(`system.notificationSystemEventField.thisRuleIsNotOne`,`This rule is not one kind of system rule — its events span device events, system and alarm, or it names none. It keeps firing as it is, but it cannot be edited here: recreate it as one rule per kind.`)}),r.length>0&&i(`p`,{className:`mt-1 text-foreground`,children:r.map(jr).join(`, `)})]})}function Vc({family:t,onChange:n}){let{t:r}=Y();return e(`div`,{"data-testid":`system-family-select`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:r(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`)}),i(I,{value:t,"aria-label":r(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`),onChange:e=>{let t=e.target.value;Oe(t)&&n(t)},options:ue.map(e=>({value:e,label:pe(e).label}))}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:r(`system.notificationSystemEventField.oneRuleAnswersOneQuestion`,`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`)})]})}c();function Hc({catalog:t,taxonomy:r,delivery:a,conditions:o,classScope:s,onClassScopeChange:c,actions:l,actionStepsOf:u,savedConditions:d,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x,scheduleOnly:S}){let{t:C}=Y(),w=(e,t)=>{let n={...o};t===void 0?delete n[e]:n[e]=t,b(n)},T=xe({delivery:a,conditions:o}),E=n(()=>t.filter(e=>fe(e,a,T)&&Yr(e.id,o)),[t,a,T,o]),D=n(()=>Ks(E),[E]),O=e=>E.some(t=>t.id===e),k=e=>Wc.has(e.id)?i(dc,{taxonomy:r,scope:s,onChange:c,exceptOffered:O(`classesExclude`)}):Gc.has(e.id)?i(oc,{conditions:o,onConditionsChange:b,exceptOffered:O(`zonesExclude`),cameraIds:m??p,cameras:h}):Kc.has(e.id)?i(sc,{conditions:o,onConditionsChange:b,exceptOffered:O(`identitiesExclude`)}):e.id===`labelEquals`?i(cc,{conditions:o,onConditionsChange:b}):null;return i(`div`,{className:`space-y-4`,children:D.map(t=>e(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${t.id}`,children:[i(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:C(`notificationRules.groups.${t.id}`,t.label)}),t.descriptors.map(t=>{let n=k(t);return e(`div`,{"data-testid":`condition-${t.id}`,children:[i(`label`,{className:X,children:qc(t,C)}),n??i(Xc,{descriptor:t,kind:T,scheduleOnly:S===!0,taxonomy:r,conditions:o,actions:l,actionStepsOf:u,savedConditions:d,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:w,onScheduleChange:x}),Jc(t,C)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Jc(t,C)})]},t.id)})]},t.id))})}function Uc({kinds:t}){let{t:n,i18n:r}=Y(),a=r.language.startsWith(`it`)?`it`:`en`,o=t.flatMap(e=>{let t=Ge(e);return t===void 0?[]:[{kind:e,text:n(`system.notificationRuleConditions.transitionMeaning`,`{{kind}}: starts = {{starts}} · finishes = {{finishes}}`,{kind:be(e,a),starts:t.starts[a],finishes:t.finishes[a],interpolation:{escapeValue:!1}})}]});return o.length===0?null:e(vt,{className:`inline-block`,children:[i(jt,{tabIndex:0,children:i(v,{className:`h-4 w-4 cursor-help text-foreground-subtle`,"aria-label":n(`system.notificationRuleConditions.transitionInfo`,`What start and finish mean`),"data-testid":`nc-sensor-transition-info`})}),i(ht,{className:`left-auto right-0 translate-x-0`,children:i(`ul`,{className:`w-60 space-y-1 whitespace-normal text-left text-[11px]`,children:o.map(e=>i(`li`,{children:e.text},e.kind))})})]})}var Wc=new Set([`classes`,`classesExclude`]),Gc=new Set([`zones`,`zonesExclude`]),Kc=new Set([`identities`,`identitiesExclude`]);function qc(e,t){return Wc.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):Gc.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):Kc.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 Jc(e,t){if(!Yc.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.id===`schedule`?t(`notificationRules.schedule.hint`,`Only fire inside these weekly windows. Leave it empty to fire at any time.`):e.description}var Yc=new Set([...Wc,...Gc,...Kc,`labelEquals`,`crossing`]);function Xc({descriptor:t,kind:n,taxonomy:r,conditions:a,actions:o,actionStepsOf:s,savedConditions:c,schedule:l,deviceIds:u,cameras:d,fleet:f,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v,scheduleOnly:y}){let{t:b}=Y();switch(t.valueType){case`deviceIdList`:{if(!xi(t.id))break;let e=t.id,n=a[e]??[];return i(ir,{cameras:d,fleet:f,emptyMeansAll:!0,savedHadDevices:(c?.[e]?.length??0)>0,value:n,onChange:t=>_(e,t.length>0?t:void 0)})}case`stringList`:{if(!Mr(t.id))break;let e=t.id,n=t=>_(e,t.length>0?t:void 0);if(e===`eventTypeTokens`)return i(wn,{deviceIds:u,cameras:d,...m===void 0?{}:{allDevices:m},value:ti(a,e),onChange:n});let o=Ce(e,r);return o===null?i(Yn,{value:ti(a,e),placeholder:b(`system.notificationRuleConditions.addValue`,`Add value…`),onChange:n}):i(sn,{picker:o,value:ti(a,e),onChange:n})}case`number01`:{if(!hi(t.id))break;let e=t.id;return i(Mn,{value:ui(a,e),min:0,max:1,step:.05,onChange:t=>_(e,t)})}case`number`:{if(!Gr(t.id))break;let e=t.id;return i(Mn,{value:ui(a,e),min:0,step:1,onChange:t=>_(e,t)})}case`sourceSelect`:{if(!wi(t.id))break;let e=t.id;return tl(t,a[e],t=>_(e,t))}case`systemEvent`:{if(!Rr(t.id))break;let e=t.id,r=Ee(n);return r===void 0?i(Bc,{value:a[e]}):i(zc,{family:r,value:a[e],cameras:d,fleet:f,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[e]?.deviceIds?.length??0)>0,onChange:t=>_(e,t),scheduleOnly:y===!0})}case`deviceState`:if(!ii(t.id))break;return i(ur,{gateable:h,value:a.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!kr(t.id))break;return i(yr,{scenes:g,value:a.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!Fr(t.id))break;let e=t.id;return nl(t,a[e],t=>_(e,t))}case`packagePhase`:{if(!si(t.id))break;let e=t.id;return i(I,{value:a[e]??``,options:[{value:``,label:b(`system.notificationRuleConditions.anyPhase`,`— any phase —`)},...xn(t,yn).map(e=>({value:e.value,label:e.label}))],onChange:t=>_(e,el(t.target.value))})}case`sensorTransition`:{if(!Qr(t.id))break;let n=t.id,r=Le({conditions:a,...o===void 0?{}:{actions:o},...s===void 0?{}:{actionStepsOf:s}});return e(p,{children:[e(`div`,{className:`flex items-center gap-2`,children:[i(I,{value:a[n]??``,options:xn(t,Zr).map(e=>({value:e.value,label:e.label})),onChange:e=>_(n,jn(e.target.value))}),i(Uc,{kinds:a.sensorKinds??[]})]}),r&&i(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`nc-sensor-transition-never-fires`,children:`This rule belongs to the alarm, and an alarm rule fires only when an opening OPENS. Set to “only when it clears”, it can never fire.`})]})}case`plateMatcher`:{if(!vi(t.id))break;let e=t.id;return i(pr,{value:a[e],onChange:t=>_(e,t)})}case`occupancy`:{if(!Cr(t.id))break;let e=t.id;return i(gr,{deviceIds:u,cameras:d,classOptions:Zc(r),value:a[e],onChange:t=>_(e,t)})}case`audio`:{if(!on(t.id))break;let e=t.id;return i(sr,{taxonomy:r,value:a[e],onChange:t=>_(e,t)})}case`schedule`:return i(fn,{value:l,onChange:v});default:break}return i(Qc,{descriptor:t,conditions:a})}function Zc(e){let t=Ce(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Qc({descriptor:t,conditions:n}){let{t:r}=Y(),i=Object.entries(n).find(([e])=>e===t.id);return e(`p`,{className:Fn,children:[i!==void 0&&i[1]!==void 0?r(`system.notificationRuleConditions.authoredElsewhereAndPreservedThis`,`Authored elsewhere and preserved — this admin editor cannot change it yet.`):r(`system.notificationRuleConditions.notEditableHereYetThis`,`Not editable here yet — this condition has no admin editor.`),` `,e(`span`,{className:`text-foreground-muted`,children:[`(`,t.valueType,`)`]})]})}function $c(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function el(e){return yn.find(t=>t.value===e)?.value}function tl(e,t,n){return i(I,{value:t??`any`,options:xn(e,ln).map(e=>({value:e.value,label:e.label})),onChange:e=>n($c(e.target.value))})}function nl(e,t,n){return i(Dn,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function rl({catalog:t,delivery:n,conditions:r,onConditionsChange:a}){let{t:o}=Y(),s=xe({delivery:n,conditions:r}),c=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,a(n)},l=e=>t.find(t=>t.id===e&&fe(t,n,s)&&Yr(e,r)),u=l(`source`),d=l(`crossing`);return u===void 0&&d===void 0?null:e(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[u&&wi(u.id)&&e(`div`,{"data-testid":`condition-source`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:qc(u,o)}),tl(u,r.source,e=>c(`source`,e)),Jc(u,o)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Jc(u,o)})]}),d&&Fr(d.id)&&e(`div`,{"data-testid":`condition-crossing`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:qc(d,o)}),nl(d,r.crossing,e=>c(`crossing`,e)),Jc(d,o)!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Jc(d,o)})]})]})}var il=[`notificationRules`,`getRuleLastRuns`],al=3e4;function ol(){let e=j(),t=s({queryKey:il,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:al});return{status:t.status,data:t.data,error:t.error}}var sl={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function cl({cell:t}){let{t:n}=Y();switch(t.kind){case`pending`:return i(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":n(`system.notificationRuleLastRun.lastRunLoading`,`Last run loading`),className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return i(`span`,{"data-testid":`rule-last-run-failed`,title:n(`system.notificationRuleLastRun.lastRunCouldNotBe`,`Last run could not be read: {{reason}}`,{reason:t.reason}),className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.phrase});case`ran`:return e(`span`,{className:`flex items-center gap-1.5`,title:new Date(t.lastAt).toLocaleString(),children:[i(`span`,{"data-testid":`rule-last-run-dot`,title:t.status,className:`inline-block h-2 w-2 rounded-full ${sl[t.status]}`}),i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Bi(t.lastAt)})]})}}function ll({rule:t,onOpenHistory:n}){let{t:r}=Y(),a=r(`system.notificationRuleLastRun.historyThisRuleSDeliveries`,`History — this rule's deliveries`);return e(vt,{children:[i(jt,{children:i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n(t),"aria-label":r(`system.notificationRuleLastRun.historyOf`,`history of {{name}}`,{name:t.name}),children:i(m,{className:`h-3.5 w-3.5`})})}),i(ht,{children:a})]})}c();var ul=[`notificationRules`,`listSnoozes`],dl=[10,30,60,120];function fl({ruleId:t,ruleName:n,exempt:r=!1,variant:a=`icon`}){let{t:s}=Y(),c=j(),l=u(),[d,p]=o(30),[m,h]=o(null),_=f({mutationFn:e=>c.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:t,durationMinutes:e}}),onMutate:()=>h(null),onSuccess:()=>l.invalidateQueries({queryKey:ul}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?a===`icon`?null:i(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`system.notificationRuleSnoozeControl.thisRuleConcernsOrTriggers`,`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`)}):a===`icon`?i(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:_.isPending,onClick:()=>_.mutate(30),title:s(`system.notificationRuleSnoozeControl.silenceThisRuleForIt`,`Silence this rule for {{value1}} — it appears under "Silenced right now"`,{value1:Vn(30)}),"aria-label":s(`system.notificationRuleSnoozeControl.snooze`,`snooze {{ruleName}}`,{ruleName:n}),"data-testid":`nc-rule-snooze-now`,children:_.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(L,{className:`h-3.5 w-3.5`})}):e(`div`,{className:`space-y-1`,children:[e(`div`,{className:`flex items-end gap-2`,children:[i(`div`,{className:`w-32`,children:i(I,{value:String(d),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:dl.map(e=>({value:String(e),label:Vn(e)}))})}),e(q,{size:`sm`,variant:`outline`,type:`button`,disabled:_.isPending,onClick:()=>_.mutate(d),"data-testid":`nc-rule-snooze-now`,children:[_.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(L,{className:`h-3.5 w-3.5`}),s(`system.notificationRuleSnoozeControl.silenceThisRuleNow`,`Silence this rule now`)]})]}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`system.notificationRuleSnoozeControl.opensARealSnoozeWindow`,`Opens a real snooze window right now — distinct from the buttons above, which only choose the durations this rule's NOTIFICATION offers. It appears under "Silenced right now" and can be ended from there.`)}),m!==null&&i(`p`,{className:`text-[10px] text-danger`,children:m})]})}c();function pl(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function ml(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 hl(e,t){let[,n]=o(0);a(()=>{let r=ml(e,t,Date.now());if(r===null)return;let i=setTimeout(()=>n(e=>e+1),Math.max(0,r-Date.now())+50);return()=>clearTimeout(i)},[e,t])}function gl(){let e=j();return s({queryKey:ul,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function _l({rule:t,snoozes:n,exempt:r}){let{t:a}=Y(),o=j(),s=u();hl(n,t.id);let c=pl(n,t.id,Date.now()),l=()=>s.invalidateQueries({queryKey:ul}),d=f({mutationFn:()=>o.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:t.id,durationMinutes:30}}),onSuccess:l}),p=f({mutationFn:async e=>{for(let t of e)await o.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:l});if(r)return null;let m=d.isError||p.isError;return e(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[i(G,{checked:c.length>0,disabled:!t.enabled||d.isPending||p.isPending,onCheckedChange:e=>e?d.mutate():p.mutate(c),"aria-label":a(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,t.name),title:a(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),m&&i(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:a(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var vl=`nc.listPrunes`;function yl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var bl=new Set([`rule`,`timelapse`,`summary`]),xl=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function Sl(e){return typeof e==`string`&&bl.has(e)}function Cl(e){return typeof e==`string`&&xl.has(e)}function wl(e){return e===`device`||e===`target`}function Tl(e){if(!yl(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!Sl(t)||!wl(r)||!Cl(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 El(e){return!yl(e)||!Array.isArray(e.prunes)?null:e.prunes.map(Tl).filter(e=>e!==null)}function Dl(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 Ol(e,t){let n=t(e.at);return e.subjectKind===`device`?J.t(`helpers.notificationPrunes.lastDevice`,{when:n,subject:e.subject}):J.t(`helpers.notificationPrunes.lastTarget`,{when:n,subject:e.subject})}function kl(e){return new Date(e).toLocaleDateString()}function Al({kind:t,ruleId:n,enabled:r,updatedAt:a}){let o=j(),c=s({queryKey:[`pipelineAnalytics`,vl],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>El(await o.trpcClient.addons.custom.mutate({addonId:Xi,action:vl,input:{}}))}).data;if(c==null)return null;let l=Dl(c,t,n,r,a);return l===null?null:e(`div`,{"data-testid":`nc-prune-banner`,className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-foreground`,children:[i(v,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),i(`span`,{children:Ol(l,kl)})]})}var jl=5e3;function Ml({status:t,now:n,name:r}){let{t:a}=Y();if(t.openWindows===null)return e(`p`,{className:`flex items-start gap-1.5`,children:[i(O,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),i(`span`,{"data-testid":`nc-grouped-status-headline`,children:a(`notificationRules.status.grouped.unknown`,{reason:t.reason??``,defaultValue:`Open windows unknown — {{reason}}`})})]});let o=t.openWindows,{windows:s,waiting:c}=Gi(o);return e(p,{children:[e(`p`,{className:`flex items-start gap-1.5`,children:[i(O,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),i(`span`,{"data-testid":`nc-grouped-status-headline`,children:s===0?a(`notificationRules.status.grouped.none`,`No window open`):`${a(`notificationRules.status.grouped.windows`,{count:s,defaultValue_one:`{{count}} open window`,defaultValue_other:`{{count}} open windows`})} · ${a(`notificationRules.status.grouped.waiting`,{count:c,defaultValue:`{{count}} waiting`})}`})]}),o.map(t=>e(`p`,{className:`flex items-start gap-1.5`,children:[i(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),i(`span`,{children:a(`notificationRules.status.grouped.windowLine`,{camera:r(t.deviceId),members:t.members,pending:t.pending,seconds:Math.max(0,Math.ceil((t.closesAt-n)/1e3)),defaultValue:`{{camera}} · {{members}} in the window · {{pending}} waiting · closes within {{seconds}} s`})})]},t.windowKey))]})}function Nl({ruleId:t,cameraName:n}){let{t:r}=Y(),a=j(),o=s({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,t],refetchInterval:jl,queryFn:async()=>Yi(await a.trpcClient.addons.custom.mutate({addonId:Xi,action:Ki,input:{ruleId:t}}))}).data;if(o==null||o.kind===`none`)return null;let c=Date.now(),l=e=>n?.(e)??r(`system.notificationRuleStatus.cameraFallback`,{deviceId:e});return e(`div`,{"data-testid":`nc-rule-status`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[o.kind===`occupancy`&&e(`p`,{className:`flex items-start gap-1.5`,children:[o.unavailable!==void 0||o.warning!==void 0?i(w,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):i(O,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),e(`span`,{children:[i(`span`,{className:`text-foreground`,children:l(o.deviceId)}),` —`,` `,qi(o,c)]})]}),o.kind===`grouped`&&i(Ml,{status:o,now:c,name:l}),o.kind===`timelapse`&&e(p,{children:[o.devices.map(t=>e(`p`,{className:`flex items-start gap-1.5`,children:[i(O,{className:`mt-0.5 h-3 w-3 shrink-0 ${t.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),e(`span`,{children:[Wi(t,l(t.deviceId),c),t.lastArtifact!==void 0&&e(p,{children:[` · `,i(`a`,{className:`text-primary hover:underline`,href:`/${t.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:r(`common.open`)})]})]})]},t.deviceId)),e(`p`,{className:`flex items-start gap-1.5`,children:[i(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),e(`span`,{children:[o.nextWindow===void 0?r(`system.notificationRuleStatus.noFurtherWindowOpensIn`,`No further window opens in the next nine days`):r(`system.notificationRuleStatus.nextWindowOpens`,`Next window opens {{value1}}`,{value1:new Date(o.nextWindow.startMs).toLocaleString()}),o.settleMs>0&&` · ${r(`system.notificationRuleStatus.settled`,{minutes:Math.round(o.settleMs/6e4)})}`]})]})]})]})}function Pl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fl(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Il(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Ll(e){if(!Pl(e))return null;let t=Fl(e,`ruleId`),n=Fl(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=Fl(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:Fl(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Il(e,`targetIds`)}}function Rl(e){if(!Pl(e))return null;let t=Fl(e,`conditionId`),n=Fl(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function zl(e){if(!Pl(e))return;let t=e.split;if(t!==`rule`&&t!==`section`||typeof e.nothingToReport!=`boolean`)return;let n=[];for(let t of Array.isArray(e.sections)?e.sections:[]){if(!Pl(t))continue;let e=Fl(t,`id`),r=t.status;e===void 0||r!==`read`&&r!==`unavailable`||n.push({id:e,status:r,items:typeof t.items==`number`?t.items:0})}let r=[];for(let t of Array.isArray(e.rows)?e.rows:[]){if(!Pl(t))continue;let e=Fl(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 Bl(e){if(!Pl(e))return null;let t=Fl(e,`recordId`),n=Fl(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=Ll(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Rl(t);e!==null&&i.push(e)}let a=Fl(e,`droppedBy`),o=zl(e.stateSummary);return{recordId:t,delivery:n,trigger:Fl(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:Fl(e,`still`)??`none`,notes:Il(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function Vl(e){if(e.stateSummary!==void 0)return Hl(e,e.stateSummary);if(e.droppedBy!==void 0)return J.t(`helpers.notificationRuleTest.dropped`,{reason:e.droppedBy});let t=e.outcomes[0];if(t===void 0)return J.t(`helpers.notificationRuleTest.notCandidate`,{trigger:e.trigger});if(!t.matched)return t.failedCondition===void 0?J.t(`helpers.notificationRuleTest.noMatchOwn`):J.t(`helpers.notificationRuleTest.noMatchCond`,{condition:t.failedCondition});if(t.enqueued===0)return J.t(`helpers.notificationRuleTest.matchedNoQueue`);let n=e.still===`live`?` ${J.t(`helpers.notificationRuleTest.stillLive`)}`:e.still===`unavailable`?` ${J.t(`helpers.notificationRuleTest.stillUnavailable`)}`:e.still===`unattachable`?` ${J.t(`helpers.notificationRuleTest.stillUnattachable`)}`:``;return J.t(`helpers.notificationRuleTest.matched`,{queued:t.enqueued,targets:t.targetIds.length,still:n})}function Hl(e,t){if(t.nothingToReport){let e=t.sections.map(e=>`${e.id}: ${e.status===`unavailable`?J.t(`helpers.notificationRuleTest.unavailable`):J.t(`helpers.notificationRuleTest.noneOpen`)}`).join(`, `);return J.t(`helpers.notificationRuleTest.nothingToReport`,{reads:e})}let n=t.rows.reduce((e,t)=>e+t.enqueued,0),r=e.outcomes[0]?.targetIds.length??0;if(n===0)return J.t(`helpers.notificationRuleTest.summaryNoQueue`);let i=t.rows.flatMap(e=>e.section===void 0?[]:[e.section]).map(e=>`${e} (${String(t.sections.find(t=>t.id===e)?.items??0)})`),a=t.split===`section`?` (${J.t(`helpers.notificationRuleTest.perCategory`,{sections:i.join(`, `)})})`:``;return J.t(`helpers.notificationRuleTest.summaryBuilt`,{queued:n,perCategory:a,targets:r})}c();function Ul({ruleId:t,ruleName:n,fallbackDeviceId:r,variant:a=`icon`,showResult:s=!1,summary:c=!1}){let{t:l}=Y(),u=j(),[d,m]=o(null),[_,v]=o(null),y=f({mutationFn:async()=>Bl(await u.trpcClient.addons.custom.mutate({addonId:Xi,action:Ji,input:{ruleId:t,...c?{summary:!0}:{},...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{m(null),v(null)},onSuccess:e=>m(e),onError:e=>v(e instanceof Error?e.message:`The test could not be run.`)}),b=d===null?_===null?c?l(`system.notificationRuleTestButton.sendSummaryTitle`,`Sends this rule’s state summary now, to every target`):l(`system.notificationRuleTestButton.testNowFiresThisRule`,`Test now — fires this rule and really sends the notification`):_:Vl(d),x=e(q,{size:`sm`,variant:a===`icon`?`ghost`:`outline`,type:`button`,disabled:y.isPending,onClick:()=>y.mutate(),...a===`full`?{title:b}:{},"aria-label":c?l(`system.notificationRuleTestButton.sendSummaryAria`,`send the summary of {{ruleName}} now`,{ruleName:n}):l(`system.notificationRuleTestButton.testNow`,`test {{ruleName}} now`,{ruleName:n}),"data-testid":c?`nc-rule-test-summary`:`nc-rule-test-now`,children:[y.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(h,{className:`h-3.5 w-3.5`}),a===`full`&&(c?l(`system.notificationRuleTestButton.sendSummaryNow`,`Send the summary now`):l(`system.notificationRuleTestButton.testNow2`,`Test now`))]});return e(p,{children:[a===`icon`?e(vt,{children:[i(jt,{children:x}),i(ht,{children:b})]}):x,s&&_!==null&&i(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:_}),s&&d!==null&&e(`div`,{"data-testid":`nc-rule-test-result`,className:`mt-2 space-y-1 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[i(`p`,{className:`text-foreground`,children:Vl(d)}),d.planNotes.map(t=>e(`p`,{className:`flex gap-1.5`,children:[i(w,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),i(`span`,{children:t.note})]},t.conditionId)),d.notes.map(t=>e(`p`,{children:[`· `,t]},t))]})]})}c();var Wl=[`notificationRules`,`listSnoozes`],Gl=3e4;function Kl(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function ql(e){if(e===0)return J.t(`system.notificationSnoozes.remEnding`);if(e<60)return J.t(`system.notificationSnoozes.remMin`,{count:e});let t=Math.floor(e/60),n=e%60;return n===0?J.t(`system.notificationSnoozes.remHour`,{count:t}):J.t(`system.notificationSnoozes.remHourMin`,{hours:t,minutes:n})}function Jl({rules:t}){let{t:r}=Y(),a=j(),o=u(),c=s({queryKey:Wl,refetchInterval:Gl,queryFn:async()=>(await a.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),l=f({mutationFn:e=>a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>o.invalidateQueries({queryKey:Wl})}),d=n(()=>{let e=new Map;for(let n of t)e.set(n.id,n.name);return e},[t]),p=Date.now(),m=(c.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return e(Yt,{className:`p-4`,children:[e(`div`,{className:`flex items-center gap-2 mb-3`,children:[i(L,{className:`h-4 w-4 text-foreground-subtle`}),i(`h3`,{className:`text-sm font-medium text-foreground`,children:r(`system.notificationSnoozes.silencedRightNow`,`Silenced right now`)})]}),m.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`system.notificationSnoozes.nothingIsSilencedASnooze`,`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`)}),i(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:m.map(t=>e(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`text-xs text-foreground truncate`,children:t.scope===`all`?`Everything`:t.scope===`device`?`Camera ${t.deviceId??`?`}`:d.get(t.ruleId??``)??`A rule`}),t.global&&i(U,{variant:`warning`,className:`text-[10px]`,children:r(`common.everyone`)}),t.classes!==void 0&&t.classes.length>0&&i(U,{variant:`info`,className:`text-[10px]`,children:t.classes.join(`, `)}),!t.summary&&i(U,{variant:`default`,className:`text-[10px]`,children:r(`system.notificationSnoozes.noSummary`,`no summary`)})]}),i(`span`,{className:`text-[10px] text-foreground-subtle`,children:r(`system.notificationSnoozes.setBy`,{user:t.userId,remaining:ql(Kl(t,p))})})]}),i(q,{size:`sm`,variant:`outline`,disabled:l.isPending,onClick:()=>l.mutate(t.id),children:r(`system.notificationSnoozes.endNow`,`End now`)})]},t.id))})]})}var Z=`block text-[11px] font-medium text-foreground mb-1`,Yl=`mt-1 text-[10px] text-foreground-subtle`;function Q({title:t,hint:n,children:r}){return e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:t}),n!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:n}),i(`div`,{className:`space-y-3`,children:r})]})}function Xl({problems:t,testId:n=`digest-problems`}){let{t:r}=Y();return t.length===0?null:e(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":n,children:[e(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[i(w,{className:`h-3.5 w-3.5`}),r(`system.notificationDigestFields.thisRuleCouldNeverProduce`,`This rule could never produce anything, so it cannot be saved:`)]}),i(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:t.map(e=>i(`li`,{children:e},e))})]})}function Zl({warnings:t,testId:n=`digest-warnings`}){let{t:r}=Y();return t.length===0?null:e(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":n,children:[e(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[i(v,{className:`h-3.5 w-3.5`}),r(`system.notificationDigestFields.worthKnowing`,`Worth knowing:`)]}),i(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:t.map(e=>i(`li`,{children:e},e))})]})}function Ql({cameras:t,value:n,onChange:r,fleet:a,hint:o}){return e(`div`,{className:`space-y-1`,children:[i(Et,{devices:t,listState:a.state,fleet:a,value:n,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),o!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:o})]})}function $l(e){let{t}=Y();return i(mt,{...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 eu({label:t,value:n,onChange:r,min:a,max:o,step:s,hint:c,emptyPlaceholder:l,testId:u,disabled:d=!1}){return e(`div`,{children:[i(`label`,{className:Z,children:t}),i(K,{type:`number`,value:n===void 0?``:String(n),disabled:d,...a===void 0?{}:{min:a},...o===void 0?{}:{max:o},...s===void 0?{}:{step:s},...l===void 0?{}:{placeholder:l},...u===void 0?{}:{"data-testid":u},onChange:e=>{let t=e.target.value.trim();if(t.length===0){r(void 0);return}let n=Number(t);Number.isFinite(n)&&r(n)}}),c!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:c})]})}function tu({label:t,checked:n,onChange:r,hint:a,testId:o}){return e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(G,{checked:n,onCheckedChange:r,"aria-label":t,...o===void 0?{}:{"data-testid":o}}),t]}),a!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function nu({title:t,body:n,onTitleChange:r,onBodyChange:a,family:o,testIdPrefix:s}){let{t:c}=Y(),l=ms(),u=e=>l.data?us(l.data,{family:o,field:e}):void 0;return e(`div`,{className:`space-y-2`,children:[i(vs,{label:c(`system.notificationDigestFields.notificationTitle`,`Notification title`),value:t,onChange:r,vars:u(`title`),testId:`${s}-title`}),i(vs,{label:c(`system.notificationDigestFields.notificationBody`,`Notification body`),value:n,onChange:a,vars:u(`body`),multiline:!0,testId:`${s}-body`}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`system.notificationDigestFields.leaveBothBlankToUse`,`Leave both blank to use the hub's own wording (editable on the Texts tab).`)}),i(ys,{context:{family:o,field:`body`},title:t,body:n,testId:`${s}-preview`})]})}function ru({open:t,ruleName:n,windowDescription:r,targetDescription:a,pending:o,onConfirm:s,onCancel:c,extra:l,confirmDisabled:u=!1}){let{t:d}=Y();return t?i(xt,{open:!0,onOpenChange:e=>!e&&c(),children:i(Xt,{width:`sm`,children:e(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[i(h,{className:`h-4 w-4 text-warning`}),d(`system.notificationDigestFields.sendARealNotificationNow`,`Send a real notification now?`)]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:d(`system.notificationDigestFields.confirmSend`,{rule:n,window:r,target:a})}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:d(`system.notificationDigestFields.itDoesNotConsumeThe`,`It does not consume the schedule: the next scheduled run still happens.`)}),l,e(`div`,{className:`flex justify-end gap-2`,children:[i(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:d(`common.cancel`,`Cancel`)}),i(q,{size:`sm`,type:`button`,disabled:o||u,onClick:s,"data-testid":`digest-test-confirm-send`,children:o?d(`system.notificationDigestFields.sending`,`Sending…`):d(`system.notificationDigestFields.produceAndSend`,`Produce and send`)})]})]})})}):null}function iu(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 au=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function ou(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function su(e){let t=e.windows[0];if(t===void 0)return J.t(`helpers.notificationDigest.noWindow`);let n=t.days.toSorted((e,t)=>e-t).map(e=>au[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${ou(t.startMinute)}–${ou(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function cu(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return J.t(`helpers.notificationDigest.ago`,{duration:iu(Math.round(r/1e3))})}function lu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function uu(e){return Array.isArray(e)?`[${e.map(uu).join(`,`)}]`:lu(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${uu(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function du(e,t){return uu(e)===uu(t)}function fu(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,pu=`nc.getTexts`,mu=`nc.setLanguage`,hu=`nc.setTextOverrides`,gu={en:`English`,it:`Italiano`};function _u(e){return e===`en`||e===`it`}function vu(e){return e===`override`||e===`shipped`||e===`fallback`}function yu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bu(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 xu(e){if(!yu(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`||!_u(r)||!vu(o)||i!==null&&typeof i!=`string`)return null;let s=bu(e.placeholders),c=bu(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 Su(e){if(!yu(e))return null;let{language:t,activeLanguage:n}=e;if(!_u(t)||!_u(n))return null;let r=bu(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)_u(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=xu(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Cu(e,t){return t.get(e.key)??e.override??e.shipped}function wu(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 Tu(e,t){return Object.keys(wu(e,t)).length}function Eu(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 Du(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Ou(e){return e.pluralCategories.length===0?null:J.t(`helpers.notificationTexts.pluralWarning`,{categories:e.pluralCategories.join(`, `)})}function ku(e){if(!Array.isArray(e))return;let t=e.filter(e=>typeof e==`string`);return t.length>0?t:void 0}function Au(e){return e.length>0?{tags:[...e]}:{}}function ju(e,t){let n=$e(e),r=$e(t??[]);return n.length===r.length&&n.every((e,t)=>e===r[t])?{}:{tags:[...e]}}var Mu=[`notificationCalendarEvents`,`list`],Nu=`nc.listCalendarEventsRules`,Pu=`nc.upsertCalendarEventsRule`,Fu=`nc.deleteCalendarEventsRule`,Iu=at({timezone:nt().min(1),windows:ot(at({days:ot(tt().int().min(0).max(6)).min(1),startMinute:tt().int().min(0).max(1439),endMinute:tt().int().min(0).max(1439)})).min(1),invert:it().optional()}),Lu=at({targetId:nt().min(1),params:rt(nt(),st()).optional()}),Ru=at({rules:ot(at({id:nt().min(1),name:nt().min(1),enabled:it(),schedule:Iu,calendars:ot(nt().min(1)).max(64).optional(),calendarsExclude:ot(nt().min(1)).max(64).optional(),horizonDays:tt().int(),deliverEmpty:it(),targets:ot(Lu).min(1),template:at({title:nt().optional(),body:nt().optional()}).optional(),priority:tt().int(),targetOverrides:Ze.optional(),generatedAt:tt().optional(),readOnly:it().optional(),tags:ot(nt()).optional()}))});function zu(e){let t=Ru.safeParse(e);return t.success?t.data.rules:null}function Bu(e){return e.readOnly!==!0}var Vu=[{key:`basics`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_basics`)}},{key:`schedule`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_schedule`)}},{key:`calendars`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_calendars`)}},{key:`targets`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_targets`)}},{key:`template`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_template`)}}],Hu=`basics`;function Uu(){return le([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function Wu(e){let t=me(e);if(t===null||t.length===0)return su(e);let n=t[0];if(n===void 0)return su(e);let r=String(Math.floor(n.minute/60)).padStart(2,`0`),i=String(n.minute%60).padStart(2,`0`),a=t.length>1?` +${t.length-1}`:``;return J.t(`helpers.notificationCalendarEvents.scheduleAt`,{time:`${r}:${i}`,more:a})}function Gu(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:Uu(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``,targetOverrides:{},tags:[]}}function Ku(e){return{name:e.name,enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,calendars:e.calendars??[],calendarsExclude:e.calendarsExclude??[],targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,targetOverrides:e.targetOverrides??{},tags:[...e.tags??[]]}}function qu(e){return e.name.trim().length>0&&e.targetIds.length>0&&e.horizonDays>=1&&e.horizonDays<=30&&e.schedule.windows.length>0}function Ju(e,t){let n=Nr(e.targetIds,e.targetOverrides,t),r=e.targetIds.map(e=>({targetId:e}));return{name:e.name.trim(),enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,...e.calendars.length>0?{calendars:[...e.calendars]}:{},...e.calendarsExclude.length>0&&e.calendars.length===0?{calendarsExclude:[...e.calendarsExclude]}:{},targets:r,...Object.keys(n).length>0?{targetOverrides:n}:{},...Au(e.tags),...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 Yu(e,t,n){let{tags:r,...i}=Ju(e,n);return{...i,...ju(e.tags,t.tags),...i.targetOverrides===void 0&&Object.keys(t.targetOverrides??{}).length>0?{targetOverrides:{}}:{},calendars:e.calendars.length===0&&(t.calendars?.length??0)>0?null:i.calendars,calendarsExclude:e.calendarsExclude.length===0&&(t.calendarsExclude?.length??0)>0?null:i.calendarsExclude,template:e.templateTitle.trim().length===0&&e.templateBody.trim().length===0&&t.template!==void 0?null:i.template}}function Xu(e){return J.t(`helpers.notificationCalendarEvents.horizon`,{count:e})}function Zu(e){return e.calendars!==void 0&&e.calendars.length>0?J.t(`helpers.notificationCalendarEvents.calendars`,{count:e.calendars.length}):e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?J.t(`helpers.notificationCalendarEvents.allExcept`,{count:e.calendarsExclude.length}):J.t(`helpers.notificationCalendarEvents.allCalendars`)}c();function Qu({rule:t,targets:n,onSaved:r,onCancel:a}){let{t:s}=Y(),c=j(),l=qt(),[u,d]=o(()=>t===null?Gu():Ku(t)),[p,m]=o(()=>pi(t===null?void 0:t.calendars,t===null?void 0:t.calendarsExclude)),[h,_]=o(Hu),[v,y]=o(null),b=e=>d(t=>({...t,...e})),x=Ls(),S=Ur(Vr(n),x),C=f({mutationFn:async()=>{let e=cr(p),n={...u,calendars:e.include??[],calendarsExclude:e.exclude??[]};if(!qu(n))throw Error(`Name, at least one target, and a schedule are required`);let r=t===null?{rule:Ju(n,S)}:{ruleId:t.id,patch:Yu(n,t,S)};await c.trpcClient.addons.custom.mutate({addonId:$,action:Pu,input:r})},onSuccess:()=>r(),onError:e=>{y(e instanceof Error?e.message:String(e))}}),w=(l.data??[]).map(e=>({id:e.id,name:e.name}));return i(xt,{open:!0,onOpenChange:e=>!e&&a(),children:e(Xt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendar-events-editor`,children:[e(`div`,{className:`mb-3 flex shrink-0 items-center justify-between gap-2 pr-10`,children:[e(`div`,{className:`flex min-w-0 items-center gap-2`,children:[i(ne,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:t===null?s(`system.notificationCalendarEventsEditor.newCalendarEvents`,`New calendar events`):u.name})]}),i(q,{size:`sm`,type:`button`,disabled:C.isPending,onClick:()=>{y(null),C.mutateAsync()},"data-testid":`calendar-events-save`,children:C.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):s(`common.save`,`Save`)})]}),e(Qt,{value:h,onValueChange:e=>{let t=Vu.find(t=>t.key===e);t!==void 0&&_(t.key)},children:[i(Kt,{className:`mb-3`,children:Vu.map(e=>i($t,{value:e.key,children:e.label},e.key))}),e(wt,{className:`space-y-4 pr-1`,children:[v===null?null:i(`p`,{className:`text-sm text-destructive`,children:v}),i(W,{value:`basics`,className:`space-y-3`,children:e(Q,{title:s(`system.notificationCalendarEventsEditor.basics`,`Basics`),children:[e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.name`,`Name`),i(K,{className:`mt-1`,value:u.name,onChange:e=>b({name:e.target.value}),"data-testid":`calendar-events-name`})]}),e(`div`,{children:[i(`span`,{className:`mb-1 block text-sm`,children:s(`common.tags`,`Tags`)}),i(Ht,{value:u.tags,onChange:e=>b({tags:e}),label:s(`common.tags`,`Tags`)})]}),i(eu,{label:s(`system.notificationCalendarEventsEditor.horizonDays`,`Horizon (days)`),value:u.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&b({horizonDays:e})}}),i(eu,{label:s(`system.notificationCalendarEventsEditor.priority`,`Priority`),value:u.priority,min:1,max:5,onChange:e=>{e!==void 0&&b({priority:e})}}),i(tu,{label:s(`system.notificationCalendarEventsEditor.enabled`,`Enabled`),checked:u.enabled,onChange:e=>b({enabled:e})}),i(tu,{label:s(`system.notificationCalendarEventsEditor.deliverWhenEmpty`,`Deliver when empty`),checked:u.deliverEmpty,onChange:e=>b({deliverEmpty:e})})]})}),i(W,{value:`schedule`,className:`space-y-3`,children:e(Q,{title:s(`system.notificationCalendarEventsEditor.schedule`,`Schedule`),children:[i(fn,{mode:`times`,value:u.schedule,onChange:e=>b({schedule:e})}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:s(`system.notificationCalendarEventsEditor.oneSendTimePerRow`,`One send time per row. The digest fires at that minute.`)})]})}),i(W,{value:`calendars`,className:`space-y-3`,children:i(Q,{title:s(`system.notificationCalendarEventsEditor.calendars`,`Calendars`),children:i(tc,{draft:p,onChange:m,exceptOffered:!0,plural:`calendars`,describe:e=>w.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>i(Et,{devices:w,listState:l.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),i(W,{value:`targets`,className:`space-y-3`,children:i(Q,{title:s(`system.notificationCalendarEventsEditor.targets`,`Targets`),children:i($l,{targets:n,value:u.targetIds,onChange:e=>b({targetIds:e})})})}),i(W,{value:`template`,className:`space-y-3`,children:e(Q,{title:s(`system.notificationCalendarEventsEditor.template`,`Template`),children:[e(`p`,{className:`text-[11px] text-foreground-subtle`,children:[s(`system.notificationCalendarEventsEditor.optionalLeaveBlankForThe`,`Optional. Leave blank for the default digest body (tomorrow highlighted, then later days). Variables:`),` `,s(`system.notificationCalendarEventsEditor.templateVars`,{ruleVar:`{{rule}}`,countVar:`{{count}}`,horizonVar:`{{horizonDays}}`,eventsVar:`{{events}}`})]}),e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.title`,`Title`),i(K,{className:`mt-1`,value:u.templateTitle,onChange:e=>b({templateTitle:e.target.value})})]}),e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.body`,`Body`),i(zt,{className:`mt-1 min-h-[8rem] w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:u.templateBody,onChange:e=>b({templateBody:e.target.value})})]}),i(Rs,{surface:`calendar-events`,targetIds:u.targetIds,targets:n,overrides:u.targetOverrides,rulePriority:u.priority,onChange:e=>b({targetOverrides:e})})]})})]})]})]})})}var $u=`nc.listSummaryRules`,ed=`nc.upsertSummaryRule`,td=`nc.deleteSummaryRule`,nd=`nc.testSummaryRule`,rd=3600,id=86400,ad=3600,od=3600,sd=3*36e5,cd=[`importance`,`recency`,`dwell`],ld={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},ud=[`none`,`tiles`,`all`],dd=`none`,fd={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},pd=[`en`,`it`],md=[`deliver-without-text`,`skip`],hd=2048,gd=2e3;function _d(e){return e.window.kind!==`unsupported`&&!e.readOnly}function vd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yd(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 bd(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 xd(e){if(e!==void 0)return typeof e==`string`?e:null}function Sd(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function Cd(e){return cd.some(t=>t===e)}function wd(e){return e===void 0?dd:ud.find(t=>t===e)??null}function Td(e){if(!vd(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!vd(n))return null;let e=yd(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=xd(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 Ed(e){if(!vd(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=Td(e.schedule);return t===null?null:{kind:`schedule`,schedule:t}}if(e.kind===`motion`){let t=e.quietSeconds,n=e.maxWindowSeconds;return typeof t!=`number`||typeof n!=`number`?null:{kind:`motion`,quietSeconds:t,maxWindowSeconds:n}}return{kind:`unsupported`,raw:e.kind}}function Dd(e){if(e==null)return;if(!vd(e))return null;let t=e.classes===void 0?void 0:bd(e.classes),n=e.classesExclude===void 0?void 0:bd(e.classesExclude),r=e.zones===void 0?void 0:bd(e.zones);if(t===null||n===null||r===null)return null;let i=Sd(e.minImportance),a=Sd(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 Od(e){if(e==null)return;if(!vd(e))return null;let t=xd(e.title),n=xd(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function kd(e){return pd.some(t=>t===e)}function Ad(e){return md.some(t=>t===e)}function jd(e){if(e==null)return;if(!vd(e)||typeof e.enabled!=`boolean`)return null;let t=xd(e.profileId),n=xd(e.prompt);if(t===null||n===null)return null;let r=Sd(e.maxImagePx),i=Sd(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!kd(a))return null;let o=e.onFailure;return o!==void 0&&!Ad(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 Md(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!vd(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!vd(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function Nd(e){if(e===void 0)return;let t=Ze.safeParse(e);return t.success?t.data:null}function Pd(e){if(!vd(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`||!Cd(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=yd(e.deviceIds),u=Ed(e.window),d=Md(e.targets);if(l===null||u===null||d===null)return null;let f=Dd(e.filters),p=Od(e.template);if(f===null||p===null)return null;let m=xd(e.captionText),h=Sd(e.generatedAt),g=Sd(e.updatedAt);if(m===null||h===null||g===null)return null;let _=wd(e.captions);if(_===null)return null;let v=jd(e.ai);if(v===null)return null;let y=Nd(e.targetOverrides);if(y===null)return null;let b=ku(e.tags);return{id:t,name:n,enabled:r,deviceIds:l,window:u,...f===void 0?{}:{filters:f},maxTiles:i,maxAiImages:a,rank:o,barrierSeconds:s,targets:d,...p===void 0?{}:{template:p},captions:_,...m===void 0?{}:{captionText:m},deliverEmpty:c,priority:e.priority,...y===void 0?{}:{targetOverrides:y},...h===void 0?{}:{generatedAt:h},...g===void 0?{}:{updatedAt:g},readOnly:e.readOnly===!0,...v===void 0?{}:{ai:v},...b===void 0?{}:{tags:b}}}function Fd(e){if(!vd(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=Pd(n);if(e===null)return null;t.push(e)}return t}function Id(e){if(!vd(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=Sd(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=Sd(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=xd(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 Ld(){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:dd,captionText:``,deliverEmpty:!1,priority:3,targetOverrides:{},aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`,tags:[]}}function Rd(e){let t=Ld(),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),tags:[...e.tags??[]],templateTitle:e.template?.title??``,templateBody:e.template?.body??``,mosaicCaptions:e.captions,captionText:e.captionText??``,deliverEmpty:e.deliverEmpty,priority:e.priority,targetOverrides:e.targetOverrides??{},aiEnabled:e.ai?.enabled??t.aiEnabled,aiProfileId:e.ai?.profileId??``,aiPrompt:e.ai?.prompt??``,aiLanguage:e.ai?.language??``,aiMaxImagePx:e.ai?.maxImagePx,aiTimeoutSeconds:e.ai?.timeoutMs===void 0?void 0:Math.round(e.ai.timeoutMs/1e3),aiOnFailure:e.ai?.onFailure??t.aiOnFailure}}function zd(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Bd(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 Vd(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 Hd(e){return fu(e.targetIds)}function Ud(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 Wd(e,t){let n=Bd(e),r=Vd(e),i=Ud(e),a=e.captionText.trim(),o=Nr(e.targetIds,e.targetOverrides,t);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:zd(e),...n===void 0?{}:{filters:n},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Hd(e),...r===void 0?{}:{template:r},captions:e.mosaicCaptions,...a.length>0?{captionText:a}:{},deliverEmpty:e.deliverEmpty,priority:e.priority,...Object.keys(o).length>0?{targetOverrides:o}:{},...i===void 0?{}:{ai:i},...Au(e.tags)}}function Gd(e,t,n){let r=Wd(e,n),i={};return r.name!==t.name&&(i.name=r.name),r.enabled!==t.enabled&&(i.enabled=r.enabled),du(r.deviceIds,t.deviceIds)||(i.deviceIds=r.deviceIds),du(r.window,t.window)||(i.window=r.window),du(r.filters,t.filters)||(i.filters=r.filters??null),r.maxTiles!==t.maxTiles&&(i.maxTiles=r.maxTiles),r.maxAiImages!==t.maxAiImages&&(i.maxAiImages=r.maxAiImages),r.rank!==t.rank&&(i.rank=r.rank),r.barrierSeconds!==t.barrierSeconds&&(i.barrierSeconds=r.barrierSeconds),du(r.targets,t.targets)||(i.targets=r.targets),du(r.template,t.template)||(i.template=r.template??null),r.captions!==t.captions&&(i.captions=r.captions),(r.captionText??``)!==(t.captionText??``)&&(i.captionText=r.captionText??``),r.deliverEmpty!==t.deliverEmpty&&(i.deliverEmpty=r.deliverEmpty),r.priority!==t.priority&&(i.priority=r.priority),du(r.targetOverrides??{},t.targetOverrides??{})||(i.targetOverrides=r.targetOverrides??{}),du(r.ai,t.ai)||(i.ai=r.ai??null),{...i,...ju(e.tags,t.tags)}}function Kd(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 ${rd}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${id}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 ${ad}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 ${od}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 ${gd} 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 ${hd} 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 qd(e){return Kd(e).length===0}function Jd(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 Yd=[{key:`rule`,get label(){return J.t(`helpers.notificationSummaries.tab_rule`)},fields:[`name`,`enabled`,`tags`,`deviceIds`]},{key:`window`,get label(){return J.t(`helpers.notificationSummaries.tab_window`)},fields:[`windowKind`,`schedule`,`quietSeconds`,`maxWindowSeconds`,`barrierSeconds`]},{key:`content`,get label(){return J.t(`helpers.notificationSummaries.tab_content`)},fields:[`classes`,`classesExclude`,`zones`,`minImportance`,`minDwellSeconds`,`includeStationary`]},{key:`mosaic`,get label(){return J.t(`helpers.notificationSummaries.tab_mosaic`)},fields:[`maxTiles`,`rank`,`mosaicCaptions`,`captionText`]},{key:`ai`,label:`AI`,fields:[`aiEnabled`,`aiProfileId`,`aiPrompt`,`aiLanguage`,`aiMaxImagePx`,`aiTimeoutSeconds`,`aiOnFailure`,`maxAiImages`]},{key:`delivery`,get label(){return J.t(`helpers.notificationSummaries.tab_delivery`)},fields:[`targetIds`,`priority`,`deliverEmpty`,`templateTitle`,`templateBody`,`targetOverrides`]}],Xd=`rule`;function Zd(e){return Yd.find(t=>t.key===e)?.key}function Qd(e){return e.kind===`motion`?J.t(`helpers.notificationSummaries.winMotion`,{quiet:iu(e.quietSeconds),max:iu(e.maxWindowSeconds)}):e.kind===`unsupported`?J.t(`helpers.notificationSummaries.winUnsupported`,{raw:e.raw}):J.t(`helpers.notificationSummaries.winSchedule`,{schedule:su(e.schedule)})}function $d(e,t){return cu(e,t,`Never run`)}function ef(e){if(e===void 0)return J.t(`helpers.notificationSummaries.allPassages`);let t=[];return e.classes!==void 0&&e.classes.length>0&&t.push(e.classes.join(`, `)),e.classesExclude!==void 0&&e.classesExclude.length>0&&t.push(J.t(`helpers.notificationSummaries.filterNot`,{classes:e.classesExclude.join(`, `)})),e.zones!==void 0&&e.zones.length>0&&t.push(J.t(`helpers.notificationSummaries.filterZones`,{count:e.zones.length})),e.minImportance!==void 0&&t.push(J.t(`helpers.notificationSummaries.filterImportance`,{value:e.minImportance})),e.minDwellSeconds!==void 0&&t.push(J.t(`helpers.notificationSummaries.filterStay`,{value:iu(e.minDwellSeconds)})),e.includeStationary===!0&&t.push(J.t(`helpers.notificationSummaries.filterParked`)),t.length===0?J.t(`helpers.notificationSummaries.allPassages`):t.join(` · `)}function tf(e){return{windowStartMs:e-sd,windowEndMs:e}}c();var nf={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},rf={en:`English`,it:`Italiano`};function af(e){return cd.find(t=>t===e)}function of(e){return ud.find(t=>t===e)}function sf(e){return pd.find(t=>t===e)??``}function cf(e){return md.find(t=>t===e)}function lf({rule:t,cameras:r,fleet:a,targets:s,taxonomy:c,onSaved:l,onCancel:u}){let{t:d}=Y(),p=j(),[m,h]=o(()=>t===null?Ld():Rd(t)),[_,v]=o(null),[y,b]=o(t!==null),[x,S]=o(Xd),C=e=>h(t=>({...t,...e})),w=n(()=>{let e=Ce(`occupancy`,c);return e===null?[]:e.groups.flatMap(e=>e.options)},[c]),{options:T,loading:E}=Jn(m.deviceIds,r.map(e=>({id:e.id,name:e.name}))),D=gt({functionCap:`llm`}),O=(D.data??[]).filter(Qi),k=Ls(),A=Ur(Vr(s),k),ee=f({mutationFn:async()=>{let e=t===null?{rule:Wd(m,A)}:{ruleId:t.id,patch:Gd(m,t,A)};await p.trpcClient.addons.custom.mutate({addonId:$,action:ed,input:e})},onSuccess:l,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),M=ms(),N=M.data?us(M.data,{family:`summary`,field:`captionText`}):void 0,P=m.mosaicCaptions===`all`,F=Kd(m),te=Jd(m),L=Yd.some(e=>e.key===x)?x:Xd;return i(xt,{open:!0,onOpenChange:e=>!e&&u(),children:e(Xt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:e(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[i(lt,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`span`,{className:`truncate`,children:t===null?d(`system.notificationSummaryEditor.newSummary`,`New summary`):d(`system.notificationSummaryEditor.edit`,`Edit {{name}}`,{name:t.name})})]})}),_!==null&&i(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),e(`div`,{className:`shrink-0 space-y-2`,children:[t!==null&&i(Al,{kind:`summary`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt??1/0}),y?i(Xl,{problems:F,testId:`summary-problems`}):null,i(Zl,{warnings:te,testId:`summary-warnings`})]}),e(Qt,{value:L,onValueChange:e=>S(Zd(e)??x),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[i(Kt,{className:`mb-3 shrink-0`,children:Yd.map(e=>i($t,{value:e.key,children:e.label},e.key))}),e(wt,{className:`pr-1`,children:[e(W,{value:`rule`,className:`space-y-3`,children:[e(Q,{title:d(`system.notificationSummaryEditor.whatItIs`,`What it is`),hint:d(`system.notificationSummaryEditor.oneWindowOnePictureThe`,`One window, one picture: the best shot of every track the window held, laid out as one mosaic and delivered once.`),children:[e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.name`,`Name`)}),i(K,{value:m.name,onChange:e=>C({name:e.target.value}),placeholder:d(`system.notificationSummaryEditor.eGOvernightSweep`,`e.g. Overnight sweep`),"data-testid":`summary-name`})]}),i(`div`,{className:`pb-1.5`,children:i(tu,{label:d(`system.notificationSummaryEditor.enabled`,`Enabled`),checked:m.enabled,onChange:e=>C({enabled:e}),testId:`summary-enabled`})})]}),e(`div`,{children:[i(`span`,{className:Z,children:d(`common.tags`,`Tags`)}),i(Ht,{value:m.tags,onChange:e=>C({tags:e}),label:d(`common.tags`,`Tags`)})]})]}),i(Q,{title:d(`system.notificationSummaryEditor.cameras`,`Cameras`),hint:d(`system.notificationSummaryEditor.everyCameraInTheDigest`,`Every camera in the digest gets at least one tile when it contributed anything — a digest in which two of six cameras never appear is not multi-camera.`),children:i(Ql,{cameras:r,value:m.deviceIds,fleet:a,onChange:e=>C({deviceIds:e}),hint:d(`system.notificationSummaryEditor.theFirstCameraSelectedOwns`,`The first camera selected owns the delivered notification.`)})})]}),i(W,{value:`window`,className:`space-y-3`,children:e(Q,{title:d(`system.notificationSummaryEditor.whenTheWindowCloses`,`When the window closes`),children:[e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.window`,`Window`)}),i(I,{value:m.windowKind,options:[{value:`motion`,label:d(`system.notificationSummaryEditor.motionOpenedAndClosedBy`,`Motion — opened and closed by activity`)},{value:`schedule`,label:d(`system.notificationSummaryEditor.scheduleFixedWeeklyWindows`,`Schedule — fixed weekly windows`)}],onChange:e=>C({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),m.windowKind===`motion`?e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(eu,{label:d(`system.notificationSummaryEditor.quietPeriodSeconds`,`Quiet period (seconds)`),value:m.quietSeconds,min:30,max:rd,onChange:e=>C({quietSeconds:e??0}),hint:d(`system.notificationSummaryEditor.theWindowOpensOnThe`,`The window opens on the first motion on any of these cameras and stays open while more arrives. This much silence closes it.`),testId:`summary-quiet`}),i(eu,{label:d(`system.notificationSummaryEditor.longestWindowSeconds`,`Longest window (seconds)`),value:m.maxWindowSeconds,min:60,max:id,onChange:e=>C({maxWindowSeconds:e??0}),hint:d(`system.notificationSummaryEditor.aPermanentlyBusyDrivewayWould`,`A permanently busy driveway would otherwise never deliver. At this bound the window closes with whatever it holds.`),testId:`summary-max-window`})]}):e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.weeklyWindows`,`Weekly windows`)}),i(fn,{value:m.schedule,onChange:e=>C({schedule:e})}),i(`p`,{className:Yl,children:d(`system.notificationSummaryEditor.theDigestIsProducedWhen`,`The digest is produced when a window CLOSES, and covers exactly that window. The first one is the first window that closes after you save — nothing is backfilled.`)})]}),i(eu,{label:d(`system.notificationSummaryEditor.waitForOpenTracksSeconds`,`Wait for open tracks (seconds)`),value:m.barrierSeconds,min:0,max:ad,onChange:e=>C({barrierSeconds:e??0}),hint:d(`system.notificationSummaryEditor.aTrackSBestShot`,`A track's best shot is written when the track ENDS. Rendering the instant the window closes would show every still-moving subject with no picture. 0 disables the wait.`),testId:`summary-barrier`})]})}),i(W,{value:`content`,className:`space-y-3`,children:e(Q,{title:d(`system.notificationSummaryEditor.whatGoesIn`,`What goes in`),hint:d(`system.notificationSummaryEditor.evaluatedOnTracksOnePassage`,`Evaluated on tracks: one passage is one tile.`),children:[e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.classes`,`Classes`)}),i(fr,{options:w,value:m.classes,onChange:e=>C({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),i(`p`,{className:Yl,children:d(`system.notificationSummaryEditor.emptyEveryClassOnlyThe`,`Empty = every class. Only the macro classes are offered: a digest matches the class stored on the track, and tracks store macros — a sub-type would match nothing, forever.`)})]}),e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.excludedClasses`,`Excluded classes`)}),i(fr,{options:w,value:m.classesExclude,onChange:e=>C({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.zones`,`Zones`)}),i(fr,{options:T,value:m.zones,onChange:e=>C({zones:e}),loading:E,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),i(`p`,{className:Yl,children:d(`system.notificationSummaryEditor.zonesAreScopedPerCamera`,`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(eu,{label:d(`system.notificationSummaryEditor.minimumImportance`,`Minimum importance`),value:m.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>C({minImportance:e}),hint:d(`system.notificationSummaryEditor.thePipelineSOwnScore`,`The pipeline's own score, 0–1. Empty keeps everything.`),testId:`summary-min-importance`}),i(eu,{label:d(`system.notificationSummaryEditor.minimumStaySeconds`,`Minimum stay (seconds)`),value:m.minDwellSeconds,min:0,max:od,emptyPlaceholder:`any`,onChange:e=>C({minDwellSeconds:e}),hint:d(`system.notificationSummaryEditor.dropsThePassagesTooBrief`,`Drops the passages too brief to be worth a tile.`),testId:`summary-min-dwell`})]}),i(tu,{label:d(`system.notificationSummaryEditor.includeParkedObjects`,`Include parked objects`),checked:m.includeStationary,onChange:e=>C({includeStationary:e}),hint:d(`system.notificationSummaryEditor.offByDefaultACar`,`Off by default. A car left in the drive is tracked until it is recognised as parked, and it stays parked for as long as it is there — with this on, a digest fills up with the same stationary object instead of the passages. Parked objects remain on the Events page either way.`),testId:`summary-include-stationary`})]})}),i(W,{value:`mosaic`,className:`space-y-3`,children:e(Q,{title:d(`system.notificationSummaryEditor.theMosaic`,`The mosaic`),children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(eu,{label:d(`system.notificationSummaryEditor.tiles`,`Tiles`),value:m.maxTiles,min:1,max:24,onChange:e=>C({maxTiles:e??1}),hint:d(`system.notificationSummaryEditor.9A33Grid`,`9 (a 3×3 grid) is the most a phone lock-screen thumbnail can carry and still be read.`),testId:`summary-max-tiles`}),e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.whenThereAreMoreTracks`,`When there are more tracks than tiles`)}),i(I,{value:m.rank,options:cd.map(e=>({value:e,label:ld[e]})),onChange:e=>{let t=af(e.target.value);t!==void 0&&C({rank:t})},"data-testid":`summary-rank`}),i(`p`,{className:Yl,children:d(`system.notificationSummaryEditor.everyContributingCameraKeepsIts`,`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`)})]})]}),e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.textOnTheMosaic`,`Text on the mosaic`)}),i(I,{value:m.mosaicCaptions,options:ud.map(e=>({value:e,label:fd[e]})),onChange:e=>{let t=of(e.target.value);t!==void 0&&C({mosaicCaptions:t})},"data-testid":`summary-captions`}),i(`p`,{className:Yl,children:d(`system.notificationSummaryEditor.imagesOnlyIsTheDefault`,`Images only is the default, and it is what a rule with nothing set here does. Anything drawn is burnt into the picture for good — a label covers the bottom of the tile, which is where feet, wheels and parcels are, and a caption from a detection that was wrong cannot be un-drawn. Nothing downstream needs the words: the written summary reads the frames themselves and is told the camera, the class and the time in its prompt.`)})]}),e(`div`,{children:[i(vs,{label:d(`system.notificationSummaryEditor.captionBurnedOntoTheMosaic`,`Caption burned onto the mosaic`),value:m.captionText,disabled:!P,onChange:e=>C({captionText:e}),placeholder:d(`system.notificationSummaryEditor.leaveEmptyForNoCaption`,`Leave empty for no caption`),vars:N,deviceValues:!1,testId:`summary-caption`}),i(`p`,{className:Yl,children:P?d(`system.notificationSummaryEditor.acrossTheTopBand`,`Across the top band.`):d(`system.notificationSummaryEditor.onlyDrawnWithTileLabels`,`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`)})]})]})}),i(W,{value:`ai`,className:`space-y-3`,children:e(Q,{title:d(`system.notificationSummaryEditor.writtenSummary`,`Written summary`),hint:d(`system.notificationSummaryEditor.oneVisionCallOverThe`,`One vision call over the window's best frames TOGETHER, so the answer is an account of what happened rather than a list of pictures. The sentence goes in the notification body.`),children:[i(tu,{label:d(`system.notificationSummaryEditor.haveAModelDescribeThe`,`Have a model describe the window`),checked:m.aiEnabled,onChange:e=>C({aiEnabled:e}),hint:d(`system.notificationSummaryEditor.offByDefaultTheMosaic`,`Off by default. The mosaic and the counts are delivered either way.`),testId:`summary-ai-enabled`}),!m.aiEnabled&&i(`p`,{className:`rounded-md border border-border bg-surface px-2.5 py-1.5 text-[10px] text-foreground-muted`,"data-testid":`summary-ai-off-note`,children:d(`system.notificationSummaryEditor.theSwitchAboveIsOff`,`The switch above is off, so nothing below it can be edited. Everything you already set is kept — turning it on hands the fields back exactly as you left them.`)}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.visionProfile`,`Vision profile`)}),i(I,{value:m.aiProfileId,disabled:!m.aiEnabled,options:[{value:``,label:d(`system.notificationSummaryEditor.theHubSDefaultVision`,`The hub's default vision profile`)},...O.map(e=>({value:e.id,label:`${e.name} · ${$i(e)}${e.enabled?``:` · disabled`}`}))],onChange:e=>C({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),i(`p`,{className:Yl,children:D.isError?d(`system.notificationSummaryEditor.thisHubDidNotAnswer`,`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`):O.length===0?d(`system.notificationSummaryEditor.noVisionCapableProfileOn`,`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`):d(`system.notificationSummaryEditor.onlyVisionCapableProfilesAre`,`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`)})]}),e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.answerIn`,`Answer in`)}),i(I,{value:m.aiLanguage,disabled:!m.aiEnabled,options:[{value:``,label:d(`system.notificationSummaryEditor.donTAskForA`,`Don’t ask for a language`)},...pd.map(e=>({value:e,label:rf[e]}))],onChange:e=>C({aiLanguage:sf(e.target.value)}),"data-testid":`summary-ai-language`}),i(`p`,{className:Yl,children:d(`system.notificationSummaryEditor.nothingIsAddedToThe`,`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`)})]})]}),e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.yourQuestionOptional`,`Your question (optional)`)}),i(zt,{value:m.aiPrompt,rows:3,maxLength:gd,disabled:!m.aiEnabled,onChange:e=>C({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:d(`system.notificationSummaryEditor.eGTellMeWhether`,`e.g. Tell me whether anybody approached the gate, and whether a parcel was left.`),className:`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50`}),i(`p`,{className:Yl,children:d(`system.notificationSummaryEditor.leaveBlankForWhatHappened`,`Leave blank for “what happened during this period?”. Your words are the only free text the model is given: what the cameras are called and what the pipeline classified are reduced to plain labels first, and anything written INSIDE a frame — a sign, a plate, an overlay — is treated as scenery, never as an instruction.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(eu,{label:d(`system.notificationSummaryEditor.framesTheModelMayLook`,`Frames the model may look at`),value:m.maxAiImages,min:1,max:8,disabled:!m.aiEnabled,onChange:e=>C({maxAiImages:e??1}),hint:d(`system.notificationSummaryEditor.theHighestRankedTilesSent`,`The highest-ranked tiles, sent as ONE question. Bounded separately from the tile budget — one is bounded by pixels, the other by the model's time — and never larger than it.`),testId:`summary-max-ai-images`}),i(eu,{label:d(`system.notificationSummaryEditor.timeLimitSeconds`,`Time limit (seconds)`),value:m.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!m.aiEnabled,onChange:e=>C({aiTimeoutSeconds:e}),hint:d(`system.notificationSummaryEditor.nobodyIsWaitingOnA`,`Nobody is waiting on a phone for a digest, so this is generous. At the bound the generation is cancelled, not merely abandoned.`),testId:`summary-ai-timeout`})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(eu,{label:d(`system.notificationSummaryEditor.frameSizeSentPixels`,`Frame size sent (pixels)`),value:m.aiMaxImagePx,min:64,max:hd,emptyPlaceholder:`448`,disabled:!m.aiEnabled,onChange:e=>C({aiMaxImagePx:e}),hint:d(`system.notificationSummaryEditor.longestEdge448IsThe`,`Longest edge. 448 is the native tile size of these vision encoders — larger costs tokens and latency without adding detail the encoder can see.`),testId:`summary-ai-max-px`}),e(`div`,{children:[i(`label`,{className:Z,children:d(`system.notificationSummaryEditor.ifTheModelGivesNo`,`If the model gives no answer`)}),i(I,{value:m.aiOnFailure,disabled:!m.aiEnabled,options:md.map(e=>({value:e,label:nf[e]})),onChange:e=>{let t=cf(e.target.value);t!==void 0&&C({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),i(`p`,{className:Yl,children:d(`system.notificationSummaryEditor.aColdModelAnUnreachable`,`A cold model, an unreachable endpoint or an answer the hub cannot parse are all this case. The default delivers: the mosaic and the counts are worth more than silence, and a closed window does not come back.`)})]})]})]})}),i(W,{value:`delivery`,className:`space-y-3`,children:e(Q,{title:d(`system.notificationSummaryEditor.delivery`,`Delivery`),children:[i($l,{targets:s,value:m.targetIds,onChange:e=>C({targetIds:e})}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(eu,{label:d(`system.notificationSummaryEditor.priority`,`Priority`),value:m.priority,min:1,max:5,onChange:e=>C({priority:e??3}),testId:`summary-priority`}),i(tu,{label:d(`system.notificationSummaryEditor.deliverAWindowThatMatched`,`Deliver a window that matched nothing`),checked:m.deliverEmpty,onChange:e=>C({deliverEmpty:e}),hint:d(`system.notificationSummaryEditor.offByDefaultANightly`,`Off by default: a nightly '0 events' is a line nobody reads, and it costs the lines beside it their reader.`),testId:`summary-deliver-empty`})]}),i(nu,{title:m.templateTitle,body:m.templateBody,onTitleChange:e=>C({templateTitle:e}),onBodyChange:e=>C({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),i(`p`,{className:Yl,children:i(br,{i18nKey:`system.notificationSummaryEditor.aiToken`,values:{token:`{{ai}}`},components:{code:i(`code`,{})}})}),i(Rs,{surface:`summary`,templateFamily:`summary`,targetIds:m.targetIds,targets:s,overrides:m.targetOverrides,rulePriority:m.priority,onChange:e=>C({targetOverrides:e})})]})})]})]}),e(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[i(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:u,children:d(`common.cancel`,`Cancel`)}),e(q,{size:`sm`,type:`button`,disabled:ee.isPending,onClick:()=>{b(!0),!(!qd(m)||ee.isPending)&&ee.mutate()},children:[ee.isPending&&i(g,{className:`h-3.5 w-3.5 animate-spin`}),t===null?d(`system.notificationSummaryEditor.create`,`Create`):d(`common.save`,`Save`)]})]})]})})}var uf=`nc.listTimelapseRules`,df=`nc.upsertTimelapseRule`,ff=`nc.deleteTimelapseRule`,pf=`nc.testTimelapseRule`,mf=3600,hf=3600,gf=30,_f=1,vf=[`image`,`gif`],yf={image:`Still frame`,gif:`Short animation (GIF)`},bf=at({rules:ot(ve.extend({readOnly:it().optional()}))});function xf(e){let t=bf.safeParse(e);return t.success?t.data.rules:null}function Sf(e){return e.readOnly!==!0}var Cf=at({produced:tt(),exportId:nt().optional(),coveragePercent:tt().optional(),enqueued:tt().optional(),windowStartMs:tt().optional(),windowEndMs:tt().optional(),error:nt().optional()});function wf(e){let t=Cf.safeParse(e);return t.success?t.data:null}function Tf(){return{name:``,enabled:!0,deviceIds:[],schedule:void 0,cadenceSec:15,framerate:10,denseCadenceSec:void 0,minDwellSec:void 0,targetIds:[],templateTitle:``,templateBody:``,previewText:``,previewTextSet:!1,previewMode:`image`,reportClasses:[],priority:3,targetOverrides:{},tags:[]}}function Ef(e){return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule,cadenceSec:e.cadenceSec,framerate:e.framerate,denseCadenceSec:e.denseCadenceSec,minDwellSec:e.minDwellSec,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,previewText:e.previewText??``,previewTextSet:e.previewText!==void 0,previewMode:e.previewMode,reportClasses:[...e.reportClasses??[]],priority:e.priority,targetOverrides:e.targetOverrides??{},tags:[...e.tags??[]]}}var Df={windows:[{days:[1],startMinute:0,endMinute:60}]};function Of(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 kf(e,t){let n=Of(e),r=Nr(e.targetIds,e.targetOverrides,t);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??Df,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:fu(e.targetIds),...n===void 0?{}:{template:n},...e.previewTextSet?{previewText:e.previewText}:{},previewMode:e.previewMode,...e.reportClasses.length>0?{reportClasses:[...e.reportClasses]}:{},priority:e.priority,...Object.keys(r).length>0?{targetOverrides:r}:{},...Au(e.tags)}}function Af(e,t,n){let r=kf(e,n),i={};return r.name!==t.name&&(i.name=r.name),r.enabled!==t.enabled&&(i.enabled=r.enabled),du(r.deviceIds,t.deviceIds)||(i.deviceIds=r.deviceIds),du(r.schedule,t.schedule)||(i.schedule=r.schedule),r.cadenceSec!==t.cadenceSec&&(i.cadenceSec=r.cadenceSec),r.framerate!==t.framerate&&(i.framerate=r.framerate),r.denseCadenceSec!==t.denseCadenceSec&&(i.denseCadenceSec=r.denseCadenceSec??jf(r.cadenceSec)),r.minDwellSec!==t.minDwellSec&&r.minDwellSec!==void 0&&(i.minDwellSec=r.minDwellSec),du(r.targets,t.targets)||(i.targets=r.targets),du(r.template,t.template)||(i.template=r.template??null),r.previewText!==t.previewText&&r.previewText!==void 0&&(i.previewText=r.previewText),r.previewMode!==t.previewMode&&(i.previewMode=r.previewMode),du(r.reportClasses,t.reportClasses)||(i.reportClasses=r.reportClasses??[]),r.priority!==t.priority&&(i.priority=r.priority),du(r.targetOverrides??{},t.targetOverrides??{})||(i.targetOverrides=r.targetOverrides??{}),{...i,...ju(e.tags,t.tags)}}function jf(e){return Math.max(_f,e/gf)}function Mf(e,t,n){return t<=0||n<=0?0:e/t/n}function Nf(e,t){return e*t*Ve}function Pf(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 ${mf}.`),(!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 ${Ve}s and ${hf}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 Ff(e){return Pf(e).length===0}function If(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=Nf(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 Lf(e){return su(e)}function Rf(e,t){return cu(e,t,`Never run`)}function zf(e){return e.denseCadenceSec===void 0?{seconds:jf(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var Bf=[{key:`rule`,get label(){return J.t(`helpers.notificationTimelapse.tab_rule`)},fields:[`name`,`enabled`,`tags`,`deviceIds`]},{key:`window`,get label(){return J.t(`helpers.notificationTimelapse.tab_window`)},fields:[`schedule`]},{key:`sampling`,get label(){return J.t(`helpers.notificationTimelapse.tab_sampling`)},fields:[`cadenceSec`,`framerate`,`denseCadenceSec`,`minDwellSec`]},{key:`delivery`,get label(){return J.t(`helpers.notificationTimelapse.tab_delivery`)},fields:[`targetIds`,`priority`,`previewMode`,`previewText`,`previewTextSet`,`templateTitle`,`templateBody`,`reportClasses`,`targetOverrides`]}],Vf=`rule`;function Hf(e){return Bf.find(t=>t.key===e)?.key}c();var Uf=7;function Wf(e){return vf.find(t=>t===e)}function Gf({rule:t,cameras:n,fleet:r,targets:a,onSaved:s,onCancel:c}){let{t:l}=Y(),u=j(),[d,m]=o(()=>t===null?Tf():Ef(t)),[h,_]=o(null),[v,y]=o(t!==null),[b,x]=o(Vf),S=e=>m(t=>({...t,...e})),C=ms(),w=C.data?us(C.data,{family:`timelapse`,field:`previewText`}):void 0,T=Ls(),E=Ur(Vr(a),T),D=f({mutationFn:async()=>{let e=t===null?{rule:kf(d,E)}:{ruleId:t.id,patch:Af(d,t,E)};await u.trpcClient.addons.custom.mutate({addonId:$,action:df,input:e})},onSuccess:s,onError:e=>_(e instanceof Error?e.message:`Save failed`)}),O=Pf(d),k=If(d),A=zf(d),ee=Mf(Uf,A.seconds,d.framerate),M=Bf.some(e=>e.key===b)?b:Vf;return i(xt,{open:!0,onOpenChange:e=>!e&&c(),children:e(Xt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:e(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[i(te,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),i(`span`,{className:`truncate`,children:t===null?l(`system.notificationTimelapseEditor.newTimelapse`,`New timelapse`):l(`system.notificationTimelapseEditor.edit`,`Edit {{name}}`,{name:t.name})})]})}),h!==null&&i(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:h}),e(`div`,{className:`shrink-0 space-y-2`,children:[t!==null&&i(Al,{kind:`timelapse`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt}),v?i(Xl,{problems:O,testId:`timelapse-problems`}):null,i(Zl,{warnings:k,testId:`timelapse-warnings`})]}),e(Qt,{value:M,onValueChange:e=>x(Hf(e)??b),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[i(Kt,{className:`mb-3 shrink-0`,children:Bf.map(e=>i($t,{value:e.key,children:e.label},e.key))}),e(wt,{className:`pr-1`,children:[e(W,{value:`rule`,className:`space-y-3`,children:[e(Q,{title:l(`system.notificationTimelapseEditor.whatItIs`,`What it is`),hint:l(`system.notificationTimelapseEditor.oneVideoPerCameraAssembled`,`One video per camera, assembled from that camera's RECORDED footage when the window closes.`),children:[e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.name`,`Name`)}),i(K,{value:d.name,onChange:e=>S({name:e.target.value}),placeholder:l(`system.notificationTimelapseEditor.eGNightDriveway`,`e.g. Night driveway`),"data-testid":`timelapse-name`})]}),i(`div`,{className:`pb-1.5`,children:i(tu,{label:l(`system.notificationTimelapseEditor.enabled`,`Enabled`),checked:d.enabled,onChange:e=>S({enabled:e}),testId:`timelapse-enabled`})})]}),e(`div`,{children:[i(`span`,{className:Z,children:l(`common.tags`,`Tags`)}),i(Ht,{value:d.tags,onChange:e=>S({tags:e}),label:l(`common.tags`,`Tags`)})]})]}),i(Q,{title:l(`system.notificationTimelapseEditor.cameras`,`Cameras`),children:i(Ql,{cameras:n,value:d.deviceIds,fleet:r,onChange:e=>S({deviceIds:e}),hint:l(`system.notificationTimelapseEditor.eachCameraRendersAndDelivers`,`Each camera renders and delivers its own video. Recording must be ON for a camera — a timelapse is cut from recorded footage, and the hub refuses a rule for a camera that does not record.`)})})]}),i(W,{value:`window`,className:`space-y-3`,children:i(Q,{title:l(`system.notificationTimelapseEditor.when`,`When`),children:e(`div`,{children:[i(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.weeklyWindows`,`Weekly windows`)}),i(fn,{value:d.schedule,onChange:e=>S({schedule:e})}),i(`p`,{className:Yl,children:l(`system.notificationTimelapseEditor.theVideoCoversExactlyOne`,`The video covers exactly one window and is delivered when it CLOSES. A window that crosses midnight (21:00 → 07:00) is the ordinary case for a night timelapse.`)})]})})}),i(W,{value:`sampling`,className:`space-y-3`,children:e(Q,{title:l(`system.notificationTimelapseEditor.sampling`,`Sampling`),hint:l(`system.notificationTimelapseEditor.twoRatesABaseRate`,`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`),children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[i(eu,{label:l(`system.notificationTimelapseEditor.baseCadenceSeconds`,`Base cadence (seconds)`),value:d.cadenceSec,min:2,max:mf,onChange:e=>S({cadenceSec:e??0}),hint:l(`system.notificationTimelapseEditor.oneFrameEveryNSeconds`,`One frame every N seconds across the quiet parts of the window.`),testId:`timelapse-cadence`}),i(eu,{label:l(`system.notificationTimelapseEditor.outputFrameRateFps`,`Output frame rate (fps)`),value:d.framerate,min:1,max:60,onChange:e=>S({framerate:e??0}),hint:l(`system.notificationTimelapseEditor.howFastTheAssembledVideo`,`How fast the assembled video plays.`),testId:`timelapse-framerate`})]}),e(`div`,{children:[i(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.denseCadenceNearTheDetections`,`Dense cadence, near the detections`)}),e(`div`,{className:`flex items-center gap-2`,children:[i(I,{value:d.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:zf(d).seconds}),"data-testid":`timelapse-dense-mode`}),d.denseCadenceSec!==void 0&&i(K,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(d.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&S({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),e(`p`,{className:Yl,"data-testid":`timelapse-dense-hint`,children:[l(`system.notificationTimelapseEditor.denseHint`,{seconds:A.seconds,fps:d.framerate,passage:Uf,onScreen:ee.toFixed(2)}),` `,A.derived?l(`system.notificationTimelapseEditor.denseDerived`):l(`system.notificationTimelapseEditor.denseFixed`,{seconds:zf({...d,denseCadenceSec:void 0}).seconds})]})]}),i(eu,{label:l(`system.notificationTimelapseEditor.minimumSecondsOfVideoPer`,`Minimum seconds of video per detection (optional)`),value:d.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>S({minDwellSec:e}),hint:l(`system.notificationTimelapseEditor.stateTheStayAndLet`,`State the stay and let the renderer solve for the cadence. It only ever samples DENSER, down to the recording's own frame interval — a passage too short to reach it is rendered with every frame that exists and no more.`),testId:`timelapse-min-dwell`})]})}),i(W,{value:`delivery`,className:`space-y-3`,children:e(Q,{title:l(`system.notificationTimelapseEditor.theNotification`,`The notification`),children:[i($l,{targets:a,value:d.targetIds,onChange:e=>S({targetIds:e})}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:Z,children:l(`system.notificationTimelapseEditor.preview`,`Preview`)}),i(I,{value:d.previewMode,options:vf.map(e=>({value:e,label:yf[e]})),onChange:e=>{let t=Wf(e.target.value);t!==void 0&&S({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),i(eu,{label:l(`system.notificationTimelapseEditor.priority`,`Priority`),value:d.priority,min:1,max:5,onChange:e=>S({priority:e??3}),testId:`timelapse-priority`})]}),e(`div`,{children:[i(vs,{label:l(`system.notificationTimelapseEditor.captionOnThePreviewFrame`,`Caption on the preview frame`),value:d.previewTextSet?d.previewText:``,placeholder:l(`system.notificationTimelapseEditor.shippedDefault`,`{{DEFAULT_TIMELAPSE_PREVIEW_TEXT}} (shipped default)`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:ce}),onChange:e=>S({previewText:e,previewTextSet:!0}),vars:w,deviceValues:!1,testId:`timelapse-preview-text`}),e(`p`,{className:Yl,children:[d.previewTextSet&&d.previewText.length===0?l(`system.notificationTimelapseEditor.emptyAndSetThePreview`,`Empty and set: the preview frame carries NO caption.`):l(`system.notificationTimelapseEditor.leaveUntouchedForTheShipped`,`Leave untouched for the shipped caption ({{DEFAULT_TIMELAPSE_PREVIEW_TEXT}}).`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:ce}),d.previewTextSet&&e(p,{children:[` `,i(q,{variant:`unstyled`,type:`button`,className:`underline`,onClick:()=>S({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:l(`system.notificationTimelapseEditor.backToTheShippedCaption`,`Back to the shipped caption`)})]})]})]}),i(nu,{title:d.templateTitle,body:d.templateBody,onTitleChange:e=>S({templateTitle:e}),onBodyChange:e=>S({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:i(br,{i18nKey:`system.notificationTimelapseEditor.detectionSummaryNote`,values:{token:`{{detectionSummary}}`},components:{code:i(`code`,{})}})}),i(Rs,{surface:`timelapse`,templateFamily:`timelapse`,targetIds:d.targetIds,targets:a,overrides:d.targetOverrides,rulePriority:d.priority,onChange:e=>S({targetOverrides:e})})]})})]})]}),e(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[i(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:l(`common.cancel`,`Cancel`)}),e(q,{size:`sm`,type:`button`,disabled:D.isPending,onClick:()=>{y(!0),!(!Ff(d)||D.isPending)&&D.mutate()},children:[D.isPending&&i(g,{className:`h-3.5 w-3.5 animate-spin`}),t===null?l(`system.notificationTimelapseEditor.create`,`Create`):l(`common.save`,`Save`)]})]})]})})}function Kf({children:e,className:t}){return i(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function qf(){return i(`div`,{className:`flex items-center justify-center py-16`,children:i(g,{className:`h-6 w-6 animate-spin text-primary`})})}function Jf({children:e,testId:t}){return i(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function Yf({name:t,enabled:n,onOpen:r,badges:a,openTestId:o}){let{t:s}=Y();return e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[r===void 0?i(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t}):i(Kf,{children:i(q,{variant:`unstyled`,type:`button`,onClick:r,className:`truncate rounded text-left text-sm font-medium text-foreground hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,...o===void 0?{}:{"data-testid":o},children:t})}),!n&&i(U,{variant:`warning`,children:s(`common.disabled`)}),a]})}function Xf({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:a=`Delete`,cancelLabel:o=`Cancel`,ariaLabel:s,testId:c,onConfirm:l}){let u=N(),d=async()=>{await u({title:n,message:r,confirmLabel:a,cancelLabel:o,variant:`danger`})&&l()};return i(q,{variant:`unstyled`,type:`button`,title:a,"aria-label":s,disabled:e||t,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void d(),...c===void 0?{}:{"data-testid":c},children:i(re,{className:`h-3.5 w-3.5 text-danger`})})}c();var Zf=[`notificationSummaries`,`listSummaryRules`];function Qf(t){return[{key:`name`,header:J.t(`system.notificationSummaries.digest`,`Digest`),render:n=>i(Yf,{name:n.name,enabled:n.enabled,..._d(n)?{onOpen:()=>t.onOpen(n)}:{},openTestId:`summary-edit-${n.id}`,badges:e(p,{children:[!_d(n)&&i(U,{variant:`warning`,children:`read-only`}),n.ai?.enabled===!0&&i(U,{variant:`info`,children:`AI`}),n.ai!==void 0&&!n.ai.enabled&&i(U,{variant:`default`,children:J.t(`system.notificationSummaries.aiOff`,`AI off`)})]})})},{key:`cameras`,header:J.t(`system.notificationSummaries.cameras`,`Cameras`),align:`center`,nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:J.t(`system.notificationSummaries.window`,`Window`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Qd(e.window)})},{key:`filters`,header:J.t(`system.notificationSummaries.keeps`,`Keeps`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:ef(e.filters)})},{key:`mosaic`,header:J.t(`system.notificationSummaries.mosaic`,`Mosaic`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:J.t(`system.notificationSummaries.tilesRank`,{count:e.maxTiles,rank:e.rank})})},{key:`targets`,header:J.t(`system.notificationSummaries.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationSummaries.lastRun`,`Last run`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${e.id}`,children:$d(e.generatedAt,t.nowMs)})},{key:`enabled`,header:J.t(`system.notificationSummaries.on`,`On`),align:`center`,nowrap:!0,render:e=>i(Kf,{children:i(G,{checked:e.enabled,disabled:e.readOnly,onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationSummaries.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(Kf,{className:`flex items-center justify-end gap-1`,children:[e(vt,{children:[i(jt,{children:i(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.readOnly,onClick:()=>t.onTest(n),"aria-label":J.t(`system.notificationSummaries.test`,`test {{name}}`,{name:n.name}),"data-testid":`summary-test-${n.id}`,children:i(ct,{className:`h-3.5 w-3.5`})})}),i(ht,{children:J.t(`system.notificationSummaries.produceThisDigestNowAnd`,`Produce this digest now and DELIVER it`)})]}),i(Xf,{disabled:n.readOnly,pending:t.deletePending,title:J.t(`system.notificationSummaries.deleteThisSummary`,`Delete this summary?`),message:J.t(`system.notificationSummaries.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:n.name}),ariaLabel:J.t(`system.notificationSummaries.delete`,`delete {{name}}`,{name:n.name}),testId:`summary-delete-${n.id}`,onConfirm:()=>t.onConfirmDelete(n)})]})}]}c();var $f=[`notificationTimelapses`,`listTimelapseRules`];function ep(t){return[{key:`name`,header:J.t(`system.notificationTimelapses.timelapse`,`Timelapse`),render:e=>i(Yf,{name:e.name,enabled:e.enabled,...Sf(e)?{onOpen:()=>t.onOpen(e),openTestId:`timelapse-edit-${e.id}`}:{},badges:Sf(e)?null:i(U,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:J.t(`system.notificationTimelapses.cameras`,`Cameras`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length===1?t.cameraNameById.get(e.deviceIds[0]??-1)??`#${e.deviceIds[0]}`:J.t(`system.notificationTimelapses.cameras2`,`{{length}} cameras`,{length:e.deviceIds.length})})},{key:`schedule`,header:J.t(`system.notificationTimelapses.window`,`Window`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Lf(e.schedule)})},{key:`sampling`,header:J.t(`system.notificationTimelapses.sampling`,`Sampling`),nowrap:!0,render:t=>{let n=zf(Ef(t));return e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[J.t(n.derived?`system.notificationTimelapses.ruleSummaryAuto`:`system.notificationTimelapses.ruleSummary`,{cadence:t.cadenceSec,fps:t.framerate,dense:n.seconds}),t.minDwellSec===void 0?``:` · ${J.t(`system.notificationTimelapses.ruleDwell`,{sec:t.minDwellSec})}`]})}},{key:`targets`,header:J.t(`system.notificationTimelapses.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationTimelapses.lastRun`,`Last run`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${e.id}`,children:Rf(e.lastGeneratedAt,t.nowMs)})},{key:`enabled`,header:J.t(`system.notificationTimelapses.on`,`On`),align:`center`,nowrap:!0,render:e=>i(Kf,{children:i(G,{checked:e.enabled,disabled:!Sf(e),onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationTimelapses.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(Kf,{className:`flex items-center justify-end gap-1`,children:[e(vt,{children:[i(jt,{children:i(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Sf(n),onClick:()=>t.onTest(n),"aria-label":J.t(`system.notificationTimelapses.test`,`test {{name}}`,{name:n.name}),"data-testid":`timelapse-test-${n.id}`,children:i(ct,{className:`h-3.5 w-3.5`})})}),i(ht,{children:J.t(`system.notificationTimelapses.renderThisRuleSLast`,`Render this rule's last closed window now and DELIVER it`)})]}),i(Xf,{disabled:!Sf(n),pending:t.deletePending,title:J.t(`system.notificationTimelapses.deleteThisTimelapse`,`Delete this timelapse?`),message:J.t(`system.notificationTimelapses.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:n.name}),ariaLabel:J.t(`system.notificationTimelapses.delete`,`delete {{name}}`,{name:n.name}),testId:`timelapse-delete-${n.id}`,onConfirm:()=>t.onConfirmDelete(n)})]})}]}c();var tp={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`}},np=`system.notificationProducerRules.unreadableMessage`,rp=[`summary`,`timelapse`,`calendar-events`];function ip(e){return e===`all`?rp:e===`summaries`?[`summary`]:e===`timelapses`?[`timelapse`]:e===`calendar-events`?[`calendar-events`]:[]}function ap({cameras:t,fleet:n,targets:r,taxonomy:a}){let{t:c}=Y(),l=j(),[u,d]=o({mode:`closed`}),[m,h]=o(null),[g,_]=o(null),[v,y]=o(null),[b,x]=o(null),S=s({queryKey:Zf,queryFn:async()=>Fd(await l.trpcClient.addons.custom.mutate({addonId:$,action:$u,input:{}}))}),C=s({queryKey:$f,queryFn:async()=>xf(await l.trpcClient.addons.custom.mutate({addonId:$,action:uf,input:{}}))}),w=s({queryKey:Mu,queryFn:async()=>zu(await l.trpcClient.addons.custom.mutate({addonId:$,action:Nu,input:{}}))}),T=S.data??[],E=C.data??[],D=w.data??[],O=f({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:ed,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),k=f({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:td,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),A=f({mutationFn:async e=>Id(await l.trpcClient.addons.custom.mutate({addonId:$,action:nd,input:{ruleId:e,...tf(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),ee=f({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:df,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),M=f({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:ff,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),N=f({mutationFn:async e=>wf(await l.trpcClient.addons.custom.mutate({addonId:$,action:pf,input:e})),onSuccess:e=>{y(null),x(e)}}),P=f({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Pu,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void w.refetch()}),F=f({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:$,action:Fu,input:{ruleId:e}}),onSuccess:()=>void w.refetch()}),te=t.toSorted((e,t)=>e.name.localeCompare(t.name)),L=r.map(e=>({id:e.id,name:e.name,enabled:e.enabled,kind:e.kind,addonId:e.addonId})),ne=new Map(L.map(e=>[e.id,e.name])),re=new Map(te.map(e=>[e.id,e.name])),R=Date.now(),z={summary:{nowMs:R,targetNameById:ne,deletePending:k.isPending,onToggle:(e,t)=>O.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{_d(e)&&d({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>k.mutate(e.id)},timelapse:{nowMs:R,cameraNameById:re,targetNameById:ne,deletePending:M.isPending,onToggle:(e,t)=>ee.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Sf(e)&&d({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>M.mutate(e.id)},calendar:{nowMs:R,targetNameById:ne,deletePending:F.isPending,onToggle:(e,t)=>P.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Bu(e)&&d({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>F.mutate(e.id)}},B=e=>{switch(e.family){case`summary`:z.summary.onOpen(e.rule);return;case`timelapse`:z.timelapse.onOpen(e.rule);return;case`calendar-events`:z.calendar.onOpen(e.rule);return}},ie=e=>{d(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=>ip(e).some(e=>ae(e)!==null),ce=t=>e(p,{children:[ip(t).flatMap(e=>{let t=ae(e);return t===null?[]:[{kind:e,unreadable:t.unreadable}]}).map(({kind:e,unreadable:t})=>i(dt,{title:c(tp[e].titleKey),message:c(t?np:tp[e].messageKey),onRetry:()=>oe(e)},e)),k.isError&&i(dt,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(k.error)}),M.isError&&i(dt,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(M.error)}),F.isError&&i(dt,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(F.error)}),A.isError&&i(dt,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(A.error)}),N.isError&&i(dt,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(N.error)}),g!==null&&i(op,{outcome:g,onDismiss:()=>_(null)}),b!==null&&i(sp,{outcome:b,onDismiss:()=>x(null)})]}),le=()=>d({mode:`closed`}),ue=e(p,{children:[u.mode===`summary`&&i(lf,{rule:u.rule,cameras:te,fleet:n,targets:L,taxonomy:a,onCancel:le,onSaved:()=>{le(),S.refetch()}}),u.mode===`timelapse`&&i(Gf,{rule:u.rule,cameras:te,fleet:n,targets:L,onCancel:le,onSaved:()=>{le(),C.refetch()}}),u.mode===`calendar-events`&&i(Qu,{rule:u.rule,targets:L,onCancel:le,onSaved:()=>{le(),w.refetch()}}),i(ru,{open:m!==null,ruleName:m?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${m?.targets.length??0} target${(m?.targets.length??0)===1?``:`s`}`,pending:A.isPending,onCancel:()=>h(null),onConfirm:()=>{m!==null&&A.mutate(m.id)}}),i(ru,{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:N.isPending,confirmDisabled:v?.deviceId===null,extra:v===null?null:e(`div`,{children:[i(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.notificationProducerRules.whichCamera`,`Which camera`)}),i(I,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:re.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&&N.mutate({ruleId:v.rule.id,deviceId:v.deviceId})}})]});return{summaries:T,timelapses:E,calendarEvents:D,loading:S.isLoading||C.isLoading||w.isLoading,columnDeps:z,open:B,create:ie,notices:ce,listFailed:se,overlays:ue}}function op({outcome:t,onDismiss:n}){let{t:r}=Y();return e(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[t.error===void 0?e(`span`,{children:[r(`system.notificationProducerRules.summaryProduced`,{digests:r(`system.notificationProducerRules.digestCount`,{count:t.produced}),tiles:r(`system.notificationProducerRules.tileCount`,{count:t.tiles??0}),cameras:r(`system.notificationProducerRules.cameraCount`,{count:t.cameras??0}),matched:r(`system.notificationProducerRules.tracksMatched`,{count:t.matched??0}),sent:r(`system.notificationProducerRules.notificationsSent`,{count:t.enqueued??0})}),(t.droppedStationary??0)>0&&i(`span`,{"data-testid":`summary-test-dropped-stationary`,className:`ml-1`,children:r(`system.notificationProducerRules.droppedStationary`,{count:t.droppedStationary})})]}):e(`span`,{className:`text-warning`,children:[r(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,t.error]}),i(q,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:n,children:r(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}function sp({outcome:t,onDismiss:n}){let{t:r}=Y();return e(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[t.error===void 0?i(`span`,{children:r(t.coveragePercent===void 0?`system.notificationProducerRules.timelapseProduced`:`system.notificationProducerRules.timelapseProducedCoverage`,{videos:r(`system.notificationProducerRules.videoCount`,{count:t.produced}),percent:Math.round(t.coveragePercent??0),sent:r(`system.notificationProducerRules.notificationsSent`,{count:t.enqueued??0})})}):e(`span`,{className:`text-warning`,children:[r(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,t.error]}),i(q,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:n,children:r(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}var cp=[{key:`summaries`,get label(){return J.t(`helpers.notificationRulesArea.sumLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.sumBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.sumNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.sumEmpty`)}},{key:`timelapses`,get label(){return J.t(`helpers.notificationRulesArea.tlLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.tlBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.tlNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.tlEmpty`)}},{key:`calendar-events`,get label(){return J.t(`helpers.notificationRulesArea.calLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.calBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.calNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.calEmpty`)}}],lp=[{type:`detection`,get label(){return J.t(`helpers.notificationRulesArea.opt_detection_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_detection_hint`)}},{type:`sensor`,get label(){return J.t(`helpers.notificationRulesArea.opt_sensor_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_sensor_hint`)}},{type:`audio`,get label(){return J.t(`helpers.notificationRulesArea.opt_audio_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_audio_hint`)}},{type:`occupancy`,get label(){return J.t(`helpers.notificationRulesArea.opt_occupancy_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_occupancy_hint`)}},{type:`device-events`,get label(){return J.t(`helpers.notificationRulesArea.opt_deviceEvents_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_deviceEvents_hint`)}},{type:`system`,get label(){return J.t(`helpers.notificationRulesArea.opt_system_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_system_hint`)}},{type:`alarm`,get label(){return J.t(`helpers.notificationRulesArea.opt_alarm_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_alarm_hint`)}},{type:`summary`,get label(){return J.t(`helpers.notificationRulesArea.opt_summary_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_summary_hint`)}},{type:`timelapse`,get label(){return J.t(`helpers.notificationRulesArea.opt_timelapse_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_timelapse_hint`)}},{type:`calendar-events`,get label(){return J.t(`helpers.notificationRulesArea.opt_calendarEvents_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_calendarEvents_hint`)}}];function up(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function dp(e){if(!(e==null||e.length===0))return up(e)?e:He(e)}function fp(e){let t=cp.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function pp(e){return[...Wn.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...cp]}function mp(e){return!up(e)}function hp(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}c();function gp(e){return[{key:`name`,header:J.t(`system.notificationCalendarEventsPage.rule`,`Rule`),render:t=>i(Yf,{name:t.name,enabled:t.enabled,...Bu(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:Bu(t)?null:i(U,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:J.t(`system.notificationCalendarEventsPage.when`,`When`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Wu(e.schedule)})},{key:`horizon`,header:J.t(`system.notificationCalendarEventsPage.horizon`,`Horizon`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Xu(e.horizonDays)})},{key:`calendars`,header:J.t(`system.notificationCalendarEventsPage.calendars`,`Calendars`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Zu(e)})},{key:`targets`,header:J.t(`system.notificationCalendarEventsPage.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationCalendarEventsPage.lastRun`,`Last run`),nowrap:!0,render:t=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:$d(t.generatedAt,e.nowMs)})},{key:`enabled`,header:J.t(`system.notificationCalendarEventsPage.on`,`On`),align:`center`,nowrap:!0,render:t=>i(Kf,{children:i(G,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":J.t(`system.notificationCalendarEventsPage.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>i(Kf,{className:`flex items-center justify-end gap-1`,children:i(Xf,{disabled:t.readOnly,pending:e.deletePending,title:J.t(`system.notificationCalendarEventsPage.deleteThisCalendarEventsRule`,`Delete this calendar-events rule?`),message:J.t(`system.notificationCalendarEventsPage.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:J.t(`system.notificationCalendarEventsPage.delete`,`delete {{name}}`,{name:t.name}),testId:`calendar-events-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})})}]}function _p(e,t){return e.replaceAll(`{{name}}`,t)}function vp(t){return[{key:`name`,header:J.t(`system.notificationRuleColumns.rule`,`Rule`),render:e=>i(Yf,{name:e.name,enabled:e.enabled,...Rn(e)?{onOpen:()=>t.onOpen(e)}:{}})},{key:`trigger`,header:J.t(`system.notificationRuleColumns.trigger`,`Trigger`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] text-foreground-subtle`,children:hr(n,t.t(`notificationRules.grouping.choice`,hn))}),!kn(n.delivery)&&i(U,{variant:`warning`,children:J.t(`common.readOnly`)})]})},{key:`targets`,header:J.t(`system.notificationRuleColumns.targets`,`Targets`),render:e=>{let n=e.targets[0],r=n?t.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&r?r:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationRuleColumns.lastRun`,`Last run`),nowrap:!0,render:e=>i(cl,{cell:t.lastRunOf(e.id)})},{key:`priority`,header:J.t(`system.notificationRuleColumns.priority`,`Priority`),align:`center`,nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:t.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:e=>i(Kf,{children:i(_l,{rule:e,snoozes:t.snoozes,exempt:Un(e.conditions,vn({onActivation:e.actions?.onActivation??[],onDeactivation:e.actions?.onDeactivation??[],onTrigger:e.actions?.onTrigger??[],onTriggerOff:e.actions?.onTriggerOff??[],buttons:e.actions?.buttons??[]},t.actions))})})},{key:`enabled`,header:J.t(`system.notificationRuleColumns.on`,`On`),align:`center`,nowrap:!0,render:e=>i(Kf,{children:i(G,{checked:e.enabled,onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationRuleColumns.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>Rn(n)?e(Kf,{className:`flex items-center justify-end gap-1`,children:[i(Ul,{ruleId:n.id,ruleName:n.name,...n.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:n.conditions.devices[0]}}),t.onOpenHistory&&i(ll,{rule:n,onOpenHistory:t.onOpenHistory}),t.onTest&&e(vt,{children:[i(jt,{children:i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest?.(n),"aria-label":J.t(`system.notificationRuleColumns.simulate`,`simulate {{name}}`,{name:n.name}),children:i(ct,{className:`h-3.5 w-3.5`})})}),i(ht,{children:J.t(`system.notificationRuleColumns.openInTheSimulatorDescribe`,`Open in the simulator — describe an event and tune it before injecting`)})]}),e(vt,{children:[i(jt,{children:i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDuplicate(n),"aria-label":J.t(`system.notificationRuleColumns.duplicate`,`Duplicate`),children:i(y,{className:`h-3.5 w-3.5`})})}),i(ht,{children:J.t(`system.notificationRuleColumns.duplicate`,`Duplicate`)})]}),i(bp,{rule:n,deps:t})]}):i(yp,{rule:n,deps:t})}]}function yp({rule:t,deps:n}){let{t:r}=Y();return e(Kf,{className:`flex items-center justify-end gap-1`,children:[i(`span`,{title:pe(xe(t)).blurb,children:i(U,{variant:`warning`,children:r(`system.notificationRuleColumns.recreateAsOneRulePer`,`Recreate as one rule per family`)})}),n.onOpenHistory&&i(ll,{rule:t,onOpenHistory:n.onOpenHistory}),i(bp,{rule:t,deps:n})]})}function bp({rule:e,deps:t}){let{t:n}=Y();return i(Xf,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:_p(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:_p(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function xp(e){let t=vp(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:J.t(`system.notificationRuleColumns.events`,`Events`),render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:_i(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:J.t(`system.notificationRuleColumns.scope`,`Scope`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:qr(e.conditions.systemEvent)})},{key:`targets`,header:J.t(`system.notificationRuleColumns.targets`,`Targets`),render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`cooldown`,header:J.t(`system.notificationRuleColumns.cooldown`,`Cooldown`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,children:Bn(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}var Sp=e=>e.rule.tags,Cp=e=>[e.name];function wp(e){switch(e){case`detection`:return J.t(`helpers.unifiedRulesModel.kind_detection`);case`sensor`:return J.t(`helpers.unifiedRulesModel.kind_sensor`);case`sound`:return J.t(`helpers.unifiedRulesModel.kind_sound`);case`occupancy`:return J.t(`helpers.unifiedRulesModel.kind_occupancy`);case`device-events`:return J.t(`helpers.unifiedRulesModel.kind_device_events`);case`system`:return J.t(`helpers.unifiedRulesModel.kind_system`);case`alarm`:return J.t(`helpers.unifiedRulesModel.kind_alarm`);case`mixed`:return J.t(`helpers.unifiedRulesModel.kind_mixed`);case`summary`:return J.t(`helpers.unifiedRulesModel.kind_summary`);case`timelapse`:return J.t(`helpers.unifiedRulesModel.kind_timelapse`);case`calendar-events`:return J.t(`helpers.unifiedRulesModel.kind_calendar_events`)}}function Tp(e){return{family:`event`,kind:xe(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Ep(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Dp(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Op(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function kp(e){return[...e.events.map(Tp),...e.summaries.map(Ep),...e.timelapses.map(Dp),...e.calendarEvents.map(Op)]}function Ap(e,t){return t===`all`?!0:up(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:mp(t)&&e.family===`event`?he(e.rule,t):!1}function jp(e,t){return kp(t).filter(t=>Ap(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function Mp(e,t){return jp(e,t).length}function Np(e){return e===`all`?1020:980}function Pp(e){return e.family===`event`?e.rule:null}function Fp(e){return e.family===`summary`?e.rule:null}function Ip(e){return e.family===`timelapse`?e.rule:null}function Lp(e){return e.family===`calendar-events`?e.rule:null}function Rp(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 zp(e,t){return e.map(e=>Rp(e,t))}function Bp(e,t){return e.find(e=>e.key===t)}function Vp(e,t,n){let r=Bp(vp(n.event),e),i=Bp(Qf(n.summary),e),a=Bp(ep(n.timelapse),e),o=Bp(gp(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 Hp(e){switch(e.family){case`event`:return null;case`summary`:return Qd(e.rule.window);case`timelapse`:return Lf(e.rule.schedule);case`calendar-events`:return Wu(e.rule.schedule)}}function Up(e){let t=Bp(vp(e.event),`trigger`);return{key:`when`,header:J.t(`system.unifiedRulesColumns.when`,`When`),render:(e,n)=>{let r=Hp(e);return r===null?e.family===`event`?t?.render(e.rule,n)??null:null:i(`span`,{className:`text-[11px] text-foreground-subtle`,children:r})}}}function Wp(e){return[Vp(`name`,`Name`,e),{key:`type`,header:J.t(`system.unifiedRulesColumns.type`,`Type`),nowrap:!0,render:e=>i(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:wp(e.kind)})},Up(e),Vp(`targets`,`Targets`,e),Vp(`lastRun`,`Last run`,e),Vp(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),Vp(`enabled`,`On`,e),Vp(`actions`,``,e)]}function Gp(e,t){return e===`all`?Wp(t):e===`summaries`?zp(Qf(t.summary),Fp):e===`timelapses`?zp(ep(t.timelapse),Ip):e===`calendar-events`?zp(gp(t.calendar),Lp):mp(e)&&Zn(e)?zp(xp(t.event),Pp):zp(vp(t.event),Pp)}function Kp({value:t,family:n,kinds:r,onChange:a,draft:o}){let{t:s}=Y();if(!Br(n))return null;let c=fi(t,r),l=[{id:`activation`,on:c.onActivation,label:s(`system.notificationSystemEventDelivery.whenItStarts`,`When it starts`)},{id:`deactivation`,on:c.onDeactivation,label:s(`system.notificationSystemEventDelivery.whenItClears`,`When it clears`)},{id:`schedule`,on:c.onSchedule!==void 0,label:s(`system.notificationSystemEventDelivery.onASchedule`,`On a schedule`)}],u=De({delivery:`system-event`,conditions:r.length>0?{systemEvent:{kinds:[...r]}}:{},systemEventDelivery:c}).filter(e=>e.code===`no-mode`||e.code===`no-instant-kind`).map(we);return e(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:s(`system.notificationSystemEventDelivery.delivery`,`Delivery`)}),i(`div`,{className:`flex flex-wrap gap-1.5`,role:`group`,children:l.map(t=>e(`label`,{className:R(ie,`cursor-pointer`,t.on?B:A),children:[i(F,{checked:t.on,onChange:e=>a(Wr(c,t.id,e.target.checked)),"data-testid":`rule-delivery-${t.id}`}),t.label]},t.id))}),i(qp,{modes:c,kinds:r}),u.map(e=>i(`p`,{className:`mt-2 text-[11px] text-danger`,"data-testid":`rule-delivery-problem`,children:e},e)),c.onSchedule!==void 0&&i(Jp,{value:c,onChange:a,draft:o})]})}function qp({modes:t,kinds:n}){let{t:r}=Y(),a=Pr(n),o=!t.onActivation&&!t.onDeactivation;return e(`div`,{className:`mt-2 space-y-1`,"data-testid":`rule-delivery-hints`,children:[t.onDeactivation&&a.adds.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-clears-hint`,children:r(`system.notificationSystemEventDelivery.clearsAdds`,`When it clears also reports the recovery of: {{what}}.`,{what:a.adds.join(` · `)})}),t.onDeactivation&&a.without>0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-no-clearing-hint`,children:r(`system.notificationSystemEventDelivery.noClearingEvent`,{count:a.without})}),t.onSchedule!==void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-schedule-hint`,children:o?r(`system.notificationSystemEventDelivery.scheduleOnlyHint`,`Only on a schedule: nothing is sent per event, and the active hours and actions of this rule do not apply.`):r(`system.notificationSystemEventDelivery.scheduleBesideHint`,`The summary is sent at the times below whatever the active hours of this rule say, and runs no actions.`)})]})}function Jp({value:t,onChange:n,draft:r}){let{t:a}=Y(),o=t.onSchedule;return o===void 0?null:e(`div`,{className:`mt-2 space-y-2`,children:[i(`p`,{className:Fn,children:a(`system.notificationSystemEventDelivery.summaryExplain`,`At each time below, one notification lists what is still true for the kinds and filters of this rule — low batteries, consumables, devices or streams offline, updates available. Nothing to report sends nothing. Time zone: {{timezone}}.`,{timezone:o.schedule.timezone??a(`system.notificationSystemEventDelivery.theHubS`,`the hub’s`)})}),i(fn,{mode:`times`,value:o.schedule,onChange:e=>{e!==void 0&&n(Sr(t,e))}}),i(G,{checked:o.grouping===`section`,onCheckedChange:e=>n(Hr(t,e?`section`:`rule`)),label:a(`system.notificationSystemEventDelivery.onePerCategory`,`One notification per category`),"data-testid":`rule-delivery-grouping`}),i(Yp,{draft:r,split:o.grouping})]})}function Yp({draft:t,split:n}){let{t:r}=Y(),a=j(),o=f({mutationFn:e=>a.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),s=ri(o.status,o.data,o.error,n);return e(`div`,{className:`space-y-1.5`,children:[i(q,{size:`sm`,variant:`secondary`,onClick:()=>o.mutate(t()),disabled:o.isPending,"data-testid":`rule-delivery-preview`,children:o.isPending?r(`system.notificationSystemEventDelivery.readingTheState`,`Reading the state…`):r(`system.notificationSystemEventDelivery.previewTheSummaryNow`,`Preview the summary now`)}),s!==null&&i(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:s.lines.map((e,t)=>i(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function Xp(e,t){if(e.status===`error`)return{kind:`failed`,reason:e.error instanceof Error?e.error.message:J.t(`helpers.notificationRuleLastRun.unknownError`)};if(e.status!==`success`||e.data===void 0)return{kind:`pending`};let n=e.data.runs.find(e=>e.ruleId===t);return n===void 0?{kind:`absent`,phrase:em(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var Zp=6e4,Qp=60*Zp,$p=24*Qp;function em(e){return e===null?J.t(`helpers.notificationRuleLastRun.noDelivery`):e>=$p?J.t(`helpers.notificationRuleLastRun.notInDay`,{count:Math.floor(e/$p)}):e>=Qp?J.t(`helpers.notificationRuleLastRun.notInHour`,{count:Math.floor(e/Qp)}):e>=Zp?J.t(`helpers.notificationRuleLastRun.notInMinute`,{count:Math.floor(e/Zp)}):J.t(`helpers.notificationRuleLastRun.notInWindow`)}c();var tm=[`notificationRules`,`listRules`],nm=[`notificationRules`,`getConditionCatalog`],rm=[`deviceManager`,`gateableDevices`],im=ge.options;function am({onSimulateRule:r,onOpenHistory:c,createRequested:l=!1,onCreateConsumed:u,createTypeRequested:d=null,onCreateTypeConsumed:p,headerOwnsCreate:m=!1}={}){let h=j(),{t:g}=Y(),{state:_,openEdit:v,close:y}=Jt({editKey:`rule`}),[x,S]=At(`section`),[C,w]=At(`editTab`),[T,E]=o({mode:`closed`}),[D,O]=o(!1),A=dp(x)??`all`,ee=e=>{S(e===`all`?null:e)},M=s({queryKey:tm,queryFn:async()=>(await h.trpcClient.notificationRules.listRules.query({})).rules}),N=t(null);a(()=>{if(T.mode!==`closed`)return;if(_.mode!==`edit`){_.mode===`closed`&&(N.current=null);return}let e=_.id;if(e===`new`||N.current===e)return;let t=M.data?.find(t=>t.id===e);t===void 0||!Rn(t)||(N.current=e,E({mode:`form`,rule:t}))},[T.mode,_,M.data]);let P=Hi(),F=s({queryKey:nm,queryFn:()=>h.trpcClient.notificationRules.getConditionCatalog.query({})}),I=Vt({projection:`slim`}),te=ol(),L=n(()=>I.data??[],[I.data]),ne=Wt(I),re=n(()=>L.map(e=>e.id),[L]),R=s({queryKey:[...rm,re],enabled:re.length>0,queryFn:async()=>{let e=[];for(let t of L){let n=Ae(await h.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),im);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),z=n(()=>{let e=Mt(L);return L.filter(e=>Te(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]),B=n(()=>L.filter(e=>e.type===Je.Camera).map(e=>({id:e.id,name:e.name})),[L]),ie=Zi(n(()=>B.map(e=>e.id),[B])),ae=n(()=>{let e=new Map(B.map(e=>[e.id,e.name]));return ie.results.flatMap(t=>t.monitors.map(n=>({sceneId:n.id,deviceId:t.deviceId,cameraName:e.get(t.deviceId)??`#${String(t.deviceId)}`,label:n.label,verdict:n.verdict,latched:n.latched,emit:n.emit})))},[ie.results,B]),oe=n(()=>{let e=new Map;for(let t of P.data??[])e.set(t.id,t.name);return e},[P.data]),se=f({mutationFn:e=>h.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void M.refetch()}),ce=f({mutationFn:e=>h.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void M.refetch()}),le=gl(),ue=Ft({},{refetchInterval:sm}),de=ue.data??[],fe=M.data??[],V=ap({cameras:B,fleet:ne,targets:P.data??[],taxonomy:F.data?.taxonomy}),pe={events:fe,summaries:V.summaries,timelapses:V.timelapses,calendarEvents:V.calendarEvents},me=pp(new Map(Wn.map(e=>[e.key,Mp(e.key,pe)]))),H=me.find(e=>e.key===A)??me[0]??Wn[0],he=up(H.key)?fp(H.key):void 0;mp(H.key)&&H.key;let ge=jp(H.key,pe),ve=()=>{_.mode===`edit`&&(N.current=_.id),E({mode:`closed`}),y(),w(null)},ye=e=>{if(!Rn(e))return;let t=e.id.length>0?e.id:`new`;N.current=t,E({mode:`form`,rule:e}),v(t),w(null)},be=e=>{if(hp(e)){N.current=`new`,E({mode:`form`,rule:null,seed:_e(e)}),v(`new`),w(null);return}V.create(e)};a(()=>{d!==null&&(be(d),p?.())},[d]),a(()=>{l&&(O(!0),u?.())},[l]);let xe=e=>{if(e.family===`event`){ye(e.rule);return}V.open(e)},Se={targetNameById:oe,snoozes:le,actions:de,deletePending:ce.isPending,onToggle:(e,t)=>se.mutate({ruleId:e.id,enabled:t}),onOpen:ye,t:g,onDuplicate:e=>ye({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>ce.mutate(e.id),...r?{onTest:r}:{},lastRunOf:e=>Xp(te,e),...c?{onOpenHistory:c}:{}},Ce=Gp(H.key,{event:Se,summary:V.columnDeps.summary,timelapse:V.columnDeps.timelapse,calendar:V.columnDeps.calendar}),we=he?.blurb??(`blurb`in H?H.blurb:``),Ee=he===void 0?`creatable`in H?H.creatable:!1:!0,De=m||!Ee?null:A===`all`?e(q,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:()=>O(!0),children:[i(k,{className:`h-3.5 w-3.5`}),g(`system.notificationRules.newRule`,`New rule`)]}):he===void 0?e(q,{size:`sm`,type:`button`,onClick:()=>be(H.key),"data-testid":`rules-new-${H.key}`,children:[i(k,{className:`h-3.5 w-3.5`}),`newRuleLabel`in H?H.newRuleLabel:g(`system.notificationRules.newRule`,`New rule`)]}):e(q,{size:`sm`,type:`button`,onClick:()=>be(he.key===`summaries`?`summary`:he.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":he.key===`summaries`?`summary-new`:he.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[i(k,{className:`h-3.5 w-3.5`}),he.newLabel]});return i(Ui,{embedded:!0,icon:b,title:g(`system.notificationRules.rules`,`Rules`),subtitle:we,children:e(`div`,{className:`flex flex-col gap-3`,children:[De===null?null:i(`div`,{className:`flex justify-end`,children:De}),i(Qt,{appearance:`pills`,value:H.key,onValueChange:e=>ee(dp(e)??A),children:i(Kt,{children:me.map(t=>e($t,{value:t.key,children:[t.label,i(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:Mp(t.key,pe)})]},t.key))})}),i(Jl,{rules:fe}),V.notices(H.key),(M.isLoading||V.loading)&&i(qf,{}),M.isError&&!M.isLoading&&i(dt,{title:g(`system.notificationRules.failedToLoadRules`,`Failed to load rules`),message:M.error instanceof Error?M.error.message:g(`system.notificationRules.unknownError`,`Unknown error`),onRetry:()=>void M.refetch()}),!M.isLoading&&!V.loading&&!M.isError&&!V.listFailed(H.key)&&ge.length===0&&i(Jf,{children:he?.emptyHint??(`emptyHint`in H?H.emptyHint:g(`system.notificationRules.noRulesYet`,`No rules yet.`))}),ge.length>0&&i(Yt,{variant:`bordered`,children:i(Ut,{section:`notification-rules`,bordered:!1,getTags:Sp,searchText:Cp,searchLabel:g(`system.notificationRules.searchRules`,`Search rules`),columns:Ce,rows:ge,rowKey:e=>`${e.family}:${e.id}`,onRowClick:xe,minWidthPx:Np(H.key),maxBodyHeight:`max-h-[60vh]`},H.key)}),T.mode===`form`&&i(cm,{rule:T.rule,...T.seed?{seed:T.seed}:{},targets:P.data??[],actuatable:z,fleet:ne,actions:de,actionsAnswered:ue.data!==void 0,catalog:$r(F.data?.catalog??[]),taxonomy:F.data?.taxonomy,cameras:B,gateable:R.data??[],gateableScenes:ae,initialEditTab:Kr(C??``)??`rule`,onEditTabChange:e=>w(e===`rule`?null:e),onCancel:ve,onSaved:()=>{ve(),M.refetch()}}),V.overlays,D?i(om,{onCancel:()=>O(!1),onPick:e=>{O(!1),be(e)}}):null]})})}function om({onPick:t,onCancel:n}){let{t:r}=Y();return i(Zt,{open:!0,onClose:n,title:r(`system.notificationRules.chooseARuleType`,`Choose a rule type`),width:`lg`,children:i(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:lp.map(n=>e(`button`,{type:`button`,"data-testid":`rules-new-${n.type}`,title:n.hint,onClick:()=>t(n.type),className:`flex flex-col items-start gap-1 rounded-lg border border-border bg-surface px-3 py-3 text-left text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[i(`span`,{className:`font-medium text-foreground`,children:n.label}),i(`span`,{className:`text-[10px] font-normal text-foreground-subtle`,children:n.hint})]},n.type))})})}var sm=1e4;function cm({rule:t,seed:r,targets:a,catalog:c,taxonomy:l,cameras:u,gateable:d,gateableScenes:m,actuatable:h,fleet:_,actions:v,actionsAnswered:y,initialEditTab:x=Si,onEditTabChange:S,onSaved:C,onCancel:w}){let T=j(),{t:E}=Y(),D=t!=null&&t.id.length>0,[O]=o(()=>t?zn(t):Ai(r?.delivery,r?.conditions)),[k,A]=o(O),[ee,M]=o(null),[N,P]=o(D),[te,L]=o(null),[ne,re]=o(x),R=e=>A(t=>({...t,...e})),z=t?Ar(t):void 0,B=f({mutationFn:async()=>{let e=yi(k,z,c,le);if(D&&t){let n=ci(k,c);await T.trpcClient.notificationRules.updateRule.mutate({ruleId:t.id,patch:e,...n.length>0?{clear:n}:{}})}else await T.trpcClient.notificationRules.createRule.mutate({rule:e})},onSuccess:C,onError:e=>M(e instanceof Error?e.message:`Save failed`)}),ie=f({mutationFn:async()=>{let e=yi(k,z,c,le);return(await T.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>L(null),onSuccess:e=>L(e),onError:e=>M(e instanceof Error?e.message:`Test failed`)}),ae=k.targetIds.map(e=>a.find(t=>t.id===e)?.name??e),oe=Ls(),se=Ti(k.targetIds,a,oe),ce=e=>se.get(e)?.shown??!0,le=Ur(a,oe),ue=s({queryKey:[`userManagement`,`listUsers`],queryFn:()=>T.trpcClient.userManagement.listUsers.query()}).data,fe=n(()=>(ue??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[ue]),V=Hn(k),me=V===`immediate-grouped`,H=String(k.groupingSec??20),he=Kn(k).map(e=>({...e,label:e.value===`immediate-grouped`?E(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?E(`notificationRules.grouping.hint`,{n:H,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}}`,H):e.hint})),ge=he.find(e=>e.value===V)?.hint,_e=cn(k,z),ve=Ue(k.delivery),be=je({...k.systemEventDelivery===void 0?{}:{systemEventDelivery:k.systemEventDelivery}}),Se=ve&&be.schedule!==null&&!Xr(k),Ce=xe(k),we=pe(Ce),Te=et(Ce),De=ji.filter(e=>Te.includes(e.value)),Oe=de(k.conditions).length>0,ke=Ee(Ce),Ae=ye(Ce),Me=s({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,Ae??[]],enabled:Ae!==null,queryFn:async()=>{let e=await Promise.all((Ae??[]).map(e=>T.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),Ne=n(()=>{if(Ae===null||Me.data===void 0)return h;let e=Me.data,t=new Set(mr(k.deviceScope));return h.filter(n=>e.has(n.id)||t.has(n.id))},[h,Ae,Me.data,k.deviceScope]),Pe=Ae!==null&&Me.isLoading,Fe=Ae!==null&&Me.isError,Ie=ms(),Le=e=>({family:`rule`,field:e,kind:Ce,delivery:k.delivery,...Xr(k)?{systemEventDelivery:`summary`}:{},...k.conditions.systemEvent?{systemEventKinds:[...k.conditions.systemEvent.kinds]}:{}}),Re=e=>Ie.data?us(Ie.data,Le(e)):void 0,ze=gi(k),Be=y?new Set(v.map(e=>e.id)):ar(k.actions),Ve=Un(k.conditions,vn(k.actions,v)),He=k.conditions.identities!==void 0||k.conditions.plates!==void 0,We=wr(k.delivery,k.conditions),Ge=We.some(e=>e.key===ne)?ne:Si;return kn(k.delivery)?i(Qt,{value:Ge,onValueChange:e=>{let t=Kr(e);t!==void 0&&(re(t),S?.(t))},children:e(Zt,{open:!0,onClose:w,title:D?E(`system.notificationRules.edit`,`Edit {{name}}`,{name:t?.name}):E(`system.notificationRules.newNotificationRule`,`New notification rule`),icon:b,error:ee,width:`lg`,testId:`rule-form-dialog`,beforeBody:e(p,{children:[D&&t&&e(`div`,{className:`mb-3 space-y-2`,children:[i(Al,{kind:`rule`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt}),i(Nl,{ruleId:t.id,cameraName:e=>u.find(t=>t.id===e)?.name??E(`system.notificationRuleStatus.cameraFallback`,{deviceId:e})})]}),i(Kt,{className:`mb-3`,children:We.map(e=>i($t,{value:e.key,children:e.label},e.key))})]}),footer:e(`div`,{className:`flex w-full flex-col gap-3`,children:[ze.length>0&&e(`div`,{"data-testid":`rule-form-dropped`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1 text-left`,children:[i(`p`,{className:`text-foreground`,children:E(`system.notificationRules.savingDrops`,{count:ze.length})}),ze.map(t=>e(`p`,{children:[i(`span`,{className:`text-foreground`,children:t.conditionId}),` — `,t.reason]},t.conditionId))]}),N&&_e.length>0?i(`div`,{"data-testid":`rule-form-problems`,className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1 text-left`,children:_e.map(e=>i(`p`,{children:e},e))}):null,i(`div`,{className:`flex justify-end gap-2`,children:e(q,{size:`sm`,type:`button`,disabled:B.isPending,onClick:()=>{P(!0),M(null),!(!gn(k,z,Be)||B.isPending)&&B.mutate()},children:[B.isPending&&i(g,{className:`h-3.5 w-3.5 animate-spin`}),D?E(`system.notificationRules.saveChanges`,`Save changes`):E(`system.notificationRules.createRule`,`Create rule`)]})})]}),children:[e(W,{value:`rule`,className:`space-y-4`,children:[e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.name`,`Name`)}),i(K,{value:k.name,onChange:e=>R({name:e.target.value}),placeholder:E(`system.notificationRules.eGFrontDoorPackage`,`e.g. Front door package`)})]}),e(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[i(G,{checked:k.enabled,onCheckedChange:e=>R({enabled:e}),"aria-label":E(`system.notificationRules.enabled`,`Enabled`)}),E(`system.notificationRules.enabled`,`Enabled`)]})]}),e(`div`,{children:[i(`span`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`common.tags`,`Tags`)}),i(Ht,{value:k.tags,onChange:e=>R({tags:e}),label:E(`common.tags`,`Tags`)})]}),e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.trigger`,`Trigger`)}),i(I,{value:V,onChange:e=>{let t=lr(e.target.value);t&&A(e=>Qn(e,t))},options:he.map(e=>({value:e.value,label:e.label}))}),ge&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:ge}),me&&e(`div`,{className:`mt-2`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),i(K,{type:`number`,min:5,max:60,step:1,value:H,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=Cn(e.target.value);t!==void 0&&R({groupingSec:t})}}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),He&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`notificationRules.grouping.scopedHint`,{n:H,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,H)})]}),e(`div`,{className:`mt-2`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`notificationRules.groupWithin.seconds`,`Group notifications within (s)`)}),i(K,{type:`number`,min:0,max:300,step:1,value:String(k.groupWithinSec),"data-testid":`rule-group-within-sec`,onChange:e=>{let t=Cn(e.target.value);t!==void 0&&R({groupWithinSec:t})}}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`notificationRules.groupWithin.hint`,`0 sends each notification immediately. Two or more in the window become one summary.`)})]}),V===`immediate`&&He&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!D&&ke!==void 0&&i(Vc,{family:ke,onChange:e=>A(t=>mn(t,e))}),i(mt,{label:E(`system.notificationRules.deliveryTargets`,`Delivery targets`),targets:a,value:k.targetIds,onChange:e=>A(t=>({...t,targetIds:e})),emptyMessage:E(`system.notificationRules.noDeliveryTargetsConfiguredAdd`,`No delivery targets configured. Add one under the Targets tab first.`),testIdPrefix:`rule-target`}),i(Ps,{targetIds:k.targetIds,targets:a,kinds:oe,overrides:k.targetOverrides,targetParams:k.targetParams,rulePriority:k.priority,onOverridesChange:e=>R({targetOverrides:e}),onTargetParamsChange:e=>R({targetParams:e}),varsFor:Re}),i(tn,{mode:`multi`,options:fe,value:k.targetUsers,onChange:e=>R({targetUsers:e}),searchable:!0,creatable:!1,label:E(`system.notificationRules.notifyUsers`,`Notify users`),description:E(`system.notificationRules.deliversToTheTargetsEach`,`Delivers to the targets each user owns, only for cameras that user can access.`),emptyMessage:E(`system.notificationRules.noUsersToNotify`,`No users to notify.`),placeholder:E(`system.notificationRules.searchUsers`,`Search users…`),testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),e(W,{value:`devices`,className:`space-y-4`,children:[Pe&&i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:E(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Fe&&i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:E(`notificationRules.devices.compatFailed`,`Couldn't check which devices this rule's kind can use — every device is listed. The hub still refuses an incompatible one on save.`)}),i(mc,{devices:Ne,scope:k.deviceScope,onChange:e=>R({deviceScope:e}),listState:_.state,savedScope:O.deviceScope,exceptOffered:Jr(c,`devicesExclude`,k)})]}),i(W,{value:`actions`,className:`space-y-4`,children:i(Os,{value:k.actions,onChange:e=>R({actions:e}),actions:v,showProblems:N})}),e(W,{value:`advanced`,className:`space-y-4`,children:[i(rl,{catalog:c,delivery:k.delivery,conditions:k.conditions,onConditionsChange:e=>R({conditions:e})}),e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.cooldownSeconds`,`Cooldown (seconds)`)}),i(K,{type:`number`,min:0,max:Ni,step:1,value:String(k.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=or(e.target.value);t!==void 0&&R({cooldownSec:t})}}),e(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[ve?E(`system.notificationRules.aCameraThatFlapsOr`,`A camera that flaps, or a node that reconnects every minute, would otherwise send one notification per flap. The cooldown is the shortest gap between two deliveries of this rule.`):E(`system.notificationRules.theShortestGapBetweenTwo`,`The shortest gap between two deliveries of this rule, counted as chosen below.`),` `,E(`system.notificationRules.cooldownRange`,{max:String(Ni)})]})]}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.cooldownCounted`,`Cooldown counted`)}),i(I,{value:k.cooldownScope,onChange:e=>{let t=rr(e.target.value);t!==void 0&&R({cooldownScope:t})},options:$n.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`system.notificationRules.perDeviceADeliveryAbout`,`Per device: a delivery about one camera (or node) does not hold back another. Whole rule: one delivery per cooldown, whichever device matched.`)})]}),e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.acrossObjectClasses`,`Across object classes`)}),i(I,{value:k.cooldownGranularity??`per-class`,onChange:e=>R({cooldownGranularity:En(e.target.value)}),options:Or.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`system.notificationRules.separateDefaultADogAfter`,`Separate (default): a dog after a cat is delivered at once, a second cat still waits. Shared: a cat holds back the next dog for the cooldown. Sounds always count per class.`)})]})]}),e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(G,{checked:k.snoozeAllowGlobal,onCheckedChange:e=>R({snoozeAllowGlobal:e}),"aria-label":E(`system.notificationRules.allowGlobalSnooze`,`allow global snooze`),disabled:Ve}),E(`system.notificationRules.anyoneMaySnoozeThisRule`,`Anyone may snooze this rule for everyone`)]}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`system.notificationRules.aSnoozeIsPersonalBy`,`A snooze is personal by default — it silences only the person who set it. Turn this on for a rule where silencing the whole household is legitimate (the gardener is here all afternoon). Admins can always do it.`)})]}),bn(k)&&e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(G,{checked:k.askVerdict===!0,onCheckedChange:e=>R({askVerdict:e}),"aria-label":E(`system.notificationRules.askVerdictAria`,`ask me to confirm detections`),"data-testid":`rule-ask-verdict`}),E(`system.notificationRules.askVerdict`,`Ask me to confirm detections`)]}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`system.notificationRules.askVerdictHint`,`The notification carries Correct and Wrong. A tap marks the detection for retraining, the same mark as in the Library, and records who was asked and when. Channels with no buttons (email, Pushover, Gotify, WhatsApp, Discord) get the same two choices as links.`)})]}),Mi(k)&&e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(G,{checked:k.offerAlertAction!==!1,onCheckedChange:e=>R({offerAlertAction:e}),"aria-label":E(`system.notificationRules.offerAlertActionAria`,`offer the alert’s action`),"data-testid":`rule-offer-alert-action`}),E(`system.notificationRules.offerAlertAction`,`Offer the alert’s action`)]}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E(`system.notificationRules.offerAlertActionHint`,`The notification carries the alert’s own button, such as signing in again.`)})]}),!Ve&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.snoozeButtons`,`Snooze buttons`)}),e(p,{children:[i(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Dr.map(e=>{let t=k.snoozeOptions??Pi,n=t.includes(e);return i(q,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>R({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Vn(e)},e)})}),i(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:k.snoozeOptions===void 0?E(`system.notificationRules.notSetTheNotificationOffers`,`Not set — the notification offers the defaults ({{value1}}). A pause opened from a button silences this camera for this class of subject, only for whoever received the notification, and sends no summary.`,{value1:Pi.map(Vn).join(`, `)}):k.snoozeOptions.length===0?E(`system.notificationRules.noSnoozeButtonsOnThis`,`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`):E(`system.notificationRules.fourAtMostEverySnooze`,`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`)}),k.snoozeOptions!==void 0&&i(q,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>R({snoozeOptions:void 0}),children:E(`system.notificationRules.backToTheDefaults`,`Back to the defaults`)})]})]}),D&&t&&!Ve&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.silenceItNow`,`Silence it now`)}),i(fl,{ruleId:t.id,ruleName:t.name,exempt:Ve,variant:`full`})]})]}),e(W,{value:`notification`,className:`space-y-4`,children:[e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[ce(`priority`)&&e(`div`,{"data-testid":`rule-priority`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.priority`,`Priority`)}),i(I,{value:String(k.priority),onChange:e=>R({priority:Number(e.target.value)}),options:_n.map(e=>({value:String(e.value),label:e.label}))}),i(Is,{support:se.get(`priority`)})]}),!we.carriesMedia&&i(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:we.mediaBlurb??E(`system.notificationRules.aSystemEventCarriesNo`,`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`)}),we.carriesMedia&&!ce(`attachments`)&&i(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-undeliverable`,children:E(`system.notificationRules.targetSettings.noTargetShowsMedia`,`None of the selected targets can show a picture or a clip, so this rule sends none.`)}),we.carriesMedia&&ce(`attachments`)&&we.mediaBlurb!==void 0&&i(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:we.mediaBlurb}),we.carriesMedia&&ce(`attachments`)&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.notificationImage`,`Image`)}),i(Is,{support:se.get(`attachments`)}),i(I,{value:k.mediaImage,onChange:e=>{let t=mi(e.target.value);t&&R({mediaImage:t})},options:De.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-image`}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:De.find(e=>e.value===k.mediaImage)?.description}),e(`div`,{className:`mt-2 space-y-1`,children:[Oe&&k.mediaImage!==`crop`&&k.mediaImage!==`none`&&e(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(F,{checked:k.mediaShowTriggerZone,onChange:e=>R({mediaShowTriggerZone:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-trigger-zone`}),e(`span`,{children:[E(`system.notificationRules.showTriggerZone`,`Draw the zone that triggered the rule`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.showTriggerZoneHelp`,`Outlines the zone on the scene. Not drawn on a subject crop.`)})]})]}),Qe(Ce)&&k.mediaImage!==`none`&&e(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(F,{checked:k.mediaShowSubjectPath,onChange:e=>R({mediaShowSubjectPath:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-subject-path`}),e(`span`,{children:[E(`system.notificationRules.showSubjectPath`,`Show the subject's path`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.showSubjectPathHelp`,`Draws the line the subject walked, up to the moment of the picture. On a crop, only the part inside it.`)})]})]}),e(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[i(F,{checked:k.mediaGif,onChange:e=>R({mediaGif:e.target.checked}),className:`accent-primary`}),E(`system.notificationRules.attachAGifAroundThe`,`Attach a GIF around the event`)]}),e(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[i(F,{checked:k.mediaClip,onChange:e=>R({mediaClip:e.target.checked}),className:`accent-primary`}),E(`system.notificationRules.attachAnMp4ClipAround`,`Attach an MP4 clip around the event`)]})]}),(k.mediaGif||k.mediaClip)&&e(`div`,{className:`mt-2`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.videoQuality`,`Video quality`)}),i(I,{value:k.mediaProfile??``,onChange:e=>R({mediaProfile:Li(e.target.value)}),options:ki.map(e=>({value:e.value,label:e.label}))}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.aNotificationIsWatchedOn`,`A notification is watched on a phone — the cheapest stream is normally the right one, and the high profile only costs CPU to render.`)}),i(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.playbackSpeed`,`Playback speed`)}),i(I,{value:k.mediaClipSpeed===void 0?``:String(k.mediaClipSpeed),onChange:e=>R({mediaClipSpeed:dn(e.target.value)}),options:Fi.map(e=>({value:e.value,label:e.label}))}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.aNotificationClipIsGlanced`,`A notification clip is glanced at, not watched: at 2× the recipient sees the whole passage in half the time and the file is half the size. Real time is there when the detail matters more than the glance.`)})]})]}),Ce===`sensor`&&we.carriesMedia&&k.mediaImage!==`none`&&e(`div`,{children:[i(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:E(`system.notificationRules.linkedCameras`,`Linked cameras`)}),i(I,{value:k.mediaLinkedCameras??``,onChange:e=>R({mediaLinkedCameras:Pn(e.target.value)}),options:tr.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.whenTheSensorIsLinked`,`When the sensor is linked to several cameras, all of them are photographed the moment it fires. Cameras that are offline or asleep are left out.`)}),e(`label`,{className:`mt-2 flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[i(F,{checked:k.mediaWakeSleepingCamera!==!1,onChange:e=>R({mediaWakeSleepingCamera:e.target.checked?void 0:!1}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-wake-sleeping-camera`}),e(`span`,{children:[E(`system.notificationRules.wakeSleepingCamera`,`Wake a sleeping battery camera for the picture`),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.wakeSleepingCameraHelp`,`Costs battery and waits up to 15 s before the notification is sent.`)})]})]})]})]}),e(`div`,{className:`space-y-2`,children:[ce(`title`)&&e(p,{children:[i(vs,{label:E(`system.notificationRules.notificationTitle`,`Notification title`),value:k.templateTitle,onChange:e=>R({templateTitle:e}),vars:Re(`title`),testId:`rule-template-title`}),i(Is,{support:se.get(`title`)})]}),ce(`body`)&&e(p,{children:[i(vs,{label:E(`system.notificationRules.notificationBody`,`Notification body`),value:k.templateBody,onChange:e=>R({templateBody:e}),vars:Re(`body`),multiline:!0,testId:`rule-template-body`}),i(Is,{support:se.get(`body`)})]}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.leaveBothBlankForThe`,`Leave both blank for the hub's own wording (editable on the Texts tab).`)}),Gn(k)!==null&&i(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:Gn(k)}),i(ys,{context:Le(`body`),title:k.templateTitle,body:k.templateBody,testId:`rule-template-preview`})]}),ve&&i(Kp,{value:k.systemEventDelivery,family:ke,kinds:k.conditions.systemEvent?.kinds??[],onChange:e=>R({systemEventDelivery:e}),draft:()=>yi(k,z,c,le)})]}),e(W,{value:`conditions`,className:`space-y-4`,children:[e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[i(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:ve?E(`system.notificationRules.whichSystemEvents`,`Which system events`):ai(k.conditions)??E(`system.notificationRules.conditions`,`Conditions`)}),k.conditions.audio!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.thisIsASoundRule`,`This is a SOUND rule: it fires on a confirmed sampling window of audio, never on a picture. Name the sounds and/or keep a level threshold — with neither it can never match. Everything else below still composes (a camera scope, a schedule).`)}),k.conditions.occupancy!==void 0&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.thisIsAnOccupancyRule`,`This is an OCCUPANCY rule: it fires when the count in a camera frame or a zone crosses your threshold and holds. Pick the camera on the Devices tab first — the zone list is that camera's.`)}),ve&&i(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.pickTheEventsThisRule`,`Pick the events this rule reacts to, then narrow them if you want. Nothing else on a system rule is a condition — there is no detection behind it.`)}),c.length===0?i(`p`,{className:`text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.conditionCatalogUnavailableThisRule`,`Condition catalog unavailable — this rule matches on its trigger and targets alone.`)}):i(Hc,{catalog:Xr(k)?c.filter(e=>e.id!==`schedule`):c,taxonomy:l,delivery:k.delivery,conditions:k.conditions,classScope:k.classScope,onClassScopeChange:e=>R({classScope:e}),actions:Ii(k.actions),actionStepsOf:e=>v.find(t=>t.id===e)?.steps,savedConditions:O.conditions,schedule:k.schedule,deviceIds:er(k),zoneCameraIds:nc(k.deviceScope,u),cameras:u,fleet:_,allDevices:h,gateable:d,gateableScenes:m,onConditionsChange:e=>R({conditions:e}),onScheduleChange:e=>R({schedule:e}),scheduleOnly:Xr(k)})]}),D&&t&&e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:E(`system.notificationRules.testThisRuleForReal`,`Test this rule for real`)}),i(Ul,{ruleId:t.id,ruleName:t.name,variant:`full`,showResult:!0,...er(k)[0]===void 0?{}:{fallbackDeviceId:er(k)[0]}})]}),Se&&e(`div`,{className:`mt-2 flex items-center justify-between gap-2`,children:[i(`span`,{className:`text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.sendSummaryHint`,`The scheduled summary is sent on its own: to every target, now.`)}),i(Ul,{ruleId:t.id,ruleName:t.name,variant:`full`,showResult:!0,summary:!0})]}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.buildsTheEventThisRule`,`Builds the event this rule is about, runs the REAL evaluation and delivery, and sends the notification to every target — marked [TEST] in the body. The cooldown and the camera mute are bypassed (neither window is consumed); the rule's actions are never run. Saved conditions only: save first to test an edit.`)})]}),!ve&&e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:E(`system.notificationRules.testRule`,`Test rule`)}),e(q,{size:`sm`,variant:`outline`,type:`button`,disabled:ie.isPending||!gn(k,z,Be),onClick:()=>{M(null),ie.mutate()},children:[ie.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(ct,{className:`h-3.5 w-3.5`}),E(`system.notificationRules.dryRunLast60Min`,`Dry-run (last 60 min)`)]})]}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:E(`system.notificationRules.evaluateTheCurrentUnsavedRule`,`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`)}),te!==null&&i(um,{delivery:k.delivery,results:te,targetNames:ae})]})]})]})}):i(lm,{rule:t,onCancel:w})}function lm({rule:t,onCancel:n}){let{t:r}=Y(),a=Object.keys(t?.conditions??{});return e(Zt,{open:!0,onClose:n,title:t?.name??r(`system.notificationRules.rule`,`Rule`),icon:b,width:`lg`,children:[i(U,{variant:`warning`,className:`mb-3`,children:`read-only`}),i(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,"data-testid":`unsupported-trigger-notice`,children:i(br,{i18nKey:`system.notificationRules.unsupportedTrigger`,values:{trigger:t?.delivery},components:{code:i(`code`,{})}})}),e(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.trigger`,`Trigger`)}),i(`dd`,{className:`text-foreground`,children:t?.delivery})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.enabled`,`Enabled`)}),i(`dd`,{className:`text-foreground`,children:t?.enabled?r(`common.yes`):r(`common.no`)})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.targets`,`Targets`)}),i(`dd`,{className:`text-foreground`,children:t?.targets.length??0})]}),e(`div`,{className:`flex gap-2`,children:[i(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:r(`system.notificationRules.conditions`,`Conditions`)}),i(`dd`,{className:`text-foreground`,children:a.length>0?a.join(`, `):r(`common.none`)})]})]})]})}function um({delivery:t,results:n,targetNames:r}){let{t:a}=Y();if(t===`device-event`)return i(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.deviceEventRulesCannotBe`,`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`)});if(n.length===0)return i(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.noRecordsInTheLast`,`No records in the last 60 minutes matched — nothing to evaluate.`)});let o=n.filter(e=>e.wouldFire).length;return e(`div`,{className:`mt-2 space-y-1.5`,children:[i(`div`,{className:`text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.wouldFire`,{firing:o,count:n.length})}),i(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:n.slice(0,50).map(t=>e(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[t.wouldFire?i(C,{className:`h-3.5 w-3.5 shrink-0 text-success`}):i(P,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(t.timestamp).toLocaleString()}),e(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,t.deviceId]}),i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:t.label??t.className??a(`system.notificationRules.objectFallback`)}),t.wouldFire?e(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,r.join(`, `)||a(`system.notificationRules.targetsFallback`)]}):t.failedCondition&&e(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,t.failedCondition]})]},t.recordId))})]})}var dm=`alert-center`,fm=`alerts`;function pm(){let{t}=Y(),n=j();return e(`div`,{className:`space-y-3`,"data-testid":`notification-settings`,children:[i(`p`,{className:ae,children:t(`systemPage.notifications.settingsHint`,`Alert storage and retention. Alerts are notified only through notification rules on the alert kinds.`)}),i(kt,{trpc:n.trpcClient,addonId:dm,cap:fm,scope:`cluster`,bare:!0})]})}var mm=[{value:`object-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.objectLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.objectHint`)}},{value:`track-end`,get label(){return J.t(`helpers.notificationSimulateHelpers.trackEndLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.trackEndHint`)}},{value:`device-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.deviceEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.deviceEventHint`)}},{value:`package-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.packageEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.packageEventHint`)}},{value:`audio-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.audioEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.audioEventHint`)}},{value:`occupancy-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.occupancyEdgeLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.occupancyEdgeHint`)}}];function hm(e){return mm.find(t=>t.value===e)?.value}function gm(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function _m(e){return``}var vm={x:.25,y:.25,w:.5,h:.5},ym={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function bm(){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:vm,occupancy:ym,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function xm(e){return e.deviceId!==null}function Sm(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Cm(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function wm(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function Tm(e){if(e.deviceId===null)return null;let t=e.trigger,n=Cm(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:Em(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 Em(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 Dm(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Om(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 km(e){let t=bm(),n=e.conditions,r=Om(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:Dm(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Dm(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Dm(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:_m(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Am(n.occupancy)},onlyRuleId:e.id}}function Am(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 jm(e){let t=[];return e.conditions.deviceState!==void 0&&t.push({conditionId:`deviceState`,note:J.t(`helpers.notificationSimulateHelpers.caveatDevice`,{deviceId:e.conditions.deviceState.deviceId})}),e.conditions.scene!==void 0&&t.push({conditionId:`scene`,note:J.t(`helpers.notificationSimulateHelpers.caveatScene`,{state:e.conditions.scene.requiredState})}),e.conditions.customZones!==void 0&&e.conditions.customZones.length>0&&t.push({conditionId:`customZones`,note:J.t(`helpers.notificationSimulateHelpers.caveatZones`)}),t}function Mm(e){return{form:km(e),caveats:jm(e),ruleName:e.name}}var Nm=null;function Pm(e){Nm=e}function Fm(){return Nm}function Im(){Nm=null}var Lm=[`n/a`,`clear`,`suppressed`,`bypassed`],Rm=[`live`,`none`,`unavailable`,`unattachable`];function zm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bm(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Vm(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Hm(e){if(!zm(e))return null;let t=Bm(e,`ruleId`),n=Bm(e,`ruleName`),r=Bm(e,`cooldown`),i=Lm.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Bm(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Vm(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:Vm(e,`targetIds`)}}function Um(e){if(!zm(e))return null;let t=Bm(e,`recordId`),n=Bm(e,`delivery`),r=Bm(e,`still`),i=Rm.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=Hm(e);t!==null&&o.push(t)}let s=Bm(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Vm(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Wm(e){if(e.droppedBy!==void 0)return J.t(`helpers.notificationSimulateHelpers.dropped`,{reason:e.droppedBy});if(e.candidates===0)return J.t(`helpers.notificationSimulateHelpers.noCandidates`,{delivery:e.delivery});let t=e.outcomes.filter(e=>e.matched).length,n=e.outcomes.reduce((e,t)=>e+t.enqueued,0);return t===0?J.t(`helpers.notificationSimulateHelpers.noneMatched`,{count:e.candidates}):J.t(`helpers.notificationSimulateHelpers.matchedSummary`,{matched:t,candidates:e.candidates,enqueued:n})}var Gm=new Set([`sensor`,`control`,`custom`]);function Km({form:t,cameras:n,taxonomy:r,kinds:a,kindsLoading:o,onPatch:s}){let{t:c}=Y(),l=t.deviceId===null?[]:[t.deviceId],u=Ce(`classes`,r);if(t.trigger===`device-event`)return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(qm,{form:t,kinds:a,loading:o,onPatch:s})]});if(t.trigger===`audio-event`){let r=a.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),e(`div`,{children:[i(`label`,{className:X,children:c(`system.notificationSimulateFields.audioClasses`,`Audio classes`)}),i(fr,{options:r,value:t.classNames,onChange:e=>s({classNames:e}),loading:o,emptyHint:t.deviceId===null?`Pick a camera first — the audio vocabulary is per camera.`:`This camera advertises no audio kinds. The audio classifier is probably off for it.`,placeholder:c(`system.notificationSimulateFields.audioClassId`,`Audio class id…`)})]}),e(`div`,{children:[i(`label`,{className:X,children:c(`system.notificationSimulateFields.zones`,`Zones`)}),i(Ir,{deviceIds:l,cameras:n,value:t.zones,onChange:e=>s({zones:e})})]})]})}return t.trigger===`occupancy-event`?e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),i(Jm,{form:t,cameras:n,taxonomy:r,onPatch:s})]}):e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),e(`div`,{children:[i(`label`,{className:X,children:c(`system.notificationSimulateFields.detectedClasses`,`Detected classes`)}),u===null?i(Yn,{value:t.classNames,placeholder:c(`system.notificationSimulateFields.classIdPersonCar`,`Class id (person, car…)`),onChange:e=>s({classNames:e})}):i(sn,{picker:u,value:t.classNames,onChange:e=>s({classNames:e})})]}),e(`div`,{children:[i(`label`,{className:X,children:c(`system.notificationSimulateFields.zonesTheSubjectIsIn`,`Zones the subject is in`)}),i(Ir,{deviceIds:l,cameras:n,value:t.zones,onChange:e=>s({zones:e})})]}),t.trigger===`package-event`&&e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:`block text-[11px] font-medium text-foreground`,children:c(`system.notificationSimulateFields.packagePhase`,`Package phase`)}),i(I,{value:t.packagePhase,options:[{value:``,label:c(`system.notificationSimulateFields.none`,`— none —`)},{value:`delivered`,label:c(`system.notificationSimulateFields.delivered`,`Delivered`)},{value:`picked-up`,label:c(`system.notificationSimulateFields.pickedUp`,`Picked up`)}],onChange:e=>s({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function qm({form:t,kinds:n,loading:r,onPatch:a}){let{t:o}=Y(),s=n.filter(e=>Gm.has(e.category)),c=s.find(e=>e.kind===t.sensorKind);return e(p,{children:[e(`div`,{children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.eventKind`,`Event kind`)}),i(I,{value:t.sensorKind,options:[{value:``,label:r?o(`system.notificationSimulateFields.loadingKinds`,`Loading kinds…`):o(`system.notificationSimulateFields.pickAKind`,`— pick a kind —`)},...s.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=s.find(t=>t.kind===e.target.value);a({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!r&&s.length===0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:t.deviceId===null?o(`system.notificationSimulateFields.pickACameraFirstSensor`,`Pick a camera first — sensor and control kinds come from the devices linked to it.`):o(`system.notificationSimulateFields.thisCameraHasNoLinked`,`This camera has no linked sensor or control device, so it can produce no device event. Link one on the camera page first.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.sourceDevice`,`Source device`)}),i(K,{type:`number`,value:t.sourceDeviceId===null?``:String(t.sourceDeviceId),placeholder:o(`system.notificationSimulateFields.theCameraItself`,`the camera itself`),onChange:e=>a({sourceDeviceId:Sm(e.target.value)??null})}),i(`p`,{className:Fn,children:c===void 0?o(`system.notificationSimulateFields.theLinkedDeviceWhoseState`,`The linked device whose state changed. Filled in for you when you pick a kind.`):o(`system.notificationSimulateFields.filledInFromContributedBy`,`Filled in from "{{label}}" — contributed by device #{{deviceId}} via the {{capName}} capability.`,{label:c.label,deviceId:c.source.deviceId,capName:c.source.capName})})]}),e(`div`,{children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.eventTypeToken`,`Event type token`)}),i(K,{value:t.eventType,placeholder:o(`system.notificationSimulateFields.pressPressLong`,`press, press_long…`),onChange:e=>a({eventType:e.target.value})}),i(`p`,{className:Fn,children:o(`system.notificationSimulateFields.onlyEventEmitterSourcesCarry`,`Only event-emitter sources carry one. A passive sensor emits none, and a rule gating on a token would fail closed for it.`)})]})]})]})}function Jm({form:t,cameras:n,taxonomy:r,onPatch:a}){let{t:o}=Y(),s=t.deviceId===null?[]:[t.deviceId],c=Ce(`occupancy`,r),l=c===null?[]:c.groups.flatMap(e=>e.options),u=t.occupancy,d=e=>a({occupancy:{...u,...e}});return e(p,{children:[e(`div`,{children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.zone`,`Zone`)}),i(Ir,{deviceIds:s,cameras:n,value:u.zoneId===``?[]:[u.zoneId],onChange:e=>d({zoneId:e[e.length-1]??``})}),i(`p`,{className:Fn,children:o(`system.notificationSimulateFields.leaveEmptyForTheWhole`,`Leave empty for the whole frame.`)})]}),e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:X,children:o(`system.notificationSimulateFields.class`,`Class`)}),i(I,{value:u.className,options:[{value:``,label:o(`system.notificationSimulateFields.anyClass`,`— any class —`)},...l.map(e=>({value:e.value,label:e.label}))],onChange:e=>d({className:e.target.value})})]}),e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countNow`,`Count now`),i(K,{type:`number`,min:0,className:`w-20`,value:String(u.count),onChange:e=>d({count:Sm(e.target.value)??0})})]}),e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countBefore`,`Count before`),i(K,{type:`number`,min:0,className:`w-20`,value:String(u.previousCount),onChange:e=>d({previousCount:Sm(e.target.value)??0})})]}),e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.threshold`,`Threshold`),i(K,{type:`number`,min:1,className:`w-20`,value:String(u.threshold),onChange:e=>d({threshold:Sm(e.target.value)??1})})]}),e(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[i(G,{checked:u.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":o(`system.notificationSimulateFields.occupiedLabel`)}),o(`system.notificationSimulateFields.occupiedLabel`,`Occupied`)]})]})]})}function Ym({form:t,cameras:n,onPatch:r}){let{t:a}=Y(),o=t.deviceId===null?[]:[t.deviceId];return e(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[i(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:a(`system.notificationSimulateFields.advanced`,`Advanced`)}),e(`div`,{className:`mt-2 space-y-3`,children:[t.trigger===`object-event`&&e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(G,{checked:t.crossingEnabled,onCheckedChange:e=>r({crossingEnabled:e}),"aria-label":a(`system.notificationSimulateFields.zoneCrossing`,`zone crossing`)}),a(`system.notificationSimulateFields.thisEventIsAConfirmed`,`This event is a confirmed zone crossing`)]}),t.crossingEnabled&&e(`div`,{className:`mt-1 space-y-1.5`,children:[i(`div`,{className:`max-w-[12rem]`,children:i(I,{value:t.crossingDirection,options:[{value:`enter`,label:a(`system.notificationSimulateFields.enteredTheZone`,`Entered the zone`)},{value:`exit`,label:a(`system.notificationSimulateFields.leftTheZone`,`Left the zone`)}],onChange:e=>r({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),i(Ir,{deviceIds:o,cameras:n,value:t.crossingZoneId===``?[]:[t.crossingZoneId],onChange:e=>r({crossingZoneId:e[e.length-1]??``})})]})]}),e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(G,{checked:t.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":a(`system.notificationSimulateFields.boundingBox`,`bounding box`)}),a(`system.notificationSimulateFields.carryABoundingBox`,`Carry a bounding box`)]}),i(`p`,{className:Fn,children:a(`system.notificationSimulateFields.normalized01TopLeft`,"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed.")}),t.bboxEnabled&&i(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(n=>e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[n,i(K,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(t.bbox[n]),onChange:e=>r({bbox:{...t.bbox,[n]:Sm(e.target.value)??0}})})]},n))})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:X,children:a(`system.notificationSimulateFields.happenedAt`,`Happened at`)}),e(`div`,{className:`flex items-center gap-2`,children:[i(K,{type:`datetime-local`,value:t.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),t.timestampLocal===``?i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:wm(Date.now())}),children:a(`system.notificationSimulateFields.set`,`Set`)}):i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:a(`system.notificationSimulateFields.now`,`Now`)})]}),i(`p`,{className:Fn,children:a(`system.notificationSimulateFields.emptyNowSetItTo`,`Empty = now. Set it to a time inside (or outside) a rule's schedule window to test the schedule without waiting for the hour.`)})]}),e(`div`,{children:[i(`label`,{className:X,children:a(`system.notificationSimulateFields.detectionSource`,`Detection source`)}),i(I,{value:t.source,options:[{value:``,label:a(`system.notificationSimulateFields.unsetReadsAsPipeline`,`— unset (reads as pipeline) —`)},{value:`pipeline`,label:a(`system.notificationSimulateFields.pipeline`,`Pipeline`)},{value:`onboard`,label:a(`system.notificationSimulateFields.onboardCamera`,`Onboard (camera)`)},{value:`sensor`,label:a(`system.notificationSimulateFields.sensor`,`Sensor`)},{value:`audio`,label:a(`system.notificationSimulateFields.audio`,`Audio`)}],onChange:e=>{let t=e.target.value;r({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function Xm({checked:t,label:n,hint:r,danger:a=!1,onChange:o}){let{t:s}=Y();return e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[i(G,{checked:t,onCheckedChange:o,"aria-label":n}),n,a&&i(U,{variant:`danger`,children:s(`system.notificationSimulateFields.actuatesDevices`,`actuates devices`)})]}),i(`p`,{className:Fn,children:r})]})}c();var Zm={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.`},Qm={"n/a":`The rule did not match, so no cooldown was consulted.`,clear:`No cooldown was in effect — the rule was free to fire.`,suppressed:`A cooldown from an earlier fire silenced this one. Re-run with "Ignore cooldown".`,bypassed:`A cooldown was in effect and was deliberately ignored for this run.`};function $m({result:t,targetName:n}){let{t:r}=Y();return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[i(`p`,{className:`text-xs font-medium text-foreground`,children:Wm(t)}),e(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[i(eh,{recordId:t.recordId}),i(`span`,{children:i(br,{i18nKey:`system.notificationSimulateResult.delivery`,values:{value:t.delivery},components:{b:i(`span`,{className:`text-foreground`})}})}),i(`span`,{children:i(br,{i18nKey:`system.notificationSimulateResult.candidates`,values:{value:t.candidates},components:{b:i(`span`,{className:`text-foreground`})}})}),i(`span`,{title:Zm[t.still],children:i(br,{i18nKey:`system.notificationSimulateResult.still`,values:{value:t.still},components:{b:i(`span`,{className:`text-foreground`})}})}),t.droppedBy!==void 0&&i(U,{variant:`warning`,children:r(`system.notificationSimulateResult.droppedBy`,{by:t.droppedBy})})]}),t.notes.length>0&&i(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:t.notes.map(e=>i(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),t.outcomes.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:i(br,{i18nKey:`system.notificationSimulateResult.noRuleEvaluated`,values:{delivery:t.delivery},components:{b:i(`span`,{className:`text-foreground`})}})}):i(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.outcomes.map(e=>i(th,{outcome:e,targetName:n},e.ruleId))})]})}function eh({recordId:t}){let{t:n}=Y(),[r,a]=o(!1);return e(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[i(`code`,{className:`text-[10px] text-foreground`,children:t}),i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let e=navigator.clipboard;e!==void 0&&e.writeText(t).then(()=>{a(!0),setTimeout(()=>a(!1),1500)},()=>a(!1))},title:n(`system.notificationSimulateResult.copyRecordId`,`Copy record id`),children:i(y,{className:`h-3 w-3`})}),r&&i(`span`,{className:`text-[10px] text-success`,children:n(`common.copiedLower`)})]})}function th({outcome:t,targetName:n}){let{t:r}=Y();return e(`li`,{className:`space-y-1 px-2.5 py-2`,children:[e(`div`,{className:`flex items-center gap-2`,children:[t.matched?i(C,{className:`h-3.5 w-3.5 shrink-0 text-success`}):i(P,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:t.ruleName}),e(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:Qm[t.cooldown],children:[`cooldown: `,t.cooldown]})]}),!t.matched&&i(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:t.failedCondition===void 0?r(`system.notificationSimulateResult.didNotMatchTheEngine`,`Did not match. The engine reported no failing condition id.`):i(br,{i18nKey:`system.notificationSimulateResult.failingCondition`,values:{condition:t.failedCondition},components:{code:i(`code`,{className:`text-foreground`})}})}),t.matched&&e(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[r(`system.notificationSimulateResult.enqueued`,{count:t.enqueued}),t.targetIds.length>0?` → ${t.targetIds.map(n).join(`, `)}`:` — ${r(`system.notificationSimulateResult.noTargetResolved`)}`,`.`]}),t.matchedOn!==void 0&&t.matchedOn.length>0&&i(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:r(`system.notificationSimulateResult.matchedOn`,{on:t.matchedOn.join(`, `)})})]})}c();var nh=`pipeline-analytics`,rh=`nc.injectTestEvent`;function ih(){let{t}=Y(),r=j(),[c,l]=o(()=>Fm()?.form??bm()),[u,d]=o(()=>Fm()?.caveats??[]),[p,m]=o(()=>Fm()?.ruleName??null);a(()=>Im(),[]);let[h,_]=o(null),[v,y]=o(!1),[b,x]=o(null),S=e=>l(t=>({...t,...e})),C=Vt({projection:`slim`}),T=s({queryKey:nm,queryFn:()=>r.trpcClient.notificationRules.getConditionCatalog.query({})}),E=s({queryKey:tm,queryFn:async()=>(await r.trpcClient.notificationRules.listRules.query({})).rules}),D=Hi(),O=c.deviceId,k=s({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:O}],enabled:O!==null,staleTime:6e4,queryFn:async()=>O===null?[]:(await r.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[O]})).flatMap(e=>[...e.kinds])}),A=n(()=>(C.data??[]).filter(e=>e.type===Je.Camera).map(e=>({id:e.id,name:e.name})),[C.data]),ee=T.data?.taxonomy,M=k.data??[],N=n(()=>{let e=new Map;for(let t of D.data??[])e.set(t.id,t.name);return e},[D.data]),P=f({mutationFn:async()=>{let e=Tm(c);if(e===null)throw Error(`Pick a camera first.`);return r.trpcClient.addons.custom.mutate({addonId:nh,action:rh,input:e})},onMutate:()=>{_(null),y(!1),x(null)},onSuccess:e=>{let t=Um(e);_(t),y(t===null)},onError:e=>x(e instanceof Error?e.message:`The simulation failed.`)}),F=gm(c.trigger),te=E.data?.find(e=>e.id===c.onlyRuleId);return e(Ui,{embedded:!0,icon:ct,title:t(`system.notificationSimulate.simulateAnEvent`,`Simulate an event`),subtitle:t(`system.notificationSimulate.injectASyntheticDetectionDoorbell`,`Inject a synthetic detection, doorbell press or occupancy edge and see exactly which rules match it, which condition each one fails on, and what would be delivered. Nothing is persisted — no track, no event row, no media.`),children:[C.isError&&i(dt,{title:t(`system.notificationSimulate.failedToLoadCameras`,`Failed to load cameras`),message:C.error instanceof Error?C.error.message:t(`system.notificationSimulate.unknownError`,`Unknown error`),onRetry:()=>void C.refetch()}),p!==null&&i(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:i(br,{i18nKey:`system.notificationSimulate.seededFrom`,values:{rule:p},components:{b:i(`span`,{className:`font-medium`})}})}),u.length>0&&i(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:u.map(t=>e(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[i(w,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),i(`span`,{children:t.note})]},t.conditionId))}),e(Yt,{className:`space-y-4`,children:[e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.ruleToSimulate`,`Rule to simulate`)}),i(I,{"data-testid":`simulate-seed-rule`,value:c.onlyRuleId,options:[{value:``,label:t(`system.notificationSimulate.pickARuleToPrefill`,`— pick a rule to prefill trigger + conditions —`)},...(E.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.delivery}`}))],onChange:e=>{let t=e.target.value;if(t.length===0){l(bm()),d([]),m(null);return}let n=E.data?.find(e=>e.id===t);if(n===void 0){S({onlyRuleId:t});return}l(km(n)),d(jm(n)),m(n.name)}}),i(`p`,{className:Fn,children:t(`system.notificationSimulate.picksTheTriggerThatRule`,`Picks the trigger that rule listens for and fills the fields from its conditions. Edit any value below, then inject.`)})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.camera`,`Camera`)}),i(I,{"data-testid":`simulate-camera`,value:c.deviceId===null?``:String(c.deviceId),options:[{value:``,label:A.length===0?t(`system.notificationSimulate.loadingCameras`,`Loading cameras…`):t(`system.notificationSimulate.pickACamera`,`— pick a camera —`)},...A.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{S({deviceId:Sm(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...c.occupancy,zoneId:``}})}}),i(`p`,{className:Fn,children:t(`system.notificationSimulate.theCameraTheEventIs`,`The camera the event is attributed to — what a notification shows.`)})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.trigger`,`Trigger`)}),i(I,{"data-testid":`simulate-trigger`,value:c.trigger,options:mm.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=hm(e.target.value);if(!t)return;let n=_m(c.trigger);S({trigger:t,source:c.source===``||c.source===n?_m(t):c.source})}}),e(`p`,{className:Fn,children:[mm.find(e=>e.value===c.trigger)?.hint,` `,i(br,{i18nKey:`system.notificationSimulate.onlyRulesWhoseTrigger`,values:{delivery:F},components:{b:i(`span`,{className:`text-foreground`})}})]})]}),i(Km,{form:c,cameras:A,taxonomy:ee,kinds:M,kindsLoading:k.isLoading,onPatch:S}),e(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[i(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:t(`system.notificationSimulate.quality`,`Quality`)}),e(`div`,{className:`mt-2 space-y-3`,children:[i(`p`,{className:Fn,children:t(`system.notificationSimulate.everyFieldHereCanBe`,`Every field here can be left EMPTY, and empty is a real state: a rule with a minimum confidence FAILS on a subject that carries none. Leave one blank to reproduce exactly that.`)}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.labelIdentityNamePlateSubclass`,`Label (identity name / plate / subclass)`)}),i(K,{value:c.label,placeholder:t(`system.notificationSimulate.eGMarcoAb123cd`,`e.g. Marco, AB123CD`),onChange:e=>S({label:e.target.value})})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.detectionConfidence`,`Detection confidence`)}),i(Mn,{value:c.confidence,min:0,max:1,step:.05,onChange:e=>S({confidence:e})})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.labelMatchConfidence`,`Label-match confidence`)}),i(Mn,{value:c.labelConfidence,min:0,max:1,step:.05,onChange:e=>S({labelConfidence:e})})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.importance`,`Importance`)}),i(Mn,{value:c.importance,min:0,max:1,step:.05,onChange:e=>S({importance:e})})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.dwellSeconds`,`Dwell (seconds)`)}),i(Mn,{value:c.dwellSeconds,min:0,step:1,onChange:e=>S({dwellSeconds:e})})]})]})]})]}),i(Ym,{form:c,cameras:A,onPatch:S}),e(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`text-[11px] font-semibold text-foreground`,children:t(`system.notificationSimulate.howToRunIt`,`How to run it`)}),i(Xm,{checked:c.bypassCooldown,label:t(`system.notificationSimulate.ignoreTheCooldown`,`Ignore the cooldown`),hint:t(`system.notificationSimulate.aRuleThatAlreadyFired`,`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`),onChange:e=>S({bypassCooldown:e})}),i(Xm,{checked:c.bypassMute,label:t(`system.notificationSimulate.ignoreMutesAndSnoozes`,`Ignore mutes and snoozes`),hint:t(`system.notificationSimulate.aMutedCameraOrA`,`A muted camera or a snoozed rule drops the event before any rule is consulted.`),onChange:e=>S({bypassMute:e})}),i(Xm,{checked:c.runActions,danger:!0,label:t(`system.notificationSimulate.runTheRuleSActions`,`Run the rule's actions — this actuates real devices`),hint:t(`system.notificationSimulate.aMatchedRuleSOntrigger`,`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`),onChange:e=>S({runActions:e})}),e(`div`,{className:`max-w-[14rem]`,children:[i(`label`,{className:X,children:t(`system.notificationSimulate.stillImage`,`Still image`)}),i(I,{value:c.still,options:[{value:`live`,label:t(`system.notificationSimulate.liveSnapshotOfTheCamera`,`Live snapshot of the camera`)},{value:`none`,label:t(`system.notificationSimulate.noImage`,`No image`)}],onChange:e=>S({still:e.target.value===`none`?`none`:`live`})})]}),e(`div`,{children:[i(`label`,{className:X,children:t(`system.notificationSimulate.evaluateOnlyOneRule`,`Evaluate only one rule`)}),i(I,{value:c.onlyRuleId,options:[{value:``,label:t(`system.notificationSimulate.everyEnabledRule`,`— every enabled rule —`)},...(E.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>S({onlyRuleId:e.target.value})}),c.onlyRuleId.length>0&&te===void 0&&i(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:i(br,{i18nKey:`system.notificationSimulate.ruleNotInList`,values:{id:c.onlyRuleId},components:{code:i(`code`,{})}})})]})]}),b!==null&&i(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:b}),e(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[i(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:t(`system.notificationSimulate.nothingIsPersistedNoTrack`,`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`)}),e(q,{size:`sm`,type:`button`,disabled:P.isPending||!xm(c),onClick:()=>P.mutate(),children:[P.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(ct,{className:`h-3.5 w-3.5`}),t(`system.notificationSimulate.injectEvent`,`Inject event`)]})]})]}),v&&i(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:t(`system.notificationSimulate.theHubAnsweredButThis`,`The hub answered, but this build could not read the answer. That is what a hub older than the simulator looks like — update the server, then re-run.`)}),h!==null&&i($m,{result:h,targetName:e=>N.get(e)??e})]})}var ah=e=>typeof e==`string`&&e.length>0;function oh(e){let t=qe(e);return{showTitle:t.includes(`title`),showBody:t.includes(`body`),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 sh(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function ch(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];ah(i)&&n.push({mediaType:r,url:i})}return n}function lh(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=ah(r.label),i=ah(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:J.t(`helpers.notificationTestComposer.actionN`,{n:n.length+1}),...i?{url:r.url}:{}})}return n}function uh(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=ch(e,t.attachmentUrls),i=lh(e,t.actions),a=e.ttl&&ah(t.ttl)?Number(t.ttl):void 0,o=qe(e);return{body:o.includes(`body`)?t.body:``,format:sh(e,t.format),priority:ph(t.priority),...o.includes(`title`)&&ah(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&ah(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&ah(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...ah(t.tag)?{tag:t.tag}:{}}}function dh(e,t){let n=qe(e);return n.includes(`body`)?t.body.length>0:n.includes(`title`)?t.title.length>0:!0}function fh(e,t){let n=qe(e),r=n.includes(`body`),i=n.includes(`title`);return r&&i?t:r?{...t,title:``}:i?{...t,title:t.body.length>0?t.body:t.title,body:``}:{...t,title:``,body:``}}function ph(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function mh(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 hh(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var gh={image:S(`/addon/notifiers/samples/image`),video:S(`/addon/notifiers/samples/video`),gif:S(`/addon/notifiers/samples/gif`),audio:S(`/addon/notifiers/samples/audio`),icon:S(`/addon/notifiers/samples/icon`)};function _h(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function vh(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])_h(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),qe(e).includes(`body`)&&t.push(`overflow`),t}function yh(e,t,n){let r=hh(e);return _h(e,t)?{...r,body:n,attachmentUrls:{[t]:gh[t]}}:{...r,body:n}}function bh(e,t){return fh(e,xh(e,t))}function xh(e,t){let n=hh(e);switch(t){case`text`:return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetText`)};case`image`:return yh(e,`image`,J.t(`helpers.notificationTestComposer.presetImage`));case`gif`:return yh(e,`gif`,J.t(`helpers.notificationTestComposer.presetGif`));case`video`:return yh(e,`video`,J.t(`helpers.notificationTestComposer.presetVideo`));case`audio`:return yh(e,`audio`,J.t(`helpers.notificationTestComposer.presetAudio`));case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:J.t(`helpers.notificationTestComposer.actionN`,{n:t+1}),url:`/`}));return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetActions`),actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=mh(e);return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetCritical`),priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}c();var Sh={get text(){return J.t(`system.notificationTestPanel.presetText`)},get image(){return J.t(`system.notificationTestPanel.presetImage`)},get gif(){return J.t(`system.notificationTestPanel.presetGif`)},get video(){return J.t(`system.notificationTestPanel.presetVideo`)},get audio(){return J.t(`system.notificationTestPanel.presetAudio`)},get actions(){return J.t(`system.notificationTestPanel.presetActions`)},get critical(){return J.t(`system.notificationTestPanel.presetCritical`)},get overflow(){return J.t(`system.notificationTestPanel.presetOverflow`)}},Ch=`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`,wh=`block text-[11px] font-medium text-foreground mb-1`;function Th({target:t,kind:r,open:a,onClose:s}){let{t:c}=Y(),l=j(),u=n(()=>oh(r.caps),[r.caps]),d=n(()=>vh(r.caps),[r.caps]),[p,m]=o(()=>hh(r.caps)),[_,v]=o(null),y=n(()=>uh(r.caps,p),[r.caps,p]),b=u.showBody?p.body.length:0,x=b>u.bodyMaxLen,S=e=>m(t=>({...t,...e})),C=f({mutationFn:()=>l.trpcClient.notificationOutput.testTarget.mutate({addonId:t.addonId,targetId:t.id,sample:uh(r.caps,p)}),onMutate:()=>v(null),onSuccess:e=>v(e),onError:e=>v({success:!1,error:e instanceof Error?e.message:J.t(`system.notificationTestPanel.testFailed`)})}),w=e=>{m(bh(r.caps,e)),v(null)},T=(e,t,n)=>{let r=p.actions.length>0?[...p.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},S({actions:r})};return i(xt,{open:a,onOpenChange:e=>!e&&s(),children:e(Xt,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[i(It,{children:i(Rt,{children:c(`system.notificationTestPanel.testTitle`,{name:t.name,kind:r.label})})}),e(wt,{className:`space-y-4 pr-1`,children:[i(`div`,{className:`flex flex-wrap gap-1.5`,children:d.map(e=>i(q,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>w(e),children:Sh[e]},e))}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[u.levels.length>0&&e(`div`,{children:[i(`label`,{className:wh,children:c(`system.notificationTestPanel.level`,`Level`)}),e(I,{wrapperClassName:`inline-block w-auto`,className:Ch,value:p.level,onChange:e=>S({level:e.target.value}),children:[i(`option`,{value:``,children:c(`system.notificationTestPanel.deriveFromPriority`,`— derive from priority —`)}),u.levels.map(t=>e(`option`,{value:t.id,children:[t.label,t.ordinal===null?` (${c(`system.notificationTestPanel.qualitative`)})`:` (p${t.ordinal})`]},t.id))]}),(()=>{let t=u.levels.find(e=>e.id===p.level);return t?e(`div`,{className:`mt-1 space-y-1`,children:[t.description&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:t.description}),e(`div`,{className:`flex flex-wrap gap-1`,children:[t.flags?.critical&&i(U,{variant:`danger`,"data-testid":`flag-critical`,children:c(`system.notificationTestPanel.critical`)}),t.flags?.silent&&i(U,{variant:`info`,children:c(`system.notificationTestPanel.silent`)}),t.flags?.noPush&&i(U,{variant:`warning`,children:`no-push`})]}),t.requires&&t.requires.length>0&&e(`p`,{className:`text-[10px] text-warning`,children:[c(`system.notificationTestPanel.requiresTargetConfig`,`Requires target config:`),` `,t.requires.join(`, `)]})]}):null})()]}),e(`div`,{children:[e(`label`,{className:wh,children:[c(`system.notificationTestPanel.priorityOrdinal`,`Priority (ordinal):`),` `,p.priority]}),i(z,{min:1,max:5,step:1,value:p.priority,onChange:e=>S({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":c(`system.notificationTestPanel.priority`)})]})]}),u.formats.length>0&&e(`div`,{children:[i(`label`,{className:wh,children:c(`system.notificationTestPanel.format`,`Format`)}),i(`div`,{className:`flex flex-wrap gap-2`,children:u.formats.map(t=>e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[i(Gt,{name:`format`,className:`accent-primary`,checked:p.format===t,onChange:()=>S({format:t})}),t]},t))})]}),u.showTitle&&e(`div`,{children:[i(`label`,{className:wh,children:c(`system.notificationTestPanel.testTitle`,`Title`)}),i(K,{className:Ch,value:p.title,onChange:e=>S({title:e.target.value})})]}),u.showBody&&e(`div`,{children:[e(`label`,{className:wh,children:[c(`system.notificationTestPanel.body`),` `,e(`span`,{className:x?`text-danger`:`text-foreground-subtle`,children:[`(`,b,`/`,u.bodyMaxLen,x?` — ${c(`system.notificationTestPanel.overflow`)}`:``,`)`]})]}),i(zt,{className:`${Ch} min-h-[80px] resize-y`,value:p.body,onChange:e=>S({body:e.target.value})})]}),u.attachmentSlots.length>0&&e(`div`,{children:[e(`label`,{className:wh,children:[c(`system.notificationTestPanel.attachments`),` `,i(`span`,{className:`text-foreground-subtle`,children:u.attachmentMaxBytes?c(`system.notificationTestPanel.attachmentsMetaMb`,{mode:u.attachmentMode,max:u.attachmentMax,mb:Math.round(u.attachmentMaxBytes/1024/1024)}):c(`system.notificationTestPanel.attachmentsMeta`,{mode:u.attachmentMode,max:u.attachmentMax})})]}),i(`div`,{className:`space-y-1.5`,children:u.attachmentSlots.map(t=>e(`div`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:t}),i(K,{className:Ch,placeholder:c(`system.notificationTestPanel.url`,`{{mt}} URL`,{mt:t}),value:p.attachmentUrls[t]??``,onChange:e=>S({attachmentUrls:{...p.attachmentUrls,[t]:e.target.value}})})]},t))})]}),u.showActions&&e(`div`,{children:[i(`label`,{className:wh,children:c(`system.notificationTestPanel.actionsUpTo`,{max:u.maxActions})}),i(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(u.maxActions,3)},(t,n)=>e(`div`,{className:`flex items-center gap-2`,children:[i(K,{className:Ch,placeholder:c(`system.notificationTestPanel.actionLabelPlaceholder`),value:p.actions[n]?.label??``,onChange:e=>T(n,`label`,e.target.value)}),i(K,{className:Ch,placeholder:c(`system.notificationTestPanel.actionUrlPlaceholder`),value:p.actions[n]?.url??``,onChange:e=>T(n,`url`,e.target.value)})]},n))})]}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[u.showClickUrl&&e(`div`,{children:[i(`label`,{className:wh,children:c(`system.notificationTestPanel.clickUrl`,`Click URL`)}),i(K,{className:Ch,value:p.clickUrl,onChange:e=>S({clickUrl:e.target.value})})]}),u.showSound&&e(`div`,{children:[i(`label`,{className:wh,children:c(`system.notificationTestPanel.sound`,`Sound`)}),i(K,{className:Ch,value:p.sound,onChange:e=>S({sound:e.target.value})})]}),u.showTtl&&e(`div`,{children:[i(`label`,{className:wh,children:c(`system.notificationTestPanel.ttlSeconds`,`TTL (seconds)`)}),i(K,{className:Ch,type:`number`,value:p.ttl,onChange:e=>S({ttl:e.target.value})})]}),u.showTag&&e(`div`,{children:[i(`label`,{className:wh,children:c(`system.notificationTestPanel.tag`,`Tag`)}),i(K,{className:Ch,value:p.tag,onChange:e=>S({tag:e.target.value})})]})]}),_&&i(Eh,{result:_}),e(`details`,{className:`text-[10px]`,children:[i(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:c(`system.notificationTestPanel.payloadPreview`,`Payload preview`)}),i(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(y,null,2)})]})]}),e(Lt,{children:[i(q,{variant:`secondary`,size:`sm`,type:`button`,onClick:s,children:c(`common.close`,`Close`)}),e(q,{size:`sm`,type:`button`,disabled:C.isPending||!dh(r.caps,p),onClick:()=>C.mutate(),children:[C.isPending?i(g,{className:`h-3.5 w-3.5 animate-spin`}):i(h,{className:`h-3.5 w-3.5`}),c(`system.notificationTestPanel.sendTest`,`Send test`)]})]})]})})}function Eh({result:t}){let{t:n}=Y(),r=t.renderedAs;return e(`div`,{className:`rounded-md border px-3 py-2 text-xs ${t.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[e(`div`,{className:`flex items-center gap-2 font-medium`,children:[t.success?i(C,{className:`h-3.5 w-3.5 text-success`}):i(P,{className:`h-3.5 w-3.5 text-danger`}),i(`span`,{children:t.success?n(`system.notificationTestPanel.delivered`,`Delivered`):n(`system.notificationTestPanel.failed`,`Failed`)})]}),t.error&&i(`p`,{className:`mt-1 text-danger`,children:t.error}),r&&e(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[i(`dt`,{children:n(`system.notificationTestPanel.resolvedLevel`,`Resolved level`)}),i(`dd`,{className:`text-foreground`,children:r.level}),i(`dt`,{children:n(`system.notificationTestPanel.formatSent`,`Format sent`)}),i(`dd`,{className:`text-foreground`,children:r.format}),i(`dt`,{children:n(`system.notificationTestPanel.attachmentsSent`,`Attachments sent`)}),i(`dd`,{className:`text-foreground`,children:r.attachmentsSent}),i(`dt`,{children:n(`system.notificationTestPanel.actionsSent`,`Actions sent`)}),i(`dd`,{className:`text-foreground`,children:r.actionsSent}),i(`dt`,{children:n(`system.notificationTestPanel.truncated`,`Truncated`)}),i(`dd`,{className:`text-foreground`,children:r.truncated?n(`common.yes`):n(`common.no`)}),i(`dt`,{children:n(`system.notificationTestPanel.dropped`,`Dropped`)}),i(`dd`,{className:`text-foreground`,children:r.dropped.length>0?r.dropped.join(`, `):`—`})]})]})}c();var Dh=`ownerUserId`,Oh=`notification-output`;function kh(e){let t=e.formValues[Dh];return typeof t==`string`&&t.length>0?t:null}function Ah({row:e}){let{t}=Y(),n=j(),r=gt({functionCap:Oh}),a=s({queryKey:[`userManagement`,`listUsers`],queryFn:()=>n.trpcClient.userManagement.listUsers.query()});if(e.kind!==`instance`)return null;let o=(r.data??[]).find(t=>t.id===e.id),c=o===void 0?null:kh(o);if(c===null)return i(U,{variant:`default`,children:t(`common.systemWord`,`system`)});if(a.data===void 0&&!a.isError)return i(Ot,{className:`h-3 w-16`});let l=(a.data??[]).find(e=>e.id===c)?.username;return i(`span`,{className:`text-xs text-foreground`,children:l??t(`system.notificationTargets.unknownUser`,`unknown user`)})}function jh(e){return{key:`owner`,header:e,nowrap:!0,notSortableReason:e,render:e=>i(Ah,{row:e})}}function Mh(){let{t}=Y(),n=j(),a=s({queryKey:[`notificationOutput`,`listTargetKinds`],queryFn:()=>n.trpcClient.notificationOutput.listTargetKinds.query({})}),[c,l]=o(null),u=c===null||c.kindId===void 0?void 0:(a.data??[]).find(e=>e.kind===Pe(c.kindId??``)&&e.addonId===c.addonId),d=r(e=>i(ft,{icon:h,variant:`ghost`,size:`sm`,"aria-label":t(`system.notificationTargets.testTarget`,`Send a test to {{name}}`,{name:e.name}),onClick:()=>l(e)}),[t]),f=c===null||u===void 0?null:{id:c.id,name:c.name,kind:u.kind,addonId:c.addonId,enabled:c.enabled,config:{}};return e(p,{children:[i(zi,{functionCap:Oh,icon:_,title:t(`system.notificationTargets.notificationTargets`,`Notification Targets`),subtitle:t(`system.notificationTargets.deliverNotificationsToNtfyPushover`,`Deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more. Each target's kind declares its capabilities; the test panel shows exactly what a message degrades to.`),emptyTitle:t(`system.notificationTargets.emptyTitle`,`No notification targets yet`),emptyDescription:t(`system.notificationTargets.emptyDescription`,`Add a target to deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more.`),addLabel:t(`system.notificationTargets.addTarget`,`Add target`),testLabel:t(`system.notificationTargets.sendTest`,`Send test message`),testHint:t(`system.notificationTargets.sendTestHint`,`Send test message delivers a real notification to the destination typed above, before you save.`),extraColumns:[jh(t(`system.notificationTargets.owner`,`Owner`))],rowActions:d}),f!==null&&u!==void 0&&i(Th,{target:f,kind:u,open:!0,onClose:()=>l(null)})]})}c();var Nh=`notificationTexts`,Ph=`Every sentence the Notification Center can print — and your wording for it.`;function Fh({entry:t,value:n,busy:r,onChange:a,onReset:o}){let{t:s}=Y(),c=Ou(t),l=t.override!==null;return e(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${t.key}`,"data-source":t.source,children:[e(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[i(`code`,{className:`text-xs font-medium`,children:t.key}),l?i(U,{variant:`info`,children:s(`common.customised`)}):null,t.source===`fallback`?i(U,{variant:`warning`,children:s(`system.notificationTexts.englishFallback`,`English fallback`)}):null]}),e(`div`,{className:`flex items-start gap-2`,children:[i(`div`,{className:`flex-1`,children:i(vs,{label:``,value:n,onChange:a,vars:Du(t),deviceValues:!1,disabled:r,testId:`text-input-${t.key}`})}),i(q,{variant:`ghost`,size:`sm`,disabled:r||!l&&n===t.shipped,onClick:o,title:s(`system.notificationTexts.resetToTheShippedWording`,`Reset to the shipped wording`),"data-testid":`text-reset-${t.key}`,children:i(D,{className:`h-3.5 w-3.5`})})]}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[i(`span`,{className:`font-medium`,children:s(`system.notificationTexts.shipped`,`Shipped:`)}),` `,i(`span`,{className:`font-mono`,children:t.shipped})]}),c===null?null:i(`p`,{className:`text-xs text-warning`,children:c})]})}function Ih(){let{t}=Y(),r=j(),a=u(),[c,l]=o(null),[d,p]=o(``),[m,h]=o(new Map),[_,v]=o(!1),y=s({queryKey:[Nh,c??`hub`],queryFn:async()=>{let e=Su(await r.trpcClient.addons.custom.mutate({addonId:$,action:pu,input:c===null?{}:{language:c}}));return v(e===null),e}}),b=()=>{h(new Map),a.invalidateQueries({queryKey:[Nh]})},x=f({mutationFn:e=>r.trpcClient.addons.custom.mutate({addonId:$,action:mu,input:{language:e}}),onSuccess:b}),S=f({mutationFn:e=>r.trpcClient.addons.custom.mutate({addonId:$,action:hu,input:e}),onSuccess:b}),C=y.data??null,w=n(()=>C===null?[]:Eu(C.entries,d),[C,d]);if(y.isLoading)return i(Ui,{embedded:!0,icon:ut,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:Ph,children:i(g,{className:`h-5 w-5 animate-spin`})});if(y.isError||C===null)return i(Ui,{embedded:!0,icon:ut,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:Ph,children:i(dt,{title:t(`system.notificationTexts.theNotificationTextCatalogIs`,`The notification text catalog is not available on this hub`),message:_?t(`system.notificationTexts.theHubAnsweredSomethingThis`,`The hub answered something this admin build does not understand. Update both and reload.`):t(`system.notificationTexts.thisHubHasNotBeen`,`This hub has not been updated to serve the notification text catalog yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime: notifications keep using the shipped wording.`)})});let E=C.language,D=x.isPending||S.isPending,O=wu(C.entries,m),k=Tu(C.entries,m),A=C.entries.filter(e=>e.override!==null).length,ee=C.languages.map(e=>({value:e,label:gu[e]})),M=(e,t)=>h(n=>new Map(n).set(e,t)),N=e=>M(e.key,e.shipped);return i(Ui,{embedded:!0,icon:ut,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:Ph,children:e(`div`,{className:`flex flex-col gap-4`,children:[x.isError?i(dt,{title:t(`system.notificationTexts.couldNotChangeTheLanguage`,`Could not change the language`),message:String(x.error)}):null,S.isError?i(dt,{title:t(`system.notificationTexts.couldNotSave`,`Could not save`),message:String(S.error)}):null,e(Yt,{className:`p-4`,children:[e(`div`,{className:`flex flex-wrap items-end gap-6`,children:[e(`div`,{className:`flex flex-col gap-1`,children:[i(`label`,{className:`text-sm font-medium`,children:t(`system.notificationTexts.hubLanguage`,`Hub language`)}),i(`div`,{className:`w-44`,children:i(I,{value:C.activeLanguage,disabled:D,options:ee,onChange:e=>{let t=e.target.value;_u(t)&&x.mutate(t)},"data-testid":`texts-hub-language`})}),i(`p`,{className:`text-xs text-foreground-subtle`,children:t(`system.notificationTexts.everyNotificationIsWrittenIn`,`Every notification is written in this language.`)})]}),e(`div`,{className:`flex flex-col gap-1`,children:[i(`label`,{className:`text-sm font-medium`,children:t(`system.notificationTexts.editing`,`Editing`)}),i(`div`,{className:`w-44`,children:i(I,{value:E,disabled:D,options:ee,onChange:e=>{let t=e.target.value;_u(t)&&(h(new Map),l(t))},"data-testid":`texts-editing-language`})}),i(`p`,{className:`text-xs text-foreground-subtle`,children:E===C.activeLanguage?t(`system.notificationTexts.ofTextsCustomised`,`{{overriddenCount}} of {{length}} texts customised.`,{overriddenCount:A,length:C.entries.length}):t(`system.notificationTexts.thisHubDoesNotSpeak`,`This hub does not speak this language — these words are not in use yet.`)})]})]}),i(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:t(`system.notificationTexts.aRuleThatWritesIts`,`A rule that writes its own title or body still overrides everything here — this page is the wording used when a rule does not.`)})]}),e(`div`,{className:`flex flex-wrap items-center gap-3`,children:[e(`div`,{className:`relative min-w-[12rem] flex-1`,children:[i(T,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),i(K,{searchHotkey:!0,value:d,placeholder:t(`system.notificationTexts.searchAKeyOrA`,`Search a key or a sentence…`),onChange:e=>p(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),e(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[w.length,` of `,C.entries.length]}),e(q,{className:`ml-auto`,disabled:D||k===0,onClick:()=>S.mutate({language:E,overrides:O}),"data-testid":`texts-save`,children:[D?i(g,{className:`h-3.5 w-3.5 animate-spin`}):null,k===0?t(`common.save`,`Save`):t(`system.notificationTexts.save`,`Save {{pending}}`,{pending:k})]})]}),i(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?i(`p`,{className:`text-sm text-foreground-subtle`,children:t(`system.notificationTexts.noTextMatchesThatSearch`,`No text matches that search.`)}):w.map(e=>i(Fh,{entry:e,value:Cu(e,m),busy:D,onChange:t=>M(e.key,t),onReset:()=>N(e)},e.key))})]})})}c();var Lh=`simulate`,Rh=`rules`,zh=[`instance`,`instance-new`],Bh=new Set([Rh]);function Vh(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function Hh(t,n,r){if(t===`mixed`)return;if(t===`all`)return e(q,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:n,children:[i(k,{className:`h-3.5 w-3.5`}),J.t(`systemPage.notifications.newRule`,`New rule`)]});if(up(t)){let n=fp(t),a=Vh(t);return a===null?void 0:e(q,{size:`sm`,type:`button`,onClick:()=>r(a),"data-testid":t===`summaries`?`summary-new`:t===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[i(k,{className:`h-3.5 w-3.5`}),n.newLabel]})}let a=Wn.find(e=>e.key===t);if(!(a===void 0||!a.creatable))return e(q,{size:`sm`,type:`button`,onClick:()=>r(t),"data-testid":`rules-new-${t}`,children:[i(k,{className:`h-3.5 w-3.5`}),a.newRuleLabel]})}function Uh(){let{t:e}=Y(),[t,n]=pn(),[r,s]=o(!1),[c,l]=o(null);a(()=>{let e=t.get(`tab`);if(e===null||!up(e))return;let r=new URLSearchParams(t);r.set(`tab`,Rh),r.set(`section`,e),n(r,{replace:!0})},[t,n]);let u=t.get(`tab`)??`targets`,[d]=At(`section`),f=dp(d)??`all`,p=e=>{Pm(Mm(e));let r=new URLSearchParams(t);r.set(`tab`,Lh),n(r,{replace:!0})},m=e=>{n(Ho(t,e.id),{replace:!0})},h=Er(`/system/notifications`,{t:e,isAdmin:!0})??{icon:_,title:e(`system.notifications`,`Notifications`)},g=()=>s(!1),v=(()=>{if(u===Rh)return Hh(f,()=>s(!0),e=>l(e))})();return a(()=>{Bh.has(u)||(s(!1),l(null))},[u]),i(Ri,{icon:h.icon,title:h.title,defaultSection:`targets`,sectionsLabel:`${h.title} sections`,actions:v,sections:[{id:`targets`,label:e(`systemPage.notifications.targets`,`Targets`),content:i(Mh,{}),ownedParams:zh},{id:Rh,label:e(`systemPage.notifications.rules`,`Rules`),content:i(am,{onSimulateRule:p,onOpenHistory:m,headerOwnsCreate:!0,createRequested:u===Rh&&r,onCreateConsumed:g,createTypeRequested:u===Rh?c:null,onCreateTypeConsumed:()=>l(null)}),ownedParams:[`section`,`rule`,`editTab`]},{id:Lh,label:e(`systemPage.notifications.simulate`,`Simulate`),content:i(ih,{})},{id:Io,label:e(`systemPage.notifications.history`,`History`),content:i($o,{}),ownedParams:Ro},{id:`alarm`,label:e(`systemPage.notifications.alarm`,`Alarm`),content:i(Fo,{})},{id:`texts`,label:e(`systemPage.notifications.texts`,`Texts`),content:i(Ih,{})},{id:`settings`,label:e(`systemPage.notifications.settings`,`Settings`),content:i(pm,{})}]})}export{Uh as NotificationsPage,Uh as default};