@camstack/addon-admin-ui 1.2.290 → 1.2.291

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 (104) hide show
  1. package/dist/assets/{AddonCollectionPage-D1pWGGvT.js → AddonCollectionPage-C9l7ftV0.js} +1 -1
  2. package/dist/assets/Addons-TAyselNK.js +1 -0
  3. package/dist/assets/{AdminTabs-DJBff_i8.js → AdminTabs-CDIoD5NP.js} +1 -1
  4. package/dist/assets/AiProfiles-Kf7NoHuq.js +3 -0
  5. package/dist/assets/{BrokerForm-qoePj2K4.js → BrokerForm-DoQjILhI.js} +1 -1
  6. package/dist/assets/Build-rTKtg_tx.js +32 -0
  7. package/dist/assets/{Capabilities-S4kRIl4K.js → Capabilities-PhNKP5DZ.js} +1 -1
  8. package/dist/assets/{CapabilityBadges-DwWL_l7c.js → CapabilityBadges-yL7FrxsG.js} +1 -1
  9. package/dist/assets/Cluster-DeKFim31.js +11 -0
  10. package/dist/assets/{CompositionEditor-D1r-JisY.js → CompositionEditor-Bu6ufcCG.js} +1 -1
  11. package/dist/assets/{CompositionEditorPage-B9h3eUkU.js → CompositionEditorPage-BekLUIPP.js} +1 -1
  12. package/dist/assets/Data-DZ4iVZ3r.js +1 -0
  13. package/dist/assets/DetectionIntelligence-BAE1rpvx.js +1 -0
  14. package/dist/assets/{DeviceAggregateSection-VpXFysnh.js → DeviceAggregateSection-BEv0e5dZ.js} +1 -1
  15. package/dist/assets/DeviceDetail-DTzUAv1F.js +2 -0
  16. package/dist/assets/{Devices-ENl1rQTV.js → Devices-DnvCLFMr.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-CZv8OzxI.js → EmbedPlayerPage-DN8DYcVD.js} +1 -1
  18. package/dist/assets/Events-DIW0IfdN.js +1 -0
  19. package/dist/assets/{FormBuilder-DmVp78xs.js → FormBuilder-Bytus5Tf.js} +1 -1
  20. package/dist/assets/Identity-DuejF2qu.js +1 -0
  21. package/dist/assets/IntegrationDetail-ChJqGuPV.js +1 -0
  22. package/dist/assets/Integrations-BmXG4x-9.js +1 -0
  23. package/dist/assets/Integrations-aQZGbD9Y.js +1 -0
  24. package/dist/assets/Locations-DpmnmMuB.js +3 -0
  25. package/dist/assets/{Logs-BwQ51kvC.js → Logs-DPVRa9WP.js} +1 -1
  26. package/dist/assets/{ModelLicenses-URNrQt1_.js → ModelLicenses-CdSE1ZrE.js} +1 -1
  27. package/dist/assets/{MotionZonesSettings-YQ3UaVz7.js → MotionZonesSettings-Bz_Qdfpp.js} +1 -1
  28. package/dist/assets/{MyAccess-_aiNFcbi.js → MyAccess-Bkvp6GTW.js} +1 -1
  29. package/dist/assets/Network-Ds6N6CJ-.js +1 -0
  30. package/dist/assets/{NodeAddonsSettingsPanel-BY9z0lZa.js → NodeAddonsSettingsPanel-skqKbqMj.js} +1 -1
  31. package/dist/assets/{NodeInferenceDevices-DZ-_1qB2.js → NodeInferenceDevices-B2JedlHO.js} +1 -1
  32. package/dist/assets/Notifications-BV-4IwuU.js +1 -0
  33. package/dist/assets/Pipeline-CAt-bvHB.js +1 -0
  34. package/dist/assets/{Plates-5zDioApI.js → Plates-DzEWm4_s.js} +1 -1
  35. package/dist/assets/{PrivacyMaskSettings-Bo3emiuH.js → PrivacyMaskSettings-CbDYhk2o.js} +1 -1
  36. package/dist/assets/{ProviderIcon-CnCmdk4B.js → ProviderIcon-BBtV-kNn.js} +1 -1
  37. package/dist/assets/Recordings-DdR7d9ou.js +1 -0
  38. package/dist/assets/{ScanNetworkModal-DWiaxsCk.js → ScanNetworkModal-ClrFcKCl.js} +1 -1
  39. package/dist/assets/{SceneMonitorEditor-CVrYjKnp.js → SceneMonitorEditor-DMCML24R.js} +1 -1
  40. package/dist/assets/{Scenes-CvM_wh49.js → Scenes-C9RWMuVR.js} +1 -1
  41. package/dist/assets/{Settings-C0t6ywVO.js → Settings-ucmI8LXJ.js} +1 -1
  42. package/dist/assets/{Showroom-Dr0ztns6.js → Showroom-Bdt-D63k.js} +1 -1
  43. package/dist/assets/{StorageLocationsPanel-DYu23Cr2.js → StorageLocationsPanel-4Tgyiymp.js} +1 -1
  44. package/dist/assets/{Terminal-C3DyYl4d.js → Terminal-BrAUK0eG.js} +4 -4
  45. package/dist/assets/{Viewer-ig9o4_z0.js → Viewer-DQrms2_u.js} +1 -1
  46. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BXMJgpii.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Dq0fVJWM.js} +1 -1
  47. package/dist/assets/{archive-Da1Yqakr.js → archive-BUE32U7F.js} +1 -1
  48. package/dist/assets/{authed-media-BMuC_wHZ.js → authed-media-MbHpXS-m.js} +1 -1
  49. package/dist/assets/{boxes-Baa5Ogmj.js → boxes-CNe0g7jU.js} +1 -1
  50. package/dist/assets/circle-slash-fCLxXnZu.js +1 -0
  51. package/dist/assets/{debounced-invalidate-BrkGpqQR.js → debounced-invalidate-nyczfeAF.js} +1 -1
  52. package/dist/assets/{device-integration-icon-DMH1CC1W.js → device-integration-icon-fftDP3wp.js} +1 -1
  53. package/dist/assets/dist-B4mIz_Rx.js +349 -0
  54. package/dist/assets/{dist-DnbX2Ts3.js → dist-CUNGowXS.js} +1 -1
  55. package/dist/assets/{face-bbox-CqL9Av-Z.js → face-bbox-BDj6xgbi.js} +1 -1
  56. package/dist/assets/{hard-drive-download-BLcXiD8l.js → hard-drive-download-BwgF6zZo.js} +1 -1
  57. package/dist/assets/{hostInit-DZGOkLOR.js → hostInit-BruU7SYo.js} +1 -1
  58. package/dist/assets/index-C8vIAU5v.css +2 -0
  59. package/dist/assets/{index-DmZC8m5k.js → index-DrF3b0h3.js} +3 -3
  60. package/dist/assets/{layers-CheyENp_.js → layers-DH10EL_n.js} +1 -1
  61. package/dist/assets/{location-owned-usage-Cqkcqdng.js → location-owned-usage-bz1tVRVt.js} +1 -1
  62. package/dist/assets/{mf-entry-bootstrap-0-f6e27852.js → mf-entry-bootstrap-0-ad4a1c50.js} +2 -2
  63. package/dist/assets/{player-overlays-COWJpSPo.js → player-overlays-gbZ2vznV.js} +1 -1
  64. package/dist/assets/remoteEntry-BaEDGIXI.js +1 -0
  65. package/dist/assets/{send-WZjVf7tk.js → send-BO7aVZEW.js} +1 -1
  66. package/dist/assets/{settings-2-CHLR6iGS.js → settings-2-CYX3Zwgy.js} +1 -1
  67. package/dist/assets/{square-check-big-x9DuWnSt.js → square-check-big-BhfLbxK8.js} +1 -1
  68. package/dist/assets/src-4fqKwwai.js +349 -0
  69. package/dist/assets/{src-CxavCtUA.js → src-BqkvLgRS.js} +17 -17
  70. package/dist/assets/{use-scenes-feed-C6zdrId0.js → use-scenes-feed-CoCQD-QZ.js} +1 -1
  71. package/dist/assets/{use-stationary-objects-CgZoUHn3.js → use-stationary-objects-BvLkAOl-.js} +1 -1
  72. package/dist/assets/useDevice-D541xOeQ.js +1 -0
  73. package/dist/assets/useEventInvalidation-DxM8yEtK.js +1 -0
  74. package/dist/assets/{useNodeUrlSelection-CAolorcm.js → useNodeUrlSelection-DBqemZZ0.js} +1 -1
  75. package/dist/assets/user-round-DMTk-6Io.js +1 -0
  76. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Iofpk1rr.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-S6IHSmgw.js} +2 -2
  77. package/dist/index.html +6 -6
  78. package/dist/server/addon.js +123 -3
  79. package/package.json +1 -1
  80. package/dist/assets/Addons-BZ97Xzg1.js +0 -1
  81. package/dist/assets/AiProfiles-B2ZTI_l9.js +0 -3
  82. package/dist/assets/Build-C2d1cwHA.js +0 -32
  83. package/dist/assets/Cluster-67TUhWLy.js +0 -11
  84. package/dist/assets/Data-CTGdXReL.js +0 -1
  85. package/dist/assets/DetectionIntelligence-ClVstSbX.js +0 -1
  86. package/dist/assets/DeviceDetail-BC1J_Uus.js +0 -2
  87. package/dist/assets/Events-BAtHdRH_.js +0 -1
  88. package/dist/assets/Identity-DBJbXwFL.js +0 -1
  89. package/dist/assets/IntegrationDetail-BOSgQh4k.js +0 -1
  90. package/dist/assets/Integrations-B9TIBbr7.js +0 -1
  91. package/dist/assets/Integrations-DGY8tg5o.js +0 -1
  92. package/dist/assets/Locations-Cb0oJLNi.js +0 -3
  93. package/dist/assets/Network-GxxrMQ2A.js +0 -1
  94. package/dist/assets/Notifications-BmxbDLAS.js +0 -1
  95. package/dist/assets/Pipeline-Cod6aDKO.js +0 -1
  96. package/dist/assets/Recordings-s4jIucSI.js +0 -1
  97. package/dist/assets/circle-slash-BRokabFn.js +0 -1
  98. package/dist/assets/dist-B2jpWgNR.js +0 -349
  99. package/dist/assets/index-Dw7R0OTh.css +0 -2
  100. package/dist/assets/remoteEntry-4ktgOeTU.js +0 -1
  101. package/dist/assets/src-CYsrYOj2.js +0 -349
  102. package/dist/assets/useDevice-DbxoO2nr.js +0 -1
  103. package/dist/assets/useEventInvalidation-5ATLpxzV.js +0 -1
  104. package/dist/assets/user-round-5BSQ3oXA.js +0 -1
