@camstack/addon-admin-ui 1.2.86 → 1.2.88

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 (111) hide show
  1. package/dist/assets/{AddLocationWizard-CVvsaNYx.js → AddLocationWizard-BntkKU2V.js} +1 -1
  2. package/dist/assets/{AddonCollectionPage-JA8tzL7q.js → AddonCollectionPage-DfZQjIPJ.js} +1 -1
  3. package/dist/assets/Addons-Cof7W-Ym.js +1 -0
  4. package/dist/assets/{AdminTabs-B-UL_iuP.js → AdminTabs-FswV6m19.js} +1 -1
  5. package/dist/assets/{AiProfiles-DI31JvyZ.js → AiProfiles-Bol2xzPZ.js} +1 -1
  6. package/dist/assets/{BrokerForm-CFTyH54D.js → BrokerForm-rlgpgB9M.js} +1 -1
  7. package/dist/assets/{Build-BP0Mx9FT.js → Build--P11mU0s.js} +3 -3
  8. package/dist/assets/{Capabilities-BvxWbN6u.js → Capabilities-Di_wIznW.js} +1 -1
  9. package/dist/assets/CapabilityBadges-BOwdQNDH.js +1 -0
  10. package/dist/assets/{Cluster-CsEHMgVp.js → Cluster-B58mM4Kr.js} +1 -1
  11. package/dist/assets/{Data-Bt2o6J7H.js → Data-uwnl2ZR0.js} +1 -1
  12. package/dist/assets/{DetectionIntelligence-CeunXPtW.js → DetectionIntelligence-wpF45dZl.js} +1 -1
  13. package/dist/assets/{DeviceAggregateSection-DLNzCtMs.js → DeviceAggregateSection-r5_ljoI1.js} +1 -1
  14. package/dist/assets/DeviceDetail-Bf3FJFNv.js +2 -0
  15. package/dist/assets/{Devices-fMM-N9UK.js → Devices-D3k50BRl.js} +1 -1
  16. package/dist/assets/{EmbedPlayerPage-D8LRITOt.js → EmbedPlayerPage-C2EWx5XY.js} +1 -1
  17. package/dist/assets/Events-DuXVjBmB.js +1 -0
  18. package/dist/assets/{FormBuilder-ChyOUw_O.js → FormBuilder-QY4tah4S.js} +1 -1
  19. package/dist/assets/{Identity-kjnupMGz.js → Identity-BV8WXb2H.js} +1 -1
  20. package/dist/assets/{IntegrationDetail-683FxnPV.js → IntegrationDetail-ClwD7H7W.js} +1 -1
  21. package/dist/assets/{Integrations-BAa7Hx8I.js → Integrations-BGbVMFT4.js} +1 -1
  22. package/dist/assets/{Integrations-Bvz5KiZt.js → Integrations-Dy_WWWKK.js} +1 -1
  23. package/dist/assets/{Logs-CPMTc4WW.js → Logs-Dr2j0QZR.js} +1 -1
  24. package/dist/assets/{MotionZonesSettings-DhO5kuER.js → MotionZonesSettings-Ds8nYWoN.js} +1 -1
  25. package/dist/assets/{MyAccess-C5kfikXk.js → MyAccess-Bsf24wbg.js} +1 -1
  26. package/dist/assets/Network-D_OMCOsR.js +1 -0
  27. package/dist/assets/{NodeAddonsSettingsPanel-BdP5wGIu.js → NodeAddonsSettingsPanel-B3-jgI6Y.js} +1 -1
  28. package/dist/assets/{NodeInferenceDevices-CubcmlvI.js → NodeInferenceDevices-vixWXUkV.js} +1 -1
  29. package/dist/assets/Notifications-DbYpUqwt.js +1 -0
  30. package/dist/assets/Pipeline-m823fIKM.js +1 -0
  31. package/dist/assets/{Plates-DiVTWUKg.js → Plates-BIkYeFJp.js} +1 -1
  32. package/dist/assets/{PrivacyMaskSettings-zKU6VZ4G.js → PrivacyMaskSettings-C2nmPqsf.js} +1 -1
  33. package/dist/assets/{ProviderIcon-JxmOoO_O.js → ProviderIcon-yuhuUjyO.js} +1 -1
  34. package/dist/assets/Recordings-ChPRJj_w.js +1 -0
  35. package/dist/assets/{ScanNetworkModal-DkqUu2Xc.js → ScanNetworkModal-B6Dhtqhv.js} +1 -1
  36. package/dist/assets/{SceneMonitorEditor-DZucoVrl.js → SceneMonitorEditor-CpU_-6iK.js} +1 -1
  37. package/dist/assets/{Scenes-DMSYbhd1.js → Scenes-Bp-HU3HC.js} +1 -1
  38. package/dist/assets/{Settings-olnTIAze.js → Settings-CxNCTStH.js} +1 -1
  39. package/dist/assets/{Showroom-CdPGD4R4.js → Showroom-BfQj_ruk.js} +1 -1
  40. package/dist/assets/{Terminal-Ck0I64eZ.js → Terminal-COkGK9Eu.js} +5 -3
  41. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BpY1fOVD.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CtfWG-B0.js} +1 -1
  42. package/dist/assets/{bell-ring-BgQsFN7F.js → bell-ring-BIkgL1EI.js} +1 -1
  43. package/dist/assets/{boxes-BnOBLNz5.js → boxes-EqdcdFpg.js} +1 -1
  44. package/dist/assets/{build-cluster-graph-BwHdP82z.js → build-cluster-graph-C0MeCzJZ.js} +1 -1
  45. package/dist/assets/circle-check-big-DGl1OsLR.js +1 -0
  46. package/dist/assets/{circle-x-DAqnOyA6.js → circle-x-CBZPec7u.js} +1 -1
  47. package/dist/assets/clock-M4NiOyl_.js +1 -0
  48. package/dist/assets/{copy-Dl5E5of_.js → copy-BPgY4Eey.js} +1 -1
  49. package/dist/assets/{debounced-invalidate-BIRVvqvY.js → debounced-invalidate-B1bc5kFD.js} +1 -1
  50. package/dist/assets/{dist-CUfLXJC3.js → dist-DjbCvztb.js} +1 -1
  51. package/dist/assets/dist-IEXliP3K.js +349 -0
  52. package/dist/assets/{download-AfoMEWCf.js → download-Dq2bfdRX.js} +1 -1
  53. package/dist/assets/{face-bbox-BFT7iMc1.js → face-bbox-DUGyLE43.js} +1 -1
  54. package/dist/assets/{hard-drive-C9zTEogy.js → hard-drive-COdkuHqf.js} +1 -1
  55. package/dist/assets/{hostInit-Cw_l9Xfz.js → hostInit-BSakAGif.js} +1 -1
  56. package/dist/assets/index-LPwis6Rq.js +4 -0
  57. package/dist/assets/{key-round-sF-8oSo7.js → key-round-CfAFZkMw.js} +1 -1
  58. package/dist/assets/{mf-entry-bootstrap-0-8f39d7c2.js → mf-entry-bootstrap-0-e9ffa7b9.js} +2 -2
  59. package/dist/assets/{pencil-DsWgW1cM.js → pencil-CfoKCBNv.js} +1 -1
  60. package/dist/assets/play-CqrjGyv7.js +1 -0
  61. package/dist/assets/{player-overlays-BGbLKvcn.js → player-overlays-CBKaIBph.js} +1 -1
  62. package/dist/assets/plus-DHRgxEWi.js +1 -0
  63. package/dist/assets/power-DGhEdOiQ.js +1 -0
  64. package/dist/assets/{radio-CWn4dw9L.js → radio-BOUTlTbE.js} +1 -1
  65. package/dist/assets/{refresh-cw-Cly4MRhi.js → refresh-cw-CllqntzE.js} +1 -1
  66. package/dist/assets/remoteEntry-BsYVmvk8.js +1 -0
  67. package/dist/assets/rotate-ccw-CdTrnBTI.js +1 -0
  68. package/dist/assets/rotate-cw-Dre2EA6E.js +1 -0
  69. package/dist/assets/search-Dx_k5G37.js +1 -0
  70. package/dist/assets/{send-yaKZ1tHd.js → send-DcXtHjaz.js} +1 -1
  71. package/dist/assets/{server-CLOtA1S4.js → server-DbU7BgZv.js} +1 -1
  72. package/dist/assets/shield-BojVNBVL.js +1 -0
  73. package/dist/assets/square-DynbJcCj.js +1 -0
  74. package/dist/assets/{square-check-big-DsiPGDCA.js → square-check-big-Ch-X3CcM.js} +1 -1
  75. package/dist/assets/src-0pbBUmTo.js +349 -0
  76. package/dist/assets/src-BLHY9yig.js +67 -0
  77. package/dist/assets/{star-fUCw1hyi.js → star-BotqSaGv.js} +1 -1
  78. package/dist/assets/{undo-2-DXcExZt9.js → undo-2-CXIWJrgH.js} +1 -1
  79. package/dist/assets/{upload-CLT-rIe6.js → upload-CafOTsXz.js} +1 -1
  80. package/dist/assets/{use-scenes-feed-CvesyXw2.js → use-scenes-feed-DTuzztEP.js} +1 -1
  81. package/dist/assets/useEventInvalidation-BDOhX3vo.js +1 -0
  82. package/dist/assets/{video-CFtTGKiz.js → video-GQHe9bLG.js} +1 -1
  83. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BwIIU_83.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-7s6IgvIP.js} +2 -2
  84. package/dist/assets/{wifi-Glpx3AkR.js → wifi-MOwlhPpo.js} +1 -1
  85. package/dist/assets/{zap-aTn3GS-l.js → zap-BiojyRpM.js} +1 -1
  86. package/dist/index.html +5 -5
  87. package/dist/server/addon.js +135 -7
  88. package/package.json +1 -1
  89. package/dist/assets/Addons-BOYMP0uf.js +0 -1
  90. package/dist/assets/CapabilityBadges-DjOvNnpp.js +0 -1
  91. package/dist/assets/DeviceDetail-DCh8ydpY.js +0 -2
  92. package/dist/assets/Events-Drj6ybP0.js +0 -1
  93. package/dist/assets/Network-DBtVDYGt.js +0 -1
  94. package/dist/assets/Notifications-DBH3QGle.js +0 -1
  95. package/dist/assets/Pipeline-DgZbCwcO.js +0 -1
  96. package/dist/assets/Recordings-DTGdM6Ip.js +0 -1
  97. package/dist/assets/circle-check-big-FvfSWrhR.js +0 -1
  98. package/dist/assets/clock-BpmU9WHJ.js +0 -1
  99. package/dist/assets/dist-C2l22cSJ.js +0 -349
  100. package/dist/assets/index-vZPXzSPK.js +0 -4
  101. package/dist/assets/play-BkPr3HPj.js +0 -1
  102. package/dist/assets/plus-zSkh3oEn.js +0 -1
  103. package/dist/assets/power-C4yi0usE.js +0 -1
  104. package/dist/assets/remoteEntry-BwhR6qpk.js +0 -1
  105. package/dist/assets/rotate-ccw-D0bM0VXI.js +0 -1
  106. package/dist/assets/rotate-cw-CNTEn7nJ.js +0 -1
  107. package/dist/assets/search-Bq3ZLayo.js +0 -1
  108. package/dist/assets/square-BlSn3fsr.js +0 -1
  109. package/dist/assets/src-Buv5KpAz.js +0 -67
  110. package/dist/assets/src-CQVcBp6b.js +0 -349
  111. package/dist/assets/useEventInvalidation-B-Cb5-ry.js +0 -1
