@camstack/addon-admin-ui 1.2.301 → 1.2.302

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 (84) hide show
  1. package/dist/assets/{AddonCollectionPage-BnTiX7Mw.js → AddonCollectionPage-DruLtBHf.js} +1 -1
  2. package/dist/assets/Addons-BVFhILYH.js +1 -0
  3. package/dist/assets/{AdminTabs-D3ZZKVwl.js → AdminTabs-DvJd3Fuc.js} +1 -1
  4. package/dist/assets/AiProfiles-DMIHqW_2.js +3 -0
  5. package/dist/assets/{BrokerForm-BD78_5tg.js → BrokerForm-B755jBSt.js} +1 -1
  6. package/dist/assets/Build-DmTptVWU.js +32 -0
  7. package/dist/assets/{Capabilities-D9AGWB9e.js → Capabilities-DmKltkv5.js} +1 -1
  8. package/dist/assets/{CapabilityBadges-BFtbkvNK.js → CapabilityBadges-DX8mXXvb.js} +1 -1
  9. package/dist/assets/Cluster-kDxwVrM9.js +11 -0
  10. package/dist/assets/CompositionEditor-DYzGsy12.js +1 -0
  11. package/dist/assets/{CompositionEditorPage-DO2Dn0BI.js → CompositionEditorPage-DCXlsgUi.js} +1 -1
  12. package/dist/assets/Data-DpCmbJ_B.js +1 -0
  13. package/dist/assets/DetectionIntelligence-DcIrUiPQ.js +1 -0
  14. package/dist/assets/{DeviceAggregateSection-OZ3GwyRb.js → DeviceAggregateSection-kq3fKGNp.js} +1 -1
  15. package/dist/assets/DeviceDetail-B3zM465-.js +2 -0
  16. package/dist/assets/{Devices-RfJpSG6M.js → Devices-B8XrULYT.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-b0W8BoaF.js → EmbedPlayerPage-BBVKozYW.js} +1 -1
  18. package/dist/assets/Events-qTNyusq_.js +1 -0
  19. package/dist/assets/{FormBuilder-M_GZXV4k.js → FormBuilder-C380RUX3.js} +1 -1
  20. package/dist/assets/Identity-Ba_s7k1t.js +1 -0
  21. package/dist/assets/IntegrationDetail-DnWqxK8d.js +1 -0
  22. package/dist/assets/Integrations-CG07sO53.js +1 -0
  23. package/dist/assets/{Integrations-Vj5Kts6b.js → Integrations-Dc05GINY.js} +1 -1
  24. package/dist/assets/Locations-DS5-cOjp.js +3 -0
  25. package/dist/assets/{Logs-pFB0lGw0.js → Logs-CXiN_sya.js} +1 -1
  26. package/dist/assets/{ModelLicenses-T33GLdnY.js → ModelLicenses-DdSg3MQF.js} +1 -1
  27. package/dist/assets/{MyAccess-D6dfeu_5.js → MyAccess-JBjeuA_M.js} +1 -1
  28. package/dist/assets/Network-B5SmXgtx.js +1 -0
  29. package/dist/assets/{NodeAddonsSettingsPanel-KwlHuLN0.js → NodeAddonsSettingsPanel-C1Q5ETLf.js} +1 -1
  30. package/dist/assets/{NodeInferenceDevices-BaLeolR0.js → NodeInferenceDevices-CgDQDuBw.js} +1 -1
  31. package/dist/assets/Notifications-CKPuSgCX.js +1 -0
  32. package/dist/assets/Pipeline-BrmA4fYv.js +1 -0
  33. package/dist/assets/Plates-CyyGyl81.js +1 -0
  34. package/dist/assets/{ProviderIcon-BW6fsTrj.js → ProviderIcon-DoyEB7Oo.js} +1 -1
  35. package/dist/assets/Recordings-CiqVFnhk.js +1 -0
  36. package/dist/assets/{ScanNetworkModal-DGm3V3AY.js → ScanNetworkModal-CCqfr6h0.js} +1 -1
  37. package/dist/assets/{Scenes-BjqtqVUq.js → Scenes-rmy6HV5o.js} +1 -1
  38. package/dist/assets/{Settings-1zacrZyc.js → Settings-DQrG1WnS.js} +1 -1
  39. package/dist/assets/{Showroom-CCuHI1yd.js → Showroom-CuxeKqf_.js} +1 -1
  40. package/dist/assets/{StorageLocationsPanel-xou583ou.js → StorageLocationsPanel-B-jHqDfu.js} +1 -1
  41. package/dist/assets/{Terminal-CQN9K0Z2.js → Terminal-s6B7SK5g.js} +5 -5
  42. package/dist/assets/{Viewer-BLDwrU_F.js → Viewer-D4-GFVUH.js} +1 -1
  43. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-x75tan6e.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Ce3pikFV.js} +1 -1
  44. package/dist/assets/{authed-media-BmlgH74O.js → authed-media-BCA7Q9cq.js} +1 -1
  45. package/dist/assets/{debounced-invalidate-BImOg_ej.js → debounced-invalidate-DIctNEfo.js} +1 -1
  46. package/dist/assets/{device-integration-icon-CoYGmkej.js → device-integration-icon-C8XEBb7P.js} +1 -1
  47. package/dist/assets/{face-bbox-CqLZuQn-.js → face-bbox-i86vm5WS.js} +1 -1
  48. package/dist/assets/{hostInit-CssTvujo.js → hostInit-DzYukA60.js} +1 -1
  49. package/dist/assets/index-BAjcYqXN.js +4 -0
  50. package/dist/assets/{location-owned-usage-CKoP8-My.js → location-owned-usage-bvxtyNqS.js} +1 -1
  51. package/dist/assets/{mf-entry-bootstrap-0-55e73a3c.js → mf-entry-bootstrap-0-7502e00d.js} +2 -2
  52. package/dist/assets/remoteEntry-BqNHYh4E.js +1 -0
  53. package/dist/assets/{src-Buu4CseM.js → src-CjhDatMf.js} +2 -2
  54. package/dist/assets/{use-scenes-feed-C9tg2qpm.js → use-scenes-feed-uZP8KUJo.js} +1 -1
  55. package/dist/assets/{use-stationary-objects-CXwrzeLa.js → use-stationary-objects-BjObNHBK.js} +1 -1
  56. package/dist/assets/useDevice-IfdakO5U.js +1 -0
  57. package/dist/assets/useEventInvalidation-BYzMHWC-.js +1 -0
  58. package/dist/assets/{useNodeUrlSelection-D_ox3pUe.js → useNodeUrlSelection-DHX-26yj.js} +1 -1
  59. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BIr1NVuq.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-sZc8aFdf.js} +2 -2
  60. package/dist/index.html +3 -3
  61. package/dist/server/addon.js +63 -63
  62. package/package.json +1 -1
  63. package/dist/assets/Addons-NArkp3Bb.js +0 -1
  64. package/dist/assets/AiProfiles-CIGOtBAy.js +0 -3
  65. package/dist/assets/Build-Bkj0kU6Z.js +0 -32
  66. package/dist/assets/Cluster-CCK3Ofw6.js +0 -11
  67. package/dist/assets/CompositionEditor-BUQ9ugbg.js +0 -1
  68. package/dist/assets/Data-MoQKoTfb.js +0 -1
  69. package/dist/assets/DetectionIntelligence-CBR9HYfA.js +0 -1
  70. package/dist/assets/DeviceDetail-D5EJCiVV.js +0 -2
  71. package/dist/assets/Events-DROVZr1F.js +0 -1
  72. package/dist/assets/Identity-CVw5aYBA.js +0 -1
  73. package/dist/assets/IntegrationDetail-SxKnTPYX.js +0 -1
  74. package/dist/assets/Integrations-BWqdsUzg.js +0 -1
  75. package/dist/assets/Locations-CR3p3Ljq.js +0 -3
  76. package/dist/assets/Network-DiTcuuq1.js +0 -1
  77. package/dist/assets/Notifications-D3hxleJC.js +0 -1
  78. package/dist/assets/Pipeline-CaUjv02o.js +0 -1
  79. package/dist/assets/Plates-Dhhg5WVA.js +0 -1
  80. package/dist/assets/Recordings-DKPW0Ihl.js +0 -1
  81. package/dist/assets/index-BOh94Uhr.js +0 -4
  82. package/dist/assets/remoteEntry-D01ROqJK.js +0 -1
  83. package/dist/assets/useDevice-B0TWll8e.js +0 -1
  84. package/dist/assets/useEventInvalidation-Emuu5bns.js +0 -1