@@ -0,0 +1 @@
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,q as c,t as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{Z as f,at as p,lt as m,st as h,yt as g}from"./player-overlays-gbZ2vznV.js";import{$i as _,Bt as v,Du as y,Ft as b,Gc as x,Hl as S,Il as C,It as w,Ju as T,Ll as E,Lt as D,Lu as O,Mt as k,Nt as A,R as j,Rt as M,Ru as N,St as ee,Wc as P,Wl as te,Xu as F,Yt as ne,Yu as re,an as I,bt as L,cd as ie,cn as R,dt as ae,gs as oe,gu as se,jt as ce,kl as le,ms as ue,mu as de,nn as z,nu as B,ol as V,sn as H,su as fe,tn as U,ut as pe,vi as me,wl as he,xn as ge,xt as _e,yt as ve}from"./src-BqkvLgRS.js";import{t as ye}from"./send-BO7aVZEW.js";import{$ as be,A as xe,B as Se,C as Ce,E as we,F as Te,G as Ee,H as De,I as Oe,J as ke,Jt as Ae,K as je,Kt as Me,L as Ne,M as Pe,N as Fe,O as Ie,P as Le,Q as Re,R as ze,S as Be,Sn as Ve,T as He,U as Ue,V as We,W as Ge,X as Ke,Y as qe,Z as Je,_ as Ye,b as Xe,c as Ze,d as Qe,et as $e,f as et,g as tt,h as nt,it as rt,j as it,k as at,l as ot,m as st,nt as ct,p as lt,q as ut,qt as dt,rt as ft,tt as pt,u as mt,v as ht,w as gt,x as _t,xt as vt,y as yt,z as bt}from"./src-4fqKwwai.js";import{D as xt,M as St,O as Ct,v as wt,y as Tt}from"./__vite-browser-external-Cc3gW-QT.js";import{c as Et,d as Dt,m as Ot}from"./index-DrF3b0h3.js";import{t as W}from"./AdminPage-CiKtOLQm.js";import{n as kt,r as At}from"./FormBuilder-Bytus5Tf.js";import{t as jt}from"./AdminTabs-CDIoD5NP.js";import{t as Mt}from"./use-scenes-feed-CoCQD-QZ.js";var Nt=g(`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`}]]),Pt=g(`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`}]]),Ft=g(`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();function It(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function Lt(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 Rt(e,t,n,r){let i=new Set((t??[]).map(e=>e.id));return Lt(e.filter(e=>!i.has(e)),n,r)}function zt(e,t,n){return e===`answered`&&t===0&&n===0}function Bt(e,t,n){return e&&t===0&&n}var Vt={camera:`cameras`,device:`devices`,node:`nodes`,package:`packages`,class:`classes`};function Ht(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`camera`:case`device`:return e.removed?`Device #${n} — removed`:e.name??`Device #${n}`}}function Ut({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 `,Vt[e],`.`]})}function Wt({noun:e=`cameras`}){return n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Loading `,e,`…`]})}function Gt({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 Kt=[`contact`,`cover`,`lock-control`];function qt(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 Jt(e,t,n){if(e.allDevices||e.deviceIds.includes(n))return!0;let r=t?.openings.find(t=>t.mode===e.mode);return(r?.devices.some(e=>e.deviceId===n)??!1)||(r?.unknown.includes(n)??!1)}function Yt(e){let t=new Set(qt(e.live));for(let n of e.openingIds??[])t.add(n);for(let n of e.listed)t.add(n);let n=[...t].toSorted((e,t)=>e-t);return{ids:n,uncovered:n.filter(t=>!Jt(e.coverage,e.live,t)),unresolved:e.openingIds===null}}function Xt(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function Zt(e,t,n=new Map){let r=[...e].map(([e,t])=>({id:e,name:t})),i=e=>{let t=n.get(e)?.trim();return t===void 0||t===``?null:t},a=e=>Lt([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?`Device #${String(e)}`:Ht(t))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function Qt(e){let t=e.name.trim();return t===``?`Device #${String(e.deviceId)}`:t}function $t(e){return e===0?`Not armed — the hub refused without naming an open device.`:`Not armed — these are open:`}var en={home:`Home`,away:`Away`,night:`Night`};function tn(e){return en[e]??e}function nn(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 rn(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 — ${cn(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${cn(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(t).join(`, `)}function an(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${on[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var on={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function sn(e){return e.ruleCount===0}function cn(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function ln(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 un=2e3,dn=15e3,fn=new Set([`arming`,`pending`,`triggered`]);function pn(e){return e!==void 0&&fn.has(e)?un:dn}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 hn(e){let t=mn[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${tn(e.targetMode)}`}function gn(e){return e!==`disarmed`}function _n(e){return e===`open`?`ignored until it closes`:`closed — monitored at next open`}function vn(e,t){return e.nonBlocking.find(e=>e.mode===t)?.deviceIds??[]}function yn(e,t,n){let r=n.length===0?[]:[{mode:t,deviceIds:[...n]}],i=e.nonBlocking.some(e=>e.mode===t),a=e.nonBlocking.flatMap(e=>e.mode===t?r:[{mode:e.mode,deviceIds:[...e.deviceIds]}]);return i?a:[...a,...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 xn=[`unknown-refusal`,`stale`,`expired`,`used`];function Sn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cn(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Sn(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(!Sn(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Cn(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Cn(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=xn.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return null}var Tn={"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 En(e){return Tn[e]}var Dn=`pipeline-analytics`,On=`The hub answered something this build cannot read — refresh after updating.`;function kn(e){return e instanceof Error?e.message:String(e)}function An(e){return e.map(e=>`${Qt(e)} (${e.state})`).join(`, `)}function jn({live:e,onChanged:t}){let r=p(),[i,a]=c(null),[o,s]=c(null),[d,f]=c(null),m=(e,t)=>r.trpcClient.addons.custom.mutate({addonId:Dn,action:e,input:t}),h=e=>{if(e===null){s(On);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: ${En(e.reason)}.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;f(e.excluded.length===0?`${t}.`:`${t} — excluded: ${An(e.excluded)}.`)},g=()=>{s(null),f(null)},_=l({mutationFn:async e=>wn(await m(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>s(kn(e)),onSettled:t}),v=l({mutationFn:async e=>wn(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>s(kn(e)),onSettled:t}),y=l({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{g(),a(null)},onSuccess:()=>f(`Disarmed.`),onError:e=>s(kn(e)),onSettled:t});if(e===void 0)return n(z,{className:`p-4`,children:[u(`h3`,{className:`text-sm font-semibold mb-1`,children:`Panel`}),u(`p`,{className:`text-sm text-foreground-subtle`,children:`This hub does not report the panel's live state yet — update it to arm from here.`})]});let b=_.isPending||v.isPending||y.isPending;return n(z,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[n(`div`,{children:[u(`h3`,{className:`text-sm font-semibold`,children:`Panel`}),u(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:hn(e)})]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?u(B,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>n(R,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:[`Arm `,tn(e)]},e)),u(R,{type:`button`,size:`md`,variant:gn(e.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:`Disarm`})]})]}),o===null?null:u(`div`,{className:`mt-3`,children:u(I,{title:`The panel did not do that`,message:o})}),d===null?null:u(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:d}),i===null?null:n(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[u(`p`,{className:`text-sm font-medium`,children:$t(i.blocking.length)}),i.blocking.length>0?u(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:i.blocking.map(e=>n(`li`,{children:[Qt(e),` `,n(`span`,{className:`text-foreground-subtle`,children:[`(`,e.state,`)`]})]},e.deviceId))}):null,n(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[u(R,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(i.refusalId),children:`Arm anyway`}),u(`span`,{className:`text-xs text-foreground-subtle`,children:`Each open device is ignored until it closes, then monitored again.`})]})]}),n(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[u(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:`Excluded sensors`}),e.exclusions.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:`No sensor is excluded.`}):u(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:e.exclusions.map(e=>n(`li`,{children:[Qt(e),` —`,` `,u(`span`,{className:`text-foreground-subtle`,children:_n(e.phase)})]},e.deviceId))})]})]})}function Mn(e,t){return typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}function Nn(e){return`${[e.name,e.location??``,e.type??``,e.detail??``].join(` `)} ${String(e.id)}`.toLowerCase()}function Pn(e){return e.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0)}function Fn(e,t){let n=Pn(t);return n.length===0?e:e.filter(e=>{let t=Nn(e);return n.every(e=>t.includes(e))})}function In(e,t){return e===t?0:e===null?1:t===null?-1:e.localeCompare(t)}function Ln(e){return e==null||e.trim()===``?null:e}function Rn(e,t){return`${e??``}|${t??``}`}function zn(e,t){let n=new Set(t),r=new Map;for(let t of e){let e=Ln(t.type),n=Ln(t.location),i=Rn(e,n),a=r.get(i);a===void 0?r.set(i,{type:e,location:n,devices:[t]}):a.devices.push(t)}let i=[];for(let[e,t]of r){let r=[...t.devices].sort((e,t)=>e.name.localeCompare(t.name)||Mn(e.id,t.id));i.push({key:e,type:t.type,location:t.location,devices:r,selectedCount:r.filter(e=>n.has(e.id)).length})}return i.sort((e,t)=>In(e.type,t.type)||In(e.location,t.location))}function Bn(e,t,n){let r=t.get(e.key);return r===void 0?n||e.selectedCount>0?!0:e.devices.length<=8:r}function Vn(e,t,n,r){let i=new Set(t),a=[];for(let t of e){let e=Bn(t,n,r);if(a.push({kind:`header`,key:`h:${t.key}`,group:t,expanded:e}),e)for(let e of t.devices)a.push({kind:`device`,key:`d:${String(e.id)}`,device:e,groupKey:t.key,selected:i.has(e.id)})}return a}function Hn(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function Un(e,t){let n=[...e],r=new Set(e);for(let e of t.devices)r.has(e.id)||n.push(e.id);return n}function Wn(e,t){let n=new Set(t.devices.map(e=>e.id));return e.filter(e=>!n.has(e))}function Gn(e,t){return t||e.length<=6?{shown:e,hidden:0}:{shown:e.slice(0,6),hidden:e.length-6}}function Kn(e,t){let n=Math.max(0,Math.min(e.length,t));return{rows:e.slice(0,n),remaining:e.length-n}}var qn=[`zone`,`location`,`none`],Jn=`zone`;function Yn(e){return e===`zone`||e===`location`||e===`none`?e:Jn}function Xn(e){return e.trim().toLowerCase()}var Zn=1,Qn=2;function $n(e,t){return e.name.localeCompare(t.name)||Mn(e.id,t.id)}function er(e){return e.kind===`zone`||e.kind===`location`?e.label:``}var tr={key:`-location`,heading:{kind:`no-location`},rank:Qn},nr={key:`-zone`,heading:{kind:`no-zone`},rank:Zn};function rr(e){let t=new Map;for(let n of e)for(let e of n.locationKeys){let r=Xn(e);t.has(r)||t.set(r,n)}return t}function ir(e){return e===null?tr:{key:`l:${Xn(e)}`,heading:{kind:`location`,label:e.trim()},rank:0}}function ar(e,t){if(e===null)return tr;let n=t.get(Xn(e));return n===void 0?nr:{key:`z:${n.zoneKey}`,heading:{kind:`zone`,label:n.label},rank:0}}function or(e,t,n,r){let i=new Set(t),a=[...e].sort($n),o=e=>e.filter(e=>i.has(e.id)).length;if(n===`none`)return{groupBy:n,fallback:null,flat:!0,groups:[{key:`all`,type:null,location:null,devices:a,selectedCount:o(a)}]};let s=n===`zone`&&r.state!==`answered`?r.state:null,c=s===null?n:`location`,l=r.state===`answered`?rr(r.zones):new Map,u=new Map;for(let e of a){let t=Ln(e.location),n=c===`zone`?ar(t,l):ir(t),r=u.get(n.key);r===void 0?u.set(n.key,{heading:n.heading,rank:n.rank,devices:[e]}):r.devices.push(e)}return{groupBy:c,fallback:s,flat:!1,groups:[...u].sort(([,e],[,t])=>e.rank-t.rank||er(e.heading).localeCompare(er(t.heading))).map(([e,t])=>({key:e,type:null,location:t.heading.kind===`location`?t.heading.label:null,devices:t.devices,selectedCount:o(t.devices),heading:t.heading}))}}function sr(e,t,n,r){if(!e.flat)return Vn(e.groups,t,n,r);let i=new Set(t),a=[];for(let t of e.groups)for(let e of t.devices)a.push({kind:`device`,key:`d:${String(e.id)}`,device:e,groupKey:t.key,selected:i.has(e.id)});return a}function cr(e,t){return{location:t===`location`?null:Ln(e.location),type:Ln(e.type)}}t();var lr=`camstack.admin.device-picker.group-by`,ur=[[`deviceManager`,`listSiteZones`],`device-picker`],dr=6e4;function fr(){try{let e=globalThis.localStorage?.getItem(`camstack.admin.device-picker.group-by`)??null;return e===null?Jn:Yn(e)}catch{return Jn}}function pr(e){try{globalThis.localStorage?.setItem(lr,e)}catch{}}function mr(){let[e,t]=c(fr);return{groupBy:e,setGroupBy:e=>{t(e),pr(e)}}}function hr(e){let t=p().trpcClient,{data:n,isError:a}=i({queryKey:ur,enabled:e,staleTime:dr,queryFn:()=>t.deviceManager.listSiteZones.query()});return r(()=>n===void 0?a?{state:`failed`}:{state:`pending`}:{state:`answered`,zones:n},[n,a])}t();function gr(e){if(e===null)return`No type`;let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function _r(e){switch(e.kind){case`zone`:case`location`:return e.label;case`no-zone`:return`No zone`;case`no-location`:return`No location`}}function vr(e){return e.heading===void 0?`${gr(e.type)} · ${e.location??`No room`}`:_r(e.heading)}var yr={zone:`Zone`,location:`Location`,none:`None`};function br(e){return e===`camera`||e===`device`}function xr(e,t,n,r){let i=new Map(t.map(e=>[e.id,e.name])),a=new Map(Rt(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:Ht(n,r),removed:n.removed}})}function Sr(e){let[t,n]=c(e);return d(()=>{let t=setTimeout(()=>n(e),200);return()=>clearTimeout(t)},[e]),t}function Cr(e,t){let n=Vt[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 wr({devices:e,listState:t,fleet:r,value:i,onChange:a,emptyMeansAll:o=!1,savedHadDevices:s=!1,noun:l=`camera`,groupTitle:d=vr,emptyLabel:f,annotate:p,disabled:m=!1,testId:h}){let g=r??{state:t,devices:t===`answered`?e:void 0},[_,v]=c(!1),[y,b]=c(!1),[x,S]=c(s||i.length>0);i.length>0&&!x&&S(!0);let C=xr(i,e,g,l),w=Gn(C,y),T=Bt(o,i.length,x),E=Vt[l];return t===`answered`&&zt(t,e.length,i.length)?n(`div`,{"data-testid":h,children:[u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Cr(l,o)}),T&&u(Ut,{noun:l})]}):n(`div`,{className:`mt-1 space-y-1.5`,"data-testid":h,children:[t===`pending`&&u(Wt,{noun:E}),t===`failed`&&u(Gt,{noun:l===`camera`?`devices`:E}),n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[C.length===0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:f??(o?`Every ${l} — no restriction`:`None selected`)}):w.shown.map(e=>u(At,{testId:`picker-chip-${String(e.id)}`,label:e.label,warning:e.removed,...m?{}:{onRemove:()=>a(i.filter(t=>t!==e.id))}},e.id)),w.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:()=>b(!0),children:[`+`,w.hidden,` more`]}),y&&C.length>6&&u(`button`,{type:`button`,className:`text-[11px] text-foreground-subtle underline`,onClick:()=>b(!1),children:`Show fewer`}),t!==`pending`&&u(`button`,{type:`button`,disabled:m,"aria-expanded":_,onClick:()=>v(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:_?`Done`:i.length===0?`Add ${E}…`:`Edit…`})]}),_&&t===`answered`&&(br(l)?u(Tr,{devices:e,value:i,onChange:a,annotate:p,groupTitle:d,noun:l,disabled:m}):u(Or,{devices:e,value:i,onChange:a,annotate:p,groupTitle:d,noun:l,disabled:m})),T&&u(Ut,{noun:l})]})}function Tr(e){let{groupBy:t,setGroupBy:n}=mr(),r=hr(t===`zone`);return u(Or,{...e,grouping:{groupBy:t,onGroupByChange:n,zones:r}})}function Er({control:e,fallback:t}){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:[u(`span`,{className:`mr-1 font-semibold uppercase tracking-wide`,children:`Group by`}),qn.map(t=>{let n=t===e.groupBy;return u(`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:yr[t]},t)})]}),t!==null&&u(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,"data-testid":`picker-zones-note`,children:t===`pending`?`Loading zones — grouped by location for now`:`Zones unavailable — grouped by location`})]})}function Dr(e){return e===`camera`||e===`device`?`Search by name, room or type…`:e===`class`?`Search by class or category…`:`Search by name or id…`}function Or({devices:e,value:t,onChange:i,annotate:a,groupTitle:o,noun:s,disabled:l,grouping:d}){let[f,p]=c(``),m=Sr(f),[h,g]=c(new Map),[_,v]=c(60),y=Pn(m).length>0,b=r(()=>Fn(e,m),[e,m]),x=d?.groupBy,S=d?.zones,C=r(()=>x!==void 0&&S!==void 0?or(b,t,x,S):null,[b,t,x,S]),w=r(()=>C===null?Vn(zn(b,t),t,h,y):sr(C,t,h,y),[C,b,t,h,y]),T=C?.groupBy??null,E=Kn(w,_),D=(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!==void 0&&u(Er,{control:d,fallback:C?.fallback??null}),n(`div`,{className:kt,children:[u(le,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`input`,{type:`text`,value:f,placeholder:Dr(s),"aria-label":s===`camera`||s===`device`?`Search devices`:`Search ${Vt[s]}`,className:`min-w-0 flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-foreground-disabled`,onChange:e=>{p(e.target.value),v(60)}})]}),n(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:[b.length,` of `,e.length,` shown · `,t.length,` selected`]}),w.length===0?u(`p`,{className:`py-2 text-[11px] text-foreground-subtle italic`,children:s===`camera`||s===`device`?`No device matches.`:`No ${s} matches.`}):n(`div`,{className:`mt-1 max-h-72 overflow-y-auto`,"data-testid":`device-picker-rows`,children:[E.rows.map(e=>u(Ar,{row:e,value:t,onChange:i,onToggleGroup:D,annotate:a,groupTitle:o,groupBy:T,disabled:l},e.key)),E.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(E.remaining,60),` more (`,E.remaining,` left)`]})]})]})}function kr(e,t){if(t===null)return e.detail;let n=cr(e,t),r=[n.location,n.type===null?null:gr(n.type),e.detail??null].filter(e=>e!==null);return r.length>0?r.join(` · `):void 0}function Ar({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:[u(`span`,{children:s?`▾`:`▸`}),u(`span`,{className:`truncate`,children:o(a)}),n(`span`,{className:`font-normal normal-case`,children:[`(`,a.selectedCount,`/`,a.devices.length,`)`]})]}),u(`button`,{type:`button`,disabled:c,className:`text-[10px] text-primary hover:underline disabled:opacity-50`,onClick:()=>r(Un(t,a)),children:`All`}),u(`button`,{type:`button`,disabled:c,className:`text-[10px] text-foreground-subtle hover:underline disabled:opacity-50`,onClick:()=>r(Wn(t,a)),children:`Clear`})]})}let l=a?.(e.device.id),d=kr(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:[u(`input`,{type:`checkbox`,checked:e.selected,disabled:c,onChange:()=>r(Hn(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:[u(`span`,{className:`truncate`,children:e.device.name}),d!==void 0&&u(`span`,{className:`truncate text-[10px] text-foreground-subtle`,children:d}),l!==void 0&&u(`span`,{className:`text-[10px] text-warning`,children:l})]})]})}function jr({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?u(`p`,{className:`text-xs text-foreground-subtle`,children:`Open devices: not reported by the hub.`}):i.devices.length===0&&i.unknown.length===0?u(`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`:``]}),u(`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:[Qt(e),` (`,e.state,`) — `,e.blocking?`refuses the arm`:`non-blocking`]},e.deviceId))})]})}function Mr(e){return e.status===`answered`?e.openingIds:null}function Nr({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:[u(B,{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.`]}),u(R,{type:`button`,size:`sm`,variant:`outline`,className:`mt-1`,onClick:e.retry,children:`Retry`})]}):null:null}var Pr={"no-opening":`This household has no opening — no contact, cover or lock — to list here.`},Fr=`Not covered by any rule of this mode — never blocks`;function Ir({coverage:e,live:t,settings:r,names:i,devices:a,devicesState:o,openingsCheck:s,disabled:c,onNonBlockingChange:l}){let d=vn(r,e.mode),f=Yt({live:t,coverage:e,listed:d,openingIds:Mr(s)}),p=Xt(f),{nameOf:m}=i,h=new Set(f.uncovered),g=new Map(a.map(e=>[e.id,e])),_=f.ids.filter(e=>!i.isRemoved(e)).map(e=>({...g.get(e),id:e,name:m(e)}));return n(z,{className:`p-4`,"data-mode":e.mode,"data-empty":sn(e)?`true`:`false`,children:[n(`div`,{className:`flex items-start gap-2`,children:[u(`h3`,{className:`text-sm font-semibold`,children:tn(e.mode)}),sn(e)?u(V,{className:`h-4 w-4 shrink-0 text-warning`}):null]}),u(`p`,{className:`mt-1 text-sm text-foreground-subtle`,children:rn(e,m)}),e.skippedDevices.length>0?u(`div`,{className:`mt-0.5 text-xs text-warning`,"data-testid":`alarm-skipped`,children:an(e.skippedDevices,m)}):null,u(`div`,{className:`mt-3`,children:u(jr,{live:t,coverage:e})}),n(`div`,{className:`mt-3`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[u(`h4`,{className:`text-xs font-semibold`,children:`Non-blocking devices`}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[`May be open when `,tn(e.mode),` arms without refusing it. Every opening of the household (contacts, covers, locks) is listed; one no rule of this mode covers is marked — it can never block this mode, so listing it changes nothing until a rule covers it.`]}),u(Nr,{check:s,view:f}),p===null?null:u(`p`,{className:`mt-1 text-xs text-foreground-subtle`,children:Pr[p]}),u(wr,{devices:_,listState:`answered`,fleet:{state:o,devices:o===`answered`?a:void 0},value:d,onChange:l,noun:`device`,emptyLabel:`None — every open opening refuses the arm`,annotate:e=>h.has(e)?Fr:void 0,disabled:c})]})]})}t();var Lr=[`notificationRules`,`getAlarmConfig`],Rr=[`notificationOutput`,`listTargets`],zr=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],Br=6e4,Vr=600,Hr=3600;function Ur({label:e,hint:t,value:r,max:i,zeroMeans:a,disabled:o,onCommit:s}){let[l,d]=c(null);return n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:e}),n(`div`,{className:`flex items-center gap-2`,children:[u(v,{type:`number`,min:0,max:i,value:l??String(r),disabled:o,onChange:e=>d(e.target.value),onBlur:()=>{let e=l===null?null:ln(l,i);d(null),e!==null&&e!==r&&s(e)},className:`w-28`,"data-testid":`alarm-delay-${e.toLowerCase().replace(/\s+/g,`-`)}`}),u(`span`,{className:`text-sm text-foreground-subtle`,children:nn(r,a)})]}),u(`p`,{className:`text-xs text-foreground-subtle`,children:t})]})}function Wr(){let e=p(),t=s(),a=i({queryKey:Lr,queryFn:async()=>e.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>pn(e.state.data?.live?.state)}),o=i({queryKey:Rr,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),c=me({projection:`slim`}),d=l({mutationFn:t=>e.trpcClient.notificationRules.setAlarmConfig.mutate({patch:t}),onSuccess:e=>t.setQueryData(Lr,e)}),f=()=>t.invalidateQueries({queryKey:Lr}),m=r(()=>{let e=new Map;for(let t of c.data??[])e.set(t.id,t.name);return e},[c.data]),h=a.data?.live,g=i({queryKey:zr,staleTime:Br,queryFn:async()=>new Set(await e.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...Kt]}))}),_=r(()=>(c.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[c.data]),v=g.isError?{status:`failed`,error:g.error instanceof Error?g.error.message:String(g.error),retry:()=>void g.refetch()}:g.data===void 0?{status:`pending`}:{status:`answered`,openingIds:g.data},y=r(()=>{let e=new Map;for(let t of h?.openings??[])for(let n of t.devices)e.set(n.deviceId,Qt(n));return Zt(m,It(c),e)},[h,m,c]);if(a.isLoading)return u(W,{icon:he,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(B,{className:`h-5 w-5 animate-spin`})});let b=a.data;if(b===void 0||a.isError)return u(W,{icon:he,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(I,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(b.deviceId===null)return u(W,{icon:he,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(z,{className:`p-4`,children:u(`p`,{className:`text-sm text-foreground-subtle`,children:`This installation has no alarm panel. The panel is created by the Notification Center on the hub — if this is the hub, its creation failed and the server log says why.`})})});let x=b.settings,S=d.isPending,C=x.announceTargets,w=e=>{d.mutate(e)};return u(W,{icon:he,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:[d.isError?u(I,{title:`Could not save`,message:String(d.error)}):null,u(jn,{live:b.live,onChanged:f}),n(`div`,{className:`flex flex-col gap-4`,"data-testid":`alarm-coverage`,children:[u(`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.`}),b.coverage.map(e=>u(Ir,{coverage:e,live:b.live,settings:x,names:y,devices:_,devicesState:It(c),openingsCheck:v,disabled:S,onNonBlockingChange:t=>w({nonBlocking:yn(x,e.mode,t)})},e.mode))]}),n(z,{className:`p-4`,"data-testid":`alarm-recipients`,children:[u(`h3`,{className:`text-sm font-semibold`,children:`Recipients`}),u(`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:[u(Gr,{query:o,selected:C,disabled:S,onToggle:e=>{w({announceTargets:C.includes(e)?C.filter(t=>t!==e):[...C,e]})}}),C.length===0?u(`p`,{className:`text-xs text-warning`,"data-testid":`alarm-no-recipient`,children:`No recipient selected — alarm changes are not sent to anyone.`}):null]})]}),n(z,{className:`p-4`,children:[u(`h3`,{className:`text-sm font-semibold mb-3`,children:`Delays`}),n(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[u(Ur,{label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,value:x.exitDelaySec,max:Vr,zeroMeans:`arms immediately`,disabled:S,onCommit:e=>w({exitDelaySec:e})}),u(Ur,{label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,value:x.entryDelaySec,max:Vr,zeroMeans:`fires immediately`,disabled:S,onCommit:e=>w({entryDelaySec:e})}),u(Ur,{label:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,value:x.triggeredDurationSec,max:Hr,zeroMeans:`until disarmed`,disabled:S,onCommit:e=>w({triggeredDurationSec:e})})]})]})]})})}function Gr({query:e,selected:t,disabled:r,onToggle:i}){if(e.isPending)return u(B,{className:`h-4 w-4 animate-spin`});if(e.isError)return u(I,{title:`Targets could not be read`,message:String(e.error)});let a=e.data;return a.length===0?u(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification targets are configured — nothing can be sent.`}):u(`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:[u(`input`,{type:`checkbox`,checked:t.includes(e.id),disabled:r,onChange:()=>i(e.id),"data-testid":`alarm-target-${e.id}`}),u(`span`,{className:`min-w-0 truncate`,children:e.name}),e.enabled?null:u(U,{variant:`warning`,children:`disabled`})]},e.id))})}var Kr=`history`,qr=`ruleId`,Jr=[qr],Yr=24,Xr=0,Zr=100;function Qr(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Kr),n.set(qr,t),n}function $r(e,t){let n=new URLSearchParams(e);return t===``?n.delete(qr):n.set(qr,t),n}function ei(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Yr:Xr,limit:Zr}}function ti(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 ni=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],ri=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],ii=[50,100,250,500];function ai(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function oi(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function si(){let e=p(),[t,a]=Ot(),[o,s]=c(()=>ei(t)),l=e=>s(t=>({...t,...e})),d=e=>{l({ruleId:e}),a($r(t,e),{replace:!0})},f=i({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),m=me({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)}:{},...ai(o.status)?{status:ai(o.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),_=r(()=>{let e=new Map;for(let t of m.data??[])t.type===Ve.Camera&&e.set(t.id,t.name);return e},[m.data]),v=e=>_.get(e)??`Camera #${String(e)}`,y=g.data??[],b=g.isError;return n(W,{icon:Nt,title:`Delivery history`,subtitle:`A searchable log of every notification the rules delivered (or failed to deliver).`,children:[n(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),u(H,{"data-testid":`history-rule-filter`,value:o.ruleId,onChange:e=>d(e.target.value),options:[...ti({rules:f.data??[],answered:f.isSuccess,selected:o.ruleId})]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),u(H,{value:o.deviceId,onChange:e=>l({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(m.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),u(H,{value:o.status,onChange:e=>l({status:e.target.value}),options:ri.map(e=>({value:e.value,label:e.label}))})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),u(H,{value:String(o.windowHours),onChange:e=>l({windowHours:Number(e.target.value)}),options:ni.map(e=>({value:String(e.value),label:e.label}))})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),u(H,{value:String(o.limit),onChange:e=>l({limit:Number(e.target.value)}),options:ii.map(e=>({value:String(e),label:String(e)}))})]})]}),g.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(B,{className:`h-6 w-6 animate-spin text-primary`})}),b&&!g.isLoading&&u(z,{children:n(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[u(Nt,{className:`h-6 w-6 text-foreground-subtle`}),u(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),u(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:`The history query is not available on this hub yet. It becomes queryable after the next server update ships the notification-center history endpoint. Rules still deliver and record their outcome in the meantime.`}),n(`button`,{type:`button`,onClick:()=>void 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:[u(C,{className:`h-3 w-3`}),` Retry`]})]})}),!b&&!g.isLoading&&y.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!b&&y.length>0&&u(z,{children:u(pe,{columns:ci(v),rows:y,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})})]})}function ci(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>u(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`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:[u(U,{variant:oi(e.status),children:e.status}),e.attempts>1?n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:`Detail`,render:e=>e.error?u(`span`,{className:`text-[11px] text-danger`,children:e.error}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var li=/\{\{\s*(\w+)\s*\}\}/g,ui=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function di(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 fi(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function pi(e){return[...e.matchAll(li)].map(e=>e[1]??``).filter(e=>e.length>0)}function mi(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function hi(e,t){return[...new Set(pi(e))].filter(e=>!mi(e,t))}var gi={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function _i(e){return e.map(e=>{let t=Xe.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)||yt.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function vi(e){let t=new Set(e.map(e=>e.name)),n=Xe.filter(e=>_t(e)&&!t.has(e.name));return[...e,...n]}function yi(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=gi[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)||!Ce(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:gt(e,t)&&Be(e,t))}function bi(e){return ui.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var xi=[`nc`,`template-catalog`],Si=400;function Ci(){let e=p();return i({queryKey:xi,staleTime:5*6e4,queryFn:async()=>vi(_i((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function wi(e,t,n){let r=p(),a=j(t.title??``,Si),o=j(t.body??``,Si);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 Ti={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},Ei=`block text-[11px] font-medium text-foreground mb-1`,Di=`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 Oi({label:t,value:r,onChange:i,vars:a,multiline:o=!1,placeholder:s,disabled:c=!1,testId:l}){let d=e(null),f=e(null),p=a?hi(r,a):[],m=e=>{let t=o?f.current:d.current,n={start:t?.selectionStart??r.length,end:t?.selectionEnd??r.length},a=fi(e),s=di(r,n,a.text);i(s.value);let c=s.cursor-a.text.length+a.cursorOffset;requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(c,c)})},h=e=>i(e.target.value);return n(`div`,{className:`space-y-1`,children:[u(`label`,{className:Ei,children:t}),o?u(`textarea`,{ref:f,value:r,rows:2,disabled:c,placeholder:s,onChange:h,className:Di,"data-testid":`${l}-input`}):u(v,{ref:d,value:r,disabled:c,placeholder:s,onChange:h,"data-testid":`${l}-input`}),a&&a.length===0?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`No variables for this field.`}):null,a&&a.length>0?u(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:bi(a).map(e=>n(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${l}-group-${e.group}`,children:[u(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:Ti[e.group]}),e.vars.map(e=>u(`button`,{type:`button`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),title:`${e.description??e.label} — e.g. "${e.example}"`,className:`rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-foreground hover:bg-surface-hover`,"data-testid":`${l}-chip-${e.name}`,children:e.dynamic?`${e.name}<class>`:e.name},e.name))]},e.group))}):null,p.length>0?n(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${l}-unknown`,children:[u(V,{className:`h-3 w-3`}),p.map(e=>`{{${e}}}`).join(` `),` will be empty in this notification.`]}):null]})}function ki({context:e,title:t,body:r,testId:i}){let a=wi(e,{title:t,body:r},!0);return a.data?n(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":i,children:[u(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:`Preview (example values)`}),a.data.title===null?null:u(`p`,{className:`font-medium`,children:a.data.title}),a.data.body===null?null:u(`p`,{className:`whitespace-pre-wrap`,children:a.data.body})]}):null}function Ai(e){let t=[],n=e.find(e=>e.type===Ve.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===Ve.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 ji(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 Mi=[{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`}],Ni={sequences:[],buttons:[]};function Pi(e){return e===void 0?Ni:{sequences:[...e.onTrigger??[]],buttons:[...e.buttons??[]]}}function Fi(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 Ii(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 Li(e){return{name:`sequence ${String(e+1)}`,enabled:!1,actions:[]}}function Ri(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequence:t}}function zi(){return{kind:`wait`,seconds:5}}var Bi=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,Vi=`block text-[11px] font-medium text-foreground`;function Hi({title:e,description:t,children:r}){return n(`div`,{className:`flex flex-col gap-2`,children:[n(`div`,{children:[u(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t})]}),u(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function Ui({value:e,onChange:t,devices:r,devicesState:i}){let a=Ii(e),o=Ai(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&&u(`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=>u(`p`,{children:e.message},e.message))}),n(`section`,{className:`space-y-2`,children:[n(Hi,{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(R,{size:`sm`,variant:`ghost`,type:`button`,title:r.hint,className:`min-w-0 max-w-full`,onClick:()=>t(ji(e,r)),children:[u(P,{className:`h-3.5 w-3.5 shrink-0`}),u(`span`,{className:`truncate`,children:r.label})]},r.id)),n(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t({...e,sequences:[...e.sequences,Li(e.sequences.length)]}),children:[u(S,{className:`h-3.5 w-3.5 shrink-0`}),` Sequence`]})]}),e.sequences.length===0?u(`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)=>u(Wi,{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:[u(Hi,{title:`Buttons on the notification`,description:`Each button runs one of the sequences above when tapped.`,children:n(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:e.sequences.length===0,onClick:()=>t({...e,buttons:[...e.buttons,Ri(e.buttons.length,e.sequences[0]?.name??``)]}),children:[u(S,{className:`h-3.5 w-3.5 shrink-0`}),` Button`]})}),e.buttons.length>0&&n(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:[u(V,{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 `,u(`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?u(`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?u(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No buttons. The notification arrives with nothing to tap.`}):e.buttons.map((n,r)=>u(qi,{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 Wi({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:[u(`label`,{className:Vi,children:`Name`}),u(v,{className:`mt-1`,value:e.name,onChange:t=>i({...e,name:t.target.value})})]}),n(`div`,{className:`w-28`,children:[u(`label`,{className:Vi,children:`Min delay (s)`}),u(`input`,{type:`number`,min:0,className:Bi,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:[u(M,{checked:e.enabled,onCheckedChange:t=>i({...e,enabled:t})}),u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.enabled?`Runs on match`:`Only when a button is tapped`})]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,title:`Remove`,children:u(h,{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)=>u(Gi,{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(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i({...e,actions:[...e.actions,zi()]}),children:[u(S,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function Gi({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:[u(`label`,{className:Vi,children:`Step`}),n(`select`,{className:Bi,value:e.kind,onChange:e=>i(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[u(`option`,{value:`cap`,children:`Do`}),u(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?n(`div`,{className:`w-28`,children:[u(`label`,{className:Vi,children:`Seconds`}),u(`input`,{type:`number`,min:0,max:300,className:Bi,value:e.seconds,onChange:e=>i({kind:`wait`,seconds:Number(e.target.value)})})]}):u(Ki,{step:e,devices:t,devicesState:r,onChange:i}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,title:`Remove step`,children:u(h,{className:`h-3.5 w-3.5`})})]})}function Ki({step:e,devices:t,devicesState:r,onChange:o}){let s=p(),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?Lt([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:[u(`label`,{className:Vi,children:`Device`}),n(`select`,{className:l?.removed===!0?`${Bi} border-warning text-warning`:Bi,value:String(e.deviceId),onChange:t=>o({...e,deviceId:Number(t.target.value),cap:``}),children:[u(`option`,{value:`0`,children:`Select…`}),l!==void 0&&u(`option`,{value:String(l.id),className:l.removed?`text-warning`:void 0,children:Ht(l)}),t.map(e=>u(`option`,{value:String(e.id),children:e.name},e.id))]})]}),n(`div`,{className:`min-w-[8rem] flex-1`,children:[u(`label`,{className:Vi,children:`Capability`}),n(`select`,{className:Bi,value:e.cap,disabled:c.length===0,onChange:t=>o({...e,cap:t.target.value,method:``}),children:[u(`option`,{value:``,children:c.length===0?`No devices bound`:`Select…`}),c.map(e=>u(`option`,{value:e,children:e},e))]})]}),n(`div`,{className:`min-w-[7rem] flex-1`,children:[u(`label`,{className:Vi,children:`Method`}),u(v,{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:[u(`label`,{className:Vi,children:`Arguments (JSON)`}),u(v,{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 qi({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:[u(`label`,{className:Vi,children:`Label`}),u(v,{className:`mt-1`,value:e.label,onChange:t=>r({...e,label:t.target.value})})]}),n(`div`,{className:`min-w-[8rem] flex-1`,children:[u(`label`,{className:Vi,children:`Runs`}),n(`select`,{className:Bi,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=>u(`option`,{value:e,children:e},e))]})]}),n(`div`,{className:`w-32`,children:[u(`label`,{className:Vi,children:`Icon`}),n(`select`,{className:Bi,value:e.icon??``,onChange:t=>{let n={...e};if(t.target.value===``)delete n.icon;else{let e=Mi.find(e=>e.value===t.target.value);e!==void 0&&(n.icon=e.value)}r(n)},children:[u(`option`,{value:``,children:`None`}),Mi.map(e=>u(`option`,{value:e.value,children:e.label},e.value))]})]}),n(`div`,{className:`flex items-center gap-2 pb-1`,children:[u(M,{checked:e.destructive===!0,onCheckedChange:t=>{let n={...e};t?n.destructive=!0:delete n.destructive,r(n)}}),u(U,{variant:e.destructive===!0?`danger`:`default`,children:`Destructive style`})]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:u(h,{className:`h-3.5 w-3.5`})})]})}function G(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var Ji=G({devices:!0}),Yi=G({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),Xi=G({zonesExclude:!0}),Zi=G({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),Qi=G({minDwellSeconds:!0}),$i=G({source:!0}),ea=G({crossing:!0}),ta=G({packagePhase:!0}),na=G({sensorTransition:!0}),ra=G({zones:!0}),ia=G({plates:!0}),aa=G({occupancy:!0}),oa=G({audio:!0}),sa=G({systemEvent:!0}),ca=G({deviceState:!0}),la=G({scene:!0});function ua(e,t){let n=e[t];return Array.isArray(n)?n:[]}function da(e,t){let n=e[t];return typeof n==`number`?n:void 0}var fa=[{id:`system`,label:`System events`},{id:`scope`,label:`Scope`},{id:`class`,label:`Classes`},{id:`zones`,label:`Zones`},{id:`quality`,label:`Quality`},{id:`label`,label:`Identity & plates`},{id:`device`,label:`Device event`},{id:`package`,label:`Package`},{id:`occupancy`,label:`Occupancy`},{id:`audio`,label:`Sound`},{id:`schedule`,label:`Schedule`}];function pa(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function ma(e,t){let n=e.filter(t),r=new Set(fa.map(e=>e.id)),i=[];for(let e of fa){let t=n.filter(t=>t.group===e.id);t.length>0&&i.push({id:e.id,label:e.label,descriptors:t})}let a=[];for(let e of n)r.has(e.group)||a.includes(e.group)||a.push(e.group);for(let e of a)i.push({id:e,label:pa(e),descriptors:n.filter(t=>t.group===e)});return i}t();function ha(e,t){let n=p().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)}},[i,t])}function ga(e){let t=p().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 _a(){let e=_();return r(()=>({options:(e.data??[]).map(e=>({value:e.id,label:e.name})),loading:e.isLoading}),[e.data,e.isLoading])}function va(){let e=ue({limit:200}),t=oe();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 ya({options:e,value:t,onChange:i,loading:a,emptyHint:o,placeholder:s,noFreeText:l=!1}){let[d,f]=c(``),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=d.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&&u(`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?u(`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:[u(`input`,{type:`checkbox`,checked:m.has(e.value),onChange:()=>g(e.value),className:`accent-primary`}),u(`span`,{className:`flex-1 truncate`,children:e.label}),e.hint!==void 0&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.hint})]},e.value))}):u(`p`,{className:`text-[10px] text-foreground-subtle`,children:a===!0?`Loading…`:o}),!l&&u(`input`,{value:d,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 ba=[{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 xa(e){return ba.find(t=>t.value===e)?.label??e}function Sa(e){return ba.find(t=>t.value===e)?.value}function Ca(e){return ba.some(t=>t.value===e)}var wa=[{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 & devices`,blurb:`Rules driven by what the cameras and sensors SEE — detections, tracks, doorbell presses and package events.`,newRuleLabel:`New detection rule`,emptyHint:`No detection rules yet. Click "New detection rule" to author one.`,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 Ta(e){return wa.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0)}function Ea(e){return Oe(Te(e)).editable}function Da(e){return Fe(Oa(e))}function Oa(e){switch(e){case`device-events`:case`system`:case`alarm`:case`mixed`:return e;default:return}}var ka=new Map([[0,`No cooldown`],[60,`1 minute`],[3600,`1 hour`]]),Aa=86400;function ja(e){let t=ka.get(e);return t===void 0?e%3600==0?`${e/3600} hours`:e%60==0?`${e/60} minutes`:`${e} seconds`:t}function Ma(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)&&t>=0?Math.trunc(t):void 0}var Na=[{value:`rule-device`,label:`Per device`},{value:`rule`,label:`Whole rule (one window for every device)`}];function Pa(e){return Na.find(t=>t.value===e)?.value}var Fa=[{value:``,label:`Shared across classes (default)`},{value:`shared`,label:`Shared across classes`},{value:`per-class`,label:`Separate window per class`}];function Ia(e){let t=Fa.find(t=>t.value===e)?.value;return t===``?void 0:t}var La=[{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 Ra(e){return La.find(t=>t.value===e)?.value}var za=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function Ba(e){let t=za.find(t=>t.value===e)?.value;return t===``?void 0:t}var Va=[{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 Ha(e){let t=Va.find(t=>t.value===e)?.value;return t===``?void 0:t}var Ua=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function Wa(e){let t=Ua.find(t=>t.value===e)?.value;return t===``?void 0:t}var Ga=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],Ka=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],qa=[{value:``,label:`It triggers and when it clears`},{value:`raised`,label:`Only when it triggers`},{value:`cleared`,label:`Only when it clears`}];function Ja(e){return e===`raised`||e===`cleared`?e:void 0}function Ya(e,t){return e===`sensorTransition`?we(t.sensorKinds):!0}var Xa=[{value:``,label:`Not set — entering`,hint:`Entries, and every detection that is not a crossing at all. Exits are excluded. This is what a rule without a crossing condition already does, and choosing it writes nothing to the rule.`},{value:`enter`,label:`Entered a zone`,hint:`The same matches as "not set", stated explicitly: entries and non-crossing detections pass, exits do not.`},{value:`exit`,label:`Left a zone`,hint:`ONLY an exit crossing. A detection that is not a crossing fails, so this rule cannot fire on ordinary movement — pair it with the zones the subject must have left.`},{value:`any`,label:`Entered or left`,hint:`No direction filter: entries, exits and non-crossing detections alike. This is the only choice that adds exits to what the rule already matched.`}];function Za(e){let t=Xa.find(t=>t.value===e)?.value;return t===``||t===void 0?void 0:t}var Qa=[{value:`any`,label:`Any of`},{value:`all`,label:`All of`}],$a=[{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 eo(e,t){return e.options&&e.options.length>0?e.options:t}var to=[{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 no(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var ro=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 io(e){return ro.get(e)}var ao={"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.`},oo=Ue.map(e=>({id:e.id,family:e.family,label:e.label,hint:ao[e.id]??``,kinds:e.kinds.flatMap(e=>{let t=io(e);return t===void 0?[]:[{value:e,label:t}]})}));function so(e){return oo.filter(t=>t.family===e)}function co(e){let t=ze(e).conditions.systemEvent;return t===void 0?{kinds:(so(e)[0]?.kinds??[]).map(e=>e.value)}:{...t,kinds:[...t.kinds]}}var lo=oo.flatMap(e=>e.kinds);function uo(e){return lo.find(t=>t.value===e)?.label??e}function fo(e){return{devices:Ee(e,`deviceIds`),deviceTypes:Ee(e,`deviceTypes`),nodes:Ee(e,`nodeIds`),packages:Ee(e,`packageNames`),consumableThreshold:Ee(e,`consumableLowPercent`)}}function po(e,t){let n=De[e],r=fo(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 mo=Object.values(Ve).map(e=>({value:e,label:ho(e)})).toSorted((e,t)=>e.label.localeCompare(t.label));function ho(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function go(e,t,n){if(!so(n).some(e=>e.kinds.some(e=>e.value===t)))return e;let r=e?.kinds??[];return r.length===1&&r[0]===t?e:bo(e,r.includes(t)?r.filter(e=>e!==t):lo.filter(e=>e.value===t||r.includes(e.value)).map(e=>e.value),n)}function _o(e,t){return t===void 0?void 0:bo(t,t.kinds,e)}function vo(e,t){let n=e?.kinds??[];if(n.length===0)return;let r=yo(t,`deviceIds`,e?.deviceIds),i=yo(t,`excludeDeviceIds`,e?.excludeDeviceIds),a=yo(t,`deviceTypes`,e?.deviceTypes),o=yo(t,`nodeIds`,e?.nodeIds),s=yo(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 yo(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 bo(e,t,n){let r=po(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 xo=95;function So(e){let t=e.trim();if(t===``)return{kind:`clear`};let n=Number(t);return Number.isInteger(n)&&n>=1&&n<=xo?{kind:`set`,value:n}:{kind:`invalid`}}function Co(e,t=2){if(e===void 0||e.length===0)return`No event selected`;let n=e.slice(0,t).map(uo).join(`, `),r=e.length-Math.min(t,e.length);return r>0?`${n} +${r}`:n}function wo(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(ho).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 To(e){return e===void 0||(e.deviceTypes?.length??0)===0?!1:e.kinds.some(e=>Me.includes(e))}var Eo=[`all`,`only`,`except`];function Do(e,t){return(e??[]).length>0?`only`:(t??[]).length>0?`except`:`all`}function Oo(e,t){let n=[...e??[]],r=[...t??[]];return{mode:Do(n,r),include:n,exclude:r,legacyBoth:n.length>0&&r.length>0}}function ko(e,t){return{...e,mode:t}}function Ao(e){switch(e.mode){case`only`:return e.include;case`except`:return e.exclude;case`all`:return[]}}function jo(e,t){switch(e.mode){case`only`:return{...e,include:[...t]};case`except`:return{...e,exclude:[...t]};case`all`:return e}}function Mo(e){return e.mode===`only`&&e.legacyBoth?e.exclude:[]}function No(e){return{...e,exclude:[],legacyBoth:!1}}function Po(e){switch(e.mode){case`all`:return{};case`except`:return e.exclude.length>0?{exclude:[...e.exclude]}:{};case`only`:{let t=Mo(e);return{...e.include.length>0?{include:[...e.include]}:{},...t.length>0?{exclude:[...t]}:{}}}}}function Fo(e){let t=Po(e),n=t.include??[],r=t.exclude??[];return[...e.include.filter(e=>!n.includes(e)),...e.exclude.filter(e=>!r.includes(e))]}var Io=[10,30,60],Lo=[5,10,15,30,60,120,240,480];function Ro(e){return e>=60&&e%60==0?`${e/60} h`:`${e} min`}var zo=new Set([`alarm-arm-refused`,`alarm-check-failed`,`alarm-arming`,`alarm-armed`,`alarm-pending`,`alarm-triggered`,`alarm-rearmed`,`alarm-sensor-bypass`,`alarm-disarmed`]),Bo=`alarm-panel`;function Vo(e,t){for(let t of e.systemEvent?.kinds??[])if(zo.has(t))return!0;for(let e of t)for(let t of e.actions)if(t.kind===`cap`&&t.cap===Bo)return!0;return!1}function Ho(e){let{devices:t,devicesExclude:n,classes:r,classesExclude:i,...a}=e;return{conditions:a,deviceScope:Oo(t,n),classScope:Oo(r,i)}}function Uo(e){let t=Po(e.deviceScope),n=Po(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 Wo(e){return e.deviceScope.mode===`only`?e.deviceScope.include:[]}function Go(e,t,n){let r=Te(n);return e.some(e=>e.id===t&&xe(e,n.delivery,r))}function Ko(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:``,...Ho(t),schedule:void 0,systemEventDelivery:void 0,snoozeAllowGlobal:!1,waitForEnhancement:!1,snoozeOptions:void 0,actions:Ni,cooldownSec:30,cooldownScope:`rule-device`,cooldownGranularity:void 0}}function qo(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??``,...Ho(e.conditions),schedule:e.schedule,systemEventDelivery:e.systemEventDelivery,snoozeAllowGlobal:e.snoozeAllowGlobal===!0,waitForEnhancement:e.waitForEnhancement===!0,snoozeOptions:e.snoozeOptions,actions:Pi(e.actions),cooldownSec:e.throttle.cooldownSec,cooldownScope:e.throttle.scope,cooldownGranularity:e.throttle.granularity}}function Jo(e){let t=[];if(Re(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(Aa)} (24 hours). 0 means every match is delivered.`),Zo(e))for(let n of Ye({delivery:e.delivery,conditions:e.conditions,...e.systemEventDelivery===void 0?{}:{systemEventDelivery:e.systemEventDelivery},...Fi(e.actions)===void 0?{}:{actions:Fi(e.actions)}}))t.push(st(n));return t}function Yo(e){let t=e.systemEventDelivery;return t===void 0?{}:Pe(e.delivery)?{systemEventDelivery:t}:t.mode===`summary`?{systemEventDelivery:{mode:`instant`}}:{}}function Xo(e){return!Zo(e)||ht(e.templateBody)?null:`This body names none of the summary ({{summaryText}} or a section variable) — the hub appends {{summaryText}} to it when it sends.`}function Zo(e){return Pe(e.delivery)&&e.systemEventDelivery?.mode===`summary`}function Qo(e){return Jo(e).length===0&&Ca(e.delivery)&&(!Pe(e.delivery)||ts(e)>0)&&Te(e)!==`mixed`&&e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&Ii(e.actions).length===0}function $o(e,t){return Pe(t)&&(e.conditions.systemEvent?.kinds.length??0)===0?{...e,delivery:t,conditions:{...e.conditions,systemEvent:co(`device-events`)}}:{...e,delivery:t}}function es(e,t){return Se(e.conditions.systemEvent)===t?e:{...e,conditions:{...e.conditions,systemEvent:co(t)}}}function ts(e){return e.conditions.systemEvent?.kinds.length??0}function ns(e,t){return e.appliesTo.includes(t)}var rs={source:`any`};function is(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||rs[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 as=dt.filter(e=>e.id===`audio`);function os(e){if(e.length===0)return e;let t=new Set(e.map(e=>e.id)),n=as.filter(e=>!t.has(e.id));return n.length===0?e:[...e,...n]}function ss(e,t,n,r=Te({delivery:t,conditions:e})){let i=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&xe(e,t,r)).map(e=>e.id)),a={};for(let[t,n]of Object.entries(e))i!==null&&!i.has(t)||Ya(t,e)&&(is(t,n)||(a[t]=n));return a}function cs(e,t){if(e===void 0)return{};let n=_o(e,t.systemEvent);return n===void 0?{}:{systemEvent:n}}function ls(e){return e!==void 0&&e.windows.length>0}function us(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 ds(e){let t=us(e.media);return{...e.confirm===void 0?{}:{confirm:e.confirm},...e.groupIdleSec===void 0?{}:{groupIdleSec:e.groupIdleSec},...t===void 0?{}:{media:t}}}function fs(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=Fi(e.actions),s=Te(e),c=Oe(s),l=bt(s),u=n.length===0?!0:n.some(t=>t.id===`schedule`&&ns(t,e.delivery)),d=!Zo(e)&&u&&ls(e.schedule)?e.schedule:void 0,f=n.length===0?!0:n.some(t=>t.id===`devices`&&ns(t,e.delivery)),p=n.length===0?!0:n.some(t=>t.id===`devicesExclude`&&ns(t,e.delivery)),{devices:m,devicesExclude:h,...g}=Uo(e);return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...ss(g,e.delivery,n,s),...f&&m!==void 0?{devices:m}:{},...p&&h!==void 0?{devicesExclude:h}:{},...cs(l,e.conditions)},...d?{schedule:d}:{},...Yo(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 ps(e,t){let n=fs(e,void 0,t);return[`template`,`schedule`,`targetUsers`,`snoozeOptions`,`snoozeAllowGlobal`,`waitForEnhancement`,`actions`].filter(e=>n[e]===void 0)}var ms=[{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 hs(e,t={}){let n=Te({delivery:e,conditions:t}),r=Oe(n),i=ms.map(e=>e.key===`conditions`?{...e,label:r.label}:e);return Fe(n)?i.filter(e=>e.key!==`devices`):i}function gs(e){if(e.audio!==void 0)return`Sound`;if(e.occupancy!==void 0)return`Occupancy`}function _s(e){let t=Te(e),n=it(Uo(e),t);return t===`sensor`&&e.conditions.sensorTransition!==void 0&&!Ya(`sensorTransition`,e.conditions)?[...n,{conditionId:`sensorTransition`,reason:He}]:n}var vs=`rule`;function ys(e){return ms.find(t=>t.key===e)?.key}t();var K=`block text-[11px] font-medium text-foreground`,q=`text-[10px] text-foreground-subtle mt-0.5`;function bs({cameras:e,fleet:t,value:n,onChange:r,emptyMeansAll:i=!1,savedHadDevices:a=!1}){return u(wr,{devices:e,listState:t.state,fleet:t,value:n,onChange:r,emptyMeansAll:i,savedHadDevices:a})}function xs({value:e,placeholder:t,onChange:r}){let[i,a]=c(``),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&&u(`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,u(`button`,{type:`button`,onClick:()=>s(e),"aria-label":`remove ${e}`,className:`text-foreground-subtle hover:text-danger`,children:u(x,{className:`h-3 w-3`})})]},e))}),u(v,{value:i,placeholder:t,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),o())},onBlur:o})]})}function Ss({picker:e,value:t,onChange:i}){let a=r(()=>ut(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&&u(`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:[u(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-muted mb-1`,children:e.fallbackLabel}),u(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map(e=>{let t=o.has(e.value);return u(`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 Cs({value:e,min:t,max:r,step:i,onChange:a}){return n(`div`,{className:`mt-1 flex items-center gap-2`,children:[u(v,{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&&u(`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 ws({value:e,onChange:t,options:r}){let i=e??``,a=r&&r.length>0?r:Xa,o=a.find(e=>e.value===i);return n(`div`,{className:`mt-1 space-y-1`,children:[u(H,{value:i,options:a.map(e=>({value:e.value,label:e.label})),onChange:e=>t(Za(e.target.value))}),o!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:o.hint})]})}function Ts({deviceIds:e,cameras:t,value:r,onChange:i}){let a=r?.ids??[],o=r?.match??`any`,s=e=>i(e.length>0?{ids:e,match:o}:void 0),c=e=>i(a.length>0?{ids:a,match:e}:void 0);return n(`div`,{className:`mt-1 space-y-1.5`,children:[u(`div`,{className:`max-w-[10rem]`,children:u(H,{value:o,options:Qa.map(e=>({value:e.value,label:e.label})),onChange:e=>c(e.target.value===`all`?`all`:`any`)})}),u(Es,{deviceIds:e,cameras:t,value:a,onChange:s})]})}function Es({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=ha(e,t);return u(ya,{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 Ds({value:e,onChange:t}){let{options:n,loading:r}=_a();return u(ya,{options:n,value:e,onChange:t,loading:r,emptyHint:`No identities in the face gallery yet — type a name.`,placeholder:`Identity name…`})}function Os({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=ga(e);return u(ya,{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 ks=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}];function As(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 js({deviceIds:e,cameras:t,classOptions:r,value:i,onChange:a}){let{options:o,loading:s}=ha(e,t),c=i??at,l=e=>a({...c,...e}),d=c.op===`became-occupied`||c.op===`became-free`,f=As(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:[u(`div`,{className:`min-w-[10rem]`,children:u(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})})}),u(`div`,{className:`min-w-[9rem]`,children:u(H,{value:c.className??``,options:[{value:``,label:`— any class —`},...f],onChange:e=>l({className:e.target.value===``?void 0:e.target.value})})}),u(`div`,{className:`min-w-[9rem]`,children:u(H,{value:c.op,options:ks.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=ks.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:[d?`Threshold`:`Count`,u(v,{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`,u(v,{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:u(`button`,{type:`button`,onClick:()=>a(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),e.length===0&&u(`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.`}),u(`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 Ms=[{value:`label`,label:`Sounds — fires at once`,Icon:le},{value:`level`,label:`Volume — over a window`,Icon:ie}];function Ns({taxonomy:e,value:t,onChange:r}){let i=pt(t),o=e=>r(ft(t,e)),{choices:s,unknownLabels:c}=be(e,i.labels),l=$e(t)??`label`;return n(`div`,{className:`mt-1 space-y-2`,children:[n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[Ms.map(e=>u(`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:[u(e.Icon,{className:`h-3 w-3`}),e.label]})},e.value)),t===void 0?null:u(`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:[u(`div`,{className:`flex flex-wrap gap-1`,children:s.map(e=>{let t=ct(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 u(`button`,{type:`button`,"aria-pressed":t,title:e.unknown?`Stored by the rule — not offered by this hub`:void 0,onClick:()=>o({labels:rt(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:[u(ge,{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`,u(v,{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`,u(v,{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:[u(`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`,u(v,{type:`number`,min:qe,max:0,step:3,className:`w-20`,value:String(i.dbThreshold??Ke),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`,u(v,{type:`number`,min:1,max:100,step:5,className:`w-16`,value:String(i.hitPercent),onChange:e=>o({hitPercent:Number(e.target.value)})}),`% (default `,Je.hitPercent,`)`]}),n(`label`,{className:`flex items-center gap-1`,children:[`over`,u(v,{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 `,Je.samplingSeconds,`)`]})]}),n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`dBFS is negative-going: 0 is full scale, `,qe,` 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.`]})]}),Re(t)?u(`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 Ps({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=va().filter(e=>!r.includes(e));return n(`div`,{className:`mt-1 space-y-1.5`,children:[u(xs,{value:r,placeholder:`Plate text…`,onChange:a}),s.length>0&&n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[u(`span`,{className:`text-[10px] text-foreground-subtle`,children:`Seen:`}),s.slice(0,12).map(e=>u(`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`,u(v,{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 Fs({gateable:e,value:t,onChange:r}){let i=e.find(e=>e.id===t?.deviceId),a=new Set(t?.states??[]),o=e=>{let t=Number(e);if(!Number.isFinite(t)||t===0)return r(void 0);r({deviceId:t,states:[]})},s=e=>{if(t===void 0)return;let n=new Set(a);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:[u(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=>o(e.target.value)}),i!==void 0&&u(`div`,{className:`flex flex-wrap gap-1.5`,children:i.states.map(e=>u(`button`,{type:`button`,onClick:()=>s(e),className:a.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:e},e))}),i!==void 0&&i.states.length===0&&u(`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&&u(`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 Is(e){let t=e.verdict===`matched`?`matched`:e.verdict===`diverged`?`diverged`:`cannot judge`;return e.latched?`${t} · latched`:t}function Ls({scenes:e,value:t,onChange:r}){let i=e.find(e=>e.sceneId===t?.sceneId),a=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}})},o=e=>{t!==void 0&&r({...t,requiredState:e===`matched`?`matched`:`diverged`})},s=e=>{if(t!==void 0){if(e===``){let{latched:e,...n}=t;return r(n)}r({...t,latched:e===`latched`})}};return e.length===0?u(`p`,{className:q,children:`No scenes on this hub yet — create one on the Scenes page first. A rule cannot be gated on a scene that does not exist.`}):n(`div`,{className:`mt-1 space-y-2`,children:[u(H,{value:t?.sceneId??``,options:[{value:``,label:`— no scene gate —`},...e.map(e=>({value:e.sceneId,label:`${e.cameraName} · ${e.label} — ${Is(e)}`}))],onChange:e=>a(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:[`Only while it is`,u(H,{value:t.requiredState,options:[{value:`diverged`,label:`diverged (changed)`},{value:`matched`,label:`matched (as captured)`}],onChange:e=>o(e.target.value)})]}),n(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Read`,u(H,{value:t.latched===void 0?``:t.latched?`latched`:`live`,options:[{value:``,label:i===void 0?`the scene's own setting`:`the scene's own setting (${i.emit})`},{value:`latched`,label:`the latch (since it was armed)`},{value:`live`,label:`the live verdict (right now)`}],onChange:e=>s(e.target.value)})]})]}),i!==void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Right now: `,Is(i),`. The rule is silent whenever the scene is in any other state — including when it cannot judge at all (no reference for this light, the view shifted, no snapshot) and until this hub has read the scene once.`]}),t!==void 0&&i===void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`This rule is gated on a scene this hub cannot find (id `,t.sceneId,`). It was deleted or disabled — the rule is enabled and permanently silent until you pick another scene or remove the gate.`]})]})}var Rs=`classes`;function zs(e){let t=ke(Rs,e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function Bs(e){return e.type??`Other`}var Vs={all:`All`,only:`Only these`,except:`All except these`};function Hs({draft:e,onChange:t,exceptOffered:r,plural:i,renderPicker:a,describe:o,testId:s}){let c=Eo.filter(t=>t!==`except`||r||e.mode===`except`),l=Mo(e),d=Fo(e),f=e.mode===`all`?null:e.mode;return n(`div`,{className:`mt-1 space-y-1.5`,"data-testid":s,children:[u(`div`,{role:`radiogroup`,"aria-label":`Which ${i}`,className:`inline-flex flex-wrap items-center gap-1`,children:c.map(n=>{let r=n===e.mode;return u(`button`,{type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${n}`,onClick:()=>t(ko(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:Vs[n]},n)})}),f===null?n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Every `,Us(i),` — no restriction.`]}):a(Ao(e),n=>t(jo(e,n)),f),l.length>0&&n(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[`This rule also excludes `,l.map(o).join(`, `),` — kept when you save.`,` `,u(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>t(No(e)),children:`Remove exclusions`})]}),d.length>0&&n(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:[`Saving in this mode clears `,d.map(o).join(`, `),` from the rule.`]})]})}function Us(e){return e.endsWith(`sses`)?e.slice(0,-2):e.endsWith(`s`)?e.slice(0,-1):e}t();function Ws({taxonomy:e,scope:t,onChange:n,exceptOffered:i}){let a=r(()=>zs(e),[e]),o=r(()=>new Map((a??[]).map(e=>[e.id,e.name])),[a]);return u(Hs,{draft:t,onChange:n,exceptOffered:i,plural:`classes`,describe:e=>o.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>a===null?u(xs,{value:e,placeholder:`Add value…`,onChange:t}):u(wr,{devices:a,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:Bs,testId:`class-picker`},n)})}var Gs=[{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 Ks(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function qs(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 Js(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function Ys({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,Js()],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?u(`p`,{className:q,children:`Always active — add a window to restrict when the rule fires.`}):r.map((e,t)=>u(Xs,{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:[u(S,{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:[u(`input`,{type:`checkbox`,checked:i,onChange:e=>a([...r],e.target.checked),className:`accent-primary`}),`Active outside the windows`]})]})]})}function Xs({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:[u(`input`,{type:`time`,value:Ks(e.startMinute),onChange:n=>t({...e,startMinute:qs(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),u(`span`,{className:`text-foreground-subtle`,children:`→`}),u(`input`,{type:`time`,value:Ks(e.endMinute),onChange:n=>t({...e,endMinute:qs(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),u(`span`,{className:`flex-1`}),u(`button`,{type:`button`,onClick:r,"aria-label":`Remove window`,className:`text-foreground-subtle hover:text-danger`,children:u(h,{className:`h-3.5 w-3.5`})})]}),u(`div`,{className:`flex flex-wrap gap-1`,children:Gs.map(t=>u(`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 Zs(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function Qs({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return u(wr,{devices:e.map(Zs),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`})}function $s({devices:e,scope:t,onChange:n,listState:r,savedScope:i,exceptOffered:a}){let o=new Map(e.map(e=>[e.id,e.name]));return u(Hs,{draft:t,onChange:n,exceptOffered:a,plural:`devices`,describe:e=>o.get(e)??`Device #${String(e)}`,testId:`rule-device-scope`,renderPicker:(t,n,a)=>u(Qs,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function ec(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function tc(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function nc(e){let t=ec(e),n=e.data===void 0?[]:Qe(e.data.nodes),r=tc(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function rc(e){let t=ec(e),n=e.data===void 0?[]:et(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var ic=[`nc-pickers`,`node-directory`],ac=[`nc-pickers`,`package-list`],oc=6e4,sc={hub:`Hub`,agent:`Agents`},cc={server:`Server`,framework:`Framework`,wrapper:`Wrapper`,addon:`Addons`};function lc(e){let t=sc[e.type??``]??`Nodes`;return e.location===`offline`?`${t} · offline`:t}function uc(e){return cc[e.type??``]??`Packages`}function dc({value:e,onChange:t,testId:r}){let a=p().trpcClient,o=i({queryKey:ic,staleTime:oc,queryFn:()=>a.nodes.directory.query()}),s=nc(o);return n(`div`,{children:[u(wr,{devices:s.items,listState:s.listState,fleet:s.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:lc,...r===void 0?{}:{testId:r}}),o.data?.complete===!1&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:`The node history could not be read — offline nodes may be missing from this list.`})]})}function fc({value:e,onChange:t,testId:n}){let r=p().trpcClient,a=rc(i({queryKey:ac,staleTime:oc,queryFn:()=>r.addons.listPackages.query()}));return u(wr,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:uc,...n===void 0?{}:{testId:n}})}var pc={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-tank-low`]},template:{body:`{{deviceName}}`}};function mc(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 hc(e,t){return e===`pending`?`pending`:e===`success`?`current`:mc(t)===`BAD_REQUEST`?`outdated`:`unknown`}function gc(e){let t=p(),n=i({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(pc)});return e?hc(n.status,n.error):`pending`}t();var _c=`/system/settings`,vc=`/system/notifications?tab=alarm`,yc=`text-primary underline-offset-2 hover:underline`;function bc({family:e,value:t,cameras:i,allDevices:a,fleet:o,savedHadDevices:s,onChange:c}){let l=r(()=>t?.kinds??[],[t]),d=r(()=>a===void 0?i:a.map(Zs),[a,i]),f=po(e,l),p=gc(e===`device-events`),m=e===`alarm`;return n(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[so(e).map(r=>n(`div`,{children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:r.label}),u(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:r.kinds.map(n=>{let r=l.includes(n.value);return u(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":n.label,onClick:()=>c(go(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)})}),u(`p`,{className:q,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):`,` `,u(Dt,{to:_c,target:`_blank`,rel:`noreferrer`,className:yc,children:`Settings → Battery & offline alerts`}),`.`]}),e===`alarm`&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[u(Dt,{to:vc,target:`_blank`,rel:`noreferrer`,className:yc,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`&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`}),f.consumableThreshold&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:`Consumable low at (%)`}),u(v,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:xo,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=So(e.target.value);n.kind!==`invalid`&&c(vo(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:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these device types (optional)`}),u(ya,{options:mo,value:t?.deviceTypes??[],onChange:e=>c(vo(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`}),u(`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.`})]}),To(t)&&u(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`battery-device-types-warning`,children:`Battery and consumable alerts are narrowed by device type here. Batteries and consumables belong to sensors, containers, vacuums and mowers — rarely to a camera — so a type filter meant for liveness silences them. Leave the types empty, or put these kinds in a rule of their own.`}),f.devices&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:m?`Only when triggered by these cameras (optional)`:`Only these devices (optional)`}),u(wr,{devices:m?i:d,listState:o.state,fleet:o,emptyMeansAll:!0,savedHadDevices:s,noun:m?`camera`:`device`,value:t?.deviceIds??[],onChange:e=>c(vo(t,{deviceIds:e})),testId:`system-event-include`}),u(`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:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Never these devices (optional)`}),u(wr,{devices:d,listState:o.state,fleet:o,noun:`device`,emptyLabel:`No device excluded`,value:t?.excludeDeviceIds??[],onChange:e=>c(vo(t,{excludeDeviceIds:e})),testId:`system-event-exclude`}),u(`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:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these nodes (optional)`}),u(dc,{value:t?.nodeIds??[],onChange:e=>c(vo(t,{nodeIds:e})),testId:`system-event-nodes`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave it empty to watch every node.`})]}),f.packages&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these packages (optional)`}),u(fc,{value:t?.packageNames??[],onChange:e=>c(vo(t,{packageNames:e})),testId:`system-event-packages`}),u(`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 xc({value:e}){let t=e?.kinds??[];return n(`div`,{className:`mt-1 rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-mixed`,children:[u(`p`,{children:`This rule is not one kind of system rule — its events span device events, system and alarm, or it names none. It keeps firing as it is, but it cannot be edited here: recreate it as one rule per kind.`}),t.length>0&&u(`p`,{className:`mt-1 text-foreground`,children:t.map(uo).join(`, `)})]})}function Sc({family:e,onChange:t}){return n(`div`,{"data-testid":`system-family-select`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Kind of system rule`}),u(H,{value:e,"aria-label":`Kind of system rule`,onChange:e=>{let n=e.target.value;Ge(n)&&t(n)},options:We.map(e=>({value:e,label:Oe(e).label}))}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`})]})}t();function Cc({catalog:e,taxonomy:t,delivery:i,conditions:a,classScope:o,onClassScopeChange:s,onTrigger:l,savedConditions:d,schedule:f,deviceIds:p,cameras:m,fleet:h,allDevices:g,gateable:_,gateableScenes:v,onConditionsChange:y,onScheduleChange:b}){let x=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,y(n)},S=Te({delivery:i,conditions:a}),C=r(()=>e.filter(e=>xe(e,i,S)),[e,i,S]),w=e.length-C.length,T=r(()=>C.filter(e=>Ya(e.id,a)),[C,a]),E=T.some(e=>e.id===`classesExclude`),{baseGroups:D,advancedGroups:O}=r(()=>{let e=T.find(e=>Ec.has(e.id))?.id,t=t=>!Tc.has(t.id)&&(!Ec.has(t.id)||t.id===e);return{baseGroups:ma(T,e=>t(e)&&Dc(e,i,a)),advancedGroups:ma(T,e=>t(e)&&!Dc(e,i,a))}},[T,i,a]),[k,A]=c(()=>{if(Oc(a,f))return!0;try{return localStorage.getItem(wc)===`1`}catch{return!1}}),j=()=>{let e=!k;A(e);try{localStorage.setItem(wc,e?`1`:`0`)}catch{}},M=e=>e.map(e=>n(`div`,{className:`space-y-2.5`,children:[u(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:e.label}),e.descriptors.map(e=>Ec.has(e.id)?n(`div`,{"data-testid":`condition-${e.id}`,children:[u(`label`,{className:K,children:`Object classes`}),u(Ws,{taxonomy:t,scope:o,onChange:s,exceptOffered:E})]},e.id):n(`div`,{"data-testid":`condition-${e.id}`,children:[u(`label`,{className:K,children:e.label}),u(kc,{descriptor:e,kind:S,taxonomy:t,conditions:a,onTrigger:l??[],savedConditions:d,schedule:f,deviceIds:p,cameras:m,fleet:h,...g===void 0?{}:{allDevices:g},gateable:_,gateableScenes:v,onFieldChange:x,onScheduleChange:b}),e.description&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.description})]},e.id))]},e.id));return n(`div`,{className:`space-y-4`,children:[M(D),w>0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`nc-kind-hidden-note`,children:[w,` condition`,w===1?``:`s`,` that belong to other kinds of rule`,` `,w===1?`is`:`are`,` not shown — this rule fires on`,` `,Oe(S).label.toLowerCase(),` and the engine could never match`,` `,w===1?`it`:`them`,` against its subject.`]}),O.length>0&&u(`button`,{type:`button`,onClick:j,"data-testid":`nc-advanced-toggle`,className:`w-full rounded-md border border-border px-3 py-1.5 text-left text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:k?`▾ Hide advanced configurations`:`▸ Show more configurations`}),k&&M(O)]})}var wc=`camstack.nc.showAdvanced`,Tc=new Set([`devices`,`devicesExclude`]),Ec=new Set([`classes`,`classesExclude`]);function Dc(e,t,n={}){return t===`system-event`?e.id===`systemEvent`:e.id===`audio`?n.audio!==void 0:e.id===`occupancy`?n.occupancy!==void 0:je(e.id)}function Oc(e,t){for(let[t,n]of Object.entries(e))if(!je(t)&&!(Tc.has(t)||Ec.has(t))&&t!==`systemEvent`&&!(t===`audio`||t===`occupancy`)&&n!==void 0&&!(Array.isArray(n)&&n.length===0))return!0;return t!==void 0&&t.windows.length>0}function kc({descriptor:e,kind:t,taxonomy:r,conditions:i,onTrigger:o,savedConditions:s,schedule:c,deviceIds:l,cameras:d,fleet:f,allDevices:p,gateable:m,gateableScenes:h,onFieldChange:g,onScheduleChange:_}){switch(e.valueType){case`deviceIdList`:{if(!Ji(e.id))break;let t=e.id,n=i[t]??[];return u(bs,{cameras:d,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(!Yi(e.id))break;let t=e.id,n=e=>g(t,e.length>0?e:void 0);if(t===`identities`||t===`identitiesExclude`)return u(Ds,{value:ua(i,t),onChange:e=>t===`identities`?g(t,e):n(e)});if(t===`eventTypeTokens`)return u(Os,{deviceIds:l,value:ua(i,t),onChange:n});let a=ke(t,r);return a===null?u(xs,{value:ua(i,t),placeholder:`Add value…`,onChange:n}):u(Ss,{picker:a,value:ua(i,t),onChange:n})}case`zoneIdList`:{if(!Xi(e.id))break;let t=e.id;return u(Es,{deviceIds:l,cameras:d,value:ua(i,t),onChange:e=>g(t,e.length>0?e:void 0)})}case`number01`:{if(!Zi(e.id))break;let t=e.id;return u(Cs,{value:da(i,t),min:0,max:1,step:.05,onChange:e=>g(t,e)})}case`number`:{if(!Qi(e.id))break;let t=e.id;return u(Cs,{value:da(i,t),min:0,step:1,onChange:e=>g(t,e)})}case`sourceSelect`:{if(!$i(e.id))break;let t=e.id;return u(H,{value:i[t]??`any`,options:eo(e,Ga).map(e=>({value:e.value,label:e.label})),onChange:e=>g(t,Mc(e.target.value))})}case`systemEvent`:{if(!sa(e.id))break;let n=e.id,r=bt(t);return r===void 0?u(xc,{value:i[n]}):u(bc,{family:r,value:i[n],cameras:d,fleet:f,...p===void 0?{}:{allDevices:p},savedHadDevices:(s?.[n]?.deviceIds?.length??0)>0,onChange:e=>g(n,e)})}case`deviceState`:if(!ca(e.id))break;return u(Fs,{gateable:m,value:i.deviceState,onChange:e=>g(`deviceState`,e)});case`scene`:if(!la(e.id))break;return u(Ls,{scenes:h,value:i.scene,onChange:e=>g(`scene`,e)});case`crossingSelect`:{if(!ea(e.id))break;let t=e.id;return u(ws,{value:i[t],onChange:e=>g(t,e),...e.options?{options:e.options}:{}})}case`packagePhase`:{if(!ta(e.id))break;let t=e.id;return u(H,{value:i[t]??``,options:[{value:``,label:`— any phase —`},...eo(e,Ka).map(e=>({value:e.value,label:e.label}))],onChange:e=>g(t,Nc(e.target.value))})}case`sensorTransition`:{if(!na(e.id))break;let t=e.id,r=Ie({conditions:i,onTrigger:o});return n(a,{children:[u(H,{value:i[t]??``,options:eo(e,qa).map(e=>({value:e.value,label:e.label})),onChange:e=>g(t,Ja(e.target.value))}),r&&u(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`nc-sensor-transition-never-fires`,children:`This rule belongs to the alarm, and an alarm rule fires only when an opening OPENS. Set to “only when it clears”, it can never fire.`})]})}case`zoneSelection`:{if(!ra(e.id))break;let t=e.id;return u(Ts,{deviceIds:l,cameras:d,value:i[t],onChange:e=>g(t,e)})}case`plateMatcher`:{if(!ia(e.id))break;let t=e.id;return u(Ps,{value:i[t],onChange:e=>g(t,e)})}case`occupancy`:{if(!aa(e.id))break;let t=e.id;return u(js,{deviceIds:l,cameras:d,classOptions:Ac(r),value:i[t],onChange:e=>g(t,e)})}case`audio`:{if(!oa(e.id))break;let t=e.id;return u(Ns,{taxonomy:r,value:i[t],onChange:e=>g(t,e)})}case`schedule`:return u(Ys,{value:c,onChange:_});default:break}return u(jc,{descriptor:e,conditions:i})}function Ac(e){let t=ke(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function jc({descriptor:e,conditions:t}){let r=Object.entries(t).find(([t])=>t===e.id);return n(`p`,{className:q,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 Mc(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Nc(e){return Ka.find(t=>t.value===e)?.value}var Pc=6e4,Fc=60*Pc,Ic=24*Fc,Lc=Date.UTC(2e3,0,1);function Rc(e){if(e==null||e<Lc)return`—`;let t=Date.now()-e;return t<0||t<3e4?`just now`:t<Fc?`${String(Math.floor(t/Pc))}m ago`:t<Ic?`${String(Math.floor(t/Fc))}h ago`:`${String(Math.floor(t/Ic))}d ago`}var zc=[`notificationRules`,`getRuleLastRuns`],Bc=3e4;function Vc(){let e=p(),t=i({queryKey:zc,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:Bc});return{status:t.status,data:t.data,error:t.error}}var Hc={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function Uc({cell:e}){switch(e.kind){case`pending`:return u(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":`Last run loading`,className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return u(`span`,{"data-testid":`rule-last-run-failed`,title:`Last run could not be read: ${e.reason}`,className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.phrase});case`ran`:return n(`span`,{className:`flex items-center gap-1.5`,title:new Date(e.lastAt).toLocaleString(),children:[u(`span`,{"data-testid":`rule-last-run-dot`,title:e.status,className:`inline-block h-2 w-2 rounded-full ${Hc[e.status]}`}),u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Rc(e.lastAt)})]})}}function Wc({rule:e,onOpenHistory:t}){return u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t(e),title:`History — this rule's deliveries`,"aria-label":`history of ${e.name}`,children:u(Nt,{className:`h-3.5 w-3.5`})})}t();var Gc=[`notificationRules`,`listSnoozes`],Kc=[10,30,60,120];function qc({ruleId:e,ruleName:t,exempt:r=!1,variant:i=`icon`}){let a=p(),o=s(),[d,f]=c(30),[m,h]=c(null),g=l({mutationFn:t=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>o.invalidateQueries({queryKey:Gc}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?i===`icon`?null:u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`}):i===`icon`?u(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:`Silence this rule for ${Ro(30)} — it appears under "Silenced right now"`,"aria-label":`snooze ${t}`,"data-testid":`nc-rule-snooze-now`,children:g.isPending?u(B,{className:`h-3.5 w-3.5 animate-spin`}):u(F,{className:`h-3.5 w-3.5`})}):n(`div`,{className:`space-y-1`,children:[n(`div`,{className:`flex items-end gap-2`,children:[u(`div`,{className:`w-32`,children:u(H,{value:String(d),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&f(t)},options:Kc.map(e=>({value:String(e),label:Ro(e)}))})}),n(R,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(d),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?u(B,{className:`h-3.5 w-3.5 animate-spin`}):u(F,{className:`h-3.5 w-3.5`}),`Silence this rule now`]})]}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Opens a real snooze window right now — distinct from the buttons above, which only choose the durations this rule's NOTIFICATION offers. It appears under "Silenced right now" and can be ended from there.`}),m!==null&&u(`p`,{className:`text-[10px] text-danger`,children:m})]})}var Jc=`pipeline-analytics`,Yc=`nc.getRuleStatus`,Xc=`nc.testRule`;function Zc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Qc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function $c(e){if(!Zc(e))return;let t=Qc(e,`id`),n=Qc(e,`downloadPath`),r=J(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:Qc(e,`mediaType`)??`video`,sizeBytes:J(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function el(e){if(!Zc(e))return;let t=J(e,`startMs`),n=J(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function tl(e){if(!Zc(e))return null;let t=J(e,`deviceId`);if(t===void 0)return null;let n=J(e,`lastGeneratedAt`),r=$c(e.lastArtifact),i=e.rendering,a=Zc(i)?{startedAt:J(i,`startedAt`)??0,windowStartMs:J(i,`windowStartMs`)??0,windowEndMs:J(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function nl(e){if(!Zc(e))return null;let t=Qc(e,`kind`);if(t===`none`)return{kind:`none`,reason:Qc(e,`reason`)??``};if(t===`occupancy`){let t=J(e,`deviceId`),n=J(e,`threshold`),r=J(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=Qc(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=J(e,`count`),s=J(e,`observedAt`),c=J(e,`since`),l=Qc(e,`scope`),u=Qc(e,`className`),d=Qc(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=tl(e);t!==null&&n.push(t)}let r=el(e.lastWindow),i=e.nextWindow,a=Zc(i)?{startMs:J(i,`startMs`)??0,endMs:J(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:J(e,`settleMs`)??0}}return null}function rl(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 il(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 al(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 ${rl(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 ol(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${rl(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} · ${il(i.sizeBytes)}`}var sl=`nc.listPrunes`;function cl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ll=new Set([`rule`,`timelapse`,`summary`]),ul=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`]);function dl(e){return typeof e==`string`&&ll.has(e)}function fl(e){return typeof e==`string`&&ul.has(e)}function pl(e){return e===`device`||e===`target`}function ml(e){if(!cl(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!dl(t)||!pl(r)||!fl(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 hl(e){return!cl(e)||!Array.isArray(e.prunes)?null:e.prunes.map(ml).filter(e=>e!==null)}function gl(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 _l(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 vl(e){return new Date(e).toLocaleDateString()}function yl({kind:e,ruleId:t,enabled:r,updatedAt:a}){let o=p(),s=i({queryKey:[`pipelineAnalytics`,sl],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>hl(await o.trpcClient.addons.custom.mutate({addonId:Jc,action:sl,input:{}}))}).data;if(s==null)return null;let c=gl(s,e,t,r,a);return c===null?null:n(`div`,{"data-testid":`nc-prune-banner`,className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-foreground`,children:[u(fe,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`span`,{children:_l(c,vl)})]})}var bl=5e3;function xl({ruleId:e,cameraName:t}){let r=p(),o=i({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:bl,queryFn:async()=>nl(await r.trpcClient.addons.custom.mutate({addonId:Jc,action:Yc,input:{ruleId:e}}))}).data;if(o==null||o.kind===`none`)return null;let s=Date.now(),c=e=>t?.(e)??`camera ${String(e)}`;return n(`div`,{"data-testid":`nc-rule-status`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[o.kind===`occupancy`&&n(`p`,{className:`flex items-start gap-1.5`,children:[o.unavailable!==void 0||o.warning!==void 0?u(V,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):u(E,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),n(`span`,{children:[u(`span`,{className:`text-foreground`,children:c(o.deviceId)}),` —`,` `,al(o,s)]})]}),o.kind===`timelapse`&&n(a,{children:[o.devices.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[u(E,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),n(`span`,{children:[ol(e,c(e.deviceId),s),e.lastArtifact!==void 0&&n(a,{children:[` · `,u(`a`,{className:`text-primary hover:underline`,href:`/${e.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:`open`})]})]})]},e.deviceId)),n(`p`,{className:`flex items-start gap-1.5`,children:[u(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),n(`span`,{children:[o.nextWindow===void 0?`No further window opens in the next nine days`:`Next window opens ${new Date(o.nextWindow.startMs).toLocaleString()}`,o.settleMs>0&&` · rendered ${String(Math.round(o.settleMs/6e4))} min after it closes, so the footage has settled`]})]})]})]})}function Sl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cl(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function wl(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Tl(e){if(!Sl(e))return null;let t=Cl(e,`ruleId`),n=Cl(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=Cl(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:Cl(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:wl(e,`targetIds`)}}function El(e){if(!Sl(e))return null;let t=Cl(e,`conditionId`),n=Cl(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Dl(e){if(!Sl(e))return null;let t=Cl(e,`recordId`),n=Cl(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=Tl(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=El(t);e!==null&&i.push(e)}let a=Cl(e,`droppedBy`);return{recordId:t,delivery:n,trigger:Cl(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:Cl(e,`still`)??`none`,notes:wl(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i}}function Ol(e){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.`}t();function kl({ruleId:e,ruleName:t,fallbackDeviceId:r,variant:i=`icon`,showResult:o=!1}){let s=p(),[d,f]=c(null),[m,h]=c(null),g=l({mutationFn:async()=>Dl(await s.trpcClient.addons.custom.mutate({addonId:Jc,action:Xc,input:{ruleId:e,...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{f(null),h(null)},onSuccess:e=>f(e),onError:e=>h(e instanceof Error?e.message:`The test could not be run.`)}),_=d===null?m===null?void 0:m:Ol(d);return n(a,{children:[n(R,{size:`sm`,variant:i===`icon`?`ghost`:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(),title:_??`Test now — fires this rule and really sends the notification`,"aria-label":`test ${t} now`,"data-testid":`nc-rule-test-now`,children:[g.isPending?u(B,{className:`h-3.5 w-3.5 animate-spin`}):u(ye,{className:`h-3.5 w-3.5`}),i===`full`&&`Test now`]}),o&&m!==null&&u(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:m}),o&&d!==null&&n(`div`,{"data-testid":`nc-rule-test-result`,className:`mt-2 space-y-1 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[u(`p`,{className:`text-foreground`,children:Ol(d)}),d.planNotes.map(e=>n(`p`,{className:`flex gap-1.5`,children:[u(V,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId)),d.notes.map(e=>n(`p`,{children:[`· `,e]},e))]})]})}t();var Al=[`notificationRules`,`listSnoozes`],jl=3e4;function Ml(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function Nl(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 Pl({rules:e}){let t=p(),a=s(),o=i({queryKey:Al,refetchInterval:jl,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),c=l({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>a.invalidateQueries({queryKey:Al})}),d=r(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),f=Date.now(),m=(o.data??[]).filter(e=>f>=e.startedAt&&f<e.expiresAt);return n(z,{className:`p-4`,children:[n(`div`,{className:`flex items-center gap-2 mb-3`,children:[u(F,{className:`h-4 w-4 text-foreground-subtle`}),u(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),m.length===0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`}),u(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:m.map(e=>n(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[n(`div`,{className:`min-w-0`,children:[n(`div`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:d.get(e.ruleId??``)??`A rule`}),e.global&&u(U,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&u(U,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&u(U,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,Nl(Ml(e,f))]})]}),u(R,{size:`sm`,variant:`outline`,disabled:c.isPending,onClick:()=>c.mutate(e.id),children:`End now`})]},e.id))})]})}var Fl={days:[0,1,2,3,4,5,6],minute:480},Il=[{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 Ll(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Rl(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 zl(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 Bl(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 Vl(e,t,n){if(e===`error`)return zl(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 r=[];r.push(t.empty?`Nothing to report right now — no notification would be sent.`:`${String(t.count)} item(s) would be sent now:\n${t.text}`);let i=Bl(t.dropped);return i!==null&&r.push(i),t.excludedGroups.includes(`backups-exports`)&&r.push(`Backups and exports are completed jobs, not a state — they are not in a summary.`),{lines:r}}function Hl({value:e,family:t,onChange:r,draft:i}){if(t===void 0||!lt.includes(t))return null;let a=e?.mode===`summary`?e:null;return n(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:`Delivery`}),n(`div`,{className:`flex flex-wrap gap-3 text-xs`,children:[n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-delivery`,checked:a===null,onChange:()=>r({mode:`instant`}),"data-testid":`rule-delivery-instant`}),`Instant — a notification per event`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-delivery`,checked:a!==null,onChange:()=>r({mode:`summary`,schedule:nt([Fl])}),"data-testid":`rule-delivery-summary`}),`Summary on schedule — the current state, at set times`]})]}),a!==null&&u(Ul,{value:a,onChange:r,draft:i})]})}function Ul({value:e,onChange:t,draft:r}){let i=tt(e.schedule),o=e.schedule.timezone,s=e=>{e.length!==0&&t({mode:`summary`,schedule:nt(e,o)})};return n(`div`,{className:`mt-2 space-y-2`,children:[n(`p`,{className:q,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. Nothing to report sends nothing. Time zone: `,o??`the hub’s`,`.`]}),i===null?n(a,{children:[u(`p`,{className:q,"data-testid":`rule-delivery-custom`,children:`Custom schedule: the summary is sent when each window below ENDS.`}),u(Ys,{value:e.schedule,onChange:e=>{e!==void 0&&t({mode:`summary`,schedule:e})}})]}):n(a,{children:[i.map((e,t)=>u(Wl,{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,Fl]),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:[u(S,{className:`h-3 w-3`}),` Add a send time`]})]}),u(Gl,{draft:r})]})}function Wl({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:[u(`span`,{className:`text-foreground-subtle`,children:`Send at`}),u(`input`,{type:`time`,value:Ll(e.minute),onChange:t=>r({...e,minute:Rl(t.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`,"data-testid":`rule-delivery-time-${String(t)}`}),u(`span`,{className:`flex-1`}),i!==void 0&&u(`button`,{type:`button`,onClick:i,"aria-label":`Remove send time`,className:`text-foreground-subtle hover:text-danger`,children:u(h,{className:`h-3.5 w-3.5`})})]}),u(`div`,{className:`flex flex-wrap gap-1`,children:Il.map(t=>u(`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 Gl({draft:e}){let t=p(),r=l({mutationFn:e=>t.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),i=Vl(r.status,r.data,r.error);return n(`div`,{className:`space-y-1.5`,children:[u(R,{size:`sm`,variant:`secondary`,onClick:()=>r.mutate(e()),disabled:r.isPending,"data-testid":`rule-delivery-preview`,children:r.isPending?`Reading the state…`:`Preview the summary now`}),i!==null&&u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:i.lines.map((e,t)=>u(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function Kl(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:Zl(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var ql=6e4,Jl=60*ql,Yl=24*Jl;function Xl(e,t){return e===1?`the last ${t}`:`the last ${String(e)} ${t}s`}function Zl(e){return e===null?`No delivery on record`:e>=Yl?`Not in ${Xl(Math.floor(e/Yl),`day`)}`:e>=Jl?`Not in ${Xl(Math.floor(e/Jl),`hour`)}`:e>=ql?`Not in ${Xl(Math.floor(e/ql),`minute`)}`:`Not in the window read`}function Ql(e){return{state:It(e),devices:e.data}}t();var $l=[`notificationRules`,`listRules`],eu=[`notificationOutput`,`listTargets`,`forRules`],tu=[`notificationRules`,`getConditionCatalog`],nu=[`deviceManager`,`gateableDevices`],ru=Ae.options;function iu({onSimulateRule:e,onOpenHistory:t}={}){let a=p(),[o,s]=c({mode:`closed`}),[d,f]=c(null),[m,h]=c(`all`),g=i({queryKey:$l,queryFn:async()=>(await a.trpcClient.notificationRules.listRules.query({})).rules}),_=i({queryKey:eu,queryFn:()=>a.trpcClient.notificationOutput.listTargets.query({})}),v=i({queryKey:tu,queryFn:()=>a.trpcClient.notificationRules.getConditionCatalog.query({})}),y=me({projection:`slim`}),b=Vc(),x=r(()=>y.data??[],[y.data]),C=Ql(y),w=r(()=>x.map(e=>e.id),[x]),T=i({queryKey:[...nu,w],enabled:w.length>0,queryFn:async()=>{let e=[];for(let t of x){let n=vt(await a.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),ru);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),E=r(()=>{let e=Et(x);return x.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))},[x]),D=r(()=>x.filter(e=>e.type===Ve.Camera).map(e=>({id:e.id,name:e.name})),[x]),O=Mt(r(()=>D.map(e=>e.id),[D])),k=r(()=>{let e=new Map(D.map(e=>[e.id,e.name]));return O.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})))},[O.results,D]),A=r(()=>{let e=new Map;for(let t of _.data??[])e.set(t.id,t.name);return e},[_.data]),j=l({mutationFn:e=>a.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void g.refetch()}),M=l({mutationFn:e=>a.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>{f(null),g.refetch()}}),N=g.data??[],P=r(()=>{let e=new Map;for(let t of wa)e.set(t.key,N.filter(e=>Ne(e,t.key)).length);return e},[N]),te=Ta(P),F=te.find(e=>e.key===m)??wa[0],ne=r(()=>N.filter(e=>Ne(e,F.key)),[N,F.key]),L=Da(F.key),ie=e=>{Ea(e)&&s({mode:`form`,rule:e})};return n(W,{icon:re,title:`Notification Rules`,subtitle:F.blurb,actions:F.creatable?n(R,{size:`sm`,type:`button`,onClick:()=>s({mode:`form`,rule:null,seed:ze(F.key)}),children:[u(S,{className:`h-3.5 w-3.5`}),F.newRuleLabel]}):void 0,children:[u(ve,{value:F.key,onValueChange:e=>h(Le(e)??m),children:u(_e,{className:`mb-3`,children:te.map(e=>n(ee,{value:e.key,children:[e.label,u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:P.get(e.key)??0})]},e.key))})}),u(Pl,{rules:N}),g.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(B,{className:`h-6 w-6 animate-spin text-primary`})}),g.isError&&!g.isLoading&&u(I,{title:`Failed to load rules`,message:g.error instanceof Error?g.error.message:`Unknown error`,onRetry:()=>void g.refetch()}),!g.isLoading&&!g.isError&&ne.length===0&&u(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:F.emptyHint}),ne.length>0&&u(z,{children:u(pe,{columns:L?cu({targetNameById:A,confirmDeleteId:d,deletePending:M.isPending,onToggle:(e,t)=>j.mutate({ruleId:e.id,enabled:t}),onEdit:ie,onDuplicate:e=>ie({...e,id:``,name:`${e.name} (copy)`}),onAskDelete:f,onConfirmDelete:e=>M.mutate(e.id),lastRunOf:e=>Kl(b,e),...t?{onOpenHistory:t}:{}}):au({targetNameById:A,confirmDeleteId:d,deletePending:M.isPending,onToggle:(e,t)=>j.mutate({ruleId:e.id,enabled:t}),onEdit:ie,onDuplicate:e=>ie({...e,id:``,name:`${e.name} (copy)`}),onAskDelete:f,onConfirmDelete:e=>M.mutate(e.id),...e?{onTest:e}:{},lastRunOf:e=>Kl(b,e),...t?{onOpenHistory:t}:{}}),rows:ne,rowKey:e=>e.id,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),o.mode===`form`&&u(lu,{rule:o.rule,...o.seed?{seed:o.seed}:{},targets:_.data??[],actuatable:E,fleet:C,catalog:os(v.data?.catalog??[]),taxonomy:v.data?.taxonomy,cameras:D,gateable:T.data??[],gateableScenes:k,onCancel:()=>s({mode:`closed`}),onSaved:()=>{s({mode:`closed`}),g.refetch()}})]})}function au(e){return[{key:`name`,header:`Rule`,render:e=>n(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&u(U,{variant:`warning`,children:`disabled`}),Vo(e.conditions,e.actions?.onTrigger??[])&&u(U,{variant:`info`,children:`Snooze disabled (alarm rule)`})]})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:e=>n(`span`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] text-foreground-subtle`,children:xa(e.delivery)}),!Ca(e.delivery)&&u(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 u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(Uc,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(M,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>Ea(t)?n(`span`,{className:`flex items-center justify-end gap-1`,children:[u(kl,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&u(Wc,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:`Open in the simulator — describe an event and tune it before injecting`,"aria-label":`simulate ${t.name}`,children:u(de,{className:`h-3.5 w-3.5`})}),u(qc,{ruleId:t.id,ruleName:t.name,exempt:Vo(t.conditions,t.actions?.onTrigger??[])}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onEdit(t),title:`Edit`,children:u(te,{className:`h-3.5 w-3.5`})}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:u(y,{className:`h-3.5 w-3.5`})}),u(su,{rule:t,deps:e})]}):u(ou,{rule:t,deps:e})}]}function ou({rule:e,deps:t}){return n(`span`,{className:`flex items-center justify-end gap-1`,children:[u(`span`,{title:Oe(Te(e)).blurb,children:u(U,{variant:`warning`,children:`Recreate as one rule per family`})}),t.onOpenHistory&&u(Wc,{rule:e,onOpenHistory:t.onOpenHistory}),u(su,{rule:e,deps:t})]})}function su({rule:e,deps:t}){return t.confirmDeleteId===e.id?n(a,{children:[n(R,{size:`sm`,variant:`danger`,type:`button`,disabled:t.deletePending,onClick:()=>t.onConfirmDelete(e),children:[t.deletePending&&u(B,{className:`h-3.5 w-3.5 animate-spin`}),`Confirm`]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onAskDelete(null),children:`Cancel`})]}):u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onAskDelete(e.id),title:`Delete`,children:u(h,{className:`h-3.5 w-3.5 text-danger`})})}function cu(e){let t=au(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Co(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:wo(e.conditions.systemEvent)})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`cooldown`,header:`Cooldown`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:ja(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`enabled`),...n(`actions`)]}function lu({rule:e,seed:t,targets:r,catalog:o,taxonomy:s,cameras:d,gateable:f,gateableScenes:m,actuatable:h,fleet:g,onSaved:_,onCancel:y}){let b=p(),x=e!=null&&e.id.length>0,[S]=c(()=>e?qo(e):Ko(t?.delivery,t?.conditions)),[C,w]=c(S),[T,E]=c(null),[D,O]=c(null),[j,N]=c(vs),P=e=>w(t=>({...t,...e})),te=e?ds(e):void 0,F=l({mutationFn:async()=>{let t=fs(C,te,o);if(x&&e){let n=ps(C,o);await b.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await b.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:_,onError:e=>E(e instanceof Error?e.message:`Save failed`)}),ne=l({mutationFn:async()=>{let e=fs(C,te,o);return(await b.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>O(null),onSuccess:e=>O(e),onError:e=>E(e instanceof Error?e.message:`Test failed`)}),I=C.targetIds.map(e=>r.find(t=>t.id===e)?.name??e),ie=e=>P({targetIds:C.targetIds.includes(e)?C.targetIds.filter(t=>t!==e):[...C.targetIds,e]}),ae=i({queryKey:[`userManagement`,`listUsers`],queryFn:()=>b.trpcClient.userManagement.listUsers.query()}).data,oe=e=>P({targetUsers:C.targetUsers.includes(e)?C.targetUsers.filter(t=>t!==e):[...C.targetUsers,e]}),se=ba.find(e=>e.value===C.delivery)?.hint,le=Jo(C),ue=Pe(C.delivery),z=Te(C),V=Oe(z),fe=bt(z),pe=Ci(),me=e=>({family:`rule`,field:e,kind:z,delivery:C.delivery,...Zo(C)?{systemEventDelivery:`summary`}:{},...C.conditions.systemEvent?{systemEventKinds:[...C.conditions.systemEvent.kinds]}:{}}),he=e=>pe.data?yi(pe.data,me(e)):void 0,ge=_s(C),ye=Vo(C.conditions,C.actions.sequences),be=C.conditions.identities!==void 0||C.conditions.plates!==void 0,xe=hs(C.delivery,C.conditions),Se=xe.some(e=>e.key===j)?j:vs;return Ca(C.delivery)?u(ce,{open:!0,onOpenChange:e=>!e&&y(),children:n(A,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex min-w-0 items-center gap-2`,children:[u(re,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:x?`Edit ${e?.name}`:`New notification rule`})]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:y,children:`Cancel`})]}),T&&u(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:T}),x&&e&&n(`div`,{className:`shrink-0 mb-3 space-y-2`,children:[u(yl,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(xl,{ruleId:e.id,cameraName:e=>d.find(t=>t.id===e)?.name??`camera ${String(e)}`})]}),n(ve,{value:Se,onValueChange:e=>N(ys(e)??j),className:`flex min-h-0 flex-1 flex-col`,children:[u(_e,{className:`mb-3 shrink-0`,children:xe.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(k,{className:`pr-1`,children:[n(L,{value:`rule`,className:`space-y-4`,children:[n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),u(v,{value:C.name,onChange:e=>P({name:e.target.value}),placeholder:`e.g. Front door package`})]}),n(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[u(M,{checked:C.enabled,onCheckedChange:e=>P({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),u(H,{value:C.delivery,onChange:e=>{let t=Sa(e.target.value);t&&w(e=>$o(e,t))},options:ba.map(e=>({value:e.value,label:e.label}))}),se&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:se})]}),!x&&fe!==void 0&&u(Sc,{family:fe,onChange:e=>w(t=>es(t,e))}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),r.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery targets configured. Add one under the Targets tab first.`}):u(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:r.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:[u(`input`,{type:`checkbox`,checked:C.targetIds.includes(e.id),onChange:()=>ie(e.id),className:`accent-primary`}),u(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&u(U,{variant:`warning`,children:`disabled`})]},e.id))})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(ae??[]).length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No users to notify.`}):u(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:(ae??[]).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:[u(`input`,{type:`checkbox`,checked:C.targetUsers.includes(e.id),onChange:()=>oe(e.id),className:`accent-primary`}),u(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&u(U,{variant:`info`,children:`admin`})]},e.id))}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Delivers to the targets each user owns, only for cameras that user can access.`})]})]}),u(L,{value:`devices`,className:`space-y-4`,children:u($s,{devices:h,scope:C.deviceScope,onChange:e=>P({deviceScope:e}),listState:g.state,savedScope:S.deviceScope,exceptOffered:Go(o,`devicesExclude`,C)})}),u(L,{value:`actions`,className:`space-y-4`,children:u(Ui,{value:C.actions,onChange:e=>P({actions:e}),devices:h,devicesState:g.state})}),n(L,{value:`advanced`,className:`space-y-4`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown (seconds)`}),u(v,{type:`number`,min:0,max:Aa,step:1,value:String(C.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=Ma(e.target.value);t!==void 0&&P({cooldownSec:t})}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[ue?`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(Aa),` (24 hours).`]})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown counted`}),u(H,{value:C.cooldownScope,onChange:e=>{let t=Pa(e.target.value);t!==void 0&&P({cooldownScope:t})},options:Na.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Per device: a delivery about one camera (or node) does not hold back another. Whole rule: one delivery per cooldown, whichever device matched.`})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Across object classes`}),u(H,{value:C.cooldownGranularity??``,onChange:e=>P({cooldownGranularity:Ia(e.target.value)}),options:Fa.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Shared: a cat holds back the next dog for the cooldown. Separate: a dog after a cat is delivered at once, a second cat still waits. Sounds always count per class.`})]})]}),C.delivery===`immediate`?n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(M,{checked:C.waitForEnhancement,onCheckedChange:e=>P({waitForEnhancement:e}),"aria-label":`wait for recognition`,disabled:!be}),`Wait for the face or plate before notifying`]}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:be?`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:[u(M,{checked:C.snoozeAllowGlobal,onCheckedChange:e=>P({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:ye}),`Anyone may snooze this rule for everyone`]}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`A snooze is personal by default — it silences only the person who set it. Turn this on for a rule where silencing the whole household is legitimate (the gardener is here all afternoon). Admins can always do it.`})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),ye?u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Snooze disabled (alarm rule). This rule concerns — or triggers — the alarm panel, and no snooze window can silence it: not a notification button, not a pause opened from the app on this camera or on the whole feed.`}):n(a,{children:[u(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Lo.map(e=>{let t=C.snoozeOptions??Io,n=t.includes(e);return u(R,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>P({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Ro(e)},e)})}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:C.snoozeOptions===void 0?`Not set — the notification offers the defaults (${Io.map(Ro).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.`:C.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.`}),C.snoozeOptions!==void 0&&u(R,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>P({snoozeOptions:void 0}),children:`Back to the defaults`})]})]}),x&&e&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Silence it now`}),u(qc,{ruleId:e.id,ruleName:e.name,exempt:ye,variant:`full`})]})]}),n(L,{value:`notification`,className:`space-y-4`,children:[n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),u(H,{value:String(C.priority),onChange:e=>P({priority:Number(e.target.value)}),options:$a.map(e=>({value:String(e.value),label:e.label}))})]}),!V.carriesMedia&&u(`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.`}),V.carriesMedia&&V.mediaBlurb!==void 0&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:V.mediaBlurb}),V.carriesMedia&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),u(H,{value:C.mediaAttach,onChange:e=>{let t=Ra(e.target.value);t&&P({mediaAttach:t})},options:La.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:La.find(e=>e.value===C.mediaAttach)?.description}),n(`div`,{className:`mt-2 space-y-1`,children:[V.carriesSubjectCrop&&n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:C.mediaZoneCrop,onChange:e=>P({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),`Crop the image to the rule's zone`]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:C.mediaGif,onChange:e=>P({mediaGif:e.target.checked}),className:`accent-primary`}),`Attach a GIF around the event`]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:C.mediaClip,onChange:e=>P({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(C.mediaGif||C.mediaClip)&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),u(H,{value:C.mediaProfile??``,onChange:e=>P({mediaProfile:Wa(e.target.value)}),options:Ua.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`A notification is watched on a phone — the cheapest stream is normally the right one, and the high profile only costs CPU to render.`}),u(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),u(H,{value:C.mediaClipSpeed===void 0?``:String(C.mediaClipSpeed),onChange:e=>P({mediaClipSpeed:no(e.target.value)}),options:to.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`A notification clip is glanced at, not watched: at 2× the recipient sees the whole passage in half the time and the file is half the size. Real time is there when the detail matters more than the glance.`})]})]}),z===`sensor`&&V.carriesMedia&&C.mediaAttach!==`none`&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Linked cameras`}),u(H,{value:C.mediaLinkedCameras??``,onChange:e=>P({mediaLinkedCameras:Ha(e.target.value)}),options:Va.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`When the sensor is linked to several cameras, all of them are photographed the moment it fires. Cameras that are offline or asleep are left out.`})]}),V.carriesMedia&&V.carriesSubjectCrop&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),u(H,{value:C.mediaFrame??``,onChange:e=>P({mediaFrame:Ba(e.target.value)}),options:za.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`What the attached still shows. "Automatic" leaves it to the attachment mode above.`})]})]}),n(`div`,{className:`space-y-2`,children:[u(Oi,{label:`Notification title`,value:C.templateTitle,onChange:e=>P({templateTitle:e}),vars:he(`title`),testId:`rule-template-title`}),u(Oi,{label:`Notification body`,value:C.templateBody,onChange:e=>P({templateBody:e}),vars:he(`body`),multiline:!0,testId:`rule-template-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank for the hub's own wording (editable on the Texts tab).`}),Xo(C)!==null&&u(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:Xo(C)}),u(ki,{context:me(`body`),title:C.templateTitle,body:C.templateBody,testId:`rule-template-preview`})]})]}),n(L,{value:`conditions`,className:`space-y-4`,children:[n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:ue?`Which system events`:gs(C.conditions)??`Conditions`}),C.conditions.audio!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`This is a SOUND rule: it fires on a confirmed sampling window of audio, never on a picture. Name the sounds and/or keep a level threshold — with neither it can never match. Everything else below still composes (a camera scope, a schedule).`}),C.conditions.occupancy!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`This is an OCCUPANCY rule: it fires when the count in a camera frame or a zone crosses your threshold and holds. Pick the camera on the Devices tab first — the zone list is that camera's.`}),ue&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`Pick the events this rule reacts to, then narrow them if you want. Nothing else on a system rule is a condition — there is no detection behind it.`}),o.length===0?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):u(Cc,{catalog:Zo(C)?o.filter(e=>e.id!==`schedule`):o,taxonomy:s,delivery:C.delivery,conditions:C.conditions,classScope:C.classScope,onClassScopeChange:e=>P({classScope:e}),onTrigger:C.actions.sequences,savedConditions:S.conditions,schedule:C.schedule,deviceIds:Wo(C),cameras:d,fleet:g,allDevices:h,gateable:f,gateableScenes:m,onConditionsChange:e=>P({conditions:e}),onScheduleChange:e=>P({schedule:e})})]}),ue&&u(Hl,{value:C.systemEventDelivery,family:fe,onChange:e=>P({systemEventDelivery:e}),draft:()=>fs(C,te,o)}),x&&e&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test this rule for real`}),u(kl,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...Wo(C)[0]===void 0?{}:{fallbackDeviceId:Wo(C)[0]}})]}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Builds the event this rule is about, runs the REAL evaluation and delivery, and sends the notification to every target — marked [TEST] in the body. The cooldown and the camera mute are bypassed (neither window is consumed); the rule's actions are never run. Saved conditions only: save first to test an edit.`})]}),!ue&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),n(R,{size:`sm`,variant:`outline`,type:`button`,disabled:ne.isPending||!Qo(C),onClick:()=>{E(null),ne.mutate()},children:[ne.isPending?u(B,{className:`h-3.5 w-3.5 animate-spin`}):u(de,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),D!==null&&u(du,{delivery:C.delivery,results:D,targetNames:I})]})]})]})]}),ge.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 `,ge.length,` condition`,ge.length===1?``:`s`,` this kind of rule cannot use:`]}),ge.map(e=>n(`p`,{children:[u(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),le.length>0&&u(`div`,{"data-testid":`rule-form-problems`,className:`mt-3 shrink-0 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1`,children:le.map(e=>u(`p`,{children:e},e))}),n(`div`,{className:`flex shrink-0 justify-end gap-2 mt-4`,children:[u(R,{variant:`secondary`,size:`sm`,type:`button`,onClick:y,children:`Cancel`}),n(R,{size:`sm`,type:`button`,disabled:F.isPending||!Qo(C),onClick:()=>{E(null),F.mutate()},children:[F.isPending&&u(B,{className:`h-3.5 w-3.5 animate-spin`}),x?`Save changes`:`Create rule`]})]})]})}):u(uu,{rule:e,onCancel:y})}function uu({rule:e,onCancel:t}){let r=Object.keys(e?.conditions??{});return u(ce,{open:!0,onOpenChange:e=>!e&&t(),children:n(A,{width:`lg`,placement:`sheet-on-mobile`,children:[n(`div`,{className:`flex items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[u(re,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),u(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 `,u(`code`,{children:e?.delivery}),`, which this version of the admin UI cannot author. It is shown exactly as stored and nothing here can change it — editing it with an editor that does not know the trigger would rewrite it. Update the server bundle, or edit this rule from the viewer app.`]}),n(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),u(`dd`,{className:`text-foreground`,children:e?.delivery})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),u(`dd`,{className:`text-foreground`,children:e?.enabled?`yes`:`no`})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),u(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),u(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):`none`})]})]}),u(`div`,{className:`flex justify-end gap-2 mt-4`,children:u(R,{variant:`secondary`,size:`sm`,type:`button`,onClick:t,children:`Close`})})]})})}function du({delivery:e,results:t,targetNames:r}){if(e===`device-event`)return u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`});if(t.length===0)return u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`No records in the last 60 minutes matched — nothing to evaluate.`});let i=t.filter(e=>e.wouldFire).length;return n(`div`,{className:`mt-2 space-y-1.5`,children:[n(`div`,{className:`text-[11px] text-foreground-subtle`,children:[i,` of `,t.length,` evaluated record`,t.length===1?``:`s`,` would fire.`]}),u(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>n(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?u(O,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(N,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),n(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`object`}),e.wouldFire?n(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,r.join(`, `)||`targets`]}):e.failedCondition&&n(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}var fu=[{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 pu(e){return fu.find(t=>t.value===e)?.value}function mu(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function hu(e){return``}var gu={x:.25,y:.25,w:.5,h:.5},_u={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function vu(){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:gu,occupancy:_u,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function yu(e){return e.deviceId!==null}function bu(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function xu(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Su(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 Cu(e){if(e.deviceId===null)return null;let t=e.trigger,n=xu(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:wu(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 wu(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 Tu(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Eu(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 Du(e){let t=vu(),n=e.conditions,r=Eu(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:Tu(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Tu(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Tu(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:hu(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Ou(n.occupancy)},onlyRuleId:e.id}}function Ou(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 ku(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 Au(e){return{form:Du(e),caveats:ku(e),ruleName:e.name}}var ju=null;function Mu(e){ju=e}function Nu(){return ju}function Pu(){ju=null}var Fu=[`n/a`,`clear`,`suppressed`,`bypassed`],Iu=[`live`,`none`,`unavailable`,`unattachable`];function Lu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ru(e,t){let n=e[t];return typeof n==`string`?n:void 0}function zu(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Bu(e){if(!Lu(e))return null;let t=Ru(e,`ruleId`),n=Ru(e,`ruleName`),r=Ru(e,`cooldown`),i=Fu.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Ru(e,`failedCondition`),o=Array.isArray(e.matchedOn)?zu(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:zu(e,`targetIds`)}}function Vu(e){if(!Lu(e))return null;let t=Ru(e,`recordId`),n=Ru(e,`delivery`),r=Ru(e,`still`),i=Iu.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=Bu(e);t!==null&&o.push(t)}let s=Ru(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:zu(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Hu(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 Uu=new Set([`sensor`,`control`,`custom`]);function Wu({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:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),u(Gu,{form:e,kinds:i,loading:a,onPatch:o})]});if(e.trigger===`audio-event`){let r=i.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[u(`label`,{className:K,children:`Audio classes`}),u(ya,{options:r,value:e.classNames,onChange:e=>o({classNames:e}),loading:a,emptyHint:e.deviceId===null?`Pick a camera first — the audio vocabulary is per camera.`:`This camera advertises no audio kinds. The audio classifier is probably off for it.`,placeholder:`Audio class id…`})]}),n(`div`,{children:[u(`label`,{className:K,children:`Zones`}),u(Es,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]})]})}return e.trigger===`occupancy-event`?n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),u(Ku,{form:e,cameras:t,taxonomy:r,onPatch:o})]}):n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[u(`label`,{className:K,children:`Detected classes`}),c===null?u(xs,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):u(Ss,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),n(`div`,{children:[u(`label`,{className:K,children:`Zones the subject is in`}),u(Es,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),u(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 Gu({form:e,kinds:t,loading:r,onPatch:i}){let o=t.filter(e=>Uu.has(e.category)),s=o.find(t=>t.kind===e.sensorKind);return n(a,{children:[n(`div`,{children:[u(`label`,{className:K,children:`Event kind`}),u(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&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.deviceId===null?`Pick a camera first — sensor and control kinds come from the devices linked to it.`:`This camera has no linked sensor or control device, so it can produce no device event. Link one on the camera page first.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:K,children:`Source device`}),u(v,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>i({sourceDeviceId:bu(e.target.value)??null})}),u(`p`,{className:q,children:s===void 0?`The linked device whose state changed. Filled in for you when you pick a kind.`:`Filled in from "${s.label}" — contributed by device #${s.source.deviceId} via the ${s.source.capName} capability.`})]}),n(`div`,{children:[u(`label`,{className:K,children:`Event type token`}),u(v,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>i({eventType:e.target.value})}),u(`p`,{className:q,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 Ku({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,d=e=>i({occupancy:{...l,...e}});return n(a,{children:[n(`div`,{children:[u(`label`,{className:K,children:`Zone`}),u(Es,{deviceIds:o,cameras:t,value:l.zoneId===``?[]:[l.zoneId],onChange:e=>d({zoneId:e[e.length-1]??``})}),u(`p`,{className:q,children:`Leave empty for the whole frame.`})]}),n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:K,children:`Class`}),u(H,{value:l.className,options:[{value:``,label:`— any class —`},...c.map(e=>({value:e.value,label:e.label}))],onChange:e=>d({className:e.target.value})})]}),n(`div`,{className:`flex flex-wrap items-end gap-3`,children:[n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count now`,u(v,{type:`number`,min:0,className:`w-20`,value:String(l.count),onChange:e=>d({count:bu(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,u(v,{type:`number`,min:0,className:`w-20`,value:String(l.previousCount),onChange:e=>d({previousCount:bu(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,u(v,{type:`number`,min:1,className:`w-20`,value:String(l.threshold),onChange:e=>d({threshold:bu(e.target.value)??1})})]}),n(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[u(M,{checked:l.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function qu({form:e,cameras:t,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId];return n(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[u(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Advanced`}),n(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(M,{checked:e.crossingEnabled,onCheckedChange:e=>r({crossingEnabled:e}),"aria-label":`zone crossing`}),`This event is a confirmed zone crossing`]}),e.crossingEnabled&&n(`div`,{className:`mt-1 space-y-1.5`,children:[u(`div`,{className:`max-w-[12rem]`,children:u(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`})})}),u(Es,{deviceIds:i,cameras:t,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>r({crossingZoneId:e[e.length-1]??``})})]})]}),n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(M,{checked:e.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),u(`p`,{className:q,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&u(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,u(v,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:n=>r({bbox:{...e.bbox,[t]:bu(n.target.value)??0}})})]},t))})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:K,children:`Happened at`}),n(`div`,{className:`flex items-center gap-2`,children:[u(v,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:Su(Date.now())}),children:`Set`}):u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:`Now`})]}),u(`p`,{className:q,children:`Empty = now. Set it to a time inside (or outside) a rule's schedule window to test the schedule without waiting for the hour.`})]}),n(`div`,{children:[u(`label`,{className:K,children:`Detection source`}),u(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 Ju({checked:e,label:t,hint:r,danger:i=!1,onChange:a}){return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(M,{checked:e,onCheckedChange:a,"aria-label":t}),t,i&&u(U,{variant:`danger`,children:`actuates devices`})]}),u(`p`,{className:q,children:r})]})}t();var Yu={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.`},Xu={"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 Zu({result:e,targetName:t}){return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[u(`p`,{className:`text-xs font-medium text-foreground`,children:Hu(e)}),n(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[u(Qu,{recordId:e.recordId}),n(`span`,{children:[`delivery `,u(`span`,{className:`text-foreground`,children:e.delivery})]}),n(`span`,{children:[`candidates `,u(`span`,{className:`text-foreground`,children:e.candidates})]}),n(`span`,{title:Yu[e.still],children:[`still `,u(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&n(U,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&u(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>u(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`No rule was evaluated. Either no enabled rule declares the`,` `,u(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):u(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>u($u,{outcome:e,targetName:t},e.ruleId))})]})}function Qu({recordId:e}){let[t,r]=c(!1);return n(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[u(`code`,{className:`text-[10px] text-foreground`,children:e}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)},()=>r(!1))},title:`Copy record id`,children:u(y,{className:`h-3 w-3`})}),t&&u(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function $u({outcome:e,targetName:t}){return n(`li`,{className:`space-y-1 px-2.5 py-2`,children:[n(`div`,{className:`flex items-center gap-2`,children:[e.matched?u(O,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(N,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),n(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:Xu[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&u(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?`Did not match. The engine reported no failing condition id.`:n(a,{children:[`Did not match — first failing condition`,` `,u(`code`,{className:`text-foreground`,children:e.failedCondition}),`.`]})}),e.matched&&n(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[e.enqueued,` outbox row`,e.enqueued===1?``:`s`,` enqueued`,e.targetIds.length>0?` → ${e.targetIds.map(t).join(`, `)}`:` — no target resolved, so nothing will be delivered`,`.`]}),e.matchedOn!==void 0&&e.matchedOn.length>0&&n(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:[`matched on: `,e.matchedOn.join(`, `)]})]})}t();var ed=`pipeline-analytics`,td=`nc.injectTestEvent`;function nd(){let e=p(),[t,a]=c(()=>Nu()?.form??vu()),[o]=c(()=>Nu()?.caveats??[]),[s]=c(()=>Nu()?.ruleName??null);d(()=>Pu(),[]);let[f,m]=c(null),[h,g]=c(!1),[_,y]=c(null),b=e=>a(t=>({...t,...e})),x=me({projection:`slim`}),S=i({queryKey:tu,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),C=i({queryKey:$l,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),w=i({queryKey:eu,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===Ve.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=l({mutationFn:async()=>{let n=Cu(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:ed,action:td,input:n})},onMutate:()=>{m(null),g(!1),y(null)},onSuccess:e=>{let t=Vu(e);m(t),g(t===null)},onError:e=>y(e instanceof Error?e.message:`The simulation failed.`)}),M=mu(t.trigger),N=C.data?.find(e=>e.id===t.onlyRuleId);return n(W,{icon:de,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&&u(I,{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 `,u(`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&&u(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:o.map(e=>n(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[u(V,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId))}),n(z,{className:`space-y-4`,children:[n(`div`,{children:[u(`label`,{className:K,children:`Camera`}),u(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:bu(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),u(`p`,{className:q,children:`The camera the event is attributed to — what a notification shows.`})]}),n(`div`,{children:[u(`label`,{className:K,children:`Trigger`}),u(H,{"data-testid":`simulate-trigger`,value:t.trigger,options:fu.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=pu(e.target.value);if(!n)return;let r=hu(t.trigger);b({trigger:n,source:t.source===``||t.source===r?hu(n):t.source})}}),n(`p`,{className:q,children:[fu.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,u(`span`,{className:`text-foreground`,children:M}),` are candidates.`]})]}),u(Wu,{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:[u(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),n(`div`,{className:`mt-2 space-y-3`,children:[u(`p`,{className:q,children:`Every field here can be left EMPTY, and empty is a real state: a rule with a minimum confidence FAILS on a subject that carries none. Leave one blank to reproduce exactly that.`}),n(`div`,{children:[u(`label`,{className:K,children:`Label (identity name / plate / subclass)`}),u(v,{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:[u(`label`,{className:K,children:`Detection confidence`}),u(Cs,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>b({confidence:e})})]}),n(`div`,{children:[u(`label`,{className:K,children:`Label-match confidence`}),u(Cs,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>b({labelConfidence:e})})]}),n(`div`,{children:[u(`label`,{className:K,children:`Importance`}),u(Cs,{value:t.importance,min:0,max:1,step:.05,onChange:e=>b({importance:e})})]}),n(`div`,{children:[u(`label`,{className:K,children:`Dwell (seconds)`}),u(Cs,{value:t.dwellSeconds,min:0,step:1,onChange:e=>b({dwellSeconds:e})})]})]})]})]}),u(qu,{form:t,cameras:D,onPatch:b}),n(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),u(Ju,{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})}),u(Ju,{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})}),u(Ju,{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:[u(`label`,{className:K,children:`Still image`}),u(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:[u(`label`,{className:K,children:`Evaluate only one rule`}),u(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 `,u(`code`,{children:t.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),_!==null&&u(`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:[u(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`}),n(R,{size:`sm`,type:`button`,disabled:j.isPending||!yu(t),onClick:()=>j.mutate(),children:[j.isPending?u(B,{className:`h-3.5 w-3.5 animate-spin`}):u(de,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),h&&u(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:`The hub answered, but this build could not read the answer. That is what a hub older than the simulator looks like — update the server, then re-run.`}),f!==null&&u(Zu,{result:f,targetName:e=>A.get(e)??e})]})}var Y=`block text-[11px] font-medium text-foreground mb-1`,X=`mt-1 text-[10px] text-foreground-subtle`;function Z({title:e,hint:t,children:r}){return n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),u(`div`,{className:`space-y-3`,children:r})]})}function rd({problems:e,testId:t=`digest-problems`}){return e.length===0?null:n(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":t,children:[n(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[u(V,{className:`h-3.5 w-3.5`}),`This rule could never produce anything, so it cannot be saved:`]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function id({warnings:e,testId:t=`digest-warnings`}){return e.length===0?null:n(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":t,children:[n(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[u(fe,{className:`h-3.5 w-3.5`}),`Worth knowing:`]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function ad({cameras:e,value:t,onChange:r,fleet:i,hint:a}){return n(`div`,{className:`space-y-1`,children:[u(wr,{devices:e,listState:i.state,fleet:i,value:t,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),a!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function od({targets:e,value:t,onChange:r}){let i=e=>r(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return e.length===0?u(`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.`}):u(`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:[u(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>i(e.id),className:`accent-primary`,"data-testid":`digest-target-${e.id}`}),u(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&u(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:d=!1}){return n(`div`,{children:[u(`label`,{className:Y,children:e}),u(v,{type:`number`,value:t===void 0?``:String(t),disabled:d,...i===void 0?{}:{min:i},...a===void 0?{}:{max:a},...o===void 0?{}:{step:o},...c===void 0?{}:{placeholder:c},...l===void 0?{}:{"data-testid":l},onChange:e=>{let t=e.target.value.trim();if(t.length===0){r(void 0);return}let n=Number(t);Number.isFinite(n)&&r(n)}}),s!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function sd({label:e,checked:t,onChange:r,hint:i,testId:a}){return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(M,{checked:t,onCheckedChange:r,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),i!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:i})]})}function cd({title:e,body:t,onTitleChange:r,onBodyChange:i,family:a,testIdPrefix:o}){let s=Ci(),c=e=>s.data?yi(s.data,{family:a,field:e}):void 0;return n(`div`,{className:`space-y-2`,children:[u(Oi,{label:`Notification title`,value:e,onChange:r,vars:c(`title`),testId:`${o}-title`}),u(Oi,{label:`Notification body`,value:t,onChange:i,vars:c(`body`),multiline:!0,testId:`${o}-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank to use the hub's own wording (editable on the Texts tab).`}),u(ki,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function ld({open:e,ruleName:t,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){return e?u(ce,{open:!0,onOpenChange:e=>!e&&s(),children:u(A,{width:`sm`,children:n(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[n(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[u(ye,{className:`h-4 w-4 text-warning`}),`Send a real notification now?`]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[`"`,t,`" will be produced over `,r,` and DELIVERED to`,` `,i,` — on every phone that target reaches, right now. This is not a dry run.`]}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`It does not consume the schedule: the next scheduled run still happens.`}),c,n(`div`,{className:`flex justify-end gap-2`,children:[u(R,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),u(R,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?`Sending…`:`Produce and send`})]})]})})}):null}function ud(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 dd=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function fd(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function pd(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>dd[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${fd(t.startMinute)}–${fd(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function md(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${ud(Math.round(r/1e3))} ago`}function hd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gd(e){return Array.isArray(e)?`[${e.map(gd).join(`,`)}]`:hd(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${gd(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function _d(e,t){return gd(e)===gd(t)}function vd(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,yd=`nc.getTexts`,bd=`nc.setLanguage`,xd=`nc.setTextOverrides`,Sd={en:`English`,it:`Italiano`};function Cd(e){return e===`en`||e===`it`}function wd(e){return e===`override`||e===`shipped`||e===`fallback`}function Td(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ed(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 Dd(e){if(!Td(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`||!Cd(r)||!wd(o)||i!==null&&typeof i!=`string`)return null;let s=Ed(e.placeholders),c=Ed(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 Od(e){if(!Td(e))return null;let{language:t,activeLanguage:n}=e;if(!Cd(t)||!Cd(n))return null;let r=Ed(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Cd(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=Dd(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function kd(e,t){return t.get(e.key)??e.override??e.shipped}function Ad(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 jd(e,t){return Object.keys(Ad(e,t)).length}function Md(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 Nd(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Pd(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 Fd=`nc.listSummaryRules`,Id=`nc.upsertSummaryRule`,Ld=`nc.deleteSummaryRule`,Rd=`nc.testSummaryRule`,zd=3600,Bd=86400,Vd=3600,Hd=3600,Ud=3*36e5,Wd=[`importance`,`recency`,`dwell`],Gd={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},Kd=[`none`,`tiles`,`all`],qd=`none`,Jd={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},Yd=[`en`,`it`],Xd=[`deliver-without-text`,`skip`],Zd=2048,Qd=2e3;function $d(e){return e.window.kind!==`unsupported`&&!e.readOnly}function ef(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tf(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 nf(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 rf(e){if(e!==void 0)return typeof e==`string`?e:null}function af(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function of(e){return Wd.some(t=>t===e)}function sf(e){return e===void 0?qd:Kd.find(t=>t===e)??null}function cf(e){if(!ef(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!ef(n))return null;let e=tf(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=rf(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 lf(e){if(!ef(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=cf(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 uf(e){if(e==null)return;if(!ef(e))return null;let t=e.classes===void 0?void 0:nf(e.classes),n=e.classesExclude===void 0?void 0:nf(e.classesExclude),r=e.zones===void 0?void 0:nf(e.zones);if(t===null||n===null||r===null)return null;let i=af(e.minImportance),a=af(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 df(e){if(e==null)return;if(!ef(e))return null;let t=rf(e.title),n=rf(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function ff(e){return Yd.some(t=>t===e)}function pf(e){return Xd.some(t=>t===e)}function mf(e){if(e==null)return;if(!ef(e)||typeof e.enabled!=`boolean`)return null;let t=rf(e.profileId),n=rf(e.prompt);if(t===null||n===null)return null;let r=af(e.maxImagePx),i=af(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!ff(a))return null;let o=e.onFailure;return o!==void 0&&!pf(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 hf(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!ef(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!ef(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function gf(e){if(!ef(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`||!of(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=tf(e.deviceIds),u=lf(e.window),d=hf(e.targets);if(l===null||u===null||d===null)return null;let f=uf(e.filters),p=df(e.template);if(f===null||p===null)return null;let m=rf(e.captionText),h=af(e.generatedAt),g=af(e.updatedAt);if(m===null||h===null||g===null)return null;let _=sf(e.captions);if(_===null)return null;let v=mf(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 _f(e){if(!ef(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=gf(n);if(e===null)return null;t.push(e)}return t}function vf(e){if(!ef(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=af(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=af(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=rf(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 yf(){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:qd,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function bf(e){let t=yf(),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 xf(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Sf(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 Cf(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 wf(e){return vd(e.targetIds)}function Tf(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 Ef(e){let t=Sf(e),n=Cf(e),r=Tf(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:xf(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:wf(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 Df(e,t){let n=Ef(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),_d(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),_d(n.window,t.window)||(r.window=n.window),_d(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),_d(n.targets,t.targets)||(r.targets=n.targets),_d(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),_d(n.ai,t.ai)||(r.ai=n.ai??null),r}function Of(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 ${zd}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${Bd}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 ${Vd}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 ${Hd}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 ${Qd} 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 ${Zd} 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 kf(e){return Of(e).length===0}function Af(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 jf=[{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`]}],Mf=`rule`;function Nf(e){return jf.find(t=>t.key===e)?.key}function Pf(e){return e.kind===`motion`?`Motion · ${ud(e.quietSeconds)} quiet · max ${ud(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${pd(e.schedule)}`}function Ff(e,t){return md(e,t,`Never run`)}function If(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 ≥ ${ud(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function Lf(e){return{windowStartMs:e-Ud,windowEndMs:e}}t();var Rf={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},zf={en:`English`,it:`Italiano`};function Bf(e){return Wd.find(t=>t===e)}function Vf(e){return Kd.find(t=>t===e)}function Hf(e){return Yd.find(t=>t===e)??``}function Uf(e){return Xd.find(t=>t===e)}function Wf({rule:e,cameras:t,fleet:a,targets:o,taxonomy:s,onSaved:d,onCancel:f}){let m=p(),[h,g]=c(()=>e===null?yf():bf(e)),[_,y]=c(null),[b,x]=c(Mf),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}=ha(h.deviceIds,t.map(e=>({id:e.id,name:e.name}))),E=i({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>m.trpcClient.llm.listProfiles.query({}),retry:!1}),D=(E.data??[]).filter(e=>e.supportsVision),O=l({mutationFn:async()=>{let t=e===null?{rule:Ef(h)}:{ruleId:e.id,patch:Df(h,e)};await m.trpcClient.addons.custom.mutate({addonId:$,action:Id,input:t})},onSuccess:d,onError:e=>y(e instanceof Error?e.message:`Save failed`)}),j=Ci(),M=j.data?yi(j.data,{family:`summary`,field:`captionText`}):void 0,N=h.mosaicCaptions===`all`,P=Of(h),te=Af(h),F=kf(h)&&!O.isPending,ne=jf.some(e=>e.key===b)?b:Mf;return u(ce,{open:!0,onOpenChange:e=>!e&&f(),children:n(A,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[u(Pt,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?`New summary`:`Edit ${e.name}`})]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:f,children:`Cancel`})]}),_!==null&&u(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&u(yl,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),u(rd,{problems:P,testId:`summary-problems`}),u(id,{warnings:te,testId:`summary-warnings`})]}),n(ve,{value:ne,onValueChange:e=>x(Nf(e)??b),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(_e,{className:`mb-3 shrink-0`,children:jf.map(e=>u(ee,{value:e.key,children:e.label},e.key))}),n(k,{className:`pr-1`,children:[n(L,{value:`rule`,className:`space-y-3`,children:[u(Z,{title:`What it is`,hint:`One window, one picture: the best shot of every track the window held, laid out as one mosaic and delivered once.`,children:n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:Y,children:`Name`}),u(v,{value:h.name,onChange:e=>S({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),u(`div`,{className:`pb-1.5`,children:u(sd,{label:`Enabled`,checked:h.enabled,onChange:e=>S({enabled:e}),testId:`summary-enabled`})})]})}),u(Z,{title:`Cameras`,hint:`Every camera in the digest gets at least one tile when it contributed anything — a digest in which two of six cameras never appear is not multi-camera.`,children:u(ad,{cameras:t,value:h.deviceIds,fleet:a,onChange:e=>S({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})})]}),u(L,{value:`window`,className:`space-y-3`,children:n(Z,{title:`When the window closes`,children:[n(`div`,{children:[u(`label`,{className:Y,children:`Window`}),u(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:[u(Q,{label:`Quiet period (seconds)`,value:h.quietSeconds,min:30,max:zd,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`}),u(Q,{label:`Longest window (seconds)`,value:h.maxWindowSeconds,min:60,max:Bd,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:[u(`label`,{className:Y,children:`Weekly windows`}),u(Ys,{value:h.schedule,onChange:e=>S({schedule:e})}),u(`p`,{className:X,children:`The digest is produced when a window CLOSES, and covers exactly that window. The first one is the first window that closes after you save — nothing is backfilled.`})]}),u(Q,{label:`Wait for open tracks (seconds)`,value:h.barrierSeconds,min:0,max:Vd,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`})]})}),u(L,{value:`content`,className:`space-y-3`,children:n(Z,{title:`What goes in`,hint:`Evaluated on tracks: one passage is one tile.`,children:[n(`div`,{children:[u(`label`,{className:Y,children:`Classes`}),u(ya,{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}),u(`p`,{className:X,children:`Empty = every class. Only the macro classes are offered: a digest matches the class stored on the track, and tracks store macros — a sub-type would match nothing, forever.`})]}),n(`div`,{children:[u(`label`,{className:Y,children:`Excluded classes`}),u(ya,{options:C,value:h.classesExclude,onChange:e=>S({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),n(`div`,{children:[u(`label`,{className:Y,children:`Zones`}),u(ya,{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}),u(`p`,{className:X,children:`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Minimum importance`,value:h.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>S({minImportance:e}),hint:`The pipeline's own score, 0–1. Empty keeps everything.`,testId:`summary-min-importance`}),u(Q,{label:`Minimum stay (seconds)`,value:h.minDwellSeconds,min:0,max:Hd,emptyPlaceholder:`any`,onChange:e=>S({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]}),u(sd,{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`})]})}),u(L,{value:`mosaic`,className:`space-y-3`,children:n(Z,{title:`The mosaic`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Tiles`,value:h.maxTiles,min:1,max:24,onChange:e=>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:[u(`label`,{className:Y,children:`When there are more tracks than tiles`}),u(H,{value:h.rank,options:Wd.map(e=>({value:e,label:Gd[e]})),onChange:e=>{let t=Bf(e.target.value);t!==void 0&&S({rank:t})},"data-testid":`summary-rank`}),u(`p`,{className:X,children:`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`})]})]}),n(`div`,{children:[u(`label`,{className:Y,children:`Text on the mosaic`}),u(H,{value:h.mosaicCaptions,options:Kd.map(e=>({value:e,label:Jd[e]})),onChange:e=>{let t=Vf(e.target.value);t!==void 0&&S({mosaicCaptions:t})},"data-testid":`summary-captions`}),u(`p`,{className:X,children:`Images only is the default, and it is what a rule with nothing set here does. Anything drawn is burnt into the picture for good — a label covers the bottom of the tile, which is where feet, wheels and parcels are, and a caption from a detection that was wrong cannot be un-drawn. Nothing downstream needs the words: the written summary reads the frames themselves and is told the camera, the class and the time in its prompt.`})]}),n(`div`,{children:[u(Oi,{label:`Caption burned onto the mosaic`,value:h.captionText,disabled:!N,onChange:e=>S({captionText:e}),placeholder:`Leave empty for no caption`,vars:M,testId:`summary-caption`}),u(`p`,{className:X,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.`})]})]})}),u(L,{value:`ai`,className:`space-y-3`,children:n(Z,{title:`Written summary`,hint:`One vision call over the window's best frames TOGETHER, so the answer is an account of what happened rather than a list of pictures. The sentence goes in the notification body.`,children:[u(sd,{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&&u(`p`,{className:`rounded-md border border-border bg-surface px-2.5 py-1.5 text-[10px] text-foreground-muted`,"data-testid":`summary-ai-off-note`,children:`The switch above is off, so nothing below it can be edited. Everything you already set is kept — turning it on hands the fields back exactly as you left them.`}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:Y,children:`Vision profile`}),u(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`}),u(`p`,{className:X,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:[u(`label`,{className:Y,children:`Answer in`}),u(H,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:`Don’t ask for a language`},...Yd.map(e=>({value:e,label:zf[e]}))],onChange:e=>S({aiLanguage:Hf(e.target.value)}),"data-testid":`summary-ai-language`}),u(`p`,{className:X,children:`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`})]})]}),n(`div`,{children:[u(`label`,{className:Y,children:`Your question (optional)`}),u(`textarea`,{value:h.aiPrompt,rows:3,maxLength:Qd,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`}),u(`p`,{className:X,children:`Leave blank for “what happened during this period?”. Your words are the only free text the model is given: what the cameras are called and what the pipeline classified are reduced to plain labels first, and anything written INSIDE a frame — a sign, a plate, an overlay — is treated as scenery, never as an instruction.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Frames the model may look at`,value:h.maxAiImages,min:1,max:8,disabled:!h.aiEnabled,onChange:e=>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`}),u(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:[u(Q,{label:`Frame size sent (pixels)`,value:h.aiMaxImagePx,min:64,max:Zd,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:[u(`label`,{className:Y,children:`If the model gives no answer`}),u(H,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:Xd.map(e=>({value:e,label:Rf[e]})),onChange:e=>{let t=Uf(e.target.value);t!==void 0&&S({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),u(`p`,{className:X,children:`A cold model, an unreachable endpoint or an answer the hub cannot parse are all this case. The default delivers: the mosaic and the counts are worth more than silence, and a closed window does not come back.`})]})]})]})}),u(L,{value:`delivery`,className:`space-y-3`,children:n(Z,{title:`Delivery`,children:[u(od,{targets:o,value:h.targetIds,onChange:e=>S({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Priority`,value:h.priority,min:1,max:5,onChange:e=>S({priority:e??3}),testId:`summary-priority`}),u(sd,{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`})]}),u(cd,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>S({templateTitle:e}),onBodyChange:e=>S({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),n(`p`,{className:X,children:[u(`code`,{children:`{{ai}}`}),` is the written summary. A body that never names it still gets the sentence, appended on its own line — a template written before the AI pass existed must not make the feature look broken.`]})]})})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[u(R,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:`Cancel`}),n(R,{size:`sm`,type:`button`,disabled:!F,onClick:()=>O.mutate(),children:[O.isPending&&u(B,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}t();var Gf=[`notificationSummaries`,`listSummaryRules`],Kf=`One window, one picture: every camera’s best moments as a single mosaic.`;function qf(){let e=p(),[t,a]=c({mode:`closed`}),[o,s]=c(null),[d,f]=c(null),[m,h]=c(null),[g,_]=c(!1),v=i({queryKey:Gf,queryFn:async()=>{let t=_f(await e.trpcClient.addons.custom.mutate({addonId:$,action:Fd,input:{}}));return _(t===null),t}}),y=me({projection:`slim`}),b=r(()=>(y.data??[]).filter(e=>e.type===Ve.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[y.data]),x=i({queryKey:eu,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),C=i({queryKey:tu,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),w=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Id,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void v.refetch()}),T=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Ld,input:{ruleId:t}}),onSuccess:()=>{s(null),v.refetch()}}),E=l({mutationFn:async t=>vf(await e.trpcClient.addons.custom.mutate({addonId:$,action:Rd,input:{ruleId:t,...Lf(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(R,{size:`sm`,type:`button`,onClick:()=>a({mode:`form`,rule:null}),"data-testid":`summary-new`,children:[u(S,{className:`h-3.5 w-3.5`}),`New summary`]});return v.isLoading?u(W,{icon:Pt,title:`Summaries`,subtitle:Kf,children:u(B,{className:`h-5 w-5 animate-spin`})}):v.isError||v.data===null?u(W,{icon:Pt,title:`Summaries`,subtitle:Kf,children:u(I,{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(W,{icon:Pt,title:`Summaries`,subtitle:Kf,actions:A,children:[T.isError&&u(I,{title:`Could not delete the rule`,message:String(T.error)}),E.isError&&u(I,{title:`The test run failed`,message:String(E.error)}),m!==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:[m.error===void 0?n(`span`,{children:[`Produced `,m.produced,` digest`,m.produced===1?``:`s`,` — `,m.tiles??0,` tile`,(m.tiles??0)===1?``:`s`,` from `,m.cameras??0,` camera`,(m.cameras??0)===1?``:`s`,`, `,m.matched??0,` track`,(m.matched??0)===1?``:`s`,` matched, `,m.enqueued??0,` `,`notification`,(m.enqueued??0)===1?``:`s`,` sent.`,(m.droppedStationary??0)>0&&n(`span`,{"data-testid":`summary-test-dropped-stationary`,children:[` `,m.droppedStationary,` parked object`,m.droppedStationary===1?``:`s`,` left out.`]})]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,m.error]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>h(null),children:`Dismiss`})]}),D.length===0?u(`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.`}):u(z,{children:u(pe,{columns:Jf({nowMs:Date.now(),targetNameById:k,confirmDeleteId:o,deletePending:T.isPending,onToggle:(e,t)=>w.mutate({ruleId:e.id,enabled:t}),onEdit:e=>{$d(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:ae})}),t.mode===`form`&&u(Wf,{rule:t.rule,cameras:b,fleet:Ql(y),targets:O,taxonomy:C.data?.taxonomy,onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),v.refetch()}}),u(ld,{open:d!==null,ruleName:d?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${d?.targets.length??0} target${(d?.targets.length??0)===1?``:`s`}`,pending:E.isPending,onCancel:()=>f(null),onConfirm:()=>{d!==null&&E.mutate(d.id)}})]})}function Jf(e){return[{key:`name`,header:`Digest`,render:e=>n(`span`,{className:`flex flex-wrap items-center gap-2`,children:[u(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&u(U,{variant:`warning`,children:`disabled`}),!$d(e)&&u(U,{variant:`warning`,children:`read-only`}),e.ai?.enabled===!0&&u(U,{variant:`info`,children:`AI`}),e.ai!==void 0&&!e.ai.enabled&&u(U,{variant:`default`,children:`AI off`})]})},{key:`cameras`,header:`Cameras`,align:`center`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:`Window`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Pf(e.window)})},{key:`filters`,header:`Keeps`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:If(e.filters)})},{key:`mosaic`,header:`Mosaic`,nowrap:!0,render:e=>n(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.maxTiles,` tiles · `,e.rank]})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:Ff(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(M,{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:[u(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onTest(t),title:`Produce this digest now and DELIVER it`,"aria-label":`test ${t.name}`,"data-testid":`summary-test-${t.id}`,children:u(de,{className:`h-3.5 w-3.5`})}),u(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:!$d(t),onClick:()=>e.onEdit(t),"aria-label":`edit ${t.name}`,"data-testid":`summary-edit-${t.id}`,children:u(te,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?n(`span`,{className:`flex items-center gap-1`,children:[u(R,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),"data-testid":`summary-delete-confirm-${t.id}`,children:`Delete`}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):u(R,{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:u(h,{className:`h-3.5 w-3.5`})})]})}]}var Yf=e=>typeof e==`string`&&e.length>0;function Xf(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 Zf(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Qf(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Yf(i)&&n.push({mediaType:r,url:i})}return n}function $f(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Yf(r.label),i=Yf(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 ep(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Qf(e,t.attachmentUrls),i=$f(e,t.actions),a=e.ttl&&Yf(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:Zf(e,t.format),priority:tp(t.priority),...Yf(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Yf(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Yf(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Yf(t.tag)?{tag:t.tag}:{}}}function tp(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function np(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 rp(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var ip={image:f(`/addon/notifiers/samples/image`),video:f(`/addon/notifiers/samples/video`),gif:f(`/addon/notifiers/samples/gif`),audio:f(`/addon/notifiers/samples/audio`),icon:f(`/addon/notifiers/samples/icon`)};function ap(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function op(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])ap(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function sp(e,t,n){let r=rp(e);return ap(e,t)?{...r,body:n,attachmentUrls:{[t]:ip[t]}}:{...r,body:n}}function cp(e,t){let n=rp(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return sp(e,`image`,`Test notification with an image.`);case`gif`:return sp(e,`gif`,`Test notification with an animation.`);case`video`:return sp(e,`video`,`Test notification with a video.`);case`audio`:return sp(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=np(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 lp={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},up=`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`,dp=`block text-[11px] font-medium text-foreground mb-1`;function fp({target:e,kind:t,open:i,onClose:a}){let o=p(),s=r(()=>Xf(t.caps),[t.caps]),d=r(()=>op(t.caps),[t.caps]),[f,m]=c(()=>rp(t.caps)),[h,g]=c(null),_=r(()=>ep(t.caps,f),[t.caps,f]),v=f.body.length,y=v>s.bodyMaxLen,x=e=>m(t=>({...t,...e})),S=l({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:ep(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=>{m(cp(t.caps,e)),g(null)},T=(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},x({actions:r})};return u(ce,{open:i,onOpenChange:e=>!e&&a(),children:n(A,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[u(w,{children:n(D,{children:[`Test "`,e.name,`" (`,t.label,`)`]})}),n(k,{className:`space-y-4 pr-1`,children:[u(`div`,{className:`flex flex-wrap gap-1.5`,children:d.map(e=>u(R,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>C(e),children:lp[e]},e))}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.levels.length>0&&n(`div`,{children:[u(`label`,{className:dp,children:`Level`}),n(`select`,{className:up,value:f.level,onChange:e=>x({level:e.target.value}),children:[u(`option`,{value:``,children:`— derive from priority —`}),s.levels.map(e=>n(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=s.levels.find(e=>e.id===f.level);return e?n(`div`,{className:`mt-1 space-y-1`,children:[e.description&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),n(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&u(U,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&u(U,{variant:`info`,children:`silent`}),e.flags?.noPush&&u(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:dp,children:[`Priority (ordinal): `,f.priority]}),u(`input`,{type:`range`,min:1,max:5,step:1,value:f.priority,onChange:e=>x({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),s.formats.length>0&&n(`div`,{children:[u(`label`,{className:dp,children:`Format`}),u(`div`,{className:`flex flex-wrap gap-2`,children:s.formats.map(e=>n(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:f.format===e,onChange:()=>x({format:e})}),e]},e))})]}),n(`div`,{children:[u(`label`,{className:dp,children:`Title`}),u(`input`,{className:up,value:f.title,onChange:e=>x({title:e.target.value})})]}),n(`div`,{children:[n(`label`,{className:dp,children:[`Body`,` `,n(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,s.bodyMaxLen,y?` — overflow`:``,`)`]})]}),u(`textarea`,{className:`${up} min-h-[80px] resize-y`,value:f.body,onChange:e=>x({body:e.target.value})})]}),s.attachmentSlots.length>0&&n(`div`,{children:[n(`label`,{className:dp,children:[`Attachments`,` `,n(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,s.attachmentMode,`, max `,s.attachmentMax,s.attachmentMaxBytes?`, ≤${Math.round(s.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),u(`div`,{className:`space-y-1.5`,children:s.attachmentSlots.map(e=>n(`div`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),u(`input`,{className:up,placeholder:`${e} URL`,value:f.attachmentUrls[e]??``,onChange:t=>x({attachmentUrls:{...f.attachmentUrls,[e]:t.target.value}})})]},e))})]}),s.showActions&&n(`div`,{children:[n(`label`,{className:dp,children:[`Actions (up to `,s.maxActions,`)`]}),u(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(s.maxActions,3)},(e,t)=>n(`div`,{className:`flex items-center gap-2`,children:[u(`input`,{className:up,placeholder:`label`,value:f.actions[t]?.label??``,onChange:e=>T(t,`label`,e.target.value)}),u(`input`,{className:up,placeholder:`url`,value:f.actions[t]?.url??``,onChange:e=>T(t,`url`,e.target.value)})]},t))})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.showClickUrl&&n(`div`,{children:[u(`label`,{className:dp,children:`Click URL`}),u(`input`,{className:up,value:f.clickUrl,onChange:e=>x({clickUrl:e.target.value})})]}),s.showSound&&n(`div`,{children:[u(`label`,{className:dp,children:`Sound`}),u(`input`,{className:up,value:f.sound,onChange:e=>x({sound:e.target.value})})]}),s.showTtl&&n(`div`,{children:[u(`label`,{className:dp,children:`TTL (seconds)`}),u(`input`,{className:up,type:`number`,value:f.ttl,onChange:e=>x({ttl:e.target.value})})]}),s.showTag&&n(`div`,{children:[u(`label`,{className:dp,children:`Tag`}),u(`input`,{className:up,value:f.tag,onChange:e=>x({tag:e.target.value})})]})]}),h&&u(pp,{result:h}),n(`details`,{className:`text-[10px]`,children:[u(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),u(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),n(b,{children:[u(R,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),n(R,{size:`sm`,type:`button`,disabled:S.isPending||f.body.length===0,onClick:()=>S.mutate(),children:[S.isPending?u(B,{className:`h-3.5 w-3.5 animate-spin`}):u(ye,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function pp({result:e}){let t=e.renderedAs;return n(`div`,{className:`rounded-md border px-3 py-2 text-xs ${e.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[n(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?u(O,{className:`h-3.5 w-3.5 text-success`}):u(N,{className:`h-3.5 w-3.5 text-danger`}),u(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&u(`p`,{className:`mt-1 text-danger`,children:e.error}),t&&n(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[u(`dt`,{children:`Resolved level`}),u(`dd`,{className:`text-foreground`,children:t.level}),u(`dt`,{children:`Format sent`}),u(`dd`,{className:`text-foreground`,children:t.format}),u(`dt`,{children:`Attachments sent`}),u(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),u(`dt`,{children:`Actions sent`}),u(`dd`,{className:`text-foreground`,children:t.actionsSent}),u(`dt`,{children:`Truncated`}),u(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),u(`dt`,{children:`Dropped`}),u(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function mp(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 hp(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 gp(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 _p(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 vp(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 yp=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function bp(e){return yp.some(t=>e.includes(t))}function xp(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function Sp(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&xp(e[n])!==xp(t[n]))}function Cp(e,t,n,r){if(r===void 0)return Sp(e,t,n);let i=new Set(n),a=_p(e,t,n);return r.filter(n=>i.has(n)?n in a:xp(e[n])!==xp(t[n]))}function wp(e,t,n){let r=_p(e,t,n);return n.filter(e=>!(e in r))}function Tp(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:Tp(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Tp(e.fields,t)}))}:e)}function Ep(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:Tp(e.fields,n)}))}}function Dp({refusal:e,edited:t,reenter:r}){let i=r.length>0?`Re-type: ${r.join(`, `)}.`:null;return e===null?t.length===0||i===null?null:n(`p`,{className:`text-[11px] text-warning`,"data-testid":`target-secret-reenter`,children:[`You changed `,t.join(`, `),`. If that changes where this target sends, the hub will not reuse the stored secret. `,i]}):n(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-secret-refusal`,role:`alert`,children:[u(`p`,{className:`font-semibold`,children:`The hub needs the secret again — nothing was saved.`}),u(`p`,{className:`mt-1`,children:e}),i===null?null:u(`p`,{className:`mt-1 font-medium`,children:i})]})}t();var Op=[`notificationOutput`,`listTargets`],kp=[`notificationOutput`,`listTargetKinds`],Ap=[`userManagement`,`listUsers`],jp=`ownerUserId`;function Mp(e){let t=e.config[jp];return typeof t==`string`&&t.length>0?t:null}function Np(e){return[{key:`name`,header:`Target`,render:t=>{let r=e.kindByKey.get(t.kind);return n(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:r?.label??t.kind,children:u(Pp,{kind:r,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),u(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name}),!t.enabled&&u(U,{variant:`warning`,children:`disabled`})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByKey.get(t.kind)?.label??t.kind})},{key:`owner`,header:`Owner`,nowrap:!0,render:t=>{let n=Mp(t);return n===null?u(U,{variant:`default`,children:`system`}):u(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(M,{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:[u(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(t),title:`Test`,children:u(ye,{className:`h-3.5 w-3.5`})}),u(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onEdit(t,r),title:`Edit`,children:u(te,{className:`h-3.5 w-3.5`})}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:u(h,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function Pp({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?u(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):u(`span`,{className:n,children:e?.icon??`🔔`})}function Fp(){let e=p(),[t,a]=c({mode:`closed`}),[o,s]=c(null),d=i({queryKey:Op,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),f=i({queryKey:kp,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),m=r(()=>f.data??[],[f.data]),h=r(()=>{let e=new Map;for(let t of m)e.set(t.kind,t);return e},[m]),g=i({queryKey:Ap,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=l({mutationFn:t=>e.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:t.target.addonId,targetId:t.target.id,enabled:t.enabled}),onSuccess:()=>void d.refetch()}),y=l({mutationFn:t=>e.trpcClient.notificationOutput.deleteTarget.mutate({addonId:t.addonId,targetId:t.id}),onSuccess:()=>void d.refetch()}),b=o?h.get(o.kind):void 0;return n(W,{icon:T,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(R,{size:`sm`,type:`button`,onClick:()=>a({mode:`pick-kind`}),children:[u(S,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[d.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(B,{className:`h-6 w-6 animate-spin text-primary`})}),d.isError&&!d.isLoading&&u(I,{title:`Failed to load targets`,message:d.error instanceof Error?d.error.message:`Unknown error`,onRetry:()=>void d.refetch()}),!d.isLoading&&!d.isError&&(d.data??[]).length===0&&u(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification targets yet. Click "Add target" to configure one.`}),(d.data??[]).length>0&&u(z,{children:u(pe,{columns:Np({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:d.data??[],rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),t.mode===`pick-kind`&&u(Ip,{kinds:m,onCancel:()=>a({mode:`closed`}),onPick:e=>a({mode:`form`,kind:e,target:null})}),t.mode===`form`&&u(Lp,{kind:t.kind,target:t.target,users:g.data??[],onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),d.refetch()}}),o&&b&&u(fp,{target:o,kind:b,open:!0,onClose:()=>s(null)})]})}function Ip({kinds:e,onPick:t,onCancel:i}){let a=r(()=>mp(e),[e]);return n(z,{className:`p-4 space-y-4`,children:[n(`div`,{className:`flex items-center justify-between`,children:[u(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),a.length===0&&u(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`}),a.map(e=>n(`div`,{children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),u(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(r=>n(`button`,{type:`button`,onClick:()=>t(r),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[u(Pp,{kind:r,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),u(`span`,{className:`font-medium text-foreground`,children:r.label}),r.supportsDiscovery&&u(U,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${r.kind}`))})]},e.addonId))]})}function Lp({kind:e,target:t,users:i,onSaved:a,onCancel:o}){let s=p(),d=r(()=>hp(e.configSchema),[e.configSchema]),f=r(()=>t?.config??{},[t]),[m,h]=c(t?.name??e.label),[g,_]=c(()=>t?vp(t.config,d):{}),[v,y]=c(null),[b,x]=c(null),[S,C]=c(null),[w,T]=c(t?Mp(t)??``:``),E=l({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=l({mutationFn:()=>{let{[jp]:n,...r}=_p(g,f,d),i=w===``?r:{...r,[jp]:w},a={id:t?.id??`${e.kind}-${Date.now()}`,name:m,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`;bp(t)?C(t):x(t)}}),O=r(()=>gp(e.configSchema),[e.configSchema]),k=r(()=>t===null?[]:Cp(g,f,d,e.destinationKeys),[t,g,f,d,e.destinationKeys]),A=r(()=>t!==null&&(S!==null||k.length>0)?wp(g,f,d):[],[t,S,k,g,f,d]),j=r(()=>Ep(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(z,{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:[u(Pp,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),t?`Edit ${t.name}`:`Add ${e.label} target`]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,children:`Cancel`})]}),b&&u(`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:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),u(`input`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,value:m,onChange:e=>h(e.target.value)})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),u(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)}),u(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:`A user-owned target belongs to that user: it shows in their viewer and their own rules may deliver to it. System targets stay admin-managed.`})]}),e.supportsDiscovery&&n(`div`,{className:`space-y-2`,children:[n(R,{size:`sm`,variant:`outline`,type:`button`,disabled:E.isPending,onClick:()=>{x(null),E.mutate()},children:[E.isPending?u(B,{className:`h-3.5 w-3.5 animate-spin`}):u(le,{className:`h-3.5 w-3.5`}),`Discover`]}),v&&v.length===0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),v&&v.length>0&&u(`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:[u(`span`,{className:`text-foreground`,children:e.suggestedName}),u(`span`,{className:`text-[10px] text-primary`,children:`use`})]},`${e.suggestedName}-${t}`))})]}),d.length>0&&t&&u(`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.`}),u(Dp,{refusal:S,edited:k.map(M),reenter:A.map(M)}),u(ne,{schema:j,values:g,onChange:_}),n(`div`,{className:`flex justify-end gap-2`,children:[u(R,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:`Cancel`}),n(R,{size:`sm`,type:`button`,disabled:D.isPending||m.trim().length===0,onClick:()=>{x(null),C(null),D.mutate()},children:[D.isPending&&u(B,{className:`h-3.5 w-3.5 animate-spin`}),t?`Save changes`:`Create target`]})]})]})}t();var Rp=`notificationTexts`,zp=`Every sentence the Notification Center can print — and your wording for it.`;function Bp({entry:e,value:t,busy:r,onChange:i,onReset:a}){let o=Pd(e),s=e.override!==null;return n(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${e.key}`,"data-source":e.source,children:[n(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`code`,{className:`text-xs font-medium`,children:e.key}),s?u(U,{variant:`info`,children:`customised`}):null,e.source===`fallback`?u(U,{variant:`warning`,children:`English fallback`}):null]}),n(`div`,{className:`flex items-start gap-2`,children:[u(`div`,{className:`flex-1`,children:u(Oi,{label:``,value:t,onChange:i,vars:Nd(e),disabled:r,testId:`text-input-${e.key}`})}),u(R,{variant:`ghost`,size:`sm`,disabled:r||!s&&t===e.shipped,onClick:a,title:`Reset to the shipped wording`,"data-testid":`text-reset-${e.key}`,children:u(m,{className:`h-3.5 w-3.5`})})]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[u(`span`,{className:`font-medium`,children:`Shipped:`}),` `,u(`span`,{className:`font-mono`,children:e.shipped})]}),o===null?null:u(`p`,{className:`text-xs text-warning`,children:o})]})}function Vp(){let e=p(),t=s(),[a,o]=c(null),[d,f]=c(``),[m,h]=c(new Map),[g,_]=c(!1),y=i({queryKey:[Rp,a??`hub`],queryFn:async()=>{let t=Od(await e.trpcClient.addons.custom.mutate({addonId:$,action:yd,input:a===null?{}:{language:a}}));return _(t===null),t}}),b=()=>{h(new Map),t.invalidateQueries({queryKey:[Rp]})},x=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:bd,input:{language:t}}),onSuccess:b}),S=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:xd,input:t}),onSuccess:b}),C=y.data??null,w=r(()=>C===null?[]:Md(C.entries,d),[C,d]);if(y.isLoading)return u(W,{icon:Ft,title:`Texts`,subtitle:zp,children:u(B,{className:`h-5 w-5 animate-spin`})});if(y.isError||C===null)return u(W,{icon:Ft,title:`Texts`,subtitle:zp,children:u(I,{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=Ad(C.entries,m),O=jd(C.entries,m),k=C.entries.filter(e=>e.override!==null).length,A=C.languages.map(e=>({value:e,label:Sd[e]})),j=(e,t)=>h(n=>new Map(n).set(e,t)),M=e=>j(e.key,e.shipped);return u(W,{icon:Ft,title:`Texts`,subtitle:zp,children:n(`div`,{className:`flex flex-col gap-4`,children:[x.isError?u(I,{title:`Could not change the language`,message:String(x.error)}):null,S.isError?u(I,{title:`Could not save`,message:String(S.error)}):null,n(z,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-6`,children:[n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:`Hub language`}),u(`div`,{className:`w-44`,children:u(H,{value:C.activeLanguage,disabled:E,options:A,onChange:e=>{let t=e.target.value;Cd(t)&&x.mutate(t)},"data-testid":`texts-hub-language`})}),u(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:`Editing`}),u(`div`,{className:`w-44`,children:u(H,{value:T,disabled:E,options:A,onChange:e=>{let t=e.target.value;Cd(t)&&(h(new Map),o(t))},"data-testid":`texts-editing-language`})}),u(`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.`})]})]}),u(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:`A rule that writes its own title or body still overrides everything here — this page is the wording used when a rule does not.`})]}),n(`div`,{className:`flex flex-wrap items-center gap-3`,children:[n(`div`,{className:`relative min-w-[12rem] flex-1`,children:[u(le,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),u(v,{value:d,placeholder:`Search a key or a sentence…`,onChange:e=>f(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),n(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[w.length,` of `,C.entries.length]}),n(R,{className:`ml-auto`,disabled:E||O===0,onClick:()=>S.mutate({language:T,overrides:D}),"data-testid":`texts-save`,children:[E?u(B,{className:`h-3.5 w-3.5 animate-spin`}):null,O===0?`Save`:`Save ${O}`]})]}),u(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:w.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):w.map(e=>u(Bp,{entry:e,value:kd(e,m),busy:E,onChange:t=>j(e.key,t),onReset:()=>M(e)},e.key))})]})})}var Hp=`nc.listTimelapseRules`,Up=`nc.upsertTimelapseRule`,Wp=`nc.deleteTimelapseRule`,Gp=`nc.testTimelapseRule`,Kp=3600,qp=3600,Jp=30,Yp=1,Xp=[`image`,`gif`],Zp={image:`Still frame`,gif:`Short animation (GIF)`},Qp=Ct({rules:wt(mt.extend({readOnly:Tt().optional()}))});function $p(e){let t=Qp.safeParse(e);return t.success?t.data.rules:null}function em(e){return e.readOnly!==!0}var tm=Ct({produced:xt(),exportId:St().optional(),coveragePercent:xt().optional(),enqueued:xt().optional(),windowStartMs:xt().optional(),windowEndMs:xt().optional(),error:St().optional()});function nm(e){let t=tm.safeParse(e);return t.success?t.data:null}function rm(){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 im(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 am={windows:[{days:[1],startMinute:0,endMinute:60}]};function om(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 sm(e){let t=om(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??am,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:vd(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 cm(e,t){let n=sm(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),_d(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),_d(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??lm(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),_d(n.targets,t.targets)||(r.targets=n.targets),_d(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),_d(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function lm(e){return Math.max(Yp,e/Jp)}function um(e,t,n){return t<=0||n<=0?0:e/t/n}function dm(e,t){return e*t*ot}function fm(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 ${Kp}.`),(!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 ${ot}s and ${qp}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 pm(e){return fm(e).length===0}function mm(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=dm(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 hm(e){return pd(e)}function gm(e,t){return md(e,t,`Never run`)}function _m(e){return e.denseCadenceSec===void 0?{seconds:lm(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}t();var vm=7;function ym(e){return Xp.find(t=>t===e)}function bm({rule:e,cameras:t,fleet:r,targets:i,onSaved:o,onCancel:s}){let d=p(),[f,m]=c(()=>e===null?rm():im(e)),[h,g]=c(null),_=e=>m(t=>({...t,...e})),y=Ci(),b=y.data?yi(y.data,{family:`timelapse`,field:`previewText`}):void 0,x=l({mutationFn:async()=>{let t=e===null?{rule:sm(f)}:{ruleId:e.id,patch:cm(f,e)};await d.trpcClient.addons.custom.mutate({addonId:$,action:Up,input:t})},onSuccess:o,onError:e=>g(e instanceof Error?e.message:`Save failed`)}),S=fm(f),C=mm(f),w=_m(f),T=um(vm,w.seconds,f.framerate),E=pm(f)&&!x.isPending;return u(ce,{open:!0,onOpenChange:e=>!e&&s(),children:n(A,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[u(se,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?`New timelapse`:`Edit ${e.name}`})]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),h!==null&&u(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:h}),n(k,{className:`space-y-3 pr-1`,children:[e!==null&&u(yl,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(rd,{problems:S,testId:`timelapse-problems`}),u(id,{warnings:C,testId:`timelapse-warnings`}),u(Z,{title:`What it is`,hint:`One video per camera, assembled from that camera's RECORDED footage when the window closes.`,children:n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:Y,children:`Name`}),u(v,{value:f.name,onChange:e=>_({name:e.target.value}),placeholder:`e.g. Timelapse ingresso`,"data-testid":`timelapse-name`})]}),u(`div`,{className:`pb-1.5`,children:u(sd,{label:`Enabled`,checked:f.enabled,onChange:e=>_({enabled:e}),testId:`timelapse-enabled`})})]})}),u(Z,{title:`Cameras`,children:u(ad,{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.`})}),u(Z,{title:`When`,children:n(`div`,{children:[u(`label`,{className:Y,children:`Weekly windows`}),u(Ys,{value:f.schedule,onChange:e=>_({schedule:e})}),u(`p`,{className:X,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(Z,{title:`Sampling`,hint:`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Q,{label:`Base cadence (seconds)`,value:f.cadenceSec,min:2,max:Kp,onChange:e=>_({cadenceSec:e??0}),hint:`One frame every N seconds across the quiet parts of the window.`,testId:`timelapse-cadence`}),u(Q,{label:`Output frame rate (fps)`,value:f.framerate,min:1,max:60,onChange:e=>_({framerate:e??0}),hint:`How fast the assembled video plays.`,testId:`timelapse-framerate`})]}),n(`div`,{children:[u(`label`,{className:Y,children:`Dense cadence, near the detections`}),n(`div`,{className:`flex items-center gap-2`,children:[u(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:_m(f).seconds}),"data-testid":`timelapse-dense-mode`}),f.denseCadenceSec!==void 0&&u(v,{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:X,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,w.seconds,`s and `,f.framerate,` fps a`,` `,vm,`-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 (${_m({...f,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),u(Q,{label:`Minimum seconds of video per detection (optional)`,value:f.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>_({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(Z,{title:`The notification`,children:[u(od,{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:[u(`label`,{className:Y,children:`Preview`}),u(H,{value:f.previewMode,options:Xp.map(e=>({value:e,label:Zp[e]})),onChange:e=>{let t=ym(e.target.value);t!==void 0&&_({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),u(Q,{label:`Priority`,value:f.priority,min:1,max:5,onChange:e=>_({priority:e??3}),testId:`timelapse-priority`})]}),n(`div`,{children:[u(Oi,{label:`Caption on the preview frame`,value:f.previewTextSet?f.previewText:``,placeholder:`${Ze} (shipped default)`,onChange:e=>_({previewText:e,previewTextSet:!0}),vars:b,testId:`timelapse-preview-text`}),n(`p`,{className:X,children:[f.previewTextSet&&f.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${Ze}).`,f.previewTextSet&&n(a,{children:[` `,u(`button`,{type:`button`,className:`underline`,onClick:()=>_({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),u(cd,{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`,` `,u(`code`,{children:`{{detectionSummary}}`}),`.`]})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[u(R,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),n(R,{size:`sm`,type:`button`,disabled:!E,onClick:()=>x.mutate(),children:[x.isPending&&u(B,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}t();var xm=[`notificationTimelapses`,`listTimelapseRules`],Sm=`A night of recorded footage, assembled into one short video per camera.`;function Cm(){let e=p(),[t,a]=c({mode:`closed`}),[o,s]=c(null),[d,f]=c(null),[m,h]=c(null),[g,_]=c(!1),v=i({queryKey:xm,queryFn:async()=>{let t=$p(await e.trpcClient.addons.custom.mutate({addonId:$,action:Hp,input:{}}));return _(t===null),t}}),y=me({projection:`slim`}),b=r(()=>(y.data??[]).filter(e=>e.type===Ve.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[y.data]),x=i({queryKey:eu,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),C=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Up,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void v.refetch()}),w=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Wp,input:{ruleId:t}}),onSuccess:()=>{s(null),v.refetch()}}),T=l({mutationFn:async t=>nm(await e.trpcClient.addons.custom.mutate({addonId:$,action:Gp,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?u(W,{icon:se,title:`Timelapses`,subtitle:Sm,children:u(B,{className:`h-5 w-5 animate-spin`})}):v.isError||v.data===null?u(W,{icon:se,title:`Timelapses`,subtitle:Sm,children:u(I,{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(W,{icon:se,title:`Timelapses`,subtitle:Sm,actions:n(R,{size:`sm`,type:`button`,onClick:()=>a({mode:`form`,rule:null}),"data-testid":`timelapse-new`,children:[u(S,{className:`h-3.5 w-3.5`}),`New timelapse`]}),children:[w.isError&&u(I,{title:`Could not delete the rule`,message:String(w.error)}),T.isError&&u(I,{title:`The test run failed`,message:String(T.error)}),m!==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:[m.error===void 0?n(`span`,{children:[`Produced `,m.produced,` video`,m.produced===1?``:`s`,m.coveragePercent===void 0?``:` — ${Math.round(m.coveragePercent)}% of the window had footage`,`, `,m.enqueued??0,` notification`,(m.enqueued??0)===1?``:`s`,` sent.`]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,m.error]}),u(R,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>h(null),children:`Dismiss`})]}),E.length===0?u(`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.`}):u(z,{children:u(pe,{columns:wm({nowMs:Date.now(),cameraNameById:D,targetNameById:k,confirmDeleteId:o,deletePending:w.isPending,onToggle:(e,t)=>C.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=>w.mutate(e.id)}),rows:E,rowKey:e=>e.id,minWidthPx:900,bordered:!1,mobileMode:`scroll`,maxBodyHeight:ae})}),t.mode===`form`&&u(bm,{rule:t.rule,cameras:b,fleet:Ql(y),targets:O,onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),v.refetch()}}),u(ld,{open:d!==null,ruleName:d?.rule.name??``,windowDescription:`its last closed window`,targetDescription:`${d?.rule.targets.length??0} target${(d?.rule.targets.length??0)===1?``:`s`}`,pending:T.isPending,confirmDisabled:d?.deviceId===null,extra:d===null?null:n(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Which camera`}),u(H,{value:d.deviceId===null?``:String(d.deviceId),options:d.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:d.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>f(null),onConfirm:()=>{d!==null&&d.deviceId!==null&&T.mutate({ruleId:d.rule.id,deviceId:d.deviceId})}})]})}function wm(e){return[{key:`name`,header:`Timelapse`,render:e=>n(`span`,{className:`flex flex-wrap items-center gap-2`,children:[u(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&u(U,{variant:`warning`,children:`disabled`}),!em(e)&&u(U,{variant:`warning`,children:`read-only`})]})},{key:`cameras`,header:`Cameras`,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.deviceIds.length===1?e.cameraNameById.get(t.deviceIds[0]??-1)??`#${t.deviceIds[0]}`:`${t.deviceIds.length} cameras`})},{key:`schedule`,header:`Window`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:hm(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let t=_m(im(e));return n(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.cadenceSec,`s · `,e.framerate,`fps · dense `,t.seconds,`s`,t.derived?` (auto)`:``,e.minDwellSec===void 0?``:` · ≥${e.minDwellSec}s/detection`]})}},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:gm(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(M,{checked:t.enabled,disabled:!em(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:[u(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:!em(t),onClick:()=>e.onTest(t),title:`Render this rule's last closed window now and DELIVER it`,"aria-label":`test ${t.name}`,"data-testid":`timelapse-test-${t.id}`,children:u(de,{className:`h-3.5 w-3.5`})}),u(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:!em(t),onClick:()=>e.onEdit(t),"aria-label":`edit ${t.name}`,"data-testid":`timelapse-edit-${t.id}`,children:u(te,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?n(`span`,{className:`flex items-center gap-1`,children:[u(R,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),"data-testid":`timelapse-delete-confirm-${t.id}`,children:`Delete`}),u(R,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):u(R,{size:`sm`,variant:`ghost`,type:`button`,disabled:!em(t),onClick:()=>e.onAskDelete(t.id),"aria-label":`delete ${t.name}`,"data-testid":`timelapse-delete-${t.id}`,children:u(h,{className:`h-3.5 w-3.5`})})]})}]}var Tm=`simulate`;function Em(){let[e,t]=Ot();return u(`div`,{className:`flex flex-col p-4`,children:u(jt,{tabs:[{id:`targets`,label:`Targets`,icon:T,content:u(Fp,{})},{id:`rules`,label:`Rules`,icon:re,content:u(iu,{onSimulateRule:n=>{Mu(Au(n));let r=new URLSearchParams(e);r.set(`tab`,Tm),t(r,{replace:!0})},onOpenHistory:n=>{t(Qr(e,n.id),{replace:!0})}})},{id:Tm,label:`Simulate`,icon:de,content:u(nd,{})},{id:Kr,label:`History`,icon:Nt,content:u(si,{}),ownedParams:Jr},{id:`alarm`,label:`Alarm`,icon:he,content:u(Wr,{})},{id:`summaries`,label:`Summaries`,icon:Pt,content:u(qf,{})},{id:`timelapses`,label:`Timelapses`,icon:se,content:u(Cm,{})},{id:`texts`,label:`Texts`,icon:Ft,content:u(Vp,{})}]})})}export{Em as NotificationsPage,Em as default};