@@ -0,0 +1 @@
1
+ import{Q as e,S as t,W as n,a as r,b as i,i as a,o,q as s,t as c,x as l,z as u}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 d}from"./player-overlays-CBKaIBph.js";import{At as f,Et as p,Ft as m,Gt as h,It as g,Lt as _,Nt as v,Ot as y,Pt as b,So as x,Tt as S,Yt as C,bo as w,ct as T,dt as E,et as D,jt as O,kt as k,lt as A,oi as j,tt as M,un as N,ut as ee,wt as P}from"./src-BLHY9yig.js";import{A as te,B as ne,C as re,D as ie,E as ae,F as oe,I as F,L as se,M as ce,N as le,O as ue,P as de,Q as fe,R as pe,S as me,T as he,_ as ge,b as _e,g as I,j as ve,k as ye,mt as L,nt as be,tt as xe,v as Se,w as Ce,x as we,y as Te,z as Ee}from"./src-0pbBUmTo.js";import{D as De,E as Oe,_ as ke,j as Ae,v as je}from"./__vite-browser-external-B6qJ4svC.js";import{n as Me,t as Ne}from"./bell-ring-BIkgL1EI.js";import{t as Pe}from"./circle-check-big-DGl1OsLR.js";import{t as Fe}from"./copy-BPgY4Eey.js";import{n as Ie,t as Le}from"./send-DcXtHjaz.js";import{t as Re}from"./pencil-CfoKCBNv.js";import{t as ze}from"./plus-DHRgxEWi.js";import{t as Be}from"./radio-BOUTlTbE.js";import{t as Ve}from"./refresh-cw-CllqntzE.js";import{t as He}from"./rotate-ccw-CdTrnBTI.js";import{t as Ue}from"./search-Dx_k5G37.js";import{t as We}from"./zap-BiojyRpM.js";import{C as R,F as Ge,G as Ke,K as qe,O as Je,U as Ye,X as Xe,f as Ze,i as Qe,o as $e,s as et,w as tt}from"./index-LPwis6Rq.js";import{t as z}from"./AdminPage-CCD07UMs.js";import{t as nt}from"./AdminTabs-FswV6m19.js";import{t as rt}from"./use-scenes-feed-DTuzztEP.js";var it=qe(`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`}]]),at=qe(`images`,[[`path`,{d:`M18 22H4a2 2 0 0 1-2-2V6`,key:`pblm9e`}],[`path`,{d:`m22 13-1.296-1.296a2.41 2.41 0 0 0-3.408 0L11 18`,key:`nf6bnh`}],[`circle`,{cx:`12`,cy:`8`,r:`2`,key:`1822b1`}],[`rect`,{width:`16`,height:`16`,x:`6`,y:`2`,rx:`2`,key:`12espp`}]]),ot=qe(`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`}]]);e();var st={home:`Home`,away:`Away`,night:`Night`};function ct(e){return st[e]??e}function lt(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 ut(e,t){return e.ruleCount===0?`Arms nothing — no enabled rule is gated on this mode.`:e.allDevices?`Every device — ${mt(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${mt(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(e=>t.get(e)??`Device ${e}`).join(`, `)}function dt(e,t){if(e.length===0)return``;let n=e.map(e=>`${t.get(e.deviceId)??`Device ${e.deviceId}`} (${ft[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var ft={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function pt(e){return e.ruleCount===0}function mt(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function ht(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 gt=[`notificationRules`,`getAlarmConfig`],_t=[`notificationOutput`,`listTargets`],vt=[`deviceManager`,`listAll`,`alarm-coverage`],yt=600,bt=3600;function xt({label:e,hint:n,value:r,max:i,zeroMeans:a,disabled:o,onCommit:c}){let[u,d]=s(null);return t(`div`,{className:`flex flex-col gap-1`,children:[l(`label`,{className:`text-sm font-medium`,children:e}),t(`div`,{className:`flex items-center gap-2`,children:[l(b,{type:`number`,min:0,max:i,value:u??String(r),disabled:o,onChange:e=>d(e.target.value),onBlur:()=>{let e=u===null?null:ht(u,i);d(null),e!==null&&e!==r&&c(e)},className:`w-28`,"data-testid":`alarm-delay-${e.toLowerCase().replace(/\s+/g,`-`)}`}),l(`span`,{className:`text-sm text-foreground-subtle`,children:lt(r,a)})]}),l(`p`,{className:`text-xs text-foreground-subtle`,children:n})]})}function St(){let e=d(),i=o(),a=r({queryKey:gt,queryFn:async()=>e.trpcClient.notificationRules.getAlarmConfig.query({})}),s=r({queryKey:_t,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),u=r({queryKey:vt,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).map(e=>({id:e.id,name:e.name}))}),f=c({mutationFn:t=>e.trpcClient.notificationRules.setAlarmConfig.mutate({patch:t}),onSuccess:()=>i.invalidateQueries({queryKey:gt})}),p=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]);if(a.isLoading)return l(z,{icon:Ze,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:l(R,{className:`h-5 w-5 animate-spin`})});let h=a.data;if(h===void 0||a.isError)return l(z,{icon:Ze,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:l(C,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(h.deviceId===null)return l(z,{icon:Ze,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:l(m,{className:`p-4`,children:l(`p`,{className:`text-sm text-foreground-subtle`,children:`This installation has no alarm panel. The panel is created by the Notification Center on the hub — if this is the hub, its creation failed and the server log says why.`})})});let _=h.settings,v=f.isPending,y=s.data??[],b=_.announceTargets,x=e=>{f.mutate(e)},S=e=>{x({announceTargets:b.includes(e)?b.filter(t=>t!==e):[...b,e]})};return l(z,{icon:Ze,title:`Alarm`,subtitle:`Panel delays, and what each mode actually arms.`,children:t(`div`,{className:`flex flex-col gap-4`,children:[f.isError?l(C,{title:`Could not save`,message:String(f.error)}):null,t(m,{className:`p-4`,children:[l(`h3`,{className:`text-sm font-semibold mb-3`,children:`Delays`}),t(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[l(xt,{label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,value:_.exitDelaySec,max:yt,zeroMeans:`arms immediately`,disabled:v,onCommit:e=>x({exitDelaySec:e})}),l(xt,{label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,value:_.entryDelaySec,max:yt,zeroMeans:`fires immediately`,disabled:v,onCommit:e=>x({entryDelaySec:e})}),l(xt,{label:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,value:_.triggeredDurationSec,max:bt,zeroMeans:`until disarmed`,disabled:v,onCommit:e=>x({triggeredDurationSec:e})})]})]}),t(m,{className:`p-4`,children:[t(`div`,{className:`flex items-start justify-between gap-4`,children:[t(`div`,{children:[l(`h3`,{className:`text-sm font-semibold`,children:`Announce when a mode is armed`}),l(`p`,{className:`text-xs text-foreground-subtle mt-1`,children:`Sends one notification listing the devices that mode arms — the list below, as it stands at that moment.`})]}),l(`div`,{className:`shrink-0`,children:l(O,{checked:_.announceArm,disabled:v,onCheckedChange:e=>x({announceArm:e}),"data-testid":`alarm-announce-toggle`})})]}),_.announceArm?t(`div`,{className:`mt-3 flex flex-col gap-2`,children:[y.length===0?l(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification targets are configured — nothing can be sent.`}):l(`div`,{className:`flex max-h-56 flex-col gap-2 overflow-y-auto`,children:y.map(e=>t(`label`,{className:`flex items-center gap-2 text-sm`,children:[l(`input`,{type:`checkbox`,checked:b.includes(e.id),disabled:v,onChange:()=>S(e.id),"data-testid":`alarm-target-${e.id}`}),l(`span`,{className:`min-w-0 truncate`,children:e.name}),e.enabled?null:l(g,{variant:`warning`,children:`disabled`})]},e.id))}),b.length===0?l(`p`,{className:`text-xs text-warning`,children:`No target selected — the announcement will not be sent.`}):null]}):null]}),t(m,{className:`p-4`,children:[l(`h3`,{className:`text-sm font-semibold mb-1`,children:`What each mode arms`}),l(`p`,{className:`text-xs text-foreground-subtle mb-3`,children:`Derived from the enabled rules gated on this panel. Nothing here is stored — change a rule and this changes with it.`}),l(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-coverage`,children:h.coverage.map(e=>t(`div`,{className:`flex items-start gap-3 rounded border border-border p-2`,"data-mode":e.mode,"data-empty":pt(e)?`true`:`false`,children:[l(`div`,{className:`w-20 shrink-0 text-sm font-medium`,children:ct(e.mode)}),t(`div`,{className:`flex-1 text-sm text-foreground-subtle`,children:[ut(e,p),e.skippedDevices.length>0?l(`div`,{className:`mt-0.5 text-xs text-warning`,"data-testid":`alarm-skipped`,children:dt(e.skippedDevices,p)}):null]}),pt(e)?l($e,{className:`h-4 w-4 shrink-0 text-warning`}):null]},e.mode))})]})]})})}e();var Ct=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],wt=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],Tt=[50,100,250,500];function Et(){return{ruleId:``,deviceId:``,status:``,windowHours:24,limit:100}}function Dt(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Ot(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function kt(){let e=d(),[i,a]=s(Et),o=e=>a(t=>({...t,...e})),c=r({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),u=r({queryKey:[`deviceManager`,`listAll`,`forHistory`],queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===L.Camera).map(e=>({id:e.id,name:e.name}))}),f=Date.now(),p=r({queryKey:[`notificationRules`,`getHistory`,i],retry:!1,queryFn:async()=>{let t=i.windowHours>0?f-i.windowHours*36e5:void 0;return(await e.trpcClient.notificationRules.getHistory.query({filter:{limit:i.limit,...i.ruleId?{ruleId:i.ruleId}:{},...i.deviceId?{deviceId:Number(i.deviceId)}:{},...Dt(i.status)?{status:Dt(i.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),h=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),g=e=>h.get(e)??`Camera #${String(e)}`,_=p.data??[],y=p.isError;return t(z,{icon:it,title:`Delivery history`,subtitle:`A searchable log of every notification the rules delivered (or failed to deliver).`,children:[t(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[t(`div`,{children:[l(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),l(v,{value:i.ruleId,onChange:e=>o({ruleId:e.target.value}),options:[{value:``,label:`All rules`},...(c.data??[]).map(e=>({value:e.id,label:e.name}))]})]}),t(`div`,{children:[l(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),l(v,{value:i.deviceId,onChange:e=>o({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(u.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),t(`div`,{children:[l(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),l(v,{value:i.status,onChange:e=>o({status:e.target.value}),options:wt.map(e=>({value:e.value,label:e.label}))})]}),t(`div`,{children:[l(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),l(v,{value:String(i.windowHours),onChange:e=>o({windowHours:Number(e.target.value)}),options:Ct.map(e=>({value:String(e.value),label:e.label}))})]}),t(`div`,{children:[l(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),l(v,{value:String(i.limit),onChange:e=>o({limit:Number(e.target.value)}),options:Tt.map(e=>({value:String(e),label:String(e)}))})]})]}),p.isLoading&&l(`div`,{className:`flex items-center justify-center py-16`,children:l(R,{className:`h-6 w-6 animate-spin text-primary`})}),y&&!p.isLoading&&l(m,{children:t(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[l(it,{className:`h-6 w-6 text-foreground-subtle`}),l(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),l(`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.`}),t(`button`,{type:`button`,onClick:()=>void p.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:[l(Ve,{className:`h-3 w-3`}),` Retry`]})]})}),!y&&!p.isLoading&&_.length===0&&l(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!y&&_.length>0&&l(m,{children:l(D,{columns:At(g),rows:_,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})})]})}function At(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>l(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`Subject`,render:e=>t(`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=>t(`span`,{className:`flex items-center gap-1.5`,children:[l(g,{variant:Ot(e.status),children:e.status}),e.attempts>1?t(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:`Detail`,render:e=>e.error?l(`span`,{className:`text-[11px] text-danger`,children:e.error}):l(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}function jt(e){let t=[],n=e.find(e=>e.type===L.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===L.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 Mt(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 Nt=[{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`}],Pt={sequences:[],buttons:[]};function Ft(e){return e===void 0?Pt:{sequences:[...e.onTrigger??[]],buttons:[...e.buttons??[]]}}function It(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 Lt(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 Rt(e){return{name:`sequence ${String(e+1)}`,enabled:!1,actions:[]}}function zt(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequence:t}}function Bt(){return{kind:`wait`,seconds:5}}var Vt=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,B=`block text-[11px] font-medium text-foreground`;function Ht({title:e,description:n,children:r}){return t(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4`,children:[t(`div`,{className:`min-w-0`,children:[l(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),l(`p`,{className:`text-[11px] text-foreground-subtle`,children:n})]}),l(`div`,{className:`flex flex-wrap items-center gap-1 sm:shrink-0`,children:r})]})}function Ut({value:e,onChange:n,devices:r}){let i=Lt(e),a=jt(r),o=(t,r)=>n({...e,sequences:e.sequences.map((e,n)=>n===t?r:e)}),s=(t,r)=>n({...e,buttons:e.buttons.map((e,n)=>n===t?r:e)});return t(`div`,{className:`space-y-4`,children:[i.length>0&&l(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:i.map(e=>l(`p`,{children:e.message},e.message))}),t(`section`,{className:`space-y-2`,children:[t(Ht,{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:[a.map(r=>t(_,{size:`sm`,variant:`ghost`,type:`button`,title:r.hint,className:`min-w-0 max-w-full`,onClick:()=>n(Mt(e,r)),children:[l(We,{className:`h-3.5 w-3.5 shrink-0`}),l(`span`,{className:`truncate`,children:r.label})]},r.id)),t(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({...e,sequences:[...e.sequences,Rt(e.sequences.length)]}),children:[l(ze,{className:`h-3.5 w-3.5 shrink-0`}),` Sequence`]})]}),e.sequences.length===0?l(`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((t,i)=>l(Wt,{sequence:t,devices:r,onChange:e=>o(i,e),onRemove:()=>n({...e,sequences:e.sequences.filter((e,t)=>t!==i)})},`seq-${String(i)}`))]}),t(`section`,{className:`space-y-2`,children:[l(Ht,{title:`Buttons on the notification`,description:`Each button runs one of the sequences above when tapped.`,children:t(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:e.sequences.length===0,onClick:()=>n({...e,buttons:[...e.buttons,zt(e.buttons.length,e.sequences[0]?.name??``)]}),children:[l(ze,{className:`h-3.5 w-3.5 shrink-0`}),` Button`]})}),e.buttons.length>0&&t(`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:[l($e,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),t(`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 `,l(`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?l(`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?l(`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((t,r)=>l(qt,{button:t,sequenceNames:e.sequences.map(e=>e.name),onChange:e=>s(r,e),onRemove:()=>n({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function Wt({sequence:e,devices:n,onChange:r,onRemove:i}){let a=(t,n)=>r({...e,actions:e.actions.map((e,r)=>r===t?n:e)});return t(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:[t(`div`,{className:`flex flex-wrap items-end gap-2`,children:[t(`div`,{className:`min-w-0 flex-1`,children:[l(`label`,{className:B,children:`Name`}),l(b,{className:`mt-1`,value:e.name,onChange:t=>r({...e,name:t.target.value})})]}),t(`div`,{className:`w-28`,children:[l(`label`,{className:B,children:`Min delay (s)`}),l(`input`,{type:`number`,min:0,className:Vt,value:e.minDelaySec??``,onChange:t=>{let n=t.target.value,i={...e};n===``?delete i.minDelaySec:i.minDelaySec=Number(n),r(i)}})]}),t(`div`,{className:`flex items-center gap-2 pb-1`,children:[l(O,{checked:e.enabled,onCheckedChange:t=>r({...e,enabled:t})}),l(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.enabled?`Runs on match`:`Only when a button is tapped`})]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:l(et,{className:`h-3.5 w-3.5`})})]}),t(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[e.actions.map((t,i)=>l(Gt,{step:t,devices:n,onChange:e=>a(i,e),onRemove:()=>r({...e,actions:e.actions.filter((e,t)=>t!==i)})},`step-${String(i)}`)),t(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({...e,actions:[...e.actions,Bt()]}),children:[l(ze,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function Gt({step:e,devices:n,onChange:r,onRemove:i}){return t(`div`,{className:`flex flex-wrap items-end gap-2`,children:[t(`div`,{className:`w-24`,children:[l(`label`,{className:B,children:`Step`}),t(`select`,{className:Vt,value:e.kind,onChange:e=>r(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:n[0]?.id??0,cap:``,method:``}),children:[l(`option`,{value:`cap`,children:`Do`}),l(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?t(`div`,{className:`w-28`,children:[l(`label`,{className:B,children:`Seconds`}),l(`input`,{type:`number`,min:0,max:300,className:Vt,value:e.seconds,onChange:e=>r({kind:`wait`,seconds:Number(e.target.value)})})]}):l(Kt,{step:e,devices:n,onChange:r}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove step`,children:l(et,{className:`h-3.5 w-3.5`})})]})}function Kt({step:e,devices:n,onChange:a}){let o=d(),s=r({queryKey:[`deviceManager`,`getBindings`,e.deviceId],enabled:e.deviceId>0,staleTime:6e4,queryFn:async()=>{let t=await o.trpcClient.deviceManager.getBindings.query({deviceId:e.deviceId});return[...new Set(t.entries.map(e=>e.capName))].sort((e,t)=>e.localeCompare(t))}}).data??[];return t(i,{children:[t(`div`,{className:`min-w-[9rem] flex-1`,children:[l(`label`,{className:B,children:`Device`}),t(`select`,{className:Vt,value:String(e.deviceId),onChange:t=>a({...e,deviceId:Number(t.target.value),cap:``}),children:[l(`option`,{value:`0`,children:`Select…`}),n.map(e=>l(`option`,{value:String(e.id),children:e.name},e.id))]})]}),t(`div`,{className:`min-w-[8rem] flex-1`,children:[l(`label`,{className:B,children:`Capability`}),t(`select`,{className:Vt,value:e.cap,disabled:s.length===0,onChange:t=>a({...e,cap:t.target.value,method:``}),children:[l(`option`,{value:``,children:s.length===0?`No devices bound`:`Select…`}),s.map(e=>l(`option`,{value:e,children:e},e))]})]}),t(`div`,{className:`min-w-[7rem] flex-1`,children:[l(`label`,{className:B,children:`Method`}),l(b,{className:`mt-1`,value:e.method,placeholder:`arm`,onChange:t=>a({...e,method:t.target.value})})]}),t(`div`,{className:`min-w-[8rem] flex-1`,children:[l(`label`,{className:B,children:`Arguments (JSON)`}),l(b,{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,a(t);return}try{let t=JSON.parse(n);typeof t==`object`&&t&&!Array.isArray(t)&&a({...e,args:t})}catch{}}})]})]})}function qt({button:e,sequenceNames:n,onChange:r,onRemove:i}){return t(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[t(`div`,{className:`min-w-[7rem] flex-1`,children:[l(`label`,{className:B,children:`Label`}),l(b,{className:`mt-1`,value:e.label,onChange:t=>r({...e,label:t.target.value})})]}),t(`div`,{className:`min-w-[8rem] flex-1`,children:[l(`label`,{className:B,children:`Runs`}),t(`select`,{className:Vt,value:e.sequence,onChange:t=>r({...e,sequence:t.target.value}),children:[!n.includes(e.sequence)&&t(`option`,{value:e.sequence,children:[e.sequence,` (missing)`]}),n.map(e=>l(`option`,{value:e,children:e},e))]})]}),t(`div`,{className:`w-32`,children:[l(`label`,{className:B,children:`Icon`}),t(`select`,{className:Vt,value:e.icon??``,onChange:t=>{let n={...e};if(t.target.value===``)delete n.icon;else{let e=Nt.find(e=>e.value===t.target.value);e!==void 0&&(n.icon=e.value)}r(n)},children:[l(`option`,{value:``,children:`None`}),Nt.map(e=>l(`option`,{value:e.value,children:e.label},e.value))]})]}),t(`div`,{className:`flex items-center gap-2 pb-1`,children:[l(O,{checked:e.destructive===!0,onCheckedChange:t=>{let n={...e};t?n.destructive=!0:delete n.destructive,r(n)}}),l(g,{variant:e.destructive===!0?`danger`:`default`,children:`Destructive style`})]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:l(et,{className:`h-3.5 w-3.5`})})]})}function V(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var Jt=V({devices:!0}),Yt=V({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),Xt=V({zonesExclude:!0}),Zt=V({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),Qt=V({minDwellSeconds:!0}),$t=V({source:!0}),en=V({crossing:!0}),tn=V({packagePhase:!0}),nn=V({zones:!0}),rn=V({plates:!0}),an=V({occupancy:!0}),on=V({audio:!0}),sn=V({systemEvent:!0}),cn=V({deviceState:!0}),ln=V({scene:!0});function un(e,t){let n=e[t];return Array.isArray(n)?n:[]}function dn(e,t){let n=e[t];return typeof n==`number`?n:void 0}var fn=[{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 pn(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function mn(e,t){let n=e.filter(t),r=new Set(fn.map(e=>e.id)),i=[];for(let e of fn){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:pn(e),descriptors:n.filter(t=>t.group===e)});return i}e();function hn(e,t){let r=d().trpcClient,i=a({queries:e.map(e=>({queryKey:[[`nc-pickers`,`zones`],{deviceId:e}],staleTime:3e4,queryFn:async()=>({deviceId:e,zones:(await r.zones.listZones.query({deviceId:e})).map(e=>({id:e.id,name:e.name}))})}))});return n(()=>{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 gn(e){let t=d().trpcClient,r=a({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 n(()=>{let e=new Map;for(let t of r)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:r.some(e=>e.isLoading)}},[r])}function _n(){let e=j();return n(()=>({options:(e.data??[]).map(e=>({value:e.id,label:e.name})),loading:e.isLoading}),[e.data,e.isLoading])}function vn(){let e=w({limit:200}),t=x();return n(()=>{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 yn({options:e,value:r,onChange:i,loading:a,emptyHint:o,placeholder:c,noFreeText:u=!1}){let[d,f]=s(``),p=n(()=>new Set(e.map(e=>e.value)),[e]),m=n(()=>new Set(r),[r]),h=r.filter(e=>!p.has(e)),g=e=>{i(m.has(e)?r.filter(t=>t!==e):[...r,e])},_=()=>{let e=d.trim();e.length===0||r.includes(e)||(i([...r,e]),f(``))};return t(`div`,{className:`mt-1 space-y-1.5`,children:[h.length>0&&l(`div`,{className:`flex flex-wrap gap-1`,children:h.map(e=>t(`button`,{type:`button`,onClick:()=>i(r.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?l(`div`,{className:`max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>t(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:m.has(e.value),onChange:()=>g(e.value),className:`accent-primary`}),l(`span`,{className:`flex-1 truncate`,children:e.label}),e.hint!==void 0&&l(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.hint})]},e.value))}):l(`p`,{className:`text-[10px] text-foreground-subtle`,children:a===!0?`Loading…`:o}),!u&&l(`input`,{value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),_())},placeholder:c,className:`w-full rounded-md border border-border bg-background px-2 py-1 text-xs text-foreground placeholder:text-foreground-subtle`})]})}var bn=[{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 xn(e){return bn.find(t=>t.value===e)?.label??e}function Sn(e){return bn.find(t=>t.value===e)?.value}function Cn(e){return bn.some(t=>t.value===e)}var wn=[{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.`},{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.`},{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.`},{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.`},{key:`system`,label:`System events`,blurb:`Rules about the installation itself: a camera or stream dropping, a node leaving the cluster, an addon or server update becoming available. These carry no image and are not tied to a detection.`,newRuleLabel:`New system rule`,emptyHint:`No system-event rules yet. Click "New system rule" to be told when a camera drops, a node leaves or an update lands.`}],Tn=new Map([[0,`No cooldown`],[60,`1 minute`],[3600,`1 hour`]]),En=86400;function Dn(e){let t=Tn.get(e);return t===void 0?e%3600==0?`${e/3600} hours`:e%60==0?`${e/60} minutes`:`${e} seconds`:t}function On(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)&&t>=0?Math.trunc(t):void 0}var kn=[{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 An(e){return kn.find(t=>t.value===e)?.value}var jn=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function Mn(e){let t=jn.find(t=>t.value===e)?.value;return t===``?void 0:t}var Nn=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function Pn(e){let t=Nn.find(t=>t.value===e)?.value;return t===``?void 0:t}var Fn=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],In=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],Ln=[{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 Rn(e){let t=Ln.find(t=>t.value===e)?.value;return t===``||t===void 0?void 0:t}var zn=[{value:`any`,label:`Any of`},{value:`all`,label:`All of`}],Bn=[{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`}],Vn=[10,30,60],Hn=[5,10,15,30,60,120,240,480];function Un(e){return e>=60&&e%60==0?`${e/60} h`:`${e} min`}var Wn=new Set([`alarm-arming`,`alarm-triggered`,`alarm-armed`,`alarm-disarmed`]),Gn=`alarm-panel`;function Kn(e,t){for(let t of e.systemEvent?.kinds??[])if(Wn.has(t))return!0;for(let e of t)for(let t of e.actions)if(t.kind===`cap`&&t.cap===Gn)return!0;return!1}function qn(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,templateTitle:``,templateBody:``,conditions:t,schedule:void 0,snoozeAllowGlobal:!1,waitForEnhancement:!1,snoozeOptions:void 0,actions:Pt,deviceIds:[],cooldownSec:30}}function Jn(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,templateTitle:e.template?.title??``,templateBody:e.template?.body??``,conditions:e.conditions,schedule:e.schedule,snoozeAllowGlobal:e.snoozeAllowGlobal===!0,waitForEnhancement:e.waitForEnhancement===!0,snoozeOptions:e.snoozeOptions,actions:Ft(e.actions),deviceIds:e.conditions.devices??[],cooldownSec:e.throttle.cooldownSec}}function Yn(e){let t=[];return de(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(En)} (24 hours). 0 means every match is delivered.`),t}function Xn(e){return Yn(e).length===0&&Cn(e.delivery)&&(!re(e.delivery)||Zn(e)>0)&&e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&Lt(e.actions).length===0}function Zn(e){return e.conditions.systemEvent?.kinds.length??0}function Qn(e,t){return e.appliesTo.includes(t)}var $n={source:`any`};function er(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||$n[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 tr=xe.filter(e=>e.id===`audio`);function nr(e){if(e.length===0)return e;let t=new Set(e.map(e=>e.id)),n=tr.filter(e=>!t.has(e.id));return n.length===0?e:[...e,...n]}function rr(e,t,n,r=he({delivery:t,conditions:e})){let i=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&we(e,t,r)).map(e=>e.id)),a={};for(let[t,n]of Object.entries(e))i!==null&&!i.has(t)||er(t,n)||(a[t]=n);return a}function ir(e){return e!==void 0&&e.windows.length>0}function ar(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=It(e.actions),s=he(e),c=ae(s),l=(n.length===0||n.some(t=>t.id===`schedule`&&Qn(t,e.delivery)))&&ir(e.schedule)?e.schedule:void 0,u=n.length===0?!0:n.some(t=>t.id===`devices`&&Qn(t,e.delivery));return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...rr(e.conditions,e.delivery,n,s),...u&&e.deviceIds.length>0?{devices:[...e.deviceIds]}:{}},...l?{schedule:l}:{},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}}:{attach:`none`},throttle:{cooldownSec:e.cooldownSec,scope:t?.throttle.scope??`rule-device`,...t?.throttle.granularity===void 0?{}:{granularity:t.throttle.granularity}},priority:e.priority,...a?{template:a}:{},...e.snoozeAllowGlobal?{snoozeAllowGlobal:!0}:{},...e.waitForEnhancement?{waitForEnhancement:!0}:{},...e.snoozeOptions===void 0?{}:{snoozeOptions:[...e.snoozeOptions]},...o===void 0?{}:{actions:o}}}function or(e,t){return e.options&&e.options.length>0?e.options:t}var sr=[{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 cr(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var lr=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`delivery`,`targetIds`,`targetUsers`,`targetParams`]},{key:`devices`,label:`Devices`,fields:[`deviceIds`]},{key:`conditions`,label:`Conditions`,fields:[`conditions`,`schedule`]},{key:`notification`,label:`Notification`,fields:[`priority`,`mediaAttach`,`mediaFrame`,`mediaZoneCrop`,`mediaGif`,`mediaClip`,`mediaProfile`,`mediaClipSpeed`,`templateTitle`,`templateBody`]},{key:`actions`,label:`Actions`,fields:[`actions`]},{key:`advanced`,label:`Advanced`,fields:[`snoozeAllowGlobal`,`snoozeOptions`,`cooldownSec`,`waitForEnhancement`]}];function ur(e,t={}){let n=ae(he({delivery:e,conditions:t})),r=lr.map(e=>e.key===`conditions`?{...e,label:n.label}:e);return re(e)?r.filter(e=>e.key!==`devices`):r}function dr(e){if(e.audio!==void 0)return`Sound`;if(e.occupancy!==void 0)return`Occupancy`}function fr(e){return me(e.conditions,he(e))}var pr=`rule`;function mr(e){return lr.find(t=>t.key===e)?.key}e();var H=`block text-[11px] font-medium text-foreground`,U=`text-[10px] text-foreground-subtle mt-0.5`;function hr({cameras:e,value:n,onChange:r}){if(e.length===0)return l(`p`,{className:U,children:`No cameras available — the rule applies to all devices.`});let i=e=>r(n.includes(e)?n.filter(t=>t!==e):[...n,e]);return l(`div`,{className:`mt-1 max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>t(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:n.includes(e.id),onChange:()=>i(e.id),className:`accent-primary`}),l(`span`,{className:`flex-1 truncate`,children:e.name})]},e.id))})}function gr({value:e,placeholder:n,onChange:r}){let[i,a]=s(``),o=()=>{let t=i.trim();if(t.length===0||e.includes(t)){a(``);return}r([...e,t]),a(``)},c=t=>r(e.filter(e=>e!==t));return t(`div`,{className:`mt-1 space-y-1.5`,children:[e.length>0&&l(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>t(`span`,{className:`inline-flex items-center gap-1 rounded bg-surface-hover px-1.5 py-0.5 text-[11px] text-foreground`,children:[e,l(`button`,{type:`button`,onClick:()=>c(e),"aria-label":`remove ${e}`,className:`text-foreground-subtle hover:text-danger`,children:l(Qe,{className:`h-3 w-3`})})]},e))}),l(b,{value:i,placeholder:n,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),o())},onBlur:o})]})}function _r({picker:e,value:r,onChange:i}){let a=n(()=>te(e),[e]),o=n(()=>new Set(r),[r]),s=r.filter(e=>!a.has(e)),c=e=>{i(o.has(e)?r.filter(t=>t!==e):[...r,e])};return t(`div`,{className:`space-y-2`,children:[s.length>0&&l(`div`,{className:`flex flex-wrap gap-1`,children:s.map(e=>t(`button`,{type:`button`,onClick:()=>i(r.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=>t(`div`,{children:[l(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-muted mb-1`,children:e.fallbackLabel}),l(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map(e=>{let t=o.has(e.value);return l(`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 vr({value:e,min:n,max:r,step:i,onChange:a}){return t(`div`,{className:`mt-1 flex items-center gap-2`,children:[l(b,{type:`number`,value:e??``,min:n,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&&l(`input`,{type:`range`,min:n,max:r,step:i,value:e,onChange:e=>a(Number(e.target.value)),className:`flex-1 accent-primary`,"aria-label":`value`})]})}function yr({value:e,onChange:n,options:r}){let i=e??``,a=r&&r.length>0?r:Ln,o=a.find(e=>e.value===i);return t(`div`,{className:`mt-1 space-y-1`,children:[l(v,{value:i,options:a.map(e=>({value:e.value,label:e.label})),onChange:e=>n(Rn(e.target.value))}),o!==void 0&&l(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:o.hint})]})}function br({deviceIds:e,cameras:n,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 t(`div`,{className:`mt-1 space-y-1.5`,children:[l(`div`,{className:`max-w-[10rem]`,children:l(v,{value:o,options:zn.map(e=>({value:e.value,label:e.label})),onChange:e=>c(e.target.value===`all`?`all`:`any`)})}),l(xr,{deviceIds:e,cameras:n,value:a,onChange:s})]})}function xr({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=hn(e,t);return l(yn,{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 Sr({value:e,onChange:t}){let{options:n,loading:r}=_n();return l(yn,{options:n,value:e,onChange:t,loading:r,emptyHint:`No identities in the face gallery yet — type a name.`,placeholder:`Identity name…`})}function Cr({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=gn(e);return l(yn,{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 wr=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}];function Tr(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 Er({deviceIds:e,cameras:n,classOptions:r,value:i,onChange:a}){let{options:o,loading:s}=hn(e,n),c=i??_e,u=e=>a({...c,...e}),d=c.op===`became-occupied`||c.op===`became-free`,f=Tr(r,c.className);return t(`div`,{className:`mt-1 space-y-1.5`,children:[t(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[l(`div`,{className:`min-w-[10rem]`,children:l(v,{value:c.zoneId??``,options:[{value:``,label:s?`Loading zones…`:`— whole frame —`},...o.map(e=>({value:e.value,label:e.label}))],onChange:e=>u({zoneId:e.target.value===``?void 0:e.target.value})})}),l(`div`,{className:`min-w-[9rem]`,children:l(v,{value:c.className??``,options:[{value:``,label:`— any class —`},...f],onChange:e=>u({className:e.target.value===``?void 0:e.target.value})})}),l(`div`,{className:`min-w-[9rem]`,children:l(v,{value:c.op,options:wr.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=wr.find(t=>t.value===e.target.value);t&&u({op:t.value})}})})]}),t(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[t(`label`,{className:`flex items-center gap-1`,children:[d?`Threshold`:`Count`,l(b,{type:`number`,min:0,className:`w-16`,value:String(c.count),onChange:e=>u({count:Math.max(0,Number(e.target.value)||0)})})]}),t(`label`,{className:`flex items-center gap-1`,children:[`Hold for`,l(b,{type:`number`,min:0,max:3600,className:`w-16`,value:String(c.sustainSeconds),onChange:e=>u({sustainSeconds:Math.min(3600,Math.max(0,Number(e.target.value)||0))})}),`s`]}),i===void 0?null:l(`button`,{type:`button`,onClick:()=>a(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),e.length===0&&l(`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.`}),l(`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 Dr=[{value:`label`,label:`Sounds — fires at once`,Icon:Ue},{value:`level`,label:`Volume — over a window`,Icon:Ke}];function Or({taxonomy:e,value:n,onChange:r}){let a=se(n),o=e=>r(Ee(n,e)),{choices:s,unknownLabels:c}=oe(e,a.labels),u=F(n)??`label`;return t(`div`,{className:`mt-1 space-y-2`,children:[t(`div`,{className:`flex flex-wrap items-center gap-1`,children:[Dr.map(e=>l(`button`,{type:`button`,"aria-pressed":u===e.value,onClick:()=>o({mode:e.value}),className:`rounded border px-2 py-0.5 text-[11px] ${u===e.value?`border-primary bg-primary/15 text-foreground`:`border-border text-foreground-subtle hover:bg-surface-hover`}`,children:t(`span`,{className:`inline-flex items-center gap-1`,children:[l(e.Icon,{className:`h-3 w-3`}),e.label]})},e.value)),n===void 0?null:l(`button`,{type:`button`,onClick:()=>r(void 0),className:`ml-1 text-xs text-foreground-subtle underline hover:text-foreground`,children:`Clear`})]}),u===`label`?t(i,{children:[l(`div`,{className:`flex flex-wrap gap-1`,children:s.map(e=>{let n=pe(a.labels,e.value),r=e.unknown?`border-dashed border-warning text-warning`:n?`border-primary bg-primary/15 text-foreground`:`border-border text-foreground hover:bg-surface-hover`;return l(`button`,{type:`button`,"aria-pressed":n,title:e.unknown?`Stored by the rule — not offered by this hub`:void 0,onClick:()=>o({labels:ne(a.labels,e.value)}),className:`rounded border px-1.5 py-0.5 text-[10px] ${r}`,children:t(`span`,{className:`inline-flex items-center gap-1`,children:[l(N,{iconId:e.iconId,size:12}),e.label]})},e.value)})}),c.length>0&&t(`p`,{className:`text-[10px] text-warning`,children:[`Kept from the rule, unknown to this hub: `,c.join(`, `)]}),l(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Fires on the FIRST frame the classifier hears one of these sounds — no sampling window, however brief the sound is. The rule's cooldown is the only throttle.`})]}):t(i,{children:[l(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:t(`label`,{className:`flex items-center gap-1`,children:[`Louder than`,l(b,{type:`number`,min:ce,max:0,step:3,className:`w-20`,value:String(a.dbThreshold??-55),onChange:e=>o({dbThreshold:Number(e.target.value)})}),`dBFS`]})}),t(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[t(`label`,{className:`flex items-center gap-1`,children:[`Hits`,l(b,{type:`number`,min:1,max:100,step:5,className:`w-16`,value:String(a.hitPercent),onChange:e=>o({hitPercent:Number(e.target.value)})}),`% (default `,le.hitPercent,`)`]}),t(`label`,{className:`flex items-center gap-1`,children:[`over`,l(b,{type:`number`,min:1,max:300,step:5,className:`w-16`,value:String(a.samplingSeconds),onChange:e=>o({samplingSeconds:Number(e.target.value)})}),`s (default `,le.samplingSeconds,`)`]})]}),t(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`dBFS is negative-going: 0 is full scale, `,ce,` 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.`]})]}),de(n)?l(`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 kr({value:e,onChange:n}){let r=e?.values??[],i=e?.maxDistance??1,a=e=>n(e.length>0?{values:e,maxDistance:i}:void 0),o=e=>n(r.length>0?{values:r,maxDistance:e}:void 0),s=vn().filter(e=>!r.includes(e));return t(`div`,{className:`mt-1 space-y-1.5`,children:[l(gr,{value:r,placeholder:`Plate text…`,onChange:a}),s.length>0&&t(`div`,{className:`flex flex-wrap items-center gap-1`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:`Seen:`}),s.slice(0,12).map(e=>l(`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))]}),t(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Max distance`,l(b,{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 Ar({gateable:e,value:n,onChange:r}){let i=e.find(e=>e.id===n?.deviceId),a=new Set(n?.states??[]),o=e=>{let t=Number(e);if(!Number.isFinite(t)||t===0)return r(void 0);r({deviceId:t,states:[]})},s=e=>{if(n===void 0)return;let t=new Set(a);t.has(e)?t.delete(e):t.add(e),r(t.size===0?void 0:{deviceId:n.deviceId,states:[...t]})};return t(`div`,{className:`mt-1 space-y-2`,children:[l(v,{value:n===void 0?``:String(n.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&&l(`div`,{className:`flex flex-wrap gap-1.5`,children:i.states.map(e=>l(`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&&l(`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.`}),n!==void 0&&l(`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 jr(e){let t=e.verdict===`matched`?`matched`:e.verdict===`diverged`?`diverged`:`cannot judge`;return e.latched?`${t} · latched`:t}function Mr({scenes:e,value:n,onChange:r}){let i=e.find(e=>e.sceneId===n?.sceneId),a=t=>{if(t===``)return r(void 0);let i=e.find(e=>e.sceneId===t);if(i===void 0)return r(void 0);r({sceneId:t,deviceId:i.deviceId,requiredState:n?.requiredState??`diverged`,...n?.latched===void 0?{}:{latched:n.latched}})},o=e=>{n!==void 0&&r({...n,requiredState:e===`matched`?`matched`:`diverged`})},s=e=>{if(n!==void 0){if(e===``){let{latched:e,...t}=n;return r(t)}r({...n,latched:e===`latched`})}};return e.length===0?l(`p`,{className:U,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.`}):t(`div`,{className:`mt-1 space-y-2`,children:[l(v,{value:n?.sceneId??``,options:[{value:``,label:`— no scene gate —`},...e.map(e=>({value:e.sceneId,label:`${e.cameraName} · ${e.label} — ${jr(e)}`}))],onChange:e=>a(e.target.value)}),n!==void 0&&t(`div`,{className:`flex flex-wrap items-center gap-2`,children:[t(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Only while it is`,l(v,{value:n.requiredState,options:[{value:`diverged`,label:`diverged (changed)`},{value:`matched`,label:`matched (as captured)`}],onChange:e=>o(e.target.value)})]}),t(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Read`,l(v,{value:n.latched===void 0?``:n.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&&t(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Right now: `,jr(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.`]}),n!==void 0&&i===void 0&&t(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`This rule is gated on a scene this hub cannot find (id `,n.sceneId,`). It was deleted or disabled — the rule is enabled and permanently silent until you pick another scene or remove the gate.`]})]})}var Nr=[{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 Pr(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Fr(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 Ir(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function Lr({value:e,onChange:n}){let r=e?.windows??[],i=e?.invert??!1,a=(t,r)=>{if(t.length===0){n(void 0);return}n({windows:t,...r?{invert:!0}:{},...e?.timezone?{timezone:e.timezone}:{}})},o=()=>a([...r,Ir()],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 t(`div`,{className:`mt-1 space-y-2`,children:[r.length===0?l(`p`,{className:U,children:`Always active — add a window to restrict when the rule fires.`}):r.map((e,t)=>l(Rr,{window:e,onChange:e=>c(t,e),onRemove:()=>s(t)},t)),t(`div`,{className:`flex items-center gap-3`,children:[t(`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:[l(ze,{className:`h-3 w-3`}),` Add window`]}),r.length>0&&t(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(`input`,{type:`checkbox`,checked:i,onChange:e=>a([...r],e.target.checked),className:`accent-primary`}),`Active outside the windows`]})]})]})}function Rr({window:e,onChange:n,onRemove:r}){let i=t=>{let r=e.days.includes(t)?e.days.filter(e=>e!==t):[...e.days,t];r.length!==0&&n({...e,days:r})};return t(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[t(`div`,{className:`flex items-center gap-2 text-xs`,children:[l(`input`,{type:`time`,value:Pr(e.startMinute),onChange:t=>n({...e,startMinute:Fr(t.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),l(`span`,{className:`text-foreground-subtle`,children:`→`}),l(`input`,{type:`time`,value:Pr(e.endMinute),onChange:t=>n({...e,endMinute:Fr(t.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),l(`span`,{className:`flex-1`}),l(`button`,{type:`button`,onClick:r,"aria-label":`Remove window`,className:`text-foreground-subtle hover:text-danger`,children:l(et,{className:`h-3.5 w-3.5`})})]}),l(`div`,{className:`flex flex-wrap gap-1`,children:Nr.map(t=>l(`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))})]})}var zr=[{id:`liveness`,label:`Devices & streams`,hint:`A device the hub can no longer reach, or a stream that stopped or came back.`,kinds:[{value:`device-offline`,label:`Device offline`},{value:`device-online`,label:`Device online`},{value:`stream-offline`,label:`Stream offline`},{value:`stream-online`,label:`Stream online`}]},{id:`switches`,label:`Device switch`,hint:`A device an operator turned off or back on. Not a fault — a choice.`,kinds:[{value:`device-disabled`,label:`Device switched off`},{value:`device-enabled`,label:`Device switched on`}]},{id:`nodes`,label:`Nodes`,hint:`An agent or worker node joining or leaving the cluster.`,kinds:[{value:`node-offline`,label:`Node offline`},{value:`node-online`,label:`Node online`}]},{id:`silent-failures`,label:`Up but producing nothing`,hint:`A component that is running and returning no work: a node whose accelerators all went away, a camera being analysed that detects nothing, or an addon the hub has stopped restarting.`,kinds:[{value:`node-inference-unavailable`,label:`Node has no usable inference device`},{value:`detection-blind`,label:`Camera detecting nothing`},{value:`addon-crash-loop`,label:`Addon stopped after repeated crashes`}]},{id:`alarm`,label:`Alarm`,hint:`The alarm panel refusing to arm, arming, armed, going off, or being disarmed.`,kinds:[{value:`alarm-arm-refused`,label:`Alarm arm refused (something is open)`},{value:`alarm-arming`,label:`Alarm arming (exit delay)`},{value:`alarm-armed`,label:`Alarm armed`},{value:`alarm-triggered`,label:`Alarm triggered`},{value:`alarm-disarmed`,label:`Alarm disarmed`}]},{id:`updates`,label:`Updates`,hint:`A newer version of an addon or of the server itself is available, or an update just finished.`,kinds:[{value:`addon-update-available`,label:`Addon update available`},{value:`server-update-available`,label:`Server update available`},{value:`addon-updated`,label:`Addons updated`},{value:`server-updated`,label:`Server updated`}]},{id:`exports`,label:`Exports`,hint:`A footage export finished rendering.`,kinds:[{value:`export-completed`,label:`Export completed`}]}],Br=zr.flatMap(e=>e.kinds);function Vr(e){return Br.find(t=>t.value===e)?.label??e}function Hr(e){return{devices:Te(e,`deviceIds`),deviceTypes:Te(e,`deviceTypes`),nodes:Te(e,`nodeIds`),packages:Te(e,`packageNames`)}}var Ur=Object.values(L).map(e=>({value:e,label:Wr(e)})).toSorted((e,t)=>e.label.localeCompare(t.label));function Wr(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Gr(e,t){let n=e?.kinds??[],r=n.includes(t)?n.filter(e=>e!==t):Br.filter(e=>e.value===t||n.includes(e.value)).map(e=>e.value);if(r.length!==0)return Jr(e,r)}function Kr(e,t){let n=e?.kinds??[];if(n.length===0)return;let r=qr(t,`deviceIds`,e?.deviceIds),i=qr(t,`deviceTypes`,e?.deviceTypes),a=qr(t,`nodeIds`,e?.nodeIds),o=qr(t,`packageNames`,e?.packageNames);return{kinds:[...n],...r===void 0?{}:{deviceIds:[...r]},...i===void 0?{}:{deviceTypes:[...i]},...a===void 0?{}:{nodeIds:[...a]},...o===void 0?{}:{packageNames:[...o]}}}function qr(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 Jr(e,t){let n=Hr(t),r=n.devices?e?.deviceIds:void 0,i=n.deviceTypes?e?.deviceTypes:void 0,a=n.nodes?e?.nodeIds:void 0,o=n.packages?e?.packageNames:void 0;return{kinds:[...t],...r&&r.length>0?{deviceIds:[...r]}:{},...i&&i.length>0?{deviceTypes:[...i]}:{},...a&&a.length>0?{nodeIds:[...a]}:{},...o&&o.length>0?{packageNames:[...o]}:{}}}function Yr(e,t=2){if(e===void 0||e.length===0)return`No event selected`;let n=e.slice(0,t).map(Vr).join(`, `),r=e.length-Math.min(t,e.length);return r>0?`${n} +${r}`:n}function Xr(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;return r>0&&t.push(e.deviceTypes?.map(Wr).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`}`),t.length===0?`Everything`:t.join(` · `)}e();var Zr=[`nc-pickers`,`nodes`],Qr=[`nc-pickers`,`addon-packages`];function $r(){let e=d().trpcClient,t=r({queryKey:Zr,staleTime:6e4,queryFn:async()=>(await e.nodes.topology.query()).map(e=>({value:e.id,label:e.name.length>0?e.name:e.id,hint:e.isOnline?e.id:`${e.id} · offline`}))});return{options:t.data??[],loading:t.isLoading}}function ei(){let e=d().trpcClient,t=r({queryKey:Qr,staleTime:6e4,queryFn:async()=>(await e.addons.listPackages.query()).map(e=>({value:e.name,label:e.name,hint:e.version})).toSorted((e,t)=>e.label.localeCompare(t.label))});return{options:t.data??[],loading:t.isLoading}}function ti({value:e,cameras:r,onChange:i}){let a=n(()=>e?.kinds??[],[e]),o=Hr(a),s=$r(),c=ei();return t(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[zr.map(n=>t(`div`,{children:[l(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:n.label}),l(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:n.kinds.map(t=>{let n=a.includes(t.value);return l(`button`,{type:`button`,role:`checkbox`,"aria-checked":n,"aria-label":t.label,onClick:()=>i(Gr(e,t.value)),className:n?`rounded-md border border-primary bg-primary/10 px-2 py-1 text-[11px] text-primary`:`rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:t.label},t.value)})}),l(`p`,{className:U,children:n.hint})]},n.id)),a.length===0&&l(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,children:`Pick at least one event — a system rule with no event selected is never evaluated, and the hub refuses to save it.`}),o.deviceTypes&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these device types (optional)`}),l(yn,{options:Ur,value:e?.deviceTypes??[],onChange:t=>i(Kr(e,{deviceTypes:t})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`}),l(`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.`})]}),o.devices&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these cameras (optional)`}),l(hr,{cameras:r,value:e?.deviceIds??[],onChange:t=>i(Kr(e,{deviceIds:t}))}),l(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to watch every camera.`})]}),o.nodes&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these nodes (optional)`}),l(yn,{options:s.options,value:e?.nodeIds??[],onChange:t=>i(Kr(e,{nodeIds:t})),loading:s.loading,emptyHint:`No nodes reported — the rule watches every node.`,placeholder:`Node id…`}),l(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to watch every node.`})]}),o.packages&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these packages (optional)`}),l(yn,{options:c.options,value:e?.packageNames??[],onChange:t=>i(Kr(e,{packageNames:t})),loading:c.loading,emptyHint:`No installed packages listed — the rule watches every package.`,placeholder:`Package name…`}),l(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to be told about every addon and server update.`})]})]})}e();function ni({catalog:e,taxonomy:r,delivery:i,conditions:a,schedule:o,deviceIds:c,cameras:u,gateable:d,gateableScenes:f,onConditionsChange:p,onScheduleChange:m}){let h=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,p(n)},g=he({delivery:i,conditions:a}),_=n(()=>e.filter(e=>we(e,i,g)),[e,i,g]),v=e.length-_.length,y=n(()=>mn(_,e=>e.id!==`devices`&&ii(e,i,a)),[_,i,a]),b=n(()=>mn(_,e=>e.id!==`devices`&&!ii(e,i,a)),[_,i,a]),[x,S]=s(()=>{if(ai(a,o))return!0;try{return localStorage.getItem(ri)===`1`}catch{return!1}}),C=()=>{let e=!x;S(e);try{localStorage.setItem(ri,e?`1`:`0`)}catch{}},w=e=>e.map(e=>t(`div`,{className:`space-y-2.5`,children:[l(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:e.label}),e.descriptors.map(e=>t(`div`,{"data-testid":`condition-${e.id}`,children:[l(`label`,{className:H,children:e.label}),l(oi,{descriptor:e,taxonomy:r,conditions:a,schedule:o,deviceIds:c,cameras:u,gateable:d,gateableScenes:f,onFieldChange:h,onScheduleChange:m}),e.description&&l(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.description})]},e.id))]},e.id));return t(`div`,{className:`space-y-4`,children:[w(y),v>0&&t(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`nc-kind-hidden-note`,children:[v,` condition`,v===1?``:`s`,` that belong to other kinds of rule`,` `,v===1?`is`:`are`,` not shown — this rule fires on`,` `,ae(g).label.toLowerCase(),` and the engine could never match`,` `,v===1?`it`:`them`,` against its subject.`]}),b.length>0&&l(`button`,{type:`button`,onClick:C,"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:x?`▾ Hide advanced configurations`:`▸ Show more configurations`}),x&&w(b)]})}var ri=`camstack.nc.showAdvanced`;function ii(e,t,n={}){return t===`system-event`?e.id===`systemEvent`:e.id===`audio`?n.audio!==void 0:e.id===`occupancy`?n.occupancy!==void 0:ye(e.id)}function ai(e,t){for(let[t,n]of Object.entries(e))if(!ye(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 oi({descriptor:e,taxonomy:t,conditions:n,schedule:r,deviceIds:i,cameras:a,gateable:o,gateableScenes:s,onFieldChange:c,onScheduleChange:u}){switch(e.valueType){case`deviceIdList`:{if(!Jt(e.id))break;let t=e.id;return l(hr,{cameras:a,value:n[t]??[],onChange:e=>c(t,e.length>0?e:void 0)})}case`stringList`:{if(!Yt(e.id))break;let r=e.id,a=e=>c(r,e.length>0?e:void 0);if(r===`identities`||r===`identitiesExclude`)return l(Sr,{value:un(n,r),onChange:e=>r===`identities`?c(r,e):a(e)});if(r===`eventTypeTokens`)return l(Cr,{deviceIds:i,value:un(n,r),onChange:a});let o=ve(r,t);return o===null?l(gr,{value:un(n,r),placeholder:`Add value…`,onChange:a}):l(_r,{picker:o,value:un(n,r),onChange:a})}case`zoneIdList`:{if(!Xt(e.id))break;let t=e.id;return l(xr,{deviceIds:i,cameras:a,value:un(n,t),onChange:e=>c(t,e.length>0?e:void 0)})}case`number01`:{if(!Zt(e.id))break;let t=e.id;return l(vr,{value:dn(n,t),min:0,max:1,step:.05,onChange:e=>c(t,e)})}case`number`:{if(!Qt(e.id))break;let t=e.id;return l(vr,{value:dn(n,t),min:0,step:1,onChange:e=>c(t,e)})}case`sourceSelect`:{if(!$t(e.id))break;let t=e.id;return l(v,{value:n[t]??`any`,options:or(e,Fn).map(e=>({value:e.value,label:e.label})),onChange:e=>c(t,li(e.target.value))})}case`systemEvent`:{if(!sn(e.id))break;let t=e.id;return l(ti,{value:n[t],cameras:a,onChange:e=>c(t,e)})}case`deviceState`:if(!cn(e.id))break;return l(Ar,{gateable:o,value:n.deviceState,onChange:e=>c(`deviceState`,e)});case`scene`:if(!ln(e.id))break;return l(Mr,{scenes:s,value:n.scene,onChange:e=>c(`scene`,e)});case`crossingSelect`:{if(!en(e.id))break;let t=e.id;return l(yr,{value:n[t],onChange:e=>c(t,e),...e.options?{options:e.options}:{}})}case`packagePhase`:{if(!tn(e.id))break;let t=e.id;return l(v,{value:n[t]??``,options:[{value:``,label:`— any phase —`},...or(e,In).map(e=>({value:e.value,label:e.label}))],onChange:e=>c(t,ui(e.target.value))})}case`zoneSelection`:{if(!nn(e.id))break;let t=e.id;return l(br,{deviceIds:i,cameras:a,value:n[t],onChange:e=>c(t,e)})}case`plateMatcher`:{if(!rn(e.id))break;let t=e.id;return l(kr,{value:n[t],onChange:e=>c(t,e)})}case`occupancy`:{if(!an(e.id))break;let r=e.id;return l(Er,{deviceIds:i,cameras:a,classOptions:si(t),value:n[r],onChange:e=>c(r,e)})}case`audio`:{if(!on(e.id))break;let r=e.id;return l(Or,{taxonomy:t,value:n[r],onChange:e=>c(r,e)})}case`schedule`:return l(Lr,{value:r,onChange:u});default:break}return l(ci,{descriptor:e,conditions:n})}function si(e){let t=ve(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function ci({descriptor:e,conditions:n}){let r=Object.entries(n).find(([t])=>t===e.id);return t(`p`,{className:U,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.`,` `,t(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function li(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function ui(e){return In.find(t=>t.value===e)?.value}var di={search:``,types:[],selectedOnly:!1};function fi(e){let t=new Map;for(let n of e)t.set(n.type,(t.get(n.type)??0)+1);return[...t.entries()].map(([e,t])=>({type:e,count:t})).sort((e,t)=>t.count-e.count||e.type.localeCompare(t.type))}function pi(e,t,n){let r=new Set(n),i=t.search.trim().toLowerCase(),a=new Set(t.types);return e.filter(e=>r.has(e.id)?!0:!(t.selectedOnly||a.size>0&&!a.has(e.type)||i!==``&&!e.name.toLowerCase().includes(i)))}function mi(e){let t=new Map,n=[];for(let r of e){if(r.location===null||r.location===``){n.push(r);continue}let e=t.get(r.location)??[];e.push(r),t.set(r.location,e)}let r=[...t.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({location:e,devices:[...t].sort((e,t)=>e.name.localeCompare(t.name))}));return n.length>0&&r.push({location:null,devices:[...n].sort((e,t)=>e.name.localeCompare(t.name))}),r}function hi(e,t){let n=new Set(t);for(let t of e)n.add(t.id);return[...n]}function gi(e,t){let n=new Set(e.map(e=>e.id));return t.filter(e=>!n.has(e))}function _i(e,t){return e.length===0?`Every device (${String(t)}) — no restriction`:`${String(e.length)} of ${String(t)} selected`}e();function vi({devices:e,value:r,onChange:i,loading:a=!1}){let[o,c]=s(di),u=n(()=>fi(e),[e]),d=n(()=>pi(e,o,r),[e,o,r]),f=n(()=>mi(d),[d]),p=e=>c(t=>({...t,types:t.types.includes(e)?t.types.filter(t=>t!==e):[...t.types,e]})),m=e=>i(r.includes(e)?r.filter(t=>t!==e):[...r,e]);return a?l(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Loading devices…`}):t(`div`,{className:`space-y-3`,children:[t(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[l(`p`,{className:`text-[11px] text-foreground-subtle`,children:_i(r,e.length)}),t(`div`,{className:`flex items-center gap-1`,children:[l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i(hi(d,r)),children:`Select shown`}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i(gi(d,r)),children:`Clear shown`})]})]}),t(`div`,{className:`flex flex-wrap items-center gap-2`,children:[l(b,{className:`min-w-[10rem] flex-1`,value:o.search,placeholder:`Search by name…`,leftSlot:l(Ue,{className:`h-3.5 w-3.5 text-foreground-subtle`}),onChange:e=>c(t=>({...t,search:e.target.value}))}),t(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(`input`,{type:`checkbox`,checked:o.selectedOnly,onChange:e=>c(t=>({...t,selectedOnly:e.target.checked}))}),`Selected only`]})]}),l(`div`,{className:`flex flex-wrap gap-1`,children:u.map(e=>t(`button`,{type:`button`,onClick:()=>p(e.type),className:o.types.includes(e.type)?`rounded-full border border-primary bg-primary/10 px-2 py-0.5 text-[10px] text-foreground`:`rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-muted hover:bg-surface-hover`,children:[e.type,` `,l(`span`,{className:`text-foreground-subtle`,children:e.count})]},e.type))}),d.length===0?l(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No device matches this filter.`}):l(`div`,{className:`max-h-72 space-y-2 overflow-y-auto`,children:f.map(e=>t(`div`,{children:[l(`p`,{className:`px-1 pb-1 text-[10px] uppercase tracking-wide text-foreground-subtle`,children:e.location??`No location`}),l(`div`,{className:`divide-y divide-border rounded-md border border-border`,children:e.devices.map(e=>t(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:r.includes(e.id),onChange:()=>m(e.id),className:`accent-primary`}),l(`span`,{className:`flex-1 truncate`,children:e.name}),l(g,{variant:`default`,children:e.type})]},e.id))})]},e.location??`__unplaced`))})]})}e();var yi=[`notificationRules`,`listSnoozes`],bi=[10,30,60,120];function xi({ruleId:e,ruleName:n,exempt:r=!1,variant:i=`icon`}){let a=d(),u=o(),[f,p]=s(30),[m,h]=s(null),g=c({mutationFn:t=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>u.invalidateQueries({queryKey:yi}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?i===`icon`?null:l(`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`?l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:`Silence this rule for ${Un(30)} — it appears under "Silenced right now"`,"aria-label":`snooze ${n}`,"data-testid":`nc-rule-snooze-now`,children:g.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Me,{className:`h-3.5 w-3.5`})}):t(`div`,{className:`space-y-1`,children:[t(`div`,{className:`flex items-end gap-2`,children:[l(`div`,{className:`w-32`,children:l(v,{value:String(f),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:bi.map(e=>({value:String(e),label:Un(e)}))})}),t(_,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(f),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Me,{className:`h-3.5 w-3.5`}),`Silence this rule now`]})]}),l(`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&&l(`p`,{className:`text-[10px] text-danger`,children:m})]})}var Si=`pipeline-analytics`,Ci=`nc.getRuleStatus`,wi=`nc.testRule`;function Ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function W(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ei(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Di(e){if(!Ti(e))return;let t=Ei(e,`id`),n=Ei(e,`downloadPath`),r=W(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:Ei(e,`mediaType`)??`video`,sizeBytes:W(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function Oi(e){if(!Ti(e))return;let t=W(e,`startMs`),n=W(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function ki(e){if(!Ti(e))return null;let t=W(e,`deviceId`);if(t===void 0)return null;let n=W(e,`lastGeneratedAt`),r=Di(e.lastArtifact),i=e.rendering,a=Ti(i)?{startedAt:W(i,`startedAt`)??0,windowStartMs:W(i,`windowStartMs`)??0,windowEndMs:W(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function Ai(e){if(!Ti(e))return null;let t=Ei(e,`kind`);if(t===`none`)return{kind:`none`,reason:Ei(e,`reason`)??``};if(t===`occupancy`){let t=W(e,`deviceId`),n=W(e,`threshold`),r=W(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=Ei(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=W(e,`count`),s=W(e,`observedAt`),c=W(e,`since`),l=Ei(e,`scope`),u=Ei(e,`className`),d=Ei(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=ki(e);t!==null&&n.push(t)}let r=Oi(e.lastWindow),i=e.nextWindow,a=Ti(i)?{startMs:W(i,`startMs`)??0,endMs:W(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:W(e,`settleMs`)??0}}return null}function ji(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 Mi(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 Ni(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 ${ji(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 Pi(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${ji(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} · ${Mi(i.sizeBytes)}`}var Fi=5e3;function Ii({ruleId:e,cameraName:n}){let a=d(),o=r({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:Fi,queryFn:async()=>Ai(await a.trpcClient.addons.custom.mutate({addonId:Si,action:Ci,input:{ruleId:e}}))}).data;if(o==null||o.kind===`none`)return null;let s=Date.now(),c=e=>n?.(e)??`camera ${String(e)}`;return t(`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`&&t(`p`,{className:`flex items-start gap-1.5`,children:[o.unavailable!==void 0||o.warning!==void 0?l($e,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):l(Be,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),t(`span`,{children:[l(`span`,{className:`text-foreground`,children:c(o.deviceId)}),` —`,` `,Ni(o,s)]})]}),o.kind===`timelapse`&&t(i,{children:[o.devices.map(e=>t(`p`,{className:`flex items-start gap-1.5`,children:[l(Be,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),t(`span`,{children:[Pi(e,c(e.deviceId),s),e.lastArtifact!==void 0&&t(i,{children:[` · `,l(`a`,{className:`text-primary hover:underline`,href:`/${e.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:`open`})]})]})]},e.deviceId)),t(`p`,{className:`flex items-start gap-1.5`,children:[l(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),t(`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 Li(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function G(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ri(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function zi(e){if(!Li(e))return null;let t=G(e,`ruleId`),n=G(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=G(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:G(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Ri(e,`targetIds`)}}function Bi(e){if(!Li(e))return null;let t=G(e,`conditionId`),n=G(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Vi(e){if(!Li(e))return null;let t=G(e,`recordId`),n=G(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=zi(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Bi(t);e!==null&&i.push(e)}let a=G(e,`droppedBy`);return{recordId:t,delivery:n,trigger:G(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:G(e,`still`)??`none`,notes:Ri(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i}}function Hi(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.`}e();function Ui({ruleId:e,ruleName:n,fallbackDeviceId:r,variant:a=`icon`,showResult:o=!1}){let u=d(),[f,p]=s(null),[m,h]=s(null),g=c({mutationFn:async()=>Vi(await u.trpcClient.addons.custom.mutate({addonId:Si,action:wi,input:{ruleId:e,...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{p(null),h(null)},onSuccess:e=>p(e),onError:e=>h(e instanceof Error?e.message:`The test could not be run.`)}),v=f===null?m===null?void 0:m:Hi(f);return t(i,{children:[t(_,{size:`sm`,variant:a===`icon`?`ghost`:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(),title:v??`Test now — fires this rule and really sends the notification`,"aria-label":`test ${n} now`,"data-testid":`nc-rule-test-now`,children:[g.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Le,{className:`h-3.5 w-3.5`}),a===`full`&&`Test now`]}),o&&m!==null&&l(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:m}),o&&f!==null&&t(`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:[l(`p`,{className:`text-foreground`,children:Hi(f)}),f.planNotes.map(e=>t(`p`,{className:`flex gap-1.5`,children:[l($e,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),l(`span`,{children:e.note})]},e.conditionId)),f.notes.map(e=>t(`p`,{children:[`· `,e]},e))]})]})}e();var Wi=[`notificationRules`,`listSnoozes`],Gi=3e4;function Ki(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function qi(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 Ji({rules:e}){let i=d(),a=o(),s=r({queryKey:Wi,refetchInterval:Gi,queryFn:async()=>(await i.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),u=c({mutationFn:e=>i.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>a.invalidateQueries({queryKey:Wi})}),f=n(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),p=Date.now(),h=(s.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return t(m,{className:`p-4`,children:[t(`div`,{className:`flex items-center gap-2 mb-3`,children:[l(Me,{className:`h-4 w-4 text-foreground-subtle`}),l(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),h.length===0&&l(`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.`}),l(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:h.map(e=>t(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[t(`div`,{className:`min-w-0`,children:[t(`div`,{className:`flex items-center gap-2`,children:[l(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:f.get(e.ruleId??``)??`A rule`}),e.global&&l(g,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&l(g,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&l(g,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),t(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,qi(Ki(e,p))]})]}),l(_,{size:`sm`,variant:`outline`,disabled:u.isPending,onClick:()=>u.mutate(e.id),children:`End now`})]},e.id))})]})}e();var Yi=[`notificationRules`,`listRules`],Xi=[`notificationOutput`,`listTargets`,`forRules`],Zi=[`notificationRules`,`getConditionCatalog`],Qi=[`deviceManager`,`listAll`,`forRules`],$i=[`deviceManager`,`listAll`,`forRuleActions`],ea=[`deviceManager`,`gateableDevices`],ta=be.options;function na({onSimulateRule:e}={}){let i=d(),[a,o]=s({mode:`closed`}),[u,f]=s(null),[p,h]=s(`all`),g=r({queryKey:Yi,queryFn:async()=>(await i.trpcClient.notificationRules.listRules.query({})).rules}),v=r({queryKey:Xi,queryFn:()=>i.trpcClient.notificationOutput.listTargets.query({})}),y=r({queryKey:Zi,queryFn:()=>i.trpcClient.notificationRules.getConditionCatalog.query({})}),b=r({queryKey:ea,queryFn:async()=>{let e=await i.trpcClient.deviceManager.listAll.query({}),t=[];for(let n of e){let e=fe(await i.trpcClient.deviceManager.loadRuntimeState.query({deviceId:n.id}),ta);e.length>0&&t.push({id:n.id,name:n.name,states:e})}return t},staleTime:6e4}),x=r({queryKey:$i,queryFn:async()=>(await i.trpcClient.deviceManager.listAll.query({projection:`slim`})).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})).sort((e,t)=>e.name.localeCompare(t.name)),staleTime:6e4}),S=r({queryKey:Qi,queryFn:async()=>(await i.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===L.Camera).map(e=>({id:e.id,name:e.name}))}),w=rt(n(()=>(S.data??[]).map(e=>e.id),[S.data])),O=n(()=>{let e=new Map((S.data??[]).map(e=>[e.id,e.name]));return w.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})))},[w.results,S.data]),k=n(()=>{let e=new Map;for(let t of v.data??[])e.set(t.id,t.name);return e},[v.data]),A=c({mutationFn:e=>i.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void g.refetch()}),j=c({mutationFn:e=>i.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>{f(null),g.refetch()}}),M=g.data??[],N=n(()=>M.filter(e=>ie(e,p)),[M,p]),P=n(()=>{let e=new Map;for(let t of wn)e.set(t.key,M.filter(e=>ie(e,t.key)).length);return e},[M]),te=wn.find(e=>e.key===p)??wn[0],ne=p===`system`;return t(z,{icon:Ne,title:`Notification Rules`,subtitle:te.blurb,actions:t(_,{size:`sm`,type:`button`,onClick:()=>o({mode:`form`,rule:null,seed:ue(p)}),children:[l(ze,{className:`h-3.5 w-3.5`}),te.newRuleLabel]}),children:[l(T,{value:p,onValueChange:e=>h(Ce(e)??p),children:l(ee,{className:`mb-3`,children:wn.map(e=>t(E,{value:e.key,children:[e.label,l(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:P.get(e.key)??0})]},e.key))})}),l(Ji,{rules:M}),g.isLoading&&l(`div`,{className:`flex items-center justify-center py-16`,children:l(R,{className:`h-6 w-6 animate-spin text-primary`})}),g.isError&&!g.isLoading&&l(C,{title:`Failed to load rules`,message:g.error instanceof Error?g.error.message:`Unknown error`,onRetry:()=>void g.refetch()}),!g.isLoading&&!g.isError&&N.length===0&&l(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:te.emptyHint}),N.length>0&&l(m,{children:l(D,{columns:ne?ia({targetNameById:k,confirmDeleteId:u,deletePending:j.isPending,onToggle:(e,t)=>A.mutate({ruleId:e.id,enabled:t}),onEdit:e=>o({mode:`form`,rule:e}),onDuplicate:e=>o({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:f,onConfirmDelete:e=>j.mutate(e.id)}):ra({targetNameById:k,confirmDeleteId:u,deletePending:j.isPending,onToggle:(e,t)=>A.mutate({ruleId:e.id,enabled:t}),onEdit:e=>o({mode:`form`,rule:e}),onDuplicate:e=>o({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:f,onConfirmDelete:e=>j.mutate(e.id),...e?{onTest:e}:{}}),rows:N,rowKey:e=>e.id,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),a.mode===`form`&&l(aa,{rule:a.rule,...a.seed?{seed:a.seed}:{},targets:v.data??[],actuatable:x.data??[],catalog:nr(y.data?.catalog??[]),taxonomy:y.data?.taxonomy,cameras:S.data??[],gateable:b.data??[],gateableScenes:O,onCancel:()=>o({mode:`closed`}),onSaved:()=>{o({mode:`closed`}),g.refetch()}})]})}function ra(e){return[{key:`name`,header:`Rule`,render:e=>t(`span`,{className:`flex items-center gap-2`,children:[l(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&l(g,{variant:`warning`,children:`disabled`}),Kn(e.conditions,e.actions?.onTrigger??[])&&l(g,{variant:`info`,children:`Snooze disabled (alarm rule)`})]})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:e=>t(`span`,{className:`flex items-center gap-1.5`,children:[l(`span`,{className:`text-[11px] text-foreground-subtle`,children:xn(e.delivery)}),!Cn(e.delivery)&&l(g,{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 l(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>l(O,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>t(`span`,{className:`flex items-center justify-end gap-1`,children:[l(Ui,{ruleId:n.id,ruleName:n.name,...n.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:n.conditions.devices[0]}}),e.onTest&&l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(n),title:`Open in the simulator — describe an event and tune it before injecting`,"aria-label":`simulate ${n.name}`,children:l(Ie,{className:`h-3.5 w-3.5`})}),l(xi,{ruleId:n.id,ruleName:n.name,exempt:Kn(n.conditions,n.actions?.onTrigger??[])}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onEdit(n),title:`Edit`,children:l(Re,{className:`h-3.5 w-3.5`})}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(n),title:`Duplicate`,children:l(Fe,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===n.id?t(i,{children:[t(_,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(n),children:[e.deletePending&&l(R,{className:`h-3.5 w-3.5 animate-spin`}),`Confirm`]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(n.id),title:`Delete`,children:l(et,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function ia(e){let t=ra(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:Yr(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:Xr(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 l(`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=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:Dn(e.throttle.cooldownSec)})},...n(`enabled`),...n(`actions`)]}function aa({rule:e,seed:n,targets:a,catalog:o,taxonomy:u,cameras:f,gateable:m,gateableScenes:h,actuatable:y,onSaved:x,onCancel:C}){let w=d(),D=e!=null&&e.id.length>0,[k,j]=s(()=>e?Jn(e):qn(n?.delivery,n?.conditions)),[M,N]=s(null),[te,ne]=s(null),[ie,oe]=s(pr),F=e=>j(t=>({...t,...e})),se=D&&e?{throttle:e.throttle}:void 0,ce=c({mutationFn:async()=>{let t=ar(k,se,o);D&&e?await w.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t}):await w.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:x,onError:e=>N(e instanceof Error?e.message:`Save failed`)}),le=c({mutationFn:async()=>{let e=ar(k,se,o);return(await w.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>ne(null),onSuccess:e=>ne(e),onError:e=>N(e instanceof Error?e.message:`Test failed`)}),ue=k.targetIds.map(e=>a.find(t=>t.id===e)?.name??e),de=e=>F({targetIds:k.targetIds.includes(e)?k.targetIds.filter(t=>t!==e):[...k.targetIds,e]}),fe=r({queryKey:[`userManagement`,`listUsers`],queryFn:()=>w.trpcClient.userManagement.listUsers.query()}).data,pe=e=>F({targetUsers:k.targetUsers.includes(e)?k.targetUsers.filter(t=>t!==e):[...k.targetUsers,e]}),me=bn.find(e=>e.value===k.delivery)?.hint,ge=Yn(k),_e=re(k.delivery),I=ae(he(k)),ve=fr(k),ye=Kn(k.conditions,k.actions.sequences),L=k.conditions.identities!==void 0||k.conditions.plates!==void 0,be=ur(k.delivery,k.conditions),xe=be.some(e=>e.key===ie)?ie:pr;return Cn(k.delivery)?l(P,{open:!0,onOpenChange:e=>!e&&C(),children:t(p,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[t(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[t(`h3`,{className:`text-sm font-semibold text-foreground flex min-w-0 items-center gap-2`,children:[l(Ne,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),l(`span`,{className:`truncate`,children:D?`Edit ${e?.name}`:`New notification rule`})]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:C,children:`Cancel`})]}),M&&l(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:M}),D&&e&&l(`div`,{className:`shrink-0 mb-3`,children:l(Ii,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??`camera ${String(e)}`})}),t(T,{value:xe,onValueChange:e=>oe(mr(e)??ie),className:`flex min-h-0 flex-1 flex-col`,children:[l(ee,{className:`mb-3 shrink-0`,children:be.map(e=>l(E,{value:e.key,children:e.label},e.key))}),t(S,{className:`pr-1`,children:[t(A,{value:`rule`,className:`space-y-4`,children:[t(`div`,{className:`flex items-end gap-3`,children:[t(`div`,{className:`min-w-0 flex-1`,children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),l(b,{value:k.name,onChange:e=>F({name:e.target.value}),placeholder:`e.g. Front door package`})]}),t(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[l(O,{checked:k.enabled,onCheckedChange:e=>F({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),l(v,{value:k.delivery,onChange:e=>{let t=Sn(e.target.value);t&&F({delivery:t})},options:bn.map(e=>({value:e.value,label:e.label}))}),me&&l(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:me})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),a.length===0?l(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery targets configured. Add one under the Targets tab first.`}):l(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(e=>t(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:k.targetIds.includes(e.id),onChange:()=>de(e.id),className:`accent-primary`}),l(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&l(g,{variant:`warning`,children:`disabled`})]},e.id))})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(fe??[]).length===0?l(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No users to notify.`}):l(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:(fe??[]).map(e=>t(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:k.targetUsers.includes(e.id),onChange:()=>pe(e.id),className:`accent-primary`}),l(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&l(g,{variant:`info`,children:`admin`})]},e.id))}),l(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Delivers to the targets each user owns, only for cameras that user can access.`})]})]}),l(A,{value:`devices`,className:`space-y-4`,children:l(vi,{devices:y,value:k.deviceIds,onChange:e=>F({deviceIds:e}),loading:y.length===0})}),l(A,{value:`actions`,className:`space-y-4`,children:l(Ut,{value:k.actions,onChange:e=>F({actions:e}),devices:y})}),t(A,{value:`advanced`,className:`space-y-4`,children:[t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown (seconds)`}),l(b,{type:`number`,min:0,max:En,step:1,value:String(k.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=On(e.target.value);t!==void 0&&F({cooldownSec:t})}}),t(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[_e?`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 per device unless the rule was configured otherwise.`,` `,`Any whole number from 0 (deliver every match) to `,String(En),` (24 hours).`]})]}),k.delivery===`immediate`?t(`div`,{children:[t(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[l(O,{checked:k.waitForEnhancement,onCheckedChange:e=>F({waitForEnhancement:e}),"aria-label":`wait for recognition`,disabled:!L}),`Wait for the face or plate before notifying`]}),l(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:L?`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,t(`div`,{children:[t(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[l(O,{checked:k.snoozeAllowGlobal,onCheckedChange:e=>F({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:ye}),`Anyone may snooze this rule for everyone`]}),l(`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.`})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),ye?l(`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.`}):t(i,{children:[l(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Hn.map(e=>{let t=k.snoozeOptions??Vn,n=t.includes(e);return l(_,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>F({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Un(e)},e)})}),l(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:k.snoozeOptions===void 0?`Not set — the notification offers the defaults (${Vn.map(Un).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.`:k.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.`}),k.snoozeOptions!==void 0&&l(_,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>F({snoozeOptions:void 0}),children:`Back to the defaults`})]})]}),D&&e&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Silence it now`}),l(xi,{ruleId:e.id,ruleName:e.name,exempt:ye,variant:`full`})]})]}),t(A,{value:`notification`,className:`space-y-4`,children:[t(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),l(v,{value:String(k.priority),onChange:e=>F({priority:Number(e.target.value)}),options:Bn.map(e=>({value:String(e.value),label:e.label}))})]}),!I.carriesMedia&&l(`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.`}),I.carriesMedia&&I.mediaBlurb!==void 0&&l(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:I.mediaBlurb}),I.carriesMedia&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),l(v,{value:k.mediaAttach,onChange:e=>{let t=An(e.target.value);t&&F({mediaAttach:t})},options:kn.map(e=>({value:e.value,label:e.label}))}),l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:kn.find(e=>e.value===k.mediaAttach)?.description}),t(`div`,{className:`mt-2 space-y-1`,children:[I.carriesSubjectCrop&&t(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[l(`input`,{type:`checkbox`,checked:k.mediaZoneCrop,onChange:e=>F({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),`Crop the image to the rule's zone`]}),t(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[l(`input`,{type:`checkbox`,checked:k.mediaGif,onChange:e=>F({mediaGif:e.target.checked}),className:`accent-primary`}),`Attach a GIF around the event`]}),t(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[l(`input`,{type:`checkbox`,checked:k.mediaClip,onChange:e=>F({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(k.mediaGif||k.mediaClip)&&t(`div`,{className:`mt-2`,children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),l(v,{value:k.mediaProfile??``,onChange:e=>F({mediaProfile:Pn(e.target.value)}),options:Nn.map(e=>({value:e.value,label:e.label}))}),l(`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.`}),l(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),l(v,{value:k.mediaClipSpeed===void 0?``:String(k.mediaClipSpeed),onChange:e=>F({mediaClipSpeed:cr(e.target.value)}),options:sr.map(e=>({value:e.value,label:e.label}))}),l(`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.`})]})]}),I.carriesMedia&&I.carriesSubjectCrop&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),l(v,{value:k.mediaFrame??``,onChange:e=>F({mediaFrame:Mn(e.target.value)}),options:jn.map(e=>({value:e.value,label:e.label}))}),l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`What the attached still shows. "Automatic" leaves it to the attachment mode above.`})]})]}),t(`div`,{className:`space-y-2`,children:[t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notification title`}),l(b,{value:k.templateTitle,onChange:e=>F({templateTitle:e.target.value}),placeholder:`{{camera}} — {{class}}`})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notification body`}),l(`textarea`,{value:k.templateBody,onChange:e=>F({templateBody:e.target.value}),rows:2,placeholder:`{{label}} seen in {{zone}} at {{time}}`,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`})]}),t(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`Leave blank to use the backend default text. Supported variables include`,` `,l(`code`,{children:`{{camera}}`}),`, `,l(`code`,{children:`{{class}}`}),`,`,` `,l(`code`,{children:`{{label}}`}),`, `,l(`code`,{children:`{{zone}}`}),`,`,` `,l(`code`,{children:`{{confidence}}`}),`, `,l(`code`,{children:`{{time}}`}),`.`]})]})]}),t(A,{value:`conditions`,className:`space-y-4`,children:[t(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[l(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:_e?`Which system events`:dr(k.conditions)??`Conditions`}),k.conditions.audio!==void 0&&l(`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).`}),k.conditions.occupancy!==void 0&&l(`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.`}),_e&&l(`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?l(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):l(ni,{catalog:o,taxonomy:u,delivery:k.delivery,conditions:k.conditions,schedule:k.schedule,deviceIds:k.deviceIds,cameras:f,gateable:m,gateableScenes:h,onConditionsChange:e=>F({conditions:e}),onScheduleChange:e=>F({schedule:e})})]}),D&&e&&t(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[t(`div`,{className:`flex items-center justify-between gap-2`,children:[l(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test this rule for real`}),l(Ui,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...k.deviceIds[0]===void 0?{}:{fallbackDeviceId:k.deviceIds[0]}})]}),l(`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.`})]}),!_e&&t(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[t(`div`,{className:`flex items-center justify-between gap-2`,children:[l(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),t(_,{size:`sm`,variant:`outline`,type:`button`,disabled:le.isPending||!Xn(k),onClick:()=>{N(null),le.mutate()},children:[le.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Ie,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),te!==null&&l(sa,{delivery:k.delivery,results:te,targetNames:ue})]})]})]})]}),ve.length>0&&t(`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:[t(`p`,{className:`text-foreground`,children:[`Saving drops `,ve.length,` condition`,ve.length===1?``:`s`,` this kind of rule cannot use:`]}),ve.map(e=>t(`p`,{children:[l(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),ge.length>0&&l(`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:ge.map(e=>l(`p`,{children:e},e))}),t(`div`,{className:`flex shrink-0 justify-end gap-2 mt-4`,children:[l(_,{variant:`secondary`,size:`sm`,type:`button`,onClick:C,children:`Cancel`}),t(_,{size:`sm`,type:`button`,disabled:ce.isPending||!Xn(k),onClick:()=>{N(null),ce.mutate()},children:[ce.isPending&&l(R,{className:`h-3.5 w-3.5 animate-spin`}),D?`Save changes`:`Create rule`]})]})]})}):l(oa,{rule:e,onCancel:C})}function oa({rule:e,onCancel:n}){let r=Object.keys(e?.conditions??{});return l(P,{open:!0,onOpenChange:e=>!e&&n(),children:t(p,{width:`lg`,placement:`sheet-on-mobile`,children:[t(`div`,{className:`flex items-center justify-between mb-3`,children:[t(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[l(Ne,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),l(g,{variant:`warning`,children:`read-only`})]}),t(`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 `,l(`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.`]}),t(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[t(`div`,{className:`flex gap-2`,children:[l(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),l(`dd`,{className:`text-foreground`,children:e?.delivery})]}),t(`div`,{className:`flex gap-2`,children:[l(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),l(`dd`,{className:`text-foreground`,children:e?.enabled?`yes`:`no`})]}),t(`div`,{className:`flex gap-2`,children:[l(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),l(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),t(`div`,{className:`flex gap-2`,children:[l(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),l(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):`none`})]})]}),l(`div`,{className:`flex justify-end gap-2 mt-4`,children:l(_,{variant:`secondary`,size:`sm`,type:`button`,onClick:n,children:`Close`})})]})})}function sa({delivery:e,results:n,targetNames:r}){if(e===`device-event`)return l(`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(n.length===0)return l(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`No records in the last 60 minutes matched — nothing to evaluate.`});let i=n.filter(e=>e.wouldFire).length;return t(`div`,{className:`mt-2 space-y-1.5`,children:[t(`div`,{className:`text-[11px] text-foreground-subtle`,children:[i,` of `,n.length,` evaluated record`,n.length===1?``:`s`,` would fire.`]}),l(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:n.slice(0,50).map(e=>t(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?l(Pe,{className:`h-3.5 w-3.5 shrink-0 text-success`}):l(Ge,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),l(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),t(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),l(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`object`}),e.wouldFire?t(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,r.join(`, `)||`targets`]}):e.failedCondition&&t(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}var ca=[{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 la(e){return ca.find(t=>t.value===e)?.value}function ua(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function da(e){return``}var fa={x:.25,y:.25,w:.5,h:.5},pa={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function ma(){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:fa,occupancy:pa,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function ha(e){return e.deviceId!==null}function ga(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function _a(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function va(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 ya(e){if(e.deviceId===null)return null;let t=e.trigger,n=_a(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:ba(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 ba(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 xa(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Sa(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 Ca(e){let t=ma(),n=e.conditions,r=Sa(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:xa(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:xa(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:xa(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:da(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:wa(n.occupancy)},onlyRuleId:e.id}}function wa(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 Ta(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 Ea(e){return{form:Ca(e),caveats:Ta(e),ruleName:e.name}}var Da=null;function Oa(e){Da=e}function ka(){return Da}function Aa(){Da=null}var ja=[`n/a`,`clear`,`suppressed`,`bypassed`],Ma=[`live`,`none`,`unavailable`,`unattachable`];function Na(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pa(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Fa(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Ia(e){if(!Na(e))return null;let t=Pa(e,`ruleId`),n=Pa(e,`ruleName`),r=Pa(e,`cooldown`),i=ja.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Pa(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Fa(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:Fa(e,`targetIds`)}}function La(e){if(!Na(e))return null;let t=Pa(e,`recordId`),n=Pa(e,`delivery`),r=Pa(e,`still`),i=Ma.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=Ia(e);t!==null&&o.push(t)}let s=Pa(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Fa(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Ra(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 za=new Set([`sensor`,`control`,`custom`]);function Ba({form:e,cameras:n,taxonomy:r,kinds:i,kindsLoading:a,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=ve(`classes`,r);if(e.trigger===`device-event`)return t(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[l(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),l(Va,{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 t(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[l(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),t(`div`,{children:[l(`label`,{className:H,children:`Audio classes`}),l(yn,{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…`})]}),t(`div`,{children:[l(`label`,{className:H,children:`Zones`}),l(xr,{deviceIds:s,cameras:n,value:e.zones,onChange:e=>o({zones:e})})]})]})}return e.trigger===`occupancy-event`?t(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[l(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),l(Ha,{form:e,cameras:n,taxonomy:r,onPatch:o})]}):t(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[l(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),t(`div`,{children:[l(`label`,{className:H,children:`Detected classes`}),c===null?l(gr,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):l(_r,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),t(`div`,{children:[l(`label`,{className:H,children:`Zones the subject is in`}),l(xr,{deviceIds:s,cameras:n,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&t(`div`,{className:`max-w-[14rem]`,children:[l(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),l(v,{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 Va({form:e,kinds:n,loading:r,onPatch:a}){let o=n.filter(e=>za.has(e.category)),s=o.find(t=>t.kind===e.sensorKind);return t(i,{children:[t(`div`,{children:[l(`label`,{className:H,children:`Event kind`}),l(v,{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);a({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!r&&o.length===0&&l(`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.`})]}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[t(`div`,{children:[l(`label`,{className:H,children:`Source device`}),l(b,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>a({sourceDeviceId:ga(e.target.value)??null})}),l(`p`,{className:U,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.`})]}),t(`div`,{children:[l(`label`,{className:H,children:`Event type token`}),l(b,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>a({eventType:e.target.value})}),l(`p`,{className:U,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 Ha({form:e,cameras:n,taxonomy:r,onPatch:a}){let o=e.deviceId===null?[]:[e.deviceId],s=ve(`occupancy`,r),c=s===null?[]:s.groups.flatMap(e=>e.options),u=e.occupancy,d=e=>a({occupancy:{...u,...e}});return t(i,{children:[t(`div`,{children:[l(`label`,{className:H,children:`Zone`}),l(xr,{deviceIds:o,cameras:n,value:u.zoneId===``?[]:[u.zoneId],onChange:e=>d({zoneId:e[e.length-1]??``})}),l(`p`,{className:U,children:`Leave empty for the whole frame.`})]}),t(`div`,{className:`max-w-[14rem]`,children:[l(`label`,{className:H,children:`Class`}),l(v,{value:u.className,options:[{value:``,label:`— any class —`},...c.map(e=>({value:e.value,label:e.label}))],onChange:e=>d({className:e.target.value})})]}),t(`div`,{className:`flex flex-wrap items-end gap-3`,children:[t(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count now`,l(b,{type:`number`,min:0,className:`w-20`,value:String(u.count),onChange:e=>d({count:ga(e.target.value)??0})})]}),t(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,l(b,{type:`number`,min:0,className:`w-20`,value:String(u.previousCount),onChange:e=>d({previousCount:ga(e.target.value)??0})})]}),t(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,l(b,{type:`number`,min:1,className:`w-20`,value:String(u.threshold),onChange:e=>d({threshold:ga(e.target.value)??1})})]}),t(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[l(O,{checked:u.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function Ua({form:e,cameras:n,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId];return t(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[l(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Advanced`}),t(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&t(`div`,{children:[t(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[l(O,{checked:e.crossingEnabled,onCheckedChange:e=>r({crossingEnabled:e}),"aria-label":`zone crossing`}),`This event is a confirmed zone crossing`]}),e.crossingEnabled&&t(`div`,{className:`mt-1 space-y-1.5`,children:[l(`div`,{className:`max-w-[12rem]`,children:l(v,{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`})})}),l(xr,{deviceIds:i,cameras:n,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>r({crossingZoneId:e[e.length-1]??``})})]})]}),t(`div`,{children:[t(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[l(O,{checked:e.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),l(`p`,{className:U,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&l(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(n=>t(`label`,{className:`text-[11px] text-foreground-subtle`,children:[n,l(b,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[n]),onChange:t=>r({bbox:{...e.bbox,[n]:ga(t.target.value)??0}})})]},n))})]}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[t(`div`,{children:[l(`label`,{className:H,children:`Happened at`}),t(`div`,{className:`flex items-center gap-2`,children:[l(b,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:va(Date.now())}),children:`Set`}):l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:`Now`})]}),l(`p`,{className:U,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.`})]}),t(`div`,{children:[l(`label`,{className:H,children:`Detection source`}),l(v,{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 Wa({checked:e,label:n,hint:r,danger:i=!1,onChange:a}){return t(`div`,{children:[t(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[l(O,{checked:e,onCheckedChange:a,"aria-label":n}),n,i&&l(g,{variant:`danger`,children:`actuates devices`})]}),l(`p`,{className:U,children:r})]})}e();var Ga={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.`},Ka={"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 qa({result:e,targetName:n}){return t(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[l(`p`,{className:`text-xs font-medium text-foreground`,children:Ra(e)}),t(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[l(Ja,{recordId:e.recordId}),t(`span`,{children:[`delivery `,l(`span`,{className:`text-foreground`,children:e.delivery})]}),t(`span`,{children:[`candidates `,l(`span`,{className:`text-foreground`,children:e.candidates})]}),t(`span`,{title:Ga[e.still],children:[`still `,l(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&t(g,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&l(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>l(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?t(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`No rule was evaluated. Either no enabled rule declares the`,` `,l(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):l(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>l(Ya,{outcome:e,targetName:n},e.ruleId))})]})}function Ja({recordId:e}){let[n,r]=s(!1);return t(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[l(`code`,{className:`text-[10px] text-foreground`,children:e}),l(_,{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:l(Fe,{className:`h-3 w-3`})}),n&&l(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function Ya({outcome:e,targetName:n}){return t(`li`,{className:`space-y-1 px-2.5 py-2`,children:[t(`div`,{className:`flex items-center gap-2`,children:[e.matched?l(Pe,{className:`h-3.5 w-3.5 shrink-0 text-success`}):l(Ge,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),l(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),t(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:Ka[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&l(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?`Did not match. The engine reported no failing condition id.`:t(i,{children:[`Did not match — first failing condition`,` `,l(`code`,{className:`text-foreground`,children:e.failedCondition}),`.`]})}),e.matched&&t(`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(n).join(`, `)}`:` — no target resolved, so nothing will be delivered`,`.`]}),e.matchedOn!==void 0&&e.matchedOn.length>0&&t(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:[`matched on: `,e.matchedOn.join(`, `)]})]})}e();var Xa=`pipeline-analytics`,Za=`nc.injectTestEvent`;function Qa(){let e=d(),[i,a]=s(()=>ka()?.form??ma()),[o]=s(()=>ka()?.caveats??[]),[f]=s(()=>ka()?.ruleName??null);u(()=>Aa(),[]);let[p,h]=s(null),[g,y]=s(!1),[x,S]=s(null),w=e=>a(t=>({...t,...e})),T=r({queryKey:Qi,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===L.Camera).map(e=>({id:e.id,name:e.name}))}),E=r({queryKey:Zi,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),D=r({queryKey:Yi,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),O=r({queryKey:Xi,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),k=i.deviceId,A=r({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:k}],enabled:k!==null,staleTime:6e4,queryFn:async()=>k===null?[]:(await e.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[k]})).flatMap(e=>[...e.kinds])}),j=T.data??[],M=E.data?.taxonomy,N=A.data??[],ee=n(()=>{let e=new Map;for(let t of O.data??[])e.set(t.id,t.name);return e},[O.data]),P=c({mutationFn:async()=>{let t=ya(i);if(t===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:Xa,action:Za,input:t})},onMutate:()=>{h(null),y(!1),S(null)},onSuccess:e=>{let t=La(e);h(t),y(t===null)},onError:e=>S(e instanceof Error?e.message:`The simulation failed.`)}),te=ua(i.trigger),ne=D.data?.find(e=>e.id===i.onlyRuleId);return t(z,{icon:Ie,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:[T.isError&&l(C,{title:`Failed to load cameras`,message:T.error instanceof Error?T.error.message:`Unknown error`,onRetry:()=>void T.refetch()}),f!==null&&t(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:[`Seeded from the rule `,l(`span`,{className:`font-medium`,children:f}),`. Only that rule will be evaluated — clear "Evaluate only one rule" below to run the whole rule set.`]}),o.length>0&&l(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:o.map(e=>t(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[l($e,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),l(`span`,{children:e.note})]},e.conditionId))}),t(m,{className:`space-y-4`,children:[t(`div`,{children:[l(`label`,{className:H,children:`Camera`}),l(v,{"data-testid":`simulate-camera`,value:i.deviceId===null?``:String(i.deviceId),options:[{value:``,label:j.length===0?`Loading cameras…`:`— pick a camera —`},...j.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{w({deviceId:ga(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...i.occupancy,zoneId:``}})}}),l(`p`,{className:U,children:`The camera the event is attributed to — what a notification shows.`})]}),t(`div`,{children:[l(`label`,{className:H,children:`Trigger`}),l(v,{"data-testid":`simulate-trigger`,value:i.trigger,options:ca.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=la(e.target.value);if(!t)return;let n=da(i.trigger);w({trigger:t,source:i.source===``||i.source===n?da(t):i.source})}}),t(`p`,{className:U,children:[ca.find(e=>e.value===i.trigger)?.hint,` Only rules whose trigger is `,l(`span`,{className:`text-foreground`,children:te}),` are candidates.`]})]}),l(Ba,{form:i,cameras:j,taxonomy:M,kinds:N,kindsLoading:A.isLoading,onPatch:w}),t(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[l(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),t(`div`,{className:`mt-2 space-y-3`,children:[l(`p`,{className:U,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.`}),t(`div`,{children:[l(`label`,{className:H,children:`Label (identity name / plate / subclass)`}),l(b,{value:i.label,placeholder:`e.g. Marco, AB123CD`,onChange:e=>w({label:e.target.value})})]}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[t(`div`,{children:[l(`label`,{className:H,children:`Detection confidence`}),l(vr,{value:i.confidence,min:0,max:1,step:.05,onChange:e=>w({confidence:e})})]}),t(`div`,{children:[l(`label`,{className:H,children:`Label-match confidence`}),l(vr,{value:i.labelConfidence,min:0,max:1,step:.05,onChange:e=>w({labelConfidence:e})})]}),t(`div`,{children:[l(`label`,{className:H,children:`Importance`}),l(vr,{value:i.importance,min:0,max:1,step:.05,onChange:e=>w({importance:e})})]}),t(`div`,{children:[l(`label`,{className:H,children:`Dwell (seconds)`}),l(vr,{value:i.dwellSeconds,min:0,step:1,onChange:e=>w({dwellSeconds:e})})]})]})]})]}),l(Ua,{form:i,cameras:j,onPatch:w}),t(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[l(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),l(Wa,{checked:i.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=>w({bypassCooldown:e})}),l(Wa,{checked:i.bypassMute,label:`Ignore mutes and snoozes`,hint:`A muted camera or a snoozed rule drops the event before any rule is consulted.`,onChange:e=>w({bypassMute:e})}),l(Wa,{checked:i.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=>w({runActions:e})}),t(`div`,{className:`max-w-[14rem]`,children:[l(`label`,{className:H,children:`Still image`}),l(v,{value:i.still,options:[{value:`live`,label:`Live snapshot of the camera`},{value:`none`,label:`No image`}],onChange:e=>w({still:e.target.value===`none`?`none`:`live`})})]}),t(`div`,{children:[l(`label`,{className:H,children:`Evaluate only one rule`}),l(v,{value:i.onlyRuleId,options:[{value:``,label:`— every enabled rule —`},...(D.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>w({onlyRuleId:e.target.value})}),i.onlyRuleId.length>0&&ne===void 0&&t(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,l(`code`,{children:i.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),x!==null&&l(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:x}),t(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[l(`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.`}),t(_,{size:`sm`,type:`button`,disabled:P.isPending||!ha(i),onClick:()=>P.mutate(),children:[P.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Ie,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),g&&l(`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.`}),p!==null&&l(qa,{result:p,targetName:e=>ee.get(e)??e})]})}e();var K=`block text-[11px] font-medium text-foreground mb-1`,q=`mt-1 text-[10px] text-foreground-subtle`;function J({title:e,hint:n,children:r}){return t(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[l(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),n!==void 0&&l(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:n}),l(`div`,{className:`space-y-3`,children:r})]})}function $a({problems:e,testId:n=`digest-problems`}){return e.length===0?null:t(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":n,children:[t(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[l($e,{className:`h-3.5 w-3.5`}),`This rule could never produce anything, so it cannot be saved:`]}),l(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>l(`li`,{children:e},e))})]})}function eo({warnings:e,testId:n=`digest-warnings`}){return e.length===0?null:t(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":n,children:[t(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[l(tt,{className:`h-3.5 w-3.5`}),`Worth knowing:`]}),l(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>l(`li`,{children:e},e))})]})}function to({cameras:e,value:r,onChange:i,loading:a=!1,hint:o}){let[c,u]=s(``),d=n(()=>{let t=c.trim().toLowerCase();return t.length===0?e:e.filter(e=>e.name.toLowerCase().includes(t))},[e,c]),f=e=>i(r.includes(e)?r.filter(t=>t!==e):[...r,e]);return a?l(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Loading cameras…`}):t(`div`,{className:`space-y-2`,children:[t(`div`,{className:`flex items-center gap-2`,children:[l(b,{className:`flex-1`,value:c,placeholder:`Search a camera…`,leftSlot:l(Ue,{className:`h-3.5 w-3.5 text-foreground-subtle`}),onChange:e=>u(e.target.value),"data-testid":`digest-camera-search`}),l(`span`,{className:`whitespace-nowrap text-[11px] text-foreground-subtle`,children:r.length===0?`No camera selected`:`${r.length} selected`})]}),e.length===0?l(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No camera is available on this hub.`}):t(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,"data-testid":`digest-camera-list`,children:[d.map(e=>t(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:r.includes(e.id),onChange:()=>f(e.id),className:`accent-primary`,"data-testid":`digest-camera-${e.id}`}),l(`span`,{className:`flex-1 truncate`,children:e.name}),t(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`#`,e.id]})]},e.id)),d.length===0&&l(`p`,{className:`px-3 py-2 text-[11px] text-foreground-subtle`,children:`No camera matches that search.`})]}),o!==void 0&&l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:o})]})}function no({targets:e,value:n,onChange:r}){let i=e=>r(n.includes(e)?n.filter(t=>t!==e):[...n,e]);return e.length===0?l(`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.`}):l(`div`,{className:`divide-y divide-border rounded-md border border-border`,"data-testid":`digest-targets`,children:e.map(e=>t(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:n.includes(e.id),onChange:()=>i(e.id),className:`accent-primary`,"data-testid":`digest-target-${e.id}`}),l(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&l(g,{variant:`warning`,children:`disabled`})]},e.id))})}function Y({label:e,value:n,onChange:r,min:i,max:a,step:o,hint:s,emptyPlaceholder:c,testId:u,disabled:d=!1}){return t(`div`,{children:[l(`label`,{className:K,children:e}),l(b,{type:`number`,value:n===void 0?``:String(n),disabled:d,...i===void 0?{}:{min:i},...a===void 0?{}:{max:a},...o===void 0?{}:{step:o},...c===void 0?{}:{placeholder:c},...u===void 0?{}:{"data-testid":u},onChange:e=>{let t=e.target.value.trim();if(t.length===0){r(void 0);return}let n=Number(t);Number.isFinite(n)&&r(n)}}),s!==void 0&&l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function ro({label:e,checked:n,onChange:r,hint:i,testId:a}){return t(`div`,{children:[t(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[l(O,{checked:n,onCheckedChange:r,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),i!==void 0&&l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:i})]})}function io({title:e,body:n,onTitleChange:r,onBodyChange:i,variables:a,testIdPrefix:o}){return t(`div`,{className:`space-y-2`,children:[t(`div`,{children:[l(`label`,{className:K,children:`Notification title`}),l(b,{value:e,onChange:e=>r(e.target.value),"data-testid":`${o}-title`})]}),t(`div`,{children:[l(`label`,{className:K,children:`Notification body`}),l(`textarea`,{value:n,rows:2,onChange:e=>i(e.target.value),"data-testid":`${o}-body`,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`})]}),t(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`Leave both blank to use the hub's own wording (editable on the Texts tab). Variables:`,` `,a.map(e=>l(`code`,{className:`mr-1`,children:`{{${e}}}`},e))]})]})}function ao({open:e,ruleName:n,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:u=!1}){return e?l(P,{open:!0,onOpenChange:e=>!e&&s(),children:l(p,{width:`sm`,children:t(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[t(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[l(Le,{className:`h-4 w-4 text-warning`}),`Send a real notification now?`]}),t(`p`,{className:`text-xs text-foreground-subtle`,children:[`"`,n,`" will be produced over `,r,` and DELIVERED to`,` `,i,` — on every phone that target reaches, right now. This is not a dry run.`]}),l(`p`,{className:`text-[11px] text-foreground-subtle`,children:`It does not consume the schedule: the next scheduled run still happens.`}),c,t(`div`,{className:`flex justify-end gap-2`,children:[l(_,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),l(_,{size:`sm`,type:`button`,disabled:a||u,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?`Sending…`:`Produce and send`})]})]})})}):null}function oo(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 so=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function co(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function lo(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>so[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${co(t.startMinute)}–${co(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function uo(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${oo(Math.round(r/1e3))} ago`}function fo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function po(e){return Array.isArray(e)?`[${e.map(po).join(`,`)}]`:fo(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${po(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function X(e,t){return po(e)===po(t)}function mo(e){return e.map(e=>({targetId:e}))}var Z=`pipeline-analytics`,ho=`nc.getTexts`,go=`nc.setLanguage`,_o=`nc.setTextOverrides`,vo={en:`English`,it:`Italiano`};function yo(e){return e===`en`||e===`it`}function bo(e){return e===`override`||e===`shipped`||e===`fallback`}function xo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function So(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 Co(e){if(!xo(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`||!yo(r)||!bo(o)||i!==null&&typeof i!=`string`)return null;let s=So(e.placeholders),c=So(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 wo(e){if(!xo(e))return null;let{language:t,activeLanguage:n}=e;if(!yo(t)||!yo(n))return null;let r=So(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)yo(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=Co(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function To(e,t){return t.get(e.key)??e.override??e.shipped}function Eo(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 Do(e,t){return Object.keys(Eo(e,t)).length}function Oo(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 ko(e){return e.placeholders.length===0?`No variables — this text is printed as written.`:`Variables: ${e.placeholders.map(e=>`{{${e}}}`).join(` `)}`}function Ao(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 jo=`nc.listSummaryRules`,Mo=`nc.upsertSummaryRule`,No=`nc.deleteSummaryRule`,Po=`nc.testSummaryRule`,Fo=3600,Io=86400,Lo=3600,Ro=3600,zo=3*36e5,Bo=[`importance`,`recency`,`dwell`],Vo={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},Ho=[`none`,`tiles`,`all`],Uo=`none`,Wo={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},Go=[`en`,`it`],Ko=[`deliver-without-text`,`skip`],qo=2048,Jo=2e3;function Yo(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xo(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 Zo(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 Qo(e){if(e!==void 0)return typeof e==`string`?e:null}function $o(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function es(e){return Bo.some(t=>t===e)}function ts(e){return e===void 0?Uo:Ho.find(t=>t===e)??null}function ns(e){if(!Q(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Q(n))return null;let e=Xo(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=Qo(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 rs(e){if(!Q(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=ns(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 is(e){if(e==null)return;if(!Q(e))return null;let t=e.classes===void 0?void 0:Zo(e.classes),n=e.classesExclude===void 0?void 0:Zo(e.classesExclude),r=e.zones===void 0?void 0:Zo(e.zones);if(t===null||n===null||r===null)return null;let i=$o(e.minImportance),a=$o(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 as(e){if(e==null)return;if(!Q(e))return null;let t=Qo(e.title),n=Qo(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function os(e){return Go.some(t=>t===e)}function ss(e){return Ko.some(t=>t===e)}function cs(e){if(e==null)return;if(!Q(e)||typeof e.enabled!=`boolean`)return null;let t=Qo(e.profileId),n=Qo(e.prompt);if(t===null||n===null)return null;let r=$o(e.maxImagePx),i=$o(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!os(a))return null;let o=e.onFailure;return o!==void 0&&!ss(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 ls(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Q(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Q(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function us(e){if(!Q(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`||!es(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Xo(e.deviceIds),u=rs(e.window),d=ls(e.targets);if(l===null||u===null||d===null)return null;let f=is(e.filters),p=as(e.template);if(f===null||p===null)return null;let m=Qo(e.captionText),h=$o(e.generatedAt);if(m===null||h===null)return null;let g=ts(e.captions);if(g===null)return null;let _=cs(e.ai);return _===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:g,...m===void 0?{}:{captionText:m},deliverEmpty:c,priority:e.priority,...h===void 0?{}:{generatedAt:h},readOnly:e.readOnly===!0,..._===void 0?{}:{ai:_}}}function ds(e){if(!Q(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=us(n);if(e===null)return null;t.push(e)}return t}function fs(e){if(!Q(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=$o(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=$o(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Qo(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 ps(){return{name:``,enabled:!0,deviceIds:[],windowKind:`motion`,schedule:void 0,quietSeconds:300,maxWindowSeconds:3600,classes:[],classesExclude:[],zones:[],minImportance:void 0,minDwellSeconds:void 0,includeStationary:!1,maxTiles:9,maxAiImages:6,rank:`importance`,barrierSeconds:120,targetIds:[],templateTitle:``,templateBody:``,mosaicCaptions:Uo,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function ms(e){let t=ps(),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 hs(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function gs(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 _s(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 vs(e){return mo(e.targetIds)}function ys(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 bs(e){let t=gs(e),n=_s(e),r=ys(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:hs(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:vs(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 xs(e,t){let n=bs(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),X(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),X(n.window,t.window)||(r.window=n.window),X(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),X(n.targets,t.targets)||(r.targets=n.targets),X(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),X(n.ai,t.ai)||(r.ai=n.ai??null),r}function Ss(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 ${Fo}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${Io}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 ${Lo}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 ${Ro}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 ${Jo} 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 ${qo} 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 Cs(e){return Ss(e).length===0}function ws(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 Ts=[{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`]}],Es=`rule`;function Ds(e){return Ts.find(t=>t.key===e)?.key}function Os(e){return e.kind===`motion`?`Motion · ${oo(e.quietSeconds)} quiet · max ${oo(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${lo(e.schedule)}`}function ks(e,t){return uo(e,t,`Never run`)}function As(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 ≥ ${oo(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function js(e){return{windowStartMs:e-zo,windowEndMs:e}}e();var Ms=[`rule`,`cameras`,`tiles`,`matched`,`from`,`to`,`ai`],Ns={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},Ps={en:`English`,it:`Italiano`};function Fs(e){return Bo.find(t=>t===e)}function Is(e){return Ho.find(t=>t===e)}function Ls(e){return Go.find(t=>t===e)??``}function Rs(e){return Ko.find(t=>t===e)}function zs({rule:e,cameras:i,camerasLoading:a,targets:o,taxonomy:u,onSaved:f,onCancel:m}){let h=d(),[g,y]=s(()=>e===null?ps():ms(e)),[x,C]=s(null),[w,D]=s(Es),O=e=>y(t=>({...t,...e})),k=n(()=>{let e=ve(`occupancy`,u);return e===null?[]:e.groups.flatMap(e=>e.options)},[u]),{options:j,loading:M}=hn(g.deviceIds,i.map(e=>({id:e.id,name:e.name}))),N=r({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>h.trpcClient.llm.listProfiles.query({}),retry:!1}),te=(N.data??[]).filter(e=>e.supportsVision),ne=c({mutationFn:async()=>{let t=e===null?{rule:bs(g)}:{ruleId:e.id,patch:xs(g,e)};await h.trpcClient.addons.custom.mutate({addonId:Z,action:Mo,input:t})},onSuccess:f,onError:e=>C(e instanceof Error?e.message:`Save failed`)}),re=g.mosaicCaptions===`all`,ie=Ss(g),ae=ws(g),oe=Cs(g)&&!ne.isPending,F=Ts.some(e=>e.key===w)?w:Es;return l(P,{open:!0,onOpenChange:e=>!e&&m(),children:t(p,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[t(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[t(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[l(at,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),l(`span`,{className:`truncate`,children:e===null?`New summary`:`Edit ${e.name}`})]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:m,children:`Cancel`})]}),x!==null&&l(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:x}),t(`div`,{className:`shrink-0 space-y-2`,children:[l($a,{problems:ie,testId:`summary-problems`}),l(eo,{warnings:ae,testId:`summary-warnings`})]}),t(T,{value:F,onValueChange:e=>D(Ds(e)??w),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[l(ee,{className:`mb-3 shrink-0`,children:Ts.map(e=>l(E,{value:e.key,children:e.label},e.key))}),t(S,{className:`pr-1`,children:[t(A,{value:`rule`,className:`space-y-3`,children:[l(J,{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:t(`div`,{className:`flex items-end gap-3`,children:[t(`div`,{className:`min-w-0 flex-1`,children:[l(`label`,{className:K,children:`Name`}),l(b,{value:g.name,onChange:e=>O({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),l(`div`,{className:`pb-1.5`,children:l(ro,{label:`Enabled`,checked:g.enabled,onChange:e=>O({enabled:e}),testId:`summary-enabled`})})]})}),l(J,{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:l(to,{cameras:i,value:g.deviceIds,loading:a,onChange:e=>O({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})})]}),l(A,{value:`window`,className:`space-y-3`,children:t(J,{title:`When the window closes`,children:[t(`div`,{children:[l(`label`,{className:K,children:`Window`}),l(v,{value:g.windowKind,options:[{value:`motion`,label:`Motion — opened and closed by activity`},{value:`schedule`,label:`Schedule — fixed weekly windows`}],onChange:e=>O({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),g.windowKind===`motion`?t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Quiet period (seconds)`,value:g.quietSeconds,min:30,max:Fo,onChange:e=>O({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`}),l(Y,{label:`Longest window (seconds)`,value:g.maxWindowSeconds,min:60,max:Io,onChange:e=>O({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`})]}):t(`div`,{children:[l(`label`,{className:K,children:`Weekly windows`}),l(Lr,{value:g.schedule,onChange:e=>O({schedule:e})}),l(`p`,{className:q,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.`})]}),l(Y,{label:`Wait for open tracks (seconds)`,value:g.barrierSeconds,min:0,max:Lo,onChange:e=>O({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`})]})}),l(A,{value:`content`,className:`space-y-3`,children:t(J,{title:`What goes in`,hint:`Evaluated on tracks: one passage is one tile.`,children:[t(`div`,{children:[l(`label`,{className:K,children:`Classes`}),l(yn,{options:k,value:g.classes,onChange:e=>O({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),l(`p`,{className:q,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.`})]}),t(`div`,{children:[l(`label`,{className:K,children:`Excluded classes`}),l(yn,{options:k,value:g.classesExclude,onChange:e=>O({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),t(`div`,{children:[l(`label`,{className:K,children:`Zones`}),l(yn,{options:j,value:g.zones,onChange:e=>O({zones:e}),loading:M,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),l(`p`,{className:q,children:`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`})]}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Minimum importance`,value:g.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>O({minImportance:e}),hint:`The pipeline's own score, 0–1. Empty keeps everything.`,testId:`summary-min-importance`}),l(Y,{label:`Minimum stay (seconds)`,value:g.minDwellSeconds,min:0,max:Ro,emptyPlaceholder:`any`,onChange:e=>O({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]}),l(ro,{label:`Include parked objects`,checked:g.includeStationary,onChange:e=>O({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`})]})}),l(A,{value:`mosaic`,className:`space-y-3`,children:t(J,{title:`The mosaic`,children:[t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Tiles`,value:g.maxTiles,min:1,max:24,onChange:e=>O({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`}),t(`div`,{children:[l(`label`,{className:K,children:`When there are more tracks than tiles`}),l(v,{value:g.rank,options:Bo.map(e=>({value:e,label:Vo[e]})),onChange:e=>{let t=Fs(e.target.value);t!==void 0&&O({rank:t})},"data-testid":`summary-rank`}),l(`p`,{className:q,children:`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`})]})]}),t(`div`,{children:[l(`label`,{className:K,children:`Text on the mosaic`}),l(v,{value:g.mosaicCaptions,options:Ho.map(e=>({value:e,label:Wo[e]})),onChange:e=>{let t=Is(e.target.value);t!==void 0&&O({mosaicCaptions:t})},"data-testid":`summary-captions`}),l(`p`,{className:q,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.`})]}),t(`div`,{children:[l(`label`,{className:K,children:`Caption burned onto the mosaic`}),l(b,{value:g.captionText,disabled:!re,onChange:e=>O({captionText:e.target.value}),placeholder:`Leave empty for no caption`,"data-testid":`summary-caption`}),l(`p`,{className:q,children:re?`Across the top band. {{rule}}, {{from}} and {{to}} are filled in.`:`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`})]})]})}),l(A,{value:`ai`,className:`space-y-3`,children:t(J,{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:[l(ro,{label:`Have a model describe the window`,checked:g.aiEnabled,onChange:e=>O({aiEnabled:e}),hint:`Off by default. The mosaic and the counts are delivered either way.`,testId:`summary-ai-enabled`}),!g.aiEnabled&&l(`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.`}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[t(`div`,{children:[l(`label`,{className:K,children:`Vision profile`}),l(v,{value:g.aiProfileId,disabled:!g.aiEnabled,options:[{value:``,label:`The hub's default vision profile`},...te.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>O({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),l(`p`,{className:q,children:N.isError?`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`:te.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.`})]}),t(`div`,{children:[l(`label`,{className:K,children:`Answer in`}),l(v,{value:g.aiLanguage,disabled:!g.aiEnabled,options:[{value:``,label:`Don’t ask for a language`},...Go.map(e=>({value:e,label:Ps[e]}))],onChange:e=>O({aiLanguage:Ls(e.target.value)}),"data-testid":`summary-ai-language`}),l(`p`,{className:q,children:`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`})]})]}),t(`div`,{children:[l(`label`,{className:K,children:`Your question (optional)`}),l(`textarea`,{value:g.aiPrompt,rows:3,maxLength:Jo,disabled:!g.aiEnabled,onChange:e=>O({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`}),l(`p`,{className:q,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.`})]}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Frames the model may look at`,value:g.maxAiImages,min:1,max:8,disabled:!g.aiEnabled,onChange:e=>O({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`}),l(Y,{label:`Time limit (seconds)`,value:g.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!g.aiEnabled,onChange:e=>O({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`})]}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Frame size sent (pixels)`,value:g.aiMaxImagePx,min:64,max:qo,emptyPlaceholder:`448`,disabled:!g.aiEnabled,onChange:e=>O({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`}),t(`div`,{children:[l(`label`,{className:K,children:`If the model gives no answer`}),l(v,{value:g.aiOnFailure,disabled:!g.aiEnabled,options:Ko.map(e=>({value:e,label:Ns[e]})),onChange:e=>{let t=Rs(e.target.value);t!==void 0&&O({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),l(`p`,{className:q,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.`})]})]})]})}),l(A,{value:`delivery`,className:`space-y-3`,children:t(J,{title:`Delivery`,children:[l(no,{targets:o,value:g.targetIds,onChange:e=>O({targetIds:e})}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Priority`,value:g.priority,min:1,max:5,onChange:e=>O({priority:e??3}),testId:`summary-priority`}),l(ro,{label:`Deliver a window that matched nothing`,checked:g.deliverEmpty,onChange:e=>O({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`})]}),l(io,{title:g.templateTitle,body:g.templateBody,onTitleChange:e=>O({templateTitle:e}),onBodyChange:e=>O({templateBody:e}),variables:Ms,testIdPrefix:`summary-template`}),t(`p`,{className:q,children:[l(`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.`]})]})})]})]}),t(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[l(_,{size:`sm`,variant:`secondary`,type:`button`,onClick:m,children:`Cancel`}),t(_,{size:`sm`,type:`button`,disabled:!oe,onClick:()=>ne.mutate(),children:[ne.isPending&&l(R,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}e();var Bs=[`notificationSummaries`,`listSummaryRules`],Vs=[`deviceManager`,`listAll`,`forSummaries`],Hs=`One window, one picture: every camera’s best moments as a single mosaic.`;function Us(){let e=d(),[n,i]=s({mode:`closed`}),[a,o]=s(null),[u,f]=s(null),[p,h]=s(null),[g,v]=s(!1),y=r({queryKey:Bs,queryFn:async()=>{let t=ds(await e.trpcClient.addons.custom.mutate({addonId:Z,action:jo,input:{}}));return v(t===null),t}}),b=r({queryKey:Vs,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).filter(e=>e.type===L.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),staleTime:6e4}),x=r({queryKey:Xi,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),S=r({queryKey:Zi,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),w=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:Mo,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void y.refetch()}),T=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:No,input:{ruleId:t}}),onSuccess:()=>{o(null),y.refetch()}}),E=c({mutationFn:async t=>fs(await e.trpcClient.addons.custom.mutate({addonId:Z,action:Po,input:{ruleId:t,...js(Date.now())}})),onSuccess:e=>{f(null),h(e)}}),O=y.data??[],k=(x.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),A=new Map(k.map(e=>[e.id,e.name])),j=t(_,{size:`sm`,type:`button`,onClick:()=>i({mode:`form`,rule:null}),"data-testid":`summary-new`,children:[l(ze,{className:`h-3.5 w-3.5`}),`New summary`]});return y.isLoading?l(z,{icon:at,title:`Summaries`,subtitle:Hs,children:l(R,{className:`h-5 w-5 animate-spin`})}):y.isError||y.data===null?l(z,{icon:at,title:`Summaries`,subtitle:Hs,children:l(C,{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.`})}):t(z,{icon:at,title:`Summaries`,subtitle:Hs,actions:j,children:[T.isError&&l(C,{title:`Could not delete the rule`,message:String(T.error)}),E.isError&&l(C,{title:`The test run failed`,message:String(E.error)}),p!==null&&t(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[p.error===void 0?t(`span`,{children:[`Produced `,p.produced,` digest`,p.produced===1?``:`s`,` — `,p.tiles??0,` tile`,(p.tiles??0)===1?``:`s`,` from `,p.cameras??0,` camera`,(p.cameras??0)===1?``:`s`,`, `,p.matched??0,` track`,(p.matched??0)===1?``:`s`,` matched, `,p.enqueued??0,` `,`notification`,(p.enqueued??0)===1?``:`s`,` sent.`,(p.droppedStationary??0)>0&&t(`span`,{"data-testid":`summary-test-dropped-stationary`,children:[` `,p.droppedStationary,` parked object`,p.droppedStationary===1?``:`s`,` left out.`]})]}):t(`span`,{className:`text-warning`,children:[`Nothing was produced: `,p.error]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>h(null),children:`Dismiss`})]}),O.length===0?l(`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.`}):l(m,{children:l(D,{columns:Ws({nowMs:Date.now(),targetNameById:A,confirmDeleteId:a,deletePending:T.isPending,onToggle:(e,t)=>w.mutate({ruleId:e.id,enabled:t}),onEdit:e=>{Yo(e)&&i({mode:`form`,rule:e})},onTest:f,onAskDelete:o,onConfirmDelete:e=>T.mutate(e.id)}),rows:O,rowKey:e=>e.id,minWidthPx:860,bordered:!1,mobileMode:`scroll`,maxBodyHeight:M})}),n.mode===`form`&&l(zs,{rule:n.rule,cameras:b.data??[],camerasLoading:b.isLoading,targets:k,taxonomy:S.data?.taxonomy,onCancel:()=>i({mode:`closed`}),onSaved:()=>{i({mode:`closed`}),y.refetch()}}),l(ao,{open:u!==null,ruleName:u?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${u?.targets.length??0} target${(u?.targets.length??0)===1?``:`s`}`,pending:E.isPending,onCancel:()=>f(null),onConfirm:()=>{u!==null&&E.mutate(u.id)}})]})}function Ws(e){return[{key:`name`,header:`Digest`,render:e=>t(`span`,{className:`flex flex-wrap items-center gap-2`,children:[l(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&l(g,{variant:`warning`,children:`disabled`}),!Yo(e)&&l(g,{variant:`warning`,children:`read-only`}),e.ai?.enabled===!0&&l(g,{variant:`info`,children:`AI`}),e.ai!==void 0&&!e.ai.enabled&&l(g,{variant:`default`,children:`AI off`})]})},{key:`cameras`,header:`Cameras`,align:`center`,nowrap:!0,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:`Window`,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:Os(e.window)})},{key:`filters`,header:`Keeps`,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:As(e.filters)})},{key:`mosaic`,header:`Mosaic`,nowrap:!0,render:e=>t(`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 l(`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=>l(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:ks(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>l(O,{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:n=>t(`span`,{className:`flex items-center justify-end gap-1`,children:[l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.readOnly,onClick:()=>e.onTest(n),title:`Produce this digest now and DELIVER it`,"aria-label":`test ${n.name}`,"data-testid":`summary-test-${n.id}`,children:l(Ie,{className:`h-3.5 w-3.5`})}),l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Yo(n),onClick:()=>e.onEdit(n),"aria-label":`edit ${n.name}`,"data-testid":`summary-edit-${n.id}`,children:l(Re,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===n.id?t(`span`,{className:`flex items-center gap-1`,children:[l(_,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(n),"data-testid":`summary-delete-confirm-${n.id}`,children:`Delete`}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.readOnly,onClick:()=>e.onAskDelete(n.id),"aria-label":`delete ${n.name}`,"data-testid":`summary-delete-${n.id}`,children:l(et,{className:`h-3.5 w-3.5`})})]})}]}var Gs=e=>typeof e==`string`&&e.length>0;function Ks(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 qs(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Js(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Gs(i)&&n.push({mediaType:r,url:i})}return n}function Ys(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Gs(r.label),i=Gs(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 Xs(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Js(e,t.attachmentUrls),i=Ys(e,t.actions),a=e.ttl&&Gs(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:qs(e,t.format),priority:Zs(t.priority),...Gs(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Gs(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Gs(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Gs(t.tag)?{tag:t.tag}:{}}}function Zs(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function Qs(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 $s(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var ec={image:`/addon/notifiers/samples/image`,video:`/addon/notifiers/samples/video`,gif:`/addon/notifiers/samples/gif`,audio:`/addon/notifiers/samples/audio`,icon:`/addon/notifiers/samples/icon`};function tc(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function nc(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])tc(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function rc(e,t,n){let r=$s(e);return tc(e,t)?{...r,body:n,attachmentUrls:{[t]:ec[t]}}:{...r,body:n}}function ic(e,t){let n=$s(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return rc(e,`image`,`Test notification with an image.`);case`gif`:return rc(e,`gif`,`Test notification with an animation.`);case`video`:return rc(e,`video`,`Test notification with a video.`);case`audio`:return rc(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=Qs(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}e();var ac={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},oc=`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`,$=`block text-[11px] font-medium text-foreground mb-1`;function sc({target:e,kind:r,open:i,onClose:a}){let o=d(),u=n(()=>Ks(r.caps),[r.caps]),m=n(()=>nc(r.caps),[r.caps]),[h,v]=s(()=>$s(r.caps)),[b,x]=s(null),C=n(()=>Xs(r.caps,h),[r.caps,h]),w=h.body.length,T=w>u.bodyMaxLen,E=e=>v(t=>({...t,...e})),D=c({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:Xs(r.caps,h)}),onMutate:()=>x(null),onSuccess:e=>x(e),onError:e=>x({success:!1,error:e instanceof Error?e.message:`Test failed`})}),O=e=>{v(ic(r.caps,e)),x(null)},A=(e,t,n)=>{let r=h.actions.length>0?[...h.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},E({actions:r})};return l(P,{open:i,onOpenChange:e=>!e&&a(),children:t(p,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[l(k,{children:t(f,{children:[`Test "`,e.name,`" (`,r.label,`)`]})}),t(S,{className:`space-y-4 pr-1`,children:[l(`div`,{className:`flex flex-wrap gap-1.5`,children:m.map(e=>l(_,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>O(e),children:ac[e]},e))}),t(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[u.levels.length>0&&t(`div`,{children:[l(`label`,{className:$,children:`Level`}),t(`select`,{className:oc,value:h.level,onChange:e=>E({level:e.target.value}),children:[l(`option`,{value:``,children:`— derive from priority —`}),u.levels.map(e=>t(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=u.levels.find(e=>e.id===h.level);return e?t(`div`,{className:`mt-1 space-y-1`,children:[e.description&&l(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),t(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&l(g,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&l(g,{variant:`info`,children:`silent`}),e.flags?.noPush&&l(g,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&t(`p`,{className:`text-[10px] text-warning`,children:[`Requires target config: `,e.requires.join(`, `)]})]}):null})()]}),t(`div`,{children:[t(`label`,{className:$,children:[`Priority (ordinal): `,h.priority]}),l(`input`,{type:`range`,min:1,max:5,step:1,value:h.priority,onChange:e=>E({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),u.formats.length>0&&t(`div`,{children:[l(`label`,{className:$,children:`Format`}),l(`div`,{className:`flex flex-wrap gap-2`,children:u.formats.map(e=>t(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[l(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:h.format===e,onChange:()=>E({format:e})}),e]},e))})]}),t(`div`,{children:[l(`label`,{className:$,children:`Title`}),l(`input`,{className:oc,value:h.title,onChange:e=>E({title:e.target.value})})]}),t(`div`,{children:[t(`label`,{className:$,children:[`Body`,` `,t(`span`,{className:T?`text-danger`:`text-foreground-subtle`,children:[`(`,w,`/`,u.bodyMaxLen,T?` — overflow`:``,`)`]})]}),l(`textarea`,{className:`${oc} min-h-[80px] resize-y`,value:h.body,onChange:e=>E({body:e.target.value})})]}),u.attachmentSlots.length>0&&t(`div`,{children:[t(`label`,{className:$,children:[`Attachments`,` `,t(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,u.attachmentMode,`, max `,u.attachmentMax,u.attachmentMaxBytes?`, ≤${Math.round(u.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),l(`div`,{className:`space-y-1.5`,children:u.attachmentSlots.map(e=>t(`div`,{className:`flex items-center gap-2`,children:[l(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),l(`input`,{className:oc,placeholder:`${e} URL`,value:h.attachmentUrls[e]??``,onChange:t=>E({attachmentUrls:{...h.attachmentUrls,[e]:t.target.value}})})]},e))})]}),u.showActions&&t(`div`,{children:[t(`label`,{className:$,children:[`Actions (up to `,u.maxActions,`)`]}),l(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(u.maxActions,3)},(e,n)=>t(`div`,{className:`flex items-center gap-2`,children:[l(`input`,{className:oc,placeholder:`label`,value:h.actions[n]?.label??``,onChange:e=>A(n,`label`,e.target.value)}),l(`input`,{className:oc,placeholder:`url`,value:h.actions[n]?.url??``,onChange:e=>A(n,`url`,e.target.value)})]},n))})]}),t(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[u.showClickUrl&&t(`div`,{children:[l(`label`,{className:$,children:`Click URL`}),l(`input`,{className:oc,value:h.clickUrl,onChange:e=>E({clickUrl:e.target.value})})]}),u.showSound&&t(`div`,{children:[l(`label`,{className:$,children:`Sound`}),l(`input`,{className:oc,value:h.sound,onChange:e=>E({sound:e.target.value})})]}),u.showTtl&&t(`div`,{children:[l(`label`,{className:$,children:`TTL (seconds)`}),l(`input`,{className:oc,type:`number`,value:h.ttl,onChange:e=>E({ttl:e.target.value})})]}),u.showTag&&t(`div`,{children:[l(`label`,{className:$,children:`Tag`}),l(`input`,{className:oc,value:h.tag,onChange:e=>E({tag:e.target.value})})]})]}),b&&l(cc,{result:b}),t(`details`,{className:`text-[10px]`,children:[l(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),l(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(C,null,2)})]})]}),t(y,{children:[l(_,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),t(_,{size:`sm`,type:`button`,disabled:D.isPending||h.body.length===0,onClick:()=>D.mutate(),children:[D.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Le,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function cc({result:e}){let n=e.renderedAs;return t(`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:[t(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?l(Pe,{className:`h-3.5 w-3.5 text-success`}):l(Ge,{className:`h-3.5 w-3.5 text-danger`}),l(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&l(`p`,{className:`mt-1 text-danger`,children:e.error}),n&&t(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[l(`dt`,{children:`Resolved level`}),l(`dd`,{className:`text-foreground`,children:n.level}),l(`dt`,{children:`Format sent`}),l(`dd`,{className:`text-foreground`,children:n.format}),l(`dt`,{children:`Attachments sent`}),l(`dd`,{className:`text-foreground`,children:n.attachmentsSent}),l(`dt`,{children:`Actions sent`}),l(`dd`,{className:`text-foreground`,children:n.actionsSent}),l(`dt`,{children:`Truncated`}),l(`dd`,{className:`text-foreground`,children:n.truncated?`yes`:`no`}),l(`dt`,{children:`Dropped`}),l(`dd`,{className:`text-foreground`,children:n.dropped.length>0?n.dropped.join(`, `):`—`})]})]})}function lc(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 uc(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 dc(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 fc(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))r[t]=n.has(t)?``:i;return r}e();var pc=[`notificationOutput`,`listTargets`],mc=[`notificationOutput`,`listTargetKinds`],hc=[`userManagement`,`listUsers`],gc=`ownerUserId`;function _c(e){let t=e.config[gc];return typeof t==`string`&&t.length>0?t:null}function vc(e){return[{key:`name`,header:`Target`,render:n=>{let r=e.kindByKey.get(n.kind);return t(`span`,{className:`flex items-center gap-2`,children:[l(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:r?.label??n.kind,children:l(yc,{kind:r,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),l(`span`,{className:`truncate text-sm font-medium text-foreground`,children:n.name}),!n.enabled&&l(g,{variant:`warning`,children:`disabled`})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>l(`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=_c(t);return n===null?l(g,{variant:`default`,children:`system`}):l(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>l(O,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>{let r=e.kindByKey.get(n.kind);return t(`span`,{className:`flex items-center justify-end gap-1`,children:[l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(n),title:`Test`,children:l(Le,{className:`h-3.5 w-3.5`})}),l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onEdit(n,r),title:`Edit`,children:l(Re,{className:`h-3.5 w-3.5`})}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(n),title:`Delete`,children:l(et,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function yc({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?l(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):l(`span`,{className:n,children:e?.icon??`🔔`})}function bc(){let e=d(),[i,a]=s({mode:`closed`}),[o,u]=s(null),f=r({queryKey:pc,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),p=r({queryKey:mc,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),h=n(()=>p.data??[],[p.data]),g=n(()=>{let e=new Map;for(let t of h)e.set(t.kind,t);return e},[h]),v=r({queryKey:hc,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),y=n(()=>{let e=new Map;for(let t of v.data??[])e.set(t.id,t.username);return e},[v.data]),b=c({mutationFn:t=>e.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:t.target.addonId,targetId:t.target.id,enabled:t.enabled}),onSuccess:()=>void f.refetch()}),x=c({mutationFn:t=>e.trpcClient.notificationOutput.deleteTarget.mutate({addonId:t.addonId,targetId:t.id}),onSuccess:()=>void f.refetch()}),S=o?g.get(o.kind):void 0;return t(z,{icon:Ye,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:t(_,{size:`sm`,type:`button`,onClick:()=>a({mode:`pick-kind`}),children:[l(ze,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[f.isLoading&&l(`div`,{className:`flex items-center justify-center py-16`,children:l(R,{className:`h-6 w-6 animate-spin text-primary`})}),f.isError&&!f.isLoading&&l(C,{title:`Failed to load targets`,message:f.error instanceof Error?f.error.message:`Unknown error`,onRetry:()=>void f.refetch()}),!f.isLoading&&!f.isError&&(f.data??[]).length===0&&l(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification targets yet. Click "Add target" to configure one.`}),(f.data??[]).length>0&&l(m,{children:l(D,{columns:vc({kindByKey:g,userNameById:y,onToggle:(e,t)=>b.mutate({target:e,enabled:t}),onTest:u,onEdit:(e,t)=>a({mode:`form`,kind:t,target:e}),onDelete:e=>x.mutate(e)}),rows:f.data??[],rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),i.mode===`pick-kind`&&l(xc,{kinds:h,onCancel:()=>a({mode:`closed`}),onPick:e=>a({mode:`form`,kind:e,target:null})}),i.mode===`form`&&l(Sc,{kind:i.kind,target:i.target,users:v.data??[],onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),f.refetch()}}),o&&S&&l(sc,{target:o,kind:S,open:!0,onClose:()=>u(null)})]})}function xc({kinds:e,onPick:r,onCancel:i}){let a=n(()=>lc(e),[e]);return t(m,{className:`p-4 space-y-4`,children:[t(`div`,{className:`flex items-center justify-between`,children:[l(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),a.length===0&&l(`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=>t(`div`,{children:[l(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),l(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(n=>t(`button`,{type:`button`,onClick:()=>r(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[l(yc,{kind:n,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),l(`span`,{className:`font-medium text-foreground`,children:n.label}),n.supportsDiscovery&&l(g,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})}function Sc({kind:e,target:r,users:i,onSaved:a,onCancel:o}){let u=d(),f=n(()=>uc(e.configSchema),[e.configSchema]),p=n(()=>r?.config??{},[r]),[g,y]=s(r?.name??e.label),[b,x]=s(()=>r?fc(r.config,f):{}),[S,C]=s(null),[w,T]=s(null),[E,D]=s(r?_c(r)??``:``),O=c({mutationFn:()=>u.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:b}),onSuccess:e=>C(e),onError:e=>T(e instanceof Error?e.message:`Discovery failed`)}),k=c({mutationFn:()=>{let{[gc]:t,...n}=dc(b,p,f),i=E===``?n:{...n,[gc]:E},a={id:r?.id??`${e.kind}-${Date.now()}`,name:g,kind:e.kind,addonId:e.addonId,enabled:r?.enabled??!0,config:i};return u.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:a})},onSuccess:a,onError:e=>T(e instanceof Error?e.message:`Save failed`)}),A=e=>{y(e.suggestedName),x(t=>({...t,...e.config})),C(null)};return t(m,{className:`p-4 space-y-4`,children:[t(`div`,{className:`flex items-center justify-between`,children:[t(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[l(yc,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),r?`Edit ${r.name}`:`Add ${e.label} target`]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,children:`Cancel`})]}),w&&l(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:w}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),l(`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:g,onChange:e=>y(e.target.value)})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),l(v,{value:E,options:[{value:``,label:`System (shared, admin-managed)`},...i.map(e=>({value:e.id,label:e.username}))],onChange:e=>D(e.target.value)}),l(`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&&t(`div`,{className:`space-y-2`,children:[t(_,{size:`sm`,variant:`outline`,type:`button`,disabled:O.isPending,onClick:()=>{T(null),O.mutate()},children:[O.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Ue,{className:`h-3.5 w-3.5`}),`Discover`]}),S&&S.length===0&&l(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),S&&S.length>0&&l(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:S.map((e,n)=>t(`button`,{type:`button`,onClick:()=>A(e),className:`flex w-full items-center justify-between px-3 py-1.5 text-xs hover:bg-surface-hover`,children:[l(`span`,{className:`text-foreground`,children:e.suggestedName}),l(`span`,{className:`text-[10px] text-primary`,children:`use`})]},`${e.suggestedName}-${n}`))})]}),f.length>0&&r&&l(`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.`}),l(h,{schema:e.configSchema,values:b,onChange:x}),t(`div`,{className:`flex justify-end gap-2`,children:[l(_,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:`Cancel`}),t(_,{size:`sm`,type:`button`,disabled:k.isPending||g.trim().length===0,onClick:()=>{T(null),k.mutate()},children:[k.isPending&&l(R,{className:`h-3.5 w-3.5 animate-spin`}),r?`Save changes`:`Create target`]})]})]})}e();var Cc=`notificationTexts`,wc=`Every sentence the Notification Center can print — and your wording for it.`;function Tc({entry:e,value:n,busy:r,onChange:i,onReset:a}){let o=Ao(e),s=e.override!==null;return t(`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:[t(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[l(`code`,{className:`text-xs font-medium`,children:e.key}),s?l(g,{variant:`info`,children:`customised`}):null,e.source===`fallback`?l(g,{variant:`warning`,children:`English fallback`}):null]}),t(`div`,{className:`flex items-start gap-2`,children:[l(b,{value:n,disabled:r,onChange:e=>i(e.target.value),className:`flex-1 font-mono text-xs`,"data-testid":`text-input-${e.key}`}),l(_,{variant:`ghost`,size:`sm`,disabled:r||!s&&n===e.shipped,onClick:a,title:`Reset to the shipped wording`,"data-testid":`text-reset-${e.key}`,children:l(He,{className:`h-3.5 w-3.5`})})]}),t(`p`,{className:`text-xs text-foreground-subtle`,children:[l(`span`,{className:`font-medium`,children:`Shipped:`}),` `,l(`span`,{className:`font-mono`,children:e.shipped})]}),l(`p`,{className:`text-xs text-foreground-subtle`,children:ko(e)}),o===null?null:l(`p`,{className:`text-xs text-warning`,children:o})]})}function Ec(){let e=d(),i=o(),[a,u]=s(null),[f,p]=s(``),[h,g]=s(new Map),[y,x]=s(!1),S=r({queryKey:[Cc,a??`hub`],queryFn:async()=>{let t=wo(await e.trpcClient.addons.custom.mutate({addonId:Z,action:ho,input:a===null?{}:{language:a}}));return x(t===null),t}}),w=()=>{g(new Map),i.invalidateQueries({queryKey:[Cc]})},T=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:go,input:{language:t}}),onSuccess:w}),E=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:_o,input:t}),onSuccess:w}),D=S.data??null,O=n(()=>D===null?[]:Oo(D.entries,f),[D,f]);if(S.isLoading)return l(z,{icon:ot,title:`Texts`,subtitle:wc,children:l(R,{className:`h-5 w-5 animate-spin`})});if(S.isError||D===null)return l(z,{icon:ot,title:`Texts`,subtitle:wc,children:l(C,{title:`The notification text catalog is not available on this hub`,message:y?`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 k=D.language,A=T.isPending||E.isPending,j=Eo(D.entries,h),M=Do(D.entries,h),N=D.entries.filter(e=>e.override!==null).length,ee=D.languages.map(e=>({value:e,label:vo[e]})),P=(e,t)=>g(n=>new Map(n).set(e,t)),te=e=>P(e.key,e.shipped);return l(z,{icon:ot,title:`Texts`,subtitle:wc,children:t(`div`,{className:`flex flex-col gap-4`,children:[T.isError?l(C,{title:`Could not change the language`,message:String(T.error)}):null,E.isError?l(C,{title:`Could not save`,message:String(E.error)}):null,t(m,{className:`p-4`,children:[t(`div`,{className:`flex flex-wrap items-end gap-6`,children:[t(`div`,{className:`flex flex-col gap-1`,children:[l(`label`,{className:`text-sm font-medium`,children:`Hub language`}),l(`div`,{className:`w-44`,children:l(v,{value:D.activeLanguage,disabled:A,options:ee,onChange:e=>{let t=e.target.value;yo(t)&&T.mutate(t)},"data-testid":`texts-hub-language`})}),l(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),t(`div`,{className:`flex flex-col gap-1`,children:[l(`label`,{className:`text-sm font-medium`,children:`Editing`}),l(`div`,{className:`w-44`,children:l(v,{value:k,disabled:A,options:ee,onChange:e=>{let t=e.target.value;yo(t)&&(g(new Map),u(t))},"data-testid":`texts-editing-language`})}),l(`p`,{className:`text-xs text-foreground-subtle`,children:k===D.activeLanguage?`${N} of ${D.entries.length} texts customised.`:`This hub does not speak this language — these words are not in use yet.`})]})]}),l(`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.`})]}),t(`div`,{className:`flex flex-wrap items-center gap-3`,children:[t(`div`,{className:`relative min-w-[12rem] flex-1`,children:[l(Ue,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),l(b,{value:f,placeholder:`Search a key or a sentence…`,onChange:e=>p(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),t(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[O.length,` of `,D.entries.length]}),t(_,{className:`ml-auto`,disabled:A||M===0,onClick:()=>E.mutate({language:k,overrides:j}),"data-testid":`texts-save`,children:[A?l(R,{className:`h-3.5 w-3.5 animate-spin`}):null,M===0?`Save`:`Save ${M}`]})]}),l(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:O.length===0?l(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):O.map(e=>l(Tc,{entry:e,value:To(e,h),busy:A,onChange:t=>P(e.key,t),onReset:()=>te(e)},e.key))})]})})}var Dc=`nc.listTimelapseRules`,Oc=`nc.upsertTimelapseRule`,kc=`nc.deleteTimelapseRule`,Ac=`nc.testTimelapseRule`,jc=3600,Mc=3600,Nc=30,Pc=1,Fc=[`image`,`gif`],Ic={image:`Still frame`,gif:`Short animation (GIF)`},Lc=De({rules:ke(Se.extend({readOnly:je().optional()}))});function Rc(e){let t=Lc.safeParse(e);return t.success?t.data.rules:null}function zc(e){return e.readOnly!==!0}var Bc=De({produced:Oe(),exportId:Ae().optional(),coveragePercent:Oe().optional(),enqueued:Oe().optional(),windowStartMs:Oe().optional(),windowEndMs:Oe().optional(),error:Ae().optional()});function Vc(e){let t=Bc.safeParse(e);return t.success?t.data:null}function Hc(){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 Uc(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 Wc={windows:[{days:[1],startMinute:0,endMinute:60}]};function Gc(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 Kc(e){let t=Gc(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??Wc,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:mo(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 qc(e,t){let n=Kc(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),X(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),X(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??Jc(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),X(n.targets,t.targets)||(r.targets=n.targets),X(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),X(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function Jc(e){return Math.max(Pc,e/Nc)}function Yc(e,t,n){return t<=0||n<=0?0:e/t/n}function Xc(e,t){return e*t*ge}function Zc(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 ${jc}.`),(!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 ${ge}s and ${Mc}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 Qc(e){return Zc(e).length===0}function $c(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=Xc(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 el(e){return lo(e)}function tl(e,t){return uo(e,t,`Never run`)}function nl(e){return e.denseCadenceSec===void 0?{seconds:Jc(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}e();var rl=[`camera`,`rule`,`from`,`to`,`detections`,`detectionSummary`,`count_person`],il=7;function al(e){return Fc.find(t=>t===e)}function ol({rule:e,cameras:n,camerasLoading:r,targets:a,onSaved:o,onCancel:u}){let f=d(),[m,h]=s(()=>e===null?Hc():Uc(e)),[g,y]=s(null),x=e=>h(t=>({...t,...e})),C=c({mutationFn:async()=>{let t=e===null?{rule:Kc(m)}:{ruleId:e.id,patch:qc(m,e)};await f.trpcClient.addons.custom.mutate({addonId:Z,action:Oc,input:t})},onSuccess:o,onError:e=>y(e instanceof Error?e.message:`Save failed`)}),w=Zc(m),T=$c(m),E=nl(m),D=Yc(il,E.seconds,m.framerate),O=Qc(m)&&!C.isPending;return l(P,{open:!0,onOpenChange:e=>!e&&u(),children:t(p,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[t(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[t(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[l(Je,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),l(`span`,{className:`truncate`,children:e===null?`New timelapse`:`Edit ${e.name}`})]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:u,children:`Cancel`})]}),g!==null&&l(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:g}),t(S,{className:`space-y-3 pr-1`,children:[l($a,{problems:w,testId:`timelapse-problems`}),l(eo,{warnings:T,testId:`timelapse-warnings`}),l(J,{title:`What it is`,hint:`One video per camera, assembled from that camera's RECORDED footage when the window closes.`,children:t(`div`,{className:`flex items-end gap-3`,children:[t(`div`,{className:`min-w-0 flex-1`,children:[l(`label`,{className:K,children:`Name`}),l(b,{value:m.name,onChange:e=>x({name:e.target.value}),placeholder:`e.g. Timelapse ingresso`,"data-testid":`timelapse-name`})]}),l(`div`,{className:`pb-1.5`,children:l(ro,{label:`Enabled`,checked:m.enabled,onChange:e=>x({enabled:e}),testId:`timelapse-enabled`})})]})}),l(J,{title:`Cameras`,children:l(to,{cameras:n,value:m.deviceIds,loading:r,onChange:e=>x({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.`})}),l(J,{title:`When`,children:t(`div`,{children:[l(`label`,{className:K,children:`Weekly windows`}),l(Lr,{value:m.schedule,onChange:e=>x({schedule:e})}),l(`p`,{className:q,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.`})]})}),t(J,{title:`Sampling`,hint:`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`,children:[t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Base cadence (seconds)`,value:m.cadenceSec,min:2,max:jc,onChange:e=>x({cadenceSec:e??0}),hint:`One frame every N seconds across the quiet parts of the window.`,testId:`timelapse-cadence`}),l(Y,{label:`Output frame rate (fps)`,value:m.framerate,min:1,max:60,onChange:e=>x({framerate:e??0}),hint:`How fast the assembled video plays.`,testId:`timelapse-framerate`})]}),t(`div`,{children:[l(`label`,{className:K,children:`Dense cadence, near the detections`}),t(`div`,{className:`flex items-center gap-2`,children:[l(v,{value:m.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:`Automatic (${E.seconds}s)`},{value:`explicit`,label:`Set it myself`}],onChange:e=>x({denseCadenceSec:e.target.value===`auto`?void 0:nl(m).seconds}),"data-testid":`timelapse-dense-mode`}),m.denseCadenceSec!==void 0&&l(b,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(m.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&x({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),t(`p`,{className:q,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,E.seconds,`s and `,m.framerate,` fps a`,` `,il,`-second passage lasts `,D.toFixed(2),`s on screen; halving the cadence doubles that, and the quiet parts of the night do not change length.`,E.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 (${nl({...m,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),l(Y,{label:`Minimum seconds of video per detection (optional)`,value:m.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>x({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`})]}),t(J,{title:`The notification`,children:[l(no,{targets:a,value:m.targetIds,onChange:e=>x({targetIds:e})}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[t(`div`,{children:[l(`label`,{className:K,children:`Preview`}),l(v,{value:m.previewMode,options:Fc.map(e=>({value:e,label:Ic[e]})),onChange:e=>{let t=al(e.target.value);t!==void 0&&x({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),l(Y,{label:`Priority`,value:m.priority,min:1,max:5,onChange:e=>x({priority:e??3}),testId:`timelapse-priority`})]}),t(`div`,{children:[l(`label`,{className:K,children:`Caption on the preview frame`}),l(b,{value:m.previewTextSet?m.previewText:``,placeholder:`${I} (shipped default)`,onChange:e=>x({previewText:e.target.value,previewTextSet:!0}),"data-testid":`timelapse-preview-text`}),t(`p`,{className:q,children:[m.previewTextSet&&m.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${I}).`,m.previewTextSet&&t(i,{children:[` `,l(`button`,{type:`button`,className:`underline`,onClick:()=>x({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),l(io,{title:m.templateTitle,body:m.templateBody,onTitleChange:e=>x({templateTitle:e}),onBodyChange:e=>x({templateBody:e}),variables:rl,testIdPrefix:`timelapse-template`}),t(`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`,` `,l(`code`,{children:`{{detectionSummary}}`}),`.`]})]})]}),t(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[l(_,{size:`sm`,variant:`secondary`,type:`button`,onClick:u,children:`Cancel`}),t(_,{size:`sm`,type:`button`,disabled:!O,onClick:()=>C.mutate(),children:[C.isPending&&l(R,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}e();var sl=[`notificationTimelapses`,`listTimelapseRules`],cl=[`deviceManager`,`listAll`,`forTimelapses`],ll=`A night of recorded footage, assembled into one short video per camera.`;function ul(){let e=d(),[n,i]=s({mode:`closed`}),[a,o]=s(null),[u,f]=s(null),[p,h]=s(null),[g,y]=s(!1),b=r({queryKey:sl,queryFn:async()=>{let t=Rc(await e.trpcClient.addons.custom.mutate({addonId:Z,action:Dc,input:{}}));return y(t===null),t}}),x=r({queryKey:cl,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).filter(e=>e.type===L.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),staleTime:6e4}),S=r({queryKey:Xi,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),w=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:Oc,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void b.refetch()}),T=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:kc,input:{ruleId:t}}),onSuccess:()=>{o(null),b.refetch()}}),E=c({mutationFn:async t=>Vc(await e.trpcClient.addons.custom.mutate({addonId:Z,action:Ac,input:t})),onSuccess:e=>{f(null),h(e)}}),O=b.data??[],k=x.data??[],A=new Map(k.map(e=>[e.id,e.name])),j=(S.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),N=new Map(j.map(e=>[e.id,e.name]));return b.isLoading?l(z,{icon:Je,title:`Timelapses`,subtitle:ll,children:l(R,{className:`h-5 w-5 animate-spin`})}):b.isError||b.data===null?l(z,{icon:Je,title:`Timelapses`,subtitle:ll,children:l(C,{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.`})}):t(z,{icon:Je,title:`Timelapses`,subtitle:ll,actions:t(_,{size:`sm`,type:`button`,onClick:()=>i({mode:`form`,rule:null}),"data-testid":`timelapse-new`,children:[l(ze,{className:`h-3.5 w-3.5`}),`New timelapse`]}),children:[T.isError&&l(C,{title:`Could not delete the rule`,message:String(T.error)}),E.isError&&l(C,{title:`The test run failed`,message:String(E.error)}),p!==null&&t(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[p.error===void 0?t(`span`,{children:[`Produced `,p.produced,` video`,p.produced===1?``:`s`,p.coveragePercent===void 0?``:` — ${Math.round(p.coveragePercent)}% of the window had footage`,`, `,p.enqueued??0,` notification`,(p.enqueued??0)===1?``:`s`,` sent.`]}):t(`span`,{className:`text-warning`,children:[`Nothing was produced: `,p.error]}),l(_,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>h(null),children:`Dismiss`})]}),O.length===0?l(`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.`}):l(m,{children:l(D,{columns:dl({nowMs:Date.now(),cameraNameById:A,targetNameById:N,confirmDeleteId:a,deletePending:T.isPending,onToggle:(e,t)=>w.mutate({ruleId:e.id,enabled:t}),onEdit:e=>i({mode:`form`,rule:e}),onTest:e=>f({rule:e,deviceId:e.deviceIds[0]??null}),onAskDelete:o,onConfirmDelete:e=>T.mutate(e.id)}),rows:O,rowKey:e=>e.id,minWidthPx:900,bordered:!1,mobileMode:`scroll`,maxBodyHeight:M})}),n.mode===`form`&&l(ol,{rule:n.rule,cameras:k,camerasLoading:x.isLoading,targets:j,onCancel:()=>i({mode:`closed`}),onSaved:()=>{i({mode:`closed`}),b.refetch()}}),l(ao,{open:u!==null,ruleName:u?.rule.name??``,windowDescription:`its last closed window`,targetDescription:`${u?.rule.targets.length??0} target${(u?.rule.targets.length??0)===1?``:`s`}`,pending:E.isPending,confirmDisabled:u?.deviceId===null,extra:u===null?null:t(`div`,{children:[l(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Which camera`}),l(v,{value:u.deviceId===null?``:String(u.deviceId),options:u.rule.deviceIds.map(e=>({value:String(e),label:A.get(e)??`#${e}`})),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&f({rule:u.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>f(null),onConfirm:()=>{u!==null&&u.deviceId!==null&&E.mutate({ruleId:u.rule.id,deviceId:u.deviceId})}})]})}function dl(e){return[{key:`name`,header:`Timelapse`,render:e=>t(`span`,{className:`flex flex-wrap items-center gap-2`,children:[l(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&l(g,{variant:`warning`,children:`disabled`}),!zc(e)&&l(g,{variant:`warning`,children:`read-only`})]})},{key:`cameras`,header:`Cameras`,render:t=>l(`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=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:el(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let n=nl(Uc(e));return t(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.cadenceSec,`s · `,e.framerate,`fps · dense `,n.seconds,`s`,n.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 l(`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=>l(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:tl(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>l(O,{checked:t.enabled,disabled:!zc(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>t(`span`,{className:`flex items-center justify-end gap-1`,children:[l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:!zc(n),onClick:()=>e.onTest(n),title:`Render this rule's last closed window now and DELIVER it`,"aria-label":`test ${n.name}`,"data-testid":`timelapse-test-${n.id}`,children:l(Ie,{className:`h-3.5 w-3.5`})}),l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:!zc(n),onClick:()=>e.onEdit(n),"aria-label":`edit ${n.name}`,"data-testid":`timelapse-edit-${n.id}`,children:l(Re,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===n.id?t(`span`,{className:`flex items-center gap-1`,children:[l(_,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(n),"data-testid":`timelapse-delete-confirm-${n.id}`,children:`Delete`}),l(_,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):l(_,{size:`sm`,variant:`ghost`,type:`button`,disabled:!zc(n),onClick:()=>e.onAskDelete(n.id),"aria-label":`delete ${n.name}`,"data-testid":`timelapse-delete-${n.id}`,children:l(et,{className:`h-3.5 w-3.5`})})]})}]}var fl=`simulate`;function pl(){let[e,t]=Xe();return l(`div`,{className:`flex flex-col p-4`,children:l(nt,{tabs:[{id:`targets`,label:`Targets`,icon:Ye,content:l(bc,{})},{id:`rules`,label:`Rules`,icon:Ne,content:l(na,{onSimulateRule:n=>{Oa(Ea(n));let r=new URLSearchParams(e);r.set(`tab`,fl),t(r,{replace:!0})}})},{id:fl,label:`Simulate`,icon:Ie,content:l(Qa,{})},{id:`history`,label:`History`,icon:it,content:l(kt,{})},{id:`alarm`,label:`Alarm`,icon:Ze,content:l(St,{})},{id:`summaries`,label:`Summaries`,icon:at,content:l(Us,{})},{id:`timelapses`,label:`Timelapses`,icon:Je,content:l(ul,{})},{id:`texts`,label:`Texts`,icon:ot,content:l(Ec,{})}]})})}export{pl as NotificationsPage,pl as default};