@@ -1 +0,0 @@
1
- import{K as e,Q as t,S as n,W as r,a as i,b as a,i as o,o as s,p as c,q as l,t as u,x as d,z as f}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 p,at as m,lt as h,st as g,yt as _}from"./player-overlays-3_9ROwqy.js";import{$i as v,Bt as y,Ct as b,Du as x,Ft as S,Gc as C,Hl as w,Il as T,It as E,Ju as D,Ll as O,Lt as k,Lu as A,Mt as j,Nt as M,R as N,Rt as P,Ru as ee,St as te,Tt as F,Wc as ne,Wl as re,Xu as I,Yt as ie,Yu as ae,an as L,bt as R,cn as z,dt as oe,gs as se,gu as ce,jt as le,kl as ue,ld as de,ms as fe,mu as pe,nn as B,nu as V,ol as me,sn as H,su as he,tn as U,ut as ge,vi as _e,wl as ve,wt as ye,xn as be,xt as xe,yn as Se,yt as Ce,zt as we}from"./src-Buu4CseM.js";import{t as Te}from"./send-DH62N1Ul.js";import{$ as Ee,$t as De,A as Oe,An as ke,B as Ae,C as je,D as Me,E as Ne,Et as Pe,F as Fe,G as Ie,H as Le,I as Re,J as ze,K as Be,L as Ve,M as He,N as Ue,O as We,P as Ge,Q as Ke,Qt as qe,R as Je,S as Ye,T as Xe,U as Ze,V as Qe,W as $e,X as et,Xt as tt,Y as nt,Z as rt,Zt as it,_ as at,at as ot,b as st,c as ct,ct as lt,d as ut,et as dt,f as ft,g as pt,h as mt,it as ht,k as gt,l as _t,lt as vt,m as yt,nt as bt,ot as xt,p as St,q as Ct,rt as wt,st as Tt,tt as Et,u as Dt,v as Ot,w as kt,x as At,y as jt,z as Mt}from"./src-Dw0wc5O0.js";import{D as Nt,M as Pt,O as Ft,v as It,y as Lt}from"./__vite-browser-external-Cc3gW-QT.js";import{c as Rt,d as zt,l as W,m as Bt}from"./index-BOh94Uhr.js";import{t as G}from"./AdminPage-CiKtOLQm.js";import{C as Vt,E as Ht,S as Ut,T as Wt,_ as Gt,a as Kt,b as qt,c as Jt,d as Yt,f as Xt,g as Zt,h as Qt,i as $t,l as en,m as tn,n as nn,o as rn,p as an,s as on,t as sn,u as cn,v as ln,w as un,y as dn}from"./device-picker-model-qVKFWw6-.js";import{n as fn,r as pn}from"./FormBuilder-M_GZXV4k.js";import{t as mn}from"./AdminTabs-D3ZZKVwl.js";import{t as hn}from"./use-scenes-feed-C9tg2qpm.js";var gn=_(`history`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),_n=_(`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`}]]),vn=_(`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`}]]);t();var yn={home:`Home`,away:`Away`,night:`Night`};function bn(e){return yn[e]??e}function xn(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 Sn(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 — ${En(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${En(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(t).join(`, `)}function Cn(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${wn[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var wn={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function Tn(e){return e.ruleCount===0}function En(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function Dn(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 On=2e3,kn=15e3,An=new Set([`arming`,`pending`,`triggered`]);function jn(e){return e!==void 0&&An.has(e)?On:kn}var Mn={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 Nn(e){let t=Mn[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${bn(e.targetMode)}`}function Pn(e){return e!==`disarmed`}function Fn(e){return e===`open`?`ignored until it closes`:`closed — monitored at next open`}function In(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Ln(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 Rn(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 zn(e,t,n,r){let i=Ln(e,t,n);return r==="default"?i===void 0?null:Rn(t,n,null):i===r?null:Rn(t,n,r)}function Bn(e,t){let n=e.openings.find(e=>e.mode===t);if(n===void 0)return null;let r=n.devices.filter(e=>e.blocking).length;return{blocking:r,nonBlocking:n.devices.length-r,unknown:n.unknown.length}}var Vn=[`unknown-refusal`,`stale`,`expired`,`used`];function Hn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Un(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Hn(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 Wn(e){if(!Hn(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Un(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Un(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Vn.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return null}var Gn={"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 Kn(e){return Gn[e]}var qn=[{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:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,max:tt,zeroMeans:`until disarmed`}];function Jn({label:e,value:t,max:r,zeroMeans:i,disabled:a,testId:o,children:s,onCommit:c}){let[u,f]=l(null);return n(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:e}),n(`div`,{className:`flex items-center gap-2`,children:[d(y,{type:`number`,min:0,max:r,value:u??String(t),disabled:a,onChange:e=>f(e.target.value),onBlur:()=>{let e=u===null?null:Dn(u,r);f(null),e!==null&&c(e)},className:`w-28`,"data-testid":o}),d(`span`,{className:`text-sm text-foreground-subtle`,children:xn(t,i)})]}),s]})}function Yn(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function Xn(e,t,n){if(n!==`answered`||t===void 0)return e.map(e=>({id:e,removed:!1}));let r=new Map(t.map(e=>[e.id,e.name]));return e.map(e=>{let t=r.get(e);return t===void 0?{id:e,removed:!0}:{id:e,name:t,removed:!1}})}function Zn(e,t,n,r){let i=new Set((t??[]).map(e=>e.id));return Xn(e.filter(e=>!i.has(e)),n,r)}function Qn(e,t,n){return e===`answered`&&t===0&&n===0}function $n(e,t,n){return e&&t===0&&n}var er={camera:`cameras`,device:`devices`,node:`nodes`,package:`packages`,class:`classes`,zone:`zones`,face:`faces`};function tr(e,t=`device`){let n=String(e.id);switch(t){case`node`:return e.removed?`Node ${n} — unknown to the hub`:e.name??`Node ${n}`;case`package`:return e.removed?`${n} — not installed`:e.name??n;case`class`:return e.removed?`${n} — not in the class list`:e.name??n;case`zone`:return e.removed?`${n} — zone not found`:e.name??`${n} — zone unavailable`;case`face`:return e.removed?`${n} — not in the face gallery`:e.name??n;case`camera`:case`device`:return e.removed?`Device #${n} — removed`:e.name??`Device #${n}`}}function nr({noun:e=`camera`}){return n(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`devices-widen-warning`,children:[`No `,e,` selected: the rule will apply to ALL `,er[e],`.`]})}function rr({noun:e=`cameras`}){return n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Loading `,e,`…`]})}function ir({noun:e=`devices`}){return n(`p`,{className:`text-[11px] text-warning`,children:[`The hub did not return its `,e,` — selected ones are listed by id so they can still be removed.`]})}var ar=[`contact`,`cover`,`lock-control`];function or(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 sr(e){let t=new Set(or(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 cr(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function lr(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=>Xn([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?`Device #${String(e)}`:tr(t))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function ur(e){let t=e.name.trim();return t===``?`Device #${String(e.deviceId)}`:t}function dr(e){return e===0?`Not armed — the hub refused without naming an open device.`:`Not armed — these are open:`}t();var fr=`pipeline-analytics`,pr=`The hub answered something this build cannot read — refresh after updating.`;function mr(e){return e instanceof Error?e.message:String(e)}function hr(e){return e.map(e=>`${ur(e)} (${e.state})`).join(`, `)}function gr({live:e,onChanged:t}){let r=m(),[i,a]=l(null),[o,s]=l(null),[c,f]=l(null),p=(e,t)=>r.trpcClient.addons.custom.mutate({addonId:fr,action:e,input:t}),h=e=>{if(e===null){s(pr);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: ${Kn(e.reason)}.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;f(e.excluded.length===0?`${t}.`:`${t} — excluded: ${hr(e.excluded)}.`)},g=()=>{s(null),f(null)},_=u({mutationFn:async e=>Wn(await p(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>s(mr(e)),onSettled:t}),v=u({mutationFn:async e=>Wn(await p(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>s(mr(e)),onSettled:t}),y=u({mutationFn:async()=>p(`nc.disarmAlarm`,{}),onMutate:()=>{g(),a(null)},onSuccess:()=>f(`Disarmed.`),onError:e=>s(mr(e)),onSettled:t});if(e===void 0)return n(B,{className:`p-4`,children:[d(`h3`,{className:`text-sm font-semibold mb-1`,children:`Panel`}),d(`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(B,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[n(`div`,{children:[d(`h3`,{className:`text-sm font-semibold`,children:`Panel`}),d(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:Nn(e)})]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?d(V,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>n(z,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:[`Arm `,bn(e)]},e)),d(z,{type:`button`,size:`md`,variant:Pn(e.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:`Disarm`})]})]}),o===null?null:d(`div`,{className:`mt-3`,children:d(L,{title:`The panel did not do that`,message:o})}),c===null?null:d(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:c}),i===null?null:n(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[d(`p`,{className:`text-sm font-medium`,children:dr(i.blocking.length)}),i.blocking.length>0?d(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:i.blocking.map(e=>n(`li`,{children:[ur(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:[d(z,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(i.refusalId),children:`Arm anyway`}),d(`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:[d(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:`Excluded sensors`}),e.exclusions.length===0?d(`p`,{className:`text-sm text-foreground-subtle`,children:`No sensor is excluded.`}):d(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:e.exclusions.map(e=>n(`li`,{children:[ur(e),` —`,` `,d(`span`,{className:`text-foreground-subtle`,children:Fn(e.phase)})]},e.deviceId))})]})]})}var _r=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function vr(e){return _r.some(t=>t.test(e))}function yr(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return vr(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 br(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 xr(e){return e.kind===`unscoped`||e.kind===`not-covered`}function Sr(e){return[...e.candidates].sort((e,t)=>e.name.localeCompare(t.name)||e.id-t.id).map(t=>{let n=e.removedIds.has(t.id);return{device:t,removed:n,cell:yr(e.sensors,t.id,n),coverage:br(e.coverage,t.id),blocks:!e.nonBlocking.includes(t.id)}})}function Cr(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 wr(e,t,n,r){return e===null?{kind:`start`,write:{mode:t,deviceId:n.device.id,name:n.device.name,nonBlocking:!r}}:{kind:`refused`,inFlight:e}}function Tr(e){return{nonBlockingEdit:{mode:e.mode,deviceId:e.deviceId,nonBlocking:e.nonBlocking}}}function Er(e,t){return gt(Tr(e),t)?{kind:`landed`}:{kind:`not-landed`}}t();function Dr(e){if(e===null)return`No type`;let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}var Or={zone:`Zone`,location:`Location`,none:`None`},kr={type:`Type`,zone:`Zone`,location:`Location`},Ar={type:`No type`,zone:`No zone`,location:`No location`};function jr(e,t){return t.key===`(none)`||t.label===null?Ar[e]:e===`type`?Dr(t.label):t.label}function Mr({grouping:e}){return n(`div`,{className:`mb-1.5`,children:[n(`div`,{role:`radiogroup`,"aria-label":`Group by`,className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[d(`span`,{className:`mr-1 font-semibold uppercase tracking-wide`,children:`Group by`}),nn.map(t=>{let n=t===e.groupBy;return d(`button`,{type:`button`,role:`radio`,"aria-checked":n,onClick:()=>e.onGroupByChange(t),className:n?`rounded-md border border-primary bg-primary/10 px-1.5 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-1.5 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,children:Or[t]},t)})]}),e.fallback!==null&&d(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,"data-testid":`picker-zones-note`,children:e.fallback===`pending`?`Loading zones — grouped by location for now`:`Zones unavailable — grouped by location`})]})}function Nr({facet:e,options:t,chosen:r,onChange:i,unavailable:a,disabled:o}){let s=kr[e],c=a===void 0?r.length===0?`All`:`${String(r.length)} selected`:a;return d(`div`,{"data-testid":`picker-filter-${e}`,children:n(b,{children:[n(F,{disabled:o||a!==void 0,className:`rounded-md border border-border px-1.5 py-0.5 text-[11px] text-foreground hover:bg-surface-hover disabled:opacity-50`,children:[s,`: `,c]}),d(ye,{className:`min-w-[200px] max-h-[40vh] overflow-y-auto p-1`,children:t.map(t=>{let a=jr(e,t);return n(`label`,{className:`flex cursor-pointer items-center gap-2 px-2 py-1 text-xs text-foreground hover:bg-surface-hover`,children:[d(we,{checked:r.includes(t.key),onChange:()=>i(Ht(r,t.key)),"aria-label":a}),d(`span`,{className:`min-w-0 flex-1 truncate`,children:a}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`(`,t.count,`)`]})]},t.key)})})]})})}function Pr(e){if(e.state===`pending`)return`loading zones…`;if(e.state===`failed`)return`zones unavailable`}function Fr({filters:t,onFiltersChange:r,typeOptions:i,zoneOptions:a,locationOptions:o,zones:s,grouping:c,searchPlaceholder:u,searchLabel:p,disabled:m=!1}){let[h,g]=l(t.query),_=e({filters:t,onFiltersChange:r});_.current={filters:t,onFiltersChange:r},f(()=>{if(h===_.current.filters.query)return;let e=setTimeout(()=>_.current.onFiltersChange({..._.current.filters,query:h}),200);return()=>clearTimeout(e)},[h]);let v=Pr(s),y=v!==void 0||tn(a,t.zones),b=Zt(t)||h.trim()!==``;return n(`div`,{className:`space-y-1.5`,"data-testid":`device-filter-bar`,children:[c!==void 0&&d(Mr,{grouping:c}),n(`div`,{className:fn,children:[d(ue,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`input`,{type:`text`,value:h,placeholder:u,"aria-label":p,className:`min-w-0 flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-foreground-disabled`,onChange:e=>g(e.target.value)})]}),n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[tn(i,t.types)&&d(Nr,{facet:`type`,options:i,chosen:t.types,onChange:e=>r({...t,types:e}),disabled:m}),y&&d(Nr,{facet:`zone`,options:a,chosen:t.zones,onChange:e=>r({...t,zones:e}),...v===void 0?{}:{unavailable:v},disabled:m}),tn(o,t.locations)&&d(Nr,{facet:`location`,options:o,chosen:t.locations,onChange:e=>r({...t,locations:e}),disabled:m}),b&&d(z,{variant:`ghost`,"data-testid":`picker-reset-filters`,onClick:()=>{g(``),r(Vt())},children:`Reset filters`})]}),Ut(t,s)&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`picker-zone-filter-paused`,children:`Zone filter paused — zones not loaded`})]})}t();function Ir(e,t){let n=e?.trim()??``;if(n===``)return`—`;if(t.state===`answered`){let e=ln(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function Lr(e){switch(e.kind){case`checking`:return`Checking…`;case`hub-too-old`:return`This hub does not report sensor states — update the hub`;case`read-failed`:return`State unknown — ${e.error}`;case`open`:case`closed`:return e.offline?`${e.word} — offline, last known`:e.word;case`unknown`:return e.why===`not-answered`?`Unknown (not answered)`:e.why===`read-failed`?`Unknown (could not read)`:`Unknown (no state reported)`;case`not-opening`:return`Not an opening — never blocks`;case`removed`:return`Removed`}}function Rr(e){switch(e.kind){case`arm-checked`:return`Yes`;case`arm-checked-skipped`:return`Yes — blocks arming (notifications skipped: ${e.reason===`detection-off`?`detection off`:e.reason})`;case`unscoped`:return`Covered by an all-devices rule — the arm check does not read it; never blocks this mode`;case`not-covered`:return`No — never blocks this mode`}}function zr(e){switch(e.kind){case`zone`:case`location`:return e.label;case`no-zone`:return`No zone`;case`no-location`:return`No location`}}var Br=6;function Vr({props:e,row:t}){let{mode:r,inFlight:i,onSwitch:a,zones:o,disabled:s}=e,c=xr(t.coverage),l=i!==null&&i.mode===r&&i.deviceId===t.device.id,u=i!==null&&!l;return n(`tr`,{"data-muted":c?`true`:void 0,className:c?`text-foreground-subtle`:void 0,children:[d(`td`,{className:`py-1 pr-2`,children:t.device.name}),d(`td`,{className:`py-1 pr-2`,"data-testid":`alarm-cell-zone`,children:Ir(t.device.location,o)}),d(`td`,{className:`py-1 pr-2`,children:Dr(t.device.type??null)}),d(`td`,{className:`py-1 pr-2`,"data-testid":`alarm-cell-state`,children:Lr(t.cell)}),d(`td`,{className:`py-1 pr-2`,"data-testid":`alarm-cell-coverage`,children:Rr(t.coverage)}),d(`td`,{className:`py-1`,children:n(`span`,{className:`inline-flex items-center gap-1`,children:[d(P,{checked:t.blocks,onCheckedChange:e=>a(t,e),disabled:s,"data-device-id":String(t.device.id),"aria-label":`Blocks arming: ${t.device.name}`,"aria-busy":l?!0:void 0,"aria-disabled":u?!0:void 0,className:u?`opacity-50`:void 0}),l?d(V,{className:`h-3 w-3 animate-spin`}):null]})})]})}function Hr(e){let{mode:t,rows:i,sensorsRetry:a,zones:o,groupBy:s,onGroupByChange:c,disabled:u}=e,[f,p]=l($t),[m,h]=l(60),g=r(()=>i.map(e=>e.device),[i]),_=r(()=>Kt(g,f,o),[g,f,o]),v=r(()=>Yt(_,[],s,o),[_,s,o]),y=r(()=>Jt(v,[],new Map,!0),[v]),b=r(()=>new Map(i.map(e=>[e.device.id,e])),[i]),x=r(()=>Qt(g,`type`,f.types,o),[g,f.types,o]),S=r(()=>Qt(g,`zone`,f.zones,o),[g,f.zones,o]),C=r(()=>Qt(g,`location`,f.locations,o),[g,f.locations,o]),w=Xt(y,m),T=i.length-_.length;return n(`div`,{className:`mt-2 space-y-1.5`,children:[d(Fr,{filters:f,onFiltersChange:e=>{p(e),h(60)},typeOptions:x,zoneOptions:S,locationOptions:C,zones:o,grouping:{groupBy:s,onGroupByChange:c,fallback:v.fallback},searchPlaceholder:`Search by name, room or type…`,searchLabel:`Search devices`}),a===null?null:n(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[d(`span`,{children:`Could not read the sensor states.`}),d(z,{type:`button`,size:`sm`,variant:`outline`,onClick:a,children:`Retry`})]}),d(`div`,{className:`overflow-x-auto`,children:n(`table`,{className:`w-full text-left text-xs`,"data-testid":`alarm-sensors-${t}`,children:[d(`thead`,{children:n(`tr`,{className:`text-foreground-subtle`,children:[d(`th`,{className:`py-1 pr-2 font-semibold`,children:`Name`}),d(`th`,{className:`py-1 pr-2 font-semibold`,children:`Zone · Location`}),d(`th`,{className:`py-1 pr-2 font-semibold`,children:`Type`}),d(`th`,{className:`py-1 pr-2 font-semibold`,children:`State`}),d(`th`,{className:`py-1 pr-2 font-semibold`,children:`Checked when arming`}),d(`th`,{className:`py-1 font-semibold`,children:`Blocks arming`})]})}),n(`tbody`,{children:[y.length===0?d(`tr`,{children:d(`td`,{colSpan:Br,className:`py-2 italic text-foreground-subtle`,children:`No device matches.`})}):null,w.rows.map(t=>{if(t.kind===`header`){let e=t.group.heading;return d(`tr`,{"data-testid":`alarm-group-header`,children:d(`th`,{colSpan:Br,className:`pt-2 text-[11px] font-semibold text-foreground-subtle`,children:e===void 0?t.group.key:zr(e)})},t.key)}let n=b.get(t.device.id);return n===void 0?null:d(Vr,{props:e,row:n},t.key)})]})]})}),T>0?n(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-rows-hidden`,children:[T,` `,T===1?`row`:`rows`,` hidden by filters`]}):null,w.remaining>0?n(`button`,{type:`button`,className:`w-full rounded border border-border py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover`,onClick:()=>h(e=>e+60),children:[`Show `,Math.min(w.remaining,60),` more (`,w.remaining,` left)`]}):null]})}function Ur({live:e,coverage:t}){let r=e===void 0?null:Bn(e,t.mode),i=e?.openings.find(e=>e.mode===t.mode);return r===null||i===void 0?d(`p`,{className:`text-xs text-foreground-subtle`,children:`Open devices: not reported by the hub.`}):i.devices.length===0&&i.unknown.length===0?d(`p`,{className:`text-xs text-foreground-subtle`,children:`Nothing this mode covers is open now.`}):n(`div`,{className:`text-xs`,"data-testid":`alarm-openings-${t.mode}`,children:[n(`p`,{className:`text-foreground-subtle`,children:[`Open now: `,r.blocking,` blocking, `,r.nonBlocking,` non-blocking`,r.unknown>0?`, ${r.unknown} unreadable`:``]}),d(`ul`,{className:`mt-1 flex flex-col gap-0.5`,children:i.devices.map(e=>n(`li`,{className:e.blocking?`text-warning`:`text-foreground-subtle`,children:[ur(e),` (`,e.state,`) — `,e.blocking?`refuses the arm`:`non-blocking`]},e.deviceId))})]})}function Wr(e){return e.status===`answered`?e.openingIds:null}function Gr({check:e,view:t}){return t.unresolved?e.status===`pending`?n(`p`,{className:`mt-1 flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[d(V,{className:`h-3 w-3 animate-spin`}),`Checking which devices are openings…`]}):e.status===`failed`?n(`div`,{className:`mt-1 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[n(`p`,{children:[`Couldn't check which devices are openings (`,e.error,`). Only devices the hub read now and devices already listed are shown.`]}),d(z,{type:`button`,size:`sm`,variant:`outline`,className:`mt-1`,onClick:e.retry,children:`Retry`})]}):null:null}function Kr({coverage:e,settings:t,disabled:r,onDelayEdit:i}){let a=e.mode,o=Oe(t,a);return n(`div`,{className:`mt-3`,"data-testid":`alarm-delays-${a}`,children:[n(`h4`,{className:`text-xs font-semibold`,children:[`Delays for `,bn(a)]}),d(`div`,{className:`mt-2 grid gap-4 sm:grid-cols-3`,children:qn.map(e=>{let s=o.source[e.field]==="default";return d(Jn,{label:e.label,value:o[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:r,testId:`alarm-delay-${a}-${e.key}`,onCommit:t=>i(e.field,t),children:s?n(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,children:[d(U,{variant:`default`,children:`Default`}),`Uses the default (`,t[e.field],` s)`]}):d(z,{type:`button`,size:`sm`,variant:`outline`,disabled:r,onClick:()=>i(e.field,`default`),"data-testid":`alarm-delay-${a}-${e.key}-default`,children:`Use default`})},e.field)})})]})}var qr={"no-opening":`This household has no opening — no contact, cover or lock — to list here.`};function Jr({coverage:e,live:t,settings:r,names:i,openingsCheck:a,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:u,groupBy:f,onGroupByChange:p,onDelayEdit:m,disabled:h}){let g=sr({live:t,listed:In(r,e.mode),openingIds:Wr(a)}),_=cr(g),{nameOf:v}=i;return n(B,{className:`p-4`,"data-mode":e.mode,"data-empty":Tn(e)?`true`:`false`,children:[n(`div`,{className:`flex items-start gap-2`,children:[d(`h3`,{className:`text-sm font-semibold`,children:bn(e.mode)}),Tn(e)?d(me,{className:`h-4 w-4 shrink-0 text-warning`}):null]}),d(`p`,{className:`mt-1 text-sm text-foreground-subtle`,children:Sn(e,v)}),e.skippedDevices.length>0?d(`div`,{className:`mt-0.5 text-xs text-warning`,"data-testid":`alarm-skipped`,children:Cn(e.skippedDevices,v)}):null,d(`div`,{className:`mt-3`,children:d(Ur,{live:t,coverage:e})}),d(Kr,{coverage:e,settings:r,disabled:h,onDelayEdit:m}),n(`div`,{className:`mt-3`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[d(`h4`,{className:`text-xs font-semibold`,children:`Sensors`}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[`Every opening of the household (contacts, covers, locks). A switch ON means the device blocks `,bn(e.mode),` from arming while it is open; OFF lets it be open without refusing the arm. The arm check only reads devices a rule of this mode names — the others never block, whatever their switch says.`]}),d(Gr,{check:a,view:g}),_===null?null:d(`p`,{className:`mt-1 text-xs text-foreground-subtle`,children:qr[_]}),o.length>0?d(Hr,{mode:e.mode,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:u,groupBy:f,onGroupByChange:p,disabled:h}):null]})]})}t();var Yr=`camstack.admin.device-picker.group-by`,Xr=[[`deviceManager`,`listSiteZones`],`device-picker`],Zr=6e4;function Qr(){try{let e=globalThis.localStorage?.getItem(`camstack.admin.device-picker.group-by`)??null;return e===null?sn:an(e)}catch{return sn}}function $r(e){try{globalThis.localStorage?.setItem(Yr,e)}catch{}}function ei(){let[e,t]=l(Qr);return{groupBy:e,setGroupBy:e=>{t(e),$r(e)}}}function ti(e){let t=m().trpcClient,{data:n,isError:a}=i({queryKey:Xr,enabled:e,staleTime:Zr,queryFn:()=>t.deviceManager.listSiteZones.query()});return r(()=>n===void 0?a?{state:`failed`}:{state:`pending`}:{state:`answered`,zones:n},[n,a])}t();var ni=[`notificationRules`,`getAlarmConfig`],ri=[`notificationOutput`,`listTargets`],ii=[`notificationRules`,`getAlarmSensors`],ai=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],oi=6e4;function si(e){return e instanceof Error?e.message:String(e)}function ci({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,` (`,bn(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,`, `,bn(e.write.mode),`).`]});case`failed`:return d(`p`,{className:`text-xs text-danger`,role:`alert`,"data-testid":`alarm-switch-failed`,children:`Could not change ${e.write.name} for ${bn(e.write.mode)}: ${e.error}`})}}function li(){let t=m(),a=s(),o=i({queryKey:ni,queryFn:async()=>t.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>jn(e.state.data?.live?.state)}),f=i({queryKey:ri,queryFn:async()=>(await t.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),p=_e({projection:`slim`}),[h,g]=l(!1),_=u({mutationFn:e=>t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{a.setQueryData(ni,e),g(!gt(t,e.settings))}}),v=()=>a.invalidateQueries({queryKey:ni}),y=r(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),b=o.data?.live,x=i({queryKey:ai,staleTime:oi,queryFn:async()=>new Set(await t.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...ar]}))}),S=r(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),C=r(()=>new Map(S.map(e=>[e.id,e])),[S]),w=x.isError?{status:`failed`,error:x.error instanceof Error?x.error.message:String(x.error),retry:()=>void x.refetch()}:x.data===void 0?{status:`pending`}:{status:`answered`,openingIds:x.data},T=r(()=>{let e=new Map;for(let t of b?.openings??[])for(let n of t.devices)e.set(n.deviceId,ur(n));return lr(y,Yn(p),e)},[b,y,p]),E=ti(!0),{groupBy:D,setGroupBy:O}=ei(),k=r(()=>{let e=new Map,t=o.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,sr({live:t.live,listed:In(t.settings,n.mode),openingIds:x.data??null}).ids);return e},[o.data,x.data]),A=r(()=>{let e=new Set;for(let t of k.values())for(let n of t)T.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[k,T]),j=i({queryKey:[...ii,A],enabled:A.length>0,placeholderData:c,refetchInterval:e=>e.state.error!==null&&vr(si(e.state.error))?!1:b!==void 0&&Pn(b.state)?5e3:15e3,retry:(e,t)=>!vr(si(t))&&e<2,queryFn:async()=>{let e=[];for(let n of Cr(A,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))}}}),M=j.isError?{status:`failed`,error:si(j.error)}:j.data===void 0?{status:`pending`}:{status:`answered`,sensors:j.data.sensors},N=e(null),[P,ee]=l(null),[te,F]=l(null),ne=async e=>{try{let n=await t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:Tr(e)});Er(e,n.settings).kind===`landed`?a.setQueryData(ni,n):(F({kind:`not-landed`,write:e}),a.invalidateQueries({queryKey:ni}))}catch(t){F({kind:`failed`,write:e,error:si(t)}),a.invalidateQueries({queryKey:ni})}finally{N.current=null,ee(null),F(e=>e?.kind===`refused`?null:e)}},re=(e,t,n)=>{let r=wr(N.current,e,t,n);if(r.kind===`refused`){F({kind:`refused`,inFlight:r.inFlight});return}N.current=r.write,ee(r.write),F(null),ne(r.write)};if(o.isLoading)return d(G,{icon:ve,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:d(V,{className:`h-5 w-5 animate-spin`})});let I=o.data;if(I===void 0||o.isError)return d(G,{icon:ve,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:d(L,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(I.deviceId===null)return d(G,{icon:ve,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:d(B,{className:`p-4`,children:d(`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 ie=I.settings,ae=_.isPending,R=ie.announceTargets,z=e=>{g(!1),_.mutate(e)},oe=(e,t)=>{switch(e){case`exitDelaySec`:return z({exitDelaySec:t});case`entryDelaySec`:return z({entryDelaySec:t});case`triggeredDurationSec`:return z({triggeredDurationSec:t})}},se=(e,t,n)=>{let r=zn(ie,e,t,n);r!==null&&z({modeDelays:[r]})};return d(G,{icon:ve,title:`Alarm`,subtitle:`The panel now, what each mode arms, and who hears about it.`,children:n(`div`,{className:`flex flex-col gap-4`,children:[_.isError?d(L,{title:`Could not save`,message:String(_.error)}):null,h?d(`div`,{"data-testid":`alarm-save-not-landed`,children:d(L,{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,d(gr,{live:I.live,onChanged:v}),n(`div`,{className:`flex flex-col gap-4`,"data-testid":`alarm-coverage`,children:[d(`p`,{className:`text-xs text-foreground-subtle`,children:`What each mode arms is derived from the enabled rules gated on this panel. Nothing here is stored — change a rule and this changes with it.`}),te===null?null:d(ci,{notice:te}),I.coverage.map(e=>d(Jr,{coverage:e,live:I.live,settings:ie,names:T,openingsCheck:w,rows:Sr({candidates:(k.get(e.mode)??[]).map(e=>({...C.get(e),id:e,name:T.nameOf(e)})),removedIds:new Set((k.get(e.mode)??[]).filter(T.isRemoved)),coverage:e,nonBlocking:In(ie,e.mode),sensors:M}),sensorsRetry:M.status===`failed`&&!vr(M.error)?()=>void j.refetch():null,inFlight:P,onSwitch:(t,n)=>re(e.mode,t,n),zones:E,groupBy:D,onGroupByChange:O,onDelayEdit:(t,n)=>se(e.mode,t,n),disabled:ae},e.mode))]}),n(B,{className:`p-4`,"data-testid":`alarm-recipients`,children:[d(`h3`,{className:`text-sm font-semibold`,children:`Recipients`}),d(`p`,{className:`text-xs text-foreground-subtle mt-1`,children:`Every alarm change is sent here: arming, armed, intrusion, siren, re-armed, disarmed, refused, excluded sensors.`}),n(`div`,{className:`mt-3 flex flex-col gap-2`,children:[d(ui,{query:f,selected:R,disabled:ae,onToggle:e=>{z({announceTargets:R.includes(e)?R.filter(t=>t!==e):[...R,e]})}}),R.length===0?d(`p`,{className:`text-xs text-warning`,"data-testid":`alarm-no-recipient`,children:`No recipient selected — alarm changes are not sent to anyone.`}):null]})]}),n(B,{className:`p-4`,"data-testid":`alarm-default-delays`,children:[d(`h3`,{className:`text-sm font-semibold`,children:`Default delays`}),d(`p`,{className:`mt-1 mb-3 text-xs text-foreground-subtle`,children:`A mode without its own value uses these.`}),d(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:qn.map(e=>d(Jn,{label:e.label,value:ie[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:ae,testId:`alarm-delay-${e.label.toLowerCase().replace(/\s+/g,`-`)}`,onCommit:t=>{t!==ie[e.field]&&oe(e.field,t)},children:d(`p`,{className:`text-xs text-foreground-subtle`,children:e.hint})},e.field))})]})]})})}function ui({query:e,selected:t,disabled:r,onToggle:i}){if(e.isPending)return d(V,{className:`h-4 w-4 animate-spin`});if(e.isError)return d(L,{title:`Targets could not be read`,message:String(e.error)});let a=e.data;return a.length===0?d(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification targets are configured — nothing can be sent.`}):d(`div`,{className:`flex max-h-56 flex-col gap-2 overflow-y-auto`,children:a.map(e=>n(`label`,{className:`flex items-center gap-2 text-sm`,children:[d(`input`,{type:`checkbox`,checked:t.includes(e.id),disabled:r,onChange:()=>i(e.id),"data-testid":`alarm-target-${e.id}`}),d(`span`,{className:`min-w-0 truncate`,children:e.name}),e.enabled?null:d(U,{variant:`warning`,children:`disabled`})]},e.id))})}var di=`history`,fi=`ruleId`,pi=[fi],mi=24,hi=0,gi=100;function _i(e,t){let n=new URLSearchParams(e);return n.set(`tab`,di),n.set(fi,t),n}function vi(e,t){let n=new URLSearchParams(e);return t===``?n.delete(fi):n.set(fi,t),n}function yi(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?mi:hi,limit:gi}}function bi(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 xi=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],Si=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],Ci=[50,100,250,500];function wi(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Ti(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Ei(){let e=m(),[t,a]=Bt(),[o,s]=l(()=>yi(t)),c=e=>s(t=>({...t,...e})),u=e=>{c({ruleId:e}),a(vi(t,e),{replace:!0})},f=i({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),p=_e({projection:`slim`}),h=Date.now(),g=i({queryKey:[`notificationRules`,`getHistory`,o],retry:!1,queryFn:async()=>{let t=o.windowHours>0?h-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)}:{},...wi(o.status)?{status:wi(o.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),_=r(()=>{let e=new Map;for(let t of p.data??[])t.type===ke.Camera&&e.set(t.id,t.name);return e},[p.data]),v=e=>_.get(e)??`Camera #${String(e)}`,y=g.data??[],b=g.isError;return n(G,{icon:gn,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:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),d(H,{"data-testid":`history-rule-filter`,value:o.ruleId,onChange:e=>u(e.target.value),options:[...bi({rules:f.data??[],answered:f.isSuccess,selected:o.ruleId})]})]}),n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),d(H,{value:o.deviceId,onChange:e=>c({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(p.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),d(H,{value:o.status,onChange:e=>c({status:e.target.value}),options:Si.map(e=>({value:e.value,label:e.label}))})]}),n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),d(H,{value:String(o.windowHours),onChange:e=>c({windowHours:Number(e.target.value)}),options:xi.map(e=>({value:String(e.value),label:e.label}))})]}),n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),d(H,{value:String(o.limit),onChange:e=>c({limit:Number(e.target.value)}),options:Ci.map(e=>({value:String(e),label:String(e)}))})]})]}),g.isLoading&&d(`div`,{className:`flex items-center justify-center py-16`,children:d(V,{className:`h-6 w-6 animate-spin text-primary`})}),b&&!g.isLoading&&d(B,{children:n(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[d(gn,{className:`h-6 w-6 text-foreground-subtle`}),d(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),d(`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 g.refetch(),className:`mt-1 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:[d(T,{className:`h-3 w-3`}),` Retry`]})]})}),!b&&!g.isLoading&&y.length===0&&d(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!b&&y.length>0&&d(B,{children:d(ge,{columns:Di(v),rows:y,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})})]})}function Di(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>d(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`Subject`,render:e=>n(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.subject.label??e.subject.className,e.subject.confidence===void 0?``:` · ${Math.round(e.subject.confidence*100)}%`]})},{key:`status`,header:`Status`,nowrap:!0,render:e=>n(`span`,{className:`flex items-center gap-1.5`,children:[d(U,{variant:Ti(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?d(`span`,{className:`text-[11px] text-danger`,children:e.error}):d(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var Oi=/\{\{\s*(\w+)\s*\}\}/g,ki=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function Ai(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 ji(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function Mi(e){return[...e.matchAll(Oi)].map(e=>e[1]??``).filter(e=>e.length>0)}function Ni(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function Pi(e,t){return[...new Set(Mi(e))].filter(e=>!Ni(e,t))}var Fi={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function Ii(e){return e.map(e=>{let t=Ye.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)||At.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function Li(e){let t=new Set(e.map(e=>e.name)),n=Ye.filter(e=>je(e)&&!t.has(e.name));return[...e,...n]}function Ri(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=Fi[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)||!Xe(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:Ne(e,t)&&kt(e,t))}function zi(e){return ki.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var Bi=[`nc`,`template-catalog`],Vi=400;function Hi(){let e=m();return i({queryKey:Bi,staleTime:5*6e4,queryFn:async()=>Li(Ii((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function Ui(e,t,n){let r=m(),a=N(t.title??``,Vi),o=N(t.body??``,Vi);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 Wi={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},Gi=`block text-[11px] font-medium text-foreground mb-1`,Ki=`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 qi({label:t,value:r,onChange:i,vars:a,multiline:o=!1,placeholder:s,disabled:c=!1,testId:l}){let u=e(null),f=e(null),p=a?Pi(r,a):[],m=e=>{let t=o?f.current:u.current,n={start:t?.selectionStart??r.length,end:t?.selectionEnd??r.length},a=ji(e),s=Ai(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:[d(`label`,{className:Gi,children:t}),o?d(`textarea`,{ref:f,value:r,rows:2,disabled:c,placeholder:s,onChange:h,className:Ki,"data-testid":`${l}-input`}):d(y,{ref:u,value:r,disabled:c,placeholder:s,onChange:h,"data-testid":`${l}-input`}),a&&a.length===0?d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`No variables for this field.`}):null,a&&a.length>0?d(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:zi(a).map(e=>n(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${l}-group-${e.group}`,children:[d(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:Wi[e.group]}),e.vars.map(e=>d(`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:[d(me,{className:`h-3 w-3`}),p.map(e=>`{{${e}}}`).join(` `),` will be empty in this notification.`]}):null]})}function Ji({context:e,title:t,body:r,testId:i}){let a=Ui(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:[d(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:`Preview (example values)`}),a.data.title===null?null:d(`p`,{className:`font-medium`,children:a.data.title}),a.data.body===null?null:d(`p`,{className:`whitespace-pre-wrap`,children:a.data.body})]}):null}function Yi(e){let t=[],n=e.find(e=>e.type===ke.AlarmPanel);n!==void 0&&t.push({id:`trigger-alarm`,label:`Trigger the alarm`,hint:`Presses ${n.name}. The panel's entry delay still runs, and a disarm during it cancels the alarm.`,build:()=>({name:`trigger the alarm`,enabled:!0,actions:[{kind:`cap`,deviceId:n.id,cap:`alarm-panel`,method:`trigger`,args:{}}]})});for(let n of e.filter(e=>e.type===ke.Siren))t.push({id:`siren-${String(n.id)}`,label:`Sound ${n.name}`,hint:`On, 30 seconds, off. A siren left on by a failed step is the one this sequence exists to avoid.`,build:()=>({name:`sound ${n.name}`.toLowerCase(),enabled:!0,minDelaySec:60,actions:[{kind:`cap`,deviceId:n.id,cap:`switch`,method:`setState`,args:{on:!0}},{kind:`wait`,seconds:30},{kind:`cap`,deviceId:n.id,cap:`switch`,method:`setState`,args:{on:!1}}]})});return t}function Xi(e,t){let n=t.build(),r=new Set(e.sequences.map(e=>e.name.trim())),i=n.name;for(let e=2;r.has(i);e+=1)i=`${n.name} ${String(e)}`;return{...e,sequences:[...e.sequences,{...n,name:i}]}}var Zi=[{value:`acknowledge`,label:`Acknowledge`},{value:`dismiss`,label:`Dismiss`},{value:`silence`,label:`Silence`},{value:`snooze`,label:`Snooze`},{value:`view`,label:`View`},{value:`play`,label:`Play`},{value:`camera`,label:`Camera`},{value:`open`,label:`Open`},{value:`close`,label:`Close`},{value:`unlock`,label:`Unlock`},{value:`lock`,label:`Lock`},{value:`disarm`,label:`Disarm`},{value:`arm`,label:`Arm`},{value:`arm-home`,label:`Arm — home`},{value:`arm-away`,label:`Arm — away`},{value:`arm-night`,label:`Arm — night`},{value:`light`,label:`Light`},{value:`alert`,label:`Alert`}],Qi={sequences:[],buttons:[]};function $i(e){return e===void 0?Qi:{sequences:[...e.onTrigger??[]],buttons:[...e.buttons??[]]}}function ea(e){let t=e.sequences.filter(e=>e.name.trim()!==``),n=e.buttons.filter(e=>e.id.trim()!==``&&e.label.trim()!==``);if(!(t.length===0&&n.length===0))return{...t.length>0?{onTrigger:t}:{},...n.length>0?{buttons:n}:{}}}function ta(e){let t=[],n=new Set;for(let r of e.sequences){let e=r.name.trim();e!==``&&(n.has(e)&&t.push({kind:`duplicate-sequence`,message:`Two sequences are called "${e}". The name is how a button points at one, and how its throttle is keyed.`}),n.add(e),r.actions.length===0&&t.push({kind:`empty-sequence`,message:`"${e}" has no steps, so it would do nothing.`}))}let r=new Set;for(let i of e.buttons){let e=i.id.trim();e!==``&&(r.has(e)&&t.push({kind:`duplicate-button`,message:`Two buttons share the id "${e}". The id is what the audit line names when one is tapped.`}),r.add(e),n.has(i.sequence.trim())||t.push({kind:`unknown-sequence`,message:`"${i.label||e}" points at the sequence "${i.sequence}", which this rule does not have. It would never appear on a notification.`}))}return t}function na(e){return{name:`sequence ${String(e+1)}`,enabled:!1,actions:[]}}function ra(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequence:t}}function ia(){return{kind:`wait`,seconds:5}}var aa=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,oa=`block text-[11px] font-medium text-foreground`;function sa({title:e,description:t,children:r}){return n(`div`,{className:`flex flex-col gap-2`,children:[n(`div`,{children:[d(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:t})]}),d(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function ca({value:e,onChange:t,devices:r,devicesState:i}){let a=ta(e),o=Yi(r),s=(n,r)=>t({...e,sequences:e.sequences.map((e,t)=>t===n?r:e)}),c=(n,r)=>t({...e,buttons:e.buttons.map((e,t)=>t===n?r:e)});return n(`div`,{className:`space-y-4`,children:[a.length>0&&d(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:a.map(e=>d(`p`,{children:e.message},e.message))}),n(`section`,{className:`space-y-2`,children:[n(sa,{title:`What this rule does`,description:`Runs when the rule matches. A sequence stops at the first failed step, and its own delay limits how often it may physically run — separate from the notification cooldown.`,children:[o.map(r=>n(z,{size:`sm`,variant:`ghost`,type:`button`,title:r.hint,className:`min-w-0 max-w-full`,onClick:()=>t(Xi(e,r)),children:[d(ne,{className:`h-3.5 w-3.5 shrink-0`}),d(`span`,{className:`truncate`,children:r.label})]},r.id)),n(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t({...e,sequences:[...e.sequences,na(e.sequences.length)]}),children:[d(w,{className:`h-3.5 w-3.5 shrink-0`}),` Sequence`]})]}),e.sequences.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`This rule actuates nothing — it only notifies.`}):e.sequences.map((n,a)=>d(la,{sequence:n,devices:r,devicesState:i,onChange:e=>s(a,e),onRemove:()=>t({...e,sequences:e.sequences.filter((e,t)=>t!==a)})},`seq-${String(a)}`))]}),n(`section`,{className:`space-y-2`,children:[d(sa,{title:`Buttons on the notification`,description:`Each button runs one of the sequences above when tapped.`,children:n(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:e.sequences.length===0,onClick:()=>t({...e,buttons:[...e.buttons,ra(e.buttons.length,e.sequences[0]?.name??``)]}),children:[d(w,{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:[d(me,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),n(`span`,{children:[`A button's link travels inside the notification — through ntfy, a push relay, anyone it is forwarded to. The link is the only authority: it does not check who taps it. Anyone holding the notification can run the button `,d(`strong`,{children:`once`}),`, within 15 minutes. Do not add one for something you would not want a forwarded screenshot to do.`]})]}),e.sequences.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Add a sequence first — a button runs one, it does not define its own steps.`}):e.buttons.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No buttons. The notification arrives with nothing to tap.`}):e.buttons.map((n,r)=>d(fa,{button:n,sequenceNames:e.sequences.map(e=>e.name),onChange:e=>c(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function la({sequence:e,devices:t,devicesState:r,onChange:i,onRemove:a}){let o=(t,n)=>i({...e,actions:e.actions.map((e,r)=>r===t?n:e)});return n(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:[n(`div`,{className:`flex flex-wrap items-end gap-2`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:oa,children:`Name`}),d(y,{className:`mt-1`,value:e.name,onChange:t=>i({...e,name:t.target.value})})]}),n(`div`,{className:`w-28`,children:[d(`label`,{className:oa,children:`Min delay (s)`}),d(`input`,{type:`number`,min:0,className:aa,value:e.minDelaySec??``,onChange:t=>{let n=t.target.value,r={...e};n===``?delete r.minDelaySec:r.minDelaySec=Number(n),i(r)}})]}),n(`div`,{className:`flex items-center gap-2 pb-1`,children:[d(P,{checked:e.enabled,onCheckedChange:t=>i({...e,enabled:t})}),d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.enabled?`Runs on match`:`Only when a button is tapped`})]}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,title:`Remove`,children:d(g,{className:`h-3.5 w-3.5`})})]}),n(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[e.actions.map((n,a)=>d(ua,{step:n,devices:t,devicesState:r,onChange:e=>o(a,e),onRemove:()=>i({...e,actions:e.actions.filter((e,t)=>t!==a)})},`step-${String(a)}`)),n(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i({...e,actions:[...e.actions,ia()]}),children:[d(w,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function ua({step:e,devices:t,devicesState:r,onChange:i,onRemove:a}){return n(`div`,{className:`flex flex-wrap items-end gap-2`,children:[n(`div`,{className:`w-24`,children:[d(`label`,{className:oa,children:`Step`}),n(`select`,{className:aa,value:e.kind,onChange:e=>i(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[d(`option`,{value:`cap`,children:`Do`}),d(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?n(`div`,{className:`w-28`,children:[d(`label`,{className:oa,children:`Seconds`}),d(`input`,{type:`number`,min:0,max:300,className:aa,value:e.seconds,onChange:e=>i({kind:`wait`,seconds:Number(e.target.value)})})]}):d(da,{step:e,devices:t,devicesState:r,onChange:i}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,title:`Remove step`,children:d(g,{className:`h-3.5 w-3.5`})})]})}function da({step:e,devices:t,devicesState:r,onChange:o}){let s=m(),c=i({queryKey:[`deviceManager`,`getBindings`,e.deviceId],enabled:e.deviceId>0,staleTime:6e4,queryFn:async()=>{let t=await s.trpcClient.deviceManager.getBindings.query({deviceId:e.deviceId});return[...new Set(t.entries.map(e=>e.capName))].sort((e,t)=>e.localeCompare(t))}}).data??[],l=e.deviceId>0?Xn([e.deviceId],t,r).find(e=>e.removed||e.name===void 0):void 0;return n(a,{children:[n(`div`,{className:`min-w-[9rem] flex-1`,children:[d(`label`,{className:oa,children:`Device`}),n(`select`,{className:l?.removed===!0?`${aa} border-warning text-warning`:aa,value:String(e.deviceId),onChange:t=>o({...e,deviceId:Number(t.target.value),cap:``}),children:[d(`option`,{value:`0`,children:`Select…`}),l!==void 0&&d(`option`,{value:String(l.id),className:l.removed?`text-warning`:void 0,children:tr(l)}),t.map(e=>d(`option`,{value:String(e.id),children:e.name},e.id))]})]}),n(`div`,{className:`min-w-[8rem] flex-1`,children:[d(`label`,{className:oa,children:`Capability`}),n(`select`,{className:aa,value:e.cap,disabled:c.length===0,onChange:t=>o({...e,cap:t.target.value,method:``}),children:[d(`option`,{value:``,children:c.length===0?`No devices bound`:`Select…`}),c.map(e=>d(`option`,{value:e,children:e},e))]})]}),n(`div`,{className:`min-w-[7rem] flex-1`,children:[d(`label`,{className:oa,children:`Method`}),d(y,{className:`mt-1`,value:e.method,placeholder:`arm`,onChange:t=>o({...e,method:t.target.value})})]}),n(`div`,{className:`min-w-[8rem] flex-1`,children:[d(`label`,{className:oa,children:`Arguments (JSON)`}),d(y,{className:`mt-1`,value:e.args===void 0?``:JSON.stringify(e.args),placeholder:`{"mode":"away"}`,onChange:t=>{let n=t.target.value.trim();if(n===``){let t={...e};delete t.args,o(t);return}try{let t=JSON.parse(n);typeof t==`object`&&t&&!Array.isArray(t)&&o({...e,args:t})}catch{}}})]})]})}function fa({button:e,sequenceNames: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:`min-w-[7rem] flex-1`,children:[d(`label`,{className:oa,children:`Label`}),d(y,{className:`mt-1`,value:e.label,onChange:t=>r({...e,label:t.target.value})})]}),n(`div`,{className:`min-w-[8rem] flex-1`,children:[d(`label`,{className:oa,children:`Runs`}),n(`select`,{className:aa,value:e.sequence,onChange:t=>r({...e,sequence:t.target.value}),children:[!t.includes(e.sequence)&&n(`option`,{value:e.sequence,children:[e.sequence,` (missing)`]}),t.map(e=>d(`option`,{value:e,children:e},e))]})]}),n(`div`,{className:`w-32`,children:[d(`label`,{className:oa,children:`Icon`}),n(`select`,{className:aa,value:e.icon??``,onChange:t=>{let n={...e};if(t.target.value===``)delete n.icon;else{let e=Zi.find(e=>e.value===t.target.value);e!==void 0&&(n.icon=e.value)}r(n)},children:[d(`option`,{value:``,children:`None`}),Zi.map(e=>d(`option`,{value:e.value,children:e.label},e.value))]})]}),n(`div`,{className:`flex items-center gap-2 pb-1`,children:[d(P,{checked:e.destructive===!0,onCheckedChange:t=>{let n={...e};t?n.destructive=!0:delete n.destructive,r(n)}}),d(U,{variant:e.destructive===!0?`danger`:`default`,children:`Destructive style`})]}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:d(g,{className:`h-3.5 w-3.5`})})]})}function K(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var pa=K({devices:!0}),ma=K({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),ha=K({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),ga=K({minDwellSeconds:!0}),_a=K({source:!0}),va=K({crossing:!0}),ya=K({packagePhase:!0}),ba=K({sensorTransition:!0}),xa=K({plates:!0}),Sa=K({occupancy:!0}),Ca=K({audio:!0}),wa=K({systemEvent:!0}),Ta=K({deviceState:!0}),Ea=K({scene:!0});function Da(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Oa(e,t){let n=e[t];return typeof n==`number`?n:void 0}t();function ka(e){switch(e.kind){case`zone`:case`location`:return e.label;case`no-zone`:return`No zone`;case`no-location`:return`No location`}}function Aa(e){return e.heading===void 0?`${Dr(e.type)} · ${e.location??`No room`}`:ka(e.heading)}function ja(e){return e===`camera`||e===`device`}function Ma(e,t,n,r){let i=new Map(t.map(e=>[e.id,e.name])),a=new Map(Zn(e,t,n.devices,n.state).map(e=>[e.id,e]));return e.map(e=>{let t=i.get(e);if(t!==void 0)return{id:e,label:t,removed:!1};let n=a.get(e)??{id:e,removed:!1};return{id:e,label:tr(n,r),removed:n.removed}})}function Na(e,t){let n=er[e];return t?e===`camera`||e===`device`?`No cameras available — the rule applies to all devices.`:`No ${n} available — the rule applies to every ${e}.`:`No ${n} available.`}function Pa({devices:e,listState:t,fleet:r,value:i,onChange:a,emptyMeansAll:o=!1,savedHadDevices:s=!1,noun:c=`camera`,groupTitle:u=Aa,emptyLabel:f,annotate:p,disabled:m=!1,testId:h,showAll:g=!1}){let _=r??{state:t,devices:t===`answered`?e:void 0},[v,y]=l(!1),[b,x]=l(!1),[S,C]=l(s||i.length>0);i.length>0&&!S&&C(!0);let w=Ma(i,e,_,c),T=rn(w,b||g),E=v||g,D=$n(o,i.length,S),O=er[c];return t===`answered`&&Qn(t,e.length,i.length)?n(`div`,{"data-testid":h,children:[d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Na(c,o)}),D&&d(nr,{noun:c})]}):n(`div`,{className:`mt-1 space-y-1.5`,"data-testid":h,children:[t===`pending`&&d(rr,{noun:O}),t===`failed`&&d(ir,{noun:c===`camera`?`devices`:O}),n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[w.length===0?d(`span`,{className:`text-[11px] text-foreground-subtle`,children:f??(o?`Every ${c} — no restriction`:`None selected`)}):T.shown.map(e=>d(pn,{testId:`picker-chip-${String(e.id)}`,label:e.label,warning:e.removed,...m?{}:{onRemove:()=>a(i.filter(t=>t!==e.id))}},e.id)),T.hidden>0&&n(`button`,{type:`button`,className:`rounded-md border border-border px-1.5 py-0.5 text-[11px] text-foreground-subtle hover:bg-surface-hover`,onClick:()=>x(!0),children:[`+`,T.hidden,` more`]}),b&&w.length>6&&d(`button`,{type:`button`,className:`text-[11px] text-foreground-subtle underline`,onClick:()=>x(!1),children:`Show fewer`}),t!==`pending`&&!g&&d(`button`,{type:`button`,disabled:m,"aria-expanded":v,onClick:()=>y(e=>!e),className:`rounded-md border border-dashed border-border px-1.5 py-0.5 text-[11px] text-foreground hover:bg-surface-hover disabled:opacity-50`,children:v?`Done`:i.length===0?`Add ${O}…`:`Edit…`})]}),E&&t===`answered`&&(ja(c)?d(Fa,{devices:e,value:i,onChange:a,annotate:p,groupTitle:u,noun:c,disabled:m,showAll:g}):d(Ra,{devices:e,value:i,onChange:a,annotate:p,groupTitle:u,noun:c,disabled:m,showAll:g})),D&&d(nr,{noun:c})]})}function Fa(e){let{groupBy:t,setGroupBy:n}=ei(),r=ti(!0);return d(Ra,{...e,grouping:{groupBy:t,onGroupByChange:n,zones:r}})}function Ia(e){return e===`camera`||e===`device`?`Search by name, room or type…`:e===`class`?`Search by class or category…`:e===`zone`?`Search by camera or zone…`:`Search by name or id…`}var La={state:`answered`,zones:[]};function Ra({devices:e,value:t,onChange:i,annotate:a,groupTitle:o,noun:s,disabled:c,showAll:u,grouping:f}){let[p,m]=l($t),[h,g]=l(new Map),[_,v]=l(60),y=u||dn(p.query).length>0,b=f?.groupBy,x=f?.zones??La,S=r(()=>Kt(e,p,x),[e,p,x]),C=r(()=>b===void 0?null:Yt(S,t,b,x),[S,t,b,x]),w=r(()=>C===null?en(cn(S,t),t,h,y):Jt(C,t,h,y),[C,S,t,h,y]),T=C?.groupBy??null,E=r(()=>Qt(e,`type`,p.types,x),[e,p.types,x]),D=r(()=>Qt(e,`zone`,p.zones,x),[e,p.zones,x]),O=r(()=>f===void 0?[]:Qt(e,`location`,p.locations,x),[e,p.locations,x,f]),k=r(()=>Gt(t,e,S),[e,t,S]),A=Xt(w,u?w.length:_),j=(e,t)=>g(n=>new Map([...n,[e.key,!t]]));return n(`div`,{className:`rounded-md border border-border bg-surface p-2`,"data-testid":`device-picker-panel`,children:[d(Fr,{filters:p,onFiltersChange:e=>{m(e),v(60)},typeOptions:E,zoneOptions:D,locationOptions:O,zones:x,...f===void 0?{}:{grouping:{groupBy:f.groupBy,onGroupByChange:f.onGroupByChange,fallback:C?.fallback??null}},searchPlaceholder:Ia(s),searchLabel:s===`camera`||s===`device`?`Search devices`:`Search ${er[s]}`,disabled:c}),n(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:[S.length,` of `,e.length,` shown · `,t.length,` selected`]}),w.length===0?d(`p`,{className:`py-2 text-[11px] text-foreground-subtle italic`,children:s===`camera`||s===`device`?`No device matches.`:`No ${s} matches.`}):n(`div`,{className:u?`mt-1`:`mt-1 max-h-72 overflow-y-auto`,"data-testid":`device-picker-rows`,children:[A.rows.map(e=>d(Ba,{row:e,value:t,onChange:i,onToggleGroup:j,annotate:a,groupTitle:o,groupBy:T,disabled:c},e.key)),A.remaining>0&&n(`button`,{type:`button`,className:`mt-1 w-full rounded border border-border py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover`,onClick:()=>v(e=>e+60),children:[`Show `,Math.min(A.remaining,60),` more (`,A.remaining,` left)`]})]}),k>0&&n(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`picker-hidden-selected`,children:[k,` selected hidden by filters`]})]})}function za(e,t){if(t===null)return e.detail;let n=qt(e,t),r=[n.location,n.type===null?null:Dr(n.type),e.detail??null].filter(e=>e!==null);return r.length>0?r.join(` · `):void 0}function Ba({row:e,value:t,onChange:r,onToggleGroup:i,annotate:a,groupTitle:o,groupBy:s,disabled:c}){if(e.kind===`header`){let{group:a,expanded:s}=e;return n(`div`,{className:`flex items-center gap-2 border-b border-border px-1 py-1`,"data-testid":`device-picker-group`,children:[n(`button`,{type:`button`,"aria-expanded":s,onClick:()=>i(a,s),className:`flex min-w-0 flex-1 items-center gap-1 text-left text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:[d(`span`,{children:s?`▾`:`▸`}),d(`span`,{className:`truncate`,children:o(a)}),n(`span`,{className:`font-normal normal-case`,children:[`(`,a.selectedCount,`/`,a.devices.length,`)`]})]}),d(`button`,{type:`button`,disabled:c,className:`text-[10px] text-primary hover:underline disabled:opacity-50`,onClick:()=>r(un(t,a)),children:`All`}),d(`button`,{type:`button`,disabled:c,className:`text-[10px] text-foreground-subtle hover:underline disabled:opacity-50`,onClick:()=>r(on(t,a)),children:`Clear`})]})}let l=a?.(e.device.id),u=za(e.device,s);return n(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1 text-xs text-foreground hover:bg-surface-hover`,"data-testid":`device-picker-row`,children:[d(`input`,{type:`checkbox`,checked:e.selected,disabled:c,onChange:()=>r(Wt(t,e.device.id)),className:`accent-primary`,"data-device-id":String(e.device.id)}),n(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[d(`span`,{className:`truncate`,children:e.device.name}),u!==void 0&&d(`span`,{className:`truncate text-[10px] text-foreground-subtle`,children:u}),l!==void 0&&d(`span`,{className:`text-[10px] text-warning`,children:l})]})]})}t();function Va(e,t){let n=m().trpcClient,i=o({queries:e.map(e=>({queryKey:[[`nc-pickers`,`zones`],{deviceId:e}],staleTime:3e4,queryFn:async()=>({deviceId:e,zones:(await n.zones.listZones.query({deviceId:e})).map(e=>({id:e.id,name:e.name}))})}))});return r(()=>{let e=[],n=new Set;for(let r of i){if(!r.data)continue;let i=t.find(e=>e.id===r.data.deviceId)?.name;for(let t of r.data.zones)n.has(t.id)||(n.add(t.id),e.push({value:t.id,label:t.name,...i===void 0?{}:{hint:i}}))}return{options:e,loading:i.some(e=>e.isLoading),failed:i.some(e=>e.isError)}},[i,t])}function Ha(e){let t=m().trpcClient,n=o({queries:e.map(e=>({queryKey:[[`nc-pickers`,`event-kinds`],{deviceId:e}],staleTime:6e4,queryFn:async()=>(await t.pipelineAnalytics.listEventKinds.query({deviceId:e})).map(e=>({kind:e.kind,label:e.label}))}))});return r(()=>{let e=new Map;for(let t of n)for(let n of t.data??[])e.has(n.kind)||e.set(n.kind,n.label);let t=[...e.entries()].map(([e,t])=>({value:e,label:t}));return t.sort((e,t)=>e.label.localeCompare(t.label)),{options:t,loading:n.some(e=>e.isLoading)}},[n])}function Ua(){let e=v();return r(()=>({options:(e.data??[]).map(e=>({value:e.id,label:e.name})),loading:e.isLoading,failed:e.isError===!0}),[e.data,e.isLoading,e.isError])}function Wa(){let e=fe({limit:200}),t=se();return r(()=>{let n=new Set;for(let e of t.data??[])e.name.trim().length>0&&n.add(e.name);let r=new Set;for(let t of e.data??[])t.text.trim().length>0&&r.add(t.text);return[...[...n].sort(),...[...r].sort()]},[e.data,t.data])}function Ga({options:e,value:t,onChange:i,loading:a,emptyHint:o,placeholder:s,noFreeText:c=!1}){let[u,f]=l(``),p=r(()=>new Set(e.map(e=>e.value)),[e]),m=r(()=>new Set(t),[t]),h=t.filter(e=>!p.has(e)),g=e=>{i(m.has(e)?t.filter(t=>t!==e):[...t,e])},_=()=>{let e=u.trim();e.length===0||t.includes(e)||(i([...t,e]),f(``))};return n(`div`,{className:`mt-1 space-y-1.5`,children:[h.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,children:h.map(e=>n(`button`,{type:`button`,onClick:()=>i(t.filter(t=>t!==e)),className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,title:`Custom value — click to remove`,children:[e,` ×`]},e))}),e.length>0?d(`div`,{className:`max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>n(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[d(`input`,{type:`checkbox`,checked:m.has(e.value),onChange:()=>g(e.value),className:`accent-primary`}),d(`span`,{className:`flex-1 truncate`,children:e.label}),e.hint!==void 0&&d(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.hint})]},e.value))}):d(`p`,{className:`text-[10px] text-foreground-subtle`,children:a===!0?`Loading…`:o}),!c&&d(`input`,{value:u,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),_())},placeholder:s,className:`w-full rounded-md border border-border bg-background px-2 py-1 text-xs text-foreground placeholder:text-foreground-subtle`})]})}var Ka=[{value:`immediate`,label:`Immediate`,hint:`Fires on the first matching detection of a track (lowest latency).`},{value:`track-end`,label:`Track end`,hint:`Evaluates the finalised track record when it closes.`},{value:`device-event`,label:`Device event`,hint:`Doorbell press, sensor state change, or an occupancy edge on a linked device.`},{value:`package-event`,label:`Package event`,hint:`A parcel delivery or pick-up.`},{value:`system-event`,label:`System event`,hint:`The installation itself: a camera or stream going offline, a node leaving the cluster, an addon or server update becoming available.`}];function qa(e){return Ka.find(t=>t.value===e)?.label??e}function Ja(e){return Ka.find(t=>t.value===e)?.value}function Ya(e){return Ka.some(t=>t.value===e)}var Xa=[{key:`all`,label:`All rules`,blurb:`Every notification rule, whatever its trigger. Each rule picks a trigger, matches conditions and fans out to one or more delivery targets.`,newRuleLabel:`New rule`,emptyHint:`No notification rules yet. Click "New rule" to author one.`,creatable:!0},{key:`detection`,label:`Detections`,blurb:`Rules driven by what the cameras SEE — detections, tracks and package events. Doorbell presses and other sensor changes have their own section now (operator ruling, 2026-10-01).`,newRuleLabel:`New detection rule`,emptyHint:`No detection rules yet. Click "New detection rule" to author one.`,creatable:!0},{key:`sensor`,label:`Sensors`,blurb:`Rules driven by a device or sensor CHANGING STATE — a doorbell press, a linked sensor opening or closing. The picture is one snapshot of the camera the sensor is attributed to; there is no media choice to make.`,newRuleLabel:`New sensor rule`,emptyHint:`No sensor rules yet. Click "New sensor rule" to be told when a doorbell is pressed or a linked sensor changes.`,creatable:!0},{key:`audio`,label:`Sound`,blurb:`Rules on what the cameras HEAR: a sustained window of sound loud enough, or classified as one of the sounds you name. A sound rule is an immediate rule carrying the sound condition — it fires only on a confirmed sampling window, never on a picture.`,newRuleLabel:`New sound rule`,emptyHint:`No sound rules yet. Click "New sound rule" — it opens on the sound condition already filled in with a level threshold, so you only have to name the sounds and the targets.`,creatable:!0},{key:`occupancy`,label:`Occupancy`,blurb:`Rules on how many objects are in a camera frame or a zone, and for how long: "the driveway became occupied", "the garden emptied". An occupancy rule is a device-event rule carrying the occupancy condition.`,newRuleLabel:`New occupancy rule`,emptyHint:`No occupancy rules yet. Click "New occupancy rule" — it opens on the occupancy condition; pick the camera on the Devices tab, then the zone and the count.`,creatable:!0},{key:`device-events`,label:`Device events`,blurb:`Rules about your devices: offline or back, switched off or on, a stream dropping, a battery or consumable running low, a camera detecting nothing. These carry no image.`,newRuleLabel:`New device-event rule`,emptyHint:`No device-event rules yet. Click "New device-event rule" to be told when a device drops, a battery runs low or a camera goes blind.`,creatable:!0},{key:`system`,label:`System events`,blurb:`Rules about the installation itself: a node leaving the cluster, an addon crash-looping, an update available or installed, a backup or export finishing. These carry no image and are not tied to a detection.`,newRuleLabel:`New system rule`,emptyHint:`No system rules yet. Click "New system rule" to be told when a node leaves, an update lands or a backup finishes.`,creatable:!0},{key:`alarm`,label:`Alarm`,blurb:`Rules about the alarm panel: arming, armed, triggered, disarmed, and the refusals in between.`,newRuleLabel:`New alarm rule`,emptyHint:`No alarm rules yet. Click "New alarm rule" to be told when the alarm arms, goes off or is disarmed.`,creatable:!0},{key:`mixed`,label:`To recreate`,blurb:`System rules authored before the three families existed. Each mixes families and keeps firing as it is, but it cannot be edited: recreate it as one rule per family (Device events, System events, Alarm). Open none of them: Delete each once its replacements exist.`,newRuleLabel:`New rule`,emptyHint:`Nothing to recreate.`,creatable:!1}];function Za(e){return Xa.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0)}function Qa(e){return Qe(Ae(e)).editable}function $a(e){return Ve(eo(e))}function eo(e){switch(e){case`device-events`:case`system`:case`alarm`:case`mixed`:return e;default:return}}var to=new Map([[0,`No cooldown`],[60,`1 minute`],[3600,`1 hour`]]),no=86400;function ro(e){let t=to.get(e);return t===void 0?e%3600==0?`${e/3600} hours`:e%60==0?`${e/60} minutes`:`${e} seconds`:t}function io(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)&&t>=0?Math.trunc(t):void 0}var ao=[{value:`rule-device`,label:`Per device`},{value:`rule`,label:`Whole rule (one window for every device)`}];function oo(e){return ao.find(t=>t.value===e)?.value}var so=[{value:`per-class`,label:`Separate windows per class (default)`},{value:`shared`,label:`Shared across classes`}];function co(e){return so.find(t=>t.value===e)?.value}var lo=[{value:`best`,label:`Best available image`,description:`The best subject crop available when the notification is sent.`},{value:`best-matching`,label:`Best matching image`,description:`The image that explains why the rule fired — the face crop for an identity rule, the plate crop for a plate rule; falls back to the best image otherwise.`},{value:`keyFrame`,label:`Key frame`,description:`The clean full scene frame with no subject box.`},{value:`none`,label:`No attachment`,description:`Send the notification with no image.`}];function uo(e){return lo.find(t=>t.value===e)?.value}var fo=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function po(e){let t=fo.find(t=>t.value===e)?.value;return t===``?void 0:t}var mo=[{value:``,label:`Mosaic of every linked camera (default)`},{value:`mosaic`,label:`Mosaic of every linked camera`},{value:`each`,label:`One image per camera (first camera where only one is allowed)`}];function ho(e){let t=mo.find(t=>t.value===e)?.value;return t===``?void 0:t}var go=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function _o(e){let t=go.find(t=>t.value===e)?.value;return t===``?void 0:t}var vo=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],yo=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],bo=[{value:``,label:`It triggers and when it clears`},{value:`raised`,label:`Only when it triggers`},{value:`cleared`,label:`Only when it clears`}];function xo(e){return e===`raised`||e===`cleared`?e:void 0}function So(e,t){return e===`sensorTransition`?We(t.sensorKinds):!0}var Co=[{value:`enter`,label:`Entering`},{value:`exit`,label:`Leaving`},{value:`any`,label:`Entering or leaving`}],wo=`enter`;function To(e){return e===`exit`||e===`any`?e:void 0}var Eo=[{value:1,label:`1 — Min`},{value:2,label:`2 — Low`},{value:3,label:`3 — Default`},{value:4,label:`4 — High`},{value:5,label:`5 — Max`}];function Do(e,t){return e.options&&e.options.length>0?e.options:t}var Oo=[{value:``,label:`Default (2×)`},{value:`1`,label:`1× — real time`},{value:`2`,label:`2×`},{value:`3`,label:`3×`},{value:`4`,label:`4×`},{value:`6`,label:`6×`},{value:`8`,label:`8×`}];function ko(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var Ao=new Map(Object.entries({"device-offline":`Device offline`,"device-online":`Device online`,"device-disabled":`Device switched off`,"device-enabled":`Device switched on`,"stream-offline":`Stream offline`,"stream-online":`Stream online`,"device-battery-low":`Battery low`,"device-battery-normal":`Battery back to normal`,"device-consumable-low":`Consumable low`,"device-consumable-normal":`Consumable back to normal`,"device-tank-low":`Tank low (water, detergent)`,"device-tank-full":`Tank full (dirty water, dust)`,"device-tank-normal":`Tank back to normal`,"detection-blind":`Camera detecting nothing`,"node-offline":`Node offline`,"node-online":`Node online`,"node-inference-unavailable":`Node has no usable inference device`,"addon-crash-loop":`Addon stopped after repeated crashes`,"addon-update-available":`Addon update available`,"addon-updated":`Addons updated`,"server-update-available":`Server update available`,"server-updated":`Server updated`,"wrapper-update-available":`Container / app update available`,"export-completed":`Export completed`,"backup-completed":`Backup completed`,"alarm-arm-refused":`Alarm arm refused (something is open)`,"alarm-check-failed":`Alarm check failed (armed anyway)`,"alarm-arming":`Alarm arming (exit delay)`,"alarm-armed":`Alarm armed`,"alarm-pending":`Alarm entry delay started`,"alarm-triggered":`Alarm triggered`,"alarm-rearmed":`Alarm re-armed after siren`,"alarm-sensor-bypass":`Alarm sensor bypass`,"alarm-disarmed":`Alarm disarmed`}));function jo(e){return Ao.get(e)}var Mo={"device-state":`A device the hub can no longer reach, or that came back. Switched off / on is a device an operator turned off or back on — not a fault, a choice.`,streams:`A stream that stopped or came back.`,battery:`A battery below the cluster threshold, and (optionally) its return to normal. Devices with a binary low-battery indicator are judged by the indicator, not by the percentage.`,consumables:`A consumable — filter, brush, bag — at or below this rule’s threshold, or that the device reports as due for replacement, and (optionally) its return to normal after a change. A device that only says "replace" is judged by that, not by a percentage.`,tanks:`A robot vacuum tank the device reports as running low (clean water, detergent) or full (dirty water, dust bin), and (optionally) its return to normal once refilled or emptied.`,"detection-blind":`A camera that is running and being analysed, but detects nothing — up, and producing no work.`,nodes:`An agent or worker node joining or leaving the cluster, or an online node whose inference devices all went away.`,addons:`An addon the hub has stopped restarting after repeated crashes, a newer version of an addon, or an addon update that just finished.`,updates:`A newer version of the server itself, or of the container / app the node runs inside, is available — or a server update just finished.`,"backups-exports":`A scheduled or manual backup of the hub finished, or a footage export finished rendering.`,alarm:`The alarm panel refusing to arm, arming, armed, counting down to a siren, going off, re-arming, excluding an open sensor, or being disarmed.`},No=ze.map(e=>({id:e.id,family:e.family,label:e.label,hint:Mo[e.id]??``,kinds:e.kinds.flatMap(e=>{let t=jo(e);return t===void 0?[]:[{value:e,label:t}]})}));function Po(e){return No.filter(t=>t.family===e)}function Fo(e){let t=Ze(e).conditions.systemEvent;return t===void 0?{kinds:(Po(e)[0]?.kinds??[]).map(e=>e.value)}:{...t,kinds:[...t.kinds]}}var Io=No.flatMap(e=>e.kinds);function Lo(e){return Io.find(t=>t.value===e)?.label??e}function Ro(e){return{devices:et(e,`deviceIds`),deviceTypes:et(e,`deviceTypes`),nodes:et(e,`nodeIds`),packages:et(e,`packageNames`),consumableThreshold:et(e,`consumableLowPercent`)}}function zo(e,t){let n=Ct[e],r=Ro(t);return{devices:n.includes(`deviceIds`)&&r.devices,excludeDevices:n.includes(`excludeDeviceIds`)&&r.devices,deviceTypes:n.includes(`deviceTypes`)&&r.deviceTypes,nodes:n.includes(`nodeIds`)&&r.nodes,packages:n.includes(`packageNames`)&&r.packages,consumableThreshold:n.includes(`consumableLowPercent`)&&r.consumableThreshold}}var Bo=Object.values(ke).map(e=>({value:e,label:Vo(e)})).toSorted((e,t)=>e.label.localeCompare(t.label));function Vo(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Ho(e,t,n){if(!Po(n).some(e=>e.kinds.some(e=>e.value===t)))return e;let r=e?.kinds??[];return r.length===1&&r[0]===t?e:Ko(e,r.includes(t)?r.filter(e=>e!==t):Io.filter(e=>e.value===t||r.includes(e.value)).map(e=>e.value),n)}function Uo(e,t){return t===void 0?void 0:Ko(t,t.kinds,e)}function Wo(e,t){let n=e?.kinds??[];if(n.length===0)return;let r=Go(t,`deviceIds`,e?.deviceIds),i=Go(t,`excludeDeviceIds`,e?.excludeDeviceIds),a=Go(t,`deviceTypes`,e?.deviceTypes),o=Go(t,`nodeIds`,e?.nodeIds),s=Go(t,`packageNames`,e?.packageNames),c=Object.prototype.hasOwnProperty.call(t,`consumableLowPercent`)?t.consumableLowPercent:e?.consumableLowPercent;return{kinds:[...n],...r===void 0?{}:{deviceIds:[...r]},...i===void 0?{}:{excludeDeviceIds:[...i]},...a===void 0?{}:{deviceTypes:[...a]},...o===void 0?{}:{nodeIds:[...o]},...s===void 0?{}:{packageNames:[...s]},...c===void 0?{}:{consumableLowPercent:c}}}function Go(e,t,n){let r=Object.prototype.hasOwnProperty.call(e,t)?e[t]:n;return r!==void 0&&r.length===0?void 0:r}function Ko(e,t,n){let r=zo(n,t),i=r.devices?e?.deviceIds:void 0,a=r.excludeDevices?e?.excludeDeviceIds:void 0,o=r.deviceTypes?e?.deviceTypes:void 0,s=r.nodes?e?.nodeIds:void 0,c=r.packages?e?.packageNames:void 0,l=r.consumableThreshold?e?.consumableLowPercent:void 0;return{kinds:[...t],...i&&i.length>0?{deviceIds:[...i]}:{},...a&&a.length>0?{excludeDeviceIds:[...a]}:{},...o&&o.length>0?{deviceTypes:[...o]}:{},...s&&s.length>0?{nodeIds:[...s]}:{},...c&&c.length>0?{packageNames:[...c]}:{},...l===void 0?{}:{consumableLowPercent:l}}}var qo=95;function Jo(e){let t=e.trim();if(t===``)return{kind:`clear`};let n=Number(t);return Number.isInteger(n)&&n>=1&&n<=qo?{kind:`set`,value:n}:{kind:`invalid`}}function Yo(e,t=2){if(e===void 0||e.length===0)return`No event selected`;let n=e.slice(0,t).map(Lo).join(`, `),r=e.length-Math.min(t,e.length);return r>0?`${n} +${r}`:n}function Xo(e){if(e===void 0)return`—`;let t=[],n=e.deviceIds?.length??0,r=e.deviceTypes?.length??0,i=e.nodeIds?.length??0,a=e.packageNames?.length??0,o=e.excludeDeviceIds?.length??0;r>0&&t.push(e.deviceTypes?.map(Vo).join(`, `)??``),n>0&&t.push(`${n} device${n===1?``:`s`}`),i>0&&t.push(`${i} node${i===1?``:`s`}`),a>0&&t.push(`${a} package${a===1?``:`s`}`);let s=o>0?`except ${o} device${o===1?``:`s`}`:null,c=e.consumableLowPercent===void 0?[]:[`consumables at ${e.consumableLowPercent}%`];return t.length===0?[s===null?`Everything`:`Everything ${s}`,...c].join(` · `):[...t,...s===null?[]:[s],...c].join(` · `)}function Zo(e){return e===void 0||(e.deviceTypes?.length??0)===0?!1:e.kinds.some(e=>it.includes(e))}var Qo=[`all`,`only`,`except`];function $o(e,t){return(e??[]).length>0?`only`:(t??[]).length>0?`except`:`all`}function es(e,t){let n=[...e??[]],r=[...t??[]];return{mode:$o(n,r),include:n,exclude:r,legacyBoth:n.length>0&&r.length>0}}function ts(e,t){return{...e,mode:t}}function ns(e){switch(e.mode){case`only`:return e.include;case`except`:return e.exclude;case`all`:return[]}}function rs(e,t){switch(e.mode){case`only`:return{...e,include:[...t]};case`except`:return{...e,exclude:[...t]};case`all`:return e}}function is(e){return e.mode===`only`&&e.legacyBoth?e.exclude:[]}function as(e){return{...e,exclude:[],legacyBoth:!1}}function os(e){switch(e.mode){case`all`:return{};case`except`:return e.exclude.length>0?{exclude:[...e.exclude]}:{};case`only`:{let t=is(e);return{...e.include.length>0?{include:[...e.include]}:{},...t.length>0?{exclude:[...t]}:{}}}}}function ss(e){let t=os(e),n=t.include??[],r=t.exclude??[];return[...e.include.filter(e=>!n.includes(e)),...e.exclude.filter(e=>!r.includes(e))]}var cs=[10,30,60],ls=[5,10,15,30,60,120,240,480];function us(e){return e>=60&&e%60==0?`${e/60} h`:`${e} min`}var ds=new Set([`alarm-arm-refused`,`alarm-check-failed`,`alarm-arming`,`alarm-armed`,`alarm-pending`,`alarm-triggered`,`alarm-rearmed`,`alarm-sensor-bypass`,`alarm-disarmed`]),fs=`alarm-panel`;function ps(e,t){for(let t of e.systemEvent?.kinds??[])if(ds.has(t))return!0;for(let e of t)for(let t of e.actions)if(t.kind===`cap`&&t.cap===fs)return!0;return!1}function ms(e){let{devices:t,devicesExclude:n,classes:r,classesExclude:i,...a}=e;return{conditions:a,deviceScope:es(t,n),classScope:es(r,i)}}function hs(e){let t=os(e.deviceScope),n=os(e.classScope);return{...e.conditions,...t.include===void 0?{}:{devices:[...t.include]},...t.exclude===void 0?{}:{devicesExclude:[...t.exclude]},...n.include===void 0?{}:{classes:[...n.include]},...n.exclude===void 0?{}:{classesExclude:[...n.exclude]}}}function gs(e){return e.deviceScope.mode===`only`?e.deviceScope.include:[]}function _s(e,t,n){let r=Ae(n);return e.some(e=>e.id===t&&Ge(e,n.delivery,r))}function vs(e=`immediate`,t={}){return{name:``,enabled:!0,delivery:e,targetIds:[],targetUsers:[],targetParams:{},priority:3,mediaAttach:`best`,mediaZoneCrop:!1,mediaFrame:void 0,mediaGif:!1,mediaClip:!1,mediaProfile:void 0,mediaClipSpeed:void 0,mediaLinkedCameras:void 0,templateTitle:``,templateBody:``,...ms(t),schedule:void 0,systemEventDelivery:void 0,snoozeAllowGlobal:!1,waitForEnhancement:!1,snoozeOptions:void 0,actions:Qi,cooldownSec:30,cooldownScope:`rule-device`,cooldownGranularity:void 0}}function ys(e){let t={};for(let n of e.targets)n.params&&Object.keys(n.params).length>0&&(t[n.targetId]=n.params);return{name:e.name,enabled:e.enabled,delivery:e.delivery,targetIds:e.targets.map(e=>e.targetId),targetUsers:e.targetUsers??[],targetParams:t,priority:e.priority,mediaAttach:e.media.attach,mediaZoneCrop:e.media.zoneCrop===!0,mediaFrame:e.media.frame,mediaGif:e.media.gif===!0,mediaClip:e.media.clip===!0,mediaProfile:e.media.profile,mediaClipSpeed:e.media.clipSpeed,mediaLinkedCameras:e.media.linkedCameras,templateTitle:e.template?.title??``,templateBody:e.template?.body??``,...ms(e.conditions),schedule:e.schedule,systemEventDelivery:e.systemEventDelivery,snoozeAllowGlobal:e.snoozeAllowGlobal===!0,waitForEnhancement:e.waitForEnhancement===!0,snoozeOptions:e.snoozeOptions,actions:$i(e.actions),cooldownSec:e.throttle.cooldownSec,cooldownScope:e.throttle.scope,cooldownGranularity:e.throttle.granularity}}function bs(e){let t=[];if(wt(e.conditions.audio)&&t.push(`This sound rule names neither a sound nor a level threshold, so it can never fire — every sample would count as a hit and the engine refuses it rather than notifying on silence. Pick at least one sound, or add a level.`),(!Number.isInteger(e.cooldownSec)||e.cooldownSec<0||e.cooldownSec>86400)&&t.push(`The cooldown is a whole number of seconds between 0 and ${String(no)} (24 hours). 0 means every match is delivered.`),Cs(e))for(let n of Ot({delivery:e.delivery,conditions:e.conditions,...e.systemEventDelivery===void 0?{}:{systemEventDelivery:e.systemEventDelivery},...ea(e.actions)===void 0?{}:{actions:ea(e.actions)}}))t.push(mt(n));return t}function xs(e){let t=e.systemEventDelivery;return t===void 0?{}:Re(e.delivery)?{systemEventDelivery:t}:t.mode===`summary`?{systemEventDelivery:{mode:`instant`}}:{}}function Ss(e){if(!Cs(e))return null;if(!st(e.templateBody))return`This body names none of the summary ({{summaryText}} or a section variable) — the hub appends {{summaryText}} to it when it sends.`;let t=e.templateBody;return(e.systemEventDelivery?.mode===`summary`?e.systemEventDelivery.split:void 0)===`section`&&t.trim().length>0&&!/\{\{\s*summaryText\s*\}\}/.test(t)?`Sent one per category: this body names no {{summaryText}}, so on every other category’s notification the hub appends {{summaryText}} (that category’s lines).`:null}function Cs(e){return Re(e.delivery)&&e.systemEventDelivery?.mode===`summary`}function ws(e){return bs(e).length===0&&Ya(e.delivery)&&(!Re(e.delivery)||ks(e)>0)&&Ae(e)!==`mixed`&&e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&ta(e.actions).length===0}function Ts(e,t){let n=Ds(e.conditions,t);return Re(t)&&(n.systemEvent?.kinds.length??0)===0?{...e,delivery:t,conditions:{...n,systemEvent:Fo(`device-events`)}}:{...e,delivery:t,conditions:n}}var Es=new Set([`immediate`,`track-end`,`package-event`]);function Ds(e,t){if(e.source!==`pipeline`||Es.has(t))return e;let{source:n,...r}=e;return r}function Os(e,t){return Ie(e.conditions.systemEvent)===t?e:{...e,conditions:{...e.conditions,systemEvent:Fo(t)}}}function ks(e){return e.conditions.systemEvent?.kinds.length??0}function As(e,t){return e.appliesTo.includes(t)}var js={source:`any`};function Ms(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||js[e]===t;if(typeof t==`number`)return!Number.isFinite(t);if(typeof t==`object`){if(`ids`in t){let e=t.ids;return!Array.isArray(e)||e.length===0}if(`values`in t){let e=t.values;return!Array.isArray(e)||e.length===0}return!1}return!1}var Ns=qe.filter(e=>e.id===`audio`);function Ps(e){if(e.length===0)return e;let t=new Set(e.map(e=>e.id)),n=Ns.filter(e=>!t.has(e.id));return n.length===0?e:[...e,...n]}function Fs(e,t,n,r=Ae({delivery:t,conditions:e})){let i=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&Ge(e,t,r)).map(e=>e.id)),a={};for(let[t,n]of Object.entries(e))i!==null&&!i.has(t)||So(t,e)&&(Ms(t,n)||(a[t]=n));return a}function Is(e,t){if(e===void 0)return{};let n=Uo(e,t.systemEvent);return n===void 0?{}:{systemEvent:n}}function Ls(e){return e!==void 0&&e.windows.length>0}function Rs(e){let t={...e.clipPreRollSec===void 0?{}:{clipPreRollSec:e.clipPreRollSec},...e.clipPostRollSec===void 0?{}:{clipPostRollSec:e.clipPostRollSec}};return Object.keys(t).length>0?t:void 0}function zs(e){let t=Rs(e.media);return{...e.confirm===void 0?{}:{confirm:e.confirm},...e.groupIdleSec===void 0?{}:{groupIdleSec:e.groupIdleSec},...t===void 0?{}:{media:t}}}function Bs(e,t,n=[]){let r=e.templateTitle.trim(),i=e.templateBody.trim(),a=r.length>0||i.length>0?{...r.length>0?{title:r}:{},...i.length>0?{body:i}:{}}:void 0,o=ea(e.actions),s=Ae(e),c=Qe(s),l=$e(s),u=n.length===0?!0:n.some(t=>t.id===`schedule`&&As(t,e.delivery)),d=!Cs(e)&&u&&Ls(e.schedule)?e.schedule:void 0,f=n.length===0?!0:n.some(t=>t.id===`devices`&&As(t,e.delivery)),p=n.length===0?!0:n.some(t=>t.id===`devicesExclude`&&As(t,e.delivery)),{devices:m,devicesExclude:h,...g}=hs(e);return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...Fs(g,e.delivery,n,s),...f&&m!==void 0?{devices:m}:{},...p&&h!==void 0?{devicesExclude:h}:{},...Is(l,e.conditions)},...d?{schedule:d}:{},...xs(e),targets:e.targetIds.map(t=>{let n=e.targetParams[t];return n&&Object.keys(n).length>0?{targetId:t,params:n}:{targetId:t}}),...e.targetUsers.length>0?{targetUsers:[...e.targetUsers]}:{},media:c.carriesMedia?{attach:e.mediaAttach,...c.carriesSubjectCrop&&e.mediaZoneCrop?{zoneCrop:!0}:{},...c.carriesSubjectCrop&&e.mediaFrame!==void 0?{frame:e.mediaFrame}:{},...e.mediaGif?{gif:!0}:{},...e.mediaClip?{clip:!0}:{},...e.mediaProfile===void 0?{}:{profile:e.mediaProfile},...e.mediaClipSpeed===void 0?{}:{clipSpeed:e.mediaClipSpeed},...s===`sensor`&&e.mediaAttach!==`none`&&e.mediaLinkedCameras!==void 0?{linkedCameras:e.mediaLinkedCameras}:{},...(e.mediaGif||e.mediaClip)&&t?.media?.clipPreRollSec!==void 0?{clipPreRollSec:t.media.clipPreRollSec}:{},...(e.mediaGif||e.mediaClip)&&t?.media?.clipPostRollSec!==void 0?{clipPostRollSec:t.media.clipPostRollSec}:{}}:{attach:`none`},throttle:{cooldownSec:e.cooldownSec,scope:e.cooldownScope,...e.cooldownGranularity===void 0?{}:{granularity:e.cooldownGranularity}},priority:e.priority,...a?{template:a}:{},...e.snoozeAllowGlobal?{snoozeAllowGlobal:!0}:{},...e.waitForEnhancement?{waitForEnhancement:!0}:{},...e.snoozeOptions===void 0?{}:{snoozeOptions:[...e.snoozeOptions]},...t?.confirm===void 0?{}:{confirm:t.confirm},...t?.groupIdleSec===void 0?{}:{groupIdleSec:t.groupIdleSec},...o===void 0?{}:{actions:o}}}function Vs(e,t){let n=Bs(e,void 0,t);return[`template`,`schedule`,`targetUsers`,`snoozeOptions`,`snoozeAllowGlobal`,`waitForEnhancement`,`actions`].filter(e=>n[e]===void 0)}var Hs=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`delivery`,`targetIds`,`targetUsers`,`targetParams`]},{key:`devices`,label:`Devices`,fields:[`deviceScope`]},{key:`conditions`,label:`Conditions`,fields:[`conditions`,`classScope`,`schedule`,`systemEventDelivery`]},{key:`notification`,label:`Notification`,fields:[`priority`,`mediaAttach`,`mediaFrame`,`mediaZoneCrop`,`mediaGif`,`mediaClip`,`mediaProfile`,`mediaClipSpeed`,`mediaLinkedCameras`,`templateTitle`,`templateBody`]},{key:`actions`,label:`Actions`,fields:[`actions`]},{key:`advanced`,label:`Advanced`,fields:[`snoozeAllowGlobal`,`snoozeOptions`,`cooldownSec`,`cooldownScope`,`cooldownGranularity`,`waitForEnhancement`]}];function Us(e,t={}){let n=Ae({delivery:e,conditions:t}),r=Qe(n),i=Hs.map(e=>e.key===`conditions`?{...e,label:r.label}:e);return Ve(n)?i.filter(e=>e.key!==`devices`):i}function Ws(e){if(e.audio!==void 0)return`Sound`;if(e.occupancy!==void 0)return`Occupancy`}function Gs(e){let t=Ae(e),n=Fe(hs(e),t);return t===`sensor`&&e.conditions.sensorTransition!==void 0&&!So(`sensorTransition`,e.conditions)?[...n,{conditionId:`sensorTransition`,reason:Me}]:n}var Ks=`rule`;function qs(e){return Hs.find(t=>t.key===e)?.key}function Js(e){return e?.toLowerCase().startsWith(`it`)===!0?`it`:`en`}function Ys(){let{i18n:e}=W(),t=Js(e.language);return e=>ut(e,t)}t();var q=`block text-[11px] font-medium text-foreground`,J=`text-[10px] text-foreground-subtle mt-0.5`;function Xs({cameras:e,fleet:t,value:n,onChange:r,emptyMeansAll:i=!1,savedHadDevices:a=!1}){return d(Pa,{devices:e,listState:t.state,fleet:t,value:n,onChange:r,emptyMeansAll:i,savedHadDevices:a})}function Zs({value:e,placeholder:t,onChange:r}){let[i,a]=l(``),o=()=>{let t=i.trim();if(t.length===0||e.includes(t)){a(``);return}r([...e,t]),a(``)},s=t=>r(e.filter(e=>e!==t));return n(`div`,{className:`mt-1 space-y-1.5`,children:[e.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>n(`span`,{className:`inline-flex items-center gap-1 rounded bg-surface-hover px-1.5 py-0.5 text-[11px] text-foreground`,children:[e,d(`button`,{type:`button`,onClick:()=>s(e),"aria-label":`remove ${e}`,className:`text-foreground-subtle hover:text-danger`,children:d(C,{className:`h-3 w-3`})})]},e))}),d(y,{value:i,placeholder:t,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),o())},onBlur:o})]})}function Qs({picker:e,value:t,onChange:i}){let a=r(()=>rt(e),[e]),o=r(()=>new Set(t),[t]),s=t.filter(e=>!a.has(e)),c=e=>{i(o.has(e)?t.filter(t=>t!==e):[...t,e])};return n(`div`,{className:`space-y-2`,children:[s.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,children:s.map(e=>n(`button`,{type:`button`,onClick:()=>i(t.filter(t=>t!==e)),className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,title:`Custom value — click to remove`,children:[e,` ×`]},e))}),e.groups.map(e=>n(`div`,{children:[d(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-muted mb-1`,children:e.fallbackLabel}),d(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map(e=>{let t=o.has(e.value);return d(`button`,{type:`button`,"aria-pressed":t,onClick:()=>c(e.value),className:t?`rounded border border-primary bg-primary/15 px-1.5 py-0.5 text-[10px] text-foreground`:`rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,children:e.label},e.value)})})]},e.key))]})}function $s({value:e,min:t,max:r,step:i,onChange:a}){return n(`div`,{className:`mt-1 flex items-center gap-2`,children:[d(y,{type:`number`,value:e??``,min:t,max:r,step:i,className:`max-w-[8rem]`,onChange:e=>{let t=e.target.value;if(t===``){a(void 0);return}let n=Number(t);a(Number.isFinite(n)?n:void 0)}}),e!==void 0&&r!==void 0&&d(`input`,{type:`range`,min:t,max:r,step:i,value:e,onChange:e=>a(Number(e.target.value)),className:`flex-1 accent-primary`,"aria-label":`value`})]})}function ec({value:e,onChange:t,options:r}){let{t:i}=W(),a=tc(r??[]),o=a.length>0?a:Co;return n(`div`,{className:`mt-1 space-y-1`,children:[d(H,{value:e??`enter`,options:o.map(e=>({value:e.value,label:i(`notificationRules.crossing.${e.value}`,e.label)})),onChange:e=>t(To(e.target.value))}),d(`p`,{className:J,children:i(`notificationRules.crossing.hint`,`Which way the subject crosses the zone.`)})]})}function tc(e){let t=[];for(let n of e){let e=n.value===``||n.value===`enter`?wo:To(n.value);e===void 0||t.some(t=>t.value===e)||t.push({value:e,label:n.label})}return t}function nc({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=Va(e,t);return d(Ga,{options:i,value:n,onChange:r,loading:a,noFreeText:!0,emptyHint:e.length===0?`Select cameras first — a rule can only use zones those cameras actually have.`:`The selected cameras have no zones. Draw one in the camera’s zone editor first.`,placeholder:``})}function rc({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=Ha(e);return d(Ga,{options:r,value:t,onChange:n,loading:i,emptyHint:e.length===0?`Select cameras above to pick their event kinds — or type a token.`:`No event kinds reported for the selected cameras — type a token.`,placeholder:`Event token…`})}var ic=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}];function ac(e,t){let n=e.map(e=>({value:e.value,label:e.label}));return t===void 0||t===``||n.some(e=>e.value===t)?n:[...n,{value:t,label:`${t} — sub-type, never counts (always 0)`}]}function oc({deviceIds:e,cameras:t,classOptions:r,value:i,onChange:a}){let{options:o,loading:s}=Va(e,t),c=i??Ue,l=e=>a({...c,...e}),u=c.op===`became-occupied`||c.op===`became-free`,f=ac(r,c.className);return n(`div`,{className:`mt-1 space-y-1.5`,children:[n(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[d(`div`,{className:`min-w-[10rem]`,children:d(H,{value:c.zoneId??``,options:[{value:``,label:s?`Loading zones…`:`— whole frame —`},...o.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({zoneId:e.target.value===``?void 0:e.target.value})})}),d(`div`,{className:`min-w-[9rem]`,children:d(H,{value:c.className??``,options:[{value:``,label:`— any class —`},...f],onChange:e=>l({className:e.target.value===``?void 0:e.target.value})})}),d(`div`,{className:`min-w-[9rem]`,children:d(H,{value:c.op,options:ic.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=ic.find(t=>t.value===e.target.value);t&&l({op:t.value})}})})]}),n(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[n(`label`,{className:`flex items-center gap-1`,children:[u?`Threshold`:`Count`,d(y,{type:`number`,min:0,className:`w-16`,value:String(c.count),onChange:e=>l({count:Math.max(0,Number(e.target.value)||0)})})]}),n(`label`,{className:`flex items-center gap-1`,children:[`Hold for`,d(y,{type:`number`,min:0,max:3600,className:`w-16`,value:String(c.sustainSeconds),onChange:e=>l({sustainSeconds:Math.min(3600,Math.max(0,Number(e.target.value)||0))})}),`s`]}),i===void 0?null:d(`button`,{type:`button`,onClick:()=>a(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),e.length===0&&d(`p`,{className:`text-[11px] text-warning`,children:`No camera picked on the Devices tab: this watches EVERY camera's occupancy, and no zone can be offered until you choose one — a zone id belongs to a camera.`}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Counts confirmed tracked objects from zone analytics. The change must hold for the sustain window before it fires; with no snapshot for the camera or zone the rule never fires.`})]})}var sc=[{value:`label`,label:`Sounds — fires at once`,Icon:ue},{value:`level`,label:`Volume — over a window`,Icon:de}];function cc({taxonomy:e,value:t,onChange:r}){let i=xt(t),o=e=>r(lt(t,e)),{choices:s,unknownLabels:c}=ht(e,i.labels),l=ot(t)??`label`;return n(`div`,{className:`mt-1 space-y-2`,children:[n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[sc.map(e=>d(`button`,{type:`button`,"aria-pressed":l===e.value,onClick:()=>o({mode:e.value}),className:`rounded border px-2 py-0.5 text-[11px] ${l===e.value?`border-primary bg-primary/15 text-foreground`:`border-border text-foreground-subtle hover:bg-surface-hover`}`,children:n(`span`,{className:`inline-flex items-center gap-1`,children:[d(e.Icon,{className:`h-3 w-3`}),e.label]})},e.value)),t===void 0?null:d(`button`,{type:`button`,onClick:()=>r(void 0),className:`ml-1 text-xs text-foreground-subtle underline hover:text-foreground`,children:`Clear`})]}),l===`label`?n(a,{children:[d(`div`,{className:`flex flex-wrap gap-1`,children:s.map(e=>{let t=Tt(i.labels,e.value),r=e.unknown?`border-dashed border-warning text-warning`:t?`border-primary bg-primary/15 text-foreground`:`border-border text-foreground hover:bg-surface-hover`;return d(`button`,{type:`button`,"aria-pressed":t,title:e.unknown?`Stored by the rule — not offered by this hub`:void 0,onClick:()=>o({labels:vt(i.labels,e.value)}),className:`rounded border px-1.5 py-0.5 text-[10px] ${r}`,children:n(`span`,{className:`inline-flex items-center gap-1`,children:[d(be,{iconId:e.iconId,size:12}),e.label]})},e.value)})}),c.length>0&&n(`p`,{className:`text-[10px] text-warning`,children:[`Kept from the rule, unknown to this hub: `,c.join(`, `)]}),n(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[n(`label`,{className:`flex items-center gap-1`,children:[`Confirm after`,d(y,{type:`number`,min:1,max:20,step:1,className:`w-16`,value:String(i.confirmHits??2),onChange:e=>o({confirmHits:Number(e.target.value)})}),`frames`]}),n(`label`,{className:`flex items-center gap-1`,children:[`within`,d(y,{type:`number`,min:1,max:60,step:1,className:`w-16`,value:String(i.confirmWindowSec??5),onChange:e=>o({confirmWindowSec:Number(e.target.value)})}),`s`]})]}),n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Fires when that many labelled frames land inside the window (default`,` `,2,` in `,5,` s). A single-frame false positive never reaches 2; a real episode usually labels two or three frames. The rule's cooldown is the other throttle.`]})]}):n(a,{children:[d(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:n(`label`,{className:`flex items-center gap-1`,children:[`Louder than`,d(y,{type:`number`,min:dt,max:0,step:3,className:`w-20`,value:String(i.dbThreshold??Et),onChange:e=>o({dbThreshold:Number(e.target.value)})}),`dBFS`]})}),n(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[n(`label`,{className:`flex items-center gap-1`,children:[`Hits`,d(y,{type:`number`,min:1,max:100,step:5,className:`w-16`,value:String(i.hitPercent),onChange:e=>o({hitPercent:Number(e.target.value)})}),`% (default `,bt.hitPercent,`)`]}),n(`label`,{className:`flex items-center gap-1`,children:[`over`,d(y,{type:`number`,min:1,max:300,step:5,className:`w-16`,value:String(i.samplingSeconds),onChange:e=>o({samplingSeconds:Number(e.target.value)})}),`s (default `,bt.samplingSeconds,`)`]})]}),n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`dBFS is negative-going: 0 is full scale, `,dt,` is silence — so a HIGHER number is a narrower filter. Measured on this hub, a baby crying reads `,`−`,`55 to `,`−`,`26 dBFS, so a floor above `,`−`,`55 excludes most of it. The window must be FULL before it can match.`]})]}),wt(t)?d(`p`,{className:`text-[11px] text-warning`,children:`With neither a sound nor a level threshold this can never match — every sample would be a hit, so the engine refuses it rather than notifying on silence.`}):null]})}function lc({value:e,onChange:t}){let r=e?.values??[],i=e?.maxDistance??1,a=e=>t(e.length>0?{values:e,maxDistance:i}:void 0),o=e=>t(r.length>0?{values:r,maxDistance:e}:void 0),s=Wa().filter(e=>!r.includes(e));return n(`div`,{className:`mt-1 space-y-1.5`,children:[d(Zs,{value:r,placeholder:`Plate text…`,onChange:a}),s.length>0&&n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[d(`span`,{className:`text-[10px] text-foreground-subtle`,children:`Seen:`}),s.slice(0,12).map(e=>d(`button`,{type:`button`,onClick:()=>a([...r,e]),className:`rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:e},e))]}),n(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Max distance`,d(y,{type:`number`,min:0,max:3,step:1,value:i,className:`max-w-[5rem]`,onChange:e=>{let t=Number(e.target.value);o(Number.isFinite(t)?Math.max(0,Math.min(3,t)):1)}})]})]})}function uc({gateable:e,value:t,onChange:r}){let i=Ys(),a=e.find(e=>e.id===t?.deviceId),o=new Set(t?.states??[]),s=e=>{let t=Number(e);if(!Number.isFinite(t)||t===0)return r(void 0);r({deviceId:t,states:[]})},c=e=>{if(t===void 0)return;let n=new Set(o);n.has(e)?n.delete(e):n.add(e),r(n.size===0?void 0:{deviceId:t.deviceId,states:[...n]})};return n(`div`,{className:`mt-1 space-y-2`,children:[d(H,{value:t===void 0?``:String(t.deviceId),options:[{value:``,label:`— no device gate —`},...e.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>s(e.target.value)}),a!==void 0&&d(`div`,{className:`flex flex-wrap gap-1.5`,children:a.states.map(e=>d(`button`,{type:`button`,onClick:()=>c(e),className:o.has(e)?`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`,children:i(e)},e))}),a!==void 0&&a.states.length===0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`This device reports no state the gate can read, so it cannot arm a rule.`}),t!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`The rule is silent while the device is in any other state — including when its state cannot be read at all.`})]})}function dc(e,t){let n=t(e.verdict);return e.latched?`${n} · ${t(`latched`)}`:n}function fc({scenes:e,value:t,onChange:r}){let{t:i}=W(),a=Ys(),o=e.find(e=>e.sceneId===t?.sceneId),s=n=>{if(n===``)return r(void 0);let i=e.find(e=>e.sceneId===n);if(i===void 0)return r(void 0);r({sceneId:n,deviceId:i.deviceId,requiredState:t?.requiredState??`diverged`,...t?.latched===void 0?{}:{latched:t.latched}})},c=e=>{t!==void 0&&r({...t,requiredState:e===`matched`?`matched`:`diverged`})},l=e=>{if(t!==void 0){if(e===``){let{latched:e,...n}=t;return r(n)}r({...t,latched:e===`latched`})}};return e.length===0?d(`p`,{className:J,children:i(`notificationRules.scene.none`,`No scenes yet — create one on the Scenes page.`)}):n(`div`,{className:`mt-1 space-y-2`,children:[d(H,{value:t?.sceneId??``,options:[{value:``,label:i(`notificationRules.scene.noGate`,`— no scene gate —`)},...e.map(e=>({value:e.sceneId,label:`${e.cameraName} · ${e.label} — ${dc(e,a)}`}))],onChange:e=>s(e.target.value)}),t!==void 0&&n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[i(`notificationRules.scene.onlyWhile`,`Only while it is`),d(H,{value:t.requiredState,options:[{value:`diverged`,label:a(`diverged`)},{value:`matched`,label:a(`matched`)}],onChange:e=>c(e.target.value)})]}),n(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[i(`notificationRules.scene.read`,`Read`),d(H,{value:t.latched===void 0?``:t.latched?`latched`:`live`,options:[{value:``,label:o===void 0?i(`notificationRules.scene.readOwn`,`The scene's own setting`):`${i(`notificationRules.scene.readOwn`,`The scene's own setting`)} (${a(o.emit)})`},{value:`latched`,label:a(`latched`)},{value:`live`,label:a(`live`)}],onChange:e=>l(e.target.value)})]})]}),o!==void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[i(`notificationRules.scene.rightNow`,`Right now:`),` `,dc(o,a)]}),t!==void 0&&o===void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:i(`notificationRules.scene.missing`,`This scene no longer exists — pick another or remove the gate.`)})]})}var pc=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),mc=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],hc={minConfidence:`class`},gc=[{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 _c(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of mc)t.has(e)&&n.add(r);return n}function vc(e){return hc[e.id]??e.group}function yc(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function bc(e){let t=_c(e),n=e.filter(e=>!pc.has(e.id)&&!t.has(e.id)),r=new Set(gc.map(e=>e.id)),i=[],a=e=>n.filter(t=>vc(t)===e);for(let e of gc){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=vc(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:yc(e),descriptors:a(e)});return i}function xc(e,t){switch(e){case`zones`:return es(t.zones?.ids,t.zonesExclude);case`labels`:return es(t.labelEquals,void 0);case`identities`:return Sc(t)}}function Sc(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?es(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function Cc(e,t,n){switch(e){case`zones`:return wc(t,n);case`labels`:return Tc(t,n);case`identities`:return Ec(t,n)}}function wc(e,t){let{zones:n,zonesExclude:r,...i}=e,a=os(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function Tc(e,t){let{labelEquals:n,...r}=e,i=os(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function Ec(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=is(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=os(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var Dc={all:`All`,only:`Only these`,except:`All except these`},Oc={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.`}};function kc({draft:e,onChange:t,exceptOffered:r,plural:i,renderPicker:a,describe:o,testId:s}){let{t:c}=W(),l=(e,t,n)=>c(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),u=c(`ruleScope.items.${i}`,Oc[i].items),f=Qo.filter(t=>t!==`except`||r||e.mode===`except`),p=is(e),m=ss(e),h=e.mode===`all`?null:e.mode;return n(`div`,{className:`mt-1 space-y-1.5`,"data-testid":s,children:[d(`div`,{role:`radiogroup`,"aria-label":l(`ruleScope.which`,`Which {{items}}`,u),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(n=>{let r=n===e.mode;return d(`button`,{type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${n}`,onClick:()=>t(ts(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}`,Dc[n])},n)})}),h===null?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(`ruleScope.every.${i}`,Oc[i].every)}):a(ns(e),n=>t(rs(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(`, `)),` `,d(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>t(as(e)),children:c(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:l(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(o).join(`, `))})]})}function Ac(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 jc(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 Mc(e,t,n){let[r,i]=l(()=>xc(e,t));return[r,r=>{i(r),n(Cc(e,t,r))}]}function Nc(e,t){return t?`failed`:e?`pending`:`answered`}function Pc({conditions:e,onConditionsChange:t,exceptOffered:n,cameraIds:i,cameras:a}){let{t:o}=W(),[s,c]=Mc(`zones`,e,t),{options:l,loading:u,failed:f}=Va(i,a),p=r(()=>jc(l),[l]),m=Nc(u,!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 d(kc,{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?d(`p`,{className:J,children:o(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):d(Pa,{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 Fc({conditions:e,onConditionsChange:t,exceptOffered:n}){let{t:i}=W(),[a,o]=Mc(`identities`,e,t),{options:s,loading:c,failed:l}=Ua(),u=r(()=>s.map(e=>({id:e.value,name:e.label})),[s]),f=r(()=>new Map(u.map(e=>[e.id,e.name])),[u]);return d(kc,{draft:a,onChange:o,exceptOffered:n,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>d(Pa,{devices:u,listState:Nc(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 Ic({conditions:e,onConditionsChange:t}){let{t:n}=W(),[r,i]=Mc(`labels`,e,t);return d(kc,{draft:r,onChange:i,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>d(Zs,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function Lc(e){let t=Ee(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function Rc(e){return e.type??`Other`}t();function zc({taxonomy:e,scope:t,onChange:n,exceptOffered:i}){let a=r(()=>Lc(e),[e]),o=r(()=>new Map((a??[]).map(e=>[e.id,e.name])),[a]);return d(kc,{draft:t,onChange:n,exceptOffered:i,plural:`classes`,describe:e=>o.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>a===null?d(Zs,{value:e,placeholder:`Add value…`,onChange:t}):d(Pa,{devices:a,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:Rc,testId:`class-picker`},n)})}var Bc=[{value:1,label:`Mon`},{value:2,label:`Tue`},{value:3,label:`Wed`},{value:4,label:`Thu`},{value:5,label:`Fri`},{value:6,label:`Sat`},{value:0,label:`Sun`}];function Vc(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Hc(e){let[t,n]=e.split(`:`),r=Number(t)*60+Number(n);return Number.isFinite(r)?Math.max(0,Math.min(1439,r)):0}function Uc(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function Wc({value:e,onChange:t}){let r=e?.windows??[],i=e?.invert??!1,a=(n,r)=>{if(n.length===0){t(void 0);return}t({windows:n,...r?{invert:!0}:{},...e?.timezone?{timezone:e.timezone}:{}})},o=()=>a([...r,Uc()],i),s=e=>a(r.filter((t,n)=>n!==e),i),c=(e,t)=>a(r.map((n,r)=>r===e?t:n),i);return n(`div`,{className:`mt-1 space-y-2`,children:[r.length===0?d(`p`,{className:J,children:`Always active — add a window to restrict when the rule fires.`}):r.map((e,t)=>d(Gc,{window:e,onChange:e=>c(t,e),onRemove:()=>s(t)},t)),n(`div`,{className:`flex items-center gap-3`,children:[n(`button`,{type:`button`,onClick:o,className:`flex items-center gap-1 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground`,children:[d(w,{className:`h-3 w-3`}),` Add window`]}),r.length>0&&n(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[d(`input`,{type:`checkbox`,checked:i,onChange:e=>a([...r],e.target.checked),className:`accent-primary`}),`Active outside the windows`]})]})]})}function Gc({window:e,onChange:t,onRemove:r}){let i=n=>{let r=e.days.includes(n)?e.days.filter(e=>e!==n):[...e.days,n];r.length!==0&&t({...e,days:r})};return n(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[n(`div`,{className:`flex items-center gap-2 text-xs`,children:[d(`input`,{type:`time`,value:Vc(e.startMinute),onChange:n=>t({...e,startMinute:Hc(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),d(`span`,{className:`text-foreground-subtle`,children:`→`}),d(`input`,{type:`time`,value:Vc(e.endMinute),onChange:n=>t({...e,endMinute:Hc(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),d(`span`,{className:`flex-1`}),d(`button`,{type:`button`,onClick:r,"aria-label":`Remove window`,className:`text-foreground-subtle hover:text-danger`,children:d(g,{className:`h-3.5 w-3.5`})})]}),d(`div`,{className:`flex flex-wrap gap-1`,children:Bc.map(t=>d(`button`,{type:`button`,onClick:()=>i(t.value),className:`rounded px-1.5 py-0.5 text-[10px] ${e.days.includes(t.value)?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:t.label},t.value))})]})}function Kc(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function qc({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return d(Pa,{devices:e.map(Kc),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`,showAll:!0})}function Jc({devices:e,scope:t,onChange:n,listState:r,savedScope:i,exceptOffered:a}){let o=new Map(e.map(e=>[e.id,e.name]));return d(kc,{draft:t,onChange:n,exceptOffered:a,plural:`devices`,describe:e=>o.get(e)??`Device #${String(e)}`,testId:`rule-device-scope`,renderPicker:(t,n,a)=>d(qc,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function Yc(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function Xc(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function Zc(e){let t=Yc(e),n=e.data===void 0?[]:ft(e.data.nodes),r=Xc(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function Qc(e){let t=Yc(e),n=e.data===void 0?[]:St(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var $c=[`nc-pickers`,`node-directory`],el=[`nc-pickers`,`package-list`],tl=6e4,nl={hub:`Hub`,agent:`Agents`},rl={server:`Server`,framework:`Framework`,wrapper:`Wrapper`,addon:`Addons`};function il(e){let t=nl[e.type??``]??`Nodes`;return e.location===`offline`?`${t} · offline`:t}function al(e){return rl[e.type??``]??`Packages`}function ol({value:e,onChange:t,testId:r}){let a=m().trpcClient,o=i({queryKey:$c,staleTime:tl,queryFn:()=>a.nodes.directory.query()}),s=Zc(o);return n(`div`,{children:[d(Pa,{devices:s.items,listState:s.listState,fleet:s.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:il,...r===void 0?{}:{testId:r}}),o.data?.complete===!1&&d(`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 sl({value:e,onChange:t,testId:n}){let r=m().trpcClient,a=Qc(i({queryKey:el,staleTime:tl,queryFn:()=>r.addons.listPackages.query()}));return d(Pa,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:al,...n===void 0?{}:{testId:n}})}var cl={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-tank-low`]},template:{body:`{{deviceName}}`}};function ll(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 ul(e,t){return e===`pending`?`pending`:e===`success`?`current`:ll(t)===`BAD_REQUEST`?`outdated`:`unknown`}function dl(e){let t=m(),n=i({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(cl)});return e?ul(n.status,n.error):`pending`}t();var fl=`/system/settings`,pl=`/system/notifications?tab=alarm`,ml=`text-primary underline-offset-2 hover:underline`;function hl({family:e,value:t,cameras:i,allDevices:a,fleet:o,savedHadDevices:s,onChange:c}){let l=r(()=>t?.kinds??[],[t]),u=r(()=>a===void 0?i:a.map(Kc),[a,i]),f=zo(e,l),p=dl(e===`device-events`),m=e===`alarm`;return n(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[Po(e).map(r=>n(`div`,{children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:r.label}),d(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:r.kinds.map(n=>{let r=l.includes(n.value);return d(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":n.label,onClick:()=>c(Ho(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)})}),d(`p`,{className:J,children:r.hint})]},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):`,` `,d(zt,{to:fl,target:`_blank`,rel:`noreferrer`,className:ml,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:[d(zt,{to:pl,target:`_blank`,rel:`noreferrer`,className:ml,children:`Alarm settings`}),l.includes(`alarm-triggered`)&&` — when a rule sets the alarm off, this notification carries that rule's pictures.`]}),p===`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.`]}),p===`unknown`&&d(`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.`}),f.consumableThreshold&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:`Consumable low at (%)`}),d(y,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:qo,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=Jo(e.target.value);n.kind!==`invalid`&&c(Wo(t,{consumableLowPercent:n.kind===`set`?n.value:void 0}))}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`This rule is told when a consumable’s remaining life reaches this percentage (empty = `,15,`%). Another rule may use its own number — each is told at its own threshold. A device that reports “replace” is announced whatever this says.`]})]}),f.deviceTypes&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these device types (optional)`}),d(Ga,{options:Bo,value:t?.deviceTypes??[],onChange:e=>c(Wo(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Liveness is reported for EVERY device — cameras, plugs, sensors, the containers that hold them. Leave this empty to be told about all of them, or pick “Camera” to hear only about cameras.`})]}),Zo(t)&&d(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`battery-device-types-warning`,children:`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.`}),f.devices&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:m?`Only when triggered by these cameras (optional)`:`Only these devices (optional)`}),d(Pa,{devices:m?i:u,listState:o.state,fleet:o,emptyMeansAll:!0,savedHadDevices:s,noun:m?`camera`:`device`,value:t?.deviceIds??[],onChange:e=>c(Wo(t,{deviceIds:e})),testId:`system-event-include`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:m?`An alarm is narrowed to the camera whose rule set it off. Leave it empty for every camera.`:`Leave it empty to watch every device.`})]}),f.excludeDevices&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Never these devices (optional)`}),d(Pa,{devices:u,listState:o.state,fleet:o,noun:`device`,emptyLabel:`No device excluded`,value:t?.excludeDeviceIds??[],onChange:e=>c(Wo(t,{excludeDeviceIds:e})),testId:`system-event-exclude`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Applied after the list above: a device here is never reported, whatever else matches — "every battery except the thermometer that always reads 0 %".`})]}),f.nodes&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these nodes (optional)`}),d(ol,{value:t?.nodeIds??[],onChange:e=>c(Wo(t,{nodeIds:e})),testId:`system-event-nodes`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave it empty to watch every node.`})]}),f.packages&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these packages (optional)`}),d(sl,{value:t?.packageNames??[],onChange:e=>c(Wo(t,{packageNames:e})),testId:`system-event-packages`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave it empty to be told about every addon, server and container update.`})]})]})}function gl({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:[d(`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&&d(`p`,{className:`mt-1 text-foreground`,children:t.map(Lo).join(`, `)})]})}function _l({family:e,onChange:t}){return n(`div`,{"data-testid":`system-family-select`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Kind of system rule`}),d(H,{value:e,"aria-label":`Kind of system rule`,onChange:e=>{let n=e.target.value;nt(n)&&t(n)},options:Be.map(e=>({value:e,label:Qe(e).label}))}),d(`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 vl({catalog:e,taxonomy:t,delivery:i,conditions:a,classScope:o,onClassScopeChange:s,onTrigger:c,savedConditions:l,schedule:u,deviceIds:f,zoneCameraIds:p,cameras:m,fleet:h,allDevices:g,gateable:_,gateableScenes:v,onConditionsChange:y,onScheduleChange:b}){let{t:x}=W(),S=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,y(n)},C=Ae({delivery:i,conditions:a}),w=r(()=>e.filter(e=>Ge(e,i,C)&&So(e.id,a)),[e,i,C,a]),T=r(()=>bc(w),[w]),E=e=>w.some(t=>t.id===e),D=e=>yl.has(e.id)?d(zc,{taxonomy:t,scope:o,onChange:s,exceptOffered:E(`classesExclude`)}):bl.has(e.id)?d(Pc,{conditions:a,onConditionsChange:y,exceptOffered:E(`zonesExclude`),cameraIds:p??f,cameras:m}):xl.has(e.id)?d(Fc,{conditions:a,onConditionsChange:y,exceptOffered:E(`identitiesExclude`)}):e.id===`labelEquals`?d(Ic,{conditions:a,onConditionsChange:y}):null;return d(`div`,{className:`space-y-4`,children:T.map(e=>n(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${e.id}`,children:[d(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:x(`notificationRules.groups.${e.id}`,e.label)}),e.descriptors.map(e=>{let r=D(e);return n(`div`,{"data-testid":`condition-${e.id}`,children:[d(`label`,{className:q,children:Sl(e,x)}),r??d(Tl,{descriptor:e,kind:C,taxonomy:t,conditions:a,onTrigger:c??[],savedConditions:l,schedule:u,deviceIds:f,cameras:m,fleet:h,...g===void 0?{}:{allDevices:g},gateable:_,gateableScenes:v,onFieldChange:S,onScheduleChange:b}),Cl(e,x)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Cl(e,x)})]},e.id)})]},e.id))})}var yl=new Set([`classes`,`classesExclude`]),bl=new Set([`zones`,`zonesExclude`]),xl=new Set([`identities`,`identitiesExclude`]);function Sl(e,t){return yl.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):bl.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):xl.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 Cl(e,t){if(!wl.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var wl=new Set([...yl,...bl,...xl,`labelEquals`,`crossing`]);function Tl({descriptor:e,kind:t,taxonomy:r,conditions:i,onTrigger:o,savedConditions:s,schedule:c,deviceIds:l,cameras:u,fleet:f,allDevices:p,gateable:m,gateableScenes:h,onFieldChange:g,onScheduleChange:_}){switch(e.valueType){case`deviceIdList`:{if(!pa(e.id))break;let t=e.id,n=i[t]??[];return d(Xs,{cameras:u,fleet:f,emptyMeansAll:!0,savedHadDevices:(s?.[t]?.length??0)>0,value:n,onChange:e=>g(t,e.length>0?e:void 0)})}case`stringList`:{if(!ma(e.id))break;let t=e.id,n=e=>g(t,e.length>0?e:void 0);if(t===`eventTypeTokens`)return d(rc,{deviceIds:l,value:Da(i,t),onChange:n});let a=Ke(t,r);return a===null?d(Zs,{value:Da(i,t),placeholder:`Add value…`,onChange:n}):d(Qs,{picker:a,value:Da(i,t),onChange:n})}case`number01`:{if(!ha(e.id))break;let t=e.id;return d($s,{value:Oa(i,t),min:0,max:1,step:.05,onChange:e=>g(t,e)})}case`number`:{if(!ga(e.id))break;let t=e.id;return d($s,{value:Oa(i,t),min:0,step:1,onChange:e=>g(t,e)})}case`sourceSelect`:{if(!_a(e.id))break;let t=e.id;return Al(e,i[t],e=>g(t,e))}case`systemEvent`:{if(!wa(e.id))break;let n=e.id,r=$e(t);return r===void 0?d(gl,{value:i[n]}):d(hl,{family:r,value:i[n],cameras:u,fleet:f,...p===void 0?{}:{allDevices:p},savedHadDevices:(s?.[n]?.deviceIds?.length??0)>0,onChange:e=>g(n,e)})}case`deviceState`:if(!Ta(e.id))break;return d(uc,{gateable:m,value:i.deviceState,onChange:e=>g(`deviceState`,e)});case`scene`:if(!Ea(e.id))break;return d(fc,{scenes:h,value:i.scene,onChange:e=>g(`scene`,e)});case`crossingSelect`:{if(!va(e.id))break;let t=e.id;return jl(e,i[t],e=>g(t,e))}case`packagePhase`:{if(!ya(e.id))break;let t=e.id;return d(H,{value:i[t]??``,options:[{value:``,label:`— any phase —`},...Do(e,yo).map(e=>({value:e.value,label:e.label}))],onChange:e=>g(t,kl(e.target.value))})}case`sensorTransition`:{if(!ba(e.id))break;let t=e.id,r=He({conditions:i,onTrigger:o});return n(a,{children:[d(H,{value:i[t]??``,options:Do(e,bo).map(e=>({value:e.value,label:e.label})),onChange:e=>g(t,xo(e.target.value))}),r&&d(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`nc-sensor-transition-never-fires`,children:`This rule belongs to the alarm, and an alarm rule fires only when an opening OPENS. Set to “only when it clears”, it can never fire.`})]})}case`plateMatcher`:{if(!xa(e.id))break;let t=e.id;return d(lc,{value:i[t],onChange:e=>g(t,e)})}case`occupancy`:{if(!Sa(e.id))break;let t=e.id;return d(oc,{deviceIds:l,cameras:u,classOptions:El(r),value:i[t],onChange:e=>g(t,e)})}case`audio`:{if(!Ca(e.id))break;let t=e.id;return d(cc,{taxonomy:r,value:i[t],onChange:e=>g(t,e)})}case`schedule`:return d(Wc,{value:c,onChange:_});default:break}return d(Dl,{descriptor:e,conditions:i})}function El(e){let t=Ke(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Dl({descriptor:e,conditions:t}){let r=Object.entries(t).find(([t])=>t===e.id);return n(`p`,{className:J,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 Ol(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function kl(e){return yo.find(t=>t.value===e)?.value}function Al(e,t,n){return d(H,{value:t??`any`,options:Do(e,vo).map(e=>({value:e.value,label:e.label})),onChange:e=>n(Ol(e.target.value))})}function jl(e,t,n){return d(ec,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function Ml({catalog:e,delivery:t,conditions:r,onConditionsChange:i}){let{t:a}=W(),o=Ae({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&&Ge(e,t,o)&&So(n,r)),l=c(`source`),u=c(`crossing`);return l===void 0&&u===void 0?null:n(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[l&&_a(l.id)&&n(`div`,{"data-testid":`condition-source`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Sl(l,a)}),Al(l,r.source,e=>s(`source`,e)),Cl(l,a)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Cl(l,a)})]}),u&&va(u.id)&&n(`div`,{"data-testid":`condition-crossing`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Sl(u,a)}),jl(u,r.crossing,e=>s(`crossing`,e)),Cl(u,a)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Cl(u,a)})]})]})}var Nl=6e4,Pl=60*Nl,Fl=24*Pl,Il=Date.UTC(2e3,0,1);function Ll(e){if(e==null||e<Il)return`—`;let t=Date.now()-e;return t<0||t<3e4?`just now`:t<Pl?`${String(Math.floor(t/Nl))}m ago`:t<Fl?`${String(Math.floor(t/Pl))}h ago`:`${String(Math.floor(t/Fl))}d ago`}var Rl=[`notificationRules`,`getRuleLastRuns`],zl=3e4;function Bl(){let e=m(),t=i({queryKey:Rl,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:zl});return{status:t.status,data:t.data,error:t.error}}var Vl={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function Hl({cell:e}){switch(e.kind){case`pending`:return d(`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 d(`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 d(`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:[d(`span`,{"data-testid":`rule-last-run-dot`,title:e.status,className:`inline-block h-2 w-2 rounded-full ${Vl[e.status]}`}),d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Ll(e.lastAt)})]})}}function Ul({rule:e,onOpenHistory:t}){return d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t(e),title:`History — this rule's deliveries`,"aria-label":`history of ${e.name}`,children:d(gn,{className:`h-3.5 w-3.5`})})}t();var Wl=[`notificationRules`,`listSnoozes`],Gl=[10,30,60,120];function Kl({ruleId:e,ruleName:t,exempt:r=!1,variant:i=`icon`}){let a=m(),o=s(),[c,f]=l(30),[p,h]=l(null),g=u({mutationFn:t=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>o.invalidateQueries({queryKey:Wl}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?i===`icon`?null:d(`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`?d(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:`Silence this rule for ${us(30)} — it appears under "Silenced right now"`,"aria-label":`snooze ${t}`,"data-testid":`nc-rule-snooze-now`,children:g.isPending?d(V,{className:`h-3.5 w-3.5 animate-spin`}):d(I,{className:`h-3.5 w-3.5`})}):n(`div`,{className:`space-y-1`,children:[n(`div`,{className:`flex items-end gap-2`,children:[d(`div`,{className:`w-32`,children:d(H,{value:String(c),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&f(t)},options:Gl.map(e=>({value:String(e),label:us(e)}))})}),n(z,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(c),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?d(V,{className:`h-3.5 w-3.5 animate-spin`}):d(I,{className:`h-3.5 w-3.5`}),`Silence this rule now`]})]}),d(`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.`}),p!==null&&d(`p`,{className:`text-[10px] text-danger`,children:p})]})}t();function ql(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function Jl(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 Yl(e,t){let[,n]=l(0);f(()=>{let r=Jl(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 Xl(){let e=m();return i({queryKey:Wl,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function Zl({rule:e,snoozes:t,exempt:r}){let{t:i}=W(),a=m(),o=s();Yl(t,e.id);let c=ql(t,e.id,Date.now()),l=()=>o.invalidateQueries({queryKey:Wl}),f=u({mutationFn:()=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e.id,durationMinutes:30}}),onSuccess:l}),p=u({mutationFn:async e=>{for(let t of e)await a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:l});if(r)return null;let h=f.isError||p.isError;return n(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[d(P,{checked:c.length>0,disabled:!e.enabled||f.isPending||p.isPending,onCheckedChange:e=>e?f.mutate():p.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&&d(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:i(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var Ql=`pipeline-analytics`,$l=`nc.getRuleStatus`,eu=`nc.testRule`;function tu(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 nu(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function ru(e){if(!tu(e))return;let t=nu(e,`id`),n=nu(e,`downloadPath`),r=Y(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:nu(e,`mediaType`)??`video`,sizeBytes:Y(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function iu(e){if(!tu(e))return;let t=Y(e,`startMs`),n=Y(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function au(e){if(!tu(e))return null;let t=Y(e,`deviceId`);if(t===void 0)return null;let n=Y(e,`lastGeneratedAt`),r=ru(e.lastArtifact),i=e.rendering,a=tu(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 ou(e){if(!tu(e))return null;let t=nu(e,`kind`);if(t===`none`)return{kind:`none`,reason:nu(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=nu(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=nu(e,`scope`),u=nu(e,`className`),d=nu(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===`timelapse`){let t=Array.isArray(e.devices)?e.devices:[],n=[];for(let e of t){let t=au(e);t!==null&&n.push(t)}let r=iu(e.lastWindow),i=e.nextWindow,a=tu(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 su(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 cu(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 lu(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 ${su(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 uu(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${su(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} · ${cu(i.sizeBytes)}`}var du=`nc.listPrunes`;function fu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var pu=new Set([`rule`,`timelapse`,`summary`]),mu=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`]);function hu(e){return typeof e==`string`&&pu.has(e)}function gu(e){return typeof e==`string`&&mu.has(e)}function _u(e){return e===`device`||e===`target`}function vu(e){if(!fu(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!hu(t)||!_u(r)||!gu(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 yu(e){return!fu(e)||!Array.isArray(e.prunes)?null:e.prunes.map(vu).filter(e=>e!==null)}function bu(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 xu(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 Su(e){return new Date(e).toLocaleDateString()}function Cu({kind:e,ruleId:t,enabled:r,updatedAt:a}){let o=m(),s=i({queryKey:[`pipelineAnalytics`,du],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>yu(await o.trpcClient.addons.custom.mutate({addonId:Ql,action:du,input:{}}))}).data;if(s==null)return null;let c=bu(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:[d(he,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),d(`span`,{children:xu(c,Su)})]})}var wu=5e3;function Tu({ruleId:e,cameraName:t}){let r=m(),o=i({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:wu,queryFn:async()=>ou(await r.trpcClient.addons.custom.mutate({addonId:Ql,action:$l,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?d(me,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):d(O,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),n(`span`,{children:[d(`span`,{className:`text-foreground`,children:c(o.deviceId)}),` —`,` `,lu(o,s)]})]}),o.kind===`timelapse`&&n(a,{children:[o.devices.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[d(O,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),n(`span`,{children:[uu(e,c(e.deviceId),s),e.lastArtifact!==void 0&&n(a,{children:[` · `,d(`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:[d(`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 Eu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Du(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ou(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function ku(e){if(!Eu(e))return null;let t=Du(e,`ruleId`),n=Du(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=Du(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:Du(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Ou(e,`targetIds`)}}function Au(e){if(!Eu(e))return null;let t=Du(e,`conditionId`),n=Du(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function ju(e){if(!Eu(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(!Eu(t))continue;let e=Du(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(!Eu(t))continue;let e=Du(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 Mu(e){if(!Eu(e))return null;let t=Du(e,`recordId`),n=Du(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=ku(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Au(t);e!==null&&i.push(e)}let a=Du(e,`droppedBy`),o=ju(e.stateSummary);return{recordId:t,delivery:n,trigger:Du(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:Du(e,`still`)??`none`,notes:Ou(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function Nu(e){if(e.stateSummary!==void 0)return Pu(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 Pu(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 Fu({ruleId:e,ruleName:t,fallbackDeviceId:r,variant:i=`icon`,showResult:o=!1}){let s=m(),[c,f]=l(null),[p,h]=l(null),g=u({mutationFn:async()=>Mu(await s.trpcClient.addons.custom.mutate({addonId:Ql,action:eu,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.`)}),_=c===null?p===null?void 0:p:Nu(c);return n(a,{children:[n(z,{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?d(V,{className:`h-3.5 w-3.5 animate-spin`}):d(Te,{className:`h-3.5 w-3.5`}),i===`full`&&`Test now`]}),o&&p!==null&&d(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:p}),o&&c!==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:[d(`p`,{className:`text-foreground`,children:Nu(c)}),c.planNotes.map(e=>n(`p`,{className:`flex gap-1.5`,children:[d(me,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),d(`span`,{children:e.note})]},e.conditionId)),c.notes.map(e=>n(`p`,{children:[`· `,e]},e))]})]})}t();var Iu=[`notificationRules`,`listSnoozes`],Lu=3e4;function Ru(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function zu(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 Bu({rules:e}){let t=m(),a=s(),o=i({queryKey:Iu,refetchInterval:Lu,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),c=u({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>a.invalidateQueries({queryKey:Iu})}),l=r(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),f=Date.now(),p=(o.data??[]).filter(e=>f>=e.startedAt&&f<e.expiresAt);return n(B,{className:`p-4`,children:[n(`div`,{className:`flex items-center gap-2 mb-3`,children:[d(I,{className:`h-4 w-4 text-foreground-subtle`}),d(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),p.length===0&&d(`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.`}),d(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:p.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:[d(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:l.get(e.ruleId??``)??`A rule`}),e.global&&d(U,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&d(U,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&d(U,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,zu(Ru(e,f))]})]}),d(z,{size:`sm`,variant:`outline`,disabled:c.isPending,onClick:()=>c.mutate(e.id),children:`End now`})]},e.id))})]})}var Vu={days:[0,1,2,3,4,5,6],minute:480},Hu=[{value:1,label:`Mon`},{value:2,label:`Tue`},{value:3,label:`Wed`},{value:4,label:`Thu`},{value:5,label:`Fri`},{value:6,label:`Sat`},{value:0,label:`Sun`}];function Uu(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Wu(e){let[t,n]=e.split(`:`),r=Number(t)*60+Number(n);return Number.isFinite(r)?Math.max(0,Math.min(1439,r)):0}function Gu(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 Ku(e){let t=Object.entries(e).map(([e,t])=>`${e} ${String(t)}`);return t.length>0?`Left out by this rule's filters or a camera mute: ${t.join(`, `)}.`:null}function qu(e,t,n,r=`rule`){if(e===`error`)return Gu(n)===`NOT_FOUND`?{lines:[`This hub does not serve summary rules yet — update @camstack/server first. A rule saved now would be stored without its summary, and stay instant.`]}:{lines:[`The preview could not be read: ${n instanceof Error?n.message:String(n)}`]};if(e!==`success`||t===void 0)return null;let i=[];if(r===`section`&&t.split===void 0&&i.push(`This hub does not send per-category summaries yet — update @camstack/server first. Until then it sends one message.`),t.empty)i.push(`Nothing to report right now — no notification would be sent.`);else if(t.split===`section`&&t.rows!==void 0){let e=t.rows.length;i.push(`${String(e)} notification${e===1?``:`s`} would be sent now, one per category:`);for(let e of t.rows)i.push(`${e.title}\n${e.text}`)}else i.push(`${String(t.count)} item(s) would be sent now:\n${t.text}`);let a=Ku(t.dropped);return a!==null&&i.push(a),t.excludedGroups.includes(`backups-exports`)&&i.push(`Backups and exports are completed jobs, not a state — they are not in a summary.`),{lines:i}}function Ju(e,t){return{...e,schedule:t}}function Yu(e,t){let{split:n,...r}=e;return t===`section`?{...r,split:t}:r}function Xu({value:e,family:t,onChange:r,draft:i}){if(t===void 0||!yt.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:[d(`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:[d(`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:[d(`input`,{type:`radio`,name:`system-event-delivery`,checked:a!==null,onChange:()=>r({mode:`summary`,schedule:pt([Vu])}),"data-testid":`rule-delivery-summary`}),`Summary on schedule — the current state, at set times`]})]}),a!==null&&d(Zu,{value:a,onChange:r,draft:i})]})}function Zu({value:e,onChange:t,draft:r}){let i=at(e.schedule),o=e.schedule.timezone,s=n=>{n.length!==0&&t(Ju(e,pt(n,o)))},c=jt({systemEventDelivery:e});return n(`div`,{className:`mt-2 space-y-2`,children:[n(`p`,{className:J,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: `,o??`the hub’s`,`.`]}),i===null?n(a,{children:[d(`p`,{className:J,"data-testid":`rule-delivery-custom`,children:`Custom schedule: the summary is sent when each window below ENDS.`}),d(Wc,{value:e.schedule,onChange:n=>{n!==void 0&&t(Ju(e,n))}})]}):n(a,{children:[i.map((e,t)=>d(Qu,{time:e,onChange:e=>s(i.map((n,r)=>r===t?e:n)),onRemove:i.length>1?()=>s(i.filter((e,n)=>n!==t)):void 0,index:t},t)),n(`button`,{type:`button`,onClick:()=>s([...i,Vu]),className:`flex items-center gap-1 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground`,"data-testid":`rule-delivery-add-time`,children:[d(w,{className:`h-3 w-3`}),` Add a send time`]})]}),n(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[d(`legend`,{className:`sr-only`,children:`How the summary is sent`}),n(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-summary-split`,checked:c===`rule`,onChange:()=>t(Yu(e,`rule`)),"data-testid":`rule-delivery-split-rule`}),`One message with every category`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-summary-split`,checked:c===`section`,onChange:()=>t(Yu(e,`section`)),"data-testid":`rule-delivery-split-section`}),`One notification per category (batteries, consumables, devices…)`]})]}),d($u,{draft:r,split:c})]})}function Qu({time:e,index:t,onChange:r,onRemove:i}){let a=t=>{let n=e.days.includes(t)?e.days.filter(e=>e!==t):[...e.days,t];n.length!==0&&r({...e,days:n})};return n(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[n(`div`,{className:`flex items-center gap-2 text-xs`,children:[d(`span`,{className:`text-foreground-subtle`,children:`Send at`}),d(`input`,{type:`time`,value:Uu(e.minute),onChange:t=>r({...e,minute:Wu(t.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`,"data-testid":`rule-delivery-time-${String(t)}`}),d(`span`,{className:`flex-1`}),i!==void 0&&d(`button`,{type:`button`,onClick:i,"aria-label":`Remove send time`,className:`text-foreground-subtle hover:text-danger`,children:d(g,{className:`h-3.5 w-3.5`})})]}),d(`div`,{className:`flex flex-wrap gap-1`,children:Hu.map(t=>d(`button`,{type:`button`,onClick:()=>a(t.value),className:`rounded px-1.5 py-0.5 text-[10px] ${e.days.includes(t.value)?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:t.label},t.value))})]})}function $u({draft:e,split:t}){let r=m(),i=u({mutationFn:e=>r.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),a=qu(i.status,i.data,i.error,t);return n(`div`,{className:`space-y-1.5`,children:[d(z,{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&&d(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:a.lines.map((e,t)=>d(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function ed(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:ad(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var td=6e4,nd=60*td,rd=24*nd;function id(e,t){return e===1?`the last ${t}`:`the last ${String(e)} ${t}s`}function ad(e){return e===null?`No delivery on record`:e>=rd?`Not in ${id(Math.floor(e/rd),`day`)}`:e>=nd?`Not in ${id(Math.floor(e/nd),`hour`)}`:e>=td?`Not in ${id(Math.floor(e/td),`minute`)}`:`Not in the window read`}function od(e){return{state:Yn(e),devices:e.data}}t();var sd=[`notificationRules`,`listRules`],cd=[`notificationOutput`,`listTargets`,`forRules`],ld=[`notificationRules`,`getConditionCatalog`],ud=[`deviceManager`,`gateableDevices`],dd=De.options;function fd({onSimulateRule:e,onOpenHistory:t}={}){let a=m(),{t:o}=W(),[s,c]=l({mode:`closed`}),[f,p]=l(`all`),h=i({queryKey:sd,queryFn:async()=>(await a.trpcClient.notificationRules.listRules.query({})).rules}),g=i({queryKey:cd,queryFn:()=>a.trpcClient.notificationOutput.listTargets.query({})}),_=i({queryKey:ld,queryFn:()=>a.trpcClient.notificationRules.getConditionCatalog.query({})}),v=_e({projection:`slim`}),y=Bl(),b=r(()=>v.data??[],[v.data]),x=od(v),S=r(()=>b.map(e=>e.id),[b]),C=i({queryKey:[...ud,S],enabled:S.length>0,queryFn:async()=>{let e=[];for(let t of b){let n=Pe(await a.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),dd);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),T=r(()=>{let e=Rt(b);return b.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))},[b]),E=r(()=>b.filter(e=>e.type===ke.Camera).map(e=>({id:e.id,name:e.name})),[b]),D=hn(r(()=>E.map(e=>e.id),[E])),O=r(()=>{let e=new Map(E.map(e=>[e.id,e.name]));return D.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})))},[D.results,E]),k=r(()=>{let e=new Map;for(let t of g.data??[])e.set(t.id,t.name);return e},[g.data]),A=u({mutationFn:e=>a.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void h.refetch()}),j=u({mutationFn:e=>a.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void h.refetch()}),M=Xl(),N=h.data??[],P=r(()=>{let e=new Map;for(let t of Xa)e.set(t.key,N.filter(e=>Le(e,t.key)).length);return e},[N]),ee=Za(P),F=ee.find(e=>e.key===f)??Xa[0],ne=r(()=>N.filter(e=>Le(e,F.key)).toSorted((e,t)=>e.name.localeCompare(t.name)),[N,F.key]),re=$a(F.key),I=e=>{Qa(e)&&c({mode:`form`,rule:e})};return n(G,{icon:ae,title:`Notification Rules`,subtitle:F.blurb,actions:F.creatable?n(z,{size:`sm`,type:`button`,onClick:()=>c({mode:`form`,rule:null,seed:Ze(F.key)}),children:[d(w,{className:`h-3.5 w-3.5`}),F.newRuleLabel]}):void 0,children:[d(Ce,{value:F.key,onValueChange:e=>p(Je(e)??f),children:d(xe,{className:`mb-3`,children:ee.map(e=>n(te,{value:e.key,children:[e.label,d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:P.get(e.key)??0})]},e.key))})}),d(Bu,{rules:N}),h.isLoading&&d(`div`,{className:`flex items-center justify-center py-16`,children:d(V,{className:`h-6 w-6 animate-spin text-primary`})}),h.isError&&!h.isLoading&&d(L,{title:`Failed to load rules`,message:h.error instanceof Error?h.error.message:`Unknown error`,onRetry:()=>void h.refetch()}),!h.isLoading&&!h.isError&&ne.length===0&&d(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:F.emptyHint}),ne.length>0&&d(B,{children:d(ge,{columns:re?vd({targetNameById:k,snoozes:M,deletePending:j.isPending,onToggle:(e,t)=>A.mutate({ruleId:e.id,enabled:t}),onOpen:I,t:o,onDuplicate:e=>I({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>j.mutate(e.id),lastRunOf:e=>ed(y,e),...t?{onOpenHistory:t}:{}}):hd({targetNameById:k,snoozes:M,deletePending:j.isPending,onToggle:(e,t)=>A.mutate({ruleId:e.id,enabled:t}),onOpen:I,t:o,onDuplicate:e=>I({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>j.mutate(e.id),...e?{onTest:e}:{},lastRunOf:e=>ed(y,e),...t?{onOpenHistory:t}:{}}),rows:ne,rowKey:e=>e.id,onRowClick:I,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),s.mode===`form`&&d(yd,{rule:s.rule,...s.seed?{seed:s.seed}:{},targets:g.data??[],actuatable:T,fleet:x,catalog:Ps(_.data?.catalog??[]),taxonomy:_.data?.taxonomy,cameras:E,gateable:C.data??[],gateableScenes:O,onCancel:()=>c({mode:`closed`}),onSaved:()=>{c({mode:`closed`}),h.refetch()}})]})}function pd(e,t){return e.replaceAll(`{{name}}`,t)}function md({children:e,className:t}){return d(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function hd(e){return[{key:`name`,header:`Rule`,render:t=>n(`span`,{className:`flex items-center gap-2`,children:[Qa(t)?d(md,{children:d(`button`,{type:`button`,onClick:()=>e.onOpen(t),className:`truncate rounded text-left text-sm font-medium text-foreground hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:t.name})}):d(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name}),!t.enabled&&d(U,{variant:`warning`,children:`disabled`})]})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:e=>n(`span`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`text-[11px] text-foreground-subtle`,children:qa(e.delivery)}),!Ya(e.delivery)&&d(U,{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 d(`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=>d(Hl,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:e.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:t=>d(md,{children:d(Zl,{rule:t,snoozes:e.snoozes,exempt:ps(t.conditions,t.actions?.onTrigger??[])})})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>d(md,{children:d(P,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>Qa(t)?n(md,{className:`flex items-center justify-end gap-1`,children:[d(Fu,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&d(Ul,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&d(z,{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:d(pe,{className:`h-3.5 w-3.5`})}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:d(x,{className:`h-3.5 w-3.5`})}),d(_d,{rule:t,deps:e})]}):d(gd,{rule:t,deps:e})}]}function gd({rule:e,deps:t}){return n(md,{className:`flex items-center justify-end gap-1`,children:[d(`span`,{title:Qe(Ae(e)).blurb,children:d(U,{variant:`warning`,children:`Recreate as one rule per family`})}),t.onOpenHistory&&d(Ul,{rule:e,onOpenHistory:t.onOpenHistory}),d(_d,{rule:e,deps:t})]})}function _d({rule:e,deps:t}){let{t:n}=W(),r=Se(),i=async()=>{await r({title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:pd(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`),variant:`danger`})&&t.onConfirmDelete(e)};return d(`button`,{type:`button`,title:n(`common.delete`,`Delete`),"aria-label":pd(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),disabled:t.deletePending,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void i(),children:d(g,{className:`h-3.5 w-3.5 text-danger`})})}function vd(e){let t=hd(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Yo(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Xo(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 d(`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=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:ro(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function yd({rule:e,seed:t,targets:o,catalog:s,taxonomy:c,cameras:f,gateable:p,gateableScenes:h,actuatable:g,fleet:_,onSaved:v,onCancel:b}){let x=m(),{t:S}=W(),C=e!=null&&e.id.length>0,[w]=l(()=>e?ys(e):vs(t?.delivery,t?.conditions)),[T,E]=l(w),[D,O]=l(null),[k,A]=l(null),[N,ee]=l(Ks),F=e=>E(t=>({...t,...e})),ne=e?zs(e):void 0,re=u({mutationFn:async()=>{let t=Bs(T,ne,s);if(C&&e){let n=Vs(T,s);await x.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await x.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:v,onError:e=>O(e instanceof Error?e.message:`Save failed`)}),I=u({mutationFn:async()=>{let e=Bs(T,ne,s);return(await x.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>A(null),onSuccess:e=>A(e),onError:e=>O(e instanceof Error?e.message:`Test failed`)}),ie=T.targetIds.map(e=>o.find(t=>t.id===e)?.name??e),L=e=>F({targetIds:T.targetIds.includes(e)?T.targetIds.filter(t=>t!==e):[...T.targetIds,e]}),oe=i({queryKey:[`userManagement`,`listUsers`],queryFn:()=>x.trpcClient.userManagement.listUsers.query()}).data,se=e=>F({targetUsers:T.targetUsers.includes(e)?T.targetUsers.filter(t=>t!==e):[...T.targetUsers,e]}),ce=Ka.find(e=>e.value===T.delivery)?.hint,ue=bs(T),de=Re(T.delivery),fe=Ae(T),B=Qe(fe),me=$e(fe),he=Mt(fe),ge=i({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,he??[]],enabled:he!==null,queryFn:async()=>{let e=await Promise.all((he??[]).map(e=>x.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),_e=r(()=>{if(he===null||ge.data===void 0)return g;let e=ge.data,t=new Set(ns(T.deviceScope));return g.filter(n=>e.has(n.id)||t.has(n.id))},[g,he,ge.data,T.deviceScope]),ve=he!==null&&ge.isLoading,ye=he!==null&&ge.isError,be=Hi(),Se=e=>({family:`rule`,field:e,kind:fe,delivery:T.delivery,...Cs(T)?{systemEventDelivery:`summary`}:{},...T.conditions.systemEvent?{systemEventKinds:[...T.conditions.systemEvent.kinds]}:{}}),we=e=>be.data?Ri(be.data,Se(e)):void 0,Te=Gs(T),Ee=ps(T.conditions,T.actions.sequences),De=T.conditions.identities!==void 0||T.conditions.plates!==void 0,Oe=Us(T.delivery,T.conditions),ke=Oe.some(e=>e.key===N)?N:Ks;return Ya(T.delivery)?d(le,{open:!0,onOpenChange:e=>!e&&b(),children:n(M,{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:[d(ae,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:C?`Edit ${e?.name}`:`New notification rule`})]}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:b,children:`Cancel`})]}),D&&d(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:D}),C&&e&&n(`div`,{className:`shrink-0 mb-3 space-y-2`,children:[d(Cu,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),d(Tu,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??`camera ${String(e)}`})]}),n(Ce,{value:ke,onValueChange:e=>ee(qs(e)??N),className:`flex min-h-0 flex-1 flex-col`,children:[d(xe,{className:`mb-3 shrink-0`,children:Oe.map(e=>d(te,{value:e.key,children:e.label},e.key))}),n(j,{className:`pr-1`,children:[n(R,{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:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),d(y,{value:T.name,onChange:e=>F({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:[d(P,{checked:T.enabled,onCheckedChange:e=>F({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),d(H,{value:T.delivery,onChange:e=>{let t=Ja(e.target.value);t&&E(e=>Ts(e,t))},options:Ka.map(e=>({value:e.value,label:e.label}))}),ce&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:ce})]}),!C&&me!==void 0&&d(_l,{family:me,onChange:e=>E(t=>Os(t,e))}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),o.length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery targets configured. Add one under the Targets tab first.`}):d(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:o.map(e=>n(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[d(`input`,{type:`checkbox`,checked:T.targetIds.includes(e.id),onChange:()=>L(e.id),className:`accent-primary`}),d(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&d(U,{variant:`warning`,children:`disabled`})]},e.id))})]}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(oe??[]).length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No users to notify.`}):d(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:(oe??[]).map(e=>n(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[d(`input`,{type:`checkbox`,checked:T.targetUsers.includes(e.id),onChange:()=>se(e.id),className:`accent-primary`}),d(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&d(U,{variant:`info`,children:`admin`})]},e.id))}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Delivers to the targets each user owns, only for cameras that user can access.`})]})]}),n(R,{value:`devices`,className:`space-y-4`,children:[ve&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:S(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),ye&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:S(`notificationRules.devices.compatFailed`,`Couldn't check which devices this rule's kind can use — every device is listed. The hub still refuses an incompatible one on save.`)}),d(Jc,{devices:_e,scope:T.deviceScope,onChange:e=>F({deviceScope:e}),listState:_.state,savedScope:w.deviceScope,exceptOffered:_s(s,`devicesExclude`,T)})]}),d(R,{value:`actions`,className:`space-y-4`,children:d(ca,{value:T.actions,onChange:e=>F({actions:e}),devices:g,devicesState:_.state})}),n(R,{value:`advanced`,className:`space-y-4`,children:[d(Ml,{catalog:s,delivery:T.delivery,conditions:T.conditions,onConditionsChange:e=>F({conditions:e})}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown (seconds)`}),d(y,{type:`number`,min:0,max:no,step:1,value:String(T.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=io(e.target.value);t!==void 0&&F({cooldownSec:t})}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[de?`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(no),` (24 hours).`]})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown counted`}),d(H,{value:T.cooldownScope,onChange:e=>{let t=oo(e.target.value);t!==void 0&&F({cooldownScope:t})},options:ao.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),d(`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:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Across object classes`}),d(H,{value:T.cooldownGranularity??`per-class`,onChange:e=>F({cooldownGranularity:co(e.target.value)}),options:so.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),d(`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.`})]})]}),T.delivery===`immediate`?n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(P,{checked:T.waitForEnhancement,onCheckedChange:e=>F({waitForEnhancement:e}),"aria-label":`wait for recognition`,disabled:!De}),`Wait for the face or plate before notifying`]}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:De?`A notification’s text is fixed when it is queued, and a face is only confirmed several seconds into the visit (11 s is typical here) — so an immediate notification cannot carry a name. ON: this rule stays silent until the visit ends, then sends ONE notification with the name. OFF: it notifies at once without the name, and sends a SECOND, follow-up notification if a name lands before the visit ends. Waiting also makes the rule read the WHOLE visit: its zone condition then matches every zone the subject passed through, and a “left a zone” condition can no longer match.`:`Only applies once this rule scopes to known faces or known plates — there is nothing to wait for otherwise.`})]}):null,n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(P,{checked:T.snoozeAllowGlobal,onCheckedChange:e=>F({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:Ee}),`Anyone may snooze this rule for everyone`]}),d(`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.`})]}),!Ee&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),n(a,{children:[d(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:ls.map(e=>{let t=T.snoozeOptions??cs,n=t.includes(e);return d(z,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>F({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:us(e)},e)})}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:T.snoozeOptions===void 0?`Not set — the notification offers the defaults (${cs.map(us).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.`:T.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.`}),T.snoozeOptions!==void 0&&d(z,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>F({snoozeOptions:void 0}),children:`Back to the defaults`})]})]}),C&&e&&!Ee&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Silence it now`}),d(Kl,{ruleId:e.id,ruleName:e.name,exempt:Ee,variant:`full`})]})]}),n(R,{value:`notification`,className:`space-y-4`,children:[n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),d(H,{value:String(T.priority),onChange:e=>F({priority:Number(e.target.value)}),options:Eo.map(e=>({value:String(e.value),label:e.label}))})]}),!B.carriesMedia&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`}),B.carriesMedia&&fe===`sensor`&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:S(`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.`)}),B.carriesMedia&&fe!==`sensor`&&B.mediaBlurb!==void 0&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:B.mediaBlurb}),B.carriesMedia&&fe!==`sensor`&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),d(H,{value:T.mediaAttach,onChange:e=>{let t=uo(e.target.value);t&&F({mediaAttach:t})},options:lo.map(e=>({value:e.value,label:e.label}))}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:lo.find(e=>e.value===T.mediaAttach)?.description}),n(`div`,{className:`mt-2 space-y-1`,children:[B.carriesSubjectCrop&&n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:T.mediaZoneCrop,onChange:e=>F({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:[d(`input`,{type:`checkbox`,checked:T.mediaGif,onChange:e=>F({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:[d(`input`,{type:`checkbox`,checked:T.mediaClip,onChange:e=>F({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(T.mediaGif||T.mediaClip)&&n(`div`,{className:`mt-2`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),d(H,{value:T.mediaProfile??``,onChange:e=>F({mediaProfile:_o(e.target.value)}),options:go.map(e=>({value:e.value,label:e.label}))}),d(`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.`}),d(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),d(H,{value:T.mediaClipSpeed===void 0?``:String(T.mediaClipSpeed),onChange:e=>F({mediaClipSpeed:ko(e.target.value)}),options:Oo.map(e=>({value:e.value,label:e.label}))}),d(`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.`})]})]}),fe===`sensor`&&B.carriesMedia&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Linked cameras`}),d(H,{value:T.mediaLinkedCameras??``,onChange:e=>F({mediaLinkedCameras:ho(e.target.value)}),options:mo.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`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.`})]}),B.carriesMedia&&fe!==`sensor`&&B.carriesSubjectCrop&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),d(H,{value:T.mediaFrame??``,onChange:e=>F({mediaFrame:po(e.target.value)}),options:fo.map(e=>({value:e.value,label:e.label}))}),d(`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:[d(qi,{label:`Notification title`,value:T.templateTitle,onChange:e=>F({templateTitle:e}),vars:we(`title`),testId:`rule-template-title`}),d(qi,{label:`Notification body`,value:T.templateBody,onChange:e=>F({templateBody:e}),vars:we(`body`),multiline:!0,testId:`rule-template-body`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank for the hub's own wording (editable on the Texts tab).`}),Ss(T)!==null&&d(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:Ss(T)}),d(Ji,{context:Se(`body`),title:T.templateTitle,body:T.templateBody,testId:`rule-template-preview`})]})]}),n(R,{value:`conditions`,className:`space-y-4`,children:[n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:de?`Which system events`:Ws(T.conditions)??`Conditions`}),T.conditions.audio!==void 0&&d(`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).`}),T.conditions.occupancy!==void 0&&d(`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.`}),de&&d(`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?d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):d(vl,{catalog:Cs(T)?s.filter(e=>e.id!==`schedule`):s,taxonomy:c,delivery:T.delivery,conditions:T.conditions,classScope:T.classScope,onClassScopeChange:e=>F({classScope:e}),onTrigger:T.actions.sequences,savedConditions:w.conditions,schedule:T.schedule,deviceIds:gs(T),zoneCameraIds:Ac(T.deviceScope,f),cameras:f,fleet:_,allDevices:g,gateable:p,gateableScenes:h,onConditionsChange:e=>F({conditions:e}),onScheduleChange:e=>F({schedule:e})})]}),de&&d(Xu,{value:T.systemEventDelivery,family:me,onChange:e=>F({systemEventDelivery:e}),draft:()=>Bs(T,ne,s)}),C&&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:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test this rule for real`}),d(Fu,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...gs(T)[0]===void 0?{}:{fallbackDeviceId:gs(T)[0]}})]}),d(`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.`})]}),!de&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),n(z,{size:`sm`,variant:`outline`,type:`button`,disabled:I.isPending||!ws(T),onClick:()=>{O(null),I.mutate()},children:[I.isPending?d(V,{className:`h-3.5 w-3.5 animate-spin`}):d(pe,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),k!==null&&d(xd,{delivery:T.delivery,results:k,targetNames:ie})]})]})]})]}),Te.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 `,Te.length,` condition`,Te.length===1?``:`s`,` this kind of rule cannot use:`]}),Te.map(e=>n(`p`,{children:[d(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),ue.length>0&&d(`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:ue.map(e=>d(`p`,{children:e},e))}),n(`div`,{className:`flex shrink-0 justify-end gap-2 mt-4`,children:[d(z,{variant:`secondary`,size:`sm`,type:`button`,onClick:b,children:`Cancel`}),n(z,{size:`sm`,type:`button`,disabled:re.isPending||!ws(T),onClick:()=>{O(null),re.mutate()},children:[re.isPending&&d(V,{className:`h-3.5 w-3.5 animate-spin`}),C?`Save changes`:`Create rule`]})]})]})}):d(bd,{rule:e,onCancel:b})}function bd({rule:e,onCancel:t}){let r=Object.keys(e?.conditions??{});return d(le,{open:!0,onOpenChange:e=>!e&&t(),children:n(M,{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:[d(ae,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),d(U,{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 `,d(`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:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),d(`dd`,{className:`text-foreground`,children:e?.delivery})]}),n(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),d(`dd`,{className:`text-foreground`,children:e?.enabled?`yes`:`no`})]}),n(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),d(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),n(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),d(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):`none`})]})]}),d(`div`,{className:`flex justify-end gap-2 mt-4`,children:d(z,{variant:`secondary`,size:`sm`,type:`button`,onClick:t,children:`Close`})})]})})}function xd({delivery:e,results:t,targetNames:r}){if(e===`device-event`)return d(`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 d(`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.`]}),d(`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?d(A,{className:`h-3.5 w-3.5 shrink-0 text-success`}):d(ee,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),n(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),d(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`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))})]})}var Sd=[{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 Cd(e){return Sd.find(t=>t.value===e)?.value}function wd(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Td(e){return``}var Ed={x:.25,y:.25,w:.5,h:.5},Dd={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Od(){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:Ed,occupancy:Dd,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function kd(e){return e.deviceId!==null}function Ad(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function jd(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Md(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 Nd(e){if(e.deviceId===null)return null;let t=e.trigger,n=jd(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:Pd(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 Pd(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 Fd(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Id(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 Ld(e){let t=Od(),n=e.conditions,r=Id(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:Fd(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Fd(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Fd(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:Td(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Rd(n.occupancy)},onlyRuleId:e.id}}function Rd(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 zd(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 Bd(e){return{form:Ld(e),caveats:zd(e),ruleName:e.name}}var Vd=null;function Hd(e){Vd=e}function Ud(){return Vd}function Wd(){Vd=null}var Gd=[`n/a`,`clear`,`suppressed`,`bypassed`],Kd=[`live`,`none`,`unavailable`,`unattachable`];function qd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jd(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Yd(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Xd(e){if(!qd(e))return null;let t=Jd(e,`ruleId`),n=Jd(e,`ruleName`),r=Jd(e,`cooldown`),i=Gd.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Jd(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Yd(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:Yd(e,`targetIds`)}}function Zd(e){if(!qd(e))return null;let t=Jd(e,`recordId`),n=Jd(e,`delivery`),r=Jd(e,`still`),i=Kd.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=Xd(e);t!==null&&o.push(t)}let s=Jd(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Yd(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Qd(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 $d=new Set([`sensor`,`control`,`custom`]);function ef({form:e,cameras:t,taxonomy:r,kinds:i,kindsLoading:a,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=Ke(`classes`,r);if(e.trigger===`device-event`)return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),d(tf,{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:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[d(`label`,{className:q,children:`Audio classes`}),d(Ga,{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:[d(`label`,{className:q,children:`Zones`}),d(nc,{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:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),d(nf,{form:e,cameras:t,taxonomy:r,onPatch:o})]}):n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[d(`label`,{className:q,children:`Detected classes`}),c===null?d(Zs,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):d(Qs,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),n(`div`,{children:[d(`label`,{className:q,children:`Zones the subject is in`}),d(nc,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&n(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),d(H,{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 tf({form:e,kinds:t,loading:r,onPatch:i}){let o=t.filter(e=>$d.has(e.category)),s=o.find(t=>t.kind===e.sensorKind);return n(a,{children:[n(`div`,{children:[d(`label`,{className:q,children:`Event kind`}),d(H,{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&&d(`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:[d(`label`,{className:q,children:`Source device`}),d(y,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>i({sourceDeviceId:Ad(e.target.value)??null})}),d(`p`,{className:J,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:[d(`label`,{className:q,children:`Event type token`}),d(y,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>i({eventType:e.target.value})}),d(`p`,{className:J,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 nf({form:e,cameras:t,taxonomy:r,onPatch:i}){let o=e.deviceId===null?[]:[e.deviceId],s=Ke(`occupancy`,r),c=s===null?[]:s.groups.flatMap(e=>e.options),l=e.occupancy,u=e=>i({occupancy:{...l,...e}});return n(a,{children:[n(`div`,{children:[d(`label`,{className:q,children:`Zone`}),d(nc,{deviceIds:o,cameras:t,value:l.zoneId===``?[]:[l.zoneId],onChange:e=>u({zoneId:e[e.length-1]??``})}),d(`p`,{className:J,children:`Leave empty for the whole frame.`})]}),n(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:q,children:`Class`}),d(H,{value:l.className,options:[{value:``,label:`— any class —`},...c.map(e=>({value:e.value,label:e.label}))],onChange:e=>u({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`,d(y,{type:`number`,min:0,className:`w-20`,value:String(l.count),onChange:e=>u({count:Ad(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,d(y,{type:`number`,min:0,className:`w-20`,value:String(l.previousCount),onChange:e=>u({previousCount:Ad(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,d(y,{type:`number`,min:1,className:`w-20`,value:String(l.threshold),onChange:e=>u({threshold:Ad(e.target.value)??1})})]}),n(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[d(P,{checked:l.occupied,onCheckedChange:e=>u({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function rf({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:[d(`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:[d(P,{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:[d(`div`,{className:`max-w-[12rem]`,children:d(H,{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`})})}),d(nc,{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:[d(P,{checked:e.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),d(`p`,{className:J,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&d(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,d(y,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:n=>r({bbox:{...e.bbox,[t]:Ad(n.target.value)??0}})})]},t))})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[d(`label`,{className:q,children:`Happened at`}),n(`div`,{className:`flex items-center gap-2`,children:[d(y,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:Md(Date.now())}),children:`Set`}):d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:`Now`})]}),d(`p`,{className:J,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:[d(`label`,{className:q,children:`Detection source`}),d(H,{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 af({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:[d(P,{checked:e,onCheckedChange:a,"aria-label":t}),t,i&&d(U,{variant:`danger`,children:`actuates devices`})]}),d(`p`,{className:J,children:r})]})}t();var of={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.`},sf={"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 cf({result:e,targetName:t}){return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[d(`p`,{className:`text-xs font-medium text-foreground`,children:Qd(e)}),n(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[d(lf,{recordId:e.recordId}),n(`span`,{children:[`delivery `,d(`span`,{className:`text-foreground`,children:e.delivery})]}),n(`span`,{children:[`candidates `,d(`span`,{className:`text-foreground`,children:e.candidates})]}),n(`span`,{title:of[e.still],children:[`still `,d(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&n(U,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&d(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>d(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`No rule was evaluated. Either no enabled rule declares the`,` `,d(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>d(uf,{outcome:e,targetName:t},e.ruleId))})]})}function lf({recordId:e}){let[t,r]=l(!1);return n(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[d(`code`,{className:`text-[10px] text-foreground`,children:e}),d(z,{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:d(x,{className:`h-3 w-3`})}),t&&d(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function uf({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?d(A,{className:`h-3.5 w-3.5 shrink-0 text-success`}):d(ee,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),n(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:sf[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&d(`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`,` `,d(`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 df=`pipeline-analytics`,ff=`nc.injectTestEvent`;function pf(){let e=m(),[t,a]=l(()=>Ud()?.form??Od()),[o]=l(()=>Ud()?.caveats??[]),[s]=l(()=>Ud()?.ruleName??null);f(()=>Wd(),[]);let[c,p]=l(null),[h,g]=l(!1),[_,v]=l(null),b=e=>a(t=>({...t,...e})),x=_e({projection:`slim`}),S=i({queryKey:ld,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),C=i({queryKey:sd,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),w=i({queryKey:cd,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),T=t.deviceId,E=i({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:T}],enabled:T!==null,staleTime:6e4,queryFn:async()=>T===null?[]:(await e.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[T]})).flatMap(e=>[...e.kinds])}),D=r(()=>(x.data??[]).filter(e=>e.type===ke.Camera).map(e=>({id:e.id,name:e.name})),[x.data]),O=S.data?.taxonomy,k=E.data??[],A=r(()=>{let e=new Map;for(let t of w.data??[])e.set(t.id,t.name);return e},[w.data]),j=u({mutationFn:async()=>{let n=Nd(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:df,action:ff,input:n})},onMutate:()=>{p(null),g(!1),v(null)},onSuccess:e=>{let t=Zd(e);p(t),g(t===null)},onError:e=>v(e instanceof Error?e.message:`The simulation failed.`)}),M=wd(t.trigger),N=C.data?.find(e=>e.id===t.onlyRuleId);return n(G,{icon:pe,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:[x.isError&&d(L,{title:`Failed to load cameras`,message:x.error instanceof Error?x.error.message:`Unknown error`,onRetry:()=>void x.refetch()}),s!==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 `,d(`span`,{className:`font-medium`,children:s}),`. Only that rule will be evaluated — clear "Evaluate only one rule" below to run the whole rule set.`]}),o.length>0&&d(`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:[d(me,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),d(`span`,{children:e.note})]},e.conditionId))}),n(B,{className:`space-y-4`,children:[n(`div`,{children:[d(`label`,{className:q,children:`Camera`}),d(H,{"data-testid":`simulate-camera`,value:t.deviceId===null?``:String(t.deviceId),options:[{value:``,label:D.length===0?`Loading cameras…`:`— pick a camera —`},...D.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{b({deviceId:Ad(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),d(`p`,{className:J,children:`The camera the event is attributed to — what a notification shows.`})]}),n(`div`,{children:[d(`label`,{className:q,children:`Trigger`}),d(H,{"data-testid":`simulate-trigger`,value:t.trigger,options:Sd.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=Cd(e.target.value);if(!n)return;let r=Td(t.trigger);b({trigger:n,source:t.source===``||t.source===r?Td(n):t.source})}}),n(`p`,{className:J,children:[Sd.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,d(`span`,{className:`text-foreground`,children:M}),` are candidates.`]})]}),d(ef,{form:t,cameras:D,taxonomy:O,kinds:k,kindsLoading:E.isLoading,onPatch:b}),n(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[d(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),n(`div`,{className:`mt-2 space-y-3`,children:[d(`p`,{className:J,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:[d(`label`,{className:q,children:`Label (identity name / plate / subclass)`}),d(y,{value:t.label,placeholder:`e.g. Marco, AB123CD`,onChange:e=>b({label:e.target.value})})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[d(`label`,{className:q,children:`Detection confidence`}),d($s,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>b({confidence:e})})]}),n(`div`,{children:[d(`label`,{className:q,children:`Label-match confidence`}),d($s,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>b({labelConfidence:e})})]}),n(`div`,{children:[d(`label`,{className:q,children:`Importance`}),d($s,{value:t.importance,min:0,max:1,step:.05,onChange:e=>b({importance:e})})]}),n(`div`,{children:[d(`label`,{className:q,children:`Dwell (seconds)`}),d($s,{value:t.dwellSeconds,min:0,step:1,onChange:e=>b({dwellSeconds:e})})]})]})]})]}),d(rf,{form:t,cameras:D,onPatch:b}),n(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),d(af,{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=>b({bypassCooldown:e})}),d(af,{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=>b({bypassMute:e})}),d(af,{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=>b({runActions:e})}),n(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:q,children:`Still image`}),d(H,{value:t.still,options:[{value:`live`,label:`Live snapshot of the camera`},{value:`none`,label:`No image`}],onChange:e=>b({still:e.target.value===`none`?`none`:`live`})})]}),n(`div`,{children:[d(`label`,{className:q,children:`Evaluate only one rule`}),d(H,{value:t.onlyRuleId,options:[{value:``,label:`— every enabled rule —`},...(C.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>b({onlyRuleId:e.target.value})}),t.onlyRuleId.length>0&&N===void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,d(`code`,{children:t.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),_!==null&&d(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),n(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[d(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`}),n(z,{size:`sm`,type:`button`,disabled:j.isPending||!kd(t),onClick:()=>j.mutate(),children:[j.isPending?d(V,{className:`h-3.5 w-3.5 animate-spin`}):d(pe,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),h&&d(`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.`}),c!==null&&d(cf,{result:c,targetName:e=>A.get(e)??e})]})}var X=`block text-[11px] font-medium text-foreground mb-1`,Z=`mt-1 text-[10px] text-foreground-subtle`;function mf({title:e,hint:t,children:r}){return n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),d(`div`,{className:`space-y-3`,children:r})]})}function hf({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:[d(me,{className:`h-3.5 w-3.5`}),`This rule could never produce anything, so it cannot be saved:`]}),d(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>d(`li`,{children:e},e))})]})}function gf({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:[d(he,{className:`h-3.5 w-3.5`}),`Worth knowing:`]}),d(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>d(`li`,{children:e},e))})]})}function _f({cameras:e,value:t,onChange:r,fleet:i,hint:a}){return n(`div`,{className:`space-y-1`,children:[d(Pa,{devices:e,listState:i.state,fleet:i,value:t,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),a!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function vf({targets:e,value:t,onChange:r}){let i=e=>r(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return e.length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery target is configured. Add one on the Targets tab first — without one the artefact is rendered and thrown away.`}):d(`div`,{className:`divide-y divide-border rounded-md border border-border`,"data-testid":`digest-targets`,children:e.map(e=>n(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover`,children:[d(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>i(e.id),className:`accent-primary`,"data-testid":`digest-target-${e.id}`}),d(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&d(U,{variant:`warning`,children:`disabled`})]},e.id))})}function Q({label:e,value:t,onChange:r,min:i,max:a,step:o,hint:s,emptyPlaceholder:c,testId:l,disabled:u=!1}){return n(`div`,{children:[d(`label`,{className:X,children:e}),d(y,{type:`number`,value:t===void 0?``:String(t),disabled:u,...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&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function yf({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:[d(P,{checked:t,onCheckedChange:r,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),i!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:i})]})}function bf({title:e,body:t,onTitleChange:r,onBodyChange:i,family:a,testIdPrefix:o}){let s=Hi(),c=e=>s.data?Ri(s.data,{family:a,field:e}):void 0;return n(`div`,{className:`space-y-2`,children:[d(qi,{label:`Notification title`,value:e,onChange:r,vars:c(`title`),testId:`${o}-title`}),d(qi,{label:`Notification body`,value:t,onChange:i,vars:c(`body`),multiline:!0,testId:`${o}-body`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank to use the hub's own wording (editable on the Texts tab).`}),d(Ji,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function xf({open:e,ruleName:t,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){return e?d(le,{open:!0,onOpenChange:e=>!e&&s(),children:d(M,{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:[d(Te,{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.`]}),d(`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:[d(z,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),d(z,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?`Sending…`:`Produce and send`})]})]})})}):null}function Sf(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 Cf=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function wf(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Tf(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>Cf[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${wf(t.startMinute)}–${wf(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function Ef(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${Sf(Math.round(r/1e3))} ago`}function Df(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Of(e){return Array.isArray(e)?`[${e.map(Of).join(`,`)}]`:Df(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${Of(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function kf(e,t){return Of(e)===Of(t)}function Af(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,jf=`nc.getTexts`,Mf=`nc.setLanguage`,Nf=`nc.setTextOverrides`,Pf={en:`English`,it:`Italiano`};function Ff(e){return e===`en`||e===`it`}function If(e){return e===`override`||e===`shipped`||e===`fallback`}function Lf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rf(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 zf(e){if(!Lf(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`||!Ff(r)||!If(o)||i!==null&&typeof i!=`string`)return null;let s=Rf(e.placeholders),c=Rf(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 Bf(e){if(!Lf(e))return null;let{language:t,activeLanguage:n}=e;if(!Ff(t)||!Ff(n))return null;let r=Rf(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Ff(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=zf(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Vf(e,t){return t.get(e.key)??e.override??e.shipped}function Hf(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 Uf(e,t){return Object.keys(Hf(e,t)).length}function Wf(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 Gf(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Kf(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 qf=`nc.listSummaryRules`,Jf=`nc.upsertSummaryRule`,Yf=`nc.deleteSummaryRule`,Xf=`nc.testSummaryRule`,Zf=3600,Qf=86400,$f=3600,ep=3600,tp=3*36e5,np=[`importance`,`recency`,`dwell`],rp={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},ip=[`none`,`tiles`,`all`],ap=`none`,op={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},sp=[`en`,`it`],cp=[`deliver-without-text`,`skip`],lp=2048,up=2e3;function dp(e){return e.window.kind!==`unsupported`&&!e.readOnly}function fp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pp(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 mp(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 hp(e){if(e!==void 0)return typeof e==`string`?e:null}function gp(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function _p(e){return np.some(t=>t===e)}function vp(e){return e===void 0?ap:ip.find(t=>t===e)??null}function yp(e){if(!fp(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!fp(n))return null;let e=pp(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=hp(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 bp(e){if(!fp(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=yp(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 xp(e){if(e==null)return;if(!fp(e))return null;let t=e.classes===void 0?void 0:mp(e.classes),n=e.classesExclude===void 0?void 0:mp(e.classesExclude),r=e.zones===void 0?void 0:mp(e.zones);if(t===null||n===null||r===null)return null;let i=gp(e.minImportance),a=gp(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 Sp(e){if(e==null)return;if(!fp(e))return null;let t=hp(e.title),n=hp(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function Cp(e){return sp.some(t=>t===e)}function wp(e){return cp.some(t=>t===e)}function Tp(e){if(e==null)return;if(!fp(e)||typeof e.enabled!=`boolean`)return null;let t=hp(e.profileId),n=hp(e.prompt);if(t===null||n===null)return null;let r=gp(e.maxImagePx),i=gp(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!Cp(a))return null;let o=e.onFailure;return o!==void 0&&!wp(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 Ep(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!fp(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!fp(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function Dp(e){if(!fp(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`||!_p(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=pp(e.deviceIds),u=bp(e.window),d=Ep(e.targets);if(l===null||u===null||d===null)return null;let f=xp(e.filters),p=Sp(e.template);if(f===null||p===null)return null;let m=hp(e.captionText),h=gp(e.generatedAt),g=gp(e.updatedAt);if(m===null||h===null||g===null)return null;let _=vp(e.captions);if(_===null)return null;let v=Tp(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 Op(e){if(!fp(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=Dp(n);if(e===null)return null;t.push(e)}return t}function kp(e){if(!fp(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=gp(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=gp(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=hp(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 Ap(){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:ap,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function jp(e){let t=Ap(),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 Mp(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Np(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 Pp(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 Fp(e){return Af(e.targetIds)}function Ip(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 Lp(e){let t=Np(e),n=Pp(e),r=Ip(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:Mp(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Fp(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 Rp(e,t){let n=Lp(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),kf(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),kf(n.window,t.window)||(r.window=n.window),kf(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),kf(n.targets,t.targets)||(r.targets=n.targets),kf(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),kf(n.ai,t.ai)||(r.ai=n.ai??null),r}function zp(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 ${Zf}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${Qf}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 ${$f}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 ${ep}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 ${up} 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 ${lp} 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 Bp(e){return zp(e).length===0}function Vp(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 Hp=[{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`]}],Up=`rule`;function Wp(e){return Hp.find(t=>t.key===e)?.key}function Gp(e){return e.kind===`motion`?`Motion · ${Sf(e.quietSeconds)} quiet · max ${Sf(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${Tf(e.schedule)}`}function Kp(e,t){return Ef(e,t,`Never run`)}function qp(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 ≥ ${Sf(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function Jp(e){return{windowStartMs:e-tp,windowEndMs:e}}t();var Yp={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},Xp={en:`English`,it:`Italiano`};function Zp(e){return np.find(t=>t===e)}function Qp(e){return ip.find(t=>t===e)}function $p(e){return sp.find(t=>t===e)??``}function em(e){return cp.find(t=>t===e)}function tm({rule:e,cameras:t,fleet:a,targets:o,taxonomy:s,onSaved:c,onCancel:f}){let p=m(),[h,g]=l(()=>e===null?Ap():jp(e)),[_,v]=l(null),[b,x]=l(Up),S=e=>g(t=>({...t,...e})),C=r(()=>{let e=Ke(`occupancy`,s);return e===null?[]:e.groups.flatMap(e=>e.options)},[s]),{options:w,loading:T}=Va(h.deviceIds,t.map(e=>({id:e.id,name:e.name}))),E=i({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>p.trpcClient.llm.listProfiles.query({}),retry:!1}),D=(E.data??[]).filter(e=>e.supportsVision),O=u({mutationFn:async()=>{let t=e===null?{rule:Lp(h)}:{ruleId:e.id,patch:Rp(h,e)};await p.trpcClient.addons.custom.mutate({addonId:$,action:Jf,input:t})},onSuccess:c,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),k=Hi(),A=k.data?Ri(k.data,{family:`summary`,field:`captionText`}):void 0,N=h.mosaicCaptions===`all`,P=zp(h),ee=Vp(h),F=Bp(h)&&!O.isPending,ne=Hp.some(e=>e.key===b)?b:Up;return d(le,{open:!0,onOpenChange:e=>!e&&f(),children:n(M,{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:[d(_n,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:e===null?`New summary`:`Edit ${e.name}`})]}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:f,children:`Cancel`})]}),_!==null&&d(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&d(Cu,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),d(hf,{problems:P,testId:`summary-problems`}),d(gf,{warnings:ee,testId:`summary-warnings`})]}),n(Ce,{value:ne,onValueChange:e=>x(Wp(e)??b),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[d(xe,{className:`mb-3 shrink-0`,children:Hp.map(e=>d(te,{value:e.key,children:e.label},e.key))}),n(j,{className:`pr-1`,children:[n(R,{value:`rule`,className:`space-y-3`,children:[d(mf,{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:[d(`label`,{className:X,children:`Name`}),d(y,{value:h.name,onChange:e=>S({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),d(`div`,{className:`pb-1.5`,children:d(yf,{label:`Enabled`,checked:h.enabled,onChange:e=>S({enabled:e}),testId:`summary-enabled`})})]})}),d(mf,{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:d(_f,{cameras:t,value:h.deviceIds,fleet:a,onChange:e=>S({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})})]}),d(R,{value:`window`,className:`space-y-3`,children:n(mf,{title:`When the window closes`,children:[n(`div`,{children:[d(`label`,{className:X,children:`Window`}),d(H,{value:h.windowKind,options:[{value:`motion`,label:`Motion — opened and closed by activity`},{value:`schedule`,label:`Schedule — fixed weekly windows`}],onChange:e=>S({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:[d(Q,{label:`Quiet period (seconds)`,value:h.quietSeconds,min:30,max:Zf,onChange:e=>S({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`}),d(Q,{label:`Longest window (seconds)`,value:h.maxWindowSeconds,min:60,max:Qf,onChange:e=>S({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:[d(`label`,{className:X,children:`Weekly windows`}),d(Wc,{value:h.schedule,onChange:e=>S({schedule:e})}),d(`p`,{className:Z,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.`})]}),d(Q,{label:`Wait for open tracks (seconds)`,value:h.barrierSeconds,min:0,max:$f,onChange:e=>S({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`})]})}),d(R,{value:`content`,className:`space-y-3`,children:n(mf,{title:`What goes in`,hint:`Evaluated on tracks: one passage is one tile.`,children:[n(`div`,{children:[d(`label`,{className:X,children:`Classes`}),d(Ga,{options:C,value:h.classes,onChange:e=>S({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),d(`p`,{className:Z,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:[d(`label`,{className:X,children:`Excluded classes`}),d(Ga,{options:C,value:h.classesExclude,onChange:e=>S({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),n(`div`,{children:[d(`label`,{className:X,children:`Zones`}),d(Ga,{options:w,value:h.zones,onChange:e=>S({zones:e}),loading:T,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),d(`p`,{className:Z,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:[d(Q,{label:`Minimum importance`,value:h.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>S({minImportance:e}),hint:`The pipeline's own score, 0–1. Empty keeps everything.`,testId:`summary-min-importance`}),d(Q,{label:`Minimum stay (seconds)`,value:h.minDwellSeconds,min:0,max:ep,emptyPlaceholder:`any`,onChange:e=>S({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]}),d(yf,{label:`Include parked objects`,checked:h.includeStationary,onChange:e=>S({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`})]})}),d(R,{value:`mosaic`,className:`space-y-3`,children:n(mf,{title:`The mosaic`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(Q,{label:`Tiles`,value:h.maxTiles,min:1,max:24,onChange:e=>S({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:[d(`label`,{className:X,children:`When there are more tracks than tiles`}),d(H,{value:h.rank,options:np.map(e=>({value:e,label:rp[e]})),onChange:e=>{let t=Zp(e.target.value);t!==void 0&&S({rank:t})},"data-testid":`summary-rank`}),d(`p`,{className:Z,children:`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`})]})]}),n(`div`,{children:[d(`label`,{className:X,children:`Text on the mosaic`}),d(H,{value:h.mosaicCaptions,options:ip.map(e=>({value:e,label:op[e]})),onChange:e=>{let t=Qp(e.target.value);t!==void 0&&S({mosaicCaptions:t})},"data-testid":`summary-captions`}),d(`p`,{className:Z,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:[d(qi,{label:`Caption burned onto the mosaic`,value:h.captionText,disabled:!N,onChange:e=>S({captionText:e}),placeholder:`Leave empty for no caption`,vars:A,testId:`summary-caption`}),d(`p`,{className:Z,children:N?`Across the top band.`:`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`})]})]})}),d(R,{value:`ai`,className:`space-y-3`,children:n(mf,{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:[d(yf,{label:`Have a model describe the window`,checked:h.aiEnabled,onChange:e=>S({aiEnabled:e}),hint:`Off by default. The mosaic and the counts are delivered either way.`,testId:`summary-ai-enabled`}),!h.aiEnabled&&d(`p`,{className:`rounded-md border border-border bg-surface px-2.5 py-1.5 text-[10px] text-foreground-muted`,"data-testid":`summary-ai-off-note`,children:`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:[d(`label`,{className:X,children:`Vision profile`}),d(H,{value:h.aiProfileId,disabled:!h.aiEnabled,options:[{value:``,label:`The hub's default vision profile`},...D.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>S({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),d(`p`,{className:Z,children:E.isError?`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`:D.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:[d(`label`,{className:X,children:`Answer in`}),d(H,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:`Don’t ask for a language`},...sp.map(e=>({value:e,label:Xp[e]}))],onChange:e=>S({aiLanguage:$p(e.target.value)}),"data-testid":`summary-ai-language`}),d(`p`,{className:Z,children:`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`})]})]}),n(`div`,{children:[d(`label`,{className:X,children:`Your question (optional)`}),d(`textarea`,{value:h.aiPrompt,rows:3,maxLength:up,disabled:!h.aiEnabled,onChange:e=>S({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`}),d(`p`,{className:Z,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:[d(Q,{label:`Frames the model may look at`,value:h.maxAiImages,min:1,max:8,disabled:!h.aiEnabled,onChange:e=>S({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`}),d(Q,{label:`Time limit (seconds)`,value:h.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!h.aiEnabled,onChange:e=>S({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:[d(Q,{label:`Frame size sent (pixels)`,value:h.aiMaxImagePx,min:64,max:lp,emptyPlaceholder:`448`,disabled:!h.aiEnabled,onChange:e=>S({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:[d(`label`,{className:X,children:`If the model gives no answer`}),d(H,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:cp.map(e=>({value:e,label:Yp[e]})),onChange:e=>{let t=em(e.target.value);t!==void 0&&S({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),d(`p`,{className:Z,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.`})]})]})]})}),d(R,{value:`delivery`,className:`space-y-3`,children:n(mf,{title:`Delivery`,children:[d(vf,{targets:o,value:h.targetIds,onChange:e=>S({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(Q,{label:`Priority`,value:h.priority,min:1,max:5,onChange:e=>S({priority:e??3}),testId:`summary-priority`}),d(yf,{label:`Deliver a window that matched nothing`,checked:h.deliverEmpty,onChange:e=>S({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`})]}),d(bf,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>S({templateTitle:e}),onBodyChange:e=>S({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),n(`p`,{className:Z,children:[d(`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:[d(z,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:`Cancel`}),n(z,{size:`sm`,type:`button`,disabled:!F,onClick:()=>O.mutate(),children:[O.isPending&&d(V,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}t();var nm=[`notificationSummaries`,`listSummaryRules`],rm=`One window, one picture: every camera’s best moments as a single mosaic.`;function im(){let e=m(),[t,a]=l({mode:`closed`}),[o,s]=l(null),[c,f]=l(null),[p,h]=l(null),[g,_]=l(!1),v=i({queryKey:nm,queryFn:async()=>{let t=Op(await e.trpcClient.addons.custom.mutate({addonId:$,action:qf,input:{}}));return _(t===null),t}}),y=_e({projection:`slim`}),b=r(()=>(y.data??[]).filter(e=>e.type===ke.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[y.data]),x=i({queryKey:cd,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),S=i({queryKey:ld,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),C=u({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Jf,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void v.refetch()}),T=u({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Yf,input:{ruleId:t}}),onSuccess:()=>{s(null),v.refetch()}}),E=u({mutationFn:async t=>kp(await e.trpcClient.addons.custom.mutate({addonId:$,action:Xf,input:{ruleId:t,...Jp(Date.now())}})),onSuccess:e=>{f(null),h(e)}}),D=v.data??[],O=(x.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),k=new Map(O.map(e=>[e.id,e.name])),A=n(z,{size:`sm`,type:`button`,onClick:()=>a({mode:`form`,rule:null}),"data-testid":`summary-new`,children:[d(w,{className:`h-3.5 w-3.5`}),`New summary`]});return v.isLoading?d(G,{icon:_n,title:`Summaries`,subtitle:rm,children:d(V,{className:`h-5 w-5 animate-spin`})}):v.isError||v.data===null?d(G,{icon:_n,title:`Summaries`,subtitle:rm,children:d(L,{title:`Summary rules are 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 summary rules yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime.`})}):n(G,{icon:_n,title:`Summaries`,subtitle:rm,actions:A,children:[T.isError&&d(L,{title:`Could not delete the rule`,message:String(T.error)}),E.isError&&d(L,{title:`The test run failed`,message:String(E.error)}),p!==null&&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:[p.error===void 0?n(`span`,{children:[`Produced `,p.produced,` digest`,p.produced===1?``:`s`,` — `,p.tiles??0,` tile`,(p.tiles??0)===1?``:`s`,` from `,p.cameras??0,` camera`,(p.cameras??0)===1?``:`s`,`, `,p.matched??0,` track`,(p.matched??0)===1?``:`s`,` matched, `,p.enqueued??0,` `,`notification`,(p.enqueued??0)===1?``:`s`,` sent.`,(p.droppedStationary??0)>0&&n(`span`,{"data-testid":`summary-test-dropped-stationary`,children:[` `,p.droppedStationary,` parked object`,p.droppedStationary===1?``:`s`,` left out.`]})]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,p.error]}),d(z,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>h(null),children:`Dismiss`})]}),D.length===0?d(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,"data-testid":`summary-empty`,children:`No summary rules yet — create one, and every window it covers arrives as a single picture.`}):d(B,{children:d(ge,{columns:am({nowMs:Date.now(),targetNameById:k,confirmDeleteId:o,deletePending:T.isPending,onToggle:(e,t)=>C.mutate({ruleId:e.id,enabled:t}),onEdit:e=>{dp(e)&&a({mode:`form`,rule:e})},onTest:f,onAskDelete:s,onConfirmDelete:e=>T.mutate(e.id)}),rows:D,rowKey:e=>e.id,minWidthPx:860,bordered:!1,mobileMode:`scroll`,maxBodyHeight:oe})}),t.mode===`form`&&d(tm,{rule:t.rule,cameras:b,fleet:od(y),targets:O,taxonomy:S.data?.taxonomy,onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),v.refetch()}}),d(xf,{open:c!==null,ruleName:c?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${c?.targets.length??0} target${(c?.targets.length??0)===1?``:`s`}`,pending:E.isPending,onCancel:()=>f(null),onConfirm:()=>{c!==null&&E.mutate(c.id)}})]})}function am(e){return[{key:`name`,header:`Digest`,render:e=>n(`span`,{className:`flex flex-wrap items-center gap-2`,children:[d(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&d(U,{variant:`warning`,children:`disabled`}),!dp(e)&&d(U,{variant:`warning`,children:`read-only`}),e.ai?.enabled===!0&&d(U,{variant:`info`,children:`AI`}),e.ai!==void 0&&!e.ai.enabled&&d(U,{variant:`default`,children:`AI off`})]})},{key:`cameras`,header:`Cameras`,align:`center`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:`Window`,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Gp(e.window)})},{key:`filters`,header:`Keeps`,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:qp(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 d(`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=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:Kp(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>d(P,{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(`span`,{className:`flex items-center justify-end gap-1`,children:[d(z,{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:d(pe,{className:`h-3.5 w-3.5`})}),d(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:!dp(t),onClick:()=>e.onEdit(t),"aria-label":`edit ${t.name}`,"data-testid":`summary-edit-${t.id}`,children:d(re,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?n(`span`,{className:`flex items-center gap-1`,children:[d(z,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),"data-testid":`summary-delete-confirm-${t.id}`,children:`Delete`}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):d(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onAskDelete(t.id),"aria-label":`delete ${t.name}`,"data-testid":`summary-delete-${t.id}`,children:d(g,{className:`h-3.5 w-3.5`})})]})}]}var om=e=>typeof e==`string`&&e.length>0;function sm(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 cm(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function lm(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];om(i)&&n.push({mediaType:r,url:i})}return n}function um(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=om(r.label),i=om(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 dm(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=lm(e,t.attachmentUrls),i=um(e,t.actions),a=e.ttl&&om(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:cm(e,t.format),priority:fm(t.priority),...om(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&om(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&om(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...om(t.tag)?{tag:t.tag}:{}}}function fm(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function pm(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 mm(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var hm={image:p(`/addon/notifiers/samples/image`),video:p(`/addon/notifiers/samples/video`),gif:p(`/addon/notifiers/samples/gif`),audio:p(`/addon/notifiers/samples/audio`),icon:p(`/addon/notifiers/samples/icon`)};function gm(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function _m(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])gm(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function vm(e,t,n){let r=mm(e);return gm(e,t)?{...r,body:n,attachmentUrls:{[t]:hm[t]}}:{...r,body:n}}function ym(e,t){let n=mm(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return vm(e,`image`,`Test notification with an image.`);case`gif`:return vm(e,`gif`,`Test notification with an animation.`);case`video`:return vm(e,`video`,`Test notification with a video.`);case`audio`:return vm(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=pm(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 bm={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},xm=`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,Sm=`block text-[11px] font-medium text-foreground mb-1`;function Cm({target:e,kind:t,open:i,onClose:a}){let o=m(),s=r(()=>sm(t.caps),[t.caps]),c=r(()=>_m(t.caps),[t.caps]),[f,p]=l(()=>mm(t.caps)),[h,g]=l(null),_=r(()=>dm(t.caps,f),[t.caps,f]),v=f.body.length,y=v>s.bodyMaxLen,b=e=>p(t=>({...t,...e})),x=u({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:dm(t.caps,f)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:`Test failed`})}),C=e=>{p(ym(t.caps,e)),g(null)},w=(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 d(le,{open:i,onOpenChange:e=>!e&&a(),children:n(M,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[d(E,{children:n(k,{children:[`Test "`,e.name,`" (`,t.label,`)`]})}),n(j,{className:`space-y-4 pr-1`,children:[d(`div`,{className:`flex flex-wrap gap-1.5`,children:c.map(e=>d(z,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>C(e),children:bm[e]},e))}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.levels.length>0&&n(`div`,{children:[d(`label`,{className:Sm,children:`Level`}),n(`select`,{className:xm,value:f.level,onChange:e=>b({level:e.target.value}),children:[d(`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&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),n(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&d(U,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&d(U,{variant:`info`,children:`silent`}),e.flags?.noPush&&d(U,{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:Sm,children:[`Priority (ordinal): `,f.priority]}),d(`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:[d(`label`,{className:Sm,children:`Format`}),d(`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:[d(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:f.format===e,onChange:()=>b({format:e})}),e]},e))})]}),n(`div`,{children:[d(`label`,{className:Sm,children:`Title`}),d(`input`,{className:xm,value:f.title,onChange:e=>b({title:e.target.value})})]}),n(`div`,{children:[n(`label`,{className:Sm,children:[`Body`,` `,n(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,s.bodyMaxLen,y?` — overflow`:``,`)`]})]}),d(`textarea`,{className:`${xm} 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:Sm,children:[`Attachments`,` `,n(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,s.attachmentMode,`, max `,s.attachmentMax,s.attachmentMaxBytes?`, ≤${Math.round(s.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),d(`div`,{className:`space-y-1.5`,children:s.attachmentSlots.map(e=>n(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),d(`input`,{className:xm,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:Sm,children:[`Actions (up to `,s.maxActions,`)`]}),d(`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:[d(`input`,{className:xm,placeholder:`label`,value:f.actions[t]?.label??``,onChange:e=>w(t,`label`,e.target.value)}),d(`input`,{className:xm,placeholder:`url`,value:f.actions[t]?.url??``,onChange:e=>w(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:[d(`label`,{className:Sm,children:`Click URL`}),d(`input`,{className:xm,value:f.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),s.showSound&&n(`div`,{children:[d(`label`,{className:Sm,children:`Sound`}),d(`input`,{className:xm,value:f.sound,onChange:e=>b({sound:e.target.value})})]}),s.showTtl&&n(`div`,{children:[d(`label`,{className:Sm,children:`TTL (seconds)`}),d(`input`,{className:xm,type:`number`,value:f.ttl,onChange:e=>b({ttl:e.target.value})})]}),s.showTag&&n(`div`,{children:[d(`label`,{className:Sm,children:`Tag`}),d(`input`,{className:xm,value:f.tag,onChange:e=>b({tag:e.target.value})})]})]}),h&&d(wm,{result:h}),n(`details`,{className:`text-[10px]`,children:[d(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),d(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),n(S,{children:[d(z,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),n(z,{size:`sm`,type:`button`,disabled:x.isPending||f.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?d(V,{className:`h-3.5 w-3.5 animate-spin`}):d(Te,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function wm({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?d(A,{className:`h-3.5 w-3.5 text-success`}):d(ee,{className:`h-3.5 w-3.5 text-danger`}),d(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&d(`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:[d(`dt`,{children:`Resolved level`}),d(`dd`,{className:`text-foreground`,children:t.level}),d(`dt`,{children:`Format sent`}),d(`dd`,{className:`text-foreground`,children:t.format}),d(`dt`,{children:`Attachments sent`}),d(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),d(`dt`,{children:`Actions sent`}),d(`dd`,{className:`text-foreground`,children:t.actionsSent}),d(`dt`,{children:`Truncated`}),d(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),d(`dt`,{children:`Dropped`}),d(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function Tm(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 Em(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 Dm(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}function Om(e,t,n){let r=new Set(n),i={};for(let[n,a]of Object.entries(e)){if(!r.has(n)){i[n]=a;continue}a==null||a===``||a!==t[n]&&(i[n]=a)}return i}function km(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))r[t]=n.has(t)?``:i;return r}var Am=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function jm(e){return Am.some(t=>e.includes(t))}function Mm(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function Nm(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&Mm(e[n])!==Mm(t[n]))}function Pm(e,t,n,r){if(r===void 0)return Nm(e,t,n);let i=new Set(n),a=Om(e,t,n);return r.filter(n=>i.has(n)?n in a:Mm(e[n])!==Mm(t[n]))}function Fm(e,t,n){let r=Om(e,t,n);return n.filter(e=>!(e in r))}function Im(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:Im(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Im(e.fields,t)}))}:e)}function Lm(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:Im(e.fields,n)}))}}function Rm({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:[d(`p`,{className:`font-semibold`,children:`The hub needs the secret again — nothing was saved.`}),d(`p`,{className:`mt-1`,children:e}),i===null?null:d(`p`,{className:`mt-1 font-medium`,children:i})]})}t();var zm=[`notificationOutput`,`listTargets`],Bm=[`notificationOutput`,`listTargetKinds`],Vm=[`userManagement`,`listUsers`],Hm=`ownerUserId`;function Um(e){let t=e.config[Hm];return typeof t==`string`&&t.length>0?t:null}function Wm(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:[d(`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:d(Gm,{kind:r,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),d(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name}),!t.enabled&&d(U,{variant:`warning`,children:`disabled`})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByKey.get(t.kind)?.label??t.kind})},{key:`owner`,header:`Owner`,nowrap:!0,render:t=>{let n=Um(t);return n===null?d(U,{variant:`default`,children:`system`}):d(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>d(P,{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(`span`,{className:`flex items-center justify-end gap-1`,children:[d(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(t),title:`Test`,children:d(Te,{className:`h-3.5 w-3.5`})}),d(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onEdit(t,r),title:`Edit`,children:d(re,{className:`h-3.5 w-3.5`})}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:d(g,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function Gm({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?d(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):d(`span`,{className:n,children:e?.icon??`🔔`})}function Km(){let e=m(),[t,a]=l({mode:`closed`}),[o,s]=l(null),c=i({queryKey:zm,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),f=i({queryKey:Bm,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),p=r(()=>f.data??[],[f.data]),h=r(()=>{let e=new Map;for(let t of p)e.set(t.kind,t);return e},[p]),g=i({queryKey:Vm,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),_=r(()=>{let e=new Map;for(let t of g.data??[])e.set(t.id,t.username);return e},[g.data]),v=u({mutationFn:t=>e.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:t.target.addonId,targetId:t.target.id,enabled:t.enabled}),onSuccess:()=>void c.refetch()}),y=u({mutationFn:t=>e.trpcClient.notificationOutput.deleteTarget.mutate({addonId:t.addonId,targetId:t.id}),onSuccess:()=>void c.refetch()}),b=o?h.get(o.kind):void 0;return n(G,{icon:D,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(z,{size:`sm`,type:`button`,onClick:()=>a({mode:`pick-kind`}),children:[d(w,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[c.isLoading&&d(`div`,{className:`flex items-center justify-center py-16`,children:d(V,{className:`h-6 w-6 animate-spin text-primary`})}),c.isError&&!c.isLoading&&d(L,{title:`Failed to load targets`,message:c.error instanceof Error?c.error.message:`Unknown error`,onRetry:()=>void c.refetch()}),!c.isLoading&&!c.isError&&(c.data??[]).length===0&&d(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification targets yet. Click "Add target" to configure one.`}),(c.data??[]).length>0&&d(B,{children:d(ge,{columns:Wm({kindByKey:h,userNameById:_,onToggle:(e,t)=>v.mutate({target:e,enabled:t}),onTest:s,onEdit:(e,t)=>a({mode:`form`,kind:t,target:e}),onDelete:e=>y.mutate(e)}),rows:c.data??[],rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),t.mode===`pick-kind`&&d(qm,{kinds:p,onCancel:()=>a({mode:`closed`}),onPick:e=>a({mode:`form`,kind:e,target:null})}),t.mode===`form`&&d(Jm,{kind:t.kind,target:t.target,users:g.data??[],onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),c.refetch()}}),o&&b&&d(Cm,{target:o,kind:b,open:!0,onClose:()=>s(null)})]})}function qm({kinds:e,onPick:t,onCancel:i}){let a=r(()=>Tm(e),[e]);return n(B,{className:`p-4 space-y-4`,children:[n(`div`,{className:`flex items-center justify-between`,children:[d(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),a.length===0&&d(`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:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),d(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(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:[d(Gm,{kind:r,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),d(`span`,{className:`font-medium text-foreground`,children:r.label}),r.supportsDiscovery&&d(U,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${r.kind}`))})]},e.addonId))]})}function Jm({kind:e,target:t,users:i,onSaved:a,onCancel:o}){let s=m(),c=r(()=>Em(e.configSchema),[e.configSchema]),f=r(()=>t?.config??{},[t]),[p,h]=l(t?.name??e.label),[g,_]=l(()=>t?km(t.config,c):{}),[v,y]=l(null),[b,x]=l(null),[S,C]=l(null),[w,T]=l(t?Um(t)??``:``),E=u({mutationFn:()=>s.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:g}),onSuccess:e=>y(e),onError:e=>x(e instanceof Error?e.message:`Discovery failed`)}),D=u({mutationFn:()=>{let{[Hm]:n,...r}=Om(g,f,c),i=w===``?r:{...r,[Hm]:w},a={id:t?.id??`${e.kind}-${Date.now()}`,name:p,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:i};return s.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:a})},onSuccess:a,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;jm(t)?C(t):x(t)}}),O=r(()=>Dm(e.configSchema),[e.configSchema]),k=r(()=>t===null?[]:Pm(g,f,c,e.destinationKeys),[t,g,f,c,e.destinationKeys]),A=r(()=>t!==null&&(S!==null||k.length>0)?Fm(g,f,c):[],[t,S,k,g,f,c]),j=r(()=>Lm(e.configSchema,A),[e.configSchema,A]),M=e=>O.get(e)??e,N=e=>{h(e.suggestedName),_(t=>({...t,...e.config})),y(null)};return n(B,{className:`p-4 space-y-4`,children:[n(`div`,{className:`flex items-center justify-between`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[d(Gm,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),t?`Edit ${t.name}`:`Add ${e.label} target`]}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,children:`Cancel`})]}),b&&d(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-form-error`,children:b}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),d(`input`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,value:p,onChange:e=>h(e.target.value)})]}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),d(H,{value:w,options:[{value:``,label:`System (shared, admin-managed)`},...i.map(e=>({value:e.id,label:e.username}))],onChange:e=>T(e.target.value)}),d(`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.`})]}),e.supportsDiscovery&&n(`div`,{className:`space-y-2`,children:[n(z,{size:`sm`,variant:`outline`,type:`button`,disabled:E.isPending,onClick:()=>{x(null),E.mutate()},children:[E.isPending?d(V,{className:`h-3.5 w-3.5 animate-spin`}):d(ue,{className:`h-3.5 w-3.5`}),`Discover`]}),v&&v.length===0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),v&&v.length>0&&d(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:v.map((e,t)=>n(`button`,{type:`button`,onClick:()=>N(e),className:`flex w-full items-center justify-between px-3 py-1.5 text-xs hover:bg-surface-hover`,children:[d(`span`,{className:`text-foreground`,children:e.suggestedName}),d(`span`,{className:`text-[10px] text-primary`,children:`use`})]},`${e.suggestedName}-${t}`))})]}),c.length>0&&t&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Secret fields are hidden. Leave them blank to keep the stored value; type a new value to replace it.`}),d(Rm,{refusal:S,edited:k.map(M),reenter:A.map(M)}),d(ie,{schema:j,values:g,onChange:_}),n(`div`,{className:`flex justify-end gap-2`,children:[d(z,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:`Cancel`}),n(z,{size:`sm`,type:`button`,disabled:D.isPending||p.trim().length===0,onClick:()=>{x(null),C(null),D.mutate()},children:[D.isPending&&d(V,{className:`h-3.5 w-3.5 animate-spin`}),t?`Save changes`:`Create target`]})]})]})}t();var Ym=`notificationTexts`,Xm=`Every sentence the Notification Center can print — and your wording for it.`;function Zm({entry:e,value:t,busy:r,onChange:i,onReset:a}){let o=Kf(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:[d(`code`,{className:`text-xs font-medium`,children:e.key}),s?d(U,{variant:`info`,children:`customised`}):null,e.source===`fallback`?d(U,{variant:`warning`,children:`English fallback`}):null]}),n(`div`,{className:`flex items-start gap-2`,children:[d(`div`,{className:`flex-1`,children:d(qi,{label:``,value:t,onChange:i,vars:Gf(e),disabled:r,testId:`text-input-${e.key}`})}),d(z,{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:d(h,{className:`h-3.5 w-3.5`})})]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[d(`span`,{className:`font-medium`,children:`Shipped:`}),` `,d(`span`,{className:`font-mono`,children:e.shipped})]}),o===null?null:d(`p`,{className:`text-xs text-warning`,children:o})]})}function Qm(){let e=m(),t=s(),[a,o]=l(null),[c,f]=l(``),[p,h]=l(new Map),[g,_]=l(!1),v=i({queryKey:[Ym,a??`hub`],queryFn:async()=>{let t=Bf(await e.trpcClient.addons.custom.mutate({addonId:$,action:jf,input:a===null?{}:{language:a}}));return _(t===null),t}}),b=()=>{h(new Map),t.invalidateQueries({queryKey:[Ym]})},x=u({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Mf,input:{language:t}}),onSuccess:b}),S=u({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Nf,input:t}),onSuccess:b}),C=v.data??null,w=r(()=>C===null?[]:Wf(C.entries,c),[C,c]);if(v.isLoading)return d(G,{icon:vn,title:`Texts`,subtitle:Xm,children:d(V,{className:`h-5 w-5 animate-spin`})});if(v.isError||C===null)return d(G,{icon:vn,title:`Texts`,subtitle:Xm,children:d(L,{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 T=C.language,E=x.isPending||S.isPending,D=Hf(C.entries,p),O=Uf(C.entries,p),k=C.entries.filter(e=>e.override!==null).length,A=C.languages.map(e=>({value:e,label:Pf[e]})),j=(e,t)=>h(n=>new Map(n).set(e,t)),M=e=>j(e.key,e.shipped);return d(G,{icon:vn,title:`Texts`,subtitle:Xm,children:n(`div`,{className:`flex flex-col gap-4`,children:[x.isError?d(L,{title:`Could not change the language`,message:String(x.error)}):null,S.isError?d(L,{title:`Could not save`,message:String(S.error)}):null,n(B,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-6`,children:[n(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:`Hub language`}),d(`div`,{className:`w-44`,children:d(H,{value:C.activeLanguage,disabled:E,options:A,onChange:e=>{let t=e.target.value;Ff(t)&&x.mutate(t)},"data-testid":`texts-hub-language`})}),d(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),n(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:`Editing`}),d(`div`,{className:`w-44`,children:d(H,{value:T,disabled:E,options:A,onChange:e=>{let t=e.target.value;Ff(t)&&(h(new Map),o(t))},"data-testid":`texts-editing-language`})}),d(`p`,{className:`text-xs text-foreground-subtle`,children:T===C.activeLanguage?`${k} of ${C.entries.length} texts customised.`:`This hub does not speak this language — these words are not in use yet.`})]})]}),d(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:`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:[d(ue,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),d(y,{value:c,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(z,{className:`ml-auto`,disabled:E||O===0,onClick:()=>S.mutate({language:T,overrides:D}),"data-testid":`texts-save`,children:[E?d(V,{className:`h-3.5 w-3.5 animate-spin`}):null,O===0?`Save`:`Save ${O}`]})]}),d(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?d(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):w.map(e=>d(Zm,{entry:e,value:Vf(e,p),busy:E,onChange:t=>j(e.key,t),onReset:()=>M(e)},e.key))})]})})}var $m=`nc.listTimelapseRules`,eh=`nc.upsertTimelapseRule`,th=`nc.deleteTimelapseRule`,nh=`nc.testTimelapseRule`,rh=3600,ih=3600,ah=30,oh=1,sh=[`image`,`gif`],ch={image:`Still frame`,gif:`Short animation (GIF)`},lh=Ft({rules:It(Dt.extend({readOnly:Lt().optional()}))});function uh(e){let t=lh.safeParse(e);return t.success?t.data.rules:null}function dh(e){return e.readOnly!==!0}var fh=Ft({produced:Nt(),exportId:Pt().optional(),coveragePercent:Nt().optional(),enqueued:Nt().optional(),windowStartMs:Nt().optional(),windowEndMs:Nt().optional(),error:Pt().optional()});function ph(e){let t=fh.safeParse(e);return t.success?t.data:null}function mh(){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 hh(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 gh={windows:[{days:[1],startMinute:0,endMinute:60}]};function _h(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 vh(e){let t=_h(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??gh,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Af(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 yh(e,t){let n=vh(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),kf(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),kf(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??bh(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),kf(n.targets,t.targets)||(r.targets=n.targets),kf(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),kf(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function bh(e){return Math.max(oh,e/ah)}function xh(e,t,n){return t<=0||n<=0?0:e/t/n}function Sh(e,t){return e*t*_t}function Ch(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 ${rh}.`),(!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 ${_t}s and ${ih}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 wh(e){return Ch(e).length===0}function Th(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=Sh(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 Eh(e){return Tf(e)}function Dh(e,t){return Ef(e,t,`Never run`)}function Oh(e){return e.denseCadenceSec===void 0?{seconds:bh(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}t();var kh=7;function Ah(e){return sh.find(t=>t===e)}function jh({rule:e,cameras:t,fleet:r,targets:i,onSaved:o,onCancel:s}){let c=m(),[f,p]=l(()=>e===null?mh():hh(e)),[h,g]=l(null),_=e=>p(t=>({...t,...e})),v=Hi(),b=v.data?Ri(v.data,{family:`timelapse`,field:`previewText`}):void 0,x=u({mutationFn:async()=>{let t=e===null?{rule:vh(f)}:{ruleId:e.id,patch:yh(f,e)};await c.trpcClient.addons.custom.mutate({addonId:$,action:eh,input:t})},onSuccess:o,onError:e=>g(e instanceof Error?e.message:`Save failed`)}),S=Ch(f),C=Th(f),w=Oh(f),T=xh(kh,w.seconds,f.framerate),E=wh(f)&&!x.isPending;return d(le,{open:!0,onOpenChange:e=>!e&&s(),children:n(M,{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:[d(ce,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:e===null?`New timelapse`:`Edit ${e.name}`})]}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),h!==null&&d(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:h}),n(j,{className:`space-y-3 pr-1`,children:[e!==null&&d(Cu,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),d(hf,{problems:S,testId:`timelapse-problems`}),d(gf,{warnings:C,testId:`timelapse-warnings`}),d(mf,{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:[d(`label`,{className:X,children:`Name`}),d(y,{value:f.name,onChange:e=>_({name:e.target.value}),placeholder:`e.g. Timelapse ingresso`,"data-testid":`timelapse-name`})]}),d(`div`,{className:`pb-1.5`,children:d(yf,{label:`Enabled`,checked:f.enabled,onChange:e=>_({enabled:e}),testId:`timelapse-enabled`})})]})}),d(mf,{title:`Cameras`,children:d(_f,{cameras:t,value:f.deviceIds,fleet:r,onChange:e=>_({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.`})}),d(mf,{title:`When`,children:n(`div`,{children:[d(`label`,{className:X,children:`Weekly windows`}),d(Wc,{value:f.schedule,onChange:e=>_({schedule:e})}),d(`p`,{className:Z,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.`})]})}),n(mf,{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:[d(Q,{label:`Base cadence (seconds)`,value:f.cadenceSec,min:2,max:rh,onChange:e=>_({cadenceSec:e??0}),hint:`One frame every N seconds across the quiet parts of the window.`,testId:`timelapse-cadence`}),d(Q,{label:`Output frame rate (fps)`,value:f.framerate,min:1,max:60,onChange:e=>_({framerate:e??0}),hint:`How fast the assembled video plays.`,testId:`timelapse-framerate`})]}),n(`div`,{children:[d(`label`,{className:X,children:`Dense cadence, near the detections`}),n(`div`,{className:`flex items-center gap-2`,children:[d(H,{value:f.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:`Automatic (${w.seconds}s)`},{value:`explicit`,label:`Set it myself`}],onChange:e=>_({denseCadenceSec:e.target.value===`auto`?void 0:Oh(f).seconds}),"data-testid":`timelapse-dense-mode`}),f.denseCadenceSec!==void 0&&d(y,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(f.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&_({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),n(`p`,{className:Z,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,w.seconds,`s and `,f.framerate,` fps a`,` `,kh,`-second passage lasts `,T.toFixed(2),`s on screen; halving the cadence doubles that, and the quiet parts of the night do not change length.`,w.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 (${Oh({...f,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),d(Q,{label:`Minimum seconds of video per detection (optional)`,value:f.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>_({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`})]}),n(mf,{title:`The notification`,children:[d(vf,{targets:i,value:f.targetIds,onChange:e=>_({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[d(`label`,{className:X,children:`Preview`}),d(H,{value:f.previewMode,options:sh.map(e=>({value:e,label:ch[e]})),onChange:e=>{let t=Ah(e.target.value);t!==void 0&&_({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),d(Q,{label:`Priority`,value:f.priority,min:1,max:5,onChange:e=>_({priority:e??3}),testId:`timelapse-priority`})]}),n(`div`,{children:[d(qi,{label:`Caption on the preview frame`,value:f.previewTextSet?f.previewText:``,placeholder:`${ct} (shipped default)`,onChange:e=>_({previewText:e,previewTextSet:!0}),vars:b,testId:`timelapse-preview-text`}),n(`p`,{className:Z,children:[f.previewTextSet&&f.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${ct}).`,f.previewTextSet&&n(a,{children:[` `,d(`button`,{type:`button`,className:`underline`,onClick:()=>_({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),d(bf,{title:f.templateTitle,body:f.templateBody,onTitleChange:e=>_({templateTitle:e}),onBodyChange:e=>_({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`,` `,d(`code`,{children:`{{detectionSummary}}`}),`.`]})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[d(z,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),n(z,{size:`sm`,type:`button`,disabled:!E,onClick:()=>x.mutate(),children:[x.isPending&&d(V,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}t();var Mh=[`notificationTimelapses`,`listTimelapseRules`],Nh=`A night of recorded footage, assembled into one short video per camera.`;function Ph(){let e=m(),[t,a]=l({mode:`closed`}),[o,s]=l(null),[c,f]=l(null),[p,h]=l(null),[g,_]=l(!1),v=i({queryKey:Mh,queryFn:async()=>{let t=uh(await e.trpcClient.addons.custom.mutate({addonId:$,action:$m,input:{}}));return _(t===null),t}}),y=_e({projection:`slim`}),b=r(()=>(y.data??[]).filter(e=>e.type===ke.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[y.data]),x=i({queryKey:cd,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),S=u({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:eh,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void v.refetch()}),C=u({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:th,input:{ruleId:t}}),onSuccess:()=>{s(null),v.refetch()}}),T=u({mutationFn:async t=>ph(await e.trpcClient.addons.custom.mutate({addonId:$,action:nh,input:t})),onSuccess:e=>{f(null),h(e)}}),E=v.data??[],D=new Map(b.map(e=>[e.id,e.name])),O=(x.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),k=new Map(O.map(e=>[e.id,e.name]));return v.isLoading?d(G,{icon:ce,title:`Timelapses`,subtitle:Nh,children:d(V,{className:`h-5 w-5 animate-spin`})}):v.isError||v.data===null?d(G,{icon:ce,title:`Timelapses`,subtitle:Nh,children:d(L,{title:`Timelapse rules are 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 timelapse rules yet. Deploy addon-post-analysis and reload — the rules themselves are untouched.`})}):n(G,{icon:ce,title:`Timelapses`,subtitle:Nh,actions:n(z,{size:`sm`,type:`button`,onClick:()=>a({mode:`form`,rule:null}),"data-testid":`timelapse-new`,children:[d(w,{className:`h-3.5 w-3.5`}),`New timelapse`]}),children:[C.isError&&d(L,{title:`Could not delete the rule`,message:String(C.error)}),T.isError&&d(L,{title:`The test run failed`,message:String(T.error)}),p!==null&&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:[p.error===void 0?n(`span`,{children:[`Produced `,p.produced,` video`,p.produced===1?``:`s`,p.coveragePercent===void 0?``:` — ${Math.round(p.coveragePercent)}% of the window had footage`,`, `,p.enqueued??0,` notification`,(p.enqueued??0)===1?``:`s`,` sent.`]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,p.error]}),d(z,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>h(null),children:`Dismiss`})]}),E.length===0?d(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,"data-testid":`timelapse-empty`,children:`No timelapse rules yet — create one, and each night's recorded footage arrives as a short video.`}):d(B,{children:d(ge,{columns:Fh({nowMs:Date.now(),cameraNameById:D,targetNameById:k,confirmDeleteId:o,deletePending:C.isPending,onToggle:(e,t)=>S.mutate({ruleId:e.id,enabled:t}),onEdit:e=>a({mode:`form`,rule:e}),onTest:e=>f({rule:e,deviceId:e.deviceIds[0]??null}),onAskDelete:s,onConfirmDelete:e=>C.mutate(e.id)}),rows:E,rowKey:e=>e.id,minWidthPx:900,bordered:!1,mobileMode:`scroll`,maxBodyHeight:oe})}),t.mode===`form`&&d(jh,{rule:t.rule,cameras:b,fleet:od(y),targets:O,onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),v.refetch()}}),d(xf,{open:c!==null,ruleName:c?.rule.name??``,windowDescription:`its last closed window`,targetDescription:`${c?.rule.targets.length??0} target${(c?.rule.targets.length??0)===1?``:`s`}`,pending:T.isPending,confirmDisabled:c?.deviceId===null,extra:c===null?null:n(`div`,{children:[d(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Which camera`}),d(H,{value:c.deviceId===null?``:String(c.deviceId),options:c.rule.deviceIds.map(e=>({value:String(e),label:D.get(e)??`#${e}`})),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&f({rule:c.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>f(null),onConfirm:()=>{c!==null&&c.deviceId!==null&&T.mutate({ruleId:c.rule.id,deviceId:c.deviceId})}})]})}function Fh(e){return[{key:`name`,header:`Timelapse`,render:e=>n(`span`,{className:`flex flex-wrap items-center gap-2`,children:[d(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&d(U,{variant:`warning`,children:`disabled`}),!dh(e)&&d(U,{variant:`warning`,children:`read-only`})]})},{key:`cameras`,header:`Cameras`,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.deviceIds.length===1?e.cameraNameById.get(t.deviceIds[0]??-1)??`#${t.deviceIds[0]}`:`${t.deviceIds.length} cameras`})},{key:`schedule`,header:`Window`,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Eh(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let t=Oh(hh(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 d(`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=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:Dh(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>d(P,{checked:t.enabled,disabled:!dh(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(`span`,{className:`flex items-center justify-end gap-1`,children:[d(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:!dh(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:d(pe,{className:`h-3.5 w-3.5`})}),d(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:!dh(t),onClick:()=>e.onEdit(t),"aria-label":`edit ${t.name}`,"data-testid":`timelapse-edit-${t.id}`,children:d(re,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?n(`span`,{className:`flex items-center gap-1`,children:[d(z,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),"data-testid":`timelapse-delete-confirm-${t.id}`,children:`Delete`}),d(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):d(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:!dh(t),onClick:()=>e.onAskDelete(t.id),"aria-label":`delete ${t.name}`,"data-testid":`timelapse-delete-${t.id}`,children:d(g,{className:`h-3.5 w-3.5`})})]})}]}var Ih=`simulate`;function Lh(){let[e,t]=Bt();return d(`div`,{className:`flex flex-col p-4`,children:d(mn,{tabs:[{id:`targets`,label:`Targets`,icon:D,content:d(Km,{})},{id:`rules`,label:`Rules`,icon:ae,content:d(fd,{onSimulateRule:n=>{Hd(Bd(n));let r=new URLSearchParams(e);r.set(`tab`,Ih),t(r,{replace:!0})},onOpenHistory:n=>{t(_i(e,n.id),{replace:!0})}})},{id:Ih,label:`Simulate`,icon:pe,content:d(pf,{})},{id:di,label:`History`,icon:gn,content:d(Ei,{}),ownedParams:pi},{id:`alarm`,label:`Alarm`,icon:ve,content:d(li,{})},{id:`summaries`,label:`Summaries`,icon:_n,content:d(im,{})},{id:`timelapses`,label:`Timelapses`,icon:ce,content:d(Ph,{})},{id:`texts`,label:`Texts`,icon:vn,content:d(Qm,{})}]})})}export{Lh as NotificationsPage,Lh as default};