@camstack/addon-admin-ui 1.2.370 → 1.2.372

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 (70) hide show
  1. package/dist/assets/{AddonAssetIcon-rNUHK9wc.js → AddonAssetIcon-Bvlbs-we.js} +1 -1
  2. package/dist/assets/{AddonIntegrationBody-C5wKwiTM.js → AddonIntegrationBody-CLBlTXCr.js} +1 -1
  3. package/dist/assets/{Addons-MDKsHDDm.js → Addons-BHYRFNw1.js} +1 -1
  4. package/dist/assets/{AdminTabs-B7mqaGod.js → AdminTabs-2smlNAE_.js} +1 -1
  5. package/dist/assets/{AiProfiles-DaN2f1Go.js → AiProfiles-BwlI-5bY.js} +1 -1
  6. package/dist/assets/{BrokerForm-DjytVdo-.js → BrokerForm-B0-lyNPR.js} +1 -1
  7. package/dist/assets/{Build-CHz1FqbZ.js → Build-MbSINb6K.js} +1 -1
  8. package/dist/assets/{Calendars-B9H9vgS2.js → Calendars-C379ZdmG.js} +1 -1
  9. package/dist/assets/Cluster-CIwtiuWP.js +1 -0
  10. package/dist/assets/{ClusterStepModel-Bg7jOAJE.js → ClusterStepModel-C7lERZS9.js} +1 -1
  11. package/dist/assets/{CompositionEditor-QsBcjtRo.js → CompositionEditor-B8IeJs7c.js} +1 -1
  12. package/dist/assets/{CompositionEditorPage-CZRgABku.js → CompositionEditorPage-BTw1h9ZH.js} +1 -1
  13. package/dist/assets/{Data-CCQ5NT9z.js → Data-BbVK94E9.js} +1 -1
  14. package/dist/assets/DetectionIntelligence-hzaazWUY.js +1 -0
  15. package/dist/assets/{DeviceDetail-4Wa8zL39.js → DeviceDetail-BejYs7N7.js} +1 -1
  16. package/dist/assets/{DeviceDoActionFields-DgRa8wUB.js → DeviceDoActionFields-Do6M2l_j.js} +1 -1
  17. package/dist/assets/{Devices-BiwjNBIq.js → Devices-D9Pc88Qo.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-Cg8N_mi7.js → EmbedPlayerPage-Cq-C31nE.js} +1 -1
  19. package/dist/assets/Events-Ct5izUvZ.js +1 -0
  20. package/dist/assets/{Identity-tue9lGgH.js → Identity-FGkTFfhf.js} +1 -1
  21. package/dist/assets/IntegrationDetail-BpA3QO-E.js +1 -0
  22. package/dist/assets/{Integrations-14od7JhH.js → Integrations-BRiFwXi8.js} +1 -1
  23. package/dist/assets/{Integrations-BfRNaP7l.js → Integrations-DhrSWf1p.js} +1 -1
  24. package/dist/assets/{Locations-DS0EKKOB.js → Locations-D0REDYo5.js} +1 -1
  25. package/dist/assets/{Logs-C_MmssVj.js → Logs-B46x0jJR.js} +1 -1
  26. package/dist/assets/{MyAccess-wao27sRf.js → MyAccess-CghKYIxJ.js} +1 -1
  27. package/dist/assets/{Network-oQcNkgTu.js → Network-q_b0sLVC.js} +1 -1
  28. package/dist/assets/{NodeAddonsSettingsPanel-BMxvR3AQ.js → NodeAddonsSettingsPanel-Ci0PhhCq.js} +1 -1
  29. package/dist/assets/{Notifications-BB99xksI.js → Notifications-BriWzxUb.js} +1 -1
  30. package/dist/assets/Plates-CZ3RQk3R.js +1 -0
  31. package/dist/assets/{Recordings-B1ihCXnh.js → Recordings-AQiIOomS.js} +1 -1
  32. package/dist/assets/{ScanNetworkModal-BtSkDnst.js → ScanNetworkModal-DXODoRu9.js} +1 -1
  33. package/dist/assets/{Scenes-Cxsst6jH.js → Scenes-xNrpPskA.js} +1 -1
  34. package/dist/assets/{SessionsList-K0gNSKrq.js → SessionsList-CFIFn9Bc.js} +1 -1
  35. package/dist/assets/{Showroom-CTGDj91m.js → Showroom-UJJ5VRWX.js} +1 -1
  36. package/dist/assets/{System-CMAwUkxP.js → System-DQS8iVd0.js} +1 -1
  37. package/dist/assets/{Terminal-PyG5NErD.js → Terminal-BzbZmqDx.js} +1 -1
  38. package/dist/assets/{Viewer-Dt2_oVeL.js → Viewer-DDEk3JEc.js} +1 -1
  39. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DX05vs51.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C8DdBVOU.js} +1 -1
  40. package/dist/assets/{authed-media-DmDTbsLa.js → authed-media-Br9lZGdM.js} +1 -1
  41. package/dist/assets/{debounced-invalidate-CC0VQLjV.js → debounced-invalidate-aLTpVZnL.js} +1 -1
  42. package/dist/assets/{device-integration-icon-DbGFErfk.js → device-integration-icon-ByZPIc_Q.js} +1 -1
  43. package/dist/assets/device-picker-model-BZYpYRsM.js +1 -0
  44. package/dist/assets/{face-bbox-B9dID2jY.js → face-bbox-x3rH65-o.js} +1 -1
  45. package/dist/assets/{hostInit-Cf3_Ewlc.js → hostInit-BUJ0U0UP.js} +1 -1
  46. package/dist/assets/{index-BsZjL5HO.js → index-BlaisiEj.js} +3 -3
  47. package/dist/assets/{index-BKZRl3KT.css → index-MfQ6ok9_.css} +1 -1
  48. package/dist/assets/{location-owned-usage-CtdITciE.js → location-owned-usage-QVsNqX7g.js} +1 -1
  49. package/dist/assets/{mf-entry-bootstrap-0-625c8410.js → mf-entry-bootstrap-0-8330eb86.js} +2 -2
  50. package/dist/assets/mount-BZYpYRsM.js +1 -0
  51. package/dist/assets/{notification-schedule-field-DUWbH7XG.js → notification-schedule-field-CNwv7_6o.js} +1 -1
  52. package/dist/assets/remoteEntry-CEno4jo3.js +1 -0
  53. package/dist/assets/{src-B06iwqFQ.js → src-BTQcUQJz.js} +16 -16
  54. package/dist/assets/{use-scenes-feed-BN5zl7un.js → use-scenes-feed-DcNDaTD0.js} +1 -1
  55. package/dist/assets/{use-stationary-objects-CICValw3.js → use-stationary-objects-C6uSntPO.js} +1 -1
  56. package/dist/assets/useEventInvalidation-BZYpYRsM.js +1 -0
  57. package/dist/assets/{useNodeUrlSelection-Dcp64NLR.js → useNodeUrlSelection-DwKt8fEX.js} +1 -1
  58. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CDvKve-V.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-C0f8TSRz.js} +2 -2
  59. package/dist/index.html +6 -6
  60. package/dist/server/addon.js +1 -1
  61. package/package.json +1 -1
  62. package/dist/assets/Cluster-Dn986Tn1.js +0 -1
  63. package/dist/assets/DetectionIntelligence-C6APwggP.js +0 -1
  64. package/dist/assets/Events-C8u59wdS.js +0 -1
  65. package/dist/assets/IntegrationDetail-DItHIF-n.js +0 -1
  66. package/dist/assets/Plates-YkdrGkW8.js +0 -1
  67. package/dist/assets/device-picker-model-C9R5gyah.js +0 -1
  68. package/dist/assets/mount-C9R5gyah.js +0 -1
  69. package/dist/assets/remoteEntry-BkONRtCr.js +0 -1
  70. package/dist/assets/useEventInvalidation-C9R5gyah.js +0 -1
@@ -1 +1 @@
1
- import{K as e,Q as t,S as n,W as r,a as i,b as a,o,p as s,q as c,t as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{Z as f,at as p,gt as m,lt as h,st as g,vt as _}from"./player-overlays-B7T46vDu.js";import{$d as v,$o as y,Ad as b,An as x,Cn as S,Dn as C,En as w,Fn as T,Ft as E,Gt as D,Hl as O,Hu as k,In as A,It as j,Jt as ee,Kt as M,Lu as N,Md as P,Nn as F,Qd as I,R as L,Sd as R,Sn as z,Tn as te,Ud as B,Xn as ne,Xo as re,Xu as V,Yu as H,Zn as ie,Zo as U,_ as ae,_i as oe,ar as se,d as W,df as ce,en as G,f as le,ff as ue,g as de,gd as K,gn as fe,h as pe,if as me,ir as he,la as ge,m as _e,or as ve,ot as ye,p as be,q as xe,qn as Se,qt as Ce,sr as we,td as Te,tr as q,ts as Ee,u as De,uf as Oe,v as ke,xn as Ae,yu as je}from"./src-B06iwqFQ.js";import{t as Me}from"./history-Dcle7WpC.js";import{t as Ne}from"./send-Cx-d7NnY.js";import{$ as Pe,A as Fe,B as Ie,Bn as Le,D as Re,E as ze,Er as Be,F as Ve,H as He,In as Ue,J as We,L as Ge,N as Ke,T as qe,U as Je,V as Ye,W as Xe,X as Ze,Y as Qe,Z as $e,_t as et,at as tt,bt as nt,ct as rt,dt as it,ft as at,j as ot,k as st,lt as ct,mt as lt,nn as ut,ot as dt,q as ft,qt as pt,rt as mt,tt as ht,ut as gt,xt as _t,z as vt,zn as yt}from"./client-BBcQuaON.js";import{D as bt,F as xt,M as St,O as Ct,j as wt,v as Tt,y as Et}from"./__vite-browser-external-DF8Eb0aa.js";import{t as Dt}from"./useTranslation-Bc5yH9V9.js";import"./mount-C9R5gyah.js";import{$ as Ot,$t as kt,A as At,At as jt,B as Mt,Bt as Nt,C as Pt,Ct as Ft,D as It,Dt as Lt,E as Rt,Et as zt,F as Bt,Ft as Vt,G as Ht,Gt as Ut,H as Wt,Ht as Gt,I as Kt,It as qt,J as Jt,Jt as Yt,K as Xt,Kt as Zt,L as Qt,Lt as $t,M as en,Mt as tn,N as nn,Nt as rn,O as an,Ot as on,P as sn,Pt as cn,Q as ln,Qt as un,R as dn,Rt as fn,S as pn,St as mn,T as hn,Tt as gn,U as _n,Ut as vn,V as yn,Vt as bn,W as xn,Wt as Sn,X as Cn,Xt as wn,Y as Tn,Yt as En,Z as Dn,Zt as On,_ as kn,_n as An,_t as jn,a as Mn,an as Nn,at as Pn,b as Fn,bt as In,c as Ln,cn as Rn,ct as zn,d as Bn,dn as Vn,dt as Hn,en as Un,et as Wn,f as J,fn as Gn,ft as Kn,g as qn,gn as Jn,gt as Yn,h as Xn,hn as Zn,ht as Qn,i as $n,in as er,it as tr,j as nr,jt as rr,k as ir,kt as ar,l as or,ln as sr,lt as cr,m as lr,mn as ur,mt as dr,n as fr,nn as pr,nt as mr,o as hr,on as gr,ot as _r,p as vr,pn as yr,pt as br,q as xr,qt as Sr,r as Cr,rn as wr,rt as Tr,s as Er,sn as Dr,st as Or,t as kr,tn as Ar,tt as jr,u as Mr,un as Nr,ut as Pr,v as Fr,vt as Ir,w as Lr,wt as Rr,x as zr,xt as Br,y as Vr,yt as Hr,z as Ur,zt as Wr}from"./notification-schedule-field-DUWbH7XG.js";import{$ as Gr,Y as Kr,w as qr}from"./index-BsZjL5HO.js";import{t as Jr}from"./AdminPage-BSFohA3i.js";import{t as Yr}from"./DeviceDoActionFields-DgRa8wUB.js";import"./device-picker-model-C9R5gyah.js";import{t as Xr}from"./AdminTabs-B7mqaGod.js";import{t as Zr}from"./use-scenes-feed-BN5zl7un.js";var Qr=_(`images`,[[`path`,{d:`m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16`,key:`9kzy35`}],[`path`,{d:`M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2`,key:`1t0f0t`}],[`circle`,{cx:`13`,cy:`7`,r:`1`,fill:`currentColor`,key:`1obus6`}],[`rect`,{x:`8`,y:`2`,width:`14`,height:`14`,rx:`2`,key:`1gvhby`}]]),$r=_(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),ei=_(`list-ordered`,[[`path`,{d:`M11 5h10`,key:`1cz7ny`}],[`path`,{d:`M11 12h10`,key:`1438ji`}],[`path`,{d:`M11 19h10`,key:`11t30w`}],[`path`,{d:`M4 4h1v5`,key:`10yrso`}],[`path`,{d:`M4 9h2`,key:`r1h2o0`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`,key:`xtkcd5`}]]);t();var ti=[`contact`,`cover`,`lock-control`,`switch`];function ni(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 ri(e){let t=new Set(ni(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 ii(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function ai(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=>pe([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?`Device #${String(e)}`:be(t))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function oi(e){let t=e.name.trim();return t===``?`Device #${String(e.deviceId)}`:t}function si(e){return e===0?`Not armed — the hub refused without naming an open device.`:`Not armed — these are open:`}var ci={home:`Home`,away:`Away`,night:`Night`};function li(e){return ci[e]??e}function ui(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?`${n} min`:`${n} min ${r} s`}function di(e,t){if(e.ruleCount===0)return`Arms nothing — no enabled rule is gated on this mode.`;if(e.allDevices&&e.allDevicesExcept.length>0){let n=e.allDevicesExcept.map(t);return`All devices except ${n.length}: ${n.join(`, `)}`}return e.allDevices?`Every device — ${hi(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${hi(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(t).join(`, `)}function fi(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${pi[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var pi={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function mi(e){return e.ruleCount===0}function hi(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function gi(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 _i=2e3,vi=15e3,yi=new Set([`arming`,`pending`,`triggered`]);function bi(e){return e!==void 0&&yi.has(e)?_i:vi}var xi={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 Si(e){let t=xi[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${li(e.targetMode)}`}function Ci(e){return e!==`disarmed`}function wi(e){return e===`open`?`ignored until it closes`:`closed — monitored at next open`}function Ti(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Ei(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Di(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function Oi(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 ki(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 Ai(e,t,n,r){let i=Oi(e,t,n);return r==="default"?i===void 0?null:ki(t,n,null):i===r?null:ki(t,n,r)}function ji(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=We(e,t),a=r!==n,o=n!==`doNothing`&&i.triggeredDurationSec===0;return!a&&!o?null:{mode:t,...a?{postTriggeredAction:n}:{},...o?{triggeredDurationSec:30}:{}}}function Mi(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 Ni=[`unknown-refusal`,`stale`,`expired`,`used`];function Pi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fi(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Pi(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 Ii(e){if(!Pi(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Fi(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Fi(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Ni.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var Li={"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 Ri(e){return Li[e]}function zi(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 Bi=`pipeline-analytics`,Vi=`The hub answered something this build cannot read — refresh after updating.`;function Hi(e){return e instanceof Error?e.message:String(e)}function Ui(e){return e.map(e=>`${oi(e)} (${e.state})`).join(`, `)}function Wi({live:e,onChanged:t}){let r=p(),[i,a]=c(null),[o,s]=c(null),[d,f]=c(null),m=(e,t)=>r.trpcClient.addons.custom.mutate({addonId:Bi,action:e,input:t}),h=e=>{if(e===null){s(Vi);return}if(e.outcome===`refused`){a({refusalId:e.refusalId,blocking:e.blocking});return}if(a(null),e.outcome===`rejected`){s(`Arm anyway was not accepted: ${Ri(e.reason)}.`);return}if(e.outcome===`outside-schedule`){s(`Outside this mode's activation schedule — arm during an allowed window.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;f(e.excluded.length===0?`${t}.`:`${t} — excluded: ${Ui(e.excluded)}.`)},g=()=>{s(null),f(null)},_=l({mutationFn:async e=>Ii(await m(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>s(Hi(e)),onSettled:t}),v=l({mutationFn:async e=>Ii(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>s(Hi(e)),onSettled:t}),y=l({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{g(),a(null)},onSuccess:()=>f(`Disarmed.`),onError:e=>s(Hi(e)),onSettled:t});if(e===void 0)return n(x,{className:`p-4`,children:[u(`h3`,{className:`text-sm font-semibold mb-1`,children:`Panel`}),u(`p`,{className:`text-sm text-foreground-subtle`,children:`This hub does not report the panel's live state yet — update it to arm from here.`})]});let b=_.isPending||v.isPending||y.isPending;return n(x,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[n(`div`,{children:[u(`h3`,{className:`text-sm font-semibold`,children:`Panel`}),u(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:Si(e)})]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?u(K,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>n(A,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:[`Arm `,li(e)]},e)),u(A,{type:`button`,size:`md`,variant:Ci(e.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:`Disarm`})]})]}),o===null?null:u(`div`,{className:`mt-3`,children:u(F,{title:`The panel did not do that`,message:o})}),d===null?null:u(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:d}),i===null?null:n(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[u(`p`,{className:`text-sm font-medium`,children:si(i.blocking.length)}),i.blocking.length>0?u(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:i.blocking.map(e=>n(`li`,{children:[oi(e),` `,n(`span`,{className:`text-foreground-subtle`,children:[`(`,e.state,`)`]})]},e.deviceId))}):null,n(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[u(A,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(i.refusalId),children:`Arm anyway`}),u(`span`,{className:`text-xs text-foreground-subtle`,children:`Each open device is ignored until it closes, then monitored again.`})]})]}),n(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[u(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:`Excluded sensors`}),e.exclusions.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:`No sensor is excluded.`}):u(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:e.exclusions.map(e=>n(`li`,{children:[oi(e),` —`,` `,u(`span`,{className:`text-foreground-subtle`,children:wi(e.phase)})]},e.deviceId))})]})]})}t();var Gi=[{field:`exitDelaySec`,key:`exit`,label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,max:600,zeroMeans:`arms immediately`},{field:`entryDelaySec`,key:`entry`,label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,max:600,zeroMeans:`fires immediately`},{field:`triggeredDurationSec`,key:`siren`,label:`After (seconds)`,hint:`How long the alarm stays triggered before the after-trigger action runs. Ignored when the action is “do nothing”.`,max:Ue,zeroMeans:`runs the action immediately`}];function Ki(e){return`Enter a whole number of seconds from 0 to ${e}.`}function qi(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${Ki(t)}`}function Ji({label:e,value:t,max:r,zeroMeans:i,disabled:a,testId:o,hint:s,adornment:l,onCommit:d}){let[f,p]=c(null),[m,h]=c(null),g=f??String(t),_=f!==null&&f.trim()!==``&&gi(f,r)===null,v=ui(t,i),y=()=>{let e=f===null?null:gi(f,r);p(null),e===null?f!==null&&h(f):(h(null),d(e))};return n(L,{label:e,...s===void 0?{}:{description:s},..._?{error:Ki(r)}:m===null?{}:{error:qi(m,r)},children:[n(`div`,{className:`flex items-center gap-2`,children:[u(O,{type:`number`,min:0,max:r,value:g,disabled:a,state:_||m!==null?`error`:`default`,"aria-label":e,onChange:e=>{h(null),p(e.target.value)},onBlur:y,className:`w-20`,"data-testid":o}),u(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),l]}),v===`${t} s`?null:u(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function Yi(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=ke(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function Xi(e){switch(e.kind){case`checking`:return{word:`Checking…`,note:null};case`hub-too-old`:return{word:`Unknown`,note:`This hub does not report sensor states — update the hub`};case`read-failed`:return{word:`Unknown`,note:`Could not read: ${e.error}`};case`open`:case`closed`:return{word:e.word,note:e.offline?`Offline — last known`:null};case`unknown`:return{word:`Unknown`,note:e.why===`not-answered`?`Not answered`:e.why===`read-failed`?`Could not read`:`No state reported`};case`not-opening`:return{word:`Not an opening`,note:null};case`removed`:return{word:`Removed`,note:`No longer in the device list`}}}var Zi=`Not checked by this mode — switch on to remove the entry`;function Qi(e){return e.listedUncovered?{word:`No`,note:Zi}:$i(e.coverage)}function $i(e){switch(e.kind){case`arm-checked`:return{word:`Yes`,note:null};case`arm-checked-skipped`:return{word:`Skipped`,note:`Blocks arming; notifications skipped: ${e.reason===`detection-off`?`detection off`:e.reason}`};case`unscoped`:return{word:`All-devices`,note:`Never blocks this mode`};case`not-covered`:return{word:`No`,note:`Never blocks this mode`}}}function ea(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 ta(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 na({name:e,variant:t,words:r}){return n(`span`,{"data-testid":`alarm-cell-${e}`,className:`flex flex-col items-start gap-0.5`,children:[u(q,{variant:t,"data-testid":`alarm-cell-${e}-badge`,children:r.word}),r.note===null?null:u(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${e}-note`,children:r.note})]})}var ra=`hidden sm:table-cell`;function ia(e){let{mode:t,inFlight:r,onSwitch:i,zones:a,disabled:o}=e;return[{key:`name`,header:`Name`,cell:e=>{let t=Yi(e.device.location,a);return n(`span`,{className:`flex min-w-0 flex-col`,"data-testid":`alarm-cell-name`,"data-muted":e.listedUncovered?`true`:void 0,children:[u(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.device.name}),t===``?null:u(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:t})]})}},{key:`type`,header:`Type`,headerClassName:ra,cellClassName:`${ra} text-[11px] text-foreground-subtle`,cell:e=>ae(e.device.type??null)},{key:`state`,header:`State`,cell:e=>u(na,{name:`state`,variant:ea(e.cell),words:Xi(e.cell)})},{key:`coverage`,header:`Checked when arming`,headerClassName:ra,cellClassName:ra,cell:e=>u(na,{name:`coverage`,variant:ta(e),words:Qi(e)})},{key:`blocks`,header:`Blocks arming`,headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{let a=r!==null&&r.mode===t&&r.deviceId===e.device.id&&r.kind===`blocks`,s=r!==null&&!a;return n(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?u(K,{className:`h-3 w-3 animate-spin`}):null,u(G,{checked:e.blocks,onCheckedChange:t=>i(e,`blocks`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-blocks`,"aria-label":`Blocks arming: ${e.device.name}`,"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}},{key:`secure`,header:u(`span`,{title:`Close, lock, or turn off when this mode arms`,children:`Secure on arm`}),headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{if(!e.controllable)return u(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let a=r!==null&&r.mode===t&&r.deviceId===e.device.id&&r.kind===`secureOnArm`,s=r!==null&&!a;return n(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?u(K,{className:`h-3 w-3 animate-spin`}):null,u(G,{checked:e.secureOnArm,onCheckedChange:t=>i(e,`secureOnArm`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-secure`,"aria-label":`Secure on arm (close/lock/off): ${e.device.name}`,title:`Close, lock, or turn off when this mode arms`,"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}}]}function aa(e){let{mode:t,rows:r,sensorsRetry:i,zones:a}=e;return n(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${t}`,children:[i===null?null:n(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[u(`span`,{children:`Could not read the sensor states.`}),u(A,{type:`button`,size:`sm`,variant:`outline`,onClick:i,children:`Retry`})]}),u(xe,{mode:`generic`,items:r,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,Yi(e.device.location,a),ae(e.device.type??null)].join(` `),getFilterType:e=>ae(e.device.type??null),columns:ia(e),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:`Search sensors`,emptyLabel:`No sensor matches.`})]})}var oa=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function sa(e){return oa.some(t=>t.test(e))}function ca(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return sa(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 la(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 ua(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 da(e){return e.kind===`unscoped`||e.kind===`not-covered`}function fa(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=ua(e.coverage,r.id),a=la(e.sensors,r.id,t,r.type),o=Ze({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=$e({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&&da(i)&&(!o||c)&&c;!t&&da(i)&&!c||n.push({device:r,removed:t,cell:ca(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function pa(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function ma(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 ha(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 ga(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 _a(e,t){return ft(ga(e),t)?{kind:`landed`}:{kind:`not-landed`}}var va=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function ya({coverage:e,settings:t,disabled:r,onNotifyEdit:i}){let{t:a}=Dt(),o=Qe(t,e.mode);return n(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${e.mode}`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:a(`notificationRules.alarmNotify.title`)}),va.map(({field:t,key:s})=>n(`div`,{className:`flex items-start justify-between gap-3`,children:[n(`div`,{className:`min-w-0`,children:[u(`p`,{className:`text-xs text-foreground`,children:a(`notificationRules.alarmNotify.${s}`)}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:a(`notificationRules.alarmNotify.${s}Hint`)})]}),u(G,{checked:o[t],onCheckedChange:e=>i(t,e),disabled:r,"data-testid":`alarm-notify-${e.mode}-${t}`,"aria-label":a(`notificationRules.alarmNotify.${s}`)})]},t))]})}function ba({coverage:e,rows:t,names:r}){let i=t.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,a=di(e,r.nameOf);return n(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${e.mode}`,children:[mi(e)?u(q,{variant:`warning`,title:a,"data-testid":`alarm-arms-nothing`,children:`Arms nothing — no enabled rule is gated on this mode`}):n(q,{variant:`default`,title:a,"data-testid":`alarm-covers`,children:[`Checks `,i,` `,i===1?`sensor`:`sensors`]}),e.skippedDevices.length>0?n(q,{variant:`warning`,title:fi(e.skippedDevices,r.nameOf),"data-testid":`alarm-skipped`,children:[e.skippedDevices.length,` not notified`]}):null]})}function xa(e){return e.status===`answered`?e.openingIds:null}function Sa({check:e,view:t}){return t.unresolved?e.status===`pending`?n(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[u(K,{className:`h-3 w-3 animate-spin`}),`Checking which devices are openings…`]}):e.status===`failed`?n(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[n(`span`,{children:[`Couldn't check which devices are openings (`,e.error,`).`]}),u(A,{type:`button`,size:`sm`,variant:`outline`,onClick:e.retry,children:`Retry`})]}):null:null}var Ca=[{value:`rearmAfter`,label:`Re-arm after`},{value:`disableAfter`,label:`Disarm after`},{value:`doNothing`,label:`Do nothing (stay triggered)`}];function wa({coverage:e,settings:t,disabled:r,onDelayEdit:i,onPostTriggeredEdit:a,onScheduleEdit:o}){let s=e.mode,c=We(t,s),l=c.source.postTriggeredAction==="default",d=c.postTriggeredAction!==`doNothing`,f=(t.modeDelays??[]).find(e=>e.mode===s)?.schedule;return n(`div`,{className:`space-y-3`,"data-testid":`alarm-delays-${s}`,children:[n(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:[Gi.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let n=c.source[e.field]==="default";return u(Ji,{label:e.label,value:c[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:r,testId:`alarm-delay-${s}-${e.key}`,onCommit:t=>i(e.field,t),adornment:n?u(q,{variant:`default`,title:`Uses the system default (${t[e.field]} s)`,children:`Default`}):u(A,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:`Use the default`,"aria-label":`${e.label}: use the default`,onClick:()=>i(e.field,`default`),"data-testid":`alarm-delay-${s}-${e.key}-default`,children:u(h,{className:`h-3.5 w-3.5`})})},e.field)}),n(`div`,{children:[n(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:[`After trigger`,l?u(q,{variant:`default`,className:`ml-1.5 align-middle`,title:`Uses the system default`,children:`Default`}):u(A,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:r,title:`Use the default`,"aria-label":`After trigger: use the default`,onClick:()=>a(`default`),"data-testid":`alarm-delay-${s}-post-default`,children:u(h,{className:`h-3.5 w-3.5`})})]}),u(`select`,{className:`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:c.postTriggeredAction,disabled:r,"data-testid":`alarm-delay-${s}-post`,onChange:e=>{let t=yt.safeParse(e.target.value);t.success&&a(t.data)},children:Ca.map(e=>u(`option`,{value:e.value,children:e.label},e.value))})]}),d?Gi.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let n=c.source[e.field]==="default";return u(Ji,{label:e.label,value:c[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:r,testId:`alarm-delay-${s}-${e.key}`,onCommit:t=>i(e.field,t),adornment:n?u(q,{variant:`default`,title:`Uses the system default (${t[e.field]} s)`,children:`Default`}):u(A,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:`Use the default`,"aria-label":`${e.label}: use the default`,onClick:()=>i(e.field,`default`),"data-testid":`alarm-delay-${s}-${e.key}-default`,children:u(h,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),n(`div`,{"data-testid":`alarm-schedule-${s}`,children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Activation schedule`}),u(`p`,{className:`mb-1 text-[10px] text-foreground-subtle`,children:`When this mode may be armed. Empty means any day and time.`}),u(`fieldset`,{disabled:r,className:`min-w-0 border-0 p-0`,children:u(kr,{value:f,onChange:o,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var Ta={"no-opening":`This household has no contact, cover or lock.`};function Ea({coverage:e,live:t,settings:r,names:i,openingsCheck:a,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:d,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m,onNotifyEdit:h,disabled:g}){let _=ri({live:t,listed:Ti(r,e.mode),openingIds:xa(a)}),v=ii(_),y=pa({rowCount:o.length,candidatesComplete:!_.unresolved});return n(`div`,{className:`flex flex-col gap-3`,"data-mode":e.mode,"data-empty":mi(e)?`true`:`false`,children:[u(ba,{coverage:e,rows:o,names:i}),u(wa,{coverage:e,settings:r,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),n(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:[`Blank delay fields use the system defaults (exit 30 s, entry 20 s, re-arm after`,` `,30,` s).`]}),u(ya,{coverage:e,settings:r,disabled:g,onNotifyEdit:h}),n(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[u(Sa,{check:a,view:_}),v===null?null:u(`p`,{className:`text-xs text-foreground-subtle`,children:Ta[v]}),y===`none`&&v===null?u(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`alarm-sensors-none`,children:`No sensor is covered by a rule of this mode.`}):null,y===`rows`?u(aa,{mode:e.mode,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:d,disabled:g}):null]})]})}t();function Da({profiles:e,busy:t,onActivate:r,onCreate:i,onClone:o,onRename:s,onDelete:l}){let[d,f]=c(``),[p,m]=c(!1),h=e.items.find(t=>t.id===e.activeId)??e.items[0],_=h!==void 0&&!h.isDefault,v=d.trim(),y=()=>{v.length!==0&&(i(v),f(``))},b=()=>{v.length===0||h===void 0||(o(h.id,v),f(``))},x=()=>{v.length===0||h===void 0||(s(h.id,v),f(``),m(!1))};return n(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface-1 p-3`,"data-testid":`alarm-profiles`,children:[n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:`Profile`}),u(`select`,{id:`alarm-profile-select`,className:`h-8 min-w-[10rem] rounded-md border border-border bg-background px-2 text-sm`,"data-testid":`alarm-profile-select`,disabled:t,value:e.activeId,onChange:e=>r(e.target.value),children:e.items.map(e=>n(`option`,{value:e.id,children:[e.name,e.isDefault?` (default)`:``]},e.id))}),_?u(A,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-delete`,title:`Delete this profile`,onClick:()=>{h!==void 0&&l(h.id)},children:u(g,{className:`h-3.5 w-3.5`})}):null]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(O,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:p?`New name`:`New profile name`,value:d,disabled:t,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(p?x():y())}}),p?n(a,{children:[u(A,{type:`button`,size:`sm`,disabled:t||v.length===0,"data-testid":`alarm-profile-rename-save`,onClick:x,children:`Rename`}),u(A,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{m(!1),f(``)},children:`Cancel`})]}):n(a,{children:[n(A,{type:`button`,size:`sm`,disabled:t||v.length===0,"data-testid":`alarm-profile-create`,title:`Create with system defaults`,onClick:y,children:[u(Te,{className:`mr-1 h-3.5 w-3.5`}),`Create`]}),n(A,{type:`button`,size:`sm`,variant:`secondary`,disabled:t||v.length===0||h===void 0,"data-testid":`alarm-profile-clone`,title:`Clone the selected profile`,onClick:b,children:[u(B,{className:`mr-1 h-3.5 w-3.5`}),`Clone`]}),u(A,{type:`button`,size:`sm`,variant:`ghost`,disabled:t||h===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{m(!0),f(h?.name??``)},children:`Rename`})]})]}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Create starts from system defaults. Clone copies the selected profile (sensors, secure-on-arm, delays). Switching applies that profile for the next arm.`})]})}t();var Oa=[`notificationRules`,`getAlarmConfig`],ka=[`notificationRules`,`getAlarmSensors`],Aa=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],ja=6e4;function Ma(e){return e instanceof Error?e.message:String(e)}function Na({notice:e}){switch(e.kind){case`refused`:return n(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:[`Saving `,e.inFlight.name,` (`,li(e.inFlight.mode),`) — wait for it to finish.`]});case`not-landed`:return n(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:[`The hub did not apply this change — another editor may have changed it, or the hub needs an update (`,e.write.name,`, `,li(e.write.mode),`).`]});case`failed`:return u(`p`,{className:`text-xs text-danger`,role:`alert`,"data-testid":`alarm-switch-failed`,children:`Could not change ${e.write.name} for ${li(e.write.mode)}: ${e.error}`})}}function Pa(){let t=p(),a=o(),d=i({queryKey:Oa,queryFn:async()=>t.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>bi(e.state.data?.live?.state)}),f=ge({projection:`slim`}),[m,h]=c(!1),g=l({mutationFn:e=>t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{a.setQueryData(Oa,e),h(!ft(t,e.settings))}}),_=l({mutationFn:async e=>{switch(e.kind){case`activate`:return t.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return t.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return t.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{a.setQueryData(Oa,e),h(!1)}}),v=()=>a.invalidateQueries({queryKey:Oa}),y=r(()=>{let e=new Map;for(let t of f.data??[])e.set(t.id,t.name);return e},[f.data]),b=d.data?.live,S=i({queryKey:Aa,staleTime:ja,queryFn:async()=>new Set(await t.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...ti]}))}),C=r(()=>(f.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[f.data]),w=r(()=>new Map(C.map(e=>[e.id,e])),[C]),T=S.isError?{status:`failed`,error:S.error instanceof Error?S.error.message:String(S.error),retry:()=>void S.refetch()}:S.data===void 0?{status:`pending`}:{status:`answered`,openingIds:S.data},E=r(()=>{let e=new Map;for(let t of b?.openings??[])for(let n of t.devices)e.set(n.deviceId,oi(n));return ai(y,_e(f),e)},[b,y,f]),O=de(!0),[k,A]=c(null),j=r(()=>{let e=new Map,t=d.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,ri({live:t.live,listed:Ti(t.settings,n.mode),openingIds:S.data??null}).ids);return e},[d.data,S.data]),M=r(()=>{let e=new Set;for(let t of j.values())for(let n of t)E.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[j,E]),P=i({queryKey:[...ka,M],enabled:M.length>0,placeholderData:s,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&sa(Ma(e.state.error))?!1:b!==void 0&&Ci(b.state)?5e3:15e3,retry:(e,t)=>!sa(Ma(t))&&e<2,queryFn:async()=>{let e=[];for(let n of ma(M,500))e.push(await t.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...n]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),I=P.isError?{status:`failed`,error:Ma(P.error)}:P.data===void 0?{status:`pending`}:{status:`answered`,sensors:P.data.sensors},L=e(null),[R,z]=c(null),[te,B]=c(null),ne=async e=>{try{let n=await t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:ga(e)});_a(e,n.settings).kind===`landed`?a.setQueryData(Oa,n):(B({kind:`not-landed`,write:e}),a.invalidateQueries({queryKey:Oa}))}catch(t){B({kind:`failed`,write:e,error:Ma(t)}),a.invalidateQueries({queryKey:Oa})}finally{L.current=null,z(null),B(e=>e?.kind===`refused`?null:e)}},re=(e,t,n,r)=>{let i=ha(L.current,e,t,n,r);if(i.kind===`refused`){B({kind:`refused`,inFlight:i.inFlight});return}L.current=i.write,z(i.write),B(null),ne(i.write)};if(d.isLoading)return u(Jr,{icon:N,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(K,{className:`h-5 w-5 animate-spin`})});let V=d.data;if(V===void 0||d.isError)return u(Jr,{icon:N,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(F,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(V.deviceId===null)return u(Jr,{icon:N,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(x,{className:`p-4`,children:u(`p`,{className:`text-sm text-foreground-subtle`,children:`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 H=V.settings,ie=g.isPending||_.isPending,U=e=>{h(!1),g.mutate(e)},ae=(e,t,n)=>{let r=Ai(H,e,t,n);r!==null&&U({modeDelays:[r]})},oe=(e,t)=>{let n=ji(H,e,t);n!==null&&U({modeDelays:[n]})},se=(e,t)=>{let n=Mi(H,e,t);n!==null&&U({modeDelays:[n]})},W=(e,t,n)=>{let r=zi(H,e,t,n);r!==null&&U({modeDelays:[r]})},ce=new Map(V.coverage.map(e=>[e.mode,fa({candidates:(j.get(e.mode)??[]).map(e=>({...w.get(e),id:e,name:E.nameOf(e)})),removedIds:new Set((j.get(e.mode)??[]).filter(E.isRemoved)),coverage:e,nonBlocking:Ti(H,e.mode),blocking:Ei(H,e.mode),secureOnArmOff:Di(H,e.mode),sensors:I})])),G=V.coverage.find(e=>e.mode===k)??V.coverage.find(e=>(ce.get(e.mode)?.length??0)>0)??V.coverage[0],le=G?.mode??``;return n(Jr,{icon:N,title:`Alarm`,subtitle:`The panel, what each mode arms, and who hears about it.`,children:[g.isError?u(F,{title:`Could not save`,message:String(g.error)}):null,_.isError?u(F,{title:`Could not update profile`,message:String(_.error)}):null,m?u(`div`,{"data-testid":`alarm-save-not-landed`,children:u(F,{variant:`warning`,title:`Not applied`,message:`The hub did not apply this change — another editor may have changed it, or the hub needs an update`})}):null,V.profiles===void 0?null:u(Da,{profiles:V.profiles,busy:ie,onActivate:e=>_.mutate({kind:`activate`,id:e}),onCreate:e=>_.mutate({kind:`create`,name:e}),onClone:(e,t)=>_.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>_.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>_.mutate({kind:`delete`,id:e})}),u(Wi,{live:V.live,onChanged:v}),n(x,{className:`p-4`,"data-testid":`alarm-coverage`,children:[u(D,{value:le,onValueChange:e=>{let t=V.coverage.find(t=>t.mode===e);t!==void 0&&A(t.mode)},children:u(Ce,{className:`mb-3`,children:V.coverage.map(e=>n(ee,{value:e.mode,"data-testid":`alarm-tab-${e.mode}`,children:[li(e.mode),u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:ce.get(e.mode)?.length??0})]},e.mode))})}),te===null?null:u(Na,{notice:te}),G===void 0?null:u(Ea,{coverage:G,live:V.live,settings:H,names:E,openingsCheck:T,rows:ce.get(G.mode)??[],sensorsRetry:I.status===`failed`&&!sa(I.error)?()=>void P.refetch():null,inFlight:R,onSwitch:(e,t,n)=>re(G.mode,e,t,n),zones:O,onDelayEdit:(e,t)=>ae(G.mode,e,t),onPostTriggeredEdit:e=>oe(G.mode,e),onScheduleEdit:e=>se(G.mode,e),onNotifyEdit:(e,t)=>W(G.mode,e,t),disabled:ie},G.mode)]})]})}var Fa=`history`,Ia=`ruleId`,La=[Ia],Ra=24,za=0,Ba=100;function Va(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Fa),n.set(Ia,t),n}function Ha(e,t){let n=new URLSearchParams(e);return t===``?n.delete(Ia):n.set(Ia,t),n}function Ua(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Ra:za,limit:Ba}}function Wa(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?`Deleted rule (${e.selected})`:e.selected}]:[];return[{value:``,label:`All rules`},...t,...n]}t();var Ga=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],Ka=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],qa=[50,100,250,500];function Ja(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Ya(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Xa(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 Za({entry:e,cameraName:t,onClose:r}){let i=Xa(e),a=e.subject.systemEvent;return u(Ae,{open:!0,onOpenChange:e=>!e&&r(),children:n(S,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[u(w,{children:u(C,{className:`min-w-0 break-words`,children:i.title||e.ruleName})}),u(z,{children:n(`dl`,{className:`space-y-3`,children:[n(`div`,{children:[u(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:`Body`}),u(`dd`,{className:`mt-1 whitespace-pre-wrap text-sm text-foreground`,children:i.body.length>0?i.body:`—`})]}),n(`div`,{className:`grid grid-cols-2 gap-3 text-[11px]`,children:[n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`When`}),u(`dd`,{className:`text-foreground`,children:new Date(e.createdAt).toLocaleString()})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Status`}),u(`dd`,{className:`text-foreground`,children:e.status})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Rule`}),u(`dd`,{className:`text-foreground`,children:e.ruleName})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Device`}),u(`dd`,{className:`text-foreground`,children:t})]}),a===void 0?null:n(`div`,{className:`col-span-2`,children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Kind`}),u(`dd`,{className:`text-foreground`,children:a.kind})]}),e.error===void 0?null:n(`div`,{className:`col-span-2`,children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Error`}),u(`dd`,{className:`text-danger`,children:e.error})]})]})]})}),u(te,{children:u(A,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:`Close`})})]})})}function Qa(){let e=p(),[t,a]=Gr(),[o,s]=c(()=>Ua(t)),[l,d]=c(null),f=e=>s(t=>({...t,...e})),m=e=>{f({ruleId:e}),a(Ha(t,e),{replace:!0})},h=i({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),g=ge({projection:`slim`}),_=Date.now(),v=i({queryKey:[`notificationRules`,`getHistory`,o],retry:!1,queryFn:async()=>{let t=o.windowHours>0?_-o.windowHours*36e5:void 0;return(await e.trpcClient.notificationRules.getHistory.query({filter:{limit:o.limit,...o.ruleId?{ruleId:o.ruleId}:{},...o.deviceId?{deviceId:Number(o.deviceId)}:{},...Ja(o.status)?{status:Ja(o.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),y=r(()=>{let e=new Map;for(let t of g.data??[])t.type===Be.Camera&&e.set(t.id,t.name);return e},[g.data]),b=e=>y.get(e)??`Camera #${String(e)}`,S=v.data??[],C=v.isError;return n(Jr,{icon:Me,title:`Delivery history`,subtitle:`A searchable log of every notification the rules delivered (or failed to deliver).`,children:[n(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),u(T,{"data-testid":`history-rule-filter`,value:o.ruleId,onChange:e=>m(e.target.value),options:[...Wa({rules:h.data??[],answered:h.isSuccess,selected:o.ruleId})]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),u(T,{value:o.deviceId,onChange:e=>f({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(g.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),u(T,{value:o.status,onChange:e=>f({status:e.target.value}),options:Ka.map(e=>({value:e.value,label:e.label}))})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),u(T,{value:String(o.windowHours),onChange:e=>f({windowHours:Number(e.target.value)}),options:Ga.map(e=>({value:String(e.value),label:e.label}))})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),u(T,{value:String(o.limit),onChange:e=>f({limit:Number(e.target.value)}),options:qa.map(e=>({value:String(e),label:String(e)}))})]})]}),v.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(K,{className:`h-6 w-6 animate-spin text-primary`})}),C&&!v.isLoading&&u(x,{children:n(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[u(Me,{className:`h-6 w-6 text-foreground-subtle`}),u(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),u(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:`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.`}),n(`button`,{type:`button`,onClick:()=>void v.refetch(),className:`mt-1 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:[u(H,{className:`h-3 w-3`}),` Retry`]})]})}),!C&&!v.isLoading&&S.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!C&&S.length>0&&u(x,{children:u(E,{columns:$a(b),rows:S,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>d(e)})}),l!==null&&u(Za,{entry:l,cameraName:b(l.deviceId),onClose:()=>d(null)})]})}function $a(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>u(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`Notification`,render:e=>{let t=Xa(e);return n(`span`,{className:`block max-w-[18rem]`,children:[u(`span`,{className:`block truncate text-[11px] font-medium text-foreground`,children:t.title.length>0?t.title:e.subject.label??e.subject.className}),t.body.length>0?u(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:t.body}):null]})}},{key:`status`,header:`Status`,nowrap:!0,render:e=>n(`span`,{className:`flex items-center gap-1.5`,children:[u(q,{variant:Ya(e.status),children:e.status}),e.attempts>1?n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:`Detail`,render:e=>e.error?u(`span`,{className:`text-[11px] text-danger`,children:e.error}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var eo=/\{\{\s*(\w+)\s*\}\}/g,to=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function no(e,t,n){let r=Math.min(Math.max(t.start,0),e.length),i=Math.min(Math.max(t.end,r),e.length);return{value:e.slice(0,r)+n+e.slice(i),cursor:r+n.length}}function ro(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function io(e){return[...e.matchAll(eo)].map(e=>e[1]??``).filter(e=>e.length>0)}function ao(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function oo(e,t){return[...new Set(io(e))].filter(e=>!ao(e,t))}var so={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function co(e){return e.map(e=>{let t=Ie.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)||vt.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function lo(e){let t=new Set(e.map(e=>e.name)),n=Ie.filter(e=>Ye(e)&&!t.has(e.name));return[...e,...n]}function uo(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=so[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)||!Je(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:Xe(e,t)&&He(e,t))}function fo(e){return to.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var po=[`nc`,`template-catalog`],mo=400;function ho(){let e=p();return i({queryKey:po,staleTime:5*6e4,queryFn:async()=>lo(co((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function go(e,t,n){let r=p(),a=ye(t.title??``,mo),o=ye(t.body??``,mo);return i({queryKey:[`nc`,`template-preview`,e,a,o],enabled:n&&(a.length>0||o.length>0),staleTime:3e4,queryFn:()=>r.trpcClient.notificationRules.previewTemplate.mutate({context:e,template:{...a?{title:a}:{},...o?{body:o}:{}}})})}t();var _o={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},vo=`block text-[11px] font-medium text-foreground mb-1`,yo=`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`;function bo({label:t,value:r,onChange:i,vars:a,multiline:o=!1,placeholder:s,disabled:c=!1,testId:l}){let d=e(null),f=e(null),p=a?oo(r,a):[],m=e=>{let t=o?f.current:d.current,n={start:t?.selectionStart??r.length,end:t?.selectionEnd??r.length},a=ro(e),s=no(r,n,a.text);i(s.value);let c=s.cursor-a.text.length+a.cursorOffset;requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(c,c)})},h=e=>i(e.target.value);return n(`div`,{className:`space-y-1`,children:[u(`label`,{className:vo,children:t}),o?u(`textarea`,{ref:f,value:r,rows:2,disabled:c,placeholder:s,onChange:h,className:yo,"data-testid":`${l}-input`}):u(O,{ref:d,value:r,disabled:c,placeholder:s,onChange:h,"data-testid":`${l}-input`}),a&&a.length===0?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`No variables for this field.`}):null,a&&a.length>0?u(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:fo(a).map(e=>n(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${l}-group-${e.group}`,children:[u(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:_o[e.group]}),e.vars.map(e=>u(`button`,{type:`button`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),title:`${e.description??e.label} — e.g. "${e.example}"`,className:`rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-foreground hover:bg-surface-hover`,"data-testid":`${l}-chip-${e.name}`,children:e.dynamic?`${e.name}<class>`:e.name},e.name))]},e.group))}):null,p.length>0?n(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${l}-unknown`,children:[u(je,{className:`h-3 w-3`}),p.map(e=>`{{${e}}}`).join(` `),` will be empty in this notification.`]}):null]})}function xo({context:e,title:t,body:r,testId:i}){let a=go(e,{title:t,body:r},!0);return a.data?n(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":i,children:[u(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:`Preview (example values)`}),a.data.title===null?null:u(`p`,{className:`font-medium`,children:a.data.title}),a.data.body===null?null:u(`p`,{className:`whitespace-pre-wrap`,children:a.data.body})]}):null}var So=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,Co=`block text-[11px] font-medium text-foreground`;function wo({title:e,description:t,children:r}){return n(`div`,{className:`flex flex-col gap-2`,children:[n(`div`,{children:[u(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t})]}),r!==void 0&&u(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function To(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function Eo(e,t){return{kind:`cap`,deviceId:t,cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}}}function Do(e){let t=To(e.deviceId);return t.length===0?[Eo(e,0)]:t.map(t=>Eo(e,t))}function Oo(e){return Do(e).map(e=>({kind:`do`,action:e}))}function ko(e,t){let n=e[t];if(n===void 0||n.kind!==`cap`)return{wire:{deviceId:0,cap:``,method:``},length:1};let r=n.deviceId>0?[n.deviceId]:[],i=1;for(let a=t+1;a<e.length;a+=1){let t=e[a];if(t===void 0||t.kind!==`cap`||t.cap!==n.cap||t.method!==n.method||JSON.stringify(t.args??{})!==JSON.stringify(n.args??{}))break;t.deviceId>0&&r.push(t.deviceId),i+=1}return{wire:{deviceId:r.length===0?0:r.length===1?r[0]:[...r],cap:n.cap,method:n.method,...n.args===void 0?{}:{args:{...n.args}}},length:i}}function Ao(e,t){let n=e[t];return n===void 0||n.kind!==`do`?{wire:{deviceId:0,cap:``,method:``},length:1}:ko(e.slice(t).map(e=>e.kind===`do`?e.action:{kind:`wait`,seconds:0}),0)}function jo({value:e,onChange:t,devices:r,devicesState:i,sequences:a=[]}){let o=ln(e,new Set(a.map(e=>e.id))),s=(n,r)=>t({...e,[n]:r}),c=(n,r)=>t({...e,buttons:e.buttons.map((e,t)=>t===n?r:e)});return n(`div`,{className:`space-y-4`,children:[o.length>0&&u(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:o.map(e=>u(`p`,{children:e.message},e.message))}),Ht.map(t=>u(Mo,{hookKey:t,bindings:e[t],sequences:a,devices:r,devicesState:i,onChange:e=>s(t,e)},t)),n(`section`,{className:`space-y-2`,children:[u(wo,{title:`Buttons on the notification`,description:`Each button runs one shared sequence when tapped.`,children:n(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:a.length===0,onClick:()=>t({...e,buttons:[...e.buttons,Jt(e.buttons.length,a[0]?.id??``)]}),children:[u(Te,{className:`h-3.5 w-3.5 shrink-0`}),` Button`]})}),e.buttons.length>0&&n(`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:[u(je,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),n(`span`,{children:[`A button's link travels inside the notification. The link is the only authority: anyone holding the notification can run the button `,u(`strong`,{children:`once`}),`, within 15 minutes.`]})]}),a.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Create a sequence on the Sequences tab first — a button runs one, it does not define its own steps.`}):e.buttons.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No buttons. The notification arrives with nothing to tap.`}):e.buttons.map((n,r)=>u(No,{button:n,sequences:a,onChange:e=>c(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function Mo({hookKey:e,bindings:t,sequences:r,devices:i,devicesState:a,onChange:o}){let s=Xt[e],c=[],l=0;for(;l<t.length;){if(t[l].kind===`sequence`){c.push({start:l,kind:`sequence`,length:1}),l+=1;continue}let e=Ao(t,l);c.push({start:l,kind:`do`,length:e.length}),l+=e.length}return n(`section`,{className:`space-y-2`,children:[n(wo,{title:s.title,description:s.hint,children:[n(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4||r.length===0,onClick:()=>o([...t,Cn(r[0]?.id??``)]),children:[u(Te,{className:`h-3.5 w-3.5`}),` Sequence`]}),n(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4,onClick:()=>o([...t,Tn()]),children:[u(Te,{className:`h-3.5 w-3.5`}),` Single action`]})]}),t.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Nothing on this edge.`}):c.map(e=>{if(e.kind===`sequence`){let i=t[e.start];return i.kind===`sequence`?n(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:Co,children:`Sequence`}),u(`select`,{className:So,value:i.sequenceId,onChange:n=>{let r=[...t];r[e.start]={kind:`sequence`,sequenceId:n.target.value},o(r)},children:r.map(e=>u(`option`,{value:e.id,children:e.name},e.id))})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o(t.filter((t,n)=>n!==e.start)),title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]},`seq-${String(e.start)}`):null}return u(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:n(`div`,{className:`flex items-start justify-between gap-2`,children:[u(`div`,{className:`min-w-0 flex-1`,children:u(Yr,{value:Ao(t,e.start).wire,devices:i,listState:a,allowMultiSameFamily:!0,onChange:n=>{let r=Oo(n);o([...t.slice(0,e.start),...r,...t.slice(e.start+e.length)])}})}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o([...t.slice(0,e.start),...t.slice(e.start+e.length)]),title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})},`do-${String(e.start)}`)})]})}function No({button:e,sequences:t,onChange:r,onRemove:i}){return n(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[n(`div`,{className:`w-28`,children:[u(`label`,{className:Co,children:`Id`}),u(O,{className:`mt-1`,value:e.id,onChange:t=>r({...e,id:t.target.value})})]}),n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:Co,children:`Label`}),u(O,{className:`mt-1`,value:e.label,onChange:t=>r({...e,label:t.target.value})})]}),n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:Co,children:`Sequence`}),u(`select`,{className:So,value:e.sequenceId,onChange:t=>r({...e,sequenceId:t.target.value}),children:t.map(e=>u(`option`,{value:e.id,children:e.name},e.id))})]}),n(`div`,{className:`w-32`,children:[u(`label`,{className:Co,children:`Icon`}),n(`select`,{className:So,value:e.icon??``,onChange:t=>{let n={...e};t.target.value===``?delete n.icon:n.icon=t.target.value,r(n)},children:[u(`option`,{value:``,children:`—`}),xn.map(e=>u(`option`,{value:e.value,children:e.label},e.value))]})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})}var Po=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Fo=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],Io={minConfidence:`class`},Lo=[{id:`system`,label:`System events`},{id:`class`,label:`Detections`},{id:`zones`,label:`Zones`},{id:`label`,label:`Faces, plates & labels`},{id:`quality`,label:`Quality`},{id:`scope`,label:`Only while`},{id:`device`,label:`Device event`},{id:`package`,label:`Package`},{id:`occupancy`,label:`Occupancy`},{id:`audio`,label:`Sound`},{id:`schedule`,label:`Schedule`}];function Ro(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Fo)t.has(e)&&n.add(r);return n}function zo(e){return Io[e.id]??e.group}function Bo(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Vo(e){let t=Ro(e),n=e.filter(e=>!Po.has(e.id)&&!t.has(e.id)),r=new Set(Lo.map(e=>e.id)),i=[],a=e=>n.filter(t=>zo(t)===e);for(let e of Lo){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=zo(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Bo(e),descriptors:a(e)});return i}function Ho(e,t){switch(e){case`zones`:return Tr(t.zones?.ids,t.zonesExclude);case`labels`:return Tr(t.labelEquals,void 0);case`identities`:return Uo(t)}}function Uo(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?Tr(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function Wo(e,t,n){switch(e){case`zones`:return Go(t,n);case`labels`:return Ko(t,n);case`identities`:return qo(t,n)}}function Go(e,t){let{zones:n,zonesExclude:r,...i}=e,a=Wn(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function Ko(e,t){let{labelEquals:n,...r}=e,i=Wn(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function qo(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=tr(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=Wn(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var Jo={all:`All`,only:`Only these`,except:`All except these`},Yo={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 Xo({draft:e,onChange:t,exceptOffered:r,plural:i,renderPicker:a,describe:o,testId:s}){let{t:c}=Dt(),l=(e,t,n)=>c(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),d=c(`ruleScope.items.${i}`,Yo[i].items),f=Ot.filter(t=>t!==`except`||r||e.mode===`except`),p=tr(e),m=mr(e),h=e.mode===`all`?null:e.mode;return n(`div`,{className:`mt-1 space-y-1.5`,"data-testid":s,children:[u(`div`,{role:`radiogroup`,"aria-label":l(`ruleScope.which`,`Which {{items}}`,d),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(n=>{let r=n===e.mode;return u(`button`,{type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${n}`,onClick:()=>t(Or(e,n)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,children:c(`ruleScope.mode.${n}`,Jo[n])},n)})}),h===null?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(`ruleScope.every.${i}`,Yo[i].every)}):a(Pn(e),n=>t(_r(e,n)),h),p.length>0&&n(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[l(`ruleScope.legacy`,`This rule also excludes {{items}} — kept when you save.`,p.map(o).join(`, `)),` `,u(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>t(jr(e)),children:c(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:l(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(o).join(`, `))})]})}function Zo(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 Qo(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})}t();function $o(e,t,n){let[r,i]=c(()=>Ho(e,t));return[r,r=>{i(r),n(Wo(e,t,r))}]}function es(e,t){return t?`failed`:e?`pending`:`answered`}function ts({conditions:e,onConditionsChange:t,exceptOffered:n,cameraIds:i,cameras:a}){let{t:o}=Dt(),[s,c]=$o(`zones`,e,t),{options:l,loading:d,failed:f}=Ar(i,a),p=r(()=>Qo(l),[l]),m=es(d,!1),h=f?{state:`failed`,devices:void 0}:{state:m,devices:m===`answered`?p:void 0},g=r(()=>new Map(p.map(e=>[e.id,e.name])),[p]);return u(Xo,{draft:s,onChange:c,exceptOffered:n,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>i.length===0?u(`p`,{className:Bn,children:o(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):u(W,{devices:p,listState:m,fleet:h,value:e,onChange:t,emptyMeansAll:!0,noun:`zone`,groupTitle:e=>e.type??o(`notificationRules.zones.group`,`Zones`),testId:`zone-picker`},n)})}function ns({conditions:e,onConditionsChange:t,exceptOffered:n}){let{t:i}=Dt(),[a,o]=$o(`identities`,e,t),{options:s,loading:c,failed:l}=Un(),d=r(()=>s.map(e=>({id:e.value,name:e.label})),[s]),f=r(()=>new Map(d.map(e=>[e.id,e.name])),[d]);return u(Xo,{draft:a,onChange:o,exceptOffered:n,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>u(W,{devices:d,listState:es(c,l),value:e,onChange:t,emptyMeansAll:n===`except`,...n===`only`?{emptyLabel:i(`notificationRules.faces.anyKnown`,`Any known face — nobody in particular`)}:{},noun:`face`,groupTitle:()=>i(`notificationRules.faces.group`,`Known faces`),testId:`identity-picker`},n)})}function rs({conditions:e,onConditionsChange:t}){let{t:n}=Dt(),[r,i]=$o(`labels`,e,t);return u(Xo,{draft:r,onChange:i,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>u(kn,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function is(e){let t=_t(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function as(e){return e.type??`Other`}t();function os({taxonomy:e,scope:t,onChange:n,exceptOffered:i}){let a=r(()=>is(e),[e]),o=r(()=>new Map((a??[]).map(e=>[e.id,e.name])),[a]);return u(Xo,{draft:t,onChange:n,exceptOffered:i,plural:`classes`,describe:e=>o.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>a===null?u(kn,{value:e,placeholder:`Add value…`,onChange:t}):u(W,{devices:a,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:as,testId:`class-picker`},n)})}function ss(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function cs({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return u(W,{devices:e.map(ss),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`,showAll:!0})}function ls({devices:e,scope:t,onChange:n,listState:r,savedScope:i,exceptOffered:a}){let o=new Map(e.map(e=>[e.id,e.name]));return u(Xo,{draft:t,onChange:n,exceptOffered:a,plural:`devices`,describe:e=>o.get(e)??`Device #${String(e)}`,testId:`rule-device-scope`,renderPicker:(t,n,a)=>u(cs,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function us(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function ds(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function fs(e){let t=us(e),n=e.data===void 0?[]:st(e.data.nodes),r=ds(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function ps(e){let t=us(e),n=e.data===void 0?[]:Fe(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var ms=[`nc-pickers`,`node-directory`],hs=[`nc-pickers`,`package-list`],gs=6e4,_s={hub:`Hub`,agent:`Agents`},vs={server:`Server`,framework:`Framework`,wrapper:`Wrapper`,addon:`Addons`};function ys(e){let t=_s[e.type??``]??`Nodes`;return e.location===`offline`?`${t} · offline`:t}function bs(e){return vs[e.type??``]??`Packages`}function xs({value:e,onChange:t,testId:r}){let a=p().trpcClient,o=i({queryKey:ms,staleTime:gs,queryFn:()=>a.nodes.directory.query()}),s=fs(o);return n(`div`,{children:[u(W,{devices:s.items,listState:s.listState,fleet:s.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:ys,...r===void 0?{}:{testId:r}}),o.data?.complete===!1&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:`The node history could not be read — offline nodes may be missing from this list.`})]})}function Ss({value:e,onChange:t,testId:n}){let r=p().trpcClient,a=ps(i({queryKey:hs,staleTime:gs,queryFn:()=>r.addons.listPackages.query()}));return u(W,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:bs,...n===void 0?{}:{testId:n}})}var Cs={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-tank-low`]},template:{body:`{{deviceName}}`}};function ws(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 Ts(e,t){return e===`pending`?`pending`:e===`success`?`current`:ws(t)===`BAD_REQUEST`?`outdated`:`unknown`}function Es(e){let t=p(),n=i({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(Cs)});return e?Ts(n.status,n.error):`pending`}t();var Ds=`/system/settings`,Os=`/system/notifications?tab=alarm`,ks=`text-primary underline-offset-2 hover:underline`;function As(e,t){let n=Wn(t);return Kn(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function js({family:e,value:t,cameras:i,allDevices:a,fleet:o,savedHadDevices:s,onChange:l}){let d=r(()=>t?.kinds??[],[t]),f=r(()=>a===void 0?i:a.map(ss),[a,i]),p=r(()=>i.map(e=>({id:e.id,name:e.name,type:`camera`})),[i]),m=Qn(e,d),h=Es(e===`device-events`),g=e===`alarm`,[_,v]=c(()=>Tr(t?.deviceIds,t?.excludeDeviceIds)),[y]=c(()=>Tr(t?.deviceIds,t?.excludeDeviceIds)),b=r(()=>{let e=new Map;for(let t of g?p:f)e.set(t.id,t.name);return e},[p,g,f]);return n(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[Yn(e).map(r=>n(`div`,{children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:r.label}),u(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:r.kinds.map(n=>{let r=d.includes(n.value);return u(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":n.label,onClick:()=>l(Ir(t,n.value,e)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-1 text-[11px] text-primary`:`rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:n.label},n.value)})})]},r.id)),e===`device-events`&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-device-alert-settings`,children:[`The battery threshold and the reminder interval are cluster settings (the consumable threshold is this rule’s own, below):`,` `,u(Kr,{to:Ds,target:`_blank`,rel:`noreferrer`,className:ks,children:`Settings → Battery & offline alerts`}),`.`]}),e===`alarm`&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[u(Kr,{to:Os,target:`_blank`,rel:`noreferrer`,className:ks,children:`Alarm settings`}),d.includes(`alarm-triggered`)&&` — when a rule sets the alarm off, this notification carries that rule's pictures.`]}),h===`outdated`&&n(`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:[`This hub’s server predates per-rule consumable thresholds and tank alerts: it drops a rule’s threshold when the rule is saved (the rule then judges at`,` `,15,`%) and refuses tank events. Update the server (@camstack/server) on every node first.`]}),h===`unknown`&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`}),m.consumableThreshold&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:`Consumable low at (%)`}),u(O,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:zn,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=Hn(e.target.value);n.kind!==`invalid`&&l(Kn(t,{consumableLowPercent:n.kind===`set`?n.value:void 0}))}})]}),m.deviceTypes&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Device types`}),u(kt,{options:cr,value:t?.deviceTypes??[],onChange:e=>l(Kn(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`})]}),Pr(t)&&u(`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:`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.`}),m.devices&&n(`div`,{children:[u(Xo,{draft:_,onChange:e=>{v(e),l(As(t,e))},exceptOffered:m.excludeDevices,plural:`devices`,describe:e=>b.get(e)??`Device #${String(e)}`,testId:`system-event-device-scope`,renderPicker:(e,t,n)=>u(W,{devices:g?p:f,listState:o.state,fleet:o,emptyMeansAll:!0,savedHadDevices:(n===`only`?y.include:y.exclude).length>0||n===`only`&&s,noun:g?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),s&&_.mode===`all`&&u(le,{noun:g?`camera`:`device`})]}),m.nodes&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Nodes`}),u(xs,{value:t?.nodeIds??[],onChange:e=>l(Kn(t,{nodeIds:e})),testId:`system-event-nodes`})]}),m.packages&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Packages`}),u(Ss,{value:t?.packageNames??[],onChange:e=>l(Kn(t,{packageNames:e})),testId:`system-event-packages`})]})]})}function Ms({value:e}){let t=e?.kinds??[];return n(`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:[u(`p`,{children:`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.`}),t.length>0&&u(`p`,{className:`mt-1 text-foreground`,children:t.map(jn).join(`, `)})]})}function Ns({family:e,onChange:t}){return n(`div`,{"data-testid":`system-family-select`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Kind of system rule`}),u(T,{value:e,"aria-label":`Kind of system rule`,onChange:e=>{let n=e.target.value;et(n)&&t(n)},options:lt.map(e=>({value:e,label:ct(e).label}))}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`})]})}t();function Ps({catalog:e,taxonomy:t,delivery:i,conditions:a,classScope:o,onClassScopeChange:s,actions:c,sequenceActionsOf:l,savedConditions:d,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x}){let{t:S}=Dt(),C=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,b(n)},w=rt({delivery:i,conditions:a}),T=r(()=>e.filter(e=>ht(e,i,w)&&rn(e.id,a)),[e,i,w,a]),E=r(()=>Vo(T),[T]),D=e=>T.some(t=>t.id===e),O=e=>Fs.has(e.id)?u(os,{taxonomy:t,scope:o,onChange:s,exceptOffered:D(`classesExclude`)}):Is.has(e.id)?u(ts,{conditions:a,onConditionsChange:b,exceptOffered:D(`zonesExclude`),cameraIds:m??p,cameras:h}):Ls.has(e.id)?u(ns,{conditions:a,onConditionsChange:b,exceptOffered:D(`identitiesExclude`)}):e.id===`labelEquals`?u(rs,{conditions:a,onConditionsChange:b}):null;return u(`div`,{className:`space-y-4`,children:E.map(e=>n(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${e.id}`,children:[u(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:S(`notificationRules.groups.${e.id}`,e.label)}),e.descriptors.map(e=>{let r=O(e);return n(`div`,{"data-testid":`condition-${e.id}`,children:[u(`label`,{className:J,children:Rs(e,S)}),r??u(Vs,{descriptor:e,kind:w,taxonomy:t,conditions:a,actions:c,sequenceActionsOf:l,savedConditions:d,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:C,onScheduleChange:x}),zs(e,S)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:zs(e,S)})]},e.id)})]},e.id))})}var Fs=new Set([`classes`,`classesExclude`]),Is=new Set([`zones`,`zonesExclude`]),Ls=new Set([`identities`,`identitiesExclude`]);function Rs(e,t){return Fs.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):Is.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):Ls.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 zs(e,t){if(!Bs.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var Bs=new Set([...Fs,...Is,...Ls,`labelEquals`,`crossing`]);function Vs({descriptor:e,kind:t,taxonomy:r,conditions:i,actions:o,sequenceActionsOf:s,savedConditions:c,schedule:l,deviceIds:d,cameras:f,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v}){switch(e.valueType){case`deviceIdList`:{if(!er(e.id))break;let t=e.id,n=i[t]??[];return u(Ln,{cameras:f,fleet:p,emptyMeansAll:!0,savedHadDevices:(c?.[t]?.length??0)>0,value:n,onChange:e=>_(t,e.length>0?e:void 0)})}case`stringList`:{if(!ur(e.id))break;let t=e.id,n=e=>_(t,e.length>0?e:void 0);if(t===`eventTypeTokens`)return u(Mr,{deviceIds:d,value:An(i,t),onChange:n});let a=nt(t,r);return a===null?u(kn,{value:An(i,t),placeholder:`Add value…`,onChange:n}):u(Fr,{picker:a,value:An(i,t),onChange:n})}case`number01`:{if(!gr(e.id))break;let t=e.id;return u(vr,{value:Jn(i,t),min:0,max:1,step:.05,onChange:e=>_(t,e)})}case`number`:{if(!Dr(e.id))break;let t=e.id;return u(vr,{value:Jn(i,t),min:0,step:1,onChange:e=>_(t,e)})}case`sourceSelect`:{if(!yr(e.id))break;let t=e.id;return Ks(e,i[t],e=>_(t,e))}case`systemEvent`:{if(!Zn(e.id))break;let n=e.id,r=at(t);return r===void 0?u(Ms,{value:i[n]}):u(js,{family:r,value:i[n],cameras:f,fleet:p,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[n]?.deviceIds?.length??0)>0,onChange:e=>_(n,e)})}case`deviceState`:if(!Nn(e.id))break;return u(or,{gateable:h,value:i.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!Vn(e.id))break;return u(qn,{scenes:g,value:i.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!wr(e.id))break;let t=e.id;return qs(e,i[t],e=>_(t,e))}case`packagePhase`:{if(!sr(e.id))break;let t=e.id;return u(T,{value:i[t]??``,options:[{value:``,label:`— any phase —`},...$t(e,on).map(e=>({value:e.value,label:e.label}))],onChange:e=>_(t,Gs(e.target.value))})}case`sensorTransition`:{if(!Gn(e.id))break;let t=e.id,r=Pe({conditions:i,...o===void 0?{}:{actions:o},...s===void 0?{}:{sequenceActionsOf:s}});return n(a,{children:[u(T,{value:i[t]??``,options:$t(e,rr).map(e=>({value:e.value,label:e.label})),onChange:e=>_(t,On(e.target.value))}),r&&u(`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(!Nr(e.id))break;let t=e.id;return u(Xn,{value:i[t],onChange:e=>_(t,e)})}case`occupancy`:{if(!Rn(e.id))break;let t=e.id;return u(lr,{deviceIds:d,cameras:f,classOptions:Hs(r),value:i[t],onChange:e=>_(t,e)})}case`audio`:{if(!pr(e.id))break;let t=e.id;return u(hr,{taxonomy:r,value:i[t],onChange:e=>_(t,e)})}case`schedule`:return u(kr,{value:l,onChange:v});default:break}return u(Us,{descriptor:e,conditions:i})}function Hs(e){let t=nt(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Us({descriptor:e,conditions:t}){let r=Object.entries(t).find(([t])=>t===e.id);return n(`p`,{className:Bn,children:[r!==void 0&&r[1]!==void 0?`Authored elsewhere and preserved — this admin editor cannot change it yet.`:`Not editable here yet — this condition has no admin editor.`,` `,n(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function Ws(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Gs(e){return on.find(t=>t.value===e)?.value}function Ks(e,t,n){return u(T,{value:t??`any`,options:$t(e,tn).map(e=>({value:e.value,label:e.label})),onChange:e=>n(Ws(e.target.value))})}function qs(e,t,n){return u(Er,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function Js({catalog:e,delivery:t,conditions:r,onConditionsChange:i}){let{t:a}=Dt(),o=rt({delivery:t,conditions:r}),s=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,i(n)},c=n=>e.find(e=>e.id===n&&ht(e,t,o)&&rn(n,r)),l=c(`source`),d=c(`crossing`);return l===void 0&&d===void 0?null:n(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[l&&yr(l.id)&&n(`div`,{"data-testid":`condition-source`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Rs(l,a)}),Ks(l,r.source,e=>s(`source`,e)),zs(l,a)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:zs(l,a)})]}),d&&wr(d.id)&&n(`div`,{"data-testid":`condition-crossing`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Rs(d,a)}),qs(d,r.crossing,e=>s(`crossing`,e)),zs(d,a)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:zs(d,a)})]})]})}var Ys=6e4,Xs=60*Ys,Zs=24*Xs,Qs=Date.UTC(2e3,0,1);function $s(e){if(e==null||e<Qs)return`—`;let t=Date.now()-e;return t<0||t<3e4?`just now`:t<Xs?`${String(Math.floor(t/Ys))}m ago`:t<Zs?`${String(Math.floor(t/Xs))}h ago`:`${String(Math.floor(t/Zs))}d ago`}var ec=[`notificationRules`,`getRuleLastRuns`],tc=3e4;function nc(){let e=p(),t=i({queryKey:ec,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:tc});return{status:t.status,data:t.data,error:t.error}}var rc={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function ic({cell:e}){switch(e.kind){case`pending`:return u(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":`Last run loading`,className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return u(`span`,{"data-testid":`rule-last-run-failed`,title:`Last run could not be read: ${e.reason}`,className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.phrase});case`ran`:return n(`span`,{className:`flex items-center gap-1.5`,title:new Date(e.lastAt).toLocaleString(),children:[u(`span`,{"data-testid":`rule-last-run-dot`,title:e.status,className:`inline-block h-2 w-2 rounded-full ${rc[e.status]}`}),u(`span`,{className:`text-[11px] text-foreground-subtle`,children:$s(e.lastAt)})]})}}function ac({rule:e,onOpenHistory:t}){return u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t(e),title:`History — this rule's deliveries`,"aria-label":`history of ${e.name}`,children:u(Me,{className:`h-3.5 w-3.5`})})}t();var oc=[`notificationRules`,`listSnoozes`],sc=[10,30,60,120];function cc({ruleId:e,ruleName:t,exempt:r=!1,variant:i=`icon`}){let a=p(),s=o(),[d,f]=c(30),[m,h]=c(null),g=l({mutationFn:t=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>s.invalidateQueries({queryKey:oc}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?i===`icon`?null:u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`}):i===`icon`?u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:`Silence this rule for ${Wt(30)} — it appears under "Silenced right now"`,"aria-label":`snooze ${t}`,"data-testid":`nc-rule-snooze-now`,children:g.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(ue,{className:`h-3.5 w-3.5`})}):n(`div`,{className:`space-y-1`,children:[n(`div`,{className:`flex items-end gap-2`,children:[u(`div`,{className:`w-32`,children:u(T,{value:String(d),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&f(t)},options:sc.map(e=>({value:String(e),label:Wt(e)}))})}),n(A,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(d),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(ue,{className:`h-3.5 w-3.5`}),`Silence this rule now`]})]}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`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&&u(`p`,{className:`text-[10px] text-danger`,children:m})]})}t();function lc(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function uc(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 dc(e,t){let[,n]=c(0);d(()=>{let r=uc(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 fc(){let e=p();return i({queryKey:oc,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function pc({rule:e,snoozes:t,exempt:r}){let{t:i}=Dt(),a=p(),s=o();dc(t,e.id);let c=lc(t,e.id,Date.now()),d=()=>s.invalidateQueries({queryKey:oc}),f=l({mutationFn:()=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e.id,durationMinutes:30}}),onSuccess:d}),m=l({mutationFn:async e=>{for(let t of e)await a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:d});if(r)return null;let h=f.isError||m.isError;return n(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[u(G,{checked:c.length>0,disabled:!e.enabled||f.isPending||m.isPending,onCheckedChange:e=>e?f.mutate():m.mutate(c),"aria-label":i(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,e.name),title:i(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),h&&u(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:i(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var mc=`pipeline-analytics`,hc=`nc.getRuleStatus`,gc=`nc.testRule`;function _c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function vc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function yc(e){if(!_c(e))return;let t=vc(e,`id`),n=vc(e,`downloadPath`),r=Y(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:vc(e,`mediaType`)??`video`,sizeBytes:Y(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function bc(e){if(!_c(e))return;let t=Y(e,`startMs`),n=Y(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function xc(e){if(!_c(e))return null;let t=Y(e,`deviceId`);if(t===void 0)return null;let n=Y(e,`lastGeneratedAt`),r=yc(e.lastArtifact),i=e.rendering,a=_c(i)?{startedAt:Y(i,`startedAt`)??0,windowStartMs:Y(i,`windowStartMs`)??0,windowEndMs:Y(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function Sc(e){if(!_c(e))return null;let t=Y(e,`deviceId`),n=vc(e,`windowKey`),r=Y(e,`openedAt`),i=Y(e,`closesAt`),a=Y(e,`members`),o=Y(e,`pending`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0?null:{deviceId:t,windowKey:n,openedAt:r,closesAt:i,members:a,pending:o}}function Cc(e){if(!_c(e))return null;let t=vc(e,`kind`);if(t===`none`)return{kind:`none`,reason:vc(e,`reason`)??``};if(t===`occupancy`){let t=Y(e,`deviceId`),n=Y(e,`threshold`),r=Y(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=vc(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=Y(e,`count`),s=Y(e,`observedAt`),c=Y(e,`since`),l=vc(e,`scope`),u=vc(e,`className`),d=vc(e,`warning`);return{kind:`occupancy`,deviceId:t,threshold:n,sustainSeconds:r,...l===void 0?{}:{scope:l},...u===void 0?{}:{className:u},...o===void 0?{}:{count:o},...typeof e.occupied==`boolean`?{occupied:e.occupied}:{},...s===void 0?{}:{observedAt:s},...c===void 0?{}:{since:c},...a===void 0?{}:{unavailable:a},...d===void 0?{}:{warning:d}}}if(t===`grouped`){let t=Y(e,`groupingSec`);if(t===void 0)return null;if(e.openWindows===null){let n=vc(e,`reason`);return{kind:`grouped`,groupingSec:t,openWindows:null,...n===void 0?{}:{reason:n}}}if(!Array.isArray(e.openWindows))return null;let n=[];for(let t of e.openWindows){let e=Sc(t);if(e===null)return null;n.push(e)}return{kind:`grouped`,groupingSec:t,openWindows:n}}if(t===`timelapse`){let t=Array.isArray(e.devices)?e.devices:[],n=[];for(let e of t){let t=xc(e);t!==null&&n.push(t)}let r=bc(e.lastWindow),i=e.nextWindow,a=_c(i)?{startMs:Y(i,`startMs`)??0,endMs:Y(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:Y(e,`settleMs`)??0}}return null}function wc(e){let t=Math.max(0,Math.floor(e/6e4));if(t<1)return`less than a minute`;if(t<60)return`${String(t)} min`;let n=Math.floor(t/60),r=t%60;if(n<24)return r===0?`${String(n)} h`:`${String(n)} h ${String(r)} min`;let i=Math.floor(n/24),a=n%24;return a===0?`${String(i)} d`:`${String(i)} d ${String(a)} h`}function Tc(e){if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${t.toFixed(0)} kB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}function Ec(e,t){let n=e.scope??`the whole frame`,r=e.className??`objects`;if(e.unavailable!==void 0){let t=e.unavailable===`no-snapshot`?`no live count for this camera yet — the condition fails closed until one arrives`:`“${n}” is not in this camera’s current snapshot — the condition fails closed (deleted zone?)`;return e.warning===void 0?t:`${e.warning} · ${t}`}let i=[`Now: ${String(e.count??0)}/${String(e.threshold)} ${r} in ${n}`,e.occupied===!0?`condition TRUE`:`condition false`];e.since!==void 0&&i.push(`for ${wc(Math.max(0,t-e.since))}`),i.push(`holds ${String(e.sustainSeconds)} s before firing`);let a=i.join(` · `);return e.warning===void 0?a:`${e.warning} · ${a}`}function Dc(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${wc(Math.max(0,n-e.rendering.startedAt))} — the window ${new Date(e.rendering.windowStartMs).toLocaleString()} → ${new Date(e.rendering.windowEndMs).toLocaleString()}`;if(e.lastGeneratedAt===void 0)return`${t}: never produced a video yet`;let r=new Date(e.lastGeneratedAt).toLocaleString(),i=e.lastArtifact;return i===void 0?`${t}: last produced ${r} — the video is no longer on the shelf`:`${t}: last produced ${r} · ${Tc(i.sizeBytes)}`}function Oc(e){return{windows:e.length,waiting:e.reduce((e,t)=>e+t.pending,0)}}var kc=`nc.listPrunes`;function Ac(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var jc=new Set([`rule`,`timelapse`,`summary`]),Mc=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function Nc(e){return typeof e==`string`&&jc.has(e)}function Pc(e){return typeof e==`string`&&Mc.has(e)}function Fc(e){return e===`device`||e===`target`}function Ic(e){if(!Ac(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!Nc(t)||!Fc(r)||!Pc(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 Lc(e){return!Ac(e)||!Array.isArray(e.prunes)?null:e.prunes.map(Ic).filter(e=>e!==null)}function Rc(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 zc(e,t){let n=t(e.at);return e.subjectKind===`device`?`Disabled on ${n}: its last device (#${e.subject}) was deleted.`:`Disabled on ${n}: its last delivery target (${e.subject}) was deleted.`}function Bc(e){return new Date(e).toLocaleDateString()}function Vc({kind:e,ruleId:t,enabled:r,updatedAt:a}){let o=p(),s=i({queryKey:[`pipelineAnalytics`,kc],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>Lc(await o.trpcClient.addons.custom.mutate({addonId:mc,action:kc,input:{}}))}).data;if(s==null)return null;let c=Rc(s,e,t,r,a);return c===null?null:n(`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:[u(R,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`span`,{children:zc(c,Bc)})]})}var Hc=5e3;function Uc({status:e,now:t,name:r}){let{t:i}=Dt();if(e.openWindows===null)return n(`p`,{className:`flex items-start gap-1.5`,children:[u(V,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),u(`span`,{"data-testid":`nc-grouped-status-headline`,children:i(`notificationRules.status.grouped.unknown`,{reason:e.reason??``,defaultValue:`Open windows unknown — {{reason}}`})})]});let o=e.openWindows,{windows:s,waiting:c}=Oc(o);return n(a,{children:[n(`p`,{className:`flex items-start gap-1.5`,children:[u(V,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),u(`span`,{"data-testid":`nc-grouped-status-headline`,children:s===0?i(`notificationRules.status.grouped.none`,`No window open`):`${i(`notificationRules.status.grouped.windows`,{count:s,defaultValue_one:`{{count}} open window`,defaultValue_other:`{{count}} open windows`})} · ${i(`notificationRules.status.grouped.waiting`,{count:c,defaultValue:`{{count}} waiting`})}`})]}),o.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[u(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),u(`span`,{children:i(`notificationRules.status.grouped.windowLine`,{camera:r(e.deviceId),members:e.members,pending:e.pending,seconds:Math.max(0,Math.ceil((e.closesAt-t)/1e3)),defaultValue:`{{camera}} · {{members}} in the window · {{pending}} waiting · closes within {{seconds}} s`})})]},e.windowKey))]})}function Wc({ruleId:e,cameraName:t}){let r=p(),o=i({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:Hc,queryFn:async()=>Cc(await r.trpcClient.addons.custom.mutate({addonId:mc,action:hc,input:{ruleId:e}}))}).data;if(o==null||o.kind===`none`)return null;let s=Date.now(),c=e=>t?.(e)??`camera ${String(e)}`;return n(`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`&&n(`p`,{className:`flex items-start gap-1.5`,children:[o.unavailable!==void 0||o.warning!==void 0?u(je,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):u(V,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),n(`span`,{children:[u(`span`,{className:`text-foreground`,children:c(o.deviceId)}),` —`,` `,Ec(o,s)]})]}),o.kind===`grouped`&&u(Uc,{status:o,now:s,name:c}),o.kind===`timelapse`&&n(a,{children:[o.devices.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[u(V,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),n(`span`,{children:[Dc(e,c(e.deviceId),s),e.lastArtifact!==void 0&&n(a,{children:[` · `,u(`a`,{className:`text-primary hover:underline`,href:`/${e.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:`open`})]})]})]},e.deviceId)),n(`p`,{className:`flex items-start gap-1.5`,children:[u(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),n(`span`,{children:[o.nextWindow===void 0?`No further window opens in the next nine days`:`Next window opens ${new Date(o.nextWindow.startMs).toLocaleString()}`,o.settleMs>0&&` · rendered ${String(Math.round(o.settleMs/6e4))} min after it closes, so the footage has settled`]})]})]})]})}function Gc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function qc(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Jc(e){if(!Gc(e))return null;let t=Kc(e,`ruleId`),n=Kc(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=Kc(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:Kc(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:qc(e,`targetIds`)}}function Yc(e){if(!Gc(e))return null;let t=Kc(e,`conditionId`),n=Kc(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Xc(e){if(!Gc(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(!Gc(t))continue;let e=Kc(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(!Gc(t))continue;let e=Kc(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 Zc(e){if(!Gc(e))return null;let t=Kc(e,`recordId`),n=Kc(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=Jc(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Yc(t);e!==null&&i.push(e)}let a=Kc(e,`droppedBy`),o=Xc(e.stateSummary);return{recordId:t,delivery:n,trigger:Kc(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:Kc(e,`still`)??`none`,notes:qc(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function Qc(e){if(e.stateSummary!==void 0)return $c(e,e.stateSummary);if(e.droppedBy!==void 0)return`Nothing was evaluated (${e.droppedBy}) — the event was dropped before any rule was consulted.`;let t=e.outcomes[0];if(t===void 0)return`This rule was not a candidate for a ${e.trigger} event — check its trigger, and that it is enabled.`;if(!t.matched)return t.failedCondition===void 0?`The rule did not match the event built from its own conditions.`:`The rule did not match — the “${t.failedCondition}” condition refused the event.`;if(t.enqueued===0)return`The rule matched, but no notification was queued: every target is opted out of it, or it addresses none.`;let n=e.still===`live`?` with a live snapshot`:e.still===`unavailable`?` (the camera returned no snapshot, so it ships text-only)`:e.still===`unattachable`?` (this kind of rule carries no picture in production either)`:``;return`Matched — ${String(t.enqueued)} notification${t.enqueued===1?``:`s`} queued to ${String(t.targetIds.length)} target${t.targetIds.length===1?``:`s`}${n}. It is marked [TEST] in the body.`}function $c(e,t){if(t.nothingToReport)return`Nothing to report right now (${t.sections.map(e=>`${e.id}: ${e.status===`unavailable`?`unavailable`:`none open`}`).join(`, `)}) — nothing was sent, exactly as the scheduled summary would send nothing.`;let n=t.rows.reduce((e,t)=>e+t.enqueued,0),r=e.outcomes[0]?.targetIds.length??0;if(n===0)return`The summary was built, but no notification was queued: the rule reaches no target (its users are not admins, or every target is opted out).`;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`?` (one per category: ${i.join(`, `)})`:``;return`Summary built now — ${String(n)} notification${n===1?``:`s`} queued${a} to ${String(r)} target${r===1?``:`s`}. ${n===1?`It is`:`They are`} marked [TEST] in the body.`}t();function el({ruleId:e,ruleName:t,fallbackDeviceId:r,variant:i=`icon`,showResult:o=!1}){let s=p(),[d,f]=c(null),[m,h]=c(null),g=l({mutationFn:async()=>Zc(await s.trpcClient.addons.custom.mutate({addonId:mc,action:gc,input:{ruleId:e,...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{f(null),h(null)},onSuccess:e=>f(e),onError:e=>h(e instanceof Error?e.message:`The test could not be run.`)}),_=d===null?m===null?void 0:m:Qc(d);return n(a,{children:[n(A,{size:`sm`,variant:i===`icon`?`ghost`:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(),title:_??`Test now — fires this rule and really sends the notification`,"aria-label":`test ${t} now`,"data-testid":`nc-rule-test-now`,children:[g.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Ne,{className:`h-3.5 w-3.5`}),i===`full`&&`Test now`]}),o&&m!==null&&u(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:m}),o&&d!==null&&n(`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:[u(`p`,{className:`text-foreground`,children:Qc(d)}),d.planNotes.map(e=>n(`p`,{className:`flex gap-1.5`,children:[u(je,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId)),d.notes.map(e=>n(`p`,{children:[`· `,e]},e))]})]})}t();var tl=[`notificationRules`,`listSnoozes`],nl=3e4;function rl(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function il(e){if(e===0)return`ending`;if(e<60)return`${e}m left`;let t=Math.floor(e/60),n=e%60;return n===0?`${t}h left`:`${t}h ${n}m left`}function al({rules:e}){let t=p(),a=o(),s=i({queryKey:tl,refetchInterval:nl,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),c=l({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>a.invalidateQueries({queryKey:tl})}),d=r(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),f=Date.now(),m=(s.data??[]).filter(e=>f>=e.startedAt&&f<e.expiresAt);return n(x,{className:`p-4`,children:[n(`div`,{className:`flex items-center gap-2 mb-3`,children:[u(ue,{className:`h-4 w-4 text-foreground-subtle`}),u(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),m.length===0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`}),u(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:m.map(e=>n(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[n(`div`,{className:`min-w-0`,children:[n(`div`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:d.get(e.ruleId??``)??`A rule`}),e.global&&u(q,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&u(q,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&u(q,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,il(rl(e,f))]})]}),u(A,{size:`sm`,variant:`outline`,disabled:c.isPending,onClick:()=>c.mutate(e.id),children:`End now`})]},e.id))})]})}var X=`block text-[11px] font-medium text-foreground mb-1`,ol=`mt-1 text-[10px] text-foreground-subtle`;function Z({title:e,hint:t,children:r}){return n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),u(`div`,{className:`space-y-3`,children:r})]})}function sl({problems:e,testId:t=`digest-problems`}){return e.length===0?null:n(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":t,children:[n(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[u(je,{className:`h-3.5 w-3.5`}),`This rule could never produce anything, so it cannot be saved:`]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function cl({warnings:e,testId:t=`digest-warnings`}){return e.length===0?null:n(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":t,children:[n(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[u(R,{className:`h-3.5 w-3.5`}),`Worth knowing:`]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function ll({cameras:e,value:t,onChange:r,fleet:i,hint:a}){return n(`div`,{className:`space-y-1`,children:[u(W,{devices:e,listState:i.state,fleet:i,value:t,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),a!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function ul(e){return u(ne,{...e,testIdPrefix:e.testIdPrefix??`digest-target`,emptyMessage:e.emptyMessage??`No delivery target is configured. Add one on the Targets tab first — without one the artefact is rendered and thrown away.`})}function Q({label:e,value:t,onChange:r,min:i,max:a,step:o,hint:s,emptyPlaceholder:c,testId:l,disabled:d=!1}){return n(`div`,{children:[u(`label`,{className:X,children:e}),u(O,{type:`number`,value:t===void 0?``:String(t),disabled:d,...i===void 0?{}:{min:i},...a===void 0?{}:{max:a},...o===void 0?{}:{step:o},...c===void 0?{}:{placeholder:c},...l===void 0?{}:{"data-testid":l},onChange:e=>{let t=e.target.value.trim();if(t.length===0){r(void 0);return}let n=Number(t);Number.isFinite(n)&&r(n)}}),s!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function dl({label:e,checked:t,onChange:r,hint:i,testId:a}){return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:t,onCheckedChange:r,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),i!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:i})]})}function fl({title:e,body:t,onTitleChange:r,onBodyChange:i,family:a,testIdPrefix:o}){let s=ho(),c=e=>s.data?uo(s.data,{family:a,field:e}):void 0;return n(`div`,{className:`space-y-2`,children:[u(bo,{label:`Notification title`,value:e,onChange:r,vars:c(`title`),testId:`${o}-title`}),u(bo,{label:`Notification body`,value:t,onChange:i,vars:c(`body`),multiline:!0,testId:`${o}-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank to use the hub's own wording (editable on the Texts tab).`}),u(xo,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function pl({open:e,ruleName:t,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){return e?u(Ae,{open:!0,onOpenChange:e=>!e&&s(),children:u(S,{width:`sm`,children:n(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[n(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[u(Ne,{className:`h-4 w-4 text-warning`}),`Send a real notification now?`]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[`"`,t,`" will be produced over `,r,` and DELIVERED to`,` `,i,` — on every phone that target reaches, right now. This is not a dry run.`]}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`It does not consume the schedule: the next scheduled run still happens.`}),c,n(`div`,{className:`flex justify-end gap-2`,children:[u(A,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),u(A,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?`Sending…`:`Produce and send`})]})]})})}):null}function ml(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 hl=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function gl(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function _l(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>hl[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${gl(t.startMinute)}–${gl(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function vl(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${ml(Math.round(r/1e3))} ago`}function yl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bl(e){return Array.isArray(e)?`[${e.map(bl).join(`,`)}]`:yl(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${bl(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function xl(e,t){return bl(e)===bl(t)}function Sl(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,Cl=`nc.getTexts`,wl=`nc.setLanguage`,Tl=`nc.setTextOverrides`,El={en:`English`,it:`Italiano`};function Dl(e){return e===`en`||e===`it`}function Ol(e){return e===`override`||e===`shipped`||e===`fallback`}function kl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Al(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 jl(e){if(!kl(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`||!Dl(r)||!Ol(o)||i!==null&&typeof i!=`string`)return null;let s=Al(e.placeholders),c=Al(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 Ml(e){if(!kl(e))return null;let{language:t,activeLanguage:n}=e;if(!Dl(t)||!Dl(n))return null;let r=Al(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Dl(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=jl(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Nl(e,t){return t.get(e.key)??e.override??e.shipped}function Pl(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 Fl(e,t){return Object.keys(Pl(e,t)).length}function Il(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 Ll(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Rl(e){return e.pluralCategories.length===0?null:`This text has one form per count (${e.pluralCategories.join(`, `)}). An override replaces all of them with a single sentence.`}var zl=[`notificationCalendarEvents`,`list`],Bl=`nc.listCalendarEventsRules`,Vl=`nc.upsertCalendarEventsRule`,Hl=`nc.deleteCalendarEventsRule`,Ul=Ct({timezone:St().min(1),windows:Tt(Ct({days:Tt(bt().int().min(0).max(6)).min(1),startMinute:bt().int().min(0).max(1439),endMinute:bt().int().min(0).max(1439)})).min(1),invert:Et().optional()}),Wl=Ct({targetId:St().min(1),params:wt(St(),xt()).optional()}),Gl=Ct({rules:Tt(Ct({id:St().min(1),name:St().min(1),enabled:Et(),schedule:Ul,calendars:Tt(St().min(1)).max(64).optional(),calendarsExclude:Tt(St().min(1)).max(64).optional(),horizonDays:bt().int(),deliverEmpty:Et(),targets:Tt(Wl).min(1),template:Ct({title:St().optional(),body:St().optional()}).optional(),priority:bt().int(),generatedAt:bt().optional(),readOnly:Et().optional()}))});function Kl(e){let t=Gl.safeParse(e);return t.success?t.data.rules:null}function ql(e){return e.readOnly!==!0}var Jl=[{key:`basics`,label:`Basics`},{key:`schedule`,label:`Schedule`},{key:`calendars`,label:`Calendars`},{key:`targets`,label:`Targets`},{key:`template`,label:`Template`}],Yl=`basics`;function Xl(){return Ke([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function Zl(e){let t=Ve(e);if(t===null||t.length===0)return _l(e);let n=t[0];return n===void 0?_l(e):`At ${String(Math.floor(n.minute/60)).padStart(2,`0`)}:${String(n.minute%60).padStart(2,`0`)}${t.length>1?` +${t.length-1}`:``}`}function Ql(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:Xl(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``}}function $l(e){return{name:e.name,enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,calendars:e.calendars??[],calendarsExclude:e.calendarsExclude??[],targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``}}function eu(e){return e.name.trim().length>0&&e.targetIds.length>0&&e.horizonDays>=1&&e.horizonDays<=30&&e.schedule.windows.length>0}function tu(e){let t=e.targetIds.map(e=>({targetId:e}));return{name:e.name.trim(),enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,...e.calendars.length>0?{calendars:[...e.calendars]}:{},...e.calendarsExclude.length>0&&e.calendars.length===0?{calendarsExclude:[...e.calendarsExclude]}:{},targets:t,...e.templateTitle.trim().length>0||e.templateBody.trim().length>0?{template:{...e.templateTitle.trim().length>0?{title:e.templateTitle.trim()}:{},...e.templateBody.trim().length>0?{body:e.templateBody.trim()}:{}}}:{}}}function nu(e,t){let n=tu(e);return{...n,calendars:e.calendars.length===0&&(t.calendars?.length??0)>0?null:n.calendars,calendarsExclude:e.calendarsExclude.length===0&&(t.calendarsExclude?.length??0)>0?null:n.calendarsExclude,template:e.templateTitle.trim().length===0&&e.templateBody.trim().length===0&&t.template!==void 0?null:n.template}}function ru(e){return`next ${String(e)} day(s)`}function iu(e){return e.calendars!==void 0&&e.calendars.length>0?`${String(e.calendars.length)} calendar${e.calendars.length===1?``:`s`}`:e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?`all except ${String(e.calendarsExclude.length)}`:`all calendars`}t();function au({rule:e,targets:t,onSaved:r,onCancel:i}){let a=p(),o=oe(),[s,d]=c(()=>e===null?Ql():$l(e)),[f,m]=c(()=>Tr(e===null?void 0:e.calendars,e===null?void 0:e.calendarsExclude)),[h,g]=c(Yl),[_,v]=c(null),y=e=>d(t=>({...t,...e})),b=l({mutationFn:async()=>{let t=Wn(f),n={...s,calendars:t.include??[],calendarsExclude:t.exclude??[]};if(!eu(n))throw Error(`Name, at least one target, and a schedule are required`);let r=e===null?{rule:tu(n)}:{ruleId:e.id,patch:nu(n,e)};await a.trpcClient.addons.custom.mutate({addonId:$,action:Vl,input:r})},onSuccess:()=>r(),onError:e=>{v(e instanceof Error?e.message:String(e))}}),x=(o.data??[]).map(e=>({id:e.id,name:e.name}));return u(Ae,{open:!0,onOpenChange:e=>!e&&i(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendar-events-editor`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between gap-2`,children:[n(`div`,{className:`flex min-w-0 items-center gap-2`,children:[u(me,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:e===null?`New calendar events`:s.name})]}),n(`div`,{className:`flex shrink-0 items-center gap-2`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`}),u(A,{size:`sm`,type:`button`,disabled:b.isPending,onClick:()=>{v(null),b.mutateAsync()},"data-testid":`calendar-events-save`,children:b.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):`Save`})]})]}),n(D,{value:h,onValueChange:e=>{let t=Jl.find(t=>t.key===e);t!==void 0&&g(t.key)},children:[u(Ce,{className:`mb-3`,children:Jl.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(z,{className:`space-y-4 pr-1`,children:[_===null?null:u(`p`,{className:`text-sm text-destructive`,children:_}),u(M,{value:`basics`,className:`space-y-3`,children:n(Z,{title:`Basics`,children:[n(`label`,{className:`block text-sm`,children:[`Name`,u(O,{className:`mt-1`,value:s.name,onChange:e=>y({name:e.target.value}),"data-testid":`calendar-events-name`})]}),u(Q,{label:`Horizon (days)`,value:s.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&y({horizonDays:e})}}),u(Q,{label:`Priority`,value:s.priority,min:1,max:5,onChange:e=>{e!==void 0&&y({priority:e})}}),u(dl,{label:`Enabled`,checked:s.enabled,onChange:e=>y({enabled:e})}),u(dl,{label:`Deliver when empty`,checked:s.deliverEmpty,onChange:e=>y({deliverEmpty:e})})]})}),u(M,{value:`schedule`,className:`space-y-3`,children:n(Z,{title:`Schedule`,children:[u(kr,{mode:`times`,value:s.schedule,onChange:e=>y({schedule:e})}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`One send time per row. The digest fires at that minute.`})]})}),u(M,{value:`calendars`,className:`space-y-3`,children:u(Z,{title:`Calendars`,children:u(Xo,{draft:f,onChange:m,exceptOffered:!0,plural:`calendars`,describe:e=>x.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>u(W,{devices:x,listState:o.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),u(M,{value:`targets`,className:`space-y-3`,children:u(Z,{title:`Targets`,children:u(ul,{targets:t,value:s.targetIds,onChange:e=>y({targetIds:e})})})}),u(M,{value:`template`,className:`space-y-3`,children:n(Z,{title:`Template`,children:[n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Optional. Leave blank for the default digest body (tomorrow highlighted, then later days). Variables: `,`{{rule}}`,`, `,`{{count}}`,`, `,`{{horizonDays}}`,`,`,` `,`{{events}}`,`.`]}),n(`label`,{className:`block text-sm`,children:[`Title`,u(O,{className:`mt-1`,value:s.templateTitle,onChange:e=>y({templateTitle:e.target.value})})]}),n(`label`,{className:`block text-sm`,children:[`Body`,u(`textarea`,{className:`mt-1 min-h-[8rem] w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:s.templateBody,onChange:e=>y({templateBody:e.target.value})})]})]})})]})]})]})})}var ou=`nc.listSummaryRules`,su=`nc.upsertSummaryRule`,cu=`nc.deleteSummaryRule`,lu=`nc.testSummaryRule`,uu=3600,du=86400,fu=3600,pu=3600,mu=3*36e5,hu=[`importance`,`recency`,`dwell`],gu={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},_u=[`none`,`tiles`,`all`],vu=`none`,yu={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},bu=[`en`,`it`],xu=[`deliver-without-text`,`skip`],Su=2048,Cu=2e3;function wu(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Tu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Eu(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 Du(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`string`)return null;t.push(n)}return t}function Ou(e){if(e!==void 0)return typeof e==`string`?e:null}function ku(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function Au(e){return hu.some(t=>t===e)}function ju(e){return e===void 0?vu:_u.find(t=>t===e)??null}function Mu(e){if(!Tu(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Tu(n))return null;let e=Eu(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=Ou(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 Nu(e){if(!Tu(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=Mu(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 Pu(e){if(e==null)return;if(!Tu(e))return null;let t=e.classes===void 0?void 0:Du(e.classes),n=e.classesExclude===void 0?void 0:Du(e.classesExclude),r=e.zones===void 0?void 0:Du(e.zones);if(t===null||n===null||r===null)return null;let i=ku(e.minImportance),a=ku(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 Fu(e){if(e==null)return;if(!Tu(e))return null;let t=Ou(e.title),n=Ou(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function Iu(e){return bu.some(t=>t===e)}function Lu(e){return xu.some(t=>t===e)}function Ru(e){if(e==null)return;if(!Tu(e)||typeof e.enabled!=`boolean`)return null;let t=Ou(e.profileId),n=Ou(e.prompt);if(t===null||n===null)return null;let r=ku(e.maxImagePx),i=ku(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!Iu(a))return null;let o=e.onFailure;return o!==void 0&&!Lu(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 zu(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Tu(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Tu(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function Bu(e){if(!Tu(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`||!Au(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Eu(e.deviceIds),u=Nu(e.window),d=zu(e.targets);if(l===null||u===null||d===null)return null;let f=Pu(e.filters),p=Fu(e.template);if(f===null||p===null)return null;let m=Ou(e.captionText),h=ku(e.generatedAt),g=ku(e.updatedAt);if(m===null||h===null||g===null)return null;let _=ju(e.captions);if(_===null)return null;let v=Ru(e.ai);return v===null?null:{id:t,name:n,enabled:r,deviceIds:l,window:u,...f===void 0?{}:{filters:f},maxTiles:i,maxAiImages:a,rank:o,barrierSeconds:s,targets:d,...p===void 0?{}:{template:p},captions:_,...m===void 0?{}:{captionText:m},deliverEmpty:c,priority:e.priority,...h===void 0?{}:{generatedAt:h},...g===void 0?{}:{updatedAt:g},readOnly:e.readOnly===!0,...v===void 0?{}:{ai:v}}}function Vu(e){if(!Tu(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=Bu(n);if(e===null)return null;t.push(e)}return t}function Hu(e){if(!Tu(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=ku(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=ku(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Ou(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 Uu(){return{name:``,enabled:!0,deviceIds:[],windowKind:`motion`,schedule:void 0,quietSeconds:60,maxWindowSeconds:300,classes:[],classesExclude:[],zones:[],minImportance:void 0,minDwellSeconds:void 0,includeStationary:!1,maxTiles:12,maxAiImages:6,rank:`importance`,barrierSeconds:120,targetIds:[],templateTitle:``,templateBody:``,mosaicCaptions:vu,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function Wu(e){let t=Uu(),n=e.window.kind===`motion`?e.window:null;return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],windowKind:e.window.kind,schedule:e.window.kind===`schedule`?e.window.schedule:void 0,quietSeconds:n?.quietSeconds??t.quietSeconds,maxWindowSeconds:n?.maxWindowSeconds??t.maxWindowSeconds,classes:[...e.filters?.classes??[]],classesExclude:[...e.filters?.classesExclude??[]],zones:[...e.filters?.zones??[]],minImportance:e.filters?.minImportance,minDwellSeconds:e.filters?.minDwellSeconds,includeStationary:e.filters?.includeStationary===!0,maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,mosaicCaptions:e.captions,captionText:e.captionText??``,deliverEmpty:e.deliverEmpty,priority:e.priority,aiEnabled:e.ai?.enabled??t.aiEnabled,aiProfileId:e.ai?.profileId??``,aiPrompt:e.ai?.prompt??``,aiLanguage:e.ai?.language??``,aiMaxImagePx:e.ai?.maxImagePx,aiTimeoutSeconds:e.ai?.timeoutMs===void 0?void 0:Math.round(e.ai.timeoutMs/1e3),aiOnFailure:e.ai?.onFailure??t.aiOnFailure}}function Gu(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Ku(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 qu(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 Ju(e){return Sl(e.targetIds)}function Yu(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 Xu(e){let t=Ku(e),n=qu(e),r=Yu(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:Gu(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Ju(e),...n===void 0?{}:{template:n},captions:e.mosaicCaptions,...i.length>0?{captionText:i}:{},deliverEmpty:e.deliverEmpty,priority:e.priority,...r===void 0?{}:{ai:r}}}function Zu(e,t){let n=Xu(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),xl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),xl(n.window,t.window)||(r.window=n.window),xl(n.filters,t.filters)||(r.filters=n.filters??null),n.maxTiles!==t.maxTiles&&(r.maxTiles=n.maxTiles),n.maxAiImages!==t.maxAiImages&&(r.maxAiImages=n.maxAiImages),n.rank!==t.rank&&(r.rank=n.rank),n.barrierSeconds!==t.barrierSeconds&&(r.barrierSeconds=n.barrierSeconds),xl(n.targets,t.targets)||(r.targets=n.targets),xl(n.template,t.template)||(r.template=n.template??null),n.captions!==t.captions&&(r.captions=n.captions),(n.captionText??``)!==(t.captionText??``)&&(r.captionText=n.captionText??``),n.deliverEmpty!==t.deliverEmpty&&(r.deliverEmpty=n.deliverEmpty),n.priority!==t.priority&&(r.priority=n.priority),xl(n.ai,t.ai)||(r.ai=n.ai??null),r}function Qu(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 ${uu}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${du}s.`)),(e.maxTiles<1||e.maxTiles>24)&&t.push(`The mosaic holds between 1 and 24 tiles.`),e.maxAiImages>e.maxTiles&&t.push(`AI images (${e.maxAiImages}) cannot exceed tiles (${e.maxTiles}) — the model cannot judge frames the mosaic does not contain.`),(e.barrierSeconds<0||e.barrierSeconds>3600)&&t.push(`The track-close wait is between 0s and ${fu}s.`),e.minImportance!==void 0&&(e.minImportance<0||e.minImportance>1)&&t.push(`Minimum importance is a score between 0 and 1.`),e.minDwellSeconds!==void 0&&(e.minDwellSeconds<0||e.minDwellSeconds>3600)&&t.push(`Minimum stay is between 0s and ${pu}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 ${Cu} 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 ${Su} 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 $u(e){return Qu(e).length===0}function ed(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 td=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,label:`Window`,fields:[`windowKind`,`schedule`,`quietSeconds`,`maxWindowSeconds`,`barrierSeconds`]},{key:`content`,label:`What goes in`,fields:[`classes`,`classesExclude`,`zones`,`minImportance`,`minDwellSeconds`,`includeStationary`]},{key:`mosaic`,label:`Mosaic`,fields:[`maxTiles`,`rank`,`mosaicCaptions`,`captionText`]},{key:`ai`,label:`AI`,fields:[`aiEnabled`,`aiProfileId`,`aiPrompt`,`aiLanguage`,`aiMaxImagePx`,`aiTimeoutSeconds`,`aiOnFailure`,`maxAiImages`]},{key:`delivery`,label:`Delivery`,fields:[`targetIds`,`priority`,`deliverEmpty`,`templateTitle`,`templateBody`]}],nd=`rule`;function rd(e){return td.find(t=>t.key===e)?.key}function id(e){return e.kind===`motion`?`Motion · ${ml(e.quietSeconds)} quiet · max ${ml(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${_l(e.schedule)}`}function ad(e,t){return vl(e,t,`Never run`)}function od(e){if(e===void 0)return`All passages`;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(`not ${e.classesExclude.join(`, `)}`),e.zones!==void 0&&e.zones.length>0&&t.push(`${e.zones.length} zone${e.zones.length===1?``:`s`}`),e.minImportance!==void 0&&t.push(`importance ≥ ${e.minImportance}`),e.minDwellSeconds!==void 0&&t.push(`stay ≥ ${ml(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function sd(e){return{windowStartMs:e-mu,windowEndMs:e}}t();var cd={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},ld={en:`English`,it:`Italiano`};function ud(e){return hu.find(t=>t===e)}function dd(e){return _u.find(t=>t===e)}function fd(e){return bu.find(t=>t===e)??``}function pd(e){return xu.find(t=>t===e)}function md({rule:e,cameras:t,fleet:a,targets:o,taxonomy:s,onSaved:d,onCancel:f}){let m=p(),[h,g]=c(()=>e===null?Uu():Wu(e)),[_,v]=c(null),[y,b]=c(nd),x=e=>g(t=>({...t,...e})),C=r(()=>{let e=nt(`occupancy`,s);return e===null?[]:e.groups.flatMap(e=>e.options)},[s]),{options:w,loading:E}=Ar(h.deviceIds,t.map(e=>({id:e.id,name:e.name}))),k=i({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>m.trpcClient.llm.listProfiles.query({}),retry:!1}),j=(k.data??[]).filter(e=>e.supportsVision),N=l({mutationFn:async()=>{let t=e===null?{rule:Xu(h)}:{ruleId:e.id,patch:Zu(h,e)};await m.trpcClient.addons.custom.mutate({addonId:$,action:su,input:t})},onSuccess:d,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),P=ho(),F=P.data?uo(P.data,{family:`summary`,field:`captionText`}):void 0,I=h.mosaicCaptions===`all`,L=Qu(h),R=ed(h),te=$u(h)&&!N.isPending,B=td.some(e=>e.key===y)?y:nd;return u(Ae,{open:!0,onOpenChange:e=>!e&&f(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[u(Qr,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?`New summary`:`Edit ${e.name}`})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:f,children:`Cancel`})]}),_!==null&&u(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&u(Vc,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),u(sl,{problems:L,testId:`summary-problems`}),u(cl,{warnings:R,testId:`summary-warnings`})]}),n(D,{value:B,onValueChange:e=>b(rd(e)??y),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(Ce,{className:`mb-3 shrink-0`,children:td.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(z,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-3`,children:[u(Z,{title:`What it is`,hint:`One window, one picture: the best shot of every track the window held, laid out as one mosaic and delivered once.`,children:n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:X,children:`Name`}),u(O,{value:h.name,onChange:e=>x({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),u(`div`,{className:`pb-1.5`,children:u(dl,{label:`Enabled`,checked:h.enabled,onChange:e=>x({enabled:e}),testId:`summary-enabled`})})]})}),u(Z,{title:`Cameras`,hint:`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:u(ll,{cameras:t,value:h.deviceIds,fleet:a,onChange:e=>x({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})})]}),u(M,{value:`window`,className:`space-y-3`,children:n(Z,{title:`When the window closes`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Window`}),u(T,{value:h.windowKind,options:[{value:`motion`,label:`Motion — opened and closed by activity`},{value:`schedule`,label:`Schedule — fixed weekly windows`}],onChange:e=>x({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),h.windowKind===`motion`?n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Quiet period (seconds)`,value:h.quietSeconds,min:30,max:uu,onChange:e=>x({quietSeconds:e??0}),hint:`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`}),u(Q,{label:`Longest window (seconds)`,value:h.maxWindowSeconds,min:60,max:du,onChange:e=>x({maxWindowSeconds:e??0}),hint:`A permanently busy driveway would otherwise never deliver. At this bound the window closes with whatever it holds.`,testId:`summary-max-window`})]}):n(`div`,{children:[u(`label`,{className:X,children:`Weekly windows`}),u(kr,{value:h.schedule,onChange:e=>x({schedule:e})}),u(`p`,{className:ol,children:`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.`})]}),u(Q,{label:`Wait for open tracks (seconds)`,value:h.barrierSeconds,min:0,max:fu,onChange:e=>x({barrierSeconds:e??0}),hint:`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`})]})}),u(M,{value:`content`,className:`space-y-3`,children:n(Z,{title:`What goes in`,hint:`Evaluated on tracks: one passage is one tile.`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Classes`}),u(kt,{options:C,value:h.classes,onChange:e=>x({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),u(`p`,{className:ol,children:`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.`})]}),n(`div`,{children:[u(`label`,{className:X,children:`Excluded classes`}),u(kt,{options:C,value:h.classesExclude,onChange:e=>x({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),n(`div`,{children:[u(`label`,{className:X,children:`Zones`}),u(kt,{options:w,value:h.zones,onChange:e=>x({zones:e}),loading:E,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),u(`p`,{className:ol,children:`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Minimum importance`,value:h.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>x({minImportance:e}),hint:`The pipeline's own score, 0–1. Empty keeps everything.`,testId:`summary-min-importance`}),u(Q,{label:`Minimum stay (seconds)`,value:h.minDwellSeconds,min:0,max:pu,emptyPlaceholder:`any`,onChange:e=>x({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]}),u(dl,{label:`Include parked objects`,checked:h.includeStationary,onChange:e=>x({includeStationary:e}),hint:`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`})]})}),u(M,{value:`mosaic`,className:`space-y-3`,children:n(Z,{title:`The mosaic`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Tiles`,value:h.maxTiles,min:1,max:24,onChange:e=>x({maxTiles:e??1}),hint:`9 (a 3×3 grid) is the most a phone lock-screen thumbnail can carry and still be read.`,testId:`summary-max-tiles`}),n(`div`,{children:[u(`label`,{className:X,children:`When there are more tracks than tiles`}),u(T,{value:h.rank,options:hu.map(e=>({value:e,label:gu[e]})),onChange:e=>{let t=ud(e.target.value);t!==void 0&&x({rank:t})},"data-testid":`summary-rank`}),u(`p`,{className:ol,children:`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`})]})]}),n(`div`,{children:[u(`label`,{className:X,children:`Text on the mosaic`}),u(T,{value:h.mosaicCaptions,options:_u.map(e=>({value:e,label:yu[e]})),onChange:e=>{let t=dd(e.target.value);t!==void 0&&x({mosaicCaptions:t})},"data-testid":`summary-captions`}),u(`p`,{className:ol,children:`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.`})]}),n(`div`,{children:[u(bo,{label:`Caption burned onto the mosaic`,value:h.captionText,disabled:!I,onChange:e=>x({captionText:e}),placeholder:`Leave empty for no caption`,vars:F,testId:`summary-caption`}),u(`p`,{className:ol,children:I?`Across the top band.`:`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`})]})]})}),u(M,{value:`ai`,className:`space-y-3`,children:n(Z,{title:`Written summary`,hint:`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:[u(dl,{label:`Have a model describe the window`,checked:h.aiEnabled,onChange:e=>x({aiEnabled:e}),hint:`Off by default. The mosaic and the counts are delivered either way.`,testId:`summary-ai-enabled`}),!h.aiEnabled&&u(`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:`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.`}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Vision profile`}),u(T,{value:h.aiProfileId,disabled:!h.aiEnabled,options:[{value:``,label:`The hub's default vision profile`},...j.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>x({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),u(`p`,{className:ol,children:k.isError?`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`:j.length===0?`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`:`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`})]}),n(`div`,{children:[u(`label`,{className:X,children:`Answer in`}),u(T,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:`Don’t ask for a language`},...bu.map(e=>({value:e,label:ld[e]}))],onChange:e=>x({aiLanguage:fd(e.target.value)}),"data-testid":`summary-ai-language`}),u(`p`,{className:ol,children:`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`})]})]}),n(`div`,{children:[u(`label`,{className:X,children:`Your question (optional)`}),u(`textarea`,{value:h.aiPrompt,rows:3,maxLength:Cu,disabled:!h.aiEnabled,onChange:e=>x({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:`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`}),u(`p`,{className:ol,children:`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.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Frames the model may look at`,value:h.maxAiImages,min:1,max:8,disabled:!h.aiEnabled,onChange:e=>x({maxAiImages:e??1}),hint:`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`}),u(Q,{label:`Time limit (seconds)`,value:h.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!h.aiEnabled,onChange:e=>x({aiTimeoutSeconds:e}),hint:`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`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Frame size sent (pixels)`,value:h.aiMaxImagePx,min:64,max:Su,emptyPlaceholder:`448`,disabled:!h.aiEnabled,onChange:e=>x({aiMaxImagePx:e}),hint:`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`}),n(`div`,{children:[u(`label`,{className:X,children:`If the model gives no answer`}),u(T,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:xu.map(e=>({value:e,label:cd[e]})),onChange:e=>{let t=pd(e.target.value);t!==void 0&&x({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),u(`p`,{className:ol,children:`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.`})]})]})]})}),u(M,{value:`delivery`,className:`space-y-3`,children:n(Z,{title:`Delivery`,children:[u(ul,{targets:o,value:h.targetIds,onChange:e=>x({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Priority`,value:h.priority,min:1,max:5,onChange:e=>x({priority:e??3}),testId:`summary-priority`}),u(dl,{label:`Deliver a window that matched nothing`,checked:h.deliverEmpty,onChange:e=>x({deliverEmpty:e}),hint:`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`})]}),u(fl,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>x({templateTitle:e}),onBodyChange:e=>x({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),n(`p`,{className:ol,children:[u(`code`,{children:`{{ai}}`}),` is the written summary. A body that never names it still gets the sentence, appended on its own line — a template written before the AI pass existed must not make the feature look broken.`]})]})})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[u(A,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:`Cancel`}),n(A,{size:`sm`,type:`button`,disabled:!te,onClick:()=>N.mutate(),children:[N.isPending&&u(K,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}var hd=`nc.listTimelapseRules`,gd=`nc.upsertTimelapseRule`,_d=`nc.deleteTimelapseRule`,vd=`nc.testTimelapseRule`,yd=3600,bd=3600,xd=30,Sd=1,Cd=[`image`,`gif`],wd={image:`Still frame`,gif:`Short animation (GIF)`},Td=Ct({rules:Tt(Re.extend({readOnly:Et().optional()}))});function Ed(e){let t=Td.safeParse(e);return t.success?t.data.rules:null}function Dd(e){return e.readOnly!==!0}var Od=Ct({produced:bt(),exportId:St().optional(),coveragePercent:bt().optional(),enqueued:bt().optional(),windowStartMs:bt().optional(),windowEndMs:bt().optional(),error:St().optional()});function kd(e){let t=Od.safeParse(e);return t.success?t.data:null}function Ad(){return{name:``,enabled:!0,deviceIds:[],schedule:void 0,cadenceSec:15,framerate:10,denseCadenceSec:void 0,minDwellSec:void 0,targetIds:[],templateTitle:``,templateBody:``,previewText:``,previewTextSet:!1,previewMode:`image`,reportClasses:[],priority:3}}function jd(e){return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule,cadenceSec:e.cadenceSec,framerate:e.framerate,denseCadenceSec:e.denseCadenceSec,minDwellSec:e.minDwellSec,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,previewText:e.previewText??``,previewTextSet:e.previewText!==void 0,previewMode:e.previewMode,reportClasses:[...e.reportClasses??[]],priority:e.priority}}var Md={windows:[{days:[1],startMinute:0,endMinute:60}]};function Nd(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 Pd(e){let t=Nd(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??Md,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Sl(e.targetIds),...t===void 0?{}:{template:t},...e.previewTextSet?{previewText:e.previewText}:{},previewMode:e.previewMode,...e.reportClasses.length>0?{reportClasses:[...e.reportClasses]}:{},priority:e.priority}}function Fd(e,t){let n=Pd(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),xl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),xl(n.schedule,t.schedule)||(r.schedule=n.schedule),n.cadenceSec!==t.cadenceSec&&(r.cadenceSec=n.cadenceSec),n.framerate!==t.framerate&&(r.framerate=n.framerate),n.denseCadenceSec!==t.denseCadenceSec&&(r.denseCadenceSec=n.denseCadenceSec??Id(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),xl(n.targets,t.targets)||(r.targets=n.targets),xl(n.template,t.template)||(r.template=n.template??null),n.previewText!==t.previewText&&n.previewText!==void 0&&(r.previewText=n.previewText),n.previewMode!==t.previewMode&&(r.previewMode=n.previewMode),xl(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function Id(e){return Math.max(Sd,e/xd)}function Ld(e,t,n){return t<=0||n<=0?0:e/t/n}function Rd(e,t){return e*t*ze}function zd(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 ${yd}.`),(!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 ${ze}s and ${bd}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 Bd(e){return zd(e).length===0}function Vd(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=Rd(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 Hd(e){return _l(e)}function Ud(e,t){return vl(e,t,`Never run`)}function Wd(e){return e.denseCadenceSec===void 0?{seconds:Id(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var Gd=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,label:`Window`,fields:[`schedule`]},{key:`sampling`,label:`Sampling`,fields:[`cadenceSec`,`framerate`,`denseCadenceSec`,`minDwellSec`]},{key:`delivery`,label:`Delivery`,fields:[`targetIds`,`priority`,`previewMode`,`previewText`,`previewTextSet`,`templateTitle`,`templateBody`,`reportClasses`]}],Kd=`rule`;function qd(e){return Gd.find(t=>t.key===e)?.key}t();var Jd=7;function Yd(e){return Cd.find(t=>t===e)}function Xd({rule:e,cameras:t,fleet:r,targets:i,onSaved:o,onCancel:s}){let d=p(),[f,m]=c(()=>e===null?Ad():jd(e)),[h,g]=c(null),[_,v]=c(Kd),y=e=>m(t=>({...t,...e})),b=ho(),x=b.data?uo(b.data,{family:`timelapse`,field:`previewText`}):void 0,C=l({mutationFn:async()=>{let t=e===null?{rule:Pd(f)}:{ruleId:e.id,patch:Fd(f,e)};await d.trpcClient.addons.custom.mutate({addonId:$,action:gd,input:t})},onSuccess:o,onError:e=>g(e instanceof Error?e.message:`Save failed`)}),w=zd(f),E=Vd(f),k=Wd(f),j=Ld(Jd,k.seconds,f.framerate),N=Bd(f)&&!C.isPending,F=Gd.some(e=>e.key===_)?_:Kd;return u(Ae,{open:!0,onOpenChange:e=>!e&&s(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[u(P,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?`New timelapse`:`Edit ${e.name}`})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),h!==null&&u(`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}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&u(Vc,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(sl,{problems:w,testId:`timelapse-problems`}),u(cl,{warnings:E,testId:`timelapse-warnings`})]}),n(D,{value:F,onValueChange:e=>v(qd(e)??_),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(Ce,{className:`mb-3 shrink-0`,children:Gd.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(z,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-3`,children:[u(Z,{title:`What it is`,hint:`One video per camera, assembled from that camera's RECORDED footage when the window closes.`,children:n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:X,children:`Name`}),u(O,{value:f.name,onChange:e=>y({name:e.target.value}),placeholder:`e.g. Night driveway`,"data-testid":`timelapse-name`})]}),u(`div`,{className:`pb-1.5`,children:u(dl,{label:`Enabled`,checked:f.enabled,onChange:e=>y({enabled:e}),testId:`timelapse-enabled`})})]})}),u(Z,{title:`Cameras`,children:u(ll,{cameras:t,value:f.deviceIds,fleet:r,onChange:e=>y({deviceIds:e}),hint:`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.`})})]}),u(M,{value:`window`,className:`space-y-3`,children:u(Z,{title:`When`,children:n(`div`,{children:[u(`label`,{className:X,children:`Weekly windows`}),u(kr,{value:f.schedule,onChange:e=>y({schedule:e})}),u(`p`,{className:ol,children:`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.`})]})})}),u(M,{value:`sampling`,className:`space-y-3`,children:n(Z,{title:`Sampling`,hint:`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Base cadence (seconds)`,value:f.cadenceSec,min:2,max:yd,onChange:e=>y({cadenceSec:e??0}),hint:`One frame every N seconds across the quiet parts of the window.`,testId:`timelapse-cadence`}),u(Q,{label:`Output frame rate (fps)`,value:f.framerate,min:1,max:60,onChange:e=>y({framerate:e??0}),hint:`How fast the assembled video plays.`,testId:`timelapse-framerate`})]}),n(`div`,{children:[u(`label`,{className:X,children:`Dense cadence, near the detections`}),n(`div`,{className:`flex items-center gap-2`,children:[u(T,{value:f.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:`Automatic (${k.seconds}s)`},{value:`explicit`,label:`Set it myself`}],onChange:e=>y({denseCadenceSec:e.target.value===`auto`?void 0:Wd(f).seconds}),"data-testid":`timelapse-dense-mode`}),f.denseCadenceSec!==void 0&&u(O,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(f.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&y({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),n(`p`,{className:ol,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,k.seconds,`s and `,f.framerate,` fps a `,Jd,`-second passage lasts `,j.toFixed(2),`s on screen; halving the cadence doubles that, and the quiet parts of the night do not change length.`,k.derived?` Automatic keeps tracking the base cadence (base ÷ 30, never below 1s).`:` Fixed at this value — the hub cannot unset the field, so going back to Automatic writes the derived number (${Wd({...f,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),u(Q,{label:`Minimum seconds of video per detection (optional)`,value:f.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>y({minDwellSec:e}),hint:`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`})]})}),u(M,{value:`delivery`,className:`space-y-3`,children:n(Z,{title:`The notification`,children:[u(ul,{targets:i,value:f.targetIds,onChange:e=>y({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Preview`}),u(T,{value:f.previewMode,options:Cd.map(e=>({value:e,label:wd[e]})),onChange:e=>{let t=Yd(e.target.value);t!==void 0&&y({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),u(Q,{label:`Priority`,value:f.priority,min:1,max:5,onChange:e=>y({priority:e??3}),testId:`timelapse-priority`})]}),n(`div`,{children:[u(bo,{label:`Caption on the preview frame`,value:f.previewTextSet?f.previewText:``,placeholder:`${qe} (shipped default)`,onChange:e=>y({previewText:e,previewTextSet:!0}),vars:x,testId:`timelapse-preview-text`}),n(`p`,{className:ol,children:[f.previewTextSet&&f.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${qe}).`,f.previewTextSet&&n(a,{children:[` `,u(`button`,{type:`button`,className:`underline`,onClick:()=>y({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),u(fl,{title:f.templateTitle,body:f.templateBody,onTitleChange:e=>y({templateTitle:e}),onBodyChange:e=>y({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),n(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`With no body of your own the detection summary is appended automatically, and only when the count is non-zero. With one, nothing is appended — ask for it with`,` `,u(`code`,{children:`{{detectionSummary}}`}),`.`]})]})})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[u(A,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),n(A,{size:`sm`,type:`button`,disabled:!N,onClick:()=>C.mutate(),children:[C.isPending&&u(K,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}function Zd({children:e,className:t}){return u(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function Qd(){return u(`div`,{className:`flex items-center justify-center py-16`,children:u(K,{className:`h-6 w-6 animate-spin text-primary`})})}function $d({children:e,testId:t}){return u(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function ef({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:i}){return u(x,{children:u(E,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,mobileMode:`scroll`,maxBodyHeight:j,...i===void 0?{}:{onRowClick:i}})})}function tf({name:e,enabled:t,onOpen:r,badges:i,openTestId:a}){return n(`span`,{className:`flex flex-wrap items-center gap-2`,children:[r===void 0?u(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e}):u(Zd,{children:u(`button`,{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`,...a===void 0?{}:{"data-testid":a},children:e})}),!t&&u(q,{variant:`warning`,children:`disabled`}),i]})}function nf({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:i=`Delete`,cancelLabel:a=`Cancel`,ariaLabel:o,testId:s,onConfirm:c}){let l=Se(),d=async()=>{await l({title:n,message:r,confirmLabel:i,cancelLabel:a,variant:`danger`})&&c()};return u(`button`,{type:`button`,title:i,"aria-label":o,disabled:e||t,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void d(),...s===void 0?{}:{"data-testid":s},children:u(g,{className:`h-3.5 w-3.5 text-danger`})})}t();var rf=[`notificationSummaries`,`listSummaryRules`];function af(e){return[{key:`name`,header:`Digest`,render:t=>u(tf,{name:t.name,enabled:t.enabled,...wu(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`summary-edit-${t.id}`,badges:n(a,{children:[!wu(t)&&u(q,{variant:`warning`,children:`read-only`}),t.ai?.enabled===!0&&u(q,{variant:`info`,children:`AI`}),t.ai!==void 0&&!t.ai.enabled&&u(q,{variant:`default`,children:`AI off`})]})})},{key:`cameras`,header:`Cameras`,align:`center`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:`Window`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:id(e.window)})},{key:`filters`,header:`Keeps`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:od(e.filters)})},{key:`mosaic`,header:`Mosaic`,nowrap:!0,render:e=>n(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.maxTiles,` tiles · `,e.rank]})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:ad(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onTest(t),title:`Produce this digest now and DELIVER it`,"aria-label":`test ${t.name}`,"data-testid":`summary-test-${t.id}`,children:u(b,{className:`h-3.5 w-3.5`})}),u(nf,{disabled:t.readOnly,pending:e.deletePending,title:`Delete this summary?`,message:`This will permanently delete "${t.name}". This action cannot be undone.`,ariaLabel:`delete ${t.name}`,testId:`summary-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}t();var of=[`notificationTimelapses`,`listTimelapseRules`];function sf(e){return[{key:`name`,header:`Timelapse`,render:t=>u(tf,{name:t.name,enabled:t.enabled,...Dd(t)?{onOpen:()=>e.onOpen(t),openTestId:`timelapse-edit-${t.id}`}:{},badges:Dd(t)?null:u(q,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:`Cameras`,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.deviceIds.length===1?e.cameraNameById.get(t.deviceIds[0]??-1)??`#${t.deviceIds[0]}`:`${t.deviceIds.length} cameras`})},{key:`schedule`,header:`Window`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Hd(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let t=Wd(jd(e));return n(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.cadenceSec,`s · `,e.framerate,`fps · dense `,t.seconds,`s`,t.derived?` (auto)`:``,e.minDwellSec===void 0?``:` · ≥${e.minDwellSec}s/detection`]})}},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:Ud(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,disabled:!Dd(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Dd(t),onClick:()=>e.onTest(t),title:`Render this rule's last closed window now and DELIVER it`,"aria-label":`test ${t.name}`,"data-testid":`timelapse-test-${t.id}`,children:u(b,{className:`h-3.5 w-3.5`})}),u(nf,{disabled:!Dd(t),pending:e.deletePending,title:`Delete this timelapse?`,message:`This will permanently delete "${t.name}". This action cannot be undone.`,ariaLabel:`delete ${t.name}`,testId:`timelapse-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}t();var cf={summary:{title:`Summary rules are not available on this hub`,message:`This hub has not been updated to serve summary rules yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime.`},timelapse:{title:`Timelapse rules are not available on this hub`,message:`This hub has not been updated to serve timelapse rules yet. Deploy addon-post-analysis and reload — the rules themselves are untouched.`},"calendar-events":{title:`Calendar-events rules are not available on this hub`,message:`This hub has not been updated to serve calendar-events rules yet. Deploy addon-post-analysis and reload — the rules themselves are untouched.`}},lf=`The hub answered something this admin build does not understand. Update both and reload.`;function uf(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function df({cameras:e,fleet:t,targets:r,taxonomy:o}){let s=p(),[d,f]=c({mode:`closed`}),[m,h]=c(null),[g,_]=c(null),[v,y]=c(null),[b,x]=c(null),S=i({queryKey:rf,queryFn:async()=>Vu(await s.trpcClient.addons.custom.mutate({addonId:$,action:ou,input:{}}))}),C=i({queryKey:of,queryFn:async()=>Ed(await s.trpcClient.addons.custom.mutate({addonId:$,action:hd,input:{}}))}),w=i({queryKey:zl,queryFn:async()=>Kl(await s.trpcClient.addons.custom.mutate({addonId:$,action:Bl,input:{}}))}),E=S.data??[],D=C.data??[],O=w.data??[],k=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:su,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),A=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:cu,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),j=l({mutationFn:async e=>Hu(await s.trpcClient.addons.custom.mutate({addonId:$,action:lu,input:{ruleId:e,...sd(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),ee=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:gd,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),M=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:_d,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),N=l({mutationFn:async e=>kd(await s.trpcClient.addons.custom.mutate({addonId:$,action:vd,input:e})),onSuccess:e=>{y(null),x(e)}}),P=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:Vl,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void w.refetch()}),I=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:Hl,input:{ruleId:e}}),onSuccess:()=>void w.refetch()}),L=e.toSorted((e,t)=>e.name.localeCompare(t.name)),R=r.map(e=>({id:e.id,name:e.name,enabled:e.enabled})),z=new Map(R.map(e=>[e.id,e.name])),te=new Map(L.map(e=>[e.id,e.name])),B=Date.now(),ne={summary:{nowMs:B,targetNameById:z,deletePending:A.isPending,onToggle:(e,t)=>k.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{wu(e)&&f({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>A.mutate(e.id)},timelapse:{nowMs:B,cameraNameById:te,targetNameById:z,deletePending:M.isPending,onToggle:(e,t)=>ee.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Dd(e)&&f({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>M.mutate(e.id)},calendar:{nowMs:B,targetNameById:z,deletePending:I.isPending,onToggle:(e,t)=>P.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{ql(e)&&f({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>I.mutate(e.id)}},re=e=>{switch(e.family){case`summary`:ne.summary.onOpen(e.rule);return;case`timelapse`:ne.timelapse.onOpen(e.rule);return;case`calendar-events`:ne.calendar.onOpen(e.rule);return}},V=e=>{f(e===`summary`?{mode:`summary`,rule:null}:e===`timelapse`?{mode:`timelapse`,rule:null}:{mode:`calendar-events`,rule:null})},H=e=>{let t=e===`summary`?S:e===`timelapse`?C:w;return t.isLoading?null:t.isError?{unreadable:!1}:t.data===null?{unreadable:!0}:null},ie=e=>{e===`summary`?S.refetch():e===`timelapse`?C.refetch():w.refetch()},U=e=>{let t=uf(e);return t!==null&&H(t)!==null},ae=e=>{let t=uf(e),r=t===null?null:H(t);return n(a,{children:[t!==null&&r!==null&&u(F,{title:cf[t].title,message:r.unreadable?lf:cf[t].message,onRetry:()=>ie(t)}),A.isError&&u(F,{title:`Could not delete the rule`,message:String(A.error)}),M.isError&&u(F,{title:`Could not delete the rule`,message:String(M.error)}),I.isError&&u(F,{title:`Could not delete the rule`,message:String(I.error)}),j.isError&&u(F,{title:`The test run failed`,message:String(j.error)}),N.isError&&u(F,{title:`The test run failed`,message:String(N.error)}),g!==null&&u(ff,{outcome:g,onDismiss:()=>_(null)}),b!==null&&u(pf,{outcome:b,onDismiss:()=>x(null)})]})},oe=()=>f({mode:`closed`}),se=n(a,{children:[d.mode===`summary`&&u(md,{rule:d.rule,cameras:L,fleet:t,targets:R,taxonomy:o,onCancel:oe,onSaved:()=>{oe(),S.refetch()}}),d.mode===`timelapse`&&u(Xd,{rule:d.rule,cameras:L,fleet:t,targets:R,onCancel:oe,onSaved:()=>{oe(),C.refetch()}}),d.mode===`calendar-events`&&u(au,{rule:d.rule,targets:R,onCancel:oe,onSaved:()=>{oe(),w.refetch()}}),u(pl,{open:m!==null,ruleName:m?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${m?.targets.length??0} target${(m?.targets.length??0)===1?``:`s`}`,pending:j.isPending,onCancel:()=>h(null),onConfirm:()=>{m!==null&&j.mutate(m.id)}}),u(pl,{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:n(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Which camera`}),u(T,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:te.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:E,timelapses:D,calendarEvents:O,loading:S.isLoading||C.isLoading||w.isLoading,columnDeps:ne,open:re,create:V,notices:ae,listFailed:U,overlays:se}}function ff({outcome:e,onDismiss:t}){return n(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[e.error===void 0?n(`span`,{children:[`Produced `,e.produced,` digest`,e.produced===1?``:`s`,` —`,` `,e.tiles??0,` tile`,(e.tiles??0)===1?``:`s`,` from`,` `,e.cameras??0,` camera`,(e.cameras??0)===1?``:`s`,`,`,` `,e.matched??0,` track`,(e.matched??0)===1?``:`s`,` matched,`,` `,e.enqueued??0,` notification`,(e.enqueued??0)===1?``:`s`,` sent.`,(e.droppedStationary??0)>0&&n(`span`,{"data-testid":`summary-test-dropped-stationary`,children:[` `,e.droppedStationary,` parked object`,e.droppedStationary===1?``:`s`,` left out.`]})]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,e.error]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:`Dismiss`})]})}function pf({outcome:e,onDismiss:t}){return n(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[e.error===void 0?n(`span`,{children:[`Produced `,e.produced,` video`,e.produced===1?``:`s`,e.coveragePercent===void 0?``:` — ${Math.round(e.coveragePercent)}% of the window had footage`,`, `,e.enqueued??0,` notification`,(e.enqueued??0)===1?``:`s`,` sent.`]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,e.error]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:`Dismiss`})]})}var mf=[{key:`summaries`,label:`Summaries`,blurb:`One window, one picture: every camera's best moments as a single mosaic, delivered once when the window closes.`,newLabel:`New summary`,emptyHint:`No summary rules yet. Use "New summary" (or pick Summary under New rule) to author one.`},{key:`timelapses`,label:`Timelapses`,blurb:`A night of recorded footage, assembled into one short video per camera when the window closes.`,newLabel:`New timelapse`,emptyHint:`No timelapse rules yet. Use "New timelapse" (or pick Timelapse under New rule) to author one.`},{key:`calendar-events`,label:`Calendar events`,blurb:`At schedule time, send the upcoming events from selected calendars for the next N days.`,newLabel:`New calendar events`,emptyHint:`No calendar-events rules yet. Use "New calendar events" (or pick Calendar events under New rule) to author one.`}],hf=[{type:`detection`,label:`Detection`,hint:`Fire on what the cameras see — detections, tracks and package events.`},{type:`sensor`,label:`Sensor`,hint:`A doorbell press or linked sensor changing state.`},{type:`audio`,label:`Sound`,hint:`Sustained sound level or a named sound class.`},{type:`occupancy`,label:`Occupancy`,hint:`How many objects are in a frame or zone, and for how long.`},{type:`device-events`,label:`Device events`,hint:`Offline, battery low, stream drop, camera blind.`},{type:`system`,label:`System events`,hint:`Node, addon, update, backup or export events.`},{type:`alarm`,label:`Alarm`,hint:`Arming, armed, triggered, disarmed.`},{type:`summary`,label:`Summary`,hint:`One mosaic of the best moments across cameras for a window.`},{type:`timelapse`,label:`Timelapse`,hint:`One short video per camera from recorded footage.`},{type:`calendar-events`,label:`Calendar events`,hint:`Upcoming calendar events for the next N days, at schedule time.`}];function gf(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function _f(e){if(!(e==null||e.length===0))return gf(e)?e:tt(e)}function vf(e){let t=mf.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function yf(e){return[...jt.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...mf]}function bf(e){return!gf(e)}function xf(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}t();function Sf(e){return[{key:`name`,header:`Rule`,render:t=>u(tf,{name:t.name,enabled:t.enabled,...ql(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:ql(t)?null:u(q,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:`When`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Zl(e.schedule)})},{key:`horizon`,header:`Horizon`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:ru(e.horizonDays)})},{key:`calendars`,header:`Calendars`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:iu(e)})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:ad(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>u(Zd,{className:`flex items-center justify-end gap-1`,children:u(nf,{disabled:t.readOnly,pending:e.deletePending,title:`Delete this calendar-events rule?`,message:`This will permanently delete "${t.name}". This action cannot be undone.`,ariaLabel:`delete ${t.name}`,testId:`calendar-events-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})})}]}function Cf(e,t){return e.replaceAll(`{{name}}`,t)}function wf(e){return[{key:`name`,header:`Rule`,render:t=>u(tf,{name:t.name,enabled:t.enabled,...Wr(t)?{onOpen:()=>e.onOpen(t)}:{}})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:t=>n(`span`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] text-foreground-subtle`,children:un(t,e.t(`notificationRules.grouping.choice`,gn))}),!fn(t.delivery)&&u(q,{variant:`warning`,children:`read-only`})]})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(ic,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:e.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(pc,{rule:t,snoozes:e.snoozes,exempt:Qt(t.conditions,Bt({onActivation:t.actions?.onActivation??[],onDeactivation:t.actions?.onDeactivation??[],onTrigger:t.actions?.onTrigger??[],onTriggerOff:t.actions?.onTriggerOff??[],buttons:t.actions?.buttons??[]},e.sequences))})})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>Wr(t)?n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(el,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&u(ac,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:`Open in the simulator — describe an event and tune it before injecting`,"aria-label":`simulate ${t.name}`,children:u(b,{className:`h-3.5 w-3.5`})}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:u(B,{className:`h-3.5 w-3.5`})}),u(Ef,{rule:t,deps:e})]}):u(Tf,{rule:t,deps:e})}]}function Tf({rule:e,deps:t}){return n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(`span`,{title:ct(rt(e)).blurb,children:u(q,{variant:`warning`,children:`Recreate as one rule per family`})}),t.onOpenHistory&&u(ac,{rule:e,onOpenHistory:t.onOpenHistory}),u(Ef,{rule:e,deps:t})]})}function Ef({rule:e,deps:t}){let{t:n}=Dt();return u(nf,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:Cf(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:Cf(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function Df(e){let t=wf(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:br(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:dr(e.conditions.systemEvent)})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`cooldown`,header:`Cooldown`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:cn(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function Of(e){switch(e){case`detection`:return`Detection`;case`sensor`:return`Sensor`;case`sound`:return`Sound`;case`occupancy`:return`Occupancy`;case`device-events`:return`Device events`;case`system`:return`System`;case`alarm`:return`Alarm`;case`mixed`:return`To recreate`;case`summary`:return`Summary`;case`timelapse`:return`Timelapse`;case`calendar-events`:return`Calendar events`}}function kf(e){return{family:`event`,kind:rt(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Af(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function jf(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Mf(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Nf(e){return[...e.events.map(kf),...e.summaries.map(Af),...e.timelapses.map(jf),...e.calendarEvents.map(Mf)]}function Pf(e,t){return t===`all`?!0:gf(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:bf(t)&&e.family===`event`?gt(e.rule,t):!1}function Ff(e,t){return Nf(t).filter(t=>Pf(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function If(e,t){return Ff(e,t).length}function Lf(e){return e===`all`?900:860}function Rf(e){return e.family===`event`?e.rule:null}function zf(e){return e.family===`summary`?e.rule:null}function Bf(e){return e.family===`timelapse`?e.rule:null}function Vf(e){return e.family===`calendar-events`?e.rule:null}function Hf(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 Uf(e,t){return e.map(e=>Hf(e,t))}function Wf(e,t){return e.find(e=>e.key===t)}function Gf(e,t,n){let r=Wf(wf(n.event),e),i=Wf(af(n.summary),e),a=Wf(sf(n.timelapse),e),o=Wf(Sf(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 Kf(e){switch(e.family){case`event`:return null;case`summary`:return id(e.rule.window);case`timelapse`:return Hd(e.rule.schedule);case`calendar-events`:return Zl(e.rule.schedule)}}function qf(e){let t=Wf(wf(e.event),`trigger`);return{key:`when`,header:`When`,render:(e,n)=>{let r=Kf(e);return r===null?e.family===`event`?t?.render(e.rule,n)??null:null:u(`span`,{className:`text-[11px] text-foreground-subtle`,children:r})}}}function Jf(e){return[Gf(`name`,`Name`,e),{key:`type`,header:`Type`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:Of(e.kind)})},qf(e),Gf(`targets`,`Targets`,e),Gf(`lastRun`,`Last run`,e),Gf(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),Gf(`enabled`,`On`,e),Gf(`actions`,``,e)]}function Yf(e,t){return e===`all`?Jf(t):e===`summaries`?Uf(af(t.summary),zf):e===`timelapses`?Uf(sf(t.timelapse),Bf):e===`calendar-events`?Uf(Sf(t.calendar),Vf):bf(e)&&Nt(e)?Uf(Df(t.event),Rf):Uf(wf(t.event),Rf)}function Xf({value:e,family:t,onChange:r,draft:i}){if(t===void 0||!ot.includes(t))return null;let a=e?.mode===`summary`?e:null;return n(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:`Delivery`}),n(`div`,{className:`flex flex-wrap gap-3 text-xs`,children:[n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-delivery`,checked:a===null,onChange:()=>r({mode:`instant`}),"data-testid":`rule-delivery-instant`}),`Instant — a notification per event`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-delivery`,checked:a!==null,onChange:()=>r({mode:`summary`,schedule:Ke([fr])}),"data-testid":`rule-delivery-summary`}),`Summary on schedule — the current state, at set times`]})]}),a!==null&&u(Zf,{value:a,onChange:r,draft:i})]})}function Zf({value:e,onChange:t,draft:r}){let i=e.schedule.timezone,a=Ge({systemEventDelivery:e});return n(`div`,{className:`mt-2 space-y-2`,children:[n(`p`,{className:Bn,children:[`Nothing is sent per event. At each time below, one notification lists what is still true for the kinds and filters of this rule — low batteries, consumables, devices or streams offline, updates available — or one notification per category, if you choose so below. Nothing to report sends nothing. Time zone: `,i??`the hub’s`,`.`]}),u(kr,{mode:`times`,value:e.schedule,onChange:n=>{n!==void 0&&t($n(e,n))}}),n(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[u(`legend`,{className:`sr-only`,children:`How the summary is sent`}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-summary-split`,checked:a===`rule`,onChange:()=>t(Mn(e,`rule`)),"data-testid":`rule-delivery-split-rule`}),`One message with every category`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-summary-split`,checked:a===`section`,onChange:()=>t(Mn(e,`section`)),"data-testid":`rule-delivery-split-section`}),`One notification per category (batteries, consumables, devices…)`]})]}),u(Qf,{draft:r,split:a})]})}function Qf({draft:e,split:t}){let r=p(),i=l({mutationFn:e=>r.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),a=Cr(i.status,i.data,i.error,t);return n(`div`,{className:`space-y-1.5`,children:[u(A,{size:`sm`,variant:`secondary`,onClick:()=>i.mutate(e()),disabled:i.isPending,"data-testid":`rule-delivery-preview`,children:i.isPending?`Reading the state…`:`Preview the summary now`}),a!==null&&u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:a.lines.map((e,t)=>u(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function $f(e,t){if(e.status===`error`)return{kind:`failed`,reason:e.error instanceof Error?e.error.message:`unknown error`};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:ip(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var ep=6e4,tp=60*ep,np=24*tp;function rp(e,t){return e===1?`the last ${t}`:`the last ${String(e)} ${t}s`}function ip(e){return e===null?`No delivery on record`:e>=np?`Not in ${rp(Math.floor(e/np),`day`)}`:e>=tp?`Not in ${rp(Math.floor(e/tp),`hour`)}`:e>=ep?`Not in ${rp(Math.floor(e/ep),`minute`)}`:`Not in the window read`}t();var ap=[`notificationRules`,`listRules`],op=[`notificationOutput`,`listTargets`,`forRules`],sp=[`notificationRules`,`getConditionCatalog`],cp=[`deviceManager`,`gateableDevices`],lp=Le.options;function up({onSimulateRule:t,onOpenHistory:a}={}){let o=p(),{t:s}=Dt(),[f,h]=Gr(),[g,_]=c({mode:`closed`}),v=_f(f.get(`section`))??`all`,b=e=>{let t=new URLSearchParams(f);e===`all`?t.delete(`section`):t.set(`section`,e),h(t,{replace:!0})},x=i({queryKey:ap,queryFn:async()=>(await o.trpcClient.notificationRules.listRules.query({})).rules}),S=e(null);d(()=>{if(g.mode!==`closed`)return;let e=f.get(`rule`);if(e===null||e===`new`){e===null&&(S.current=null);return}if(S.current===e)return;let t=x.data?.find(t=>t.id===e);t===void 0||!Wr(t)||(S.current=e,_({mode:`form`,rule:t}))},[g.mode,f,x.data]);let C=i({queryKey:op,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),w=i({queryKey:sp,queryFn:()=>o.trpcClient.notificationRules.getConditionCatalog.query({})}),T=ge({projection:`slim`}),E=nc(),O=r(()=>T.data??[],[T.data]),k=De(T),j=r(()=>O.map(e=>e.id),[O]),M=i({queryKey:[...cp,j],enabled:j.length>0,queryFn:async()=>{let e=[];for(let t of O){let n=ut(await o.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),lp);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),N=r(()=>{let e=qr(O);return O.filter(e=>pt(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))},[O]),P=r(()=>O.filter(e=>e.type===Be.Camera).map(e=>({id:e.id,name:e.name})),[O]),I=Zr(r(()=>P.map(e=>e.id),[P])),L=r(()=>{let e=new Map(P.map(e=>[e.id,e.name]));return I.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})))},[I.results,P]),R=r(()=>{let e=new Map;for(let t of C.data??[])e.set(t.id,t.name);return e},[C.data]),z=l({mutationFn:e=>o.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void x.refetch()}),te=l({mutationFn:e=>o.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void x.refetch()}),B=fc(),ne=y({}),V=ne.data?.sequences??[],H=re(),ie=x.data??[],U=df({cameras:P,fleet:k,targets:C.data??[],taxonomy:w.data?.taxonomy}),ae={events:ie,summaries:U.summaries,timelapses:U.timelapses,calendarEvents:U.calendarEvents},oe=yf(new Map(jt.map(e=>[e.key,If(e.key,ae)]))),W=oe.find(e=>e.key===v)??oe[0]??jt[0],G=gf(W.key)?vf(W.key):void 0,le=bf(W.key)?W.key:null,ue=Ff(W.key,ae),de=(e,t)=>{let n=new URLSearchParams(f);e===null?n.delete(`rule`):n.set(`rule`,e),t===void 0||t===`rule`?n.delete(`editTab`):n.set(`editTab`,t),h(n,{replace:!0})},K=()=>{let e=new URLSearchParams(f);e.delete(`rule`),e.delete(`editTab`),h(e,{replace:!0})},fe=()=>{let e=f.get(`rule`);e!==null&&(S.current=e),_({mode:`closed`}),K()},pe=e=>{Wr(e)&&(S.current=e.id,_({mode:`form`,rule:e}),de(e.id))},me=()=>{let e=le??`all`;S.current=`new`,_({mode:`form`,rule:null,seed:it(e)}),de(`new`)},_e=e=>{if(xf(e)){S.current=`new`,_({mode:`form`,rule:null,seed:it(e)}),de(`new`);return}U.create(e)},ye=e=>{if(e.family===`event`){pe(e.rule);return}U.open(e)},be={targetNameById:R,snoozes:B,sequences:V,deletePending:te.isPending,onToggle:(e,t)=>z.mutate({ruleId:e.id,enabled:t}),onOpen:pe,t:s,onDuplicate:e=>pe({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>te.mutate(e.id),...t?{onTest:t}:{},lastRunOf:e=>$f(E,e),...a?{onOpenHistory:a}:{}},xe=Yf(W.key,{event:be,summary:U.columnDeps.summary,timelapse:U.columnDeps.timelapse,calendar:U.columnDeps.calendar});return n(Jr,{icon:ce,title:`Rules`,subtitle:G?.blurb??(`blurb`in W?W.blurb:``),actions:G!==void 0||`creatable`in W&&W.creatable?v===`all`?n(he,{children:[n(we,{className:`inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`rules-new-menu`,children:[u(Te,{className:`h-3.5 w-3.5`}),`New rule`,u(m,{className:`h-3 w-3 opacity-80`})]}),u(se,{align:`end`,className:`min-w-[14rem] py-1`,children:hf.map(e=>u(ve,{onClick:()=>_e(e.type),"data-testid":`rules-new-${e.type}`,title:e.hint,children:n(`span`,{className:`flex flex-col gap-0.5`,children:[u(`span`,{className:`font-medium`,children:e.label}),u(`span`,{className:`text-[10px] text-foreground-subtle font-normal`,children:e.hint})]})},e.type))})]}):G===void 0?n(A,{size:`sm`,type:`button`,onClick:me,children:[u(Te,{className:`h-3.5 w-3.5`}),`newRuleLabel`in W?W.newRuleLabel:`New rule`]}):n(A,{size:`sm`,type:`button`,onClick:()=>_e(G.key===`summaries`?`summary`:G.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":G.key===`summaries`?`summary-new`:G.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[u(Te,{className:`h-3.5 w-3.5`}),G.newLabel]}):void 0,children:[u(D,{value:W.key,onValueChange:e=>b(_f(e)??v),children:u(Ce,{className:`mb-3`,children:oe.map(e=>n(ee,{value:e.key,children:[e.label,u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:If(e.key,ae)})]},e.key))})}),u(al,{rules:ie}),U.notices(W.key),(x.isLoading||U.loading)&&u(Qd,{}),x.isError&&!x.isLoading&&u(F,{title:`Failed to load rules`,message:x.error instanceof Error?x.error.message:`Unknown error`,onRetry:()=>void x.refetch()}),!x.isLoading&&!U.loading&&!x.isError&&!U.listFailed(W.key)&&ue.length===0&&u($d,{children:G?.emptyHint??(`emptyHint`in W?W.emptyHint:`No rules yet.`)}),ue.length>0&&u(ef,{columns:xe,rows:ue,rowKey:e=>`${e.family}:${e.id}`,onRowClick:ye,minWidthPx:Lf(W.key)}),g.mode===`form`&&u(dp,{rule:g.rule,...g.seed?{seed:g.seed}:{},targets:C.data??[],actuatable:N,fleet:k,sequences:V,onCreateSequence:async e=>{let t=await H.mutateAsync({sequence:{name:e.name,...e.minDelaySec===void 0?{}:{minDelaySec:e.minDelaySec},actions:[...e.actions]}});return await ne.refetch(),t.sequence.id},catalog:an(w.data?.catalog??[]),taxonomy:w.data?.taxonomy,cameras:P,gateable:M.data??[],gateableScenes:L,initialEditTab:Pt(f.get(`editTab`)??``)??`rule`,onEditTabChange:e=>de(g.mode===`form`?g.rule?.id??`new`:`new`,e),onCancel:fe,onSaved:()=>{fe(),x.refetch()}}),U.overlays]})}function dp({rule:e,seed:t,targets:o,catalog:s,taxonomy:d,cameras:f,gateable:m,gateableScenes:h,actuatable:g,fleet:_,sequences:v,onCreateSequence:y,initialEditTab:x=Fn,onEditTabChange:C,onSaved:w,onCancel:E}){let k=p(),{t:j}=Dt(),N=e!=null&&e.id.length>0,[P]=c(()=>e?yn(e):nn(t?.delivery,t?.conditions)),[F,I]=c(P),[L,R]=c(null),[te,B]=c(null),[re,V]=c(x),H=e=>I(t=>({...t,...e})),U=e?It(e):void 0,ae=l({mutationFn:async()=>{let t=Rt(F,U,s);if(N&&e){let n=hn(F,s);await k.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await k.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:w,onError:e=>R(e instanceof Error?e.message:`Save failed`)}),oe=l({mutationFn:async()=>{let e=Rt(F,U,s);return(await k.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>B(null),onSuccess:e=>B(e),onError:e=>R(e instanceof Error?e.message:`Test failed`)}),se=F.targetIds.map(e=>o.find(t=>t.id===e)?.name??e),W=i({queryKey:[`userManagement`,`listUsers`],queryFn:()=>k.trpcClient.userManagement.listUsers.query()}).data,le=r(()=>(W??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[W]),ue=Vt(F),de=ue===`immediate-grouped`,fe=String(F.groupingSec??20),pe=qt(F).map(e=>({...e,label:e.value===`immediate-grouped`?j(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?j(`notificationRules.grouping.hint`,{n:fe,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}}`,fe):e.hint})),me=pe.find(e=>e.value===ue)?.hint,he=Ur(F,U),ge=mt(F.delivery),_e=rt(F),ve=ct(_e),ye=at(_e),be=dt(_e),xe=i({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,be??[]],enabled:be!==null,queryFn:async()=>{let e=await Promise.all((be??[]).map(e=>k.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),Se=r(()=>{if(be===null||xe.data===void 0)return g;let e=xe.data,t=new Set(Pn(F.deviceScope));return g.filter(n=>e.has(n.id)||t.has(n.id))},[g,be,xe.data,F.deviceScope]),we=be!==null&&xe.isLoading,Te=be!==null&&xe.isError,q=ho(),Ee=e=>({family:`rule`,field:e,kind:_e,delivery:F.delivery,...dn(F)?{systemEventDelivery:`summary`}:{},...F.conditions.systemEvent?{systemEventKinds:[...F.conditions.systemEvent.kinds]}:{}}),De=e=>q.data?uo(q.data,Ee(e)):void 0,Oe=pn(F),ke=Qt(F.conditions,Bt(F.actions,v)),je=F.conditions.identities!==void 0||F.conditions.plates!==void 0,Me=Lr(F.delivery,F.conditions),Ne=Me.some(e=>e.key===re)?re:Fn;return fn(F.delivery)?u(Ae,{open:!0,onOpenChange:e=>!e&&E(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex min-w-0 items-center gap-2`,children:[u(ce,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:N?`Edit ${e?.name}`:`New notification rule`})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:E,children:`Cancel`})]}),L&&u(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:L}),N&&e&&n(`div`,{className:`shrink-0 mb-3 space-y-2`,children:[u(Vc,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(Wc,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??`camera ${String(e)}`})]}),n(D,{value:Ne,onValueChange:e=>{let t=Pt(e);t!==void 0&&(V(t),C?.(t))},className:`flex min-h-0 flex-1 flex-col`,children:[u(Ce,{className:`mb-3 shrink-0`,children:Me.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(z,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-4`,children:[n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),u(O,{value:F.name,onChange:e=>H({name:e.target.value}),placeholder:`e.g. Front door package`})]}),n(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[u(G,{checked:F.enabled,onCheckedChange:e=>H({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),u(T,{value:ue,onChange:e=>{let t=Zt(e.target.value);t&&I(e=>nr(e,t))},options:pe.map(e=>({value:e.value,label:e.label}))}),me&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:me}),de&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:j(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),u(O,{type:`number`,min:5,max:60,step:1,value:fe,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=Sr(e.target.value);t!==void 0&&H({groupingSec:t})}}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:j(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),je&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:j(`notificationRules.grouping.scopedHint`,{n:fe,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,fe)})]}),ue===`immediate`&&je&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:j(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!N&&ye!==void 0&&u(Ns,{family:ye,onChange:e=>I(t=>en(t,e))}),u(ne,{label:`Delivery targets`,targets:o,value:F.targetIds,onChange:e=>I(t=>({...t,targetIds:e})),emptyMessage:`No delivery targets configured. Add one under the Targets tab first.`,testIdPrefix:`rule-target`}),u(ie,{mode:`multi`,options:le,value:F.targetUsers,onChange:e=>H({targetUsers:e}),searchable:!0,creatable:!1,label:`Notify users`,description:`Delivers to the targets each user owns, only for cameras that user can access.`,emptyMessage:`No users to notify.`,placeholder:`Search users…`,testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),n(M,{value:`devices`,className:`space-y-4`,children:[we&&u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:j(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Te&&u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:j(`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.`)}),u(ls,{devices:Se,scope:F.deviceScope,onChange:e=>H({deviceScope:e}),listState:_.state,savedScope:P.deviceScope,exceptOffered:Mt(s,`devicesExclude`,F)})]}),u(M,{value:`actions`,className:`space-y-4`,children:u(jo,{value:F.actions,onChange:e=>H({actions:e}),devices:g,devicesState:_.state,sequences:v,onCreateSequence:y})}),n(M,{value:`advanced`,className:`space-y-4`,children:[u(Js,{catalog:s,delivery:F.delivery,conditions:F.conditions,onConditionsChange:e=>H({conditions:e})}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown (seconds)`}),u(O,{type:`number`,min:0,max:mn,step:1,value:String(F.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=vn(e.target.value);t!==void 0&&H({cooldownSec:t})}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[ge?`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.`:`The shortest gap between two deliveries of this rule, counted as chosen below.`,` `,`Any whole number from 0 (deliver every match) to `,String(mn),` (24 hours).`]})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown counted`}),u(T,{value:F.cooldownScope,onChange:e=>{let t=Ut(e.target.value);t!==void 0&&H({cooldownScope:t})},options:Ft.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Per device: a delivery about one camera (or node) does not hold back another. Whole rule: one delivery per cooldown, whichever device matched.`})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Across object classes`}),u(T,{value:F.cooldownGranularity??`per-class`,onChange:e=>H({cooldownGranularity:Sn(e.target.value)}),options:Br.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`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.`})]})]}),n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:F.snoozeAllowGlobal,onCheckedChange:e=>H({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:ke}),`Anyone may snooze this rule for everyone`]}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`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.`})]}),!ke&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),n(a,{children:[u(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:At.map(e=>{let t=F.snoozeOptions??ir,n=t.includes(e);return u(A,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>H({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Wt(e)},e)})}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:F.snoozeOptions===void 0?`Not set — the notification offers the defaults (${ir.map(Wt).join(`, `)}). A pause opened from a button silences this camera for this class of subject, only for whoever received the notification, and sends no summary.`:F.snoozeOptions.length===0?`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`:`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`}),F.snoozeOptions!==void 0&&u(A,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>H({snoozeOptions:void 0}),children:`Back to the defaults`})]})]}),N&&e&&!ke&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Silence it now`}),u(cc,{ruleId:e.id,ruleName:e.name,exempt:ke,variant:`full`})]})]}),n(M,{value:`notification`,className:`space-y-4`,children:[n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),u(T,{value:String(F.priority),onChange:e=>H({priority:Number(e.target.value)}),options:ar.map(e=>({value:String(e.value),label:e.label}))})]}),!ve.carriesMedia&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:ve.mediaBlurb??`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`}),ve.carriesMedia&&_e===`sensor`&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:j(`notificationRules.media.sensorOneSnapshot`,`A sensor rule attaches one snapshot of the camera automatically — there is no detection to choose a crop, a GIF or a clip around.`)}),ve.carriesMedia&&_e!==`sensor`&&ve.mediaBlurb!==void 0&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:ve.mediaBlurb}),ve.carriesMedia&&_e!==`sensor`&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),u(T,{value:F.mediaAttach,onChange:e=>{let t=En(e.target.value);t&&H({mediaAttach:t})},options:Lt.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Lt.find(e=>e.value===F.mediaAttach)?.description}),n(`div`,{className:`mt-2 space-y-1`,children:[ve.carriesSubjectCrop&&n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:F.mediaZoneCrop,onChange:e=>H({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),`Crop the image to the rule's zone`]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:F.mediaGif,onChange:e=>H({mediaGif:e.target.checked}),className:`accent-primary`}),`Attach a GIF around the event`]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:F.mediaClip,onChange:e=>H({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(F.mediaGif||F.mediaClip)&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),u(T,{value:F.mediaProfile??``,onChange:e=>H({mediaProfile:bn(e.target.value)}),options:Hr.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`A notification is watched on a phone — the cheapest stream is normally the right one, and the high profile only costs CPU to render.`}),u(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),u(T,{value:F.mediaClipSpeed===void 0?``:String(F.mediaClipSpeed),onChange:e=>H({mediaClipSpeed:Gt(e.target.value)}),options:In.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`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.`})]})]}),_e===`sensor`&&ve.carriesMedia&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Linked cameras`}),u(T,{value:F.mediaLinkedCameras??``,onChange:e=>H({mediaLinkedCameras:Yt(e.target.value)}),options:zt.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`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.`})]}),ve.carriesMedia&&_e!==`sensor`&&ve.carriesSubjectCrop&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),u(T,{value:F.mediaFrame??``,onChange:e=>H({mediaFrame:wn(e.target.value)}),options:Rr.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`What the attached still shows. "Automatic" leaves it to the attachment mode above.`})]})]}),n(`div`,{className:`space-y-2`,children:[u(bo,{label:`Notification title`,value:F.templateTitle,onChange:e=>H({templateTitle:e}),vars:De(`title`),testId:`rule-template-title`}),u(bo,{label:`Notification body`,value:F.templateBody,onChange:e=>H({templateBody:e}),vars:De(`body`),multiline:!0,testId:`rule-template-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank for the hub's own wording (editable on the Texts tab).`}),_n(F)!==null&&u(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:_n(F)}),u(xo,{context:Ee(`body`),title:F.templateTitle,body:F.templateBody,testId:`rule-template-preview`})]})]}),n(M,{value:`conditions`,className:`space-y-4`,children:[n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:ge?`Which system events`:zr(F.conditions)??`Conditions`}),F.conditions.audio!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`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).`}),F.conditions.occupancy!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`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.`}),ge&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`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.`}),s.length===0?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):u(Ps,{catalog:dn(F)?s.filter(e=>e.id!==`schedule`):s,taxonomy:d,delivery:F.delivery,conditions:F.conditions,classScope:F.classScope,onClassScopeChange:e=>H({classScope:e}),actions:xr(F.actions),sequenceActionsOf:e=>v.find(t=>t.id===e)?.actions,savedConditions:P.conditions,schedule:F.schedule,deviceIds:sn(F),zoneCameraIds:Zo(F.deviceScope,f),cameras:f,fleet:_,allDevices:g,gateable:m,gateableScenes:h,onConditionsChange:e=>H({conditions:e}),onScheduleChange:e=>H({schedule:e})})]}),ge&&u(Xf,{value:F.systemEventDelivery,family:ye,onChange:e=>H({systemEventDelivery:e}),draft:()=>Rt(F,U,s)}),N&&e&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test this rule for real`}),u(el,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...sn(F)[0]===void 0?{}:{fallbackDeviceId:sn(F)[0]}})]}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`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.`})]}),!ge&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),n(A,{size:`sm`,variant:`outline`,type:`button`,disabled:oe.isPending||!Kt(F,U,new Set(v.map(e=>e.id))),onClick:()=>{R(null),oe.mutate()},children:[oe.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(b,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),te!==null&&u(pp,{delivery:F.delivery,results:te,targetNames:se})]})]})]})]}),Oe.length>0&&n(`div`,{"data-testid":`rule-form-dropped`,className:`mt-3 shrink-0 rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[n(`p`,{className:`text-foreground`,children:[`Saving drops `,Oe.length,` condition`,Oe.length===1?``:`s`,` this kind of rule cannot use:`]}),Oe.map(e=>n(`p`,{children:[u(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),he.length>0&&u(`div`,{"data-testid":`rule-form-problems`,className:`mt-3 shrink-0 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1`,children:he.map(e=>u(`p`,{children:e},e))}),n(`div`,{className:`flex shrink-0 justify-end gap-2 mt-4`,children:[u(A,{variant:`secondary`,size:`sm`,type:`button`,onClick:E,children:`Cancel`}),n(A,{size:`sm`,type:`button`,disabled:ae.isPending||!Kt(F,U,new Set(v.map(e=>e.id))),onClick:()=>{R(null),ae.mutate()},children:[ae.isPending&&u(K,{className:`h-3.5 w-3.5 animate-spin`}),N?`Save changes`:`Create rule`]})]})]})}):u(fp,{rule:e,onCancel:E})}function fp({rule:e,onCancel:t}){let r=Object.keys(e?.conditions??{});return u(Ae,{open:!0,onOpenChange:e=>!e&&t(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,children:[n(`div`,{className:`flex items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[u(ce,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),u(q,{variant:`warning`,children:`read-only`})]}),n(`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:[`This rule uses the trigger `,u(`code`,{children:e?.delivery}),`, which this version of the admin UI cannot author. It is shown exactly as stored and nothing here can change it — editing it with an editor that does not know the trigger would rewrite it. Update the server bundle, or edit this rule from the viewer app.`]}),n(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),u(`dd`,{className:`text-foreground`,children:e?.delivery})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),u(`dd`,{className:`text-foreground`,children:e?.enabled?`yes`:`no`})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),u(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),u(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):`none`})]})]}),u(`div`,{className:`flex justify-end gap-2 mt-4`,children:u(A,{variant:`secondary`,size:`sm`,type:`button`,onClick:t,children:`Close`})})]})})}function pp({delivery:e,results:t,targetNames:r}){if(e===`device-event`)return u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`});if(t.length===0)return u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`No records in the last 60 minutes matched — nothing to evaluate.`});let i=t.filter(e=>e.wouldFire).length;return n(`div`,{className:`mt-2 space-y-1.5`,children:[n(`div`,{className:`text-[11px] text-foreground-subtle`,children:[i,` of `,t.length,` evaluated record`,t.length===1?``:`s`,` would fire.`]}),u(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>n(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?u(I,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(v,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),n(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`object`}),e.wouldFire?n(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,r.join(`, `)||`targets`]}):e.failedCondition&&n(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}t();var mp=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,hp=`block text-[11px] font-medium text-foreground`,gp=[[`notificationRules`,`listSequences`]];function _p(){return{name:``,minDelaySec:``,actions:[Dn()]}}function vp(e){return{id:e.id,name:e.name,minDelaySec:e.minDelaySec===void 0?``:String(e.minDelaySec),actions:[...e.actions]}}function yp(e){let t=[],n=0;for(;n<e.length;){if(e[n].kind===`wait`){t.push({start:n,kind:`wait`,length:1}),n+=1;continue}let r=ko(e,n);t.push({start:n,kind:`cap`,length:r.length}),n+=r.length}return t}function bp(){let e=o(),t=y({}),i=re(),a=Ee(),s=U(),[l,d]=c(null),f=ge({projection:`slim`}),p=De(f),m=r(()=>(f.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[f.data]),h=()=>{e.invalidateQueries({queryKey:gp})},_=async()=>{if(l===null||l.name.trim()===``||l.actions.length===0)return;let e={name:l.name.trim(),...l.minDelaySec===``?{}:{minDelaySec:Number(l.minDelaySec)},actions:l.actions};l.id===void 0?await i.mutateAsync({sequence:e}):await a.mutateAsync({sequenceId:l.id,sequence:e}),d(null),h()},v=t.data?.sequences??[],b=l===null?[]:yp(l.actions);return n(Jr,{icon:ei,title:`Sequences`,subtitle:`Named step lists shared by notification rules and buttons. A rule binds to one by id; two rules sharing a gate share its throttle.`,actions:n(A,{size:`sm`,type:`button`,onClick:()=>d(_p()),children:[u(Te,{className:`h-3.5 w-3.5`}),` New sequence`]}),children:[l!==null&&n(`div`,{className:`mb-4 space-y-3 rounded-md border border-border p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-2`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:hp,children:`Name`}),u(O,{className:`mt-1`,value:l.name,onChange:e=>d({...l,name:e.target.value})})]}),n(`div`,{className:`w-28`,children:[u(`label`,{className:hp,children:`Min delay (s)`}),u(`input`,{type:`number`,min:0,className:mp,value:l.minDelaySec,onChange:e=>d({...l,minDelaySec:e.target.value})})]})]}),n(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[b.map(e=>{let t=l.actions[e.start];if(e.kind===`wait`&&t.kind===`wait`)return u(xp,{step:t,devices:m,listState:p.state,fleet:p,onChange:t=>d({...l,actions:l.actions.map((n,r)=>r===e.start?t:n)}),onRemove:()=>d({...l,actions:l.actions.filter((t,n)=>n!==e.start)})},`s-${String(e.start)}`);let r=ko(l.actions,e.start);return n(`div`,{className:`flex flex-wrap items-start gap-2`,children:[n(`div`,{className:`w-24`,children:[u(`label`,{className:hp,children:`Step`}),n(`select`,{className:mp,value:`cap`,onChange:t=>{t.target.value===`wait`&&d({...l,actions:[...l.actions.slice(0,e.start),{kind:`wait`,seconds:5},...l.actions.slice(e.start+e.length)]})},children:[u(`option`,{value:`cap`,children:`Do`}),u(`option`,{value:`wait`,children:`Wait`})]})]}),u(Yr,{value:r.wire,devices:m,listState:p.state,fleet:p,allowMultiSameFamily:!0,onChange:t=>{let n=Do(t);d({...l,actions:[...l.actions.slice(0,e.start),...n,...l.actions.slice(e.start+e.length)]})}}),u(A,{size:`sm`,variant:`ghost`,type:`button`,title:`Remove`,onClick:()=>d({...l,actions:[...l.actions.slice(0,e.start),...l.actions.slice(e.start+e.length)]}),children:u(g,{className:`h-3.5 w-3.5`})})]},`s-${String(e.start)}`)}),n(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d({...l,actions:[...l.actions,Dn()]}),children:[u(Te,{className:`h-3.5 w-3.5`}),` Step`]})]}),n(`div`,{className:`flex gap-2`,children:[u(A,{size:`sm`,type:`button`,onClick:()=>void _(),children:`Save`}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d(null),children:`Cancel`})]})]}),t.isPending?u(`p`,{className:`text-sm text-foreground-subtle`,children:`Loading…`}):v.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-sm text-foreground-subtle`,children:`No sequences yet. Create one, then bind it from a rule's Actions tab.`}):u(`ul`,{className:`space-y-2`,children:v.map(e=>n(`li`,{className:`flex flex-wrap items-center justify-between gap-2 rounded-md border border-border px-3 py-2`,children:[n(`div`,{className:`min-w-0`,children:[u(`div`,{className:`text-sm font-medium text-foreground`,children:e.name}),n(`div`,{className:`text-[11px] text-foreground-subtle`,children:[e.actions.length,` step`,e.actions.length===1?``:`s`,e.minDelaySec===void 0?``:` · min delay ${String(e.minDelaySec)}s`]})]}),n(`div`,{className:`flex gap-1`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d(vp(e)),children:`Edit`}),u(A,{size:`sm`,variant:`ghost`,type:`button`,title:`Delete`,onClick:()=>{s.mutateAsync({sequenceId:e.id}).then(h)},children:u(g,{className:`h-3.5 w-3.5`})})]})]},e.id))})]})}function xp({step:e,devices:t,listState:r,fleet:i,onChange:a,onRemove:o}){return n(`div`,{className:`flex flex-wrap items-start gap-2`,children:[n(`div`,{className:`w-24`,children:[u(`label`,{className:hp,children:`Step`}),n(`select`,{className:mp,value:`wait`,onChange:n=>a(n.target.value===`wait`?{kind:`wait`,seconds:e.seconds}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[u(`option`,{value:`cap`,children:`Do`}),u(`option`,{value:`wait`,children:`Wait`})]})]}),n(`div`,{className:`w-28`,children:[u(`label`,{className:hp,children:`Seconds`}),u(`input`,{type:`number`,min:0,max:300,className:mp,value:e.seconds,onChange:e=>a({kind:`wait`,seconds:Number(e.target.value)})})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})}var Sp=[{value:`object-event`,label:`Object detection`,hint:`A detection on a live track — what an "Immediate" rule sees.`},{value:`track-end`,label:`Track end`,hint:`A finalised track: importance, dwell and label confidence exist only here.`},{value:`device-event`,label:`Device event`,hint:`A doorbell press or a linked sensor changing state.`},{value:`package-event`,label:`Package event`,hint:`A parcel delivered or picked up.`},{value:`audio-event`,label:`Audio event`,hint:`A classified audio episode. Rides the Immediate delivery, gated by the audio classes.`},{value:`occupancy-event`,label:`Occupancy edge`,hint:`A zone count crossing its threshold. Rides the Device-event delivery.`}];function Cp(e){return Sp.find(t=>t.value===e)?.value}function wp(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Tp(e){return``}var Ep={x:.25,y:.25,w:.5,h:.5},Dp={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Op(){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:Ep,occupancy:Dp,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function kp(e){return e.deviceId!==null}function Ap(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function jp(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Mp(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 Np(e){if(e.deviceId===null)return null;let t=e.trigger,n=jp(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:Pp(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 Pp(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 Fp(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Ip(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 Lp(e){let t=Op(),n=e.conditions,r=Ip(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:Fp(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Fp(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Fp(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:Tp(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Rp(n.occupancy)},onlyRuleId:e.id}}function Rp(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 zp(e){let t=[];return e.conditions.deviceState!==void 0&&t.push({conditionId:`deviceState`,note:`This rule is gated on device #${e.conditions.deviceState.deviceId} being in a given state. The gate reads the REAL device — put it in that state first, or the simulation fails closed exactly as production would.`}),e.conditions.scene!==void 0&&t.push({conditionId:`scene`,note:`This rule is gated on a scene being ${e.conditions.scene.requiredState}. The gate reads the scene's REAL state — put the scene in that state first (or reset it), or the simulation fails closed exactly as production would.`}),e.conditions.customZones!==void 0&&e.conditions.customZones.length>0&&t.push({conditionId:`customZones`,note:`This rule matches viewer-drawn polygons against the subject bbox. The bbox below is enabled but centred — move it over the polygon, or the condition fails.`}),t}function Bp(e){return{form:Lp(e),caveats:zp(e),ruleName:e.name}}var Vp=null;function Hp(e){Vp=e}function Up(){return Vp}function Wp(){Vp=null}var Gp=[`n/a`,`clear`,`suppressed`,`bypassed`],Kp=[`live`,`none`,`unavailable`,`unattachable`];function qp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jp(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Yp(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Xp(e){if(!qp(e))return null;let t=Jp(e,`ruleId`),n=Jp(e,`ruleName`),r=Jp(e,`cooldown`),i=Gp.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Jp(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Yp(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:Yp(e,`targetIds`)}}function Zp(e){if(!qp(e))return null;let t=Jp(e,`recordId`),n=Jp(e,`delivery`),r=Jp(e,`still`),i=Kp.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=Xp(e);t!==null&&o.push(t)}let s=Jp(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Yp(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Qp(e){if(e.droppedBy!==void 0)return`Dropped before evaluation (${e.droppedBy}) — no rule was consulted.`;if(e.candidates===0)return`No enabled rule declares the "${e.delivery}" delivery, so nothing was evaluated.`;let t=e.outcomes.filter(e=>e.matched).length,n=e.outcomes.reduce((e,t)=>e+t.enqueued,0);return t===0?`${e.candidates} candidate rule${e.candidates===1?``:`s`} evaluated, none matched.`:`${t} of ${e.candidates} candidate rule${e.candidates===1?``:`s`} matched — ${n} notification${n===1?``:`s`} enqueued.`}var $p=new Set([`sensor`,`control`,`custom`]);function em({form:e,cameras:t,taxonomy:r,kinds:i,kindsLoading:a,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=nt(`classes`,r);if(e.trigger===`device-event`)return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),u(tm,{form:e,kinds:i,loading:a,onPatch:o})]});if(e.trigger===`audio-event`){let r=i.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[u(`label`,{className:J,children:`Audio classes`}),u(kt,{options:r,value:e.classNames,onChange:e=>o({classNames:e}),loading:a,emptyHint:e.deviceId===null?`Pick a camera first — the audio vocabulary is per camera.`:`This camera advertises no audio kinds. The audio classifier is probably off for it.`,placeholder:`Audio class id…`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Zones`}),u(Vr,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]})]})}return e.trigger===`occupancy-event`?n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),u(nm,{form:e,cameras:t,taxonomy:r,onPatch:o})]}):n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[u(`label`,{className:J,children:`Detected classes`}),c===null?u(kn,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):u(Fr,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Zones the subject is in`}),u(Vr,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),u(T,{value:e.packagePhase,options:[{value:``,label:`— none —`},{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`}],onChange:e=>o({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function tm({form:e,kinds:t,loading:r,onPatch:i}){let o=t.filter(e=>$p.has(e.category)),s=o.find(t=>t.kind===e.sensorKind);return n(a,{children:[n(`div`,{children:[u(`label`,{className:J,children:`Event kind`}),u(T,{value:e.sensorKind,options:[{value:``,label:r?`Loading kinds…`:`— pick a kind —`},...o.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=o.find(t=>t.kind===e.target.value);i({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!r&&o.length===0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.deviceId===null?`Pick a camera first — sensor and control kinds come from the devices linked to it.`:`This camera has no linked sensor or control device, so it can produce no device event. Link one on the camera page first.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:J,children:`Source device`}),u(O,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>i({sourceDeviceId:Ap(e.target.value)??null})}),u(`p`,{className:Bn,children:s===void 0?`The linked device whose state changed. Filled in for you when you pick a kind.`:`Filled in from "${s.label}" — contributed by device #${s.source.deviceId} via the ${s.source.capName} capability.`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Event type token`}),u(O,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>i({eventType:e.target.value})}),u(`p`,{className:Bn,children:`Only event-emitter sources carry one. A passive sensor emits none, and a rule gating on a token would fail closed for it.`})]})]})]})}function nm({form:e,cameras:t,taxonomy:r,onPatch:i}){let o=e.deviceId===null?[]:[e.deviceId],s=nt(`occupancy`,r),c=s===null?[]:s.groups.flatMap(e=>e.options),l=e.occupancy,d=e=>i({occupancy:{...l,...e}});return n(a,{children:[n(`div`,{children:[u(`label`,{className:J,children:`Zone`}),u(Vr,{deviceIds:o,cameras:t,value:l.zoneId===``?[]:[l.zoneId],onChange:e=>d({zoneId:e[e.length-1]??``})}),u(`p`,{className:Bn,children:`Leave empty for the whole frame.`})]}),n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:J,children:`Class`}),u(T,{value:l.className,options:[{value:``,label:`— any class —`},...c.map(e=>({value:e.value,label:e.label}))],onChange:e=>d({className:e.target.value})})]}),n(`div`,{className:`flex flex-wrap items-end gap-3`,children:[n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count now`,u(O,{type:`number`,min:0,className:`w-20`,value:String(l.count),onChange:e=>d({count:Ap(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,u(O,{type:`number`,min:0,className:`w-20`,value:String(l.previousCount),onChange:e=>d({previousCount:Ap(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,u(O,{type:`number`,min:1,className:`w-20`,value:String(l.threshold),onChange:e=>d({threshold:Ap(e.target.value)??1})})]}),n(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[u(G,{checked:l.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function rm({form:e,cameras:t,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId];return n(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[u(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Advanced`}),n(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:e.crossingEnabled,onCheckedChange:e=>r({crossingEnabled:e}),"aria-label":`zone crossing`}),`This event is a confirmed zone crossing`]}),e.crossingEnabled&&n(`div`,{className:`mt-1 space-y-1.5`,children:[u(`div`,{className:`max-w-[12rem]`,children:u(T,{value:e.crossingDirection,options:[{value:`enter`,label:`Entered the zone`},{value:`exit`,label:`Left the zone`}],onChange:e=>r({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),u(Vr,{deviceIds:i,cameras:t,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>r({crossingZoneId:e[e.length-1]??``})})]})]}),n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:e.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),u(`p`,{className:Bn,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&u(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,u(O,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:n=>r({bbox:{...e.bbox,[t]:Ap(n.target.value)??0}})})]},t))})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:J,children:`Happened at`}),n(`div`,{className:`flex items-center gap-2`,children:[u(O,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:Mp(Date.now())}),children:`Set`}):u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:`Now`})]}),u(`p`,{className:Bn,children:`Empty = now. Set it to a time inside (or outside) a rule's schedule window to test the schedule without waiting for the hour.`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Detection source`}),u(T,{value:e.source,options:[{value:``,label:`— unset (reads as pipeline) —`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`},{value:`audio`,label:`Audio`}],onChange:e=>{let t=e.target.value;r({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function im({checked:e,label:t,hint:r,danger:i=!1,onChange:a}){return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:e,onCheckedChange:a,"aria-label":t}),t,i&&u(q,{variant:`danger`,children:`actuates devices`})]}),u(`p`,{className:Bn,children:r})]})}t();var am={live:`A live snapshot of the camera was taken and attached.`,none:`No still was requested.`,unavailable:`A still was requested but the camera could not produce one.`,unattachable:`This trigger cannot carry a still at all — an audio or occupancy notification freezes no media owner, so it ships text-only in production too. This is not a limit of the test.`},om={"n/a":`The rule did not match, so no cooldown was consulted.`,clear:`No cooldown was in effect — the rule was free to fire.`,suppressed:`A cooldown from an earlier fire silenced this one. Re-run with "Ignore cooldown".`,bypassed:`A cooldown was in effect and was deliberately ignored for this run.`};function sm({result:e,targetName:t}){return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[u(`p`,{className:`text-xs font-medium text-foreground`,children:Qp(e)}),n(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[u(cm,{recordId:e.recordId}),n(`span`,{children:[`delivery `,u(`span`,{className:`text-foreground`,children:e.delivery})]}),n(`span`,{children:[`candidates `,u(`span`,{className:`text-foreground`,children:e.candidates})]}),n(`span`,{title:am[e.still],children:[`still `,u(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&n(q,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&u(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>u(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`No rule was evaluated. Either no enabled rule declares the`,` `,u(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):u(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>u(lm,{outcome:e,targetName:t},e.ruleId))})]})}function cm({recordId:e}){let[t,r]=c(!1);return n(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[u(`code`,{className:`text-[10px] text-foreground`,children:e}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)},()=>r(!1))},title:`Copy record id`,children:u(B,{className:`h-3 w-3`})}),t&&u(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function lm({outcome:e,targetName:t}){return n(`li`,{className:`space-y-1 px-2.5 py-2`,children:[n(`div`,{className:`flex items-center gap-2`,children:[e.matched?u(I,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(v,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),n(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:om[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&u(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?`Did not match. The engine reported no failing condition id.`:n(a,{children:[`Did not match — first failing condition`,` `,u(`code`,{className:`text-foreground`,children:e.failedCondition}),`.`]})}),e.matched&&n(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[e.enqueued,` outbox row`,e.enqueued===1?``:`s`,` enqueued`,e.targetIds.length>0?` → ${e.targetIds.map(t).join(`, `)}`:` — no target resolved, so nothing will be delivered`,`.`]}),e.matchedOn!==void 0&&e.matchedOn.length>0&&n(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:[`matched on: `,e.matchedOn.join(`, `)]})]})}t();var um=`pipeline-analytics`,dm=`nc.injectTestEvent`;function fm(){let e=p(),[t,a]=c(()=>Up()?.form??Op()),[o,s]=c(()=>Up()?.caveats??[]),[f,m]=c(()=>Up()?.ruleName??null);d(()=>Wp(),[]);let[h,g]=c(null),[_,v]=c(!1),[y,S]=c(null),C=e=>a(t=>({...t,...e})),w=ge({projection:`slim`}),E=i({queryKey:sp,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),D=i({queryKey:ap,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),k=i({queryKey:op,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),j=t.deviceId,ee=i({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:j}],enabled:j!==null,staleTime:6e4,queryFn:async()=>j===null?[]:(await e.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[j]})).flatMap(e=>[...e.kinds])}),M=r(()=>(w.data??[]).filter(e=>e.type===Be.Camera).map(e=>({id:e.id,name:e.name})),[w.data]),N=E.data?.taxonomy,P=ee.data??[],I=r(()=>{let e=new Map;for(let t of k.data??[])e.set(t.id,t.name);return e},[k.data]),L=l({mutationFn:async()=>{let n=Np(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:um,action:dm,input:n})},onMutate:()=>{g(null),v(!1),S(null)},onSuccess:e=>{let t=Zp(e);g(t),v(t===null)},onError:e=>S(e instanceof Error?e.message:`The simulation failed.`)}),R=wp(t.trigger),z=D.data?.find(e=>e.id===t.onlyRuleId);return n(Jr,{icon:b,title:`Simulate an event`,subtitle:`Inject a synthetic detection, doorbell press or occupancy edge and see exactly which rules match it, which condition each one fails on, and what would be delivered. Nothing is persisted — no track, no event row, no media.`,children:[w.isError&&u(F,{title:`Failed to load cameras`,message:w.error instanceof Error?w.error.message:`Unknown error`,onRetry:()=>void w.refetch()}),f!==null&&n(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:[`Seeded from the rule `,u(`span`,{className:`font-medium`,children:f}),`. Only that rule will be evaluated — clear "Evaluate only one rule" below to run the whole rule set.`]}),o.length>0&&u(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:o.map(e=>n(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[u(je,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId))}),n(x,{className:`space-y-4`,children:[n(`div`,{children:[u(`label`,{className:J,children:`Rule to simulate`}),u(T,{"data-testid":`simulate-seed-rule`,value:t.onlyRuleId,options:[{value:``,label:`— pick a rule to prefill trigger + conditions —`},...(D.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.delivery}`}))],onChange:e=>{let t=e.target.value;if(t.length===0){a(Op()),s([]),m(null);return}let n=D.data?.find(e=>e.id===t);if(n===void 0){C({onlyRuleId:t});return}a(Lp(n)),s(zp(n)),m(n.name)}}),u(`p`,{className:Bn,children:`Picks the trigger that rule listens for and fills the fields from its conditions. Edit any value below, then inject.`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Camera`}),u(T,{"data-testid":`simulate-camera`,value:t.deviceId===null?``:String(t.deviceId),options:[{value:``,label:M.length===0?`Loading cameras…`:`— pick a camera —`},...M.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{C({deviceId:Ap(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),u(`p`,{className:Bn,children:`The camera the event is attributed to — what a notification shows.`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Trigger`}),u(T,{"data-testid":`simulate-trigger`,value:t.trigger,options:Sp.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=Cp(e.target.value);if(!n)return;let r=Tp(t.trigger);C({trigger:n,source:t.source===``||t.source===r?Tp(n):t.source})}}),n(`p`,{className:Bn,children:[Sp.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,u(`span`,{className:`text-foreground`,children:R}),` are candidates.`]})]}),u(em,{form:t,cameras:M,taxonomy:N,kinds:P,kindsLoading:ee.isLoading,onPatch:C}),n(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[u(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),n(`div`,{className:`mt-2 space-y-3`,children:[u(`p`,{className:Bn,children:`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.`}),n(`div`,{children:[u(`label`,{className:J,children:`Label (identity name / plate / subclass)`}),u(O,{value:t.label,placeholder:`e.g. Marco, AB123CD`,onChange:e=>C({label:e.target.value})})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:J,children:`Detection confidence`}),u(vr,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>C({confidence:e})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Label-match confidence`}),u(vr,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>C({labelConfidence:e})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Importance`}),u(vr,{value:t.importance,min:0,max:1,step:.05,onChange:e=>C({importance:e})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Dwell (seconds)`}),u(vr,{value:t.dwellSeconds,min:0,step:1,onChange:e=>C({dwellSeconds:e})})]})]})]})]}),u(rm,{form:t,cameras:M,onPatch:C}),n(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),u(im,{checked:t.bypassCooldown,label:`Ignore the cooldown`,hint:`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`,onChange:e=>C({bypassCooldown:e})}),u(im,{checked:t.bypassMute,label:`Ignore mutes and snoozes`,hint:`A muted camera or a snoozed rule drops the event before any rule is consulted.`,onChange:e=>C({bypassMute:e})}),u(im,{checked:t.runActions,danger:!0,label:`Run the rule's actions — this actuates real devices`,hint:`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`,onChange:e=>C({runActions:e})}),n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:J,children:`Still image`}),u(T,{value:t.still,options:[{value:`live`,label:`Live snapshot of the camera`},{value:`none`,label:`No image`}],onChange:e=>C({still:e.target.value===`none`?`none`:`live`})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Evaluate only one rule`}),u(T,{value:t.onlyRuleId,options:[{value:``,label:`— every enabled rule —`},...(D.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>C({onlyRuleId:e.target.value})}),t.onlyRuleId.length>0&&z===void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,u(`code`,{children:t.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),y!==null&&u(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:y}),n(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[u(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`}),n(A,{size:`sm`,type:`button`,disabled:L.isPending||!kp(t),onClick:()=>L.mutate(),children:[L.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(b,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),_&&u(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:`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&&u(sm,{result:h,targetName:e=>I.get(e)??e})]})}var pm=e=>typeof e==`string`&&e.length>0;function mm(e){return{levels:e.levels,formats:e.format,bodyMaxLen:e.bodyMaxLen,attachmentSlots:e.attachments.mediaTypes,attachmentMode:e.attachments.mode,attachmentMax:e.attachments.max,attachmentMaxBytes:e.attachments.maxBytes,maxActions:e.actions,showActions:e.actions>0,showClickUrl:e.clickUrl,showSound:e.sound,showTtl:e.ttl,showTag:!0}}function hm(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function gm(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];pm(i)&&n.push({mediaType:r,url:i})}return n}function _m(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=pm(r.label),i=pm(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:`Action ${n.length+1}`,...i?{url:r.url}:{}})}return n}function vm(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=gm(e,t.attachmentUrls),i=_m(e,t.actions),a=e.ttl&&pm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:hm(e,t.format),priority:ym(t.priority),...pm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&pm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&pm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...pm(t.tag)?{tag:t.tag}:{}}}function ym(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function bm(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 xm(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Sm={image:f(`/addon/notifiers/samples/image`),video:f(`/addon/notifiers/samples/video`),gif:f(`/addon/notifiers/samples/gif`),audio:f(`/addon/notifiers/samples/audio`),icon:f(`/addon/notifiers/samples/icon`)};function Cm(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function wm(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])Cm(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function Tm(e,t,n){let r=xm(e);return Cm(e,t)?{...r,body:n,attachmentUrls:{[t]:Sm[t]}}:{...r,body:n}}function Em(e,t){let n=xm(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return Tm(e,`image`,`Test notification with an image.`);case`gif`:return Tm(e,`gif`,`Test notification with an animation.`);case`video`:return Tm(e,`video`,`Test notification with a video.`);case`audio`:return Tm(e,`audio`,`Test notification with audio.`);case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:`Action ${t+1}`,url:`/`}));return{...n,title:`CamStack`,body:`Test notification with action buttons.`,actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=bm(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}t();var Dm={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},Om=`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`,km=`block text-[11px] font-medium text-foreground mb-1`;function Am({target:e,kind:t,open:i,onClose:a}){let o=p(),s=r(()=>mm(t.caps),[t.caps]),d=r(()=>wm(t.caps),[t.caps]),[f,m]=c(()=>xm(t.caps)),[h,g]=c(null),_=r(()=>vm(t.caps,f),[t.caps,f]),v=f.body.length,y=v>s.bodyMaxLen,b=e=>m(t=>({...t,...e})),x=l({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:vm(t.caps,f)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:`Test failed`})}),T=e=>{m(Em(t.caps,e)),g(null)},E=(e,t,n)=>{let r=f.actions.length>0?[...f.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},b({actions:r})};return u(Ae,{open:i,onOpenChange:e=>!e&&a(),children:n(S,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[u(w,{children:n(C,{children:[`Test "`,e.name,`" (`,t.label,`)`]})}),n(z,{className:`space-y-4 pr-1`,children:[u(`div`,{className:`flex flex-wrap gap-1.5`,children:d.map(e=>u(A,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>T(e),children:Dm[e]},e))}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.levels.length>0&&n(`div`,{children:[u(`label`,{className:km,children:`Level`}),n(`select`,{className:Om,value:f.level,onChange:e=>b({level:e.target.value}),children:[u(`option`,{value:``,children:`— derive from priority —`}),s.levels.map(e=>n(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=s.levels.find(e=>e.id===f.level);return e?n(`div`,{className:`mt-1 space-y-1`,children:[e.description&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),n(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&u(q,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&u(q,{variant:`info`,children:`silent`}),e.flags?.noPush&&u(q,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&n(`p`,{className:`text-[10px] text-warning`,children:[`Requires target config: `,e.requires.join(`, `)]})]}):null})()]}),n(`div`,{children:[n(`label`,{className:km,children:[`Priority (ordinal): `,f.priority]}),u(`input`,{type:`range`,min:1,max:5,step:1,value:f.priority,onChange:e=>b({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),s.formats.length>0&&n(`div`,{children:[u(`label`,{className:km,children:`Format`}),u(`div`,{className:`flex flex-wrap gap-2`,children:s.formats.map(e=>n(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:f.format===e,onChange:()=>b({format:e})}),e]},e))})]}),n(`div`,{children:[u(`label`,{className:km,children:`Title`}),u(`input`,{className:Om,value:f.title,onChange:e=>b({title:e.target.value})})]}),n(`div`,{children:[n(`label`,{className:km,children:[`Body`,` `,n(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,s.bodyMaxLen,y?` — overflow`:``,`)`]})]}),u(`textarea`,{className:`${Om} min-h-[80px] resize-y`,value:f.body,onChange:e=>b({body:e.target.value})})]}),s.attachmentSlots.length>0&&n(`div`,{children:[n(`label`,{className:km,children:[`Attachments`,` `,n(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,s.attachmentMode,`, max `,s.attachmentMax,s.attachmentMaxBytes?`, ≤${Math.round(s.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),u(`div`,{className:`space-y-1.5`,children:s.attachmentSlots.map(e=>n(`div`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),u(`input`,{className:Om,placeholder:`${e} URL`,value:f.attachmentUrls[e]??``,onChange:t=>b({attachmentUrls:{...f.attachmentUrls,[e]:t.target.value}})})]},e))})]}),s.showActions&&n(`div`,{children:[n(`label`,{className:km,children:[`Actions (up to `,s.maxActions,`)`]}),u(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(s.maxActions,3)},(e,t)=>n(`div`,{className:`flex items-center gap-2`,children:[u(`input`,{className:Om,placeholder:`label`,value:f.actions[t]?.label??``,onChange:e=>E(t,`label`,e.target.value)}),u(`input`,{className:Om,placeholder:`url`,value:f.actions[t]?.url??``,onChange:e=>E(t,`url`,e.target.value)})]},t))})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.showClickUrl&&n(`div`,{children:[u(`label`,{className:km,children:`Click URL`}),u(`input`,{className:Om,value:f.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),s.showSound&&n(`div`,{children:[u(`label`,{className:km,children:`Sound`}),u(`input`,{className:Om,value:f.sound,onChange:e=>b({sound:e.target.value})})]}),s.showTtl&&n(`div`,{children:[u(`label`,{className:km,children:`TTL (seconds)`}),u(`input`,{className:Om,type:`number`,value:f.ttl,onChange:e=>b({ttl:e.target.value})})]}),s.showTag&&n(`div`,{children:[u(`label`,{className:km,children:`Tag`}),u(`input`,{className:Om,value:f.tag,onChange:e=>b({tag:e.target.value})})]})]}),h&&u(jm,{result:h}),n(`details`,{className:`text-[10px]`,children:[u(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),u(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),n(te,{children:[u(A,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),n(A,{size:`sm`,type:`button`,disabled:x.isPending||f.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Ne,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function jm({result:e}){let t=e.renderedAs;return n(`div`,{className:`rounded-md border px-3 py-2 text-xs ${e.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[n(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?u(I,{className:`h-3.5 w-3.5 text-success`}):u(v,{className:`h-3.5 w-3.5 text-danger`}),u(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&u(`p`,{className:`mt-1 text-danger`,children:e.error}),t&&n(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[u(`dt`,{children:`Resolved level`}),u(`dd`,{className:`text-foreground`,children:t.level}),u(`dt`,{children:`Format sent`}),u(`dd`,{className:`text-foreground`,children:t.format}),u(`dt`,{children:`Attachments sent`}),u(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),u(`dt`,{children:`Actions sent`}),u(`dd`,{className:`text-foreground`,children:t.actionsSent}),u(`dt`,{children:`Truncated`}),u(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),u(`dt`,{children:`Dropped`}),u(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function Mm(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.addonId);e?e.push(r):(n.set(r.addonId,[r]),t.push(r.addonId))}return t.map(e=>({addonId:e,kinds:n.get(e)??[]}))}function Nm(e){let t=[],n=e=>{for(let r of e){if(r.type===`password`){t.push(r.key);continue}if(r.type===`group`){n(r.fields);continue}if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields)}};for(let t of e.sections)n(t.fields);return t}function Pm(e){let t=new Map,n=e=>{for(let r of e)if(r.type===`group`)n(r.fields);else if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields);else r.type!==`separator`&&t.set(r.key,r.label)};for(let t of e.sections)n(t.fields);return t}var Fm=`••••••••`;function Im(e){return e===`••••••••`||e===`__redacted__`}function Lm(e,t,n){let r=new Set(n),i={};for(let[t,n]of Object.entries(e)){if(!r.has(t)){i[t]=n;continue}n==null||n===``||Im(n)||(i[t]=n)}return i}function Rm(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e)){if(!n.has(t)){r[t]=i;continue}r[t]=i!=null&&i!==``?Fm:``}return r}function zm(e){return{...e}}var Bm=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function Vm(e){return Bm.some(t=>e.includes(t))}function Hm(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function Um(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&Hm(e[n])!==Hm(t[n]))}function Wm(e,t,n,r){if(r===void 0)return Um(e,t,n);let i=new Set(n),a=Lm(e,t,n);return r.filter(n=>i.has(n)?n in a:Hm(e[n])!==Hm(t[n]))}function Gm(e,t,n){let r=Lm(e,t,n);return n.filter(e=>!(e in r))}function Km(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:Km(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Km(e.fields,t)}))}:e)}function qm(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:Km(e.fields,n)}))}}function Jm(e){let t=e.trim();return t.length===0?`Copy`:`${t} Copy`}function Ym(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,placeholder:e.placeholder??`•••••••• (leave blank to keep)`}:e.type===`group`?{...e,fields:Ym(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Ym(e.fields,t)}))}:e)}function Xm(e,t,n){let r=new Set(n.filter(e=>{let n=t[e];return n!=null&&n!==``}));return r.size===0?e:{...e,sections:e.sections.map(e=>({...e,fields:Ym(e.fields,r)}))}}var Zm=`targets`,Qm=`target`,$m=`kind`,eh=[Qm,$m];function th(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Zm),n.set(Qm,t),n.delete($m),n}function nh(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Zm),n.set(Qm,`new`),t===null||t.length===0?n.delete($m):n.set($m,t),n}function rh(e){let t=new URLSearchParams(e);return t.delete(Qm),t.delete($m),t}function ih({refusal:e,edited:t,reenter:r}){let i=r.length>0?`Re-type: ${r.join(`, `)}.`:null;return e===null?t.length===0||i===null?null:n(`p`,{className:`text-[11px] text-warning`,"data-testid":`target-secret-reenter`,children:[`You changed `,t.join(`, `),`. If that changes where this target sends, the hub will not reuse the stored secret. `,i]}):n(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-secret-refusal`,role:`alert`,children:[u(`p`,{className:`font-semibold`,children:`The hub needs the secret again — nothing was saved.`}),u(`p`,{className:`mt-1`,children:e}),i===null?null:u(`p`,{className:`mt-1 font-medium`,children:i})]})}t();var ah=[`notificationOutput`,`listTargets`],oh=[`notificationOutput`,`listTargetKinds`],sh=[`userManagement`,`listUsers`],ch=`ownerUserId`;function lh(e){let t=e.config[ch];return typeof t==`string`&&t.length>0?t:null}function uh(e){return[{key:`name`,header:`Target`,render:t=>{let r=e.kindByKey.get(t.kind);return n(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:r?.label??t.kind,children:u(dh,{kind:r,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),u(tf,{name:t.name,enabled:t.enabled,...r===void 0?{}:{onOpen:()=>e.onOpen(t,r)}})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByKey.get(t.kind)?.label??t.kind})},{key:`owner`,header:`Owner`,nowrap:!0,render:t=>{let n=lh(t);return n===null?u(q,{variant:`default`,children:`system`}):u(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let r=e.kindByKey.get(t.kind);return n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(t),title:`Test`,children:u(Ne,{className:`h-3.5 w-3.5`})}),u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onDuplicate(t,r),title:`Duplicate`,children:u(B,{className:`h-3.5 w-3.5`})}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:u(g,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function dh({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?u(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):u(`span`,{className:n,children:e?.icon??`🔔`})}function fh(){let t=p(),[a,o]=Gr(),[s,f]=c({mode:`closed`}),[m,h]=c(null),g=e(null),_=i({queryKey:ah,queryFn:()=>t.trpcClient.notificationOutput.listTargets.query({})}),v=i({queryKey:oh,queryFn:async()=>(await t.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),y=r(()=>v.data??[],[v.data]),b=r(()=>{let e=new Map;for(let t of y)e.set(t.kind,t);return e},[y]),x=i({queryKey:sh,queryFn:()=>t.trpcClient.userManagement.listUsers.query()}),S=r(()=>{let e=new Map;for(let t of x.data??[])e.set(t.id,t.username);return e},[x.data]),C=l({mutationFn:e=>t.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:e.target.addonId,targetId:e.target.id,enabled:e.enabled}),onSuccess:()=>void _.refetch()}),w=l({mutationFn:e=>t.trpcClient.notificationOutput.deleteTarget.mutate({addonId:e.addonId,targetId:e.id}),onSuccess:()=>void _.refetch()}),T=m?b.get(m.kind):void 0,E=()=>{let e=a.get(Qm);e!==null&&(g.current=e),f({mode:`closed`}),o(rh(a),{replace:!0})},D=()=>{g.current=`new`,f({mode:`pick-kind`}),o(nh(a,null),{replace:!0})},O=e=>{g.current=`new:${e.kind}`,f({mode:`form`,kind:e,target:null,cloneFrom:null}),o(nh(a,e.kind),{replace:!0})},k=(e,t)=>{g.current=e.id,f({mode:`form`,kind:t,target:e,cloneFrom:null}),o(th(a,e.id),{replace:!0})};return d(()=>{if(s.mode!==`closed`)return;let e=a.get(Qm);if(e===null){g.current=null;return}if(g.current===e)return;if(e===`new`){let e=a.get($m);if(e===null||e.length===0){g.current=`new`,f({mode:`pick-kind`});return}let t=b.get(e);if(t===void 0)return;g.current=`new:${e}`,f({mode:`form`,kind:t,target:null,cloneFrom:null});return}let t=_.data?.find(t=>t.id===e);if(t===void 0)return;let n=b.get(t.kind);n!==void 0&&(g.current=e,f({mode:`form`,kind:n,target:t,cloneFrom:null}))},[s.mode,a,_.data,b]),n(Jr,{icon:Oe,title:`Notification Targets`,subtitle:`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.`,actions:n(A,{size:`sm`,type:`button`,onClick:D,children:[u(Te,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[_.isLoading&&u(Qd,{}),_.isError&&!_.isLoading&&u(F,{title:`Failed to load targets`,message:_.error instanceof Error?_.error.message:`Unknown error`,onRetry:()=>void _.refetch()}),!_.isLoading&&!_.isError&&(_.data??[]).length===0&&u($d,{children:`No notification targets yet. Click "Add target" to configure one.`}),(_.data??[]).length>0&&u(ef,{columns:uh({kindByKey:b,userNameById:S,onToggle:(e,t)=>C.mutate({target:e,enabled:t}),onTest:h,onOpen:k,onDuplicate:(e,t)=>{g.current=`new:${t.kind}`,f({mode:`form`,kind:t,target:null,cloneFrom:e}),o(nh(a,t.kind),{replace:!0})},onDelete:e=>w.mutate(e)}),rows:_.data??[],rowKey:e=>e.id,minWidthPx:720,onRowClick:e=>{let t=b.get(e.kind);t!==void 0&&k(e,t)}}),s.mode===`pick-kind`&&u(ph,{kinds:y,onCancel:E,onPick:O}),s.mode===`form`&&u(mh,{kind:s.kind,target:s.target,cloneFrom:s.cloneFrom,users:x.data??[],onCancel:E,onSaved:()=>{E(),_.refetch()}}),m&&T&&u(Am,{target:m,kind:T,open:!0,onClose:()=>h(null)})]})}function ph({kinds:e,onPick:t,onCancel:i}){let a=r(()=>Mm(e),[e]);return u(Ae,{open:!0,onOpenChange:e=>!e&&i(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[u(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),n(z,{className:`space-y-4`,children:[a.length===0&&u(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`}),a.map(e=>n(`div`,{children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),u(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(r=>n(`button`,{type:`button`,onClick:()=>t(r),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[u(dh,{kind:r,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),u(`span`,{className:`font-medium text-foreground`,children:r.label})]},`${e.addonId}:${r.kind}`))})]},e.addonId))]})]})})}function mh({kind:e,target:t,cloneFrom:i,users:a,onSaved:o,onCancel:s}){let f=p(),m=r(()=>Nm(e.configSchema),[e.configSchema]),h=t??i,g=t?.id??i?.id,[_,v]=c(()=>i===null?t?.name??e.label:Jm(i.name)),[y,b]=c(()=>h?.config??{}),[x,C]=c(()=>h?Rm(h.config,m):{}),[w,E]=c(g===void 0),[D,O]=c(null),[k,j]=c(null),[ee,M]=c(h?lh(h)??``:``);d(()=>{if(g===void 0)return;let t=!1;return f.trpcClient.notificationOutput.getTarget.query({addonId:e.addonId,targetId:g}).then(e=>{if(t)return;let n=zm(e.config);b(n),C(n),M(lh(e)??``),E(!0)}).catch(e=>{t||(O(e instanceof Error?e.message:`Failed to load target secrets`),E(!0))}),()=>{t=!0}},[g,e.addonId,f.trpcClient]);let N=()=>Lm(x,y,m),[P,F]=c(null),I=e.kind===`whatsapp`,L=l({mutationFn:()=>f.trpcClient.notificationOutput.probeTargetConfig.mutate({addonId:e.addonId,kind:e.kind,config:N(),...g===void 0?{}:{targetId:g}}),onSuccess:e=>F(e),onError:e=>{F(null),O(e instanceof Error?e.message:`Connection test failed`)}}),R=l({mutationFn:()=>{let{[ch]:n,...r}=Lm(x,y,m),a=ee===``?r:{...r,[ch]:ee},o={id:t?.id??`${e.kind}-${Date.now()}`,name:_,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:a};return f.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:o,...i===null?{}:{cloneSecretsFrom:i.id}})},onSuccess:o,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;Vm(t)?j(t):O(t)}}),B=r(()=>Pm(e.configSchema),[e.configSchema]),ne=r(()=>g===void 0?[]:Wm(x,y,m,e.destinationKeys),[g,x,y,m,e.destinationKeys]),re=r(()=>g!==void 0&&(k!==null||ne.length>0)?Gm(x,y,m):[],[g,k,ne,x,y,m]),V=r(()=>Xm(qm(e.configSchema,re),y,m),[e.configSchema,re,y,m]),H=e=>B.get(e)??e;return u(Ae,{open:!0,onOpenChange:e=>!e&&s(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex min-w-0 items-center gap-2`,children:[u(dh,{kind:e,imgClassName:`h-5 w-5 object-contain shrink-0`,fallbackClassName:`text-lg`}),u(`span`,{className:`truncate`,children:t?`Edit ${t.name}`:i?`Duplicate ${i.name}`:`Add ${e.label} target`})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),D&&u(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,"data-testid":`target-form-error`,children:D}),n(z,{className:`space-y-4 pr-1`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),u(`input`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,value:_,onChange:e=>v(e.target.value)})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),u(T,{value:ee,options:[{value:``,label:`System (shared, admin-managed)`},...a.map(e=>({value:e.id,label:e.username}))],onChange:e=>M(e.target.value)}),u(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:`A user-owned target belongs to that user: it shows in their viewer and their own rules may deliver to it. System targets stay admin-managed.`})]}),m.length>0&&g!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Stored secrets load into the masked fields (eye to reveal). Clear a field to leave the stored value unchanged on save; type a new value to replace it.`}),u(ih,{refusal:k,edited:ne.map(H),reenter:re.map(H)}),u(fe,{schema:V,values:x,onChange:C}),I&&n(`div`,{className:`space-y-2`,children:[n(A,{size:`sm`,variant:`outline`,type:`button`,disabled:L.isPending,onClick:()=>{O(null),F(null),L.mutate()},children:[L.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Ne,{className:`h-3.5 w-3.5`}),`Test connection`]}),P!==null&&n(`p`,{className:P.ok?`text-[11px] text-success`:`text-[11px] text-danger`,"data-testid":`target-probe-result`,children:[P.ok?`Connected — ${P.stateInstance??`authorized`}`:P.error??`Connection failed`,P.resolvedUrl.length>0?` · ${P.resolvedUrl}`:``]})]})]}),n(te,{children:[u(A,{variant:`secondary`,size:`sm`,type:`button`,onClick:s,children:`Cancel`}),n(A,{size:`sm`,type:`button`,disabled:R.isPending||!w||_.trim().length===0,onClick:()=>{O(null),j(null),R.mutate()},children:[R.isPending||!w?u(K,{className:`h-3.5 w-3.5 animate-spin`}):null,t?`Save changes`:`Create target`]})]})]})})}t();var hh=`notificationTexts`,gh=`Every sentence the Notification Center can print — and your wording for it.`;function _h({entry:e,value:t,busy:r,onChange:i,onReset:a}){let o=Rl(e),s=e.override!==null;return n(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${e.key}`,"data-source":e.source,children:[n(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`code`,{className:`text-xs font-medium`,children:e.key}),s?u(q,{variant:`info`,children:`customised`}):null,e.source===`fallback`?u(q,{variant:`warning`,children:`English fallback`}):null]}),n(`div`,{className:`flex items-start gap-2`,children:[u(`div`,{className:`flex-1`,children:u(bo,{label:``,value:t,onChange:i,vars:Ll(e),disabled:r,testId:`text-input-${e.key}`})}),u(A,{variant:`ghost`,size:`sm`,disabled:r||!s&&t===e.shipped,onClick:a,title:`Reset to the shipped wording`,"data-testid":`text-reset-${e.key}`,children:u(h,{className:`h-3.5 w-3.5`})})]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[u(`span`,{className:`font-medium`,children:`Shipped:`}),` `,u(`span`,{className:`font-mono`,children:e.shipped})]}),o===null?null:u(`p`,{className:`text-xs text-warning`,children:o})]})}function vh(){let e=p(),t=o(),[a,s]=c(null),[d,f]=c(``),[m,h]=c(new Map),[g,_]=c(!1),v=i({queryKey:[hh,a??`hub`],queryFn:async()=>{let t=Ml(await e.trpcClient.addons.custom.mutate({addonId:$,action:Cl,input:a===null?{}:{language:a}}));return _(t===null),t}}),y=()=>{h(new Map),t.invalidateQueries({queryKey:[hh]})},b=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:wl,input:{language:t}}),onSuccess:y}),S=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Tl,input:t}),onSuccess:y}),C=v.data??null,w=r(()=>C===null?[]:Il(C.entries,d),[C,d]);if(v.isLoading)return u(Jr,{icon:$r,title:`Texts`,subtitle:gh,children:u(K,{className:`h-5 w-5 animate-spin`})});if(v.isError||C===null)return u(Jr,{icon:$r,title:`Texts`,subtitle:gh,children:u(F,{title:`The notification text catalog is not available on this hub`,message:g?`The hub answered something this admin build does not understand. Update both and reload.`:`This hub has not been updated to serve the notification text catalog yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime: notifications keep using the shipped wording.`})});let E=C.language,D=b.isPending||S.isPending,j=Pl(C.entries,m),ee=Fl(C.entries,m),M=C.entries.filter(e=>e.override!==null).length,N=C.languages.map(e=>({value:e,label:El[e]})),P=(e,t)=>h(n=>new Map(n).set(e,t)),I=e=>P(e.key,e.shipped);return u(Jr,{icon:$r,title:`Texts`,subtitle:gh,children:n(`div`,{className:`flex flex-col gap-4`,children:[b.isError?u(F,{title:`Could not change the language`,message:String(b.error)}):null,S.isError?u(F,{title:`Could not save`,message:String(S.error)}):null,n(x,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-6`,children:[n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:`Hub language`}),u(`div`,{className:`w-44`,children:u(T,{value:C.activeLanguage,disabled:D,options:N,onChange:e=>{let t=e.target.value;Dl(t)&&b.mutate(t)},"data-testid":`texts-hub-language`})}),u(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:`Editing`}),u(`div`,{className:`w-44`,children:u(T,{value:E,disabled:D,options:N,onChange:e=>{let t=e.target.value;Dl(t)&&(h(new Map),s(t))},"data-testid":`texts-editing-language`})}),u(`p`,{className:`text-xs text-foreground-subtle`,children:E===C.activeLanguage?`${M} of ${C.entries.length} texts customised.`:`This hub does not speak this language — these words are not in use yet.`})]})]}),u(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:`A rule that writes its own title or body still overrides everything here — this page is the wording used when a rule does not.`})]}),n(`div`,{className:`flex flex-wrap items-center gap-3`,children:[n(`div`,{className:`relative min-w-[12rem] flex-1`,children:[u(k,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),u(O,{value:d,placeholder:`Search a key or a sentence…`,onChange:e=>f(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),n(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[w.length,` of `,C.entries.length]}),n(A,{className:`ml-auto`,disabled:D||ee===0,onClick:()=>S.mutate({language:E,overrides:j}),"data-testid":`texts-save`,children:[D?u(K,{className:`h-3.5 w-3.5 animate-spin`}):null,ee===0?`Save`:`Save ${ee}`]})]}),u(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):w.map(e=>u(_h,{entry:e,value:Nl(e,m),busy:D,onChange:t=>P(e.key,t),onReset:()=>I(e)},e.key))})]})})}t();var yh=`simulate`,bh=`rules`;function xh(){let[e,t]=Gr();return d(()=>{let n=e.get(`tab`);if(n===null||!gf(n))return;let r=new URLSearchParams(e);r.set(`tab`,bh),r.set(`section`,n),t(r,{replace:!0})},[e,t]),u(`div`,{className:`flex flex-col p-4`,children:u(Xr,{tabs:[{id:`targets`,label:`Targets`,icon:Oe,content:u(fh,{}),ownedParams:eh},{id:bh,label:`Rules`,icon:ce,content:u(up,{onSimulateRule:n=>{Hp(Bp(n));let r=new URLSearchParams(e);r.set(`tab`,yh),t(r,{replace:!0})},onOpenHistory:n=>{t(Va(e,n.id),{replace:!0})}}),ownedParams:[`section`,`rule`,`editTab`]},{id:`sequences`,label:`Sequences`,icon:ei,content:u(bp,{})},{id:yh,label:`Simulate`,icon:b,content:u(fm,{})},{id:Fa,label:`History`,icon:Me,content:u(Qa,{}),ownedParams:La},{id:`alarm`,label:`Alarm`,icon:N,content:u(Pa,{})},{id:`texts`,label:`Texts`,icon:$r,content:u(vh,{})}]})})}export{xh as NotificationsPage,xh as default};
1
+ import{K as e,Q as t,S as n,W as r,a as i,b as a,o,p as s,q as c,t as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{Z as f,at as p,gt as m,lt as h,st as g,vt as _}from"./player-overlays-B7T46vDu.js";import{$d as v,$o as y,Ad as b,An as x,Cn as S,Dn as C,En as w,Fn as T,Ft as E,Gt as D,Hl as O,Hu as k,In as A,It as j,Jt as ee,Kt as M,Lu as N,Md as P,Nn as F,Qd as I,R as L,Sd as R,Sn as z,Tn as te,Ud as B,Xn as ne,Xo as re,Xu as V,Yu as H,Zn as ie,Zo as U,_ as ae,_i as oe,ar as se,d as W,df as ce,en as G,f as le,ff as ue,g as de,gd as K,gn as fe,h as pe,if as me,ir as he,la as ge,m as _e,or as ve,ot as ye,p as be,q as xe,qn as Se,qt as Ce,sr as we,td as Te,tr as q,ts as Ee,u as De,uf as Oe,v as ke,xn as Ae,yu as je}from"./src-BTQcUQJz.js";import{t as Me}from"./history-Dcle7WpC.js";import{t as Ne}from"./send-Cx-d7NnY.js";import{$ as Pe,A as Fe,B as Ie,Bn as Le,D as Re,E as ze,Er as Be,F as Ve,H as He,In as Ue,J as We,L as Ge,N as Ke,T as qe,U as Je,V as Ye,W as Xe,X as Ze,Y as Qe,Z as $e,_t as et,at as tt,bt as nt,ct as rt,dt as it,ft as at,j as ot,k as st,lt as ct,mt as lt,nn as ut,ot as dt,q as ft,qt as pt,rt as mt,tt as ht,ut as gt,xt as _t,z as vt,zn as yt}from"./client-BBcQuaON.js";import{D as bt,F as xt,M as St,O as Ct,j as wt,v as Tt,y as Et}from"./__vite-browser-external-DF8Eb0aa.js";import{t as Dt}from"./useTranslation-Bc5yH9V9.js";import"./mount-BZYpYRsM.js";import{$ as Ot,$t as kt,A as At,At as jt,B as Mt,Bt as Nt,C as Pt,Ct as Ft,D as It,Dt as Lt,E as Rt,Et as zt,F as Bt,Ft as Vt,G as Ht,Gt as Ut,H as Wt,Ht as Gt,I as Kt,It as qt,J as Jt,Jt as Yt,K as Xt,Kt as Zt,L as Qt,Lt as $t,M as en,Mt as tn,N as nn,Nt as rn,O as an,Ot as on,P as sn,Pt as cn,Q as ln,Qt as un,R as dn,Rt as fn,S as pn,St as mn,T as hn,Tt as gn,U as _n,Ut as vn,V as yn,Vt as bn,W as xn,Wt as Sn,X as Cn,Xt as wn,Y as Tn,Yt as En,Z as Dn,Zt as On,_ as kn,_n as An,_t as jn,a as Mn,an as Nn,at as Pn,b as Fn,bt as In,c as Ln,cn as Rn,ct as zn,d as Bn,dn as Vn,dt as Hn,en as Un,et as Wn,f as J,fn as Gn,ft as Kn,g as qn,gn as Jn,gt as Yn,h as Xn,hn as Zn,ht as Qn,i as $n,in as er,it as tr,j as nr,jt as rr,k as ir,kt as ar,l as or,ln as sr,lt as cr,m as lr,mn as ur,mt as dr,n as fr,nn as pr,nt as mr,o as hr,on as gr,ot as _r,p as vr,pn as yr,pt as br,q as xr,qt as Sr,r as Cr,rn as wr,rt as Tr,s as Er,sn as Dr,st as Or,t as kr,tn as Ar,tt as jr,u as Mr,un as Nr,ut as Pr,v as Fr,vt as Ir,w as Lr,wt as Rr,x as zr,xt as Br,y as Vr,yt as Hr,z as Ur,zt as Wr}from"./notification-schedule-field-CNwv7_6o.js";import{$ as Gr,Y as Kr,w as qr}from"./index-BlaisiEj.js";import{t as Jr}from"./AdminPage-BSFohA3i.js";import{t as Yr}from"./DeviceDoActionFields-Do6M2l_j.js";import"./device-picker-model-BZYpYRsM.js";import{t as Xr}from"./AdminTabs-2smlNAE_.js";import{t as Zr}from"./use-scenes-feed-DcNDaTD0.js";var Qr=_(`images`,[[`path`,{d:`m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16`,key:`9kzy35`}],[`path`,{d:`M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2`,key:`1t0f0t`}],[`circle`,{cx:`13`,cy:`7`,r:`1`,fill:`currentColor`,key:`1obus6`}],[`rect`,{x:`8`,y:`2`,width:`14`,height:`14`,rx:`2`,key:`1gvhby`}]]),$r=_(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),ei=_(`list-ordered`,[[`path`,{d:`M11 5h10`,key:`1cz7ny`}],[`path`,{d:`M11 12h10`,key:`1438ji`}],[`path`,{d:`M11 19h10`,key:`11t30w`}],[`path`,{d:`M4 4h1v5`,key:`10yrso`}],[`path`,{d:`M4 9h2`,key:`r1h2o0`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`,key:`xtkcd5`}]]);t();var ti=[`contact`,`cover`,`lock-control`,`switch`];function ni(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 ri(e){let t=new Set(ni(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 ii(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function ai(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=>pe([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?`Device #${String(e)}`:be(t))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function oi(e){let t=e.name.trim();return t===``?`Device #${String(e.deviceId)}`:t}function si(e){return e===0?`Not armed — the hub refused without naming an open device.`:`Not armed — these are open:`}var ci={home:`Home`,away:`Away`,night:`Night`};function li(e){return ci[e]??e}function ui(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?`${n} min`:`${n} min ${r} s`}function di(e,t){if(e.ruleCount===0)return`Arms nothing — no enabled rule is gated on this mode.`;if(e.allDevices&&e.allDevicesExcept.length>0){let n=e.allDevicesExcept.map(t);return`All devices except ${n.length}: ${n.join(`, `)}`}return e.allDevices?`Every device — ${hi(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${hi(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(t).join(`, `)}function fi(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${pi[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var pi={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function mi(e){return e.ruleCount===0}function hi(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function gi(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 _i=2e3,vi=15e3,yi=new Set([`arming`,`pending`,`triggered`]);function bi(e){return e!==void 0&&yi.has(e)?_i:vi}var xi={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 Si(e){let t=xi[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${li(e.targetMode)}`}function Ci(e){return e!==`disarmed`}function wi(e){return e===`open`?`ignored until it closes`:`closed — monitored at next open`}function Ti(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Ei(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Di(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function Oi(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 ki(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 Ai(e,t,n,r){let i=Oi(e,t,n);return r==="default"?i===void 0?null:ki(t,n,null):i===r?null:ki(t,n,r)}function ji(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=We(e,t),a=r!==n,o=n!==`doNothing`&&i.triggeredDurationSec===0;return!a&&!o?null:{mode:t,...a?{postTriggeredAction:n}:{},...o?{triggeredDurationSec:30}:{}}}function Mi(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 Ni=[`unknown-refusal`,`stale`,`expired`,`used`];function Pi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fi(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Pi(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 Ii(e){if(!Pi(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Fi(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Fi(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Ni.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var Li={"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 Ri(e){return Li[e]}function zi(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 Bi=`pipeline-analytics`,Vi=`The hub answered something this build cannot read — refresh after updating.`;function Hi(e){return e instanceof Error?e.message:String(e)}function Ui(e){return e.map(e=>`${oi(e)} (${e.state})`).join(`, `)}function Wi({live:e,onChanged:t}){let r=p(),[i,a]=c(null),[o,s]=c(null),[d,f]=c(null),m=(e,t)=>r.trpcClient.addons.custom.mutate({addonId:Bi,action:e,input:t}),h=e=>{if(e===null){s(Vi);return}if(e.outcome===`refused`){a({refusalId:e.refusalId,blocking:e.blocking});return}if(a(null),e.outcome===`rejected`){s(`Arm anyway was not accepted: ${Ri(e.reason)}.`);return}if(e.outcome===`outside-schedule`){s(`Outside this mode's activation schedule — arm during an allowed window.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;f(e.excluded.length===0?`${t}.`:`${t} — excluded: ${Ui(e.excluded)}.`)},g=()=>{s(null),f(null)},_=l({mutationFn:async e=>Ii(await m(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>s(Hi(e)),onSettled:t}),v=l({mutationFn:async e=>Ii(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>s(Hi(e)),onSettled:t}),y=l({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{g(),a(null)},onSuccess:()=>f(`Disarmed.`),onError:e=>s(Hi(e)),onSettled:t});if(e===void 0)return n(x,{className:`p-4`,children:[u(`h3`,{className:`text-sm font-semibold mb-1`,children:`Panel`}),u(`p`,{className:`text-sm text-foreground-subtle`,children:`This hub does not report the panel's live state yet — update it to arm from here.`})]});let b=_.isPending||v.isPending||y.isPending;return n(x,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[n(`div`,{children:[u(`h3`,{className:`text-sm font-semibold`,children:`Panel`}),u(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:Si(e)})]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?u(K,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>n(A,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:[`Arm `,li(e)]},e)),u(A,{type:`button`,size:`md`,variant:Ci(e.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:`Disarm`})]})]}),o===null?null:u(`div`,{className:`mt-3`,children:u(F,{title:`The panel did not do that`,message:o})}),d===null?null:u(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:d}),i===null?null:n(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[u(`p`,{className:`text-sm font-medium`,children:si(i.blocking.length)}),i.blocking.length>0?u(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:i.blocking.map(e=>n(`li`,{children:[oi(e),` `,n(`span`,{className:`text-foreground-subtle`,children:[`(`,e.state,`)`]})]},e.deviceId))}):null,n(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[u(A,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(i.refusalId),children:`Arm anyway`}),u(`span`,{className:`text-xs text-foreground-subtle`,children:`Each open device is ignored until it closes, then monitored again.`})]})]}),n(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[u(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:`Excluded sensors`}),e.exclusions.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:`No sensor is excluded.`}):u(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:e.exclusions.map(e=>n(`li`,{children:[oi(e),` —`,` `,u(`span`,{className:`text-foreground-subtle`,children:wi(e.phase)})]},e.deviceId))})]})]})}t();var Gi=[{field:`exitDelaySec`,key:`exit`,label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,max:600,zeroMeans:`arms immediately`},{field:`entryDelaySec`,key:`entry`,label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,max:600,zeroMeans:`fires immediately`},{field:`triggeredDurationSec`,key:`siren`,label:`After (seconds)`,hint:`How long the alarm stays triggered before the after-trigger action runs. Ignored when the action is “do nothing”.`,max:Ue,zeroMeans:`runs the action immediately`}];function Ki(e){return`Enter a whole number of seconds from 0 to ${e}.`}function qi(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${Ki(t)}`}function Ji({label:e,value:t,max:r,zeroMeans:i,disabled:a,testId:o,hint:s,adornment:l,onCommit:d}){let[f,p]=c(null),[m,h]=c(null),g=f??String(t),_=f!==null&&f.trim()!==``&&gi(f,r)===null,v=ui(t,i),y=()=>{let e=f===null?null:gi(f,r);p(null),e===null?f!==null&&h(f):(h(null),d(e))};return n(L,{label:e,...s===void 0?{}:{description:s},..._?{error:Ki(r)}:m===null?{}:{error:qi(m,r)},children:[n(`div`,{className:`flex items-center gap-2`,children:[u(O,{type:`number`,min:0,max:r,value:g,disabled:a,state:_||m!==null?`error`:`default`,"aria-label":e,onChange:e=>{h(null),p(e.target.value)},onBlur:y,className:`w-20`,"data-testid":o}),u(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),l]}),v===`${t} s`?null:u(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function Yi(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=ke(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function Xi(e){switch(e.kind){case`checking`:return{word:`Checking…`,note:null};case`hub-too-old`:return{word:`Unknown`,note:`This hub does not report sensor states — update the hub`};case`read-failed`:return{word:`Unknown`,note:`Could not read: ${e.error}`};case`open`:case`closed`:return{word:e.word,note:e.offline?`Offline — last known`:null};case`unknown`:return{word:`Unknown`,note:e.why===`not-answered`?`Not answered`:e.why===`read-failed`?`Could not read`:`No state reported`};case`not-opening`:return{word:`Not an opening`,note:null};case`removed`:return{word:`Removed`,note:`No longer in the device list`}}}var Zi=`Not checked by this mode — switch on to remove the entry`;function Qi(e){return e.listedUncovered?{word:`No`,note:Zi}:$i(e.coverage)}function $i(e){switch(e.kind){case`arm-checked`:return{word:`Yes`,note:null};case`arm-checked-skipped`:return{word:`Skipped`,note:`Blocks arming; notifications skipped: ${e.reason===`detection-off`?`detection off`:e.reason}`};case`unscoped`:return{word:`All-devices`,note:`Never blocks this mode`};case`not-covered`:return{word:`No`,note:`Never blocks this mode`}}}function ea(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 ta(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 na({name:e,variant:t,words:r}){return n(`span`,{"data-testid":`alarm-cell-${e}`,className:`flex flex-col items-start gap-0.5`,children:[u(q,{variant:t,"data-testid":`alarm-cell-${e}-badge`,children:r.word}),r.note===null?null:u(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${e}-note`,children:r.note})]})}var ra=`hidden sm:table-cell`;function ia(e){let{mode:t,inFlight:r,onSwitch:i,zones:a,disabled:o}=e;return[{key:`name`,header:`Name`,cell:e=>{let t=Yi(e.device.location,a);return n(`span`,{className:`flex min-w-0 flex-col`,"data-testid":`alarm-cell-name`,"data-muted":e.listedUncovered?`true`:void 0,children:[u(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.device.name}),t===``?null:u(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:t})]})}},{key:`type`,header:`Type`,headerClassName:ra,cellClassName:`${ra} text-[11px] text-foreground-subtle`,cell:e=>ae(e.device.type??null)},{key:`state`,header:`State`,cell:e=>u(na,{name:`state`,variant:ea(e.cell),words:Xi(e.cell)})},{key:`coverage`,header:`Checked when arming`,headerClassName:ra,cellClassName:ra,cell:e=>u(na,{name:`coverage`,variant:ta(e),words:Qi(e)})},{key:`blocks`,header:`Blocks arming`,headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{let a=r!==null&&r.mode===t&&r.deviceId===e.device.id&&r.kind===`blocks`,s=r!==null&&!a;return n(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?u(K,{className:`h-3 w-3 animate-spin`}):null,u(G,{checked:e.blocks,onCheckedChange:t=>i(e,`blocks`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-blocks`,"aria-label":`Blocks arming: ${e.device.name}`,"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}},{key:`secure`,header:u(`span`,{title:`Close, lock, or turn off when this mode arms`,children:`Secure on arm`}),headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{if(!e.controllable)return u(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let a=r!==null&&r.mode===t&&r.deviceId===e.device.id&&r.kind===`secureOnArm`,s=r!==null&&!a;return n(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?u(K,{className:`h-3 w-3 animate-spin`}):null,u(G,{checked:e.secureOnArm,onCheckedChange:t=>i(e,`secureOnArm`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-secure`,"aria-label":`Secure on arm (close/lock/off): ${e.device.name}`,title:`Close, lock, or turn off when this mode arms`,"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}}]}function aa(e){let{mode:t,rows:r,sensorsRetry:i,zones:a}=e;return n(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${t}`,children:[i===null?null:n(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[u(`span`,{children:`Could not read the sensor states.`}),u(A,{type:`button`,size:`sm`,variant:`outline`,onClick:i,children:`Retry`})]}),u(xe,{mode:`generic`,items:r,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,Yi(e.device.location,a),ae(e.device.type??null)].join(` `),getFilterType:e=>ae(e.device.type??null),columns:ia(e),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:`Search sensors`,emptyLabel:`No sensor matches.`})]})}var oa=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function sa(e){return oa.some(t=>t.test(e))}function ca(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return sa(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 la(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 ua(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 da(e){return e.kind===`unscoped`||e.kind===`not-covered`}function fa(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=ua(e.coverage,r.id),a=la(e.sensors,r.id,t,r.type),o=Ze({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=$e({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&&da(i)&&(!o||c)&&c;!t&&da(i)&&!c||n.push({device:r,removed:t,cell:ca(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function pa(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function ma(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 ha(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 ga(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 _a(e,t){return ft(ga(e),t)?{kind:`landed`}:{kind:`not-landed`}}var va=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function ya({coverage:e,settings:t,disabled:r,onNotifyEdit:i}){let{t:a}=Dt(),o=Qe(t,e.mode);return n(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${e.mode}`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:a(`notificationRules.alarmNotify.title`)}),va.map(({field:t,key:s})=>n(`div`,{className:`flex items-start justify-between gap-3`,children:[n(`div`,{className:`min-w-0`,children:[u(`p`,{className:`text-xs text-foreground`,children:a(`notificationRules.alarmNotify.${s}`)}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:a(`notificationRules.alarmNotify.${s}Hint`)})]}),u(G,{checked:o[t],onCheckedChange:e=>i(t,e),disabled:r,"data-testid":`alarm-notify-${e.mode}-${t}`,"aria-label":a(`notificationRules.alarmNotify.${s}`)})]},t))]})}function ba({coverage:e,rows:t,names:r}){let i=t.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,a=di(e,r.nameOf);return n(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${e.mode}`,children:[mi(e)?u(q,{variant:`warning`,title:a,"data-testid":`alarm-arms-nothing`,children:`Arms nothing — no enabled rule is gated on this mode`}):n(q,{variant:`default`,title:a,"data-testid":`alarm-covers`,children:[`Checks `,i,` `,i===1?`sensor`:`sensors`]}),e.skippedDevices.length>0?n(q,{variant:`warning`,title:fi(e.skippedDevices,r.nameOf),"data-testid":`alarm-skipped`,children:[e.skippedDevices.length,` not notified`]}):null]})}function xa(e){return e.status===`answered`?e.openingIds:null}function Sa({check:e,view:t}){return t.unresolved?e.status===`pending`?n(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[u(K,{className:`h-3 w-3 animate-spin`}),`Checking which devices are openings…`]}):e.status===`failed`?n(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[n(`span`,{children:[`Couldn't check which devices are openings (`,e.error,`).`]}),u(A,{type:`button`,size:`sm`,variant:`outline`,onClick:e.retry,children:`Retry`})]}):null:null}var Ca=[{value:`rearmAfter`,label:`Re-arm after`},{value:`disableAfter`,label:`Disarm after`},{value:`doNothing`,label:`Do nothing (stay triggered)`}];function wa({coverage:e,settings:t,disabled:r,onDelayEdit:i,onPostTriggeredEdit:a,onScheduleEdit:o}){let s=e.mode,c=We(t,s),l=c.source.postTriggeredAction==="default",d=c.postTriggeredAction!==`doNothing`,f=(t.modeDelays??[]).find(e=>e.mode===s)?.schedule;return n(`div`,{className:`space-y-3`,"data-testid":`alarm-delays-${s}`,children:[n(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:[Gi.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let n=c.source[e.field]==="default";return u(Ji,{label:e.label,value:c[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:r,testId:`alarm-delay-${s}-${e.key}`,onCommit:t=>i(e.field,t),adornment:n?u(q,{variant:`default`,title:`Uses the system default (${t[e.field]} s)`,children:`Default`}):u(A,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:`Use the default`,"aria-label":`${e.label}: use the default`,onClick:()=>i(e.field,`default`),"data-testid":`alarm-delay-${s}-${e.key}-default`,children:u(h,{className:`h-3.5 w-3.5`})})},e.field)}),n(`div`,{children:[n(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:[`After trigger`,l?u(q,{variant:`default`,className:`ml-1.5 align-middle`,title:`Uses the system default`,children:`Default`}):u(A,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:r,title:`Use the default`,"aria-label":`After trigger: use the default`,onClick:()=>a(`default`),"data-testid":`alarm-delay-${s}-post-default`,children:u(h,{className:`h-3.5 w-3.5`})})]}),u(`select`,{className:`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:c.postTriggeredAction,disabled:r,"data-testid":`alarm-delay-${s}-post`,onChange:e=>{let t=yt.safeParse(e.target.value);t.success&&a(t.data)},children:Ca.map(e=>u(`option`,{value:e.value,children:e.label},e.value))})]}),d?Gi.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let n=c.source[e.field]==="default";return u(Ji,{label:e.label,value:c[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:r,testId:`alarm-delay-${s}-${e.key}`,onCommit:t=>i(e.field,t),adornment:n?u(q,{variant:`default`,title:`Uses the system default (${t[e.field]} s)`,children:`Default`}):u(A,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:`Use the default`,"aria-label":`${e.label}: use the default`,onClick:()=>i(e.field,`default`),"data-testid":`alarm-delay-${s}-${e.key}-default`,children:u(h,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),n(`div`,{"data-testid":`alarm-schedule-${s}`,children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Activation schedule`}),u(`p`,{className:`mb-1 text-[10px] text-foreground-subtle`,children:`When this mode may be armed. Empty means any day and time.`}),u(`fieldset`,{disabled:r,className:`min-w-0 border-0 p-0`,children:u(kr,{value:f,onChange:o,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var Ta={"no-opening":`This household has no contact, cover or lock.`};function Ea({coverage:e,live:t,settings:r,names:i,openingsCheck:a,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:d,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m,onNotifyEdit:h,disabled:g}){let _=ri({live:t,listed:Ti(r,e.mode),openingIds:xa(a)}),v=ii(_),y=pa({rowCount:o.length,candidatesComplete:!_.unresolved});return n(`div`,{className:`flex flex-col gap-3`,"data-mode":e.mode,"data-empty":mi(e)?`true`:`false`,children:[u(ba,{coverage:e,rows:o,names:i}),u(wa,{coverage:e,settings:r,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),n(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:[`Blank delay fields use the system defaults (exit 30 s, entry 20 s, re-arm after`,` `,30,` s).`]}),u(ya,{coverage:e,settings:r,disabled:g,onNotifyEdit:h}),n(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[u(Sa,{check:a,view:_}),v===null?null:u(`p`,{className:`text-xs text-foreground-subtle`,children:Ta[v]}),y===`none`&&v===null?u(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`alarm-sensors-none`,children:`No sensor is covered by a rule of this mode.`}):null,y===`rows`?u(aa,{mode:e.mode,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:d,disabled:g}):null]})]})}t();function Da({profiles:e,busy:t,onActivate:r,onCreate:i,onClone:o,onRename:s,onDelete:l}){let[d,f]=c(``),[p,m]=c(!1),h=e.items.find(t=>t.id===e.activeId)??e.items[0],_=h!==void 0&&!h.isDefault,v=d.trim(),y=()=>{v.length!==0&&(i(v),f(``))},b=()=>{v.length===0||h===void 0||(o(h.id,v),f(``))},x=()=>{v.length===0||h===void 0||(s(h.id,v),f(``),m(!1))};return n(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface-1 p-3`,"data-testid":`alarm-profiles`,children:[n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:`Profile`}),u(`select`,{id:`alarm-profile-select`,className:`h-8 min-w-[10rem] rounded-md border border-border bg-background px-2 text-sm`,"data-testid":`alarm-profile-select`,disabled:t,value:e.activeId,onChange:e=>r(e.target.value),children:e.items.map(e=>n(`option`,{value:e.id,children:[e.name,e.isDefault?` (default)`:``]},e.id))}),_?u(A,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-delete`,title:`Delete this profile`,onClick:()=>{h!==void 0&&l(h.id)},children:u(g,{className:`h-3.5 w-3.5`})}):null]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(O,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:p?`New name`:`New profile name`,value:d,disabled:t,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(p?x():y())}}),p?n(a,{children:[u(A,{type:`button`,size:`sm`,disabled:t||v.length===0,"data-testid":`alarm-profile-rename-save`,onClick:x,children:`Rename`}),u(A,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{m(!1),f(``)},children:`Cancel`})]}):n(a,{children:[n(A,{type:`button`,size:`sm`,disabled:t||v.length===0,"data-testid":`alarm-profile-create`,title:`Create with system defaults`,onClick:y,children:[u(Te,{className:`mr-1 h-3.5 w-3.5`}),`Create`]}),n(A,{type:`button`,size:`sm`,variant:`secondary`,disabled:t||v.length===0||h===void 0,"data-testid":`alarm-profile-clone`,title:`Clone the selected profile`,onClick:b,children:[u(B,{className:`mr-1 h-3.5 w-3.5`}),`Clone`]}),u(A,{type:`button`,size:`sm`,variant:`ghost`,disabled:t||h===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{m(!0),f(h?.name??``)},children:`Rename`})]})]}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Create starts from system defaults. Clone copies the selected profile (sensors, secure-on-arm, delays). Switching applies that profile for the next arm.`})]})}t();var Oa=[`notificationRules`,`getAlarmConfig`],ka=[`notificationRules`,`getAlarmSensors`],Aa=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],ja=6e4;function Ma(e){return e instanceof Error?e.message:String(e)}function Na({notice:e}){switch(e.kind){case`refused`:return n(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:[`Saving `,e.inFlight.name,` (`,li(e.inFlight.mode),`) — wait for it to finish.`]});case`not-landed`:return n(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:[`The hub did not apply this change — another editor may have changed it, or the hub needs an update (`,e.write.name,`, `,li(e.write.mode),`).`]});case`failed`:return u(`p`,{className:`text-xs text-danger`,role:`alert`,"data-testid":`alarm-switch-failed`,children:`Could not change ${e.write.name} for ${li(e.write.mode)}: ${e.error}`})}}function Pa(){let t=p(),a=o(),d=i({queryKey:Oa,queryFn:async()=>t.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>bi(e.state.data?.live?.state)}),f=ge({projection:`slim`}),[m,h]=c(!1),g=l({mutationFn:e=>t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{a.setQueryData(Oa,e),h(!ft(t,e.settings))}}),_=l({mutationFn:async e=>{switch(e.kind){case`activate`:return t.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return t.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return t.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{a.setQueryData(Oa,e),h(!1)}}),v=()=>a.invalidateQueries({queryKey:Oa}),y=r(()=>{let e=new Map;for(let t of f.data??[])e.set(t.id,t.name);return e},[f.data]),b=d.data?.live,S=i({queryKey:Aa,staleTime:ja,queryFn:async()=>new Set(await t.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...ti]}))}),C=r(()=>(f.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[f.data]),w=r(()=>new Map(C.map(e=>[e.id,e])),[C]),T=S.isError?{status:`failed`,error:S.error instanceof Error?S.error.message:String(S.error),retry:()=>void S.refetch()}:S.data===void 0?{status:`pending`}:{status:`answered`,openingIds:S.data},E=r(()=>{let e=new Map;for(let t of b?.openings??[])for(let n of t.devices)e.set(n.deviceId,oi(n));return ai(y,_e(f),e)},[b,y,f]),O=de(!0),[k,A]=c(null),j=r(()=>{let e=new Map,t=d.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,ri({live:t.live,listed:Ti(t.settings,n.mode),openingIds:S.data??null}).ids);return e},[d.data,S.data]),M=r(()=>{let e=new Set;for(let t of j.values())for(let n of t)E.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[j,E]),P=i({queryKey:[...ka,M],enabled:M.length>0,placeholderData:s,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&sa(Ma(e.state.error))?!1:b!==void 0&&Ci(b.state)?5e3:15e3,retry:(e,t)=>!sa(Ma(t))&&e<2,queryFn:async()=>{let e=[];for(let n of ma(M,500))e.push(await t.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...n]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),I=P.isError?{status:`failed`,error:Ma(P.error)}:P.data===void 0?{status:`pending`}:{status:`answered`,sensors:P.data.sensors},L=e(null),[R,z]=c(null),[te,B]=c(null),ne=async e=>{try{let n=await t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:ga(e)});_a(e,n.settings).kind===`landed`?a.setQueryData(Oa,n):(B({kind:`not-landed`,write:e}),a.invalidateQueries({queryKey:Oa}))}catch(t){B({kind:`failed`,write:e,error:Ma(t)}),a.invalidateQueries({queryKey:Oa})}finally{L.current=null,z(null),B(e=>e?.kind===`refused`?null:e)}},re=(e,t,n,r)=>{let i=ha(L.current,e,t,n,r);if(i.kind===`refused`){B({kind:`refused`,inFlight:i.inFlight});return}L.current=i.write,z(i.write),B(null),ne(i.write)};if(d.isLoading)return u(Jr,{icon:N,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(K,{className:`h-5 w-5 animate-spin`})});let V=d.data;if(V===void 0||d.isError)return u(Jr,{icon:N,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(F,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(V.deviceId===null)return u(Jr,{icon:N,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(x,{className:`p-4`,children:u(`p`,{className:`text-sm text-foreground-subtle`,children:`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 H=V.settings,ie=g.isPending||_.isPending,U=e=>{h(!1),g.mutate(e)},ae=(e,t,n)=>{let r=Ai(H,e,t,n);r!==null&&U({modeDelays:[r]})},oe=(e,t)=>{let n=ji(H,e,t);n!==null&&U({modeDelays:[n]})},se=(e,t)=>{let n=Mi(H,e,t);n!==null&&U({modeDelays:[n]})},W=(e,t,n)=>{let r=zi(H,e,t,n);r!==null&&U({modeDelays:[r]})},ce=new Map(V.coverage.map(e=>[e.mode,fa({candidates:(j.get(e.mode)??[]).map(e=>({...w.get(e),id:e,name:E.nameOf(e)})),removedIds:new Set((j.get(e.mode)??[]).filter(E.isRemoved)),coverage:e,nonBlocking:Ti(H,e.mode),blocking:Ei(H,e.mode),secureOnArmOff:Di(H,e.mode),sensors:I})])),G=V.coverage.find(e=>e.mode===k)??V.coverage.find(e=>(ce.get(e.mode)?.length??0)>0)??V.coverage[0],le=G?.mode??``;return n(Jr,{icon:N,title:`Alarm`,subtitle:`The panel, what each mode arms, and who hears about it.`,children:[g.isError?u(F,{title:`Could not save`,message:String(g.error)}):null,_.isError?u(F,{title:`Could not update profile`,message:String(_.error)}):null,m?u(`div`,{"data-testid":`alarm-save-not-landed`,children:u(F,{variant:`warning`,title:`Not applied`,message:`The hub did not apply this change — another editor may have changed it, or the hub needs an update`})}):null,V.profiles===void 0?null:u(Da,{profiles:V.profiles,busy:ie,onActivate:e=>_.mutate({kind:`activate`,id:e}),onCreate:e=>_.mutate({kind:`create`,name:e}),onClone:(e,t)=>_.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>_.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>_.mutate({kind:`delete`,id:e})}),u(Wi,{live:V.live,onChanged:v}),n(x,{className:`p-4`,"data-testid":`alarm-coverage`,children:[u(D,{value:le,onValueChange:e=>{let t=V.coverage.find(t=>t.mode===e);t!==void 0&&A(t.mode)},children:u(Ce,{className:`mb-3`,children:V.coverage.map(e=>n(ee,{value:e.mode,"data-testid":`alarm-tab-${e.mode}`,children:[li(e.mode),u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:ce.get(e.mode)?.length??0})]},e.mode))})}),te===null?null:u(Na,{notice:te}),G===void 0?null:u(Ea,{coverage:G,live:V.live,settings:H,names:E,openingsCheck:T,rows:ce.get(G.mode)??[],sensorsRetry:I.status===`failed`&&!sa(I.error)?()=>void P.refetch():null,inFlight:R,onSwitch:(e,t,n)=>re(G.mode,e,t,n),zones:O,onDelayEdit:(e,t)=>ae(G.mode,e,t),onPostTriggeredEdit:e=>oe(G.mode,e),onScheduleEdit:e=>se(G.mode,e),onNotifyEdit:(e,t)=>W(G.mode,e,t),disabled:ie},G.mode)]})]})}var Fa=`history`,Ia=`ruleId`,La=[Ia],Ra=24,za=0,Ba=100;function Va(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Fa),n.set(Ia,t),n}function Ha(e,t){let n=new URLSearchParams(e);return t===``?n.delete(Ia):n.set(Ia,t),n}function Ua(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Ra:za,limit:Ba}}function Wa(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?`Deleted rule (${e.selected})`:e.selected}]:[];return[{value:``,label:`All rules`},...t,...n]}t();var Ga=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],Ka=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],qa=[50,100,250,500];function Ja(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Ya(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Xa(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 Za({entry:e,cameraName:t,onClose:r}){let i=Xa(e),a=e.subject.systemEvent;return u(Ae,{open:!0,onOpenChange:e=>!e&&r(),children:n(S,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[u(w,{children:u(C,{className:`min-w-0 break-words`,children:i.title||e.ruleName})}),u(z,{children:n(`dl`,{className:`space-y-3`,children:[n(`div`,{children:[u(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:`Body`}),u(`dd`,{className:`mt-1 whitespace-pre-wrap text-sm text-foreground`,children:i.body.length>0?i.body:`—`})]}),n(`div`,{className:`grid grid-cols-2 gap-3 text-[11px]`,children:[n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`When`}),u(`dd`,{className:`text-foreground`,children:new Date(e.createdAt).toLocaleString()})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Status`}),u(`dd`,{className:`text-foreground`,children:e.status})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Rule`}),u(`dd`,{className:`text-foreground`,children:e.ruleName})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Device`}),u(`dd`,{className:`text-foreground`,children:t})]}),a===void 0?null:n(`div`,{className:`col-span-2`,children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Kind`}),u(`dd`,{className:`text-foreground`,children:a.kind})]}),e.error===void 0?null:n(`div`,{className:`col-span-2`,children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:`Error`}),u(`dd`,{className:`text-danger`,children:e.error})]})]})]})}),u(te,{children:u(A,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:`Close`})})]})})}function Qa(){let e=p(),[t,a]=Gr(),[o,s]=c(()=>Ua(t)),[l,d]=c(null),f=e=>s(t=>({...t,...e})),m=e=>{f({ruleId:e}),a(Ha(t,e),{replace:!0})},h=i({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),g=ge({projection:`slim`}),_=Date.now(),v=i({queryKey:[`notificationRules`,`getHistory`,o],retry:!1,queryFn:async()=>{let t=o.windowHours>0?_-o.windowHours*36e5:void 0;return(await e.trpcClient.notificationRules.getHistory.query({filter:{limit:o.limit,...o.ruleId?{ruleId:o.ruleId}:{},...o.deviceId?{deviceId:Number(o.deviceId)}:{},...Ja(o.status)?{status:Ja(o.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),y=r(()=>{let e=new Map;for(let t of g.data??[])t.type===Be.Camera&&e.set(t.id,t.name);return e},[g.data]),b=e=>y.get(e)??`Camera #${String(e)}`,S=v.data??[],C=v.isError;return n(Jr,{icon:Me,title:`Delivery history`,subtitle:`A searchable log of every notification the rules delivered (or failed to deliver).`,children:[n(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),u(T,{"data-testid":`history-rule-filter`,value:o.ruleId,onChange:e=>m(e.target.value),options:[...Wa({rules:h.data??[],answered:h.isSuccess,selected:o.ruleId})]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),u(T,{value:o.deviceId,onChange:e=>f({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(g.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),u(T,{value:o.status,onChange:e=>f({status:e.target.value}),options:Ka.map(e=>({value:e.value,label:e.label}))})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),u(T,{value:String(o.windowHours),onChange:e=>f({windowHours:Number(e.target.value)}),options:Ga.map(e=>({value:String(e.value),label:e.label}))})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),u(T,{value:String(o.limit),onChange:e=>f({limit:Number(e.target.value)}),options:qa.map(e=>({value:String(e),label:String(e)}))})]})]}),v.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(K,{className:`h-6 w-6 animate-spin text-primary`})}),C&&!v.isLoading&&u(x,{children:n(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[u(Me,{className:`h-6 w-6 text-foreground-subtle`}),u(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),u(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:`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.`}),n(`button`,{type:`button`,onClick:()=>void v.refetch(),className:`mt-1 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:[u(H,{className:`h-3 w-3`}),` Retry`]})]})}),!C&&!v.isLoading&&S.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!C&&S.length>0&&u(x,{children:u(E,{columns:$a(b),rows:S,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>d(e)})}),l!==null&&u(Za,{entry:l,cameraName:b(l.deviceId),onClose:()=>d(null)})]})}function $a(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>u(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`Notification`,render:e=>{let t=Xa(e);return n(`span`,{className:`block max-w-[18rem]`,children:[u(`span`,{className:`block truncate text-[11px] font-medium text-foreground`,children:t.title.length>0?t.title:e.subject.label??e.subject.className}),t.body.length>0?u(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:t.body}):null]})}},{key:`status`,header:`Status`,nowrap:!0,render:e=>n(`span`,{className:`flex items-center gap-1.5`,children:[u(q,{variant:Ya(e.status),children:e.status}),e.attempts>1?n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:`Detail`,render:e=>e.error?u(`span`,{className:`text-[11px] text-danger`,children:e.error}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var eo=/\{\{\s*(\w+)\s*\}\}/g,to=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function no(e,t,n){let r=Math.min(Math.max(t.start,0),e.length),i=Math.min(Math.max(t.end,r),e.length);return{value:e.slice(0,r)+n+e.slice(i),cursor:r+n.length}}function ro(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function io(e){return[...e.matchAll(eo)].map(e=>e[1]??``).filter(e=>e.length>0)}function ao(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function oo(e,t){return[...new Set(io(e))].filter(e=>!ao(e,t))}var so={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function co(e){return e.map(e=>{let t=Ie.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)||vt.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function lo(e){let t=new Set(e.map(e=>e.name)),n=Ie.filter(e=>Ye(e)&&!t.has(e.name));return[...e,...n]}function uo(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=so[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)||!Je(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:Xe(e,t)&&He(e,t))}function fo(e){return to.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var po=[`nc`,`template-catalog`],mo=400;function ho(){let e=p();return i({queryKey:po,staleTime:5*6e4,queryFn:async()=>lo(co((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function go(e,t,n){let r=p(),a=ye(t.title??``,mo),o=ye(t.body??``,mo);return i({queryKey:[`nc`,`template-preview`,e,a,o],enabled:n&&(a.length>0||o.length>0),staleTime:3e4,queryFn:()=>r.trpcClient.notificationRules.previewTemplate.mutate({context:e,template:{...a?{title:a}:{},...o?{body:o}:{}}})})}t();var _o={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},vo=`block text-[11px] font-medium text-foreground mb-1`,yo=`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`;function bo({label:t,value:r,onChange:i,vars:a,multiline:o=!1,placeholder:s,disabled:c=!1,testId:l}){let d=e(null),f=e(null),p=a?oo(r,a):[],m=e=>{let t=o?f.current:d.current,n={start:t?.selectionStart??r.length,end:t?.selectionEnd??r.length},a=ro(e),s=no(r,n,a.text);i(s.value);let c=s.cursor-a.text.length+a.cursorOffset;requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(c,c)})},h=e=>i(e.target.value);return n(`div`,{className:`space-y-1`,children:[u(`label`,{className:vo,children:t}),o?u(`textarea`,{ref:f,value:r,rows:2,disabled:c,placeholder:s,onChange:h,className:yo,"data-testid":`${l}-input`}):u(O,{ref:d,value:r,disabled:c,placeholder:s,onChange:h,"data-testid":`${l}-input`}),a&&a.length===0?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`No variables for this field.`}):null,a&&a.length>0?u(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:fo(a).map(e=>n(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${l}-group-${e.group}`,children:[u(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:_o[e.group]}),e.vars.map(e=>u(`button`,{type:`button`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),title:`${e.description??e.label} — e.g. "${e.example}"`,className:`rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-foreground hover:bg-surface-hover`,"data-testid":`${l}-chip-${e.name}`,children:e.dynamic?`${e.name}<class>`:e.name},e.name))]},e.group))}):null,p.length>0?n(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${l}-unknown`,children:[u(je,{className:`h-3 w-3`}),p.map(e=>`{{${e}}}`).join(` `),` will be empty in this notification.`]}):null]})}function xo({context:e,title:t,body:r,testId:i}){let a=go(e,{title:t,body:r},!0);return a.data?n(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":i,children:[u(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:`Preview (example values)`}),a.data.title===null?null:u(`p`,{className:`font-medium`,children:a.data.title}),a.data.body===null?null:u(`p`,{className:`whitespace-pre-wrap`,children:a.data.body})]}):null}var So=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,Co=`block text-[11px] font-medium text-foreground`;function wo({title:e,description:t,children:r}){return n(`div`,{className:`flex flex-col gap-2`,children:[n(`div`,{children:[u(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t})]}),r!==void 0&&u(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function To(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function Eo(e,t){return{kind:`cap`,deviceId:t,cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}}}function Do(e){let t=To(e.deviceId);return t.length===0?[Eo(e,0)]:t.map(t=>Eo(e,t))}function Oo(e){return Do(e).map(e=>({kind:`do`,action:e}))}function ko(e,t){let n=e[t];if(n===void 0||n.kind!==`cap`)return{wire:{deviceId:0,cap:``,method:``},length:1};let r=n.deviceId>0?[n.deviceId]:[],i=1;for(let a=t+1;a<e.length;a+=1){let t=e[a];if(t===void 0||t.kind!==`cap`||t.cap!==n.cap||t.method!==n.method||JSON.stringify(t.args??{})!==JSON.stringify(n.args??{}))break;t.deviceId>0&&r.push(t.deviceId),i+=1}return{wire:{deviceId:r.length===0?0:r.length===1?r[0]:[...r],cap:n.cap,method:n.method,...n.args===void 0?{}:{args:{...n.args}}},length:i}}function Ao(e,t){let n=e[t];return n===void 0||n.kind!==`do`?{wire:{deviceId:0,cap:``,method:``},length:1}:ko(e.slice(t).map(e=>e.kind===`do`?e.action:{kind:`wait`,seconds:0}),0)}function jo({value:e,onChange:t,devices:r,devicesState:i,sequences:a=[]}){let o=ln(e,new Set(a.map(e=>e.id))),s=(n,r)=>t({...e,[n]:r}),c=(n,r)=>t({...e,buttons:e.buttons.map((e,t)=>t===n?r:e)});return n(`div`,{className:`space-y-4`,children:[o.length>0&&u(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:o.map(e=>u(`p`,{children:e.message},e.message))}),Ht.map(t=>u(Mo,{hookKey:t,bindings:e[t],sequences:a,devices:r,devicesState:i,onChange:e=>s(t,e)},t)),n(`section`,{className:`space-y-2`,children:[u(wo,{title:`Buttons on the notification`,description:`Each button runs one shared sequence when tapped.`,children:n(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:a.length===0,onClick:()=>t({...e,buttons:[...e.buttons,Jt(e.buttons.length,a[0]?.id??``)]}),children:[u(Te,{className:`h-3.5 w-3.5 shrink-0`}),` Button`]})}),e.buttons.length>0&&n(`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:[u(je,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),n(`span`,{children:[`A button's link travels inside the notification. The link is the only authority: anyone holding the notification can run the button `,u(`strong`,{children:`once`}),`, within 15 minutes.`]})]}),a.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Create a sequence on the Sequences tab first — a button runs one, it does not define its own steps.`}):e.buttons.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No buttons. The notification arrives with nothing to tap.`}):e.buttons.map((n,r)=>u(No,{button:n,sequences:a,onChange:e=>c(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function Mo({hookKey:e,bindings:t,sequences:r,devices:i,devicesState:a,onChange:o}){let s=Xt[e],c=[],l=0;for(;l<t.length;){if(t[l].kind===`sequence`){c.push({start:l,kind:`sequence`,length:1}),l+=1;continue}let e=Ao(t,l);c.push({start:l,kind:`do`,length:e.length}),l+=e.length}return n(`section`,{className:`space-y-2`,children:[n(wo,{title:s.title,description:s.hint,children:[n(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4||r.length===0,onClick:()=>o([...t,Cn(r[0]?.id??``)]),children:[u(Te,{className:`h-3.5 w-3.5`}),` Sequence`]}),n(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4,onClick:()=>o([...t,Tn()]),children:[u(Te,{className:`h-3.5 w-3.5`}),` Single action`]})]}),t.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Nothing on this edge.`}):c.map(e=>{if(e.kind===`sequence`){let i=t[e.start];return i.kind===`sequence`?n(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:Co,children:`Sequence`}),u(`select`,{className:So,value:i.sequenceId,onChange:n=>{let r=[...t];r[e.start]={kind:`sequence`,sequenceId:n.target.value},o(r)},children:r.map(e=>u(`option`,{value:e.id,children:e.name},e.id))})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o(t.filter((t,n)=>n!==e.start)),title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]},`seq-${String(e.start)}`):null}return u(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:n(`div`,{className:`flex items-start justify-between gap-2`,children:[u(`div`,{className:`min-w-0 flex-1`,children:u(Yr,{value:Ao(t,e.start).wire,devices:i,listState:a,allowMultiSameFamily:!0,onChange:n=>{let r=Oo(n);o([...t.slice(0,e.start),...r,...t.slice(e.start+e.length)])}})}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o([...t.slice(0,e.start),...t.slice(e.start+e.length)]),title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})},`do-${String(e.start)}`)})]})}function No({button:e,sequences:t,onChange:r,onRemove:i}){return n(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[n(`div`,{className:`w-28`,children:[u(`label`,{className:Co,children:`Id`}),u(O,{className:`mt-1`,value:e.id,onChange:t=>r({...e,id:t.target.value})})]}),n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:Co,children:`Label`}),u(O,{className:`mt-1`,value:e.label,onChange:t=>r({...e,label:t.target.value})})]}),n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:Co,children:`Sequence`}),u(`select`,{className:So,value:e.sequenceId,onChange:t=>r({...e,sequenceId:t.target.value}),children:t.map(e=>u(`option`,{value:e.id,children:e.name},e.id))})]}),n(`div`,{className:`w-32`,children:[u(`label`,{className:Co,children:`Icon`}),n(`select`,{className:So,value:e.icon??``,onChange:t=>{let n={...e};t.target.value===``?delete n.icon:n.icon=t.target.value,r(n)},children:[u(`option`,{value:``,children:`—`}),xn.map(e=>u(`option`,{value:e.value,children:e.label},e.value))]})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})}var Po=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Fo=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],Io={minConfidence:`class`},Lo=[{id:`system`,label:`System events`},{id:`class`,label:`Detections`},{id:`zones`,label:`Zones`},{id:`label`,label:`Faces, plates & labels`},{id:`quality`,label:`Quality`},{id:`scope`,label:`Only while`},{id:`device`,label:`Device event`},{id:`package`,label:`Package`},{id:`occupancy`,label:`Occupancy`},{id:`audio`,label:`Sound`},{id:`schedule`,label:`Schedule`}];function Ro(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Fo)t.has(e)&&n.add(r);return n}function zo(e){return Io[e.id]??e.group}function Bo(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Vo(e){let t=Ro(e),n=e.filter(e=>!Po.has(e.id)&&!t.has(e.id)),r=new Set(Lo.map(e=>e.id)),i=[],a=e=>n.filter(t=>zo(t)===e);for(let e of Lo){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=zo(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Bo(e),descriptors:a(e)});return i}function Ho(e,t){switch(e){case`zones`:return Tr(t.zones?.ids,t.zonesExclude);case`labels`:return Tr(t.labelEquals,void 0);case`identities`:return Uo(t)}}function Uo(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?Tr(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function Wo(e,t,n){switch(e){case`zones`:return Go(t,n);case`labels`:return Ko(t,n);case`identities`:return qo(t,n)}}function Go(e,t){let{zones:n,zonesExclude:r,...i}=e,a=Wn(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function Ko(e,t){let{labelEquals:n,...r}=e,i=Wn(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function qo(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=tr(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=Wn(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var Jo={all:`All`,only:`Only these`,except:`All except these`},Yo={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 Xo({draft:e,onChange:t,exceptOffered:r,plural:i,renderPicker:a,describe:o,testId:s}){let{t:c}=Dt(),l=(e,t,n)=>c(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),d=c(`ruleScope.items.${i}`,Yo[i].items),f=Ot.filter(t=>t!==`except`||r||e.mode===`except`),p=tr(e),m=mr(e),h=e.mode===`all`?null:e.mode;return n(`div`,{className:`mt-1 space-y-1.5`,"data-testid":s,children:[u(`div`,{role:`radiogroup`,"aria-label":l(`ruleScope.which`,`Which {{items}}`,d),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(n=>{let r=n===e.mode;return u(`button`,{type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${n}`,onClick:()=>t(Or(e,n)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,children:c(`ruleScope.mode.${n}`,Jo[n])},n)})}),h===null?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(`ruleScope.every.${i}`,Yo[i].every)}):a(Pn(e),n=>t(_r(e,n)),h),p.length>0&&n(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[l(`ruleScope.legacy`,`This rule also excludes {{items}} — kept when you save.`,p.map(o).join(`, `)),` `,u(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>t(jr(e)),children:c(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:l(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(o).join(`, `))})]})}function Zo(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 Qo(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})}t();function $o(e,t,n){let[r,i]=c(()=>Ho(e,t));return[r,r=>{i(r),n(Wo(e,t,r))}]}function es(e,t){return t?`failed`:e?`pending`:`answered`}function ts({conditions:e,onConditionsChange:t,exceptOffered:n,cameraIds:i,cameras:a}){let{t:o}=Dt(),[s,c]=$o(`zones`,e,t),{options:l,loading:d,failed:f}=Ar(i,a),p=r(()=>Qo(l),[l]),m=es(d,!1),h=f?{state:`failed`,devices:void 0}:{state:m,devices:m===`answered`?p:void 0},g=r(()=>new Map(p.map(e=>[e.id,e.name])),[p]);return u(Xo,{draft:s,onChange:c,exceptOffered:n,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>i.length===0?u(`p`,{className:Bn,children:o(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):u(W,{devices:p,listState:m,fleet:h,value:e,onChange:t,emptyMeansAll:!0,noun:`zone`,groupTitle:e=>e.type??o(`notificationRules.zones.group`,`Zones`),testId:`zone-picker`},n)})}function ns({conditions:e,onConditionsChange:t,exceptOffered:n}){let{t:i}=Dt(),[a,o]=$o(`identities`,e,t),{options:s,loading:c,failed:l}=Un(),d=r(()=>s.map(e=>({id:e.value,name:e.label})),[s]),f=r(()=>new Map(d.map(e=>[e.id,e.name])),[d]);return u(Xo,{draft:a,onChange:o,exceptOffered:n,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>u(W,{devices:d,listState:es(c,l),value:e,onChange:t,emptyMeansAll:n===`except`,...n===`only`?{emptyLabel:i(`notificationRules.faces.anyKnown`,`Any known face — nobody in particular`)}:{},noun:`face`,groupTitle:()=>i(`notificationRules.faces.group`,`Known faces`),testId:`identity-picker`},n)})}function rs({conditions:e,onConditionsChange:t}){let{t:n}=Dt(),[r,i]=$o(`labels`,e,t);return u(Xo,{draft:r,onChange:i,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>u(kn,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function is(e){let t=_t(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function as(e){return e.type??`Other`}t();function os({taxonomy:e,scope:t,onChange:n,exceptOffered:i}){let a=r(()=>is(e),[e]),o=r(()=>new Map((a??[]).map(e=>[e.id,e.name])),[a]);return u(Xo,{draft:t,onChange:n,exceptOffered:i,plural:`classes`,describe:e=>o.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>a===null?u(kn,{value:e,placeholder:`Add value…`,onChange:t}):u(W,{devices:a,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:as,testId:`class-picker`},n)})}function ss(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function cs({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return u(W,{devices:e.map(ss),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`,showAll:!0})}function ls({devices:e,scope:t,onChange:n,listState:r,savedScope:i,exceptOffered:a}){let o=new Map(e.map(e=>[e.id,e.name]));return u(Xo,{draft:t,onChange:n,exceptOffered:a,plural:`devices`,describe:e=>o.get(e)??`Device #${String(e)}`,testId:`rule-device-scope`,renderPicker:(t,n,a)=>u(cs,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function us(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function ds(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function fs(e){let t=us(e),n=e.data===void 0?[]:st(e.data.nodes),r=ds(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function ps(e){let t=us(e),n=e.data===void 0?[]:Fe(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var ms=[`nc-pickers`,`node-directory`],hs=[`nc-pickers`,`package-list`],gs=6e4,_s={hub:`Hub`,agent:`Agents`},vs={server:`Server`,framework:`Framework`,wrapper:`Wrapper`,addon:`Addons`};function ys(e){let t=_s[e.type??``]??`Nodes`;return e.location===`offline`?`${t} · offline`:t}function bs(e){return vs[e.type??``]??`Packages`}function xs({value:e,onChange:t,testId:r}){let a=p().trpcClient,o=i({queryKey:ms,staleTime:gs,queryFn:()=>a.nodes.directory.query()}),s=fs(o);return n(`div`,{children:[u(W,{devices:s.items,listState:s.listState,fleet:s.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:ys,...r===void 0?{}:{testId:r}}),o.data?.complete===!1&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:`The node history could not be read — offline nodes may be missing from this list.`})]})}function Ss({value:e,onChange:t,testId:n}){let r=p().trpcClient,a=ps(i({queryKey:hs,staleTime:gs,queryFn:()=>r.addons.listPackages.query()}));return u(W,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:bs,...n===void 0?{}:{testId:n}})}var Cs={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-tank-low`]},template:{body:`{{deviceName}}`}};function ws(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 Ts(e,t){return e===`pending`?`pending`:e===`success`?`current`:ws(t)===`BAD_REQUEST`?`outdated`:`unknown`}function Es(e){let t=p(),n=i({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(Cs)});return e?Ts(n.status,n.error):`pending`}t();var Ds=`/system/settings`,Os=`/system/notifications?tab=alarm`,ks=`text-primary underline-offset-2 hover:underline`;function As(e,t){let n=Wn(t);return Kn(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function js({family:e,value:t,cameras:i,allDevices:a,fleet:o,savedHadDevices:s,onChange:l}){let d=r(()=>t?.kinds??[],[t]),f=r(()=>a===void 0?i:a.map(ss),[a,i]),p=r(()=>i.map(e=>({id:e.id,name:e.name,type:`camera`})),[i]),m=Qn(e,d),h=Es(e===`device-events`),g=e===`alarm`,[_,v]=c(()=>Tr(t?.deviceIds,t?.excludeDeviceIds)),[y]=c(()=>Tr(t?.deviceIds,t?.excludeDeviceIds)),b=r(()=>{let e=new Map;for(let t of g?p:f)e.set(t.id,t.name);return e},[p,g,f]);return n(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[Yn(e).map(r=>n(`div`,{children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:r.label}),u(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:r.kinds.map(n=>{let r=d.includes(n.value);return u(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":n.label,onClick:()=>l(Ir(t,n.value,e)),className:r?`rounded-md border border-primary bg-primary/10 px-2 py-1 text-[11px] text-primary`:`rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:n.label},n.value)})})]},r.id)),e===`device-events`&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-device-alert-settings`,children:[`The battery threshold and the reminder interval are cluster settings (the consumable threshold is this rule’s own, below):`,` `,u(Kr,{to:Ds,target:`_blank`,rel:`noreferrer`,className:ks,children:`Settings → Battery & offline alerts`}),`.`]}),e===`alarm`&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[u(Kr,{to:Os,target:`_blank`,rel:`noreferrer`,className:ks,children:`Alarm settings`}),d.includes(`alarm-triggered`)&&` — when a rule sets the alarm off, this notification carries that rule's pictures.`]}),h===`outdated`&&n(`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:[`This hub’s server predates per-rule consumable thresholds and tank alerts: it drops a rule’s threshold when the rule is saved (the rule then judges at`,` `,15,`%) and refuses tank events. Update the server (@camstack/server) on every node first.`]}),h===`unknown`&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`}),m.consumableThreshold&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:`Consumable low at (%)`}),u(O,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:zn,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=Hn(e.target.value);n.kind!==`invalid`&&l(Kn(t,{consumableLowPercent:n.kind===`set`?n.value:void 0}))}})]}),m.deviceTypes&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Device types`}),u(kt,{options:cr,value:t?.deviceTypes??[],onChange:e=>l(Kn(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`})]}),Pr(t)&&u(`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:`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.`}),m.devices&&n(`div`,{children:[u(Xo,{draft:_,onChange:e=>{v(e),l(As(t,e))},exceptOffered:m.excludeDevices,plural:`devices`,describe:e=>b.get(e)??`Device #${String(e)}`,testId:`system-event-device-scope`,renderPicker:(e,t,n)=>u(W,{devices:g?p:f,listState:o.state,fleet:o,emptyMeansAll:!0,savedHadDevices:(n===`only`?y.include:y.exclude).length>0||n===`only`&&s,noun:g?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),s&&_.mode===`all`&&u(le,{noun:g?`camera`:`device`})]}),m.nodes&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Nodes`}),u(xs,{value:t?.nodeIds??[],onChange:e=>l(Kn(t,{nodeIds:e})),testId:`system-event-nodes`})]}),m.packages&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Packages`}),u(Ss,{value:t?.packageNames??[],onChange:e=>l(Kn(t,{packageNames:e})),testId:`system-event-packages`})]})]})}function Ms({value:e}){let t=e?.kinds??[];return n(`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:[u(`p`,{children:`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.`}),t.length>0&&u(`p`,{className:`mt-1 text-foreground`,children:t.map(jn).join(`, `)})]})}function Ns({family:e,onChange:t}){return n(`div`,{"data-testid":`system-family-select`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Kind of system rule`}),u(T,{value:e,"aria-label":`Kind of system rule`,onChange:e=>{let n=e.target.value;et(n)&&t(n)},options:lt.map(e=>({value:e,label:ct(e).label}))}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`})]})}t();function Ps({catalog:e,taxonomy:t,delivery:i,conditions:a,classScope:o,onClassScopeChange:s,actions:c,sequenceActionsOf:l,savedConditions:d,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x}){let{t:S}=Dt(),C=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,b(n)},w=rt({delivery:i,conditions:a}),T=r(()=>e.filter(e=>ht(e,i,w)&&rn(e.id,a)),[e,i,w,a]),E=r(()=>Vo(T),[T]),D=e=>T.some(t=>t.id===e),O=e=>Fs.has(e.id)?u(os,{taxonomy:t,scope:o,onChange:s,exceptOffered:D(`classesExclude`)}):Is.has(e.id)?u(ts,{conditions:a,onConditionsChange:b,exceptOffered:D(`zonesExclude`),cameraIds:m??p,cameras:h}):Ls.has(e.id)?u(ns,{conditions:a,onConditionsChange:b,exceptOffered:D(`identitiesExclude`)}):e.id===`labelEquals`?u(rs,{conditions:a,onConditionsChange:b}):null;return u(`div`,{className:`space-y-4`,children:E.map(e=>n(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${e.id}`,children:[u(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:S(`notificationRules.groups.${e.id}`,e.label)}),e.descriptors.map(e=>{let r=O(e);return n(`div`,{"data-testid":`condition-${e.id}`,children:[u(`label`,{className:J,children:Rs(e,S)}),r??u(Vs,{descriptor:e,kind:w,taxonomy:t,conditions:a,actions:c,sequenceActionsOf:l,savedConditions:d,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:C,onScheduleChange:x}),zs(e,S)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:zs(e,S)})]},e.id)})]},e.id))})}var Fs=new Set([`classes`,`classesExclude`]),Is=new Set([`zones`,`zonesExclude`]),Ls=new Set([`identities`,`identitiesExclude`]);function Rs(e,t){return Fs.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):Is.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):Ls.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 zs(e,t){if(!Bs.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var Bs=new Set([...Fs,...Is,...Ls,`labelEquals`,`crossing`]);function Vs({descriptor:e,kind:t,taxonomy:r,conditions:i,actions:o,sequenceActionsOf:s,savedConditions:c,schedule:l,deviceIds:d,cameras:f,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v}){switch(e.valueType){case`deviceIdList`:{if(!er(e.id))break;let t=e.id,n=i[t]??[];return u(Ln,{cameras:f,fleet:p,emptyMeansAll:!0,savedHadDevices:(c?.[t]?.length??0)>0,value:n,onChange:e=>_(t,e.length>0?e:void 0)})}case`stringList`:{if(!ur(e.id))break;let t=e.id,n=e=>_(t,e.length>0?e:void 0);if(t===`eventTypeTokens`)return u(Mr,{deviceIds:d,value:An(i,t),onChange:n});let a=nt(t,r);return a===null?u(kn,{value:An(i,t),placeholder:`Add value…`,onChange:n}):u(Fr,{picker:a,value:An(i,t),onChange:n})}case`number01`:{if(!gr(e.id))break;let t=e.id;return u(vr,{value:Jn(i,t),min:0,max:1,step:.05,onChange:e=>_(t,e)})}case`number`:{if(!Dr(e.id))break;let t=e.id;return u(vr,{value:Jn(i,t),min:0,step:1,onChange:e=>_(t,e)})}case`sourceSelect`:{if(!yr(e.id))break;let t=e.id;return Ks(e,i[t],e=>_(t,e))}case`systemEvent`:{if(!Zn(e.id))break;let n=e.id,r=at(t);return r===void 0?u(Ms,{value:i[n]}):u(js,{family:r,value:i[n],cameras:f,fleet:p,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[n]?.deviceIds?.length??0)>0,onChange:e=>_(n,e)})}case`deviceState`:if(!Nn(e.id))break;return u(or,{gateable:h,value:i.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!Vn(e.id))break;return u(qn,{scenes:g,value:i.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!wr(e.id))break;let t=e.id;return qs(e,i[t],e=>_(t,e))}case`packagePhase`:{if(!sr(e.id))break;let t=e.id;return u(T,{value:i[t]??``,options:[{value:``,label:`— any phase —`},...$t(e,on).map(e=>({value:e.value,label:e.label}))],onChange:e=>_(t,Gs(e.target.value))})}case`sensorTransition`:{if(!Gn(e.id))break;let t=e.id,r=Pe({conditions:i,...o===void 0?{}:{actions:o},...s===void 0?{}:{sequenceActionsOf:s}});return n(a,{children:[u(T,{value:i[t]??``,options:$t(e,rr).map(e=>({value:e.value,label:e.label})),onChange:e=>_(t,On(e.target.value))}),r&&u(`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(!Nr(e.id))break;let t=e.id;return u(Xn,{value:i[t],onChange:e=>_(t,e)})}case`occupancy`:{if(!Rn(e.id))break;let t=e.id;return u(lr,{deviceIds:d,cameras:f,classOptions:Hs(r),value:i[t],onChange:e=>_(t,e)})}case`audio`:{if(!pr(e.id))break;let t=e.id;return u(hr,{taxonomy:r,value:i[t],onChange:e=>_(t,e)})}case`schedule`:return u(kr,{value:l,onChange:v});default:break}return u(Us,{descriptor:e,conditions:i})}function Hs(e){let t=nt(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Us({descriptor:e,conditions:t}){let r=Object.entries(t).find(([t])=>t===e.id);return n(`p`,{className:Bn,children:[r!==void 0&&r[1]!==void 0?`Authored elsewhere and preserved — this admin editor cannot change it yet.`:`Not editable here yet — this condition has no admin editor.`,` `,n(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function Ws(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Gs(e){return on.find(t=>t.value===e)?.value}function Ks(e,t,n){return u(T,{value:t??`any`,options:$t(e,tn).map(e=>({value:e.value,label:e.label})),onChange:e=>n(Ws(e.target.value))})}function qs(e,t,n){return u(Er,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function Js({catalog:e,delivery:t,conditions:r,onConditionsChange:i}){let{t:a}=Dt(),o=rt({delivery:t,conditions:r}),s=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,i(n)},c=n=>e.find(e=>e.id===n&&ht(e,t,o)&&rn(n,r)),l=c(`source`),d=c(`crossing`);return l===void 0&&d===void 0?null:n(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[l&&yr(l.id)&&n(`div`,{"data-testid":`condition-source`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Rs(l,a)}),Ks(l,r.source,e=>s(`source`,e)),zs(l,a)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:zs(l,a)})]}),d&&wr(d.id)&&n(`div`,{"data-testid":`condition-crossing`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Rs(d,a)}),qs(d,r.crossing,e=>s(`crossing`,e)),zs(d,a)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:zs(d,a)})]})]})}var Ys=6e4,Xs=60*Ys,Zs=24*Xs,Qs=Date.UTC(2e3,0,1);function $s(e){if(e==null||e<Qs)return`—`;let t=Date.now()-e;return t<0||t<3e4?`just now`:t<Xs?`${String(Math.floor(t/Ys))}m ago`:t<Zs?`${String(Math.floor(t/Xs))}h ago`:`${String(Math.floor(t/Zs))}d ago`}var ec=[`notificationRules`,`getRuleLastRuns`],tc=3e4;function nc(){let e=p(),t=i({queryKey:ec,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:tc});return{status:t.status,data:t.data,error:t.error}}var rc={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function ic({cell:e}){switch(e.kind){case`pending`:return u(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":`Last run loading`,className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return u(`span`,{"data-testid":`rule-last-run-failed`,title:`Last run could not be read: ${e.reason}`,className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.phrase});case`ran`:return n(`span`,{className:`flex items-center gap-1.5`,title:new Date(e.lastAt).toLocaleString(),children:[u(`span`,{"data-testid":`rule-last-run-dot`,title:e.status,className:`inline-block h-2 w-2 rounded-full ${rc[e.status]}`}),u(`span`,{className:`text-[11px] text-foreground-subtle`,children:$s(e.lastAt)})]})}}function ac({rule:e,onOpenHistory:t}){return u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t(e),title:`History — this rule's deliveries`,"aria-label":`history of ${e.name}`,children:u(Me,{className:`h-3.5 w-3.5`})})}t();var oc=[`notificationRules`,`listSnoozes`],sc=[10,30,60,120];function cc({ruleId:e,ruleName:t,exempt:r=!1,variant:i=`icon`}){let a=p(),s=o(),[d,f]=c(30),[m,h]=c(null),g=l({mutationFn:t=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>s.invalidateQueries({queryKey:oc}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?i===`icon`?null:u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`}):i===`icon`?u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:`Silence this rule for ${Wt(30)} — it appears under "Silenced right now"`,"aria-label":`snooze ${t}`,"data-testid":`nc-rule-snooze-now`,children:g.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(ue,{className:`h-3.5 w-3.5`})}):n(`div`,{className:`space-y-1`,children:[n(`div`,{className:`flex items-end gap-2`,children:[u(`div`,{className:`w-32`,children:u(T,{value:String(d),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&f(t)},options:sc.map(e=>({value:String(e),label:Wt(e)}))})}),n(A,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(d),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(ue,{className:`h-3.5 w-3.5`}),`Silence this rule now`]})]}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`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&&u(`p`,{className:`text-[10px] text-danger`,children:m})]})}t();function lc(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function uc(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 dc(e,t){let[,n]=c(0);d(()=>{let r=uc(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 fc(){let e=p();return i({queryKey:oc,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function pc({rule:e,snoozes:t,exempt:r}){let{t:i}=Dt(),a=p(),s=o();dc(t,e.id);let c=lc(t,e.id,Date.now()),d=()=>s.invalidateQueries({queryKey:oc}),f=l({mutationFn:()=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e.id,durationMinutes:30}}),onSuccess:d}),m=l({mutationFn:async e=>{for(let t of e)await a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:d});if(r)return null;let h=f.isError||m.isError;return n(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[u(G,{checked:c.length>0,disabled:!e.enabled||f.isPending||m.isPending,onCheckedChange:e=>e?f.mutate():m.mutate(c),"aria-label":i(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,e.name),title:i(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),h&&u(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:i(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var mc=`pipeline-analytics`,hc=`nc.getRuleStatus`,gc=`nc.testRule`;function _c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function vc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function yc(e){if(!_c(e))return;let t=vc(e,`id`),n=vc(e,`downloadPath`),r=Y(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:vc(e,`mediaType`)??`video`,sizeBytes:Y(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function bc(e){if(!_c(e))return;let t=Y(e,`startMs`),n=Y(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function xc(e){if(!_c(e))return null;let t=Y(e,`deviceId`);if(t===void 0)return null;let n=Y(e,`lastGeneratedAt`),r=yc(e.lastArtifact),i=e.rendering,a=_c(i)?{startedAt:Y(i,`startedAt`)??0,windowStartMs:Y(i,`windowStartMs`)??0,windowEndMs:Y(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function Sc(e){if(!_c(e))return null;let t=Y(e,`deviceId`),n=vc(e,`windowKey`),r=Y(e,`openedAt`),i=Y(e,`closesAt`),a=Y(e,`members`),o=Y(e,`pending`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0?null:{deviceId:t,windowKey:n,openedAt:r,closesAt:i,members:a,pending:o}}function Cc(e){if(!_c(e))return null;let t=vc(e,`kind`);if(t===`none`)return{kind:`none`,reason:vc(e,`reason`)??``};if(t===`occupancy`){let t=Y(e,`deviceId`),n=Y(e,`threshold`),r=Y(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=vc(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=Y(e,`count`),s=Y(e,`observedAt`),c=Y(e,`since`),l=vc(e,`scope`),u=vc(e,`className`),d=vc(e,`warning`);return{kind:`occupancy`,deviceId:t,threshold:n,sustainSeconds:r,...l===void 0?{}:{scope:l},...u===void 0?{}:{className:u},...o===void 0?{}:{count:o},...typeof e.occupied==`boolean`?{occupied:e.occupied}:{},...s===void 0?{}:{observedAt:s},...c===void 0?{}:{since:c},...a===void 0?{}:{unavailable:a},...d===void 0?{}:{warning:d}}}if(t===`grouped`){let t=Y(e,`groupingSec`);if(t===void 0)return null;if(e.openWindows===null){let n=vc(e,`reason`);return{kind:`grouped`,groupingSec:t,openWindows:null,...n===void 0?{}:{reason:n}}}if(!Array.isArray(e.openWindows))return null;let n=[];for(let t of e.openWindows){let e=Sc(t);if(e===null)return null;n.push(e)}return{kind:`grouped`,groupingSec:t,openWindows:n}}if(t===`timelapse`){let t=Array.isArray(e.devices)?e.devices:[],n=[];for(let e of t){let t=xc(e);t!==null&&n.push(t)}let r=bc(e.lastWindow),i=e.nextWindow,a=_c(i)?{startMs:Y(i,`startMs`)??0,endMs:Y(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:Y(e,`settleMs`)??0}}return null}function wc(e){let t=Math.max(0,Math.floor(e/6e4));if(t<1)return`less than a minute`;if(t<60)return`${String(t)} min`;let n=Math.floor(t/60),r=t%60;if(n<24)return r===0?`${String(n)} h`:`${String(n)} h ${String(r)} min`;let i=Math.floor(n/24),a=n%24;return a===0?`${String(i)} d`:`${String(i)} d ${String(a)} h`}function Tc(e){if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${t.toFixed(0)} kB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}function Ec(e,t){let n=e.scope??`the whole frame`,r=e.className??`objects`;if(e.unavailable!==void 0){let t=e.unavailable===`no-snapshot`?`no live count for this camera yet — the condition fails closed until one arrives`:`“${n}” is not in this camera’s current snapshot — the condition fails closed (deleted zone?)`;return e.warning===void 0?t:`${e.warning} · ${t}`}let i=[`Now: ${String(e.count??0)}/${String(e.threshold)} ${r} in ${n}`,e.occupied===!0?`condition TRUE`:`condition false`];e.since!==void 0&&i.push(`for ${wc(Math.max(0,t-e.since))}`),i.push(`holds ${String(e.sustainSeconds)} s before firing`);let a=i.join(` · `);return e.warning===void 0?a:`${e.warning} · ${a}`}function Dc(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${wc(Math.max(0,n-e.rendering.startedAt))} — the window ${new Date(e.rendering.windowStartMs).toLocaleString()} → ${new Date(e.rendering.windowEndMs).toLocaleString()}`;if(e.lastGeneratedAt===void 0)return`${t}: never produced a video yet`;let r=new Date(e.lastGeneratedAt).toLocaleString(),i=e.lastArtifact;return i===void 0?`${t}: last produced ${r} — the video is no longer on the shelf`:`${t}: last produced ${r} · ${Tc(i.sizeBytes)}`}function Oc(e){return{windows:e.length,waiting:e.reduce((e,t)=>e+t.pending,0)}}var kc=`nc.listPrunes`;function Ac(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var jc=new Set([`rule`,`timelapse`,`summary`]),Mc=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function Nc(e){return typeof e==`string`&&jc.has(e)}function Pc(e){return typeof e==`string`&&Mc.has(e)}function Fc(e){return e===`device`||e===`target`}function Ic(e){if(!Ac(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!Nc(t)||!Fc(r)||!Pc(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 Lc(e){return!Ac(e)||!Array.isArray(e.prunes)?null:e.prunes.map(Ic).filter(e=>e!==null)}function Rc(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 zc(e,t){let n=t(e.at);return e.subjectKind===`device`?`Disabled on ${n}: its last device (#${e.subject}) was deleted.`:`Disabled on ${n}: its last delivery target (${e.subject}) was deleted.`}function Bc(e){return new Date(e).toLocaleDateString()}function Vc({kind:e,ruleId:t,enabled:r,updatedAt:a}){let o=p(),s=i({queryKey:[`pipelineAnalytics`,kc],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>Lc(await o.trpcClient.addons.custom.mutate({addonId:mc,action:kc,input:{}}))}).data;if(s==null)return null;let c=Rc(s,e,t,r,a);return c===null?null:n(`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:[u(R,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`span`,{children:zc(c,Bc)})]})}var Hc=5e3;function Uc({status:e,now:t,name:r}){let{t:i}=Dt();if(e.openWindows===null)return n(`p`,{className:`flex items-start gap-1.5`,children:[u(V,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),u(`span`,{"data-testid":`nc-grouped-status-headline`,children:i(`notificationRules.status.grouped.unknown`,{reason:e.reason??``,defaultValue:`Open windows unknown — {{reason}}`})})]});let o=e.openWindows,{windows:s,waiting:c}=Oc(o);return n(a,{children:[n(`p`,{className:`flex items-start gap-1.5`,children:[u(V,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),u(`span`,{"data-testid":`nc-grouped-status-headline`,children:s===0?i(`notificationRules.status.grouped.none`,`No window open`):`${i(`notificationRules.status.grouped.windows`,{count:s,defaultValue_one:`{{count}} open window`,defaultValue_other:`{{count}} open windows`})} · ${i(`notificationRules.status.grouped.waiting`,{count:c,defaultValue:`{{count}} waiting`})}`})]}),o.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[u(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),u(`span`,{children:i(`notificationRules.status.grouped.windowLine`,{camera:r(e.deviceId),members:e.members,pending:e.pending,seconds:Math.max(0,Math.ceil((e.closesAt-t)/1e3)),defaultValue:`{{camera}} · {{members}} in the window · {{pending}} waiting · closes within {{seconds}} s`})})]},e.windowKey))]})}function Wc({ruleId:e,cameraName:t}){let r=p(),o=i({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:Hc,queryFn:async()=>Cc(await r.trpcClient.addons.custom.mutate({addonId:mc,action:hc,input:{ruleId:e}}))}).data;if(o==null||o.kind===`none`)return null;let s=Date.now(),c=e=>t?.(e)??`camera ${String(e)}`;return n(`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`&&n(`p`,{className:`flex items-start gap-1.5`,children:[o.unavailable!==void 0||o.warning!==void 0?u(je,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):u(V,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),n(`span`,{children:[u(`span`,{className:`text-foreground`,children:c(o.deviceId)}),` —`,` `,Ec(o,s)]})]}),o.kind===`grouped`&&u(Uc,{status:o,now:s,name:c}),o.kind===`timelapse`&&n(a,{children:[o.devices.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[u(V,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),n(`span`,{children:[Dc(e,c(e.deviceId),s),e.lastArtifact!==void 0&&n(a,{children:[` · `,u(`a`,{className:`text-primary hover:underline`,href:`/${e.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:`open`})]})]})]},e.deviceId)),n(`p`,{className:`flex items-start gap-1.5`,children:[u(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),n(`span`,{children:[o.nextWindow===void 0?`No further window opens in the next nine days`:`Next window opens ${new Date(o.nextWindow.startMs).toLocaleString()}`,o.settleMs>0&&` · rendered ${String(Math.round(o.settleMs/6e4))} min after it closes, so the footage has settled`]})]})]})]})}function Gc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function qc(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Jc(e){if(!Gc(e))return null;let t=Kc(e,`ruleId`),n=Kc(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=Kc(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:Kc(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:qc(e,`targetIds`)}}function Yc(e){if(!Gc(e))return null;let t=Kc(e,`conditionId`),n=Kc(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Xc(e){if(!Gc(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(!Gc(t))continue;let e=Kc(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(!Gc(t))continue;let e=Kc(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 Zc(e){if(!Gc(e))return null;let t=Kc(e,`recordId`),n=Kc(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=Jc(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Yc(t);e!==null&&i.push(e)}let a=Kc(e,`droppedBy`),o=Xc(e.stateSummary);return{recordId:t,delivery:n,trigger:Kc(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:Kc(e,`still`)??`none`,notes:qc(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function Qc(e){if(e.stateSummary!==void 0)return $c(e,e.stateSummary);if(e.droppedBy!==void 0)return`Nothing was evaluated (${e.droppedBy}) — the event was dropped before any rule was consulted.`;let t=e.outcomes[0];if(t===void 0)return`This rule was not a candidate for a ${e.trigger} event — check its trigger, and that it is enabled.`;if(!t.matched)return t.failedCondition===void 0?`The rule did not match the event built from its own conditions.`:`The rule did not match — the “${t.failedCondition}” condition refused the event.`;if(t.enqueued===0)return`The rule matched, but no notification was queued: every target is opted out of it, or it addresses none.`;let n=e.still===`live`?` with a live snapshot`:e.still===`unavailable`?` (the camera returned no snapshot, so it ships text-only)`:e.still===`unattachable`?` (this kind of rule carries no picture in production either)`:``;return`Matched — ${String(t.enqueued)} notification${t.enqueued===1?``:`s`} queued to ${String(t.targetIds.length)} target${t.targetIds.length===1?``:`s`}${n}. It is marked [TEST] in the body.`}function $c(e,t){if(t.nothingToReport)return`Nothing to report right now (${t.sections.map(e=>`${e.id}: ${e.status===`unavailable`?`unavailable`:`none open`}`).join(`, `)}) — nothing was sent, exactly as the scheduled summary would send nothing.`;let n=t.rows.reduce((e,t)=>e+t.enqueued,0),r=e.outcomes[0]?.targetIds.length??0;if(n===0)return`The summary was built, but no notification was queued: the rule reaches no target (its users are not admins, or every target is opted out).`;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`?` (one per category: ${i.join(`, `)})`:``;return`Summary built now — ${String(n)} notification${n===1?``:`s`} queued${a} to ${String(r)} target${r===1?``:`s`}. ${n===1?`It is`:`They are`} marked [TEST] in the body.`}t();function el({ruleId:e,ruleName:t,fallbackDeviceId:r,variant:i=`icon`,showResult:o=!1}){let s=p(),[d,f]=c(null),[m,h]=c(null),g=l({mutationFn:async()=>Zc(await s.trpcClient.addons.custom.mutate({addonId:mc,action:gc,input:{ruleId:e,...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{f(null),h(null)},onSuccess:e=>f(e),onError:e=>h(e instanceof Error?e.message:`The test could not be run.`)}),_=d===null?m===null?void 0:m:Qc(d);return n(a,{children:[n(A,{size:`sm`,variant:i===`icon`?`ghost`:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(),title:_??`Test now — fires this rule and really sends the notification`,"aria-label":`test ${t} now`,"data-testid":`nc-rule-test-now`,children:[g.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Ne,{className:`h-3.5 w-3.5`}),i===`full`&&`Test now`]}),o&&m!==null&&u(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:m}),o&&d!==null&&n(`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:[u(`p`,{className:`text-foreground`,children:Qc(d)}),d.planNotes.map(e=>n(`p`,{className:`flex gap-1.5`,children:[u(je,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId)),d.notes.map(e=>n(`p`,{children:[`· `,e]},e))]})]})}t();var tl=[`notificationRules`,`listSnoozes`],nl=3e4;function rl(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function il(e){if(e===0)return`ending`;if(e<60)return`${e}m left`;let t=Math.floor(e/60),n=e%60;return n===0?`${t}h left`:`${t}h ${n}m left`}function al({rules:e}){let t=p(),a=o(),s=i({queryKey:tl,refetchInterval:nl,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),c=l({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>a.invalidateQueries({queryKey:tl})}),d=r(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),f=Date.now(),m=(s.data??[]).filter(e=>f>=e.startedAt&&f<e.expiresAt);return n(x,{className:`p-4`,children:[n(`div`,{className:`flex items-center gap-2 mb-3`,children:[u(ue,{className:`h-4 w-4 text-foreground-subtle`}),u(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),m.length===0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`}),u(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:m.map(e=>n(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[n(`div`,{className:`min-w-0`,children:[n(`div`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:d.get(e.ruleId??``)??`A rule`}),e.global&&u(q,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&u(q,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&u(q,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,il(rl(e,f))]})]}),u(A,{size:`sm`,variant:`outline`,disabled:c.isPending,onClick:()=>c.mutate(e.id),children:`End now`})]},e.id))})]})}var X=`block text-[11px] font-medium text-foreground mb-1`,ol=`mt-1 text-[10px] text-foreground-subtle`;function Z({title:e,hint:t,children:r}){return n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),u(`div`,{className:`space-y-3`,children:r})]})}function sl({problems:e,testId:t=`digest-problems`}){return e.length===0?null:n(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":t,children:[n(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[u(je,{className:`h-3.5 w-3.5`}),`This rule could never produce anything, so it cannot be saved:`]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function cl({warnings:e,testId:t=`digest-warnings`}){return e.length===0?null:n(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":t,children:[n(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[u(R,{className:`h-3.5 w-3.5`}),`Worth knowing:`]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function ll({cameras:e,value:t,onChange:r,fleet:i,hint:a}){return n(`div`,{className:`space-y-1`,children:[u(W,{devices:e,listState:i.state,fleet:i,value:t,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),a!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function ul(e){return u(ne,{...e,testIdPrefix:e.testIdPrefix??`digest-target`,emptyMessage:e.emptyMessage??`No delivery target is configured. Add one on the Targets tab first — without one the artefact is rendered and thrown away.`})}function Q({label:e,value:t,onChange:r,min:i,max:a,step:o,hint:s,emptyPlaceholder:c,testId:l,disabled:d=!1}){return n(`div`,{children:[u(`label`,{className:X,children:e}),u(O,{type:`number`,value:t===void 0?``:String(t),disabled:d,...i===void 0?{}:{min:i},...a===void 0?{}:{max:a},...o===void 0?{}:{step:o},...c===void 0?{}:{placeholder:c},...l===void 0?{}:{"data-testid":l},onChange:e=>{let t=e.target.value.trim();if(t.length===0){r(void 0);return}let n=Number(t);Number.isFinite(n)&&r(n)}}),s!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function dl({label:e,checked:t,onChange:r,hint:i,testId:a}){return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:t,onCheckedChange:r,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),i!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:i})]})}function fl({title:e,body:t,onTitleChange:r,onBodyChange:i,family:a,testIdPrefix:o}){let s=ho(),c=e=>s.data?uo(s.data,{family:a,field:e}):void 0;return n(`div`,{className:`space-y-2`,children:[u(bo,{label:`Notification title`,value:e,onChange:r,vars:c(`title`),testId:`${o}-title`}),u(bo,{label:`Notification body`,value:t,onChange:i,vars:c(`body`),multiline:!0,testId:`${o}-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank to use the hub's own wording (editable on the Texts tab).`}),u(xo,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function pl({open:e,ruleName:t,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){return e?u(Ae,{open:!0,onOpenChange:e=>!e&&s(),children:u(S,{width:`sm`,children:n(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[n(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[u(Ne,{className:`h-4 w-4 text-warning`}),`Send a real notification now?`]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[`"`,t,`" will be produced over `,r,` and DELIVERED to`,` `,i,` — on every phone that target reaches, right now. This is not a dry run.`]}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`It does not consume the schedule: the next scheduled run still happens.`}),c,n(`div`,{className:`flex justify-end gap-2`,children:[u(A,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),u(A,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?`Sending…`:`Produce and send`})]})]})})}):null}function ml(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 hl=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function gl(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function _l(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>hl[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${gl(t.startMinute)}–${gl(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function vl(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${ml(Math.round(r/1e3))} ago`}function yl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bl(e){return Array.isArray(e)?`[${e.map(bl).join(`,`)}]`:yl(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${bl(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function xl(e,t){return bl(e)===bl(t)}function Sl(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,Cl=`nc.getTexts`,wl=`nc.setLanguage`,Tl=`nc.setTextOverrides`,El={en:`English`,it:`Italiano`};function Dl(e){return e===`en`||e===`it`}function Ol(e){return e===`override`||e===`shipped`||e===`fallback`}function kl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Al(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 jl(e){if(!kl(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`||!Dl(r)||!Ol(o)||i!==null&&typeof i!=`string`)return null;let s=Al(e.placeholders),c=Al(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 Ml(e){if(!kl(e))return null;let{language:t,activeLanguage:n}=e;if(!Dl(t)||!Dl(n))return null;let r=Al(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Dl(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=jl(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Nl(e,t){return t.get(e.key)??e.override??e.shipped}function Pl(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 Fl(e,t){return Object.keys(Pl(e,t)).length}function Il(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 Ll(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Rl(e){return e.pluralCategories.length===0?null:`This text has one form per count (${e.pluralCategories.join(`, `)}). An override replaces all of them with a single sentence.`}var zl=[`notificationCalendarEvents`,`list`],Bl=`nc.listCalendarEventsRules`,Vl=`nc.upsertCalendarEventsRule`,Hl=`nc.deleteCalendarEventsRule`,Ul=Ct({timezone:St().min(1),windows:Tt(Ct({days:Tt(bt().int().min(0).max(6)).min(1),startMinute:bt().int().min(0).max(1439),endMinute:bt().int().min(0).max(1439)})).min(1),invert:Et().optional()}),Wl=Ct({targetId:St().min(1),params:wt(St(),xt()).optional()}),Gl=Ct({rules:Tt(Ct({id:St().min(1),name:St().min(1),enabled:Et(),schedule:Ul,calendars:Tt(St().min(1)).max(64).optional(),calendarsExclude:Tt(St().min(1)).max(64).optional(),horizonDays:bt().int(),deliverEmpty:Et(),targets:Tt(Wl).min(1),template:Ct({title:St().optional(),body:St().optional()}).optional(),priority:bt().int(),generatedAt:bt().optional(),readOnly:Et().optional()}))});function Kl(e){let t=Gl.safeParse(e);return t.success?t.data.rules:null}function ql(e){return e.readOnly!==!0}var Jl=[{key:`basics`,label:`Basics`},{key:`schedule`,label:`Schedule`},{key:`calendars`,label:`Calendars`},{key:`targets`,label:`Targets`},{key:`template`,label:`Template`}],Yl=`basics`;function Xl(){return Ke([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function Zl(e){let t=Ve(e);if(t===null||t.length===0)return _l(e);let n=t[0];return n===void 0?_l(e):`At ${String(Math.floor(n.minute/60)).padStart(2,`0`)}:${String(n.minute%60).padStart(2,`0`)}${t.length>1?` +${t.length-1}`:``}`}function Ql(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:Xl(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``}}function $l(e){return{name:e.name,enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,calendars:e.calendars??[],calendarsExclude:e.calendarsExclude??[],targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``}}function eu(e){return e.name.trim().length>0&&e.targetIds.length>0&&e.horizonDays>=1&&e.horizonDays<=30&&e.schedule.windows.length>0}function tu(e){let t=e.targetIds.map(e=>({targetId:e}));return{name:e.name.trim(),enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,...e.calendars.length>0?{calendars:[...e.calendars]}:{},...e.calendarsExclude.length>0&&e.calendars.length===0?{calendarsExclude:[...e.calendarsExclude]}:{},targets:t,...e.templateTitle.trim().length>0||e.templateBody.trim().length>0?{template:{...e.templateTitle.trim().length>0?{title:e.templateTitle.trim()}:{},...e.templateBody.trim().length>0?{body:e.templateBody.trim()}:{}}}:{}}}function nu(e,t){let n=tu(e);return{...n,calendars:e.calendars.length===0&&(t.calendars?.length??0)>0?null:n.calendars,calendarsExclude:e.calendarsExclude.length===0&&(t.calendarsExclude?.length??0)>0?null:n.calendarsExclude,template:e.templateTitle.trim().length===0&&e.templateBody.trim().length===0&&t.template!==void 0?null:n.template}}function ru(e){return`next ${String(e)} day(s)`}function iu(e){return e.calendars!==void 0&&e.calendars.length>0?`${String(e.calendars.length)} calendar${e.calendars.length===1?``:`s`}`:e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?`all except ${String(e.calendarsExclude.length)}`:`all calendars`}t();function au({rule:e,targets:t,onSaved:r,onCancel:i}){let a=p(),o=oe(),[s,d]=c(()=>e===null?Ql():$l(e)),[f,m]=c(()=>Tr(e===null?void 0:e.calendars,e===null?void 0:e.calendarsExclude)),[h,g]=c(Yl),[_,v]=c(null),y=e=>d(t=>({...t,...e})),b=l({mutationFn:async()=>{let t=Wn(f),n={...s,calendars:t.include??[],calendarsExclude:t.exclude??[]};if(!eu(n))throw Error(`Name, at least one target, and a schedule are required`);let r=e===null?{rule:tu(n)}:{ruleId:e.id,patch:nu(n,e)};await a.trpcClient.addons.custom.mutate({addonId:$,action:Vl,input:r})},onSuccess:()=>r(),onError:e=>{v(e instanceof Error?e.message:String(e))}}),x=(o.data??[]).map(e=>({id:e.id,name:e.name}));return u(Ae,{open:!0,onOpenChange:e=>!e&&i(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendar-events-editor`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between gap-2`,children:[n(`div`,{className:`flex min-w-0 items-center gap-2`,children:[u(me,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:e===null?`New calendar events`:s.name})]}),n(`div`,{className:`flex shrink-0 items-center gap-2`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`}),u(A,{size:`sm`,type:`button`,disabled:b.isPending,onClick:()=>{v(null),b.mutateAsync()},"data-testid":`calendar-events-save`,children:b.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):`Save`})]})]}),n(D,{value:h,onValueChange:e=>{let t=Jl.find(t=>t.key===e);t!==void 0&&g(t.key)},children:[u(Ce,{className:`mb-3`,children:Jl.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(z,{className:`space-y-4 pr-1`,children:[_===null?null:u(`p`,{className:`text-sm text-destructive`,children:_}),u(M,{value:`basics`,className:`space-y-3`,children:n(Z,{title:`Basics`,children:[n(`label`,{className:`block text-sm`,children:[`Name`,u(O,{className:`mt-1`,value:s.name,onChange:e=>y({name:e.target.value}),"data-testid":`calendar-events-name`})]}),u(Q,{label:`Horizon (days)`,value:s.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&y({horizonDays:e})}}),u(Q,{label:`Priority`,value:s.priority,min:1,max:5,onChange:e=>{e!==void 0&&y({priority:e})}}),u(dl,{label:`Enabled`,checked:s.enabled,onChange:e=>y({enabled:e})}),u(dl,{label:`Deliver when empty`,checked:s.deliverEmpty,onChange:e=>y({deliverEmpty:e})})]})}),u(M,{value:`schedule`,className:`space-y-3`,children:n(Z,{title:`Schedule`,children:[u(kr,{mode:`times`,value:s.schedule,onChange:e=>y({schedule:e})}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`One send time per row. The digest fires at that minute.`})]})}),u(M,{value:`calendars`,className:`space-y-3`,children:u(Z,{title:`Calendars`,children:u(Xo,{draft:f,onChange:m,exceptOffered:!0,plural:`calendars`,describe:e=>x.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>u(W,{devices:x,listState:o.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),u(M,{value:`targets`,className:`space-y-3`,children:u(Z,{title:`Targets`,children:u(ul,{targets:t,value:s.targetIds,onChange:e=>y({targetIds:e})})})}),u(M,{value:`template`,className:`space-y-3`,children:n(Z,{title:`Template`,children:[n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Optional. Leave blank for the default digest body (tomorrow highlighted, then later days). Variables: `,`{{rule}}`,`, `,`{{count}}`,`, `,`{{horizonDays}}`,`,`,` `,`{{events}}`,`.`]}),n(`label`,{className:`block text-sm`,children:[`Title`,u(O,{className:`mt-1`,value:s.templateTitle,onChange:e=>y({templateTitle:e.target.value})})]}),n(`label`,{className:`block text-sm`,children:[`Body`,u(`textarea`,{className:`mt-1 min-h-[8rem] w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:s.templateBody,onChange:e=>y({templateBody:e.target.value})})]})]})})]})]})]})})}var ou=`nc.listSummaryRules`,su=`nc.upsertSummaryRule`,cu=`nc.deleteSummaryRule`,lu=`nc.testSummaryRule`,uu=3600,du=86400,fu=3600,pu=3600,mu=3*36e5,hu=[`importance`,`recency`,`dwell`],gu={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},_u=[`none`,`tiles`,`all`],vu=`none`,yu={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},bu=[`en`,`it`],xu=[`deliver-without-text`,`skip`],Su=2048,Cu=2e3;function wu(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Tu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Eu(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 Du(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`string`)return null;t.push(n)}return t}function Ou(e){if(e!==void 0)return typeof e==`string`?e:null}function ku(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function Au(e){return hu.some(t=>t===e)}function ju(e){return e===void 0?vu:_u.find(t=>t===e)??null}function Mu(e){if(!Tu(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Tu(n))return null;let e=Eu(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=Ou(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 Nu(e){if(!Tu(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=Mu(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 Pu(e){if(e==null)return;if(!Tu(e))return null;let t=e.classes===void 0?void 0:Du(e.classes),n=e.classesExclude===void 0?void 0:Du(e.classesExclude),r=e.zones===void 0?void 0:Du(e.zones);if(t===null||n===null||r===null)return null;let i=ku(e.minImportance),a=ku(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 Fu(e){if(e==null)return;if(!Tu(e))return null;let t=Ou(e.title),n=Ou(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function Iu(e){return bu.some(t=>t===e)}function Lu(e){return xu.some(t=>t===e)}function Ru(e){if(e==null)return;if(!Tu(e)||typeof e.enabled!=`boolean`)return null;let t=Ou(e.profileId),n=Ou(e.prompt);if(t===null||n===null)return null;let r=ku(e.maxImagePx),i=ku(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!Iu(a))return null;let o=e.onFailure;return o!==void 0&&!Lu(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 zu(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Tu(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Tu(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function Bu(e){if(!Tu(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`||!Au(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Eu(e.deviceIds),u=Nu(e.window),d=zu(e.targets);if(l===null||u===null||d===null)return null;let f=Pu(e.filters),p=Fu(e.template);if(f===null||p===null)return null;let m=Ou(e.captionText),h=ku(e.generatedAt),g=ku(e.updatedAt);if(m===null||h===null||g===null)return null;let _=ju(e.captions);if(_===null)return null;let v=Ru(e.ai);return v===null?null:{id:t,name:n,enabled:r,deviceIds:l,window:u,...f===void 0?{}:{filters:f},maxTiles:i,maxAiImages:a,rank:o,barrierSeconds:s,targets:d,...p===void 0?{}:{template:p},captions:_,...m===void 0?{}:{captionText:m},deliverEmpty:c,priority:e.priority,...h===void 0?{}:{generatedAt:h},...g===void 0?{}:{updatedAt:g},readOnly:e.readOnly===!0,...v===void 0?{}:{ai:v}}}function Vu(e){if(!Tu(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=Bu(n);if(e===null)return null;t.push(e)}return t}function Hu(e){if(!Tu(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=ku(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=ku(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Ou(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 Uu(){return{name:``,enabled:!0,deviceIds:[],windowKind:`motion`,schedule:void 0,quietSeconds:60,maxWindowSeconds:300,classes:[],classesExclude:[],zones:[],minImportance:void 0,minDwellSeconds:void 0,includeStationary:!1,maxTiles:12,maxAiImages:6,rank:`importance`,barrierSeconds:120,targetIds:[],templateTitle:``,templateBody:``,mosaicCaptions:vu,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function Wu(e){let t=Uu(),n=e.window.kind===`motion`?e.window:null;return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],windowKind:e.window.kind,schedule:e.window.kind===`schedule`?e.window.schedule:void 0,quietSeconds:n?.quietSeconds??t.quietSeconds,maxWindowSeconds:n?.maxWindowSeconds??t.maxWindowSeconds,classes:[...e.filters?.classes??[]],classesExclude:[...e.filters?.classesExclude??[]],zones:[...e.filters?.zones??[]],minImportance:e.filters?.minImportance,minDwellSeconds:e.filters?.minDwellSeconds,includeStationary:e.filters?.includeStationary===!0,maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,mosaicCaptions:e.captions,captionText:e.captionText??``,deliverEmpty:e.deliverEmpty,priority:e.priority,aiEnabled:e.ai?.enabled??t.aiEnabled,aiProfileId:e.ai?.profileId??``,aiPrompt:e.ai?.prompt??``,aiLanguage:e.ai?.language??``,aiMaxImagePx:e.ai?.maxImagePx,aiTimeoutSeconds:e.ai?.timeoutMs===void 0?void 0:Math.round(e.ai.timeoutMs/1e3),aiOnFailure:e.ai?.onFailure??t.aiOnFailure}}function Gu(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Ku(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 qu(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 Ju(e){return Sl(e.targetIds)}function Yu(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 Xu(e){let t=Ku(e),n=qu(e),r=Yu(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:Gu(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Ju(e),...n===void 0?{}:{template:n},captions:e.mosaicCaptions,...i.length>0?{captionText:i}:{},deliverEmpty:e.deliverEmpty,priority:e.priority,...r===void 0?{}:{ai:r}}}function Zu(e,t){let n=Xu(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),xl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),xl(n.window,t.window)||(r.window=n.window),xl(n.filters,t.filters)||(r.filters=n.filters??null),n.maxTiles!==t.maxTiles&&(r.maxTiles=n.maxTiles),n.maxAiImages!==t.maxAiImages&&(r.maxAiImages=n.maxAiImages),n.rank!==t.rank&&(r.rank=n.rank),n.barrierSeconds!==t.barrierSeconds&&(r.barrierSeconds=n.barrierSeconds),xl(n.targets,t.targets)||(r.targets=n.targets),xl(n.template,t.template)||(r.template=n.template??null),n.captions!==t.captions&&(r.captions=n.captions),(n.captionText??``)!==(t.captionText??``)&&(r.captionText=n.captionText??``),n.deliverEmpty!==t.deliverEmpty&&(r.deliverEmpty=n.deliverEmpty),n.priority!==t.priority&&(r.priority=n.priority),xl(n.ai,t.ai)||(r.ai=n.ai??null),r}function Qu(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 ${uu}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${du}s.`)),(e.maxTiles<1||e.maxTiles>24)&&t.push(`The mosaic holds between 1 and 24 tiles.`),e.maxAiImages>e.maxTiles&&t.push(`AI images (${e.maxAiImages}) cannot exceed tiles (${e.maxTiles}) — the model cannot judge frames the mosaic does not contain.`),(e.barrierSeconds<0||e.barrierSeconds>3600)&&t.push(`The track-close wait is between 0s and ${fu}s.`),e.minImportance!==void 0&&(e.minImportance<0||e.minImportance>1)&&t.push(`Minimum importance is a score between 0 and 1.`),e.minDwellSeconds!==void 0&&(e.minDwellSeconds<0||e.minDwellSeconds>3600)&&t.push(`Minimum stay is between 0s and ${pu}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 ${Cu} 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 ${Su} 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 $u(e){return Qu(e).length===0}function ed(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 td=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,label:`Window`,fields:[`windowKind`,`schedule`,`quietSeconds`,`maxWindowSeconds`,`barrierSeconds`]},{key:`content`,label:`What goes in`,fields:[`classes`,`classesExclude`,`zones`,`minImportance`,`minDwellSeconds`,`includeStationary`]},{key:`mosaic`,label:`Mosaic`,fields:[`maxTiles`,`rank`,`mosaicCaptions`,`captionText`]},{key:`ai`,label:`AI`,fields:[`aiEnabled`,`aiProfileId`,`aiPrompt`,`aiLanguage`,`aiMaxImagePx`,`aiTimeoutSeconds`,`aiOnFailure`,`maxAiImages`]},{key:`delivery`,label:`Delivery`,fields:[`targetIds`,`priority`,`deliverEmpty`,`templateTitle`,`templateBody`]}],nd=`rule`;function rd(e){return td.find(t=>t.key===e)?.key}function id(e){return e.kind===`motion`?`Motion · ${ml(e.quietSeconds)} quiet · max ${ml(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${_l(e.schedule)}`}function ad(e,t){return vl(e,t,`Never run`)}function od(e){if(e===void 0)return`All passages`;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(`not ${e.classesExclude.join(`, `)}`),e.zones!==void 0&&e.zones.length>0&&t.push(`${e.zones.length} zone${e.zones.length===1?``:`s`}`),e.minImportance!==void 0&&t.push(`importance ≥ ${e.minImportance}`),e.minDwellSeconds!==void 0&&t.push(`stay ≥ ${ml(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function sd(e){return{windowStartMs:e-mu,windowEndMs:e}}t();var cd={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},ld={en:`English`,it:`Italiano`};function ud(e){return hu.find(t=>t===e)}function dd(e){return _u.find(t=>t===e)}function fd(e){return bu.find(t=>t===e)??``}function pd(e){return xu.find(t=>t===e)}function md({rule:e,cameras:t,fleet:a,targets:o,taxonomy:s,onSaved:d,onCancel:f}){let m=p(),[h,g]=c(()=>e===null?Uu():Wu(e)),[_,v]=c(null),[y,b]=c(nd),x=e=>g(t=>({...t,...e})),C=r(()=>{let e=nt(`occupancy`,s);return e===null?[]:e.groups.flatMap(e=>e.options)},[s]),{options:w,loading:E}=Ar(h.deviceIds,t.map(e=>({id:e.id,name:e.name}))),k=i({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>m.trpcClient.llm.listProfiles.query({}),retry:!1}),j=(k.data??[]).filter(e=>e.supportsVision),N=l({mutationFn:async()=>{let t=e===null?{rule:Xu(h)}:{ruleId:e.id,patch:Zu(h,e)};await m.trpcClient.addons.custom.mutate({addonId:$,action:su,input:t})},onSuccess:d,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),P=ho(),F=P.data?uo(P.data,{family:`summary`,field:`captionText`}):void 0,I=h.mosaicCaptions===`all`,L=Qu(h),R=ed(h),te=$u(h)&&!N.isPending,B=td.some(e=>e.key===y)?y:nd;return u(Ae,{open:!0,onOpenChange:e=>!e&&f(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[u(Qr,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?`New summary`:`Edit ${e.name}`})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:f,children:`Cancel`})]}),_!==null&&u(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&u(Vc,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),u(sl,{problems:L,testId:`summary-problems`}),u(cl,{warnings:R,testId:`summary-warnings`})]}),n(D,{value:B,onValueChange:e=>b(rd(e)??y),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(Ce,{className:`mb-3 shrink-0`,children:td.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(z,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-3`,children:[u(Z,{title:`What it is`,hint:`One window, one picture: the best shot of every track the window held, laid out as one mosaic and delivered once.`,children:n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:X,children:`Name`}),u(O,{value:h.name,onChange:e=>x({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),u(`div`,{className:`pb-1.5`,children:u(dl,{label:`Enabled`,checked:h.enabled,onChange:e=>x({enabled:e}),testId:`summary-enabled`})})]})}),u(Z,{title:`Cameras`,hint:`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:u(ll,{cameras:t,value:h.deviceIds,fleet:a,onChange:e=>x({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})})]}),u(M,{value:`window`,className:`space-y-3`,children:n(Z,{title:`When the window closes`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Window`}),u(T,{value:h.windowKind,options:[{value:`motion`,label:`Motion — opened and closed by activity`},{value:`schedule`,label:`Schedule — fixed weekly windows`}],onChange:e=>x({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),h.windowKind===`motion`?n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Quiet period (seconds)`,value:h.quietSeconds,min:30,max:uu,onChange:e=>x({quietSeconds:e??0}),hint:`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`}),u(Q,{label:`Longest window (seconds)`,value:h.maxWindowSeconds,min:60,max:du,onChange:e=>x({maxWindowSeconds:e??0}),hint:`A permanently busy driveway would otherwise never deliver. At this bound the window closes with whatever it holds.`,testId:`summary-max-window`})]}):n(`div`,{children:[u(`label`,{className:X,children:`Weekly windows`}),u(kr,{value:h.schedule,onChange:e=>x({schedule:e})}),u(`p`,{className:ol,children:`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.`})]}),u(Q,{label:`Wait for open tracks (seconds)`,value:h.barrierSeconds,min:0,max:fu,onChange:e=>x({barrierSeconds:e??0}),hint:`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`})]})}),u(M,{value:`content`,className:`space-y-3`,children:n(Z,{title:`What goes in`,hint:`Evaluated on tracks: one passage is one tile.`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Classes`}),u(kt,{options:C,value:h.classes,onChange:e=>x({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),u(`p`,{className:ol,children:`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.`})]}),n(`div`,{children:[u(`label`,{className:X,children:`Excluded classes`}),u(kt,{options:C,value:h.classesExclude,onChange:e=>x({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),n(`div`,{children:[u(`label`,{className:X,children:`Zones`}),u(kt,{options:w,value:h.zones,onChange:e=>x({zones:e}),loading:E,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),u(`p`,{className:ol,children:`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Minimum importance`,value:h.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>x({minImportance:e}),hint:`The pipeline's own score, 0–1. Empty keeps everything.`,testId:`summary-min-importance`}),u(Q,{label:`Minimum stay (seconds)`,value:h.minDwellSeconds,min:0,max:pu,emptyPlaceholder:`any`,onChange:e=>x({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]}),u(dl,{label:`Include parked objects`,checked:h.includeStationary,onChange:e=>x({includeStationary:e}),hint:`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`})]})}),u(M,{value:`mosaic`,className:`space-y-3`,children:n(Z,{title:`The mosaic`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Tiles`,value:h.maxTiles,min:1,max:24,onChange:e=>x({maxTiles:e??1}),hint:`9 (a 3×3 grid) is the most a phone lock-screen thumbnail can carry and still be read.`,testId:`summary-max-tiles`}),n(`div`,{children:[u(`label`,{className:X,children:`When there are more tracks than tiles`}),u(T,{value:h.rank,options:hu.map(e=>({value:e,label:gu[e]})),onChange:e=>{let t=ud(e.target.value);t!==void 0&&x({rank:t})},"data-testid":`summary-rank`}),u(`p`,{className:ol,children:`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`})]})]}),n(`div`,{children:[u(`label`,{className:X,children:`Text on the mosaic`}),u(T,{value:h.mosaicCaptions,options:_u.map(e=>({value:e,label:yu[e]})),onChange:e=>{let t=dd(e.target.value);t!==void 0&&x({mosaicCaptions:t})},"data-testid":`summary-captions`}),u(`p`,{className:ol,children:`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.`})]}),n(`div`,{children:[u(bo,{label:`Caption burned onto the mosaic`,value:h.captionText,disabled:!I,onChange:e=>x({captionText:e}),placeholder:`Leave empty for no caption`,vars:F,testId:`summary-caption`}),u(`p`,{className:ol,children:I?`Across the top band.`:`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`})]})]})}),u(M,{value:`ai`,className:`space-y-3`,children:n(Z,{title:`Written summary`,hint:`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:[u(dl,{label:`Have a model describe the window`,checked:h.aiEnabled,onChange:e=>x({aiEnabled:e}),hint:`Off by default. The mosaic and the counts are delivered either way.`,testId:`summary-ai-enabled`}),!h.aiEnabled&&u(`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:`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.`}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Vision profile`}),u(T,{value:h.aiProfileId,disabled:!h.aiEnabled,options:[{value:``,label:`The hub's default vision profile`},...j.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>x({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),u(`p`,{className:ol,children:k.isError?`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`:j.length===0?`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`:`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`})]}),n(`div`,{children:[u(`label`,{className:X,children:`Answer in`}),u(T,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:`Don’t ask for a language`},...bu.map(e=>({value:e,label:ld[e]}))],onChange:e=>x({aiLanguage:fd(e.target.value)}),"data-testid":`summary-ai-language`}),u(`p`,{className:ol,children:`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`})]})]}),n(`div`,{children:[u(`label`,{className:X,children:`Your question (optional)`}),u(`textarea`,{value:h.aiPrompt,rows:3,maxLength:Cu,disabled:!h.aiEnabled,onChange:e=>x({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:`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`}),u(`p`,{className:ol,children:`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.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Frames the model may look at`,value:h.maxAiImages,min:1,max:8,disabled:!h.aiEnabled,onChange:e=>x({maxAiImages:e??1}),hint:`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`}),u(Q,{label:`Time limit (seconds)`,value:h.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!h.aiEnabled,onChange:e=>x({aiTimeoutSeconds:e}),hint:`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`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Frame size sent (pixels)`,value:h.aiMaxImagePx,min:64,max:Su,emptyPlaceholder:`448`,disabled:!h.aiEnabled,onChange:e=>x({aiMaxImagePx:e}),hint:`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`}),n(`div`,{children:[u(`label`,{className:X,children:`If the model gives no answer`}),u(T,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:xu.map(e=>({value:e,label:cd[e]})),onChange:e=>{let t=pd(e.target.value);t!==void 0&&x({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),u(`p`,{className:ol,children:`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.`})]})]})]})}),u(M,{value:`delivery`,className:`space-y-3`,children:n(Z,{title:`Delivery`,children:[u(ul,{targets:o,value:h.targetIds,onChange:e=>x({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Priority`,value:h.priority,min:1,max:5,onChange:e=>x({priority:e??3}),testId:`summary-priority`}),u(dl,{label:`Deliver a window that matched nothing`,checked:h.deliverEmpty,onChange:e=>x({deliverEmpty:e}),hint:`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`})]}),u(fl,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>x({templateTitle:e}),onBodyChange:e=>x({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),n(`p`,{className:ol,children:[u(`code`,{children:`{{ai}}`}),` is the written summary. A body that never names it still gets the sentence, appended on its own line — a template written before the AI pass existed must not make the feature look broken.`]})]})})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[u(A,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:`Cancel`}),n(A,{size:`sm`,type:`button`,disabled:!te,onClick:()=>N.mutate(),children:[N.isPending&&u(K,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}var hd=`nc.listTimelapseRules`,gd=`nc.upsertTimelapseRule`,_d=`nc.deleteTimelapseRule`,vd=`nc.testTimelapseRule`,yd=3600,bd=3600,xd=30,Sd=1,Cd=[`image`,`gif`],wd={image:`Still frame`,gif:`Short animation (GIF)`},Td=Ct({rules:Tt(Re.extend({readOnly:Et().optional()}))});function Ed(e){let t=Td.safeParse(e);return t.success?t.data.rules:null}function Dd(e){return e.readOnly!==!0}var Od=Ct({produced:bt(),exportId:St().optional(),coveragePercent:bt().optional(),enqueued:bt().optional(),windowStartMs:bt().optional(),windowEndMs:bt().optional(),error:St().optional()});function kd(e){let t=Od.safeParse(e);return t.success?t.data:null}function Ad(){return{name:``,enabled:!0,deviceIds:[],schedule:void 0,cadenceSec:15,framerate:10,denseCadenceSec:void 0,minDwellSec:void 0,targetIds:[],templateTitle:``,templateBody:``,previewText:``,previewTextSet:!1,previewMode:`image`,reportClasses:[],priority:3}}function jd(e){return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule,cadenceSec:e.cadenceSec,framerate:e.framerate,denseCadenceSec:e.denseCadenceSec,minDwellSec:e.minDwellSec,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,previewText:e.previewText??``,previewTextSet:e.previewText!==void 0,previewMode:e.previewMode,reportClasses:[...e.reportClasses??[]],priority:e.priority}}var Md={windows:[{days:[1],startMinute:0,endMinute:60}]};function Nd(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 Pd(e){let t=Nd(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??Md,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Sl(e.targetIds),...t===void 0?{}:{template:t},...e.previewTextSet?{previewText:e.previewText}:{},previewMode:e.previewMode,...e.reportClasses.length>0?{reportClasses:[...e.reportClasses]}:{},priority:e.priority}}function Fd(e,t){let n=Pd(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),xl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),xl(n.schedule,t.schedule)||(r.schedule=n.schedule),n.cadenceSec!==t.cadenceSec&&(r.cadenceSec=n.cadenceSec),n.framerate!==t.framerate&&(r.framerate=n.framerate),n.denseCadenceSec!==t.denseCadenceSec&&(r.denseCadenceSec=n.denseCadenceSec??Id(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),xl(n.targets,t.targets)||(r.targets=n.targets),xl(n.template,t.template)||(r.template=n.template??null),n.previewText!==t.previewText&&n.previewText!==void 0&&(r.previewText=n.previewText),n.previewMode!==t.previewMode&&(r.previewMode=n.previewMode),xl(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function Id(e){return Math.max(Sd,e/xd)}function Ld(e,t,n){return t<=0||n<=0?0:e/t/n}function Rd(e,t){return e*t*ze}function zd(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 ${yd}.`),(!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 ${ze}s and ${bd}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 Bd(e){return zd(e).length===0}function Vd(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=Rd(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 Hd(e){return _l(e)}function Ud(e,t){return vl(e,t,`Never run`)}function Wd(e){return e.denseCadenceSec===void 0?{seconds:Id(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var Gd=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,label:`Window`,fields:[`schedule`]},{key:`sampling`,label:`Sampling`,fields:[`cadenceSec`,`framerate`,`denseCadenceSec`,`minDwellSec`]},{key:`delivery`,label:`Delivery`,fields:[`targetIds`,`priority`,`previewMode`,`previewText`,`previewTextSet`,`templateTitle`,`templateBody`,`reportClasses`]}],Kd=`rule`;function qd(e){return Gd.find(t=>t.key===e)?.key}t();var Jd=7;function Yd(e){return Cd.find(t=>t===e)}function Xd({rule:e,cameras:t,fleet:r,targets:i,onSaved:o,onCancel:s}){let d=p(),[f,m]=c(()=>e===null?Ad():jd(e)),[h,g]=c(null),[_,v]=c(Kd),y=e=>m(t=>({...t,...e})),b=ho(),x=b.data?uo(b.data,{family:`timelapse`,field:`previewText`}):void 0,C=l({mutationFn:async()=>{let t=e===null?{rule:Pd(f)}:{ruleId:e.id,patch:Fd(f,e)};await d.trpcClient.addons.custom.mutate({addonId:$,action:gd,input:t})},onSuccess:o,onError:e=>g(e instanceof Error?e.message:`Save failed`)}),w=zd(f),E=Vd(f),k=Wd(f),j=Ld(Jd,k.seconds,f.framerate),N=Bd(f)&&!C.isPending,F=Gd.some(e=>e.key===_)?_:Kd;return u(Ae,{open:!0,onOpenChange:e=>!e&&s(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[u(P,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?`New timelapse`:`Edit ${e.name}`})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),h!==null&&u(`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}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&u(Vc,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(sl,{problems:w,testId:`timelapse-problems`}),u(cl,{warnings:E,testId:`timelapse-warnings`})]}),n(D,{value:F,onValueChange:e=>v(qd(e)??_),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(Ce,{className:`mb-3 shrink-0`,children:Gd.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(z,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-3`,children:[u(Z,{title:`What it is`,hint:`One video per camera, assembled from that camera's RECORDED footage when the window closes.`,children:n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:X,children:`Name`}),u(O,{value:f.name,onChange:e=>y({name:e.target.value}),placeholder:`e.g. Night driveway`,"data-testid":`timelapse-name`})]}),u(`div`,{className:`pb-1.5`,children:u(dl,{label:`Enabled`,checked:f.enabled,onChange:e=>y({enabled:e}),testId:`timelapse-enabled`})})]})}),u(Z,{title:`Cameras`,children:u(ll,{cameras:t,value:f.deviceIds,fleet:r,onChange:e=>y({deviceIds:e}),hint:`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.`})})]}),u(M,{value:`window`,className:`space-y-3`,children:u(Z,{title:`When`,children:n(`div`,{children:[u(`label`,{className:X,children:`Weekly windows`}),u(kr,{value:f.schedule,onChange:e=>y({schedule:e})}),u(`p`,{className:ol,children:`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.`})]})})}),u(M,{value:`sampling`,className:`space-y-3`,children:n(Z,{title:`Sampling`,hint:`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Base cadence (seconds)`,value:f.cadenceSec,min:2,max:yd,onChange:e=>y({cadenceSec:e??0}),hint:`One frame every N seconds across the quiet parts of the window.`,testId:`timelapse-cadence`}),u(Q,{label:`Output frame rate (fps)`,value:f.framerate,min:1,max:60,onChange:e=>y({framerate:e??0}),hint:`How fast the assembled video plays.`,testId:`timelapse-framerate`})]}),n(`div`,{children:[u(`label`,{className:X,children:`Dense cadence, near the detections`}),n(`div`,{className:`flex items-center gap-2`,children:[u(T,{value:f.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:`Automatic (${k.seconds}s)`},{value:`explicit`,label:`Set it myself`}],onChange:e=>y({denseCadenceSec:e.target.value===`auto`?void 0:Wd(f).seconds}),"data-testid":`timelapse-dense-mode`}),f.denseCadenceSec!==void 0&&u(O,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(f.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&y({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),n(`p`,{className:ol,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,k.seconds,`s and `,f.framerate,` fps a `,Jd,`-second passage lasts `,j.toFixed(2),`s on screen; halving the cadence doubles that, and the quiet parts of the night do not change length.`,k.derived?` Automatic keeps tracking the base cadence (base ÷ 30, never below 1s).`:` Fixed at this value — the hub cannot unset the field, so going back to Automatic writes the derived number (${Wd({...f,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),u(Q,{label:`Minimum seconds of video per detection (optional)`,value:f.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>y({minDwellSec:e}),hint:`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`})]})}),u(M,{value:`delivery`,className:`space-y-3`,children:n(Z,{title:`The notification`,children:[u(ul,{targets:i,value:f.targetIds,onChange:e=>y({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Preview`}),u(T,{value:f.previewMode,options:Cd.map(e=>({value:e,label:wd[e]})),onChange:e=>{let t=Yd(e.target.value);t!==void 0&&y({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),u(Q,{label:`Priority`,value:f.priority,min:1,max:5,onChange:e=>y({priority:e??3}),testId:`timelapse-priority`})]}),n(`div`,{children:[u(bo,{label:`Caption on the preview frame`,value:f.previewTextSet?f.previewText:``,placeholder:`${qe} (shipped default)`,onChange:e=>y({previewText:e,previewTextSet:!0}),vars:x,testId:`timelapse-preview-text`}),n(`p`,{className:ol,children:[f.previewTextSet&&f.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${qe}).`,f.previewTextSet&&n(a,{children:[` `,u(`button`,{type:`button`,className:`underline`,onClick:()=>y({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),u(fl,{title:f.templateTitle,body:f.templateBody,onTitleChange:e=>y({templateTitle:e}),onBodyChange:e=>y({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),n(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`With no body of your own the detection summary is appended automatically, and only when the count is non-zero. With one, nothing is appended — ask for it with`,` `,u(`code`,{children:`{{detectionSummary}}`}),`.`]})]})})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[u(A,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),n(A,{size:`sm`,type:`button`,disabled:!N,onClick:()=>C.mutate(),children:[C.isPending&&u(K,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}function Zd({children:e,className:t}){return u(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function Qd(){return u(`div`,{className:`flex items-center justify-center py-16`,children:u(K,{className:`h-6 w-6 animate-spin text-primary`})})}function $d({children:e,testId:t}){return u(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function ef({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:i}){return u(x,{children:u(E,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,mobileMode:`scroll`,maxBodyHeight:j,...i===void 0?{}:{onRowClick:i}})})}function tf({name:e,enabled:t,onOpen:r,badges:i,openTestId:a}){return n(`span`,{className:`flex flex-wrap items-center gap-2`,children:[r===void 0?u(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e}):u(Zd,{children:u(`button`,{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`,...a===void 0?{}:{"data-testid":a},children:e})}),!t&&u(q,{variant:`warning`,children:`disabled`}),i]})}function nf({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:i=`Delete`,cancelLabel:a=`Cancel`,ariaLabel:o,testId:s,onConfirm:c}){let l=Se(),d=async()=>{await l({title:n,message:r,confirmLabel:i,cancelLabel:a,variant:`danger`})&&c()};return u(`button`,{type:`button`,title:i,"aria-label":o,disabled:e||t,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void d(),...s===void 0?{}:{"data-testid":s},children:u(g,{className:`h-3.5 w-3.5 text-danger`})})}t();var rf=[`notificationSummaries`,`listSummaryRules`];function af(e){return[{key:`name`,header:`Digest`,render:t=>u(tf,{name:t.name,enabled:t.enabled,...wu(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`summary-edit-${t.id}`,badges:n(a,{children:[!wu(t)&&u(q,{variant:`warning`,children:`read-only`}),t.ai?.enabled===!0&&u(q,{variant:`info`,children:`AI`}),t.ai!==void 0&&!t.ai.enabled&&u(q,{variant:`default`,children:`AI off`})]})})},{key:`cameras`,header:`Cameras`,align:`center`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:`Window`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:id(e.window)})},{key:`filters`,header:`Keeps`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:od(e.filters)})},{key:`mosaic`,header:`Mosaic`,nowrap:!0,render:e=>n(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.maxTiles,` tiles · `,e.rank]})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:ad(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onTest(t),title:`Produce this digest now and DELIVER it`,"aria-label":`test ${t.name}`,"data-testid":`summary-test-${t.id}`,children:u(b,{className:`h-3.5 w-3.5`})}),u(nf,{disabled:t.readOnly,pending:e.deletePending,title:`Delete this summary?`,message:`This will permanently delete "${t.name}". This action cannot be undone.`,ariaLabel:`delete ${t.name}`,testId:`summary-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}t();var of=[`notificationTimelapses`,`listTimelapseRules`];function sf(e){return[{key:`name`,header:`Timelapse`,render:t=>u(tf,{name:t.name,enabled:t.enabled,...Dd(t)?{onOpen:()=>e.onOpen(t),openTestId:`timelapse-edit-${t.id}`}:{},badges:Dd(t)?null:u(q,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:`Cameras`,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.deviceIds.length===1?e.cameraNameById.get(t.deviceIds[0]??-1)??`#${t.deviceIds[0]}`:`${t.deviceIds.length} cameras`})},{key:`schedule`,header:`Window`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Hd(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let t=Wd(jd(e));return n(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.cadenceSec,`s · `,e.framerate,`fps · dense `,t.seconds,`s`,t.derived?` (auto)`:``,e.minDwellSec===void 0?``:` · ≥${e.minDwellSec}s/detection`]})}},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:Ud(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,disabled:!Dd(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Dd(t),onClick:()=>e.onTest(t),title:`Render this rule's last closed window now and DELIVER it`,"aria-label":`test ${t.name}`,"data-testid":`timelapse-test-${t.id}`,children:u(b,{className:`h-3.5 w-3.5`})}),u(nf,{disabled:!Dd(t),pending:e.deletePending,title:`Delete this timelapse?`,message:`This will permanently delete "${t.name}". This action cannot be undone.`,ariaLabel:`delete ${t.name}`,testId:`timelapse-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}t();var cf={summary:{title:`Summary rules are not available on this hub`,message:`This hub has not been updated to serve summary rules yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime.`},timelapse:{title:`Timelapse rules are not available on this hub`,message:`This hub has not been updated to serve timelapse rules yet. Deploy addon-post-analysis and reload — the rules themselves are untouched.`},"calendar-events":{title:`Calendar-events rules are not available on this hub`,message:`This hub has not been updated to serve calendar-events rules yet. Deploy addon-post-analysis and reload — the rules themselves are untouched.`}},lf=`The hub answered something this admin build does not understand. Update both and reload.`;function uf(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function df({cameras:e,fleet:t,targets:r,taxonomy:o}){let s=p(),[d,f]=c({mode:`closed`}),[m,h]=c(null),[g,_]=c(null),[v,y]=c(null),[b,x]=c(null),S=i({queryKey:rf,queryFn:async()=>Vu(await s.trpcClient.addons.custom.mutate({addonId:$,action:ou,input:{}}))}),C=i({queryKey:of,queryFn:async()=>Ed(await s.trpcClient.addons.custom.mutate({addonId:$,action:hd,input:{}}))}),w=i({queryKey:zl,queryFn:async()=>Kl(await s.trpcClient.addons.custom.mutate({addonId:$,action:Bl,input:{}}))}),E=S.data??[],D=C.data??[],O=w.data??[],k=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:su,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),A=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:cu,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),j=l({mutationFn:async e=>Hu(await s.trpcClient.addons.custom.mutate({addonId:$,action:lu,input:{ruleId:e,...sd(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),ee=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:gd,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),M=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:_d,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),N=l({mutationFn:async e=>kd(await s.trpcClient.addons.custom.mutate({addonId:$,action:vd,input:e})),onSuccess:e=>{y(null),x(e)}}),P=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:Vl,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void w.refetch()}),I=l({mutationFn:e=>s.trpcClient.addons.custom.mutate({addonId:$,action:Hl,input:{ruleId:e}}),onSuccess:()=>void w.refetch()}),L=e.toSorted((e,t)=>e.name.localeCompare(t.name)),R=r.map(e=>({id:e.id,name:e.name,enabled:e.enabled})),z=new Map(R.map(e=>[e.id,e.name])),te=new Map(L.map(e=>[e.id,e.name])),B=Date.now(),ne={summary:{nowMs:B,targetNameById:z,deletePending:A.isPending,onToggle:(e,t)=>k.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{wu(e)&&f({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>A.mutate(e.id)},timelapse:{nowMs:B,cameraNameById:te,targetNameById:z,deletePending:M.isPending,onToggle:(e,t)=>ee.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Dd(e)&&f({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>M.mutate(e.id)},calendar:{nowMs:B,targetNameById:z,deletePending:I.isPending,onToggle:(e,t)=>P.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{ql(e)&&f({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>I.mutate(e.id)}},re=e=>{switch(e.family){case`summary`:ne.summary.onOpen(e.rule);return;case`timelapse`:ne.timelapse.onOpen(e.rule);return;case`calendar-events`:ne.calendar.onOpen(e.rule);return}},V=e=>{f(e===`summary`?{mode:`summary`,rule:null}:e===`timelapse`?{mode:`timelapse`,rule:null}:{mode:`calendar-events`,rule:null})},H=e=>{let t=e===`summary`?S:e===`timelapse`?C:w;return t.isLoading?null:t.isError?{unreadable:!1}:t.data===null?{unreadable:!0}:null},ie=e=>{e===`summary`?S.refetch():e===`timelapse`?C.refetch():w.refetch()},U=e=>{let t=uf(e);return t!==null&&H(t)!==null},ae=e=>{let t=uf(e),r=t===null?null:H(t);return n(a,{children:[t!==null&&r!==null&&u(F,{title:cf[t].title,message:r.unreadable?lf:cf[t].message,onRetry:()=>ie(t)}),A.isError&&u(F,{title:`Could not delete the rule`,message:String(A.error)}),M.isError&&u(F,{title:`Could not delete the rule`,message:String(M.error)}),I.isError&&u(F,{title:`Could not delete the rule`,message:String(I.error)}),j.isError&&u(F,{title:`The test run failed`,message:String(j.error)}),N.isError&&u(F,{title:`The test run failed`,message:String(N.error)}),g!==null&&u(ff,{outcome:g,onDismiss:()=>_(null)}),b!==null&&u(pf,{outcome:b,onDismiss:()=>x(null)})]})},oe=()=>f({mode:`closed`}),se=n(a,{children:[d.mode===`summary`&&u(md,{rule:d.rule,cameras:L,fleet:t,targets:R,taxonomy:o,onCancel:oe,onSaved:()=>{oe(),S.refetch()}}),d.mode===`timelapse`&&u(Xd,{rule:d.rule,cameras:L,fleet:t,targets:R,onCancel:oe,onSaved:()=>{oe(),C.refetch()}}),d.mode===`calendar-events`&&u(au,{rule:d.rule,targets:R,onCancel:oe,onSaved:()=>{oe(),w.refetch()}}),u(pl,{open:m!==null,ruleName:m?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${m?.targets.length??0} target${(m?.targets.length??0)===1?``:`s`}`,pending:j.isPending,onCancel:()=>h(null),onConfirm:()=>{m!==null&&j.mutate(m.id)}}),u(pl,{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:n(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Which camera`}),u(T,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:te.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:E,timelapses:D,calendarEvents:O,loading:S.isLoading||C.isLoading||w.isLoading,columnDeps:ne,open:re,create:V,notices:ae,listFailed:U,overlays:se}}function ff({outcome:e,onDismiss:t}){return n(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[e.error===void 0?n(`span`,{children:[`Produced `,e.produced,` digest`,e.produced===1?``:`s`,` —`,` `,e.tiles??0,` tile`,(e.tiles??0)===1?``:`s`,` from`,` `,e.cameras??0,` camera`,(e.cameras??0)===1?``:`s`,`,`,` `,e.matched??0,` track`,(e.matched??0)===1?``:`s`,` matched,`,` `,e.enqueued??0,` notification`,(e.enqueued??0)===1?``:`s`,` sent.`,(e.droppedStationary??0)>0&&n(`span`,{"data-testid":`summary-test-dropped-stationary`,children:[` `,e.droppedStationary,` parked object`,e.droppedStationary===1?``:`s`,` left out.`]})]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,e.error]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:`Dismiss`})]})}function pf({outcome:e,onDismiss:t}){return n(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[e.error===void 0?n(`span`,{children:[`Produced `,e.produced,` video`,e.produced===1?``:`s`,e.coveragePercent===void 0?``:` — ${Math.round(e.coveragePercent)}% of the window had footage`,`, `,e.enqueued??0,` notification`,(e.enqueued??0)===1?``:`s`,` sent.`]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,e.error]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:`Dismiss`})]})}var mf=[{key:`summaries`,label:`Summaries`,blurb:`One window, one picture: every camera's best moments as a single mosaic, delivered once when the window closes.`,newLabel:`New summary`,emptyHint:`No summary rules yet. Use "New summary" (or pick Summary under New rule) to author one.`},{key:`timelapses`,label:`Timelapses`,blurb:`A night of recorded footage, assembled into one short video per camera when the window closes.`,newLabel:`New timelapse`,emptyHint:`No timelapse rules yet. Use "New timelapse" (or pick Timelapse under New rule) to author one.`},{key:`calendar-events`,label:`Calendar events`,blurb:`At schedule time, send the upcoming events from selected calendars for the next N days.`,newLabel:`New calendar events`,emptyHint:`No calendar-events rules yet. Use "New calendar events" (or pick Calendar events under New rule) to author one.`}],hf=[{type:`detection`,label:`Detection`,hint:`Fire on what the cameras see — detections, tracks and package events.`},{type:`sensor`,label:`Sensor`,hint:`A doorbell press or linked sensor changing state.`},{type:`audio`,label:`Sound`,hint:`Sustained sound level or a named sound class.`},{type:`occupancy`,label:`Occupancy`,hint:`How many objects are in a frame or zone, and for how long.`},{type:`device-events`,label:`Device events`,hint:`Offline, battery low, stream drop, camera blind.`},{type:`system`,label:`System events`,hint:`Node, addon, update, backup or export events.`},{type:`alarm`,label:`Alarm`,hint:`Arming, armed, triggered, disarmed.`},{type:`summary`,label:`Summary`,hint:`One mosaic of the best moments across cameras for a window.`},{type:`timelapse`,label:`Timelapse`,hint:`One short video per camera from recorded footage.`},{type:`calendar-events`,label:`Calendar events`,hint:`Upcoming calendar events for the next N days, at schedule time.`}];function gf(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function _f(e){if(!(e==null||e.length===0))return gf(e)?e:tt(e)}function vf(e){let t=mf.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function yf(e){return[...jt.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...mf]}function bf(e){return!gf(e)}function xf(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}t();function Sf(e){return[{key:`name`,header:`Rule`,render:t=>u(tf,{name:t.name,enabled:t.enabled,...ql(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:ql(t)?null:u(q,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:`When`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Zl(e.schedule)})},{key:`horizon`,header:`Horizon`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:ru(e.horizonDays)})},{key:`calendars`,header:`Calendars`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:iu(e)})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:ad(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>u(Zd,{className:`flex items-center justify-end gap-1`,children:u(nf,{disabled:t.readOnly,pending:e.deletePending,title:`Delete this calendar-events rule?`,message:`This will permanently delete "${t.name}". This action cannot be undone.`,ariaLabel:`delete ${t.name}`,testId:`calendar-events-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})})}]}function Cf(e,t){return e.replaceAll(`{{name}}`,t)}function wf(e){return[{key:`name`,header:`Rule`,render:t=>u(tf,{name:t.name,enabled:t.enabled,...Wr(t)?{onOpen:()=>e.onOpen(t)}:{}})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:t=>n(`span`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] text-foreground-subtle`,children:un(t,e.t(`notificationRules.grouping.choice`,gn))}),!fn(t.delivery)&&u(q,{variant:`warning`,children:`read-only`})]})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(ic,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:e.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(pc,{rule:t,snoozes:e.snoozes,exempt:Qt(t.conditions,Bt({onActivation:t.actions?.onActivation??[],onDeactivation:t.actions?.onDeactivation??[],onTrigger:t.actions?.onTrigger??[],onTriggerOff:t.actions?.onTriggerOff??[],buttons:t.actions?.buttons??[]},e.sequences))})})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>Wr(t)?n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(el,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&u(ac,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:`Open in the simulator — describe an event and tune it before injecting`,"aria-label":`simulate ${t.name}`,children:u(b,{className:`h-3.5 w-3.5`})}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:u(B,{className:`h-3.5 w-3.5`})}),u(Ef,{rule:t,deps:e})]}):u(Tf,{rule:t,deps:e})}]}function Tf({rule:e,deps:t}){return n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(`span`,{title:ct(rt(e)).blurb,children:u(q,{variant:`warning`,children:`Recreate as one rule per family`})}),t.onOpenHistory&&u(ac,{rule:e,onOpenHistory:t.onOpenHistory}),u(Ef,{rule:e,deps:t})]})}function Ef({rule:e,deps:t}){let{t:n}=Dt();return u(nf,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:Cf(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:Cf(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function Df(e){let t=wf(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:br(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:dr(e.conditions.systemEvent)})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`cooldown`,header:`Cooldown`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:cn(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function Of(e){switch(e){case`detection`:return`Detection`;case`sensor`:return`Sensor`;case`sound`:return`Sound`;case`occupancy`:return`Occupancy`;case`device-events`:return`Device events`;case`system`:return`System`;case`alarm`:return`Alarm`;case`mixed`:return`To recreate`;case`summary`:return`Summary`;case`timelapse`:return`Timelapse`;case`calendar-events`:return`Calendar events`}}function kf(e){return{family:`event`,kind:rt(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Af(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function jf(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Mf(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Nf(e){return[...e.events.map(kf),...e.summaries.map(Af),...e.timelapses.map(jf),...e.calendarEvents.map(Mf)]}function Pf(e,t){return t===`all`?!0:gf(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:bf(t)&&e.family===`event`?gt(e.rule,t):!1}function Ff(e,t){return Nf(t).filter(t=>Pf(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function If(e,t){return Ff(e,t).length}function Lf(e){return e===`all`?900:860}function Rf(e){return e.family===`event`?e.rule:null}function zf(e){return e.family===`summary`?e.rule:null}function Bf(e){return e.family===`timelapse`?e.rule:null}function Vf(e){return e.family===`calendar-events`?e.rule:null}function Hf(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 Uf(e,t){return e.map(e=>Hf(e,t))}function Wf(e,t){return e.find(e=>e.key===t)}function Gf(e,t,n){let r=Wf(wf(n.event),e),i=Wf(af(n.summary),e),a=Wf(sf(n.timelapse),e),o=Wf(Sf(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 Kf(e){switch(e.family){case`event`:return null;case`summary`:return id(e.rule.window);case`timelapse`:return Hd(e.rule.schedule);case`calendar-events`:return Zl(e.rule.schedule)}}function qf(e){let t=Wf(wf(e.event),`trigger`);return{key:`when`,header:`When`,render:(e,n)=>{let r=Kf(e);return r===null?e.family===`event`?t?.render(e.rule,n)??null:null:u(`span`,{className:`text-[11px] text-foreground-subtle`,children:r})}}}function Jf(e){return[Gf(`name`,`Name`,e),{key:`type`,header:`Type`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:Of(e.kind)})},qf(e),Gf(`targets`,`Targets`,e),Gf(`lastRun`,`Last run`,e),Gf(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),Gf(`enabled`,`On`,e),Gf(`actions`,``,e)]}function Yf(e,t){return e===`all`?Jf(t):e===`summaries`?Uf(af(t.summary),zf):e===`timelapses`?Uf(sf(t.timelapse),Bf):e===`calendar-events`?Uf(Sf(t.calendar),Vf):bf(e)&&Nt(e)?Uf(Df(t.event),Rf):Uf(wf(t.event),Rf)}function Xf({value:e,family:t,onChange:r,draft:i}){if(t===void 0||!ot.includes(t))return null;let a=e?.mode===`summary`?e:null;return n(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:`Delivery`}),n(`div`,{className:`flex flex-wrap gap-3 text-xs`,children:[n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-delivery`,checked:a===null,onChange:()=>r({mode:`instant`}),"data-testid":`rule-delivery-instant`}),`Instant — a notification per event`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-delivery`,checked:a!==null,onChange:()=>r({mode:`summary`,schedule:Ke([fr])}),"data-testid":`rule-delivery-summary`}),`Summary on schedule — the current state, at set times`]})]}),a!==null&&u(Zf,{value:a,onChange:r,draft:i})]})}function Zf({value:e,onChange:t,draft:r}){let i=e.schedule.timezone,a=Ge({systemEventDelivery:e});return n(`div`,{className:`mt-2 space-y-2`,children:[n(`p`,{className:Bn,children:[`Nothing is sent per event. At each time below, one notification lists what is still true for the kinds and filters of this rule — low batteries, consumables, devices or streams offline, updates available — or one notification per category, if you choose so below. Nothing to report sends nothing. Time zone: `,i??`the hub’s`,`.`]}),u(kr,{mode:`times`,value:e.schedule,onChange:n=>{n!==void 0&&t($n(e,n))}}),n(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[u(`legend`,{className:`sr-only`,children:`How the summary is sent`}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-summary-split`,checked:a===`rule`,onChange:()=>t(Mn(e,`rule`)),"data-testid":`rule-delivery-split-rule`}),`One message with every category`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-summary-split`,checked:a===`section`,onChange:()=>t(Mn(e,`section`)),"data-testid":`rule-delivery-split-section`}),`One notification per category (batteries, consumables, devices…)`]})]}),u(Qf,{draft:r,split:a})]})}function Qf({draft:e,split:t}){let r=p(),i=l({mutationFn:e=>r.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),a=Cr(i.status,i.data,i.error,t);return n(`div`,{className:`space-y-1.5`,children:[u(A,{size:`sm`,variant:`secondary`,onClick:()=>i.mutate(e()),disabled:i.isPending,"data-testid":`rule-delivery-preview`,children:i.isPending?`Reading the state…`:`Preview the summary now`}),a!==null&&u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:a.lines.map((e,t)=>u(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function $f(e,t){if(e.status===`error`)return{kind:`failed`,reason:e.error instanceof Error?e.error.message:`unknown error`};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:ip(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var ep=6e4,tp=60*ep,np=24*tp;function rp(e,t){return e===1?`the last ${t}`:`the last ${String(e)} ${t}s`}function ip(e){return e===null?`No delivery on record`:e>=np?`Not in ${rp(Math.floor(e/np),`day`)}`:e>=tp?`Not in ${rp(Math.floor(e/tp),`hour`)}`:e>=ep?`Not in ${rp(Math.floor(e/ep),`minute`)}`:`Not in the window read`}t();var ap=[`notificationRules`,`listRules`],op=[`notificationOutput`,`listTargets`,`forRules`],sp=[`notificationRules`,`getConditionCatalog`],cp=[`deviceManager`,`gateableDevices`],lp=Le.options;function up({onSimulateRule:t,onOpenHistory:a}={}){let o=p(),{t:s}=Dt(),[f,h]=Gr(),[g,_]=c({mode:`closed`}),v=_f(f.get(`section`))??`all`,b=e=>{let t=new URLSearchParams(f);e===`all`?t.delete(`section`):t.set(`section`,e),h(t,{replace:!0})},x=i({queryKey:ap,queryFn:async()=>(await o.trpcClient.notificationRules.listRules.query({})).rules}),S=e(null);d(()=>{if(g.mode!==`closed`)return;let e=f.get(`rule`);if(e===null||e===`new`){e===null&&(S.current=null);return}if(S.current===e)return;let t=x.data?.find(t=>t.id===e);t===void 0||!Wr(t)||(S.current=e,_({mode:`form`,rule:t}))},[g.mode,f,x.data]);let C=i({queryKey:op,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),w=i({queryKey:sp,queryFn:()=>o.trpcClient.notificationRules.getConditionCatalog.query({})}),T=ge({projection:`slim`}),E=nc(),O=r(()=>T.data??[],[T.data]),k=De(T),j=r(()=>O.map(e=>e.id),[O]),M=i({queryKey:[...cp,j],enabled:j.length>0,queryFn:async()=>{let e=[];for(let t of O){let n=ut(await o.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),lp);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),N=r(()=>{let e=qr(O);return O.filter(e=>pt(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))},[O]),P=r(()=>O.filter(e=>e.type===Be.Camera).map(e=>({id:e.id,name:e.name})),[O]),I=Zr(r(()=>P.map(e=>e.id),[P])),L=r(()=>{let e=new Map(P.map(e=>[e.id,e.name]));return I.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})))},[I.results,P]),R=r(()=>{let e=new Map;for(let t of C.data??[])e.set(t.id,t.name);return e},[C.data]),z=l({mutationFn:e=>o.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void x.refetch()}),te=l({mutationFn:e=>o.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void x.refetch()}),B=fc(),ne=y({}),V=ne.data?.sequences??[],H=re(),ie=x.data??[],U=df({cameras:P,fleet:k,targets:C.data??[],taxonomy:w.data?.taxonomy}),ae={events:ie,summaries:U.summaries,timelapses:U.timelapses,calendarEvents:U.calendarEvents},oe=yf(new Map(jt.map(e=>[e.key,If(e.key,ae)]))),W=oe.find(e=>e.key===v)??oe[0]??jt[0],G=gf(W.key)?vf(W.key):void 0,le=bf(W.key)?W.key:null,ue=Ff(W.key,ae),de=(e,t)=>{let n=new URLSearchParams(f);e===null?n.delete(`rule`):n.set(`rule`,e),t===void 0||t===`rule`?n.delete(`editTab`):n.set(`editTab`,t),h(n,{replace:!0})},K=()=>{let e=new URLSearchParams(f);e.delete(`rule`),e.delete(`editTab`),h(e,{replace:!0})},fe=()=>{let e=f.get(`rule`);e!==null&&(S.current=e),_({mode:`closed`}),K()},pe=e=>{Wr(e)&&(S.current=e.id,_({mode:`form`,rule:e}),de(e.id))},me=()=>{let e=le??`all`;S.current=`new`,_({mode:`form`,rule:null,seed:it(e)}),de(`new`)},_e=e=>{if(xf(e)){S.current=`new`,_({mode:`form`,rule:null,seed:it(e)}),de(`new`);return}U.create(e)},ye=e=>{if(e.family===`event`){pe(e.rule);return}U.open(e)},be={targetNameById:R,snoozes:B,sequences:V,deletePending:te.isPending,onToggle:(e,t)=>z.mutate({ruleId:e.id,enabled:t}),onOpen:pe,t:s,onDuplicate:e=>pe({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>te.mutate(e.id),...t?{onTest:t}:{},lastRunOf:e=>$f(E,e),...a?{onOpenHistory:a}:{}},xe=Yf(W.key,{event:be,summary:U.columnDeps.summary,timelapse:U.columnDeps.timelapse,calendar:U.columnDeps.calendar});return n(Jr,{icon:ce,title:`Rules`,subtitle:G?.blurb??(`blurb`in W?W.blurb:``),actions:G!==void 0||`creatable`in W&&W.creatable?v===`all`?n(he,{children:[n(we,{className:`inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`rules-new-menu`,children:[u(Te,{className:`h-3.5 w-3.5`}),`New rule`,u(m,{className:`h-3 w-3 opacity-80`})]}),u(se,{align:`end`,className:`min-w-[14rem] py-1`,children:hf.map(e=>u(ve,{onClick:()=>_e(e.type),"data-testid":`rules-new-${e.type}`,title:e.hint,children:n(`span`,{className:`flex flex-col gap-0.5`,children:[u(`span`,{className:`font-medium`,children:e.label}),u(`span`,{className:`text-[10px] text-foreground-subtle font-normal`,children:e.hint})]})},e.type))})]}):G===void 0?n(A,{size:`sm`,type:`button`,onClick:me,children:[u(Te,{className:`h-3.5 w-3.5`}),`newRuleLabel`in W?W.newRuleLabel:`New rule`]}):n(A,{size:`sm`,type:`button`,onClick:()=>_e(G.key===`summaries`?`summary`:G.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":G.key===`summaries`?`summary-new`:G.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[u(Te,{className:`h-3.5 w-3.5`}),G.newLabel]}):void 0,children:[u(D,{value:W.key,onValueChange:e=>b(_f(e)??v),children:u(Ce,{className:`mb-3`,children:oe.map(e=>n(ee,{value:e.key,children:[e.label,u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:If(e.key,ae)})]},e.key))})}),u(al,{rules:ie}),U.notices(W.key),(x.isLoading||U.loading)&&u(Qd,{}),x.isError&&!x.isLoading&&u(F,{title:`Failed to load rules`,message:x.error instanceof Error?x.error.message:`Unknown error`,onRetry:()=>void x.refetch()}),!x.isLoading&&!U.loading&&!x.isError&&!U.listFailed(W.key)&&ue.length===0&&u($d,{children:G?.emptyHint??(`emptyHint`in W?W.emptyHint:`No rules yet.`)}),ue.length>0&&u(ef,{columns:xe,rows:ue,rowKey:e=>`${e.family}:${e.id}`,onRowClick:ye,minWidthPx:Lf(W.key)}),g.mode===`form`&&u(dp,{rule:g.rule,...g.seed?{seed:g.seed}:{},targets:C.data??[],actuatable:N,fleet:k,sequences:V,onCreateSequence:async e=>{let t=await H.mutateAsync({sequence:{name:e.name,...e.minDelaySec===void 0?{}:{minDelaySec:e.minDelaySec},actions:[...e.actions]}});return await ne.refetch(),t.sequence.id},catalog:an(w.data?.catalog??[]),taxonomy:w.data?.taxonomy,cameras:P,gateable:M.data??[],gateableScenes:L,initialEditTab:Pt(f.get(`editTab`)??``)??`rule`,onEditTabChange:e=>de(g.mode===`form`?g.rule?.id??`new`:`new`,e),onCancel:fe,onSaved:()=>{fe(),x.refetch()}}),U.overlays]})}function dp({rule:e,seed:t,targets:o,catalog:s,taxonomy:d,cameras:f,gateable:m,gateableScenes:h,actuatable:g,fleet:_,sequences:v,onCreateSequence:y,initialEditTab:x=Fn,onEditTabChange:C,onSaved:w,onCancel:E}){let k=p(),{t:j}=Dt(),N=e!=null&&e.id.length>0,[P]=c(()=>e?yn(e):nn(t?.delivery,t?.conditions)),[F,I]=c(P),[L,R]=c(null),[te,B]=c(null),[re,V]=c(x),H=e=>I(t=>({...t,...e})),U=e?It(e):void 0,ae=l({mutationFn:async()=>{let t=Rt(F,U,s);if(N&&e){let n=hn(F,s);await k.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await k.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:w,onError:e=>R(e instanceof Error?e.message:`Save failed`)}),oe=l({mutationFn:async()=>{let e=Rt(F,U,s);return(await k.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>B(null),onSuccess:e=>B(e),onError:e=>R(e instanceof Error?e.message:`Test failed`)}),se=F.targetIds.map(e=>o.find(t=>t.id===e)?.name??e),W=i({queryKey:[`userManagement`,`listUsers`],queryFn:()=>k.trpcClient.userManagement.listUsers.query()}).data,le=r(()=>(W??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[W]),ue=Vt(F),de=ue===`immediate-grouped`,fe=String(F.groupingSec??20),pe=qt(F).map(e=>({...e,label:e.value===`immediate-grouped`?j(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?j(`notificationRules.grouping.hint`,{n:fe,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}}`,fe):e.hint})),me=pe.find(e=>e.value===ue)?.hint,he=Ur(F,U),ge=mt(F.delivery),_e=rt(F),ve=ct(_e),ye=at(_e),be=dt(_e),xe=i({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,be??[]],enabled:be!==null,queryFn:async()=>{let e=await Promise.all((be??[]).map(e=>k.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),Se=r(()=>{if(be===null||xe.data===void 0)return g;let e=xe.data,t=new Set(Pn(F.deviceScope));return g.filter(n=>e.has(n.id)||t.has(n.id))},[g,be,xe.data,F.deviceScope]),we=be!==null&&xe.isLoading,Te=be!==null&&xe.isError,q=ho(),Ee=e=>({family:`rule`,field:e,kind:_e,delivery:F.delivery,...dn(F)?{systemEventDelivery:`summary`}:{},...F.conditions.systemEvent?{systemEventKinds:[...F.conditions.systemEvent.kinds]}:{}}),De=e=>q.data?uo(q.data,Ee(e)):void 0,Oe=pn(F),ke=Qt(F.conditions,Bt(F.actions,v)),je=F.conditions.identities!==void 0||F.conditions.plates!==void 0,Me=Lr(F.delivery,F.conditions),Ne=Me.some(e=>e.key===re)?re:Fn;return fn(F.delivery)?u(Ae,{open:!0,onOpenChange:e=>!e&&E(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex min-w-0 items-center gap-2`,children:[u(ce,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:N?`Edit ${e?.name}`:`New notification rule`})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:E,children:`Cancel`})]}),L&&u(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:L}),N&&e&&n(`div`,{className:`shrink-0 mb-3 space-y-2`,children:[u(Vc,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(Wc,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??`camera ${String(e)}`})]}),n(D,{value:Ne,onValueChange:e=>{let t=Pt(e);t!==void 0&&(V(t),C?.(t))},className:`flex min-h-0 flex-1 flex-col`,children:[u(Ce,{className:`mb-3 shrink-0`,children:Me.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(z,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-4`,children:[n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),u(O,{value:F.name,onChange:e=>H({name:e.target.value}),placeholder:`e.g. Front door package`})]}),n(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[u(G,{checked:F.enabled,onCheckedChange:e=>H({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),u(T,{value:ue,onChange:e=>{let t=Zt(e.target.value);t&&I(e=>nr(e,t))},options:pe.map(e=>({value:e.value,label:e.label}))}),me&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:me}),de&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:j(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),u(O,{type:`number`,min:5,max:60,step:1,value:fe,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=Sr(e.target.value);t!==void 0&&H({groupingSec:t})}}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:j(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),je&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:j(`notificationRules.grouping.scopedHint`,{n:fe,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,fe)})]}),ue===`immediate`&&je&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:j(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!N&&ye!==void 0&&u(Ns,{family:ye,onChange:e=>I(t=>en(t,e))}),u(ne,{label:`Delivery targets`,targets:o,value:F.targetIds,onChange:e=>I(t=>({...t,targetIds:e})),emptyMessage:`No delivery targets configured. Add one under the Targets tab first.`,testIdPrefix:`rule-target`}),u(ie,{mode:`multi`,options:le,value:F.targetUsers,onChange:e=>H({targetUsers:e}),searchable:!0,creatable:!1,label:`Notify users`,description:`Delivers to the targets each user owns, only for cameras that user can access.`,emptyMessage:`No users to notify.`,placeholder:`Search users…`,testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),n(M,{value:`devices`,className:`space-y-4`,children:[we&&u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:j(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Te&&u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:j(`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.`)}),u(ls,{devices:Se,scope:F.deviceScope,onChange:e=>H({deviceScope:e}),listState:_.state,savedScope:P.deviceScope,exceptOffered:Mt(s,`devicesExclude`,F)})]}),u(M,{value:`actions`,className:`space-y-4`,children:u(jo,{value:F.actions,onChange:e=>H({actions:e}),devices:g,devicesState:_.state,sequences:v,onCreateSequence:y})}),n(M,{value:`advanced`,className:`space-y-4`,children:[u(Js,{catalog:s,delivery:F.delivery,conditions:F.conditions,onConditionsChange:e=>H({conditions:e})}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown (seconds)`}),u(O,{type:`number`,min:0,max:mn,step:1,value:String(F.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=vn(e.target.value);t!==void 0&&H({cooldownSec:t})}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[ge?`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.`:`The shortest gap between two deliveries of this rule, counted as chosen below.`,` `,`Any whole number from 0 (deliver every match) to `,String(mn),` (24 hours).`]})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown counted`}),u(T,{value:F.cooldownScope,onChange:e=>{let t=Ut(e.target.value);t!==void 0&&H({cooldownScope:t})},options:Ft.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Per device: a delivery about one camera (or node) does not hold back another. Whole rule: one delivery per cooldown, whichever device matched.`})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Across object classes`}),u(T,{value:F.cooldownGranularity??`per-class`,onChange:e=>H({cooldownGranularity:Sn(e.target.value)}),options:Br.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`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.`})]})]}),n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:F.snoozeAllowGlobal,onCheckedChange:e=>H({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:ke}),`Anyone may snooze this rule for everyone`]}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`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.`})]}),!ke&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),n(a,{children:[u(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:At.map(e=>{let t=F.snoozeOptions??ir,n=t.includes(e);return u(A,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>H({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Wt(e)},e)})}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:F.snoozeOptions===void 0?`Not set — the notification offers the defaults (${ir.map(Wt).join(`, `)}). A pause opened from a button silences this camera for this class of subject, only for whoever received the notification, and sends no summary.`:F.snoozeOptions.length===0?`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`:`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`}),F.snoozeOptions!==void 0&&u(A,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>H({snoozeOptions:void 0}),children:`Back to the defaults`})]})]}),N&&e&&!ke&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Silence it now`}),u(cc,{ruleId:e.id,ruleName:e.name,exempt:ke,variant:`full`})]})]}),n(M,{value:`notification`,className:`space-y-4`,children:[n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),u(T,{value:String(F.priority),onChange:e=>H({priority:Number(e.target.value)}),options:ar.map(e=>({value:String(e.value),label:e.label}))})]}),!ve.carriesMedia&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:ve.mediaBlurb??`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`}),ve.carriesMedia&&_e===`sensor`&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:j(`notificationRules.media.sensorOneSnapshot`,`A sensor rule attaches one snapshot of the camera automatically — there is no detection to choose a crop, a GIF or a clip around.`)}),ve.carriesMedia&&_e!==`sensor`&&ve.mediaBlurb!==void 0&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:ve.mediaBlurb}),ve.carriesMedia&&_e!==`sensor`&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),u(T,{value:F.mediaAttach,onChange:e=>{let t=En(e.target.value);t&&H({mediaAttach:t})},options:Lt.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Lt.find(e=>e.value===F.mediaAttach)?.description}),n(`div`,{className:`mt-2 space-y-1`,children:[ve.carriesSubjectCrop&&n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:F.mediaZoneCrop,onChange:e=>H({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),`Crop the image to the rule's zone`]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:F.mediaGif,onChange:e=>H({mediaGif:e.target.checked}),className:`accent-primary`}),`Attach a GIF around the event`]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:F.mediaClip,onChange:e=>H({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(F.mediaGif||F.mediaClip)&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),u(T,{value:F.mediaProfile??``,onChange:e=>H({mediaProfile:bn(e.target.value)}),options:Hr.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`A notification is watched on a phone — the cheapest stream is normally the right one, and the high profile only costs CPU to render.`}),u(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),u(T,{value:F.mediaClipSpeed===void 0?``:String(F.mediaClipSpeed),onChange:e=>H({mediaClipSpeed:Gt(e.target.value)}),options:In.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`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.`})]})]}),_e===`sensor`&&ve.carriesMedia&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Linked cameras`}),u(T,{value:F.mediaLinkedCameras??``,onChange:e=>H({mediaLinkedCameras:Yt(e.target.value)}),options:zt.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`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.`})]}),ve.carriesMedia&&_e!==`sensor`&&ve.carriesSubjectCrop&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),u(T,{value:F.mediaFrame??``,onChange:e=>H({mediaFrame:wn(e.target.value)}),options:Rr.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`What the attached still shows. "Automatic" leaves it to the attachment mode above.`})]})]}),n(`div`,{className:`space-y-2`,children:[u(bo,{label:`Notification title`,value:F.templateTitle,onChange:e=>H({templateTitle:e}),vars:De(`title`),testId:`rule-template-title`}),u(bo,{label:`Notification body`,value:F.templateBody,onChange:e=>H({templateBody:e}),vars:De(`body`),multiline:!0,testId:`rule-template-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank for the hub's own wording (editable on the Texts tab).`}),_n(F)!==null&&u(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:_n(F)}),u(xo,{context:Ee(`body`),title:F.templateTitle,body:F.templateBody,testId:`rule-template-preview`})]})]}),n(M,{value:`conditions`,className:`space-y-4`,children:[n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:ge?`Which system events`:zr(F.conditions)??`Conditions`}),F.conditions.audio!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`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).`}),F.conditions.occupancy!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`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.`}),ge&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`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.`}),s.length===0?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):u(Ps,{catalog:dn(F)?s.filter(e=>e.id!==`schedule`):s,taxonomy:d,delivery:F.delivery,conditions:F.conditions,classScope:F.classScope,onClassScopeChange:e=>H({classScope:e}),actions:xr(F.actions),sequenceActionsOf:e=>v.find(t=>t.id===e)?.actions,savedConditions:P.conditions,schedule:F.schedule,deviceIds:sn(F),zoneCameraIds:Zo(F.deviceScope,f),cameras:f,fleet:_,allDevices:g,gateable:m,gateableScenes:h,onConditionsChange:e=>H({conditions:e}),onScheduleChange:e=>H({schedule:e})})]}),ge&&u(Xf,{value:F.systemEventDelivery,family:ye,onChange:e=>H({systemEventDelivery:e}),draft:()=>Rt(F,U,s)}),N&&e&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test this rule for real`}),u(el,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...sn(F)[0]===void 0?{}:{fallbackDeviceId:sn(F)[0]}})]}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`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.`})]}),!ge&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),n(A,{size:`sm`,variant:`outline`,type:`button`,disabled:oe.isPending||!Kt(F,U,new Set(v.map(e=>e.id))),onClick:()=>{R(null),oe.mutate()},children:[oe.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(b,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),te!==null&&u(pp,{delivery:F.delivery,results:te,targetNames:se})]})]})]})]}),Oe.length>0&&n(`div`,{"data-testid":`rule-form-dropped`,className:`mt-3 shrink-0 rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[n(`p`,{className:`text-foreground`,children:[`Saving drops `,Oe.length,` condition`,Oe.length===1?``:`s`,` this kind of rule cannot use:`]}),Oe.map(e=>n(`p`,{children:[u(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),he.length>0&&u(`div`,{"data-testid":`rule-form-problems`,className:`mt-3 shrink-0 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1`,children:he.map(e=>u(`p`,{children:e},e))}),n(`div`,{className:`flex shrink-0 justify-end gap-2 mt-4`,children:[u(A,{variant:`secondary`,size:`sm`,type:`button`,onClick:E,children:`Cancel`}),n(A,{size:`sm`,type:`button`,disabled:ae.isPending||!Kt(F,U,new Set(v.map(e=>e.id))),onClick:()=>{R(null),ae.mutate()},children:[ae.isPending&&u(K,{className:`h-3.5 w-3.5 animate-spin`}),N?`Save changes`:`Create rule`]})]})]})}):u(fp,{rule:e,onCancel:E})}function fp({rule:e,onCancel:t}){let r=Object.keys(e?.conditions??{});return u(Ae,{open:!0,onOpenChange:e=>!e&&t(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,children:[n(`div`,{className:`flex items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[u(ce,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),u(q,{variant:`warning`,children:`read-only`})]}),n(`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:[`This rule uses the trigger `,u(`code`,{children:e?.delivery}),`, which this version of the admin UI cannot author. It is shown exactly as stored and nothing here can change it — editing it with an editor that does not know the trigger would rewrite it. Update the server bundle, or edit this rule from the viewer app.`]}),n(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),u(`dd`,{className:`text-foreground`,children:e?.delivery})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),u(`dd`,{className:`text-foreground`,children:e?.enabled?`yes`:`no`})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),u(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),u(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):`none`})]})]}),u(`div`,{className:`flex justify-end gap-2 mt-4`,children:u(A,{variant:`secondary`,size:`sm`,type:`button`,onClick:t,children:`Close`})})]})})}function pp({delivery:e,results:t,targetNames:r}){if(e===`device-event`)return u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`});if(t.length===0)return u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`No records in the last 60 minutes matched — nothing to evaluate.`});let i=t.filter(e=>e.wouldFire).length;return n(`div`,{className:`mt-2 space-y-1.5`,children:[n(`div`,{className:`text-[11px] text-foreground-subtle`,children:[i,` of `,t.length,` evaluated record`,t.length===1?``:`s`,` would fire.`]}),u(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>n(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?u(I,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(v,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),n(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`object`}),e.wouldFire?n(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,r.join(`, `)||`targets`]}):e.failedCondition&&n(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}t();var mp=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,hp=`block text-[11px] font-medium text-foreground`,gp=[[`notificationRules`,`listSequences`]];function _p(){return{name:``,minDelaySec:``,actions:[Dn()]}}function vp(e){return{id:e.id,name:e.name,minDelaySec:e.minDelaySec===void 0?``:String(e.minDelaySec),actions:[...e.actions]}}function yp(e){let t=[],n=0;for(;n<e.length;){if(e[n].kind===`wait`){t.push({start:n,kind:`wait`,length:1}),n+=1;continue}let r=ko(e,n);t.push({start:n,kind:`cap`,length:r.length}),n+=r.length}return t}function bp(){let e=o(),t=y({}),i=re(),a=Ee(),s=U(),[l,d]=c(null),f=ge({projection:`slim`}),p=De(f),m=r(()=>(f.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[f.data]),h=()=>{e.invalidateQueries({queryKey:gp})},_=async()=>{if(l===null||l.name.trim()===``||l.actions.length===0)return;let e={name:l.name.trim(),...l.minDelaySec===``?{}:{minDelaySec:Number(l.minDelaySec)},actions:l.actions};l.id===void 0?await i.mutateAsync({sequence:e}):await a.mutateAsync({sequenceId:l.id,sequence:e}),d(null),h()},v=t.data?.sequences??[],b=l===null?[]:yp(l.actions);return n(Jr,{icon:ei,title:`Sequences`,subtitle:`Named step lists shared by notification rules and buttons. A rule binds to one by id; two rules sharing a gate share its throttle.`,actions:n(A,{size:`sm`,type:`button`,onClick:()=>d(_p()),children:[u(Te,{className:`h-3.5 w-3.5`}),` New sequence`]}),children:[l!==null&&n(`div`,{className:`mb-4 space-y-3 rounded-md border border-border p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-2`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:hp,children:`Name`}),u(O,{className:`mt-1`,value:l.name,onChange:e=>d({...l,name:e.target.value})})]}),n(`div`,{className:`w-28`,children:[u(`label`,{className:hp,children:`Min delay (s)`}),u(`input`,{type:`number`,min:0,className:mp,value:l.minDelaySec,onChange:e=>d({...l,minDelaySec:e.target.value})})]})]}),n(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[b.map(e=>{let t=l.actions[e.start];if(e.kind===`wait`&&t.kind===`wait`)return u(xp,{step:t,devices:m,listState:p.state,fleet:p,onChange:t=>d({...l,actions:l.actions.map((n,r)=>r===e.start?t:n)}),onRemove:()=>d({...l,actions:l.actions.filter((t,n)=>n!==e.start)})},`s-${String(e.start)}`);let r=ko(l.actions,e.start);return n(`div`,{className:`flex flex-wrap items-start gap-2`,children:[n(`div`,{className:`w-24`,children:[u(`label`,{className:hp,children:`Step`}),n(`select`,{className:mp,value:`cap`,onChange:t=>{t.target.value===`wait`&&d({...l,actions:[...l.actions.slice(0,e.start),{kind:`wait`,seconds:5},...l.actions.slice(e.start+e.length)]})},children:[u(`option`,{value:`cap`,children:`Do`}),u(`option`,{value:`wait`,children:`Wait`})]})]}),u(Yr,{value:r.wire,devices:m,listState:p.state,fleet:p,allowMultiSameFamily:!0,onChange:t=>{let n=Do(t);d({...l,actions:[...l.actions.slice(0,e.start),...n,...l.actions.slice(e.start+e.length)]})}}),u(A,{size:`sm`,variant:`ghost`,type:`button`,title:`Remove`,onClick:()=>d({...l,actions:[...l.actions.slice(0,e.start),...l.actions.slice(e.start+e.length)]}),children:u(g,{className:`h-3.5 w-3.5`})})]},`s-${String(e.start)}`)}),n(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d({...l,actions:[...l.actions,Dn()]}),children:[u(Te,{className:`h-3.5 w-3.5`}),` Step`]})]}),n(`div`,{className:`flex gap-2`,children:[u(A,{size:`sm`,type:`button`,onClick:()=>void _(),children:`Save`}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d(null),children:`Cancel`})]})]}),t.isPending?u(`p`,{className:`text-sm text-foreground-subtle`,children:`Loading…`}):v.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-sm text-foreground-subtle`,children:`No sequences yet. Create one, then bind it from a rule's Actions tab.`}):u(`ul`,{className:`space-y-2`,children:v.map(e=>n(`li`,{className:`flex flex-wrap items-center justify-between gap-2 rounded-md border border-border px-3 py-2`,children:[n(`div`,{className:`min-w-0`,children:[u(`div`,{className:`text-sm font-medium text-foreground`,children:e.name}),n(`div`,{className:`text-[11px] text-foreground-subtle`,children:[e.actions.length,` step`,e.actions.length===1?``:`s`,e.minDelaySec===void 0?``:` · min delay ${String(e.minDelaySec)}s`]})]}),n(`div`,{className:`flex gap-1`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d(vp(e)),children:`Edit`}),u(A,{size:`sm`,variant:`ghost`,type:`button`,title:`Delete`,onClick:()=>{s.mutateAsync({sequenceId:e.id}).then(h)},children:u(g,{className:`h-3.5 w-3.5`})})]})]},e.id))})]})}function xp({step:e,devices:t,listState:r,fleet:i,onChange:a,onRemove:o}){return n(`div`,{className:`flex flex-wrap items-start gap-2`,children:[n(`div`,{className:`w-24`,children:[u(`label`,{className:hp,children:`Step`}),n(`select`,{className:mp,value:`wait`,onChange:n=>a(n.target.value===`wait`?{kind:`wait`,seconds:e.seconds}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[u(`option`,{value:`cap`,children:`Do`}),u(`option`,{value:`wait`,children:`Wait`})]})]}),n(`div`,{className:`w-28`,children:[u(`label`,{className:hp,children:`Seconds`}),u(`input`,{type:`number`,min:0,max:300,className:mp,value:e.seconds,onChange:e=>a({kind:`wait`,seconds:Number(e.target.value)})})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})}var Sp=[{value:`object-event`,label:`Object detection`,hint:`A detection on a live track — what an "Immediate" rule sees.`},{value:`track-end`,label:`Track end`,hint:`A finalised track: importance, dwell and label confidence exist only here.`},{value:`device-event`,label:`Device event`,hint:`A doorbell press or a linked sensor changing state.`},{value:`package-event`,label:`Package event`,hint:`A parcel delivered or picked up.`},{value:`audio-event`,label:`Audio event`,hint:`A classified audio episode. Rides the Immediate delivery, gated by the audio classes.`},{value:`occupancy-event`,label:`Occupancy edge`,hint:`A zone count crossing its threshold. Rides the Device-event delivery.`}];function Cp(e){return Sp.find(t=>t.value===e)?.value}function wp(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Tp(e){return``}var Ep={x:.25,y:.25,w:.5,h:.5},Dp={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Op(){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:Ep,occupancy:Dp,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function kp(e){return e.deviceId!==null}function Ap(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function jp(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Mp(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 Np(e){if(e.deviceId===null)return null;let t=e.trigger,n=jp(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:Pp(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 Pp(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 Fp(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Ip(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 Lp(e){let t=Op(),n=e.conditions,r=Ip(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:Fp(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Fp(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Fp(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:Tp(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Rp(n.occupancy)},onlyRuleId:e.id}}function Rp(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 zp(e){let t=[];return e.conditions.deviceState!==void 0&&t.push({conditionId:`deviceState`,note:`This rule is gated on device #${e.conditions.deviceState.deviceId} being in a given state. The gate reads the REAL device — put it in that state first, or the simulation fails closed exactly as production would.`}),e.conditions.scene!==void 0&&t.push({conditionId:`scene`,note:`This rule is gated on a scene being ${e.conditions.scene.requiredState}. The gate reads the scene's REAL state — put the scene in that state first (or reset it), or the simulation fails closed exactly as production would.`}),e.conditions.customZones!==void 0&&e.conditions.customZones.length>0&&t.push({conditionId:`customZones`,note:`This rule matches viewer-drawn polygons against the subject bbox. The bbox below is enabled but centred — move it over the polygon, or the condition fails.`}),t}function Bp(e){return{form:Lp(e),caveats:zp(e),ruleName:e.name}}var Vp=null;function Hp(e){Vp=e}function Up(){return Vp}function Wp(){Vp=null}var Gp=[`n/a`,`clear`,`suppressed`,`bypassed`],Kp=[`live`,`none`,`unavailable`,`unattachable`];function qp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jp(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Yp(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Xp(e){if(!qp(e))return null;let t=Jp(e,`ruleId`),n=Jp(e,`ruleName`),r=Jp(e,`cooldown`),i=Gp.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Jp(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Yp(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:Yp(e,`targetIds`)}}function Zp(e){if(!qp(e))return null;let t=Jp(e,`recordId`),n=Jp(e,`delivery`),r=Jp(e,`still`),i=Kp.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=Xp(e);t!==null&&o.push(t)}let s=Jp(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Yp(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Qp(e){if(e.droppedBy!==void 0)return`Dropped before evaluation (${e.droppedBy}) — no rule was consulted.`;if(e.candidates===0)return`No enabled rule declares the "${e.delivery}" delivery, so nothing was evaluated.`;let t=e.outcomes.filter(e=>e.matched).length,n=e.outcomes.reduce((e,t)=>e+t.enqueued,0);return t===0?`${e.candidates} candidate rule${e.candidates===1?``:`s`} evaluated, none matched.`:`${t} of ${e.candidates} candidate rule${e.candidates===1?``:`s`} matched — ${n} notification${n===1?``:`s`} enqueued.`}var $p=new Set([`sensor`,`control`,`custom`]);function em({form:e,cameras:t,taxonomy:r,kinds:i,kindsLoading:a,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=nt(`classes`,r);if(e.trigger===`device-event`)return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),u(tm,{form:e,kinds:i,loading:a,onPatch:o})]});if(e.trigger===`audio-event`){let r=i.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[u(`label`,{className:J,children:`Audio classes`}),u(kt,{options:r,value:e.classNames,onChange:e=>o({classNames:e}),loading:a,emptyHint:e.deviceId===null?`Pick a camera first — the audio vocabulary is per camera.`:`This camera advertises no audio kinds. The audio classifier is probably off for it.`,placeholder:`Audio class id…`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Zones`}),u(Vr,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]})]})}return e.trigger===`occupancy-event`?n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),u(nm,{form:e,cameras:t,taxonomy:r,onPatch:o})]}):n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[u(`label`,{className:J,children:`Detected classes`}),c===null?u(kn,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):u(Fr,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Zones the subject is in`}),u(Vr,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),u(T,{value:e.packagePhase,options:[{value:``,label:`— none —`},{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`}],onChange:e=>o({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function tm({form:e,kinds:t,loading:r,onPatch:i}){let o=t.filter(e=>$p.has(e.category)),s=o.find(t=>t.kind===e.sensorKind);return n(a,{children:[n(`div`,{children:[u(`label`,{className:J,children:`Event kind`}),u(T,{value:e.sensorKind,options:[{value:``,label:r?`Loading kinds…`:`— pick a kind —`},...o.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=o.find(t=>t.kind===e.target.value);i({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!r&&o.length===0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.deviceId===null?`Pick a camera first — sensor and control kinds come from the devices linked to it.`:`This camera has no linked sensor or control device, so it can produce no device event. Link one on the camera page first.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:J,children:`Source device`}),u(O,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>i({sourceDeviceId:Ap(e.target.value)??null})}),u(`p`,{className:Bn,children:s===void 0?`The linked device whose state changed. Filled in for you when you pick a kind.`:`Filled in from "${s.label}" — contributed by device #${s.source.deviceId} via the ${s.source.capName} capability.`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Event type token`}),u(O,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>i({eventType:e.target.value})}),u(`p`,{className:Bn,children:`Only event-emitter sources carry one. A passive sensor emits none, and a rule gating on a token would fail closed for it.`})]})]})]})}function nm({form:e,cameras:t,taxonomy:r,onPatch:i}){let o=e.deviceId===null?[]:[e.deviceId],s=nt(`occupancy`,r),c=s===null?[]:s.groups.flatMap(e=>e.options),l=e.occupancy,d=e=>i({occupancy:{...l,...e}});return n(a,{children:[n(`div`,{children:[u(`label`,{className:J,children:`Zone`}),u(Vr,{deviceIds:o,cameras:t,value:l.zoneId===``?[]:[l.zoneId],onChange:e=>d({zoneId:e[e.length-1]??``})}),u(`p`,{className:Bn,children:`Leave empty for the whole frame.`})]}),n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:J,children:`Class`}),u(T,{value:l.className,options:[{value:``,label:`— any class —`},...c.map(e=>({value:e.value,label:e.label}))],onChange:e=>d({className:e.target.value})})]}),n(`div`,{className:`flex flex-wrap items-end gap-3`,children:[n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count now`,u(O,{type:`number`,min:0,className:`w-20`,value:String(l.count),onChange:e=>d({count:Ap(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,u(O,{type:`number`,min:0,className:`w-20`,value:String(l.previousCount),onChange:e=>d({previousCount:Ap(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,u(O,{type:`number`,min:1,className:`w-20`,value:String(l.threshold),onChange:e=>d({threshold:Ap(e.target.value)??1})})]}),n(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[u(G,{checked:l.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function rm({form:e,cameras:t,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId];return n(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[u(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Advanced`}),n(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:e.crossingEnabled,onCheckedChange:e=>r({crossingEnabled:e}),"aria-label":`zone crossing`}),`This event is a confirmed zone crossing`]}),e.crossingEnabled&&n(`div`,{className:`mt-1 space-y-1.5`,children:[u(`div`,{className:`max-w-[12rem]`,children:u(T,{value:e.crossingDirection,options:[{value:`enter`,label:`Entered the zone`},{value:`exit`,label:`Left the zone`}],onChange:e=>r({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),u(Vr,{deviceIds:i,cameras:t,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>r({crossingZoneId:e[e.length-1]??``})})]})]}),n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:e.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),u(`p`,{className:Bn,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&u(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,u(O,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:n=>r({bbox:{...e.bbox,[t]:Ap(n.target.value)??0}})})]},t))})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:J,children:`Happened at`}),n(`div`,{className:`flex items-center gap-2`,children:[u(O,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:Mp(Date.now())}),children:`Set`}):u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:`Now`})]}),u(`p`,{className:Bn,children:`Empty = now. Set it to a time inside (or outside) a rule's schedule window to test the schedule without waiting for the hour.`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Detection source`}),u(T,{value:e.source,options:[{value:``,label:`— unset (reads as pipeline) —`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`},{value:`audio`,label:`Audio`}],onChange:e=>{let t=e.target.value;r({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function im({checked:e,label:t,hint:r,danger:i=!1,onChange:a}){return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(G,{checked:e,onCheckedChange:a,"aria-label":t}),t,i&&u(q,{variant:`danger`,children:`actuates devices`})]}),u(`p`,{className:Bn,children:r})]})}t();var am={live:`A live snapshot of the camera was taken and attached.`,none:`No still was requested.`,unavailable:`A still was requested but the camera could not produce one.`,unattachable:`This trigger cannot carry a still at all — an audio or occupancy notification freezes no media owner, so it ships text-only in production too. This is not a limit of the test.`},om={"n/a":`The rule did not match, so no cooldown was consulted.`,clear:`No cooldown was in effect — the rule was free to fire.`,suppressed:`A cooldown from an earlier fire silenced this one. Re-run with "Ignore cooldown".`,bypassed:`A cooldown was in effect and was deliberately ignored for this run.`};function sm({result:e,targetName:t}){return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[u(`p`,{className:`text-xs font-medium text-foreground`,children:Qp(e)}),n(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[u(cm,{recordId:e.recordId}),n(`span`,{children:[`delivery `,u(`span`,{className:`text-foreground`,children:e.delivery})]}),n(`span`,{children:[`candidates `,u(`span`,{className:`text-foreground`,children:e.candidates})]}),n(`span`,{title:am[e.still],children:[`still `,u(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&n(q,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&u(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>u(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`No rule was evaluated. Either no enabled rule declares the`,` `,u(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):u(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>u(lm,{outcome:e,targetName:t},e.ruleId))})]})}function cm({recordId:e}){let[t,r]=c(!1);return n(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[u(`code`,{className:`text-[10px] text-foreground`,children:e}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)},()=>r(!1))},title:`Copy record id`,children:u(B,{className:`h-3 w-3`})}),t&&u(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function lm({outcome:e,targetName:t}){return n(`li`,{className:`space-y-1 px-2.5 py-2`,children:[n(`div`,{className:`flex items-center gap-2`,children:[e.matched?u(I,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(v,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),n(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:om[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&u(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?`Did not match. The engine reported no failing condition id.`:n(a,{children:[`Did not match — first failing condition`,` `,u(`code`,{className:`text-foreground`,children:e.failedCondition}),`.`]})}),e.matched&&n(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[e.enqueued,` outbox row`,e.enqueued===1?``:`s`,` enqueued`,e.targetIds.length>0?` → ${e.targetIds.map(t).join(`, `)}`:` — no target resolved, so nothing will be delivered`,`.`]}),e.matchedOn!==void 0&&e.matchedOn.length>0&&n(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:[`matched on: `,e.matchedOn.join(`, `)]})]})}t();var um=`pipeline-analytics`,dm=`nc.injectTestEvent`;function fm(){let e=p(),[t,a]=c(()=>Up()?.form??Op()),[o,s]=c(()=>Up()?.caveats??[]),[f,m]=c(()=>Up()?.ruleName??null);d(()=>Wp(),[]);let[h,g]=c(null),[_,v]=c(!1),[y,S]=c(null),C=e=>a(t=>({...t,...e})),w=ge({projection:`slim`}),E=i({queryKey:sp,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),D=i({queryKey:ap,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),k=i({queryKey:op,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),j=t.deviceId,ee=i({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:j}],enabled:j!==null,staleTime:6e4,queryFn:async()=>j===null?[]:(await e.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[j]})).flatMap(e=>[...e.kinds])}),M=r(()=>(w.data??[]).filter(e=>e.type===Be.Camera).map(e=>({id:e.id,name:e.name})),[w.data]),N=E.data?.taxonomy,P=ee.data??[],I=r(()=>{let e=new Map;for(let t of k.data??[])e.set(t.id,t.name);return e},[k.data]),L=l({mutationFn:async()=>{let n=Np(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:um,action:dm,input:n})},onMutate:()=>{g(null),v(!1),S(null)},onSuccess:e=>{let t=Zp(e);g(t),v(t===null)},onError:e=>S(e instanceof Error?e.message:`The simulation failed.`)}),R=wp(t.trigger),z=D.data?.find(e=>e.id===t.onlyRuleId);return n(Jr,{icon:b,title:`Simulate an event`,subtitle:`Inject a synthetic detection, doorbell press or occupancy edge and see exactly which rules match it, which condition each one fails on, and what would be delivered. Nothing is persisted — no track, no event row, no media.`,children:[w.isError&&u(F,{title:`Failed to load cameras`,message:w.error instanceof Error?w.error.message:`Unknown error`,onRetry:()=>void w.refetch()}),f!==null&&n(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:[`Seeded from the rule `,u(`span`,{className:`font-medium`,children:f}),`. Only that rule will be evaluated — clear "Evaluate only one rule" below to run the whole rule set.`]}),o.length>0&&u(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:o.map(e=>n(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[u(je,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId))}),n(x,{className:`space-y-4`,children:[n(`div`,{children:[u(`label`,{className:J,children:`Rule to simulate`}),u(T,{"data-testid":`simulate-seed-rule`,value:t.onlyRuleId,options:[{value:``,label:`— pick a rule to prefill trigger + conditions —`},...(D.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.delivery}`}))],onChange:e=>{let t=e.target.value;if(t.length===0){a(Op()),s([]),m(null);return}let n=D.data?.find(e=>e.id===t);if(n===void 0){C({onlyRuleId:t});return}a(Lp(n)),s(zp(n)),m(n.name)}}),u(`p`,{className:Bn,children:`Picks the trigger that rule listens for and fills the fields from its conditions. Edit any value below, then inject.`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Camera`}),u(T,{"data-testid":`simulate-camera`,value:t.deviceId===null?``:String(t.deviceId),options:[{value:``,label:M.length===0?`Loading cameras…`:`— pick a camera —`},...M.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{C({deviceId:Ap(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),u(`p`,{className:Bn,children:`The camera the event is attributed to — what a notification shows.`})]}),n(`div`,{children:[u(`label`,{className:J,children:`Trigger`}),u(T,{"data-testid":`simulate-trigger`,value:t.trigger,options:Sp.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=Cp(e.target.value);if(!n)return;let r=Tp(t.trigger);C({trigger:n,source:t.source===``||t.source===r?Tp(n):t.source})}}),n(`p`,{className:Bn,children:[Sp.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,u(`span`,{className:`text-foreground`,children:R}),` are candidates.`]})]}),u(em,{form:t,cameras:M,taxonomy:N,kinds:P,kindsLoading:ee.isLoading,onPatch:C}),n(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[u(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),n(`div`,{className:`mt-2 space-y-3`,children:[u(`p`,{className:Bn,children:`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.`}),n(`div`,{children:[u(`label`,{className:J,children:`Label (identity name / plate / subclass)`}),u(O,{value:t.label,placeholder:`e.g. Marco, AB123CD`,onChange:e=>C({label:e.target.value})})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:J,children:`Detection confidence`}),u(vr,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>C({confidence:e})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Label-match confidence`}),u(vr,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>C({labelConfidence:e})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Importance`}),u(vr,{value:t.importance,min:0,max:1,step:.05,onChange:e=>C({importance:e})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Dwell (seconds)`}),u(vr,{value:t.dwellSeconds,min:0,step:1,onChange:e=>C({dwellSeconds:e})})]})]})]})]}),u(rm,{form:t,cameras:M,onPatch:C}),n(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),u(im,{checked:t.bypassCooldown,label:`Ignore the cooldown`,hint:`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`,onChange:e=>C({bypassCooldown:e})}),u(im,{checked:t.bypassMute,label:`Ignore mutes and snoozes`,hint:`A muted camera or a snoozed rule drops the event before any rule is consulted.`,onChange:e=>C({bypassMute:e})}),u(im,{checked:t.runActions,danger:!0,label:`Run the rule's actions — this actuates real devices`,hint:`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`,onChange:e=>C({runActions:e})}),n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:J,children:`Still image`}),u(T,{value:t.still,options:[{value:`live`,label:`Live snapshot of the camera`},{value:`none`,label:`No image`}],onChange:e=>C({still:e.target.value===`none`?`none`:`live`})})]}),n(`div`,{children:[u(`label`,{className:J,children:`Evaluate only one rule`}),u(T,{value:t.onlyRuleId,options:[{value:``,label:`— every enabled rule —`},...(D.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>C({onlyRuleId:e.target.value})}),t.onlyRuleId.length>0&&z===void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,u(`code`,{children:t.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),y!==null&&u(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:y}),n(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[u(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`}),n(A,{size:`sm`,type:`button`,disabled:L.isPending||!kp(t),onClick:()=>L.mutate(),children:[L.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(b,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),_&&u(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:`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&&u(sm,{result:h,targetName:e=>I.get(e)??e})]})}var pm=e=>typeof e==`string`&&e.length>0;function mm(e){return{levels:e.levels,formats:e.format,bodyMaxLen:e.bodyMaxLen,attachmentSlots:e.attachments.mediaTypes,attachmentMode:e.attachments.mode,attachmentMax:e.attachments.max,attachmentMaxBytes:e.attachments.maxBytes,maxActions:e.actions,showActions:e.actions>0,showClickUrl:e.clickUrl,showSound:e.sound,showTtl:e.ttl,showTag:!0}}function hm(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function gm(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];pm(i)&&n.push({mediaType:r,url:i})}return n}function _m(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=pm(r.label),i=pm(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:`Action ${n.length+1}`,...i?{url:r.url}:{}})}return n}function vm(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=gm(e,t.attachmentUrls),i=_m(e,t.actions),a=e.ttl&&pm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:hm(e,t.format),priority:ym(t.priority),...pm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&pm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&pm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...pm(t.tag)?{tag:t.tag}:{}}}function ym(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function bm(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 xm(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Sm={image:f(`/addon/notifiers/samples/image`),video:f(`/addon/notifiers/samples/video`),gif:f(`/addon/notifiers/samples/gif`),audio:f(`/addon/notifiers/samples/audio`),icon:f(`/addon/notifiers/samples/icon`)};function Cm(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function wm(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])Cm(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function Tm(e,t,n){let r=xm(e);return Cm(e,t)?{...r,body:n,attachmentUrls:{[t]:Sm[t]}}:{...r,body:n}}function Em(e,t){let n=xm(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return Tm(e,`image`,`Test notification with an image.`);case`gif`:return Tm(e,`gif`,`Test notification with an animation.`);case`video`:return Tm(e,`video`,`Test notification with a video.`);case`audio`:return Tm(e,`audio`,`Test notification with audio.`);case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:`Action ${t+1}`,url:`/`}));return{...n,title:`CamStack`,body:`Test notification with action buttons.`,actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=bm(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}t();var Dm={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},Om=`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`,km=`block text-[11px] font-medium text-foreground mb-1`;function Am({target:e,kind:t,open:i,onClose:a}){let o=p(),s=r(()=>mm(t.caps),[t.caps]),d=r(()=>wm(t.caps),[t.caps]),[f,m]=c(()=>xm(t.caps)),[h,g]=c(null),_=r(()=>vm(t.caps,f),[t.caps,f]),v=f.body.length,y=v>s.bodyMaxLen,b=e=>m(t=>({...t,...e})),x=l({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:vm(t.caps,f)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:`Test failed`})}),T=e=>{m(Em(t.caps,e)),g(null)},E=(e,t,n)=>{let r=f.actions.length>0?[...f.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},b({actions:r})};return u(Ae,{open:i,onOpenChange:e=>!e&&a(),children:n(S,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[u(w,{children:n(C,{children:[`Test "`,e.name,`" (`,t.label,`)`]})}),n(z,{className:`space-y-4 pr-1`,children:[u(`div`,{className:`flex flex-wrap gap-1.5`,children:d.map(e=>u(A,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>T(e),children:Dm[e]},e))}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.levels.length>0&&n(`div`,{children:[u(`label`,{className:km,children:`Level`}),n(`select`,{className:Om,value:f.level,onChange:e=>b({level:e.target.value}),children:[u(`option`,{value:``,children:`— derive from priority —`}),s.levels.map(e=>n(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=s.levels.find(e=>e.id===f.level);return e?n(`div`,{className:`mt-1 space-y-1`,children:[e.description&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),n(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&u(q,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&u(q,{variant:`info`,children:`silent`}),e.flags?.noPush&&u(q,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&n(`p`,{className:`text-[10px] text-warning`,children:[`Requires target config: `,e.requires.join(`, `)]})]}):null})()]}),n(`div`,{children:[n(`label`,{className:km,children:[`Priority (ordinal): `,f.priority]}),u(`input`,{type:`range`,min:1,max:5,step:1,value:f.priority,onChange:e=>b({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),s.formats.length>0&&n(`div`,{children:[u(`label`,{className:km,children:`Format`}),u(`div`,{className:`flex flex-wrap gap-2`,children:s.formats.map(e=>n(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:f.format===e,onChange:()=>b({format:e})}),e]},e))})]}),n(`div`,{children:[u(`label`,{className:km,children:`Title`}),u(`input`,{className:Om,value:f.title,onChange:e=>b({title:e.target.value})})]}),n(`div`,{children:[n(`label`,{className:km,children:[`Body`,` `,n(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,s.bodyMaxLen,y?` — overflow`:``,`)`]})]}),u(`textarea`,{className:`${Om} min-h-[80px] resize-y`,value:f.body,onChange:e=>b({body:e.target.value})})]}),s.attachmentSlots.length>0&&n(`div`,{children:[n(`label`,{className:km,children:[`Attachments`,` `,n(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,s.attachmentMode,`, max `,s.attachmentMax,s.attachmentMaxBytes?`, ≤${Math.round(s.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),u(`div`,{className:`space-y-1.5`,children:s.attachmentSlots.map(e=>n(`div`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),u(`input`,{className:Om,placeholder:`${e} URL`,value:f.attachmentUrls[e]??``,onChange:t=>b({attachmentUrls:{...f.attachmentUrls,[e]:t.target.value}})})]},e))})]}),s.showActions&&n(`div`,{children:[n(`label`,{className:km,children:[`Actions (up to `,s.maxActions,`)`]}),u(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(s.maxActions,3)},(e,t)=>n(`div`,{className:`flex items-center gap-2`,children:[u(`input`,{className:Om,placeholder:`label`,value:f.actions[t]?.label??``,onChange:e=>E(t,`label`,e.target.value)}),u(`input`,{className:Om,placeholder:`url`,value:f.actions[t]?.url??``,onChange:e=>E(t,`url`,e.target.value)})]},t))})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.showClickUrl&&n(`div`,{children:[u(`label`,{className:km,children:`Click URL`}),u(`input`,{className:Om,value:f.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),s.showSound&&n(`div`,{children:[u(`label`,{className:km,children:`Sound`}),u(`input`,{className:Om,value:f.sound,onChange:e=>b({sound:e.target.value})})]}),s.showTtl&&n(`div`,{children:[u(`label`,{className:km,children:`TTL (seconds)`}),u(`input`,{className:Om,type:`number`,value:f.ttl,onChange:e=>b({ttl:e.target.value})})]}),s.showTag&&n(`div`,{children:[u(`label`,{className:km,children:`Tag`}),u(`input`,{className:Om,value:f.tag,onChange:e=>b({tag:e.target.value})})]})]}),h&&u(jm,{result:h}),n(`details`,{className:`text-[10px]`,children:[u(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),u(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),n(te,{children:[u(A,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),n(A,{size:`sm`,type:`button`,disabled:x.isPending||f.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Ne,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function jm({result:e}){let t=e.renderedAs;return n(`div`,{className:`rounded-md border px-3 py-2 text-xs ${e.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[n(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?u(I,{className:`h-3.5 w-3.5 text-success`}):u(v,{className:`h-3.5 w-3.5 text-danger`}),u(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&u(`p`,{className:`mt-1 text-danger`,children:e.error}),t&&n(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[u(`dt`,{children:`Resolved level`}),u(`dd`,{className:`text-foreground`,children:t.level}),u(`dt`,{children:`Format sent`}),u(`dd`,{className:`text-foreground`,children:t.format}),u(`dt`,{children:`Attachments sent`}),u(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),u(`dt`,{children:`Actions sent`}),u(`dd`,{className:`text-foreground`,children:t.actionsSent}),u(`dt`,{children:`Truncated`}),u(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),u(`dt`,{children:`Dropped`}),u(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function Mm(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.addonId);e?e.push(r):(n.set(r.addonId,[r]),t.push(r.addonId))}return t.map(e=>({addonId:e,kinds:n.get(e)??[]}))}function Nm(e){let t=[],n=e=>{for(let r of e){if(r.type===`password`){t.push(r.key);continue}if(r.type===`group`){n(r.fields);continue}if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields)}};for(let t of e.sections)n(t.fields);return t}function Pm(e){let t=new Map,n=e=>{for(let r of e)if(r.type===`group`)n(r.fields);else if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields);else r.type!==`separator`&&t.set(r.key,r.label)};for(let t of e.sections)n(t.fields);return t}var Fm=`••••••••`;function Im(e){return e===`••••••••`||e===`__redacted__`}function Lm(e,t,n){let r=new Set(n),i={};for(let[t,n]of Object.entries(e)){if(!r.has(t)){i[t]=n;continue}n==null||n===``||Im(n)||(i[t]=n)}return i}function Rm(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e)){if(!n.has(t)){r[t]=i;continue}r[t]=i!=null&&i!==``?Fm:``}return r}function zm(e){return{...e}}var Bm=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function Vm(e){return Bm.some(t=>e.includes(t))}function Hm(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function Um(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&Hm(e[n])!==Hm(t[n]))}function Wm(e,t,n,r){if(r===void 0)return Um(e,t,n);let i=new Set(n),a=Lm(e,t,n);return r.filter(n=>i.has(n)?n in a:Hm(e[n])!==Hm(t[n]))}function Gm(e,t,n){let r=Lm(e,t,n);return n.filter(e=>!(e in r))}function Km(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:Km(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Km(e.fields,t)}))}:e)}function qm(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:Km(e.fields,n)}))}}function Jm(e){let t=e.trim();return t.length===0?`Copy`:`${t} Copy`}function Ym(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,placeholder:e.placeholder??`•••••••• (leave blank to keep)`}:e.type===`group`?{...e,fields:Ym(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Ym(e.fields,t)}))}:e)}function Xm(e,t,n){let r=new Set(n.filter(e=>{let n=t[e];return n!=null&&n!==``}));return r.size===0?e:{...e,sections:e.sections.map(e=>({...e,fields:Ym(e.fields,r)}))}}var Zm=`targets`,Qm=`target`,$m=`kind`,eh=[Qm,$m];function th(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Zm),n.set(Qm,t),n.delete($m),n}function nh(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Zm),n.set(Qm,`new`),t===null||t.length===0?n.delete($m):n.set($m,t),n}function rh(e){let t=new URLSearchParams(e);return t.delete(Qm),t.delete($m),t}function ih({refusal:e,edited:t,reenter:r}){let i=r.length>0?`Re-type: ${r.join(`, `)}.`:null;return e===null?t.length===0||i===null?null:n(`p`,{className:`text-[11px] text-warning`,"data-testid":`target-secret-reenter`,children:[`You changed `,t.join(`, `),`. If that changes where this target sends, the hub will not reuse the stored secret. `,i]}):n(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-secret-refusal`,role:`alert`,children:[u(`p`,{className:`font-semibold`,children:`The hub needs the secret again — nothing was saved.`}),u(`p`,{className:`mt-1`,children:e}),i===null?null:u(`p`,{className:`mt-1 font-medium`,children:i})]})}t();var ah=[`notificationOutput`,`listTargets`],oh=[`notificationOutput`,`listTargetKinds`],sh=[`userManagement`,`listUsers`],ch=`ownerUserId`;function lh(e){let t=e.config[ch];return typeof t==`string`&&t.length>0?t:null}function uh(e){return[{key:`name`,header:`Target`,render:t=>{let r=e.kindByKey.get(t.kind);return n(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:r?.label??t.kind,children:u(dh,{kind:r,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),u(tf,{name:t.name,enabled:t.enabled,...r===void 0?{}:{onOpen:()=>e.onOpen(t,r)}})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByKey.get(t.kind)?.label??t.kind})},{key:`owner`,header:`Owner`,nowrap:!0,render:t=>{let n=lh(t);return n===null?u(q,{variant:`default`,children:`system`}):u(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Zd,{children:u(G,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let r=e.kindByKey.get(t.kind);return n(Zd,{className:`flex items-center justify-end gap-1`,children:[u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(t),title:`Test`,children:u(Ne,{className:`h-3.5 w-3.5`})}),u(A,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onDuplicate(t,r),title:`Duplicate`,children:u(B,{className:`h-3.5 w-3.5`})}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:u(g,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function dh({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?u(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):u(`span`,{className:n,children:e?.icon??`🔔`})}function fh(){let t=p(),[a,o]=Gr(),[s,f]=c({mode:`closed`}),[m,h]=c(null),g=e(null),_=i({queryKey:ah,queryFn:()=>t.trpcClient.notificationOutput.listTargets.query({})}),v=i({queryKey:oh,queryFn:async()=>(await t.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),y=r(()=>v.data??[],[v.data]),b=r(()=>{let e=new Map;for(let t of y)e.set(t.kind,t);return e},[y]),x=i({queryKey:sh,queryFn:()=>t.trpcClient.userManagement.listUsers.query()}),S=r(()=>{let e=new Map;for(let t of x.data??[])e.set(t.id,t.username);return e},[x.data]),C=l({mutationFn:e=>t.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:e.target.addonId,targetId:e.target.id,enabled:e.enabled}),onSuccess:()=>void _.refetch()}),w=l({mutationFn:e=>t.trpcClient.notificationOutput.deleteTarget.mutate({addonId:e.addonId,targetId:e.id}),onSuccess:()=>void _.refetch()}),T=m?b.get(m.kind):void 0,E=()=>{let e=a.get(Qm);e!==null&&(g.current=e),f({mode:`closed`}),o(rh(a),{replace:!0})},D=()=>{g.current=`new`,f({mode:`pick-kind`}),o(nh(a,null),{replace:!0})},O=e=>{g.current=`new:${e.kind}`,f({mode:`form`,kind:e,target:null,cloneFrom:null}),o(nh(a,e.kind),{replace:!0})},k=(e,t)=>{g.current=e.id,f({mode:`form`,kind:t,target:e,cloneFrom:null}),o(th(a,e.id),{replace:!0})};return d(()=>{if(s.mode!==`closed`)return;let e=a.get(Qm);if(e===null){g.current=null;return}if(g.current===e)return;if(e===`new`){let e=a.get($m);if(e===null||e.length===0){g.current=`new`,f({mode:`pick-kind`});return}let t=b.get(e);if(t===void 0)return;g.current=`new:${e}`,f({mode:`form`,kind:t,target:null,cloneFrom:null});return}let t=_.data?.find(t=>t.id===e);if(t===void 0)return;let n=b.get(t.kind);n!==void 0&&(g.current=e,f({mode:`form`,kind:n,target:t,cloneFrom:null}))},[s.mode,a,_.data,b]),n(Jr,{icon:Oe,title:`Notification Targets`,subtitle:`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.`,actions:n(A,{size:`sm`,type:`button`,onClick:D,children:[u(Te,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[_.isLoading&&u(Qd,{}),_.isError&&!_.isLoading&&u(F,{title:`Failed to load targets`,message:_.error instanceof Error?_.error.message:`Unknown error`,onRetry:()=>void _.refetch()}),!_.isLoading&&!_.isError&&(_.data??[]).length===0&&u($d,{children:`No notification targets yet. Click "Add target" to configure one.`}),(_.data??[]).length>0&&u(ef,{columns:uh({kindByKey:b,userNameById:S,onToggle:(e,t)=>C.mutate({target:e,enabled:t}),onTest:h,onOpen:k,onDuplicate:(e,t)=>{g.current=`new:${t.kind}`,f({mode:`form`,kind:t,target:null,cloneFrom:e}),o(nh(a,t.kind),{replace:!0})},onDelete:e=>w.mutate(e)}),rows:_.data??[],rowKey:e=>e.id,minWidthPx:720,onRowClick:e=>{let t=b.get(e.kind);t!==void 0&&k(e,t)}}),s.mode===`pick-kind`&&u(ph,{kinds:y,onCancel:E,onPick:O}),s.mode===`form`&&u(mh,{kind:s.kind,target:s.target,cloneFrom:s.cloneFrom,users:x.data??[],onCancel:E,onSaved:()=>{E(),_.refetch()}}),m&&T&&u(Am,{target:m,kind:T,open:!0,onClose:()=>h(null)})]})}function ph({kinds:e,onPick:t,onCancel:i}){let a=r(()=>Mm(e),[e]);return u(Ae,{open:!0,onOpenChange:e=>!e&&i(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[u(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),n(z,{className:`space-y-4`,children:[a.length===0&&u(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`}),a.map(e=>n(`div`,{children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),u(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(r=>n(`button`,{type:`button`,onClick:()=>t(r),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[u(dh,{kind:r,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),u(`span`,{className:`font-medium text-foreground`,children:r.label})]},`${e.addonId}:${r.kind}`))})]},e.addonId))]})]})})}function mh({kind:e,target:t,cloneFrom:i,users:a,onSaved:o,onCancel:s}){let f=p(),m=r(()=>Nm(e.configSchema),[e.configSchema]),h=t??i,g=t?.id??i?.id,[_,v]=c(()=>i===null?t?.name??e.label:Jm(i.name)),[y,b]=c(()=>h?.config??{}),[x,C]=c(()=>h?Rm(h.config,m):{}),[w,E]=c(g===void 0),[D,O]=c(null),[k,j]=c(null),[ee,M]=c(h?lh(h)??``:``);d(()=>{if(g===void 0)return;let t=!1;return f.trpcClient.notificationOutput.getTarget.query({addonId:e.addonId,targetId:g}).then(e=>{if(t)return;let n=zm(e.config);b(n),C(n),M(lh(e)??``),E(!0)}).catch(e=>{t||(O(e instanceof Error?e.message:`Failed to load target secrets`),E(!0))}),()=>{t=!0}},[g,e.addonId,f.trpcClient]);let N=()=>Lm(x,y,m),[P,F]=c(null),I=e.kind===`whatsapp`,L=l({mutationFn:()=>f.trpcClient.notificationOutput.probeTargetConfig.mutate({addonId:e.addonId,kind:e.kind,config:N(),...g===void 0?{}:{targetId:g}}),onSuccess:e=>F(e),onError:e=>{F(null),O(e instanceof Error?e.message:`Connection test failed`)}}),R=l({mutationFn:()=>{let{[ch]:n,...r}=Lm(x,y,m),a=ee===``?r:{...r,[ch]:ee},o={id:t?.id??`${e.kind}-${Date.now()}`,name:_,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:a};return f.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:o,...i===null?{}:{cloneSecretsFrom:i.id}})},onSuccess:o,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;Vm(t)?j(t):O(t)}}),B=r(()=>Pm(e.configSchema),[e.configSchema]),ne=r(()=>g===void 0?[]:Wm(x,y,m,e.destinationKeys),[g,x,y,m,e.destinationKeys]),re=r(()=>g!==void 0&&(k!==null||ne.length>0)?Gm(x,y,m):[],[g,k,ne,x,y,m]),V=r(()=>Xm(qm(e.configSchema,re),y,m),[e.configSchema,re,y,m]),H=e=>B.get(e)??e;return u(Ae,{open:!0,onOpenChange:e=>!e&&s(),children:n(S,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex min-w-0 items-center gap-2`,children:[u(dh,{kind:e,imgClassName:`h-5 w-5 object-contain shrink-0`,fallbackClassName:`text-lg`}),u(`span`,{className:`truncate`,children:t?`Edit ${t.name}`:i?`Duplicate ${i.name}`:`Add ${e.label} target`})]}),u(A,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),D&&u(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,"data-testid":`target-form-error`,children:D}),n(z,{className:`space-y-4 pr-1`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),u(`input`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,value:_,onChange:e=>v(e.target.value)})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),u(T,{value:ee,options:[{value:``,label:`System (shared, admin-managed)`},...a.map(e=>({value:e.id,label:e.username}))],onChange:e=>M(e.target.value)}),u(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:`A user-owned target belongs to that user: it shows in their viewer and their own rules may deliver to it. System targets stay admin-managed.`})]}),m.length>0&&g!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Stored secrets load into the masked fields (eye to reveal). Clear a field to leave the stored value unchanged on save; type a new value to replace it.`}),u(ih,{refusal:k,edited:ne.map(H),reenter:re.map(H)}),u(fe,{schema:V,values:x,onChange:C}),I&&n(`div`,{className:`space-y-2`,children:[n(A,{size:`sm`,variant:`outline`,type:`button`,disabled:L.isPending,onClick:()=>{O(null),F(null),L.mutate()},children:[L.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Ne,{className:`h-3.5 w-3.5`}),`Test connection`]}),P!==null&&n(`p`,{className:P.ok?`text-[11px] text-success`:`text-[11px] text-danger`,"data-testid":`target-probe-result`,children:[P.ok?`Connected — ${P.stateInstance??`authorized`}`:P.error??`Connection failed`,P.resolvedUrl.length>0?` · ${P.resolvedUrl}`:``]})]})]}),n(te,{children:[u(A,{variant:`secondary`,size:`sm`,type:`button`,onClick:s,children:`Cancel`}),n(A,{size:`sm`,type:`button`,disabled:R.isPending||!w||_.trim().length===0,onClick:()=>{O(null),j(null),R.mutate()},children:[R.isPending||!w?u(K,{className:`h-3.5 w-3.5 animate-spin`}):null,t?`Save changes`:`Create target`]})]})]})})}t();var hh=`notificationTexts`,gh=`Every sentence the Notification Center can print — and your wording for it.`;function _h({entry:e,value:t,busy:r,onChange:i,onReset:a}){let o=Rl(e),s=e.override!==null;return n(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${e.key}`,"data-source":e.source,children:[n(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`code`,{className:`text-xs font-medium`,children:e.key}),s?u(q,{variant:`info`,children:`customised`}):null,e.source===`fallback`?u(q,{variant:`warning`,children:`English fallback`}):null]}),n(`div`,{className:`flex items-start gap-2`,children:[u(`div`,{className:`flex-1`,children:u(bo,{label:``,value:t,onChange:i,vars:Ll(e),disabled:r,testId:`text-input-${e.key}`})}),u(A,{variant:`ghost`,size:`sm`,disabled:r||!s&&t===e.shipped,onClick:a,title:`Reset to the shipped wording`,"data-testid":`text-reset-${e.key}`,children:u(h,{className:`h-3.5 w-3.5`})})]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[u(`span`,{className:`font-medium`,children:`Shipped:`}),` `,u(`span`,{className:`font-mono`,children:e.shipped})]}),o===null?null:u(`p`,{className:`text-xs text-warning`,children:o})]})}function vh(){let e=p(),t=o(),[a,s]=c(null),[d,f]=c(``),[m,h]=c(new Map),[g,_]=c(!1),v=i({queryKey:[hh,a??`hub`],queryFn:async()=>{let t=Ml(await e.trpcClient.addons.custom.mutate({addonId:$,action:Cl,input:a===null?{}:{language:a}}));return _(t===null),t}}),y=()=>{h(new Map),t.invalidateQueries({queryKey:[hh]})},b=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:wl,input:{language:t}}),onSuccess:y}),S=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Tl,input:t}),onSuccess:y}),C=v.data??null,w=r(()=>C===null?[]:Il(C.entries,d),[C,d]);if(v.isLoading)return u(Jr,{icon:$r,title:`Texts`,subtitle:gh,children:u(K,{className:`h-5 w-5 animate-spin`})});if(v.isError||C===null)return u(Jr,{icon:$r,title:`Texts`,subtitle:gh,children:u(F,{title:`The notification text catalog is not available on this hub`,message:g?`The hub answered something this admin build does not understand. Update both and reload.`:`This hub has not been updated to serve the notification text catalog yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime: notifications keep using the shipped wording.`})});let E=C.language,D=b.isPending||S.isPending,j=Pl(C.entries,m),ee=Fl(C.entries,m),M=C.entries.filter(e=>e.override!==null).length,N=C.languages.map(e=>({value:e,label:El[e]})),P=(e,t)=>h(n=>new Map(n).set(e,t)),I=e=>P(e.key,e.shipped);return u(Jr,{icon:$r,title:`Texts`,subtitle:gh,children:n(`div`,{className:`flex flex-col gap-4`,children:[b.isError?u(F,{title:`Could not change the language`,message:String(b.error)}):null,S.isError?u(F,{title:`Could not save`,message:String(S.error)}):null,n(x,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-6`,children:[n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:`Hub language`}),u(`div`,{className:`w-44`,children:u(T,{value:C.activeLanguage,disabled:D,options:N,onChange:e=>{let t=e.target.value;Dl(t)&&b.mutate(t)},"data-testid":`texts-hub-language`})}),u(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:`Editing`}),u(`div`,{className:`w-44`,children:u(T,{value:E,disabled:D,options:N,onChange:e=>{let t=e.target.value;Dl(t)&&(h(new Map),s(t))},"data-testid":`texts-editing-language`})}),u(`p`,{className:`text-xs text-foreground-subtle`,children:E===C.activeLanguage?`${M} of ${C.entries.length} texts customised.`:`This hub does not speak this language — these words are not in use yet.`})]})]}),u(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:`A rule that writes its own title or body still overrides everything here — this page is the wording used when a rule does not.`})]}),n(`div`,{className:`flex flex-wrap items-center gap-3`,children:[n(`div`,{className:`relative min-w-[12rem] flex-1`,children:[u(k,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),u(O,{value:d,placeholder:`Search a key or a sentence…`,onChange:e=>f(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),n(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[w.length,` of `,C.entries.length]}),n(A,{className:`ml-auto`,disabled:D||ee===0,onClick:()=>S.mutate({language:E,overrides:j}),"data-testid":`texts-save`,children:[D?u(K,{className:`h-3.5 w-3.5 animate-spin`}):null,ee===0?`Save`:`Save ${ee}`]})]}),u(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):w.map(e=>u(_h,{entry:e,value:Nl(e,m),busy:D,onChange:t=>P(e.key,t),onReset:()=>I(e)},e.key))})]})})}t();var yh=`simulate`,bh=`rules`;function xh(){let[e,t]=Gr();return d(()=>{let n=e.get(`tab`);if(n===null||!gf(n))return;let r=new URLSearchParams(e);r.set(`tab`,bh),r.set(`section`,n),t(r,{replace:!0})},[e,t]),u(`div`,{className:`flex flex-col p-4`,children:u(Xr,{tabs:[{id:`targets`,label:`Targets`,icon:Oe,content:u(fh,{}),ownedParams:eh},{id:bh,label:`Rules`,icon:ce,content:u(up,{onSimulateRule:n=>{Hp(Bp(n));let r=new URLSearchParams(e);r.set(`tab`,yh),t(r,{replace:!0})},onOpenHistory:n=>{t(Va(e,n.id),{replace:!0})}}),ownedParams:[`section`,`rule`,`editTab`]},{id:`sequences`,label:`Sequences`,icon:ei,content:u(bp,{})},{id:yh,label:`Simulate`,icon:b,content:u(fm,{})},{id:Fa,label:`History`,icon:Me,content:u(Qa,{}),ownedParams:La},{id:`alarm`,label:`Alarm`,icon:N,content:u(Pa,{})},{id:`texts`,label:`Texts`,icon:$r,content:u(vh,{})}]})})}export{xh as NotificationsPage,xh as default};