@camstack/addon-admin-ui 1.2.81 → 1.2.82

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 (100) hide show
  1. package/dist/assets/{AddLocationWizard-WDALxpq-.js → AddLocationWizard-BwgLlZv7.js} +1 -1
  2. package/dist/assets/{AddonCollectionPage-D86qUT-8.js → AddonCollectionPage-Cj4wS8-x.js} +1 -1
  3. package/dist/assets/{Addons-C7jR5jKB.js → Addons-Bez0j4jh.js} +1 -1
  4. package/dist/assets/{AdminTabs-D6yDsobg.js → AdminTabs-BsOfmLas.js} +1 -1
  5. package/dist/assets/AiProfiles-CCqpaNjG.js +3 -0
  6. package/dist/assets/{BrokerForm-DnKqFWQy.js → BrokerForm-Drb3n-di.js} +1 -1
  7. package/dist/assets/{Build-Ipz6h2Qx.js → Build-BSu-hlCH.js} +5 -5
  8. package/dist/assets/{Capabilities-wOV3gO99.js → Capabilities-B9tN-DdS.js} +1 -1
  9. package/dist/assets/{CapabilityBadges-CByvC3eB.js → CapabilityBadges-BNXFPTSR.js} +1 -1
  10. package/dist/assets/{Cluster-DDXbnzQA.js → Cluster-LnvP_-DT.js} +1 -1
  11. package/dist/assets/{Data-Btzeyfj7.js → Data-DQoZzIZB.js} +1 -1
  12. package/dist/assets/{DetectionIntelligence-Dt4la9Ns.js → DetectionIntelligence-CFoMsLZW.js} +1 -1
  13. package/dist/assets/{DeviceAggregateSection-iY2G54zN.js → DeviceAggregateSection-D7sNSnRE.js} +1 -1
  14. package/dist/assets/{DeviceDetail-CVuY2t9Q.js → DeviceDetail-COpbvbHy.js} +2 -2
  15. package/dist/assets/{Devices-DornCZOc.js → Devices-BXT6J0za.js} +1 -1
  16. package/dist/assets/{EmbedPlayerPage-DLdvRzTy.js → EmbedPlayerPage-DQFmWgyi.js} +1 -1
  17. package/dist/assets/{Events-CEUNSnDV.js → Events-Cepqohr3.js} +1 -1
  18. package/dist/assets/{FormBuilder-B-sNHhCg.js → FormBuilder-yxzbuGp1.js} +1 -1
  19. package/dist/assets/{Identity-CLAq5pc-.js → Identity-4UbH5joN.js} +1 -1
  20. package/dist/assets/{IntegrationDetail-7LmaONwQ.js → IntegrationDetail-FBpSiNiq.js} +1 -1
  21. package/dist/assets/Integrations-Bg2x55D6.js +1 -0
  22. package/dist/assets/{Integrations-CDPziDzI.js → Integrations-BlwdDz0G.js} +1 -1
  23. package/dist/assets/{Logs-Rdo_SjmO.js → Logs-BCcd7cRS.js} +1 -1
  24. package/dist/assets/{MotionZonesSettings-Bhfztqso.js → MotionZonesSettings-CrtWFnAG.js} +1 -1
  25. package/dist/assets/{MyAccess-Cuk_gmTY.js → MyAccess-D5kgvplj.js} +1 -1
  26. package/dist/assets/Network-B0MvXDa9.js +1 -0
  27. package/dist/assets/{NodeAddonsSettingsPanel-mIPiVij_.js → NodeAddonsSettingsPanel-D-zNagxQ.js} +1 -1
  28. package/dist/assets/{NodeInferenceDevices-9bqVJEiE.js → NodeInferenceDevices-DBUXozHP.js} +1 -1
  29. package/dist/assets/Notifications-CblnDXBf.js +1 -0
  30. package/dist/assets/{Pipeline-C3oEXt8M.js → Pipeline-DpNEvH7k.js} +1 -1
  31. package/dist/assets/{Plates-DyGd_pUG.js → Plates-CceWOulf.js} +1 -1
  32. package/dist/assets/{PrivacyMaskSettings-CTbYEYkc.js → PrivacyMaskSettings-1sJg0nCf.js} +1 -1
  33. package/dist/assets/{ProviderIcon-D8aWAoj0.js → ProviderIcon-D6droj6v.js} +1 -1
  34. package/dist/assets/{Recordings-CcL3TTxW.js → Recordings-ZhiDhtnW.js} +1 -1
  35. package/dist/assets/{ScanNetworkModal-C8Bakspm.js → ScanNetworkModal-DB571PA-.js} +1 -1
  36. package/dist/assets/{SceneMonitorEditor-Cx7eASci.js → SceneMonitorEditor-B_qhxMl3.js} +1 -1
  37. package/dist/assets/{Scenes-DnqImYTT.js → Scenes-CPSr7A8e.js} +1 -1
  38. package/dist/assets/{Settings-COAxk1-6.js → Settings-DWSXbJID.js} +1 -1
  39. package/dist/assets/{Showroom-DmEvzSMg.js → Showroom-Cm3xY6GG.js} +1 -1
  40. package/dist/assets/{Terminal-DasTfEQo.js → Terminal-7ZPYC_zr.js} +1 -1
  41. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-tsLPdvDU.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CwufIJ7b.js} +1 -1
  42. package/dist/assets/{bell-ring-B6JDETmm.js → bell-ring-Bzv8dm-v.js} +1 -1
  43. package/dist/assets/{boxes-DVDxegRH.js → boxes-DyONyMfj.js} +1 -1
  44. package/dist/assets/{build-cluster-graph-B8Cdzik4.js → build-cluster-graph-BvbjCtkO.js} +1 -1
  45. package/dist/assets/circle-check-big-abMS-_w1.js +1 -0
  46. package/dist/assets/{circle-x-a0OLhq9b.js → circle-x-BagyAbVd.js} +1 -1
  47. package/dist/assets/clock-cR19SlFN.js +1 -0
  48. package/dist/assets/{copy-EKhXmX92.js → copy-Cg682Ob5.js} +1 -1
  49. package/dist/assets/{debounced-invalidate-BQ8ML6Ah.js → debounced-invalidate-CcW_auXQ.js} +1 -1
  50. package/dist/assets/{dist-Df5TpDx0.js → dist-B7jD-S4H.js} +1 -1
  51. package/dist/assets/{download-BChaquac.js → download--fExXTTV.js} +1 -1
  52. package/dist/assets/{face-bbox-DKVz3zEq.js → face-bbox-Cz1g9sBR.js} +1 -1
  53. package/dist/assets/{hard-drive-Dg_uzT-t.js → hard-drive-CeO72W4c.js} +1 -1
  54. package/dist/assets/{hostInit-CbA0YcFo.js → hostInit-CxhESPfk.js} +1 -1
  55. package/dist/assets/{index-DhYfPTfU.js → index-C4gpE4dh.js} +3 -3
  56. package/dist/assets/{key-round-DpXzoCIV.js → key-round-Di2VNu4U.js} +1 -1
  57. package/dist/assets/{mf-entry-bootstrap-0-631dbdb7.js → mf-entry-bootstrap-0-99898c10.js} +2 -2
  58. package/dist/assets/{pencil-dvZNet31.js → pencil-DLvxk9x1.js} +1 -1
  59. package/dist/assets/play-UOl727Zq.js +1 -0
  60. package/dist/assets/{player-overlays-DXNKqmwI.js → player-overlays-UTlrOH4s.js} +1 -1
  61. package/dist/assets/plus-CLrUKG39.js +1 -0
  62. package/dist/assets/power-CozRqx8K.js +1 -0
  63. package/dist/assets/{radio-CUBDyXa0.js → radio-RZ7CZVIj.js} +1 -1
  64. package/dist/assets/{refresh-cw-CikJV4hg.js → refresh-cw-6kHXys54.js} +1 -1
  65. package/dist/assets/remoteEntry-D-9G_Rwp.js +1 -0
  66. package/dist/assets/rotate-ccw-DV-a5MvB.js +1 -0
  67. package/dist/assets/rotate-cw-B4c6V4Ez.js +1 -0
  68. package/dist/assets/search-Diuzp1ZB.js +1 -0
  69. package/dist/assets/{send-jra0X2FY.js → send-DKjSQk9v.js} +1 -1
  70. package/dist/assets/{server-CLphEdE1.js → server-cirmHxYC.js} +1 -1
  71. package/dist/assets/square-DHyM8h05.js +1 -0
  72. package/dist/assets/{square-check-big-B4oQsHOX.js → square-check-big-ZW9Cb-30.js} +1 -1
  73. package/dist/assets/{src-DAigq6PX.js → src-C9CFJqET.js} +2 -2
  74. package/dist/assets/{src-C0QlPpXb.js → src-CEchIfpK.js} +7 -7
  75. package/dist/assets/{star-Ch9uuiCl.js → star-DYsm4pCY.js} +1 -1
  76. package/dist/assets/{undo-2-DLrLmKUr.js → undo-2-B4nFfmbK.js} +1 -1
  77. package/dist/assets/{upload-DVgOLthM.js → upload-CAXNjiO6.js} +1 -1
  78. package/dist/assets/{use-scenes-feed-DdlE4MDL.js → use-scenes-feed-CCncPGkQ.js} +1 -1
  79. package/dist/assets/{useEventInvalidation-DqKGeTpc.js → useEventInvalidation-V6uvnrrN.js} +1 -1
  80. package/dist/assets/{video-DuMIkvBP.js → video-BJrMHLZ5.js} +1 -1
  81. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DdAFU5xY.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DtSdTes5.js} +2 -2
  82. package/dist/assets/{wifi-DNsDHc6u.js → wifi-CusedooP.js} +1 -1
  83. package/dist/assets/{zap-RHfxlZhI.js → zap-DUeFTNxj.js} +1 -1
  84. package/dist/index.html +5 -5
  85. package/dist/server/addon.js +1 -1
  86. package/package.json +1 -1
  87. package/dist/assets/AiProfiles-DECvat8h.js +0 -3
  88. package/dist/assets/Integrations-o_BOKz_C.js +0 -1
  89. package/dist/assets/Network-BAt6cJW9.js +0 -1
  90. package/dist/assets/Notifications-CwcH2yYC.js +0 -1
  91. package/dist/assets/circle-check-big-BZnwR-f7.js +0 -1
  92. package/dist/assets/clock-fhk_ag9V.js +0 -1
  93. package/dist/assets/play-D6bynunz.js +0 -1
  94. package/dist/assets/plus-CDo9Tbkz.js +0 -1
  95. package/dist/assets/power-BF-VFkkW.js +0 -1
  96. package/dist/assets/remoteEntry-DbX8dE3W.js +0 -1
  97. package/dist/assets/rotate-ccw-P5OXZofT.js +0 -1
  98. package/dist/assets/rotate-cw-DDRA2uuI.js +0 -1
  99. package/dist/assets/search-DhirDmpC.js +0 -1
  100. package/dist/assets/square-UC6vONGu.js +0 -1
@@ -1 +0,0 @@
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-DXNKqmwI.js";import{At as f,Dt as p,Et as m,Ft as h,It as g,Kt as _,Lt as v,Mt as y,Pt as b,Rt as x,Tt as S,Xt as C,dt as w,ft as T,ho as E,ii as D,jt as O,kt as k,lt as A,nt as j,po as M,tt as N,ut as P}from"./src-C0QlPpXb.js";import{C as F,D as I,E as ee,H as te,S as ne,T as L,U as re,_ as ie,b as ae,f as oe,g as se,h as ce,m as le,p as ue,tt as de,v as fe,w as pe,x as me,y as he,z as ge}from"./src-DAigq6PX.js";import{D as _e,E as ve,_ as ye,j as be,v as xe}from"./__vite-browser-external-B6qJ4svC.js";import{n as Se,t as Ce}from"./bell-ring-B6JDETmm.js";import{t as we}from"./circle-check-big-BZnwR-f7.js";import{t as Te}from"./copy-EKhXmX92.js";import{n as Ee,t as De}from"./send-jra0X2FY.js";import{t as Oe}from"./pencil-dvZNet31.js";import{t as ke}from"./plus-CDo9Tbkz.js";import{t as Ae}from"./radio-CUBDyXa0.js";import{t as je}from"./refresh-cw-CikJV4hg.js";import{t as Me}from"./rotate-ccw-P5OXZofT.js";import{t as Ne}from"./search-DhirDmpC.js";import{t as Pe}from"./zap-RHfxlZhI.js";import{C as R,F as Fe,K as Ie,O as Le,U as Re,X as ze,f as Be,i as Ve,o as He,s as Ue,w as We}from"./index-DhYfPTfU.js";import{t as z}from"./AdminPage-CCD07UMs.js";import{t as Ge}from"./AdminTabs-D6yDsobg.js";import{t as Ke}from"./use-scenes-feed-DdlE4MDL.js";var qe=Ie(`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`}]]),Je=Ie(`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`}]]),Ye=Ie(`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 Xe={home:`Home`,away:`Away`,night:`Night`};function Ze(e){return Xe[e]??e}function Qe(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 $e(e,t){return e.ruleCount===0?`Arms nothing — no enabled rule is gated on this mode.`:e.allDevices?`Every device — ${rt(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${rt(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(e=>t.get(e)??`Device ${e}`).join(`, `)}function et(e,t){if(e.length===0)return``;let n=e.map(e=>`${t.get(e.deviceId)??`Device ${e.deviceId}`} (${tt[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var tt={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function nt(e){return e.ruleCount===0}function rt(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function it(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 at=[`notificationRules`,`getAlarmConfig`],ot=[`notificationOutput`,`listTargets`],st=[`deviceManager`,`listAll`,`alarm-coverage`],ct=600,lt=3600;function ut({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(h,{type:`number`,min:0,max:i,value:u??String(r),disabled:o,onChange:e=>d(e.target.value),onBlur:()=>{let e=u===null?null:it(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:Qe(r,a)})]}),l(`p`,{className:`text-xs text-foreground-subtle`,children:n})]})}function dt(){let e=d(),i=o(),a=r({queryKey:at,queryFn:async()=>e.trpcClient.notificationRules.getAlarmConfig.query({})}),s=r({queryKey:ot,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),u=r({queryKey:st,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:at})}),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:Be,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:l(R,{className:`h-5 w-5 animate-spin`})});let m=a.data;if(m===void 0||a.isError)return l(z,{icon:Be,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(m.deviceId===null)return l(z,{icon:Be,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:l(g,{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=m.settings,_=f.isPending,b=s.data??[],x=h.announceTargets,S=e=>{f.mutate(e)},w=e=>{S({announceTargets:x.includes(e)?x.filter(t=>t!==e):[...x,e]})};return l(z,{icon:Be,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(g,{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(ut,{label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,value:h.exitDelaySec,max:ct,zeroMeans:`arms immediately`,disabled:_,onCommit:e=>S({exitDelaySec:e})}),l(ut,{label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,value:h.entryDelaySec,max:ct,zeroMeans:`fires immediately`,disabled:_,onCommit:e=>S({entryDelaySec:e})}),l(ut,{label:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,value:h.triggeredDurationSec,max:lt,zeroMeans:`until disarmed`,disabled:_,onCommit:e=>S({triggeredDurationSec:e})})]})]}),t(g,{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(y,{checked:h.announceArm,disabled:_,onCheckedChange:e=>S({announceArm:e}),"data-testid":`alarm-announce-toggle`})})]}),h.announceArm?t(`div`,{className:`mt-3 flex flex-col gap-2`,children:[b.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:b.map(e=>t(`label`,{className:`flex items-center gap-2 text-sm`,children:[l(`input`,{type:`checkbox`,checked:x.includes(e.id),disabled:_,onChange:()=>w(e.id),"data-testid":`alarm-target-${e.id}`}),l(`span`,{className:`min-w-0 truncate`,children:e.name}),e.enabled?null:l(v,{variant:`warning`,children:`disabled`})]},e.id))}),x.length===0?l(`p`,{className:`text-xs text-warning`,children:`No target selected — the announcement will not be sent.`}):null]}):null]}),t(g,{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:m.coverage.map(e=>t(`div`,{className:`flex items-start gap-3 rounded border border-border p-2`,"data-mode":e.mode,"data-empty":nt(e)?`true`:`false`,children:[l(`div`,{className:`w-20 shrink-0 text-sm font-medium`,children:Ze(e.mode)}),t(`div`,{className:`flex-1 text-sm text-foreground-subtle`,children:[$e(e,p),e.skippedDevices.length>0?l(`div`,{className:`mt-0.5 text-xs text-warning`,"data-testid":`alarm-skipped`,children:et(e.skippedDevices,p)}):null]}),nt(e)?l(He,{className:`h-4 w-4 shrink-0 text-warning`}):null]},e.mode))})]})]})})}e();var ft=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],pt=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],mt=[50,100,250,500];function ht(){return{ruleId:``,deviceId:``,status:``,windowHours:24,limit:100}}function gt(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function _t(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function vt(){let e=d(),[i,a]=s(ht),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===de.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)}:{},...gt(i.status)?{status:gt(i.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),m=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),h=e=>m.get(e)??`Camera #${String(e)}`,_=p.data??[],v=p.isError;return t(z,{icon:qe,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(b,{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(b,{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(b,{value:i.status,onChange:e=>o({status:e.target.value}),options:pt.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(b,{value:String(i.windowHours),onChange:e=>o({windowHours:Number(e.target.value)}),options:ft.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(b,{value:String(i.limit),onChange:e=>o({limit:Number(e.target.value)}),options:mt.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`})}),v&&!p.isLoading&&l(g,{children:t(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[l(qe,{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(je,{className:`h-3 w-3`}),` Retry`]})]})}),!v&&!p.isLoading&&_.length===0&&l(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!v&&_.length>0&&l(g,{children:l(N,{columns:yt(h),rows:_,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})})]})}function yt(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(v,{variant:_t(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 bt(e){let t=[],n=e.find(e=>e.type===de.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===de.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 xt(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 St=[{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`}],Ct={sequences:[],buttons:[]};function wt(e){return e===void 0?Ct:{sequences:[...e.onTrigger??[]],buttons:[...e.buttons??[]]}}function Tt(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 Et(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 Dt(e){return{name:`sequence ${String(e+1)}`,enabled:!1,actions:[]}}function Ot(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequence:t}}function kt(){return{kind:`wait`,seconds:5}}var At=`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 jt({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 Mt({value:e,onChange:n,devices:r}){let i=Et(e),a=bt(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(jt,{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(x,{size:`sm`,variant:`ghost`,type:`button`,title:r.hint,className:`min-w-0 max-w-full`,onClick:()=>n(xt(e,r)),children:[l(Pe,{className:`h-3.5 w-3.5 shrink-0`}),l(`span`,{className:`truncate`,children:r.label})]},r.id)),t(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({...e,sequences:[...e.sequences,Dt(e.sequences.length)]}),children:[l(ke,{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(Nt,{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(jt,{title:`Buttons on the notification`,description:`Each button runs one of the sequences above when tapped.`,children:t(x,{size:`sm`,variant:`ghost`,type:`button`,disabled:e.sequences.length===0,onClick:()=>n({...e,buttons:[...e.buttons,Ot(e.buttons.length,e.sequences[0]?.name??``)]}),children:[l(ke,{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(He,{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(It,{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 Nt({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(h,{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:At,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(y,{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(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:l(Ue,{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(Pt,{step:t,devices:n,onChange:e=>a(i,e),onRemove:()=>r({...e,actions:e.actions.filter((e,t)=>t!==i)})},`step-${String(i)}`)),t(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({...e,actions:[...e.actions,kt()]}),children:[l(ke,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function Pt({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:At,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:At,value:e.seconds,onChange:e=>r({kind:`wait`,seconds:Number(e.target.value)})})]}):l(Ft,{step:e,devices:n,onChange:r}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove step`,children:l(Ue,{className:`h-3.5 w-3.5`})})]})}function Ft({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:At,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:At,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(h,{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(h,{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 It({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(h,{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:At,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:At,value:e.icon??``,onChange:t=>{let n={...e};if(t.target.value===``)delete n.icon;else{let e=St.find(e=>e.value===t.target.value);e!==void 0&&(n.icon=e.value)}r(n)},children:[l(`option`,{value:``,children:`None`}),St.map(e=>l(`option`,{value:e.value,children:e.label},e.value))]})]}),t(`div`,{className:`flex items-center gap-2 pb-1`,children:[l(y,{checked:e.destructive===!0,onCheckedChange:t=>{let n={...e};t?n.destructive=!0:delete n.destructive,r(n)}}),l(v,{variant:e.destructive===!0?`danger`:`default`,children:`Destructive style`})]}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:l(Ue,{className:`h-3.5 w-3.5`})})]})}function V(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var Lt=V({devices:!0}),Rt=V({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),zt=V({zonesExclude:!0}),Bt=V({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),Vt=V({minDwellSeconds:!0}),Ht=V({source:!0}),Ut=V({crossing:!0}),Wt=V({packagePhase:!0}),Gt=V({zones:!0}),Kt=V({plates:!0}),qt=V({occupancy:!0}),Jt={op:`became-occupied`,count:1,sustainSeconds:15},Yt=V({audio:!0}),Xt=V({systemEvent:!0}),Zt=V({deviceState:!0}),Qt=V({scene:!0});function $t(e,t){let n=e[t];return Array.isArray(n)?n:[]}function en(e,t){let n=e[t];return typeof n==`number`?n:void 0}var tn=[{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 nn(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function rn(e,t){let n=e.filter(t),r=new Set(tn.map(e=>e.id)),i=[];for(let e of tn){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:nn(e),descriptors:n.filter(t=>t.group===e)});return i}e();function an(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 on(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 sn(){let e=D();return n(()=>({options:(e.data??[]).map(e=>({value:e.id,label:e.name})),loading:e.isLoading}),[e.data,e.isLoading])}function cn(){let e=M({limit:200}),t=E();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 ln({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 un=`An occupancy edge is not a sensor event: it carries no sensor kind, so this condition can never match one.`,dn=`An occupancy edge carries no device event-type token — that comes from an event-emitter slice, which a count crossing has none of.`,fn=`An occupancy edge is always produced by the pipeline, so any other source can never match and “pipeline” narrows nothing.`,pn=`A confirmed sound window is always stamped as an audio subject, so any other source can never match.`,mn=`A sound rule fires on what the camera HEARD. Its subject carries no detection, so this condition can never match one — name the sounds in the Sound condition instead.`,hn=`A sound window’s evidence is a percentage of samples, not a detector score, so a confidence threshold can never be satisfied.`,gn=`A sound has no position in the frame, so a zone or a drawn polygon can never match it.`,_n=[{kind:`detection`,label:`Conditions`,excluded:{},carriesMedia:!0,carriesSubjectCrop:!0},{kind:`sensor`,label:`Conditions`,excluded:{},carriesMedia:!0,carriesSubjectCrop:!0,blurb:`A doorbell press or a linked sensor changing state. The picture comes from the camera the sensor is attributed to.`},{kind:`occupancy`,label:`Occupancy`,discriminator:`occupancy`,excluded:{sensorKinds:un,eventTypeTokens:dn,source:fn},carriesMedia:!0,carriesSubjectCrop:!0,blurb:`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.`},{kind:`sound`,label:`Sound`,discriminator:`audio`,excluded:{classes:mn,classesExclude:mn,minConfidence:hn,zones:gn,zonesExclude:gn,customZones:gn,crossing:gn,labelEquals:mn,identities:mn,identitiesExclude:mn,plates:mn,source:pn},carriesMedia:!0,carriesSubjectCrop:!1,blurb:`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.`,mediaBlurb:`A sound owns no frame, so the picture is a photograph of the camera taken at the moment of the match — the whole scene, never a crop. The GIF and the clip are cut around the same instant, from the camera.`},{kind:`system`,label:`Events`,discriminator:`systemEvent`,excluded:{},carriesMedia:!1,carriesSubjectCrop:!1,blurb:`The installation itself: a camera or stream dropping, a node leaving, an update landing. There is no detection behind it and no frame to attach.`}];function vn(e){return _n.find(t=>t.kind===e)??_n[0]}function yn(e){return e.delivery===`system-event`?`system`:e.conditions.occupancy!==void 0&&e.delivery===`device-event`?`occupancy`:e.conditions.audio!==void 0&&e.delivery===`immediate`?`sound`:e.delivery===`device-event`?`sensor`:`detection`}function bn(e,t,n){let r=vn(n);return e.id===r.discriminator?!0:e.appliesTo.includes(t)?r.excluded[e.id]===void 0:!1}function xn(e,t){let n=vn(t),r=[];for(let[t,i]of Object.entries(e)){if(i===void 0||Array.isArray(i)&&i.length===0)continue;let e=n.excluded[t];e!==void 0&&r.push({conditionId:t,reason:e})}return r}var Sn=[{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 Cn(e){return Sn.find(t=>t.value===e)?.label??e}function wn(e){return Sn.find(t=>t.value===e)?.value}function Tn(e){return Sn.some(t=>t.value===e)}function En(e){return e===`system-event`}var Dn=[{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.`}];function On(e){return Dn.find(t=>t.key===e)?.key}function kn(e){return e.conditions.audio!==void 0}function An(e){return e.conditions.occupancy!==void 0}function jn(e,t){return t===`all`?!0:t===`system`?En(e.delivery):t===`audio`?kn(e):t===`occupancy`?An(e):!En(e.delivery)&&!kn(e)&&!An(e)}var Mn={hitPercent:ae.hitPercent,samplingSeconds:ae.samplingSeconds,dbThreshold:-55};function Nn(e){switch(e){case`system`:return{delivery:`system-event`,conditions:{}};case`audio`:return{delivery:`immediate`,conditions:{audio:Mn}};case`occupancy`:return{delivery:`device-event`,conditions:{occupancy:Jt}};default:return{delivery:`immediate`,conditions:{}}}}var Pn=new Map([[0,`No cooldown`],[60,`1 minute`],[3600,`1 hour`]]),Fn=86400;function In(e){let t=Pn.get(e);return t===void 0?e%3600==0?`${e/3600} hours`:e%60==0?`${e/60} minutes`:`${e} seconds`:t}function Ln(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)&&t>=0?Math.trunc(t):void 0}var Rn=[{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 zn(e){return Rn.find(t=>t.value===e)?.value}var Bn=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function Vn(e){let t=Bn.find(t=>t.value===e)?.value;return t===``?void 0:t}var Hn=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function Un(e){let t=Hn.find(t=>t.value===e)?.value;return t===``?void 0:t}var Wn=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],Gn=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],Kn=[{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 qn(e){let t=Kn.find(t=>t.value===e)?.value;return t===``||t===void 0?void 0:t}var Jn=[{value:`any`,label:`Any of`},{value:`all`,label:`All of`}],Yn=[{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`}],Xn=[10,30,60],Zn=[5,10,15,30,60,120,240,480];function Qn(e){return e>=60&&e%60==0?`${e/60} h`:`${e} min`}var $n=new Set([`alarm-arming`,`alarm-triggered`,`alarm-armed`,`alarm-disarmed`]),er=`alarm-panel`;function tr(e,t){for(let t of e.systemEvent?.kinds??[])if($n.has(t))return!0;for(let e of t)for(let t of e.actions)if(t.kind===`cap`&&t.cap===er)return!0;return!1}function nr(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:Ct,deviceIds:[],cooldownSec:30}}function rr(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:wt(e.actions),deviceIds:e.conditions.devices??[],cooldownSec:e.throttle.cooldownSec}}function ir(e){let t=[];return me(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(Fn)} (24 hours). 0 means every match is delivered.`),t}function ar(e){return ir(e).length===0&&Tn(e.delivery)&&(!En(e.delivery)||or(e)>0)&&e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&Et(e.actions).length===0}function or(e){return e.conditions.systemEvent?.kinds.length??0}function sr(e,t){return e.appliesTo.includes(t)}var cr={source:`any`};function lr(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||cr[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 ur=te.filter(e=>e.id===`audio`);function dr(e){if(e.length===0)return e;let t=new Set(e.map(e=>e.id)),n=ur.filter(e=>!t.has(e.id));return n.length===0?e:[...e,...n]}function fr(e,t,n,r=yn({delivery:t,conditions:e})){let i=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&bn(e,t,r)).map(e=>e.id)),a={};for(let[t,n]of Object.entries(e))i!==null&&!i.has(t)||lr(t,n)||(a[t]=n);return a}function pr(e){return e!==void 0&&e.windows.length>0}function mr(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=Tt(e.actions),s=yn(e),c=vn(s),l=(n.length===0||n.some(t=>t.id===`schedule`&&sr(t,e.delivery)))&&pr(e.schedule)?e.schedule:void 0,u=n.length===0?!0:n.some(t=>t.id===`devices`&&sr(t,e.delivery));return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...fr(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 hr(e,t){return e.options&&e.options.length>0?e.options:t}var gr=[{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 _r(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var vr=[{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 yr(e,t={}){let n=vn(yn({delivery:e,conditions:t})),r=vr.map(e=>e.key===`conditions`?{...e,label:n.label}:e);return En(e)?r.filter(e=>e.key!==`devices`):r}function br(e){if(e.audio!==void 0)return`Sound`;if(e.occupancy!==void 0)return`Occupancy`}function xr(e){return xn(e.conditions,yn(e))}var Sr=`rule`;function Cr(e){return vr.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 wr({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 Tr({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(Ve,{className:`h-3 w-3`})})]},e))}),l(h,{value:i,placeholder:n,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),o())},onBlur:o})]})}function Er({picker:e,value:r,onChange:i}){let a=n(()=>ie(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 Dr({value:e,min:n,max:r,step:i,onChange:a}){return t(`div`,{className:`mt-1 flex items-center gap-2`,children:[l(h,{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 Or({value:e,onChange:n,options:r}){let i=e??``,a=r&&r.length>0?r:Kn,o=a.find(e=>e.value===i);return t(`div`,{className:`mt-1 space-y-1`,children:[l(b,{value:i,options:a.map(e=>({value:e.value,label:e.label})),onChange:e=>n(qn(e.target.value))}),o!==void 0&&l(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:o.hint})]})}function kr({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(b,{value:o,options:Jn.map(e=>({value:e.value,label:e.label})),onChange:e=>c(e.target.value===`all`?`all`:`any`)})}),l(Ar,{deviceIds:e,cameras:n,value:a,onChange:s})]})}function Ar({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=an(e,t);return l(ln,{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 jr({value:e,onChange:t}){let{options:n,loading:r}=sn();return l(ln,{options:n,value:e,onChange:t,loading:r,emptyHint:`No identities in the face gallery yet — type a name.`,placeholder:`Identity name…`})}function Mr({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=on(e);return l(ln,{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 Nr=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}];function Pr(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 Fr({deviceIds:e,cameras:n,classOptions:r,value:i,onChange:a}){let{options:o,loading:s}=an(e,n),c=i??Jt,u=e=>a({...c,...e}),d=c.op===`became-occupied`||c.op===`became-free`,f=Pr(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(b,{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(b,{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(b,{value:c.op,options:Nr.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Nr.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(h,{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(h,{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 Ir=[{value:`label`,label:`🔎 Sounds — fires at once`},{value:`level`,label:`📈 Volume — over a window`}];function Lr({taxonomy:e,value:n,onChange:r}){let a=pe(n),o=e=>r(ee(n,e)),{choices:s,unknownLabels:c}=ne(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:[Ir.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: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=L(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 t(`button`,{type:`button`,"aria-pressed":n,title:e.unknown?`Stored by the rule — not offered by this hub`:void 0,onClick:()=>o({labels:I(a.labels,e.value)}),className:`rounded border px-1.5 py-0.5 text-[10px] ${r}`,children:[l(`span`,{"aria-hidden":`true`,children:e.icon}),` `,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(h,{type:`number`,min:he,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(h,{type:`number`,min:1,max:100,step:5,className:`w-16`,value:String(a.hitPercent),onChange:e=>o({hitPercent:Number(e.target.value)})}),`% (default `,ae.hitPercent,`)`]}),t(`label`,{className:`flex items-center gap-1`,children:[`over`,l(h,{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 `,ae.samplingSeconds,`)`]})]}),t(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`dBFS is negative-going: 0 is full scale, `,he,` 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.`]})]}),me(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 Rr({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=cn().filter(e=>!r.includes(e));return t(`div`,{className:`mt-1 space-y-1.5`,children:[l(Tr,{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(h,{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 zr({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(b,{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 Br(e){let t=e.verdict===`matched`?`matched`:e.verdict===`diverged`?`diverged`:`cannot judge`;return e.latched?`${t} · latched`:t}function Vr({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(b,{value:n?.sceneId??``,options:[{value:``,label:`— no scene gate —`},...e.map(e=>({value:e.sceneId,label:`${e.cameraName} · ${e.label} — ${Br(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(b,{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(b,{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: `,Br(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 Hr=[{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 Ur(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Wr(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 Gr(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function Kr({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,Gr()],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(qr,{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(ke,{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 qr({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:Ur(e.startMinute),onChange:t=>n({...e,startMinute:Wr(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:Ur(e.endMinute),onChange:t=>n({...e,endMinute:Wr(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(Ue,{className:`h-3.5 w-3.5`})})]}),l(`div`,{className:`flex flex-wrap gap-1`,children:Hr.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 Jr=[{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`}]}],Yr=Jr.flatMap(e=>e.kinds);function Xr(e){return Yr.find(t=>t.value===e)?.label??e}function Zr(e){return{devices:ce(e,`deviceIds`),deviceTypes:ce(e,`deviceTypes`),nodes:ce(e,`nodeIds`),packages:ce(e,`packageNames`)}}var Qr=Object.values(de).map(e=>({value:e,label:$r(e)})).toSorted((e,t)=>e.label.localeCompare(t.label));function $r(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function ei(e,t){let n=e?.kinds??[],r=n.includes(t)?n.filter(e=>e!==t):Yr.filter(e=>e.value===t||n.includes(e.value)).map(e=>e.value);if(r.length!==0)return ri(e,r)}function ti(e,t){let n=e?.kinds??[];if(n.length===0)return;let r=ni(t,`deviceIds`,e?.deviceIds),i=ni(t,`deviceTypes`,e?.deviceTypes),a=ni(t,`nodeIds`,e?.nodeIds),o=ni(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 ni(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 ri(e,t){let n=Zr(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 ii(e,t=2){if(e===void 0||e.length===0)return`No event selected`;let n=e.slice(0,t).map(Xr).join(`, `),r=e.length-Math.min(t,e.length);return r>0?`${n} +${r}`:n}function ai(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($r).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 oi=[`nc-pickers`,`nodes`],si=[`nc-pickers`,`addon-packages`];function ci(){let e=d().trpcClient,t=r({queryKey:oi,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 li(){let e=d().trpcClient,t=r({queryKey:si,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 ui({value:e,cameras:r,onChange:i}){let a=n(()=>e?.kinds??[],[e]),o=Zr(a),s=ci(),c=li();return t(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[Jr.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(ei(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(ln,{options:Qr,value:e?.deviceTypes??[],onChange:t=>i(ti(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(wr,{cameras:r,value:e?.deviceIds??[],onChange:t=>i(ti(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(ln,{options:s.options,value:e?.nodeIds??[],onChange:t=>i(ti(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(ln,{options:c.options,value:e?.packageNames??[],onChange:t=>i(ti(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 di({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=yn({delivery:i,conditions:a}),_=n(()=>e.filter(e=>bn(e,i,g)),[e,i,g]),v=e.length-_.length,y=n(()=>rn(_,e=>e.id!==`devices`&&pi(e,i,a)),[_,i,a]),b=n(()=>rn(_,e=>e.id!==`devices`&&!pi(e,i,a)),[_,i,a]),[x,S]=s(()=>{if(mi(a,o))return!0;try{return localStorage.getItem(fi)===`1`}catch{return!1}}),C=()=>{let e=!x;S(e);try{localStorage.setItem(fi,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(hi,{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`,` `,vn(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 fi=`camstack.nc.showAdvanced`;function pi(e,t,n={}){return t===`system-event`?e.id===`systemEvent`:e.id===`audio`?n.audio!==void 0:e.id===`occupancy`?n.occupancy!==void 0:se(e.id)}function mi(e,t){for(let[t,n]of Object.entries(e))if(!se(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 hi({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(!Lt(e.id))break;let t=e.id;return l(wr,{cameras:a,value:n[t]??[],onChange:e=>c(t,e.length>0?e:void 0)})}case`stringList`:{if(!Rt(e.id))break;let r=e.id,a=e=>c(r,e.length>0?e:void 0);if(r===`identities`||r===`identitiesExclude`)return l(jr,{value:$t(n,r),onChange:e=>r===`identities`?c(r,e):a(e)});if(r===`eventTypeTokens`)return l(Mr,{deviceIds:i,value:$t(n,r),onChange:a});let o=fe(r,t);return o===null?l(Tr,{value:$t(n,r),placeholder:`Add value…`,onChange:a}):l(Er,{picker:o,value:$t(n,r),onChange:a})}case`zoneIdList`:{if(!zt(e.id))break;let t=e.id;return l(Ar,{deviceIds:i,cameras:a,value:$t(n,t),onChange:e=>c(t,e.length>0?e:void 0)})}case`number01`:{if(!Bt(e.id))break;let t=e.id;return l(Dr,{value:en(n,t),min:0,max:1,step:.05,onChange:e=>c(t,e)})}case`number`:{if(!Vt(e.id))break;let t=e.id;return l(Dr,{value:en(n,t),min:0,step:1,onChange:e=>c(t,e)})}case`sourceSelect`:{if(!Ht(e.id))break;let t=e.id;return l(b,{value:n[t]??`any`,options:hr(e,Wn).map(e=>({value:e.value,label:e.label})),onChange:e=>c(t,vi(e.target.value))})}case`systemEvent`:{if(!Xt(e.id))break;let t=e.id;return l(ui,{value:n[t],cameras:a,onChange:e=>c(t,e)})}case`deviceState`:if(!Zt(e.id))break;return l(zr,{gateable:o,value:n.deviceState,onChange:e=>c(`deviceState`,e)});case`scene`:if(!Qt(e.id))break;return l(Vr,{scenes:s,value:n.scene,onChange:e=>c(`scene`,e)});case`crossingSelect`:{if(!Ut(e.id))break;let t=e.id;return l(Or,{value:n[t],onChange:e=>c(t,e),...e.options?{options:e.options}:{}})}case`packagePhase`:{if(!Wt(e.id))break;let t=e.id;return l(b,{value:n[t]??``,options:[{value:``,label:`— any phase —`},...hr(e,Gn).map(e=>({value:e.value,label:e.label}))],onChange:e=>c(t,yi(e.target.value))})}case`zoneSelection`:{if(!Gt(e.id))break;let t=e.id;return l(kr,{deviceIds:i,cameras:a,value:n[t],onChange:e=>c(t,e)})}case`plateMatcher`:{if(!Kt(e.id))break;let t=e.id;return l(Rr,{value:n[t],onChange:e=>c(t,e)})}case`occupancy`:{if(!qt(e.id))break;let r=e.id;return l(Fr,{deviceIds:i,cameras:a,classOptions:gi(t),value:n[r],onChange:e=>c(r,e)})}case`audio`:{if(!Yt(e.id))break;let r=e.id;return l(Lr,{taxonomy:t,value:n[r],onChange:e=>c(r,e)})}case`schedule`:return l(Kr,{value:r,onChange:u});default:break}return l(_i,{descriptor:e,conditions:n})}function gi(e){let t=fe(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function _i({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 vi(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function yi(e){return Gn.find(t=>t.value===e)?.value}var bi={search:``,types:[],selectedOnly:!1};function xi(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 Si(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 Ci(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 wi(e,t){let n=new Set(t);for(let t of e)n.add(t.id);return[...n]}function Ti(e,t){let n=new Set(e.map(e=>e.id));return t.filter(e=>!n.has(e))}function Ei(e,t){return e.length===0?`Every device (${String(t)}) — no restriction`:`${String(e.length)} of ${String(t)} selected`}e();function Di({devices:e,value:r,onChange:i,loading:a=!1}){let[o,c]=s(bi),u=n(()=>xi(e),[e]),d=n(()=>Si(e,o,r),[e,o,r]),f=n(()=>Ci(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:Ei(r,e.length)}),t(`div`,{className:`flex items-center gap-1`,children:[l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i(wi(d,r)),children:`Select shown`}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i(Ti(d,r)),children:`Clear shown`})]})]}),t(`div`,{className:`flex flex-wrap items-center gap-2`,children:[l(h,{className:`min-w-[10rem] flex-1`,value:o.search,placeholder:`Search by name…`,leftSlot:l(Ne,{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(v,{variant:`default`,children:e.type})]},e.id))})]},e.location??`__unplaced`))})]})}e();var Oi=[`notificationRules`,`listSnoozes`],ki=[10,30,60,120];function Ai({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:Oi}),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(x,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:`Silence this rule for ${Qn(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(Se,{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(b,{value:String(f),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:ki.map(e=>({value:String(e),label:Qn(e)}))})}),t(x,{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(Se,{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 ji=`pipeline-analytics`,Mi=`nc.getRuleStatus`,Ni=`nc.testRule`;function Pi(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 Fi(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ii(e){if(!Pi(e))return;let t=Fi(e,`id`),n=Fi(e,`downloadPath`),r=W(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:Fi(e,`mediaType`)??`video`,sizeBytes:W(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function Li(e){if(!Pi(e))return;let t=W(e,`startMs`),n=W(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function Ri(e){if(!Pi(e))return null;let t=W(e,`deviceId`);if(t===void 0)return null;let n=W(e,`lastGeneratedAt`),r=Ii(e.lastArtifact),i=e.rendering,a=Pi(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 zi(e){if(!Pi(e))return null;let t=Fi(e,`kind`);if(t===`none`)return{kind:`none`,reason:Fi(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=Fi(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=Fi(e,`scope`),u=Fi(e,`className`),d=Fi(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=Ri(e);t!==null&&n.push(t)}let r=Li(e.lastWindow),i=e.nextWindow,a=Pi(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 Bi(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 Vi(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 Hi(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 ${Bi(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 Ui(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${Bi(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} · ${Vi(i.sizeBytes)}`}var Wi=5e3;function Gi({ruleId:e,cameraName:n}){let a=d(),o=r({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:Wi,queryFn:async()=>zi(await a.trpcClient.addons.custom.mutate({addonId:ji,action:Mi,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(He,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):l(Ae,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),t(`span`,{children:[l(`span`,{className:`text-foreground`,children:c(o.deviceId)}),` —`,` `,Hi(o,s)]})]}),o.kind===`timelapse`&&t(i,{children:[o.devices.map(e=>t(`p`,{className:`flex items-start gap-1.5`,children:[l(Ae,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),t(`span`,{children:[Ui(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 Ki(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 qi(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Ji(e){if(!Ki(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:qi(e,`targetIds`)}}function Yi(e){if(!Ki(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 Xi(e){if(!Ki(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=Ji(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Yi(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:qi(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i}}function Zi(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 Qi({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()=>Xi(await u.trpcClient.addons.custom.mutate({addonId:ji,action:Ni,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.`)}),_=f===null?m===null?void 0:m:Zi(f);return t(i,{children:[t(x,{size:`sm`,variant:a===`icon`?`ghost`:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(),title:_??`Test now — fires this rule and really sends the notification`,"aria-label":`test ${n} now`,"data-testid":`nc-rule-test-now`,children:[g.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(De,{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:Zi(f)}),f.planNotes.map(e=>t(`p`,{className:`flex gap-1.5`,children:[l(He,{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 $i=[`notificationRules`,`listSnoozes`],ea=3e4;function ta(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function na(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 ra({rules:e}){let i=d(),a=o(),s=r({queryKey:$i,refetchInterval:ea,queryFn:async()=>(await i.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),u=c({mutationFn:e=>i.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>a.invalidateQueries({queryKey:$i})}),f=n(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),p=Date.now(),m=(s.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return t(g,{className:`p-4`,children:[t(`div`,{className:`flex items-center gap-2 mb-3`,children:[l(Se,{className:`h-4 w-4 text-foreground-subtle`}),l(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),m.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:m.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(v,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&l(v,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&l(v,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),t(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,na(ta(e,p))]})]}),l(x,{size:`sm`,variant:`outline`,disabled:u.isPending,onClick:()=>u.mutate(e.id),children:`End now`})]},e.id))})]})}e();var ia=[`notificationRules`,`listRules`],aa=[`notificationOutput`,`listTargets`,`forRules`],oa=[`notificationRules`,`getConditionCatalog`],sa=[`deviceManager`,`listAll`,`forRules`],ca=[`deviceManager`,`listAll`,`forRuleActions`],la=[`deviceManager`,`gateableDevices`],ua=re.options;function da({onSimulateRule:e}={}){let i=d(),[a,o]=s({mode:`closed`}),[u,f]=s(null),[p,m]=s(`all`),h=r({queryKey:ia,queryFn:async()=>(await i.trpcClient.notificationRules.listRules.query({})).rules}),_=r({queryKey:aa,queryFn:()=>i.trpcClient.notificationOutput.listTargets.query({})}),v=r({queryKey:oa,queryFn:()=>i.trpcClient.notificationRules.getConditionCatalog.query({})}),y=r({queryKey:la,queryFn:async()=>{let e=await i.trpcClient.deviceManager.listAll.query({}),t=[];for(let n of e){let e=ge(await i.trpcClient.deviceManager.loadRuntimeState.query({deviceId:n.id}),ua);e.length>0&&t.push({id:n.id,name:n.name,states:e})}return t},staleTime:6e4}),b=r({queryKey:ca,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:sa,queryFn:async()=>(await i.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===de.Camera).map(e=>({id:e.id,name:e.name}))}),E=Ke(n(()=>(S.data??[]).map(e=>e.id),[S.data])),D=n(()=>{let e=new Map((S.data??[]).map(e=>[e.id,e.name]));return E.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})))},[E.results,S.data]),O=n(()=>{let e=new Map;for(let t of _.data??[])e.set(t.id,t.name);return e},[_.data]),k=c({mutationFn:e=>i.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void h.refetch()}),j=c({mutationFn:e=>i.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>{f(null),h.refetch()}}),M=h.data??[],P=n(()=>M.filter(e=>jn(e,p)),[M,p]),F=n(()=>{let e=new Map;for(let t of Dn)e.set(t.key,M.filter(e=>jn(e,t.key)).length);return e},[M]),I=Dn.find(e=>e.key===p)??Dn[0],ee=p===`system`;return t(z,{icon:Ce,title:`Notification Rules`,subtitle:I.blurb,actions:t(x,{size:`sm`,type:`button`,onClick:()=>o({mode:`form`,rule:null,seed:Nn(p)}),children:[l(ke,{className:`h-3.5 w-3.5`}),I.newRuleLabel]}),children:[l(A,{value:p,onValueChange:e=>m(On(e)??p),children:l(w,{className:`mb-3`,children:Dn.map(e=>t(T,{value:e.key,children:[e.label,l(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:F.get(e.key)??0})]},e.key))})}),l(ra,{rules:M}),h.isLoading&&l(`div`,{className:`flex items-center justify-center py-16`,children:l(R,{className:`h-6 w-6 animate-spin text-primary`})}),h.isError&&!h.isLoading&&l(C,{title:`Failed to load rules`,message:h.error instanceof Error?h.error.message:`Unknown error`,onRetry:()=>void h.refetch()}),!h.isLoading&&!h.isError&&P.length===0&&l(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:I.emptyHint}),P.length>0&&l(g,{children:l(N,{columns:ee?pa({targetNameById:O,confirmDeleteId:u,deletePending:j.isPending,onToggle:(e,t)=>k.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)}):fa({targetNameById:O,confirmDeleteId:u,deletePending:j.isPending,onToggle:(e,t)=>k.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:P,rowKey:e=>e.id,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),a.mode===`form`&&l(ma,{rule:a.rule,...a.seed?{seed:a.seed}:{},targets:_.data??[],actuatable:b.data??[],catalog:dr(v.data?.catalog??[]),taxonomy:v.data?.taxonomy,cameras:S.data??[],gateable:y.data??[],gateableScenes:D,onCancel:()=>o({mode:`closed`}),onSaved:()=>{o({mode:`closed`}),h.refetch()}})]})}function fa(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(v,{variant:`warning`,children:`disabled`}),tr(e.conditions,e.actions?.onTrigger??[])&&l(v,{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:Cn(e.delivery)}),!Tn(e.delivery)&&l(v,{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(y,{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(Qi,{ruleId:n.id,ruleName:n.name,...n.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:n.conditions.devices[0]}}),e.onTest&&l(x,{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(Ee,{className:`h-3.5 w-3.5`})}),l(Ai,{ruleId:n.id,ruleName:n.name,exempt:tr(n.conditions,n.actions?.onTrigger??[])}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onEdit(n),title:`Edit`,children:l(Oe,{className:`h-3.5 w-3.5`})}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(n),title:`Duplicate`,children:l(Te,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===n.id?t(i,{children:[t(x,{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(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(n.id),title:`Delete`,children:l(Ue,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function pa(e){let t=fa(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:ii(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:ai(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:In(e.throttle.cooldownSec)})},...n(`enabled`),...n(`actions`)]}function ma({rule:e,seed:n,targets:a,catalog:o,taxonomy:u,cameras:f,gateable:g,gateableScenes:_,actuatable:C,onSaved:E,onCancel:D}){let O=d(),k=e!=null&&e.id.length>0,[j,M]=s(()=>e?rr(e):nr(n?.delivery,n?.conditions)),[N,F]=s(null),[I,ee]=s(null),[te,ne]=s(Sr),L=e=>M(t=>({...t,...e})),re=k&&e?{throttle:e.throttle}:void 0,ie=c({mutationFn:async()=>{let t=mr(j,re,o);k&&e?await O.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t}):await O.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:E,onError:e=>F(e instanceof Error?e.message:`Save failed`)}),ae=c({mutationFn:async()=>{let e=mr(j,re,o);return(await O.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>ee(null),onSuccess:e=>ee(e),onError:e=>F(e instanceof Error?e.message:`Test failed`)}),oe=j.targetIds.map(e=>a.find(t=>t.id===e)?.name??e),se=e=>L({targetIds:j.targetIds.includes(e)?j.targetIds.filter(t=>t!==e):[...j.targetIds,e]}),ce=r({queryKey:[`userManagement`,`listUsers`],queryFn:()=>O.trpcClient.userManagement.listUsers.query()}).data,le=e=>L({targetUsers:j.targetUsers.includes(e)?j.targetUsers.filter(t=>t!==e):[...j.targetUsers,e]}),ue=Sn.find(e=>e.value===j.delivery)?.hint,de=ir(j),fe=En(j.delivery),pe=vn(yn(j)),me=xr(j),he=tr(j.conditions,j.actions.sequences),ge=j.conditions.identities!==void 0||j.conditions.plates!==void 0,_e=yr(j.delivery,j.conditions),ve=_e.some(e=>e.key===te)?te:Sr;return Tn(j.delivery)?l(S,{open:!0,onOpenChange:e=>!e&&D(),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(Ce,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),l(`span`,{className:`truncate`,children:k?`Edit ${e?.name}`:`New notification rule`})]}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:D,children:`Cancel`})]}),N&&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:N}),k&&e&&l(`div`,{className:`shrink-0 mb-3`,children:l(Gi,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??`camera ${String(e)}`})}),t(A,{value:ve,onValueChange:e=>ne(Cr(e)??te),className:`flex min-h-0 flex-1 flex-col`,children:[l(w,{className:`mb-3 shrink-0`,children:_e.map(e=>l(T,{value:e.key,children:e.label},e.key))}),t(m,{className:`pr-1`,children:[t(P,{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(h,{value:j.name,onChange:e=>L({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(y,{checked:j.enabled,onCheckedChange:e=>L({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),l(b,{value:j.delivery,onChange:e=>{let t=wn(e.target.value);t&&L({delivery:t})},options:Sn.map(e=>({value:e.value,label:e.label}))}),ue&&l(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:ue})]}),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:j.targetIds.includes(e.id),onChange:()=>se(e.id),className:`accent-primary`}),l(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&l(v,{variant:`warning`,children:`disabled`})]},e.id))})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(ce??[]).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:(ce??[]).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:j.targetUsers.includes(e.id),onChange:()=>le(e.id),className:`accent-primary`}),l(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&l(v,{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(P,{value:`devices`,className:`space-y-4`,children:l(Di,{devices:C,value:j.deviceIds,onChange:e=>L({deviceIds:e}),loading:C.length===0})}),l(P,{value:`actions`,className:`space-y-4`,children:l(Mt,{value:j.actions,onChange:e=>L({actions:e}),devices:C})}),t(P,{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(h,{type:`number`,min:0,max:Fn,step:1,value:String(j.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=Ln(e.target.value);t!==void 0&&L({cooldownSec:t})}}),t(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[fe?`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(Fn),` (24 hours).`]})]}),j.delivery===`immediate`?t(`div`,{children:[t(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[l(y,{checked:j.waitForEnhancement,onCheckedChange:e=>L({waitForEnhancement:e}),"aria-label":`wait for recognition`,disabled:!ge}),`Wait for the face or plate before notifying`]}),l(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:ge?`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(y,{checked:j.snoozeAllowGlobal,onCheckedChange:e=>L({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:he}),`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`}),he?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:Zn.map(e=>{let t=j.snoozeOptions??Xn,n=t.includes(e);return l(x,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>L({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Qn(e)},e)})}),l(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:j.snoozeOptions===void 0?`Not set — the notification offers the defaults (${Xn.map(Qn).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.`:j.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.`}),j.snoozeOptions!==void 0&&l(x,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>L({snoozeOptions:void 0}),children:`Back to the defaults`})]})]}),k&&e&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Silence it now`}),l(Ai,{ruleId:e.id,ruleName:e.name,exempt:he,variant:`full`})]})]}),t(P,{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(b,{value:String(j.priority),onChange:e=>L({priority:Number(e.target.value)}),options:Yn.map(e=>({value:String(e.value),label:e.label}))})]}),!pe.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.`}),pe.carriesMedia&&pe.mediaBlurb!==void 0&&l(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:pe.mediaBlurb}),pe.carriesMedia&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),l(b,{value:j.mediaAttach,onChange:e=>{let t=zn(e.target.value);t&&L({mediaAttach:t})},options:Rn.map(e=>({value:e.value,label:e.label}))}),l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Rn.find(e=>e.value===j.mediaAttach)?.description}),t(`div`,{className:`mt-2 space-y-1`,children:[pe.carriesSubjectCrop&&t(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[l(`input`,{type:`checkbox`,checked:j.mediaZoneCrop,onChange:e=>L({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:j.mediaGif,onChange:e=>L({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:j.mediaClip,onChange:e=>L({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(j.mediaGif||j.mediaClip)&&t(`div`,{className:`mt-2`,children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),l(b,{value:j.mediaProfile??``,onChange:e=>L({mediaProfile:Un(e.target.value)}),options:Hn.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(b,{value:j.mediaClipSpeed===void 0?``:String(j.mediaClipSpeed),onChange:e=>L({mediaClipSpeed:_r(e.target.value)}),options:gr.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.`})]})]}),pe.carriesMedia&&pe.carriesSubjectCrop&&t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),l(b,{value:j.mediaFrame??``,onChange:e=>L({mediaFrame:Vn(e.target.value)}),options:Bn.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(h,{value:j.templateTitle,onChange:e=>L({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:j.templateBody,onChange:e=>L({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(P,{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:fe?`Which system events`:br(j.conditions)??`Conditions`}),j.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).`}),j.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.`}),fe&&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(di,{catalog:o,taxonomy:u,delivery:j.delivery,conditions:j.conditions,schedule:j.schedule,deviceIds:j.deviceIds,cameras:f,gateable:g,gateableScenes:_,onConditionsChange:e=>L({conditions:e}),onScheduleChange:e=>L({schedule:e})})]}),k&&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(Qi,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...j.deviceIds[0]===void 0?{}:{fallbackDeviceId:j.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.`})]}),!fe&&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(x,{size:`sm`,variant:`outline`,type:`button`,disabled:ae.isPending||!ar(j),onClick:()=>{F(null),ae.mutate()},children:[ae.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Ee,{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.`}),I!==null&&l(ga,{delivery:j.delivery,results:I,targetNames:oe})]})]})]})]}),me.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 `,me.length,` condition`,me.length===1?``:`s`,` this kind of rule cannot use:`]}),me.map(e=>t(`p`,{children:[l(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),de.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:de.map(e=>l(`p`,{children:e},e))}),t(`div`,{className:`flex shrink-0 justify-end gap-2 mt-4`,children:[l(x,{variant:`secondary`,size:`sm`,type:`button`,onClick:D,children:`Cancel`}),t(x,{size:`sm`,type:`button`,disabled:ie.isPending||!ar(j),onClick:()=>{F(null),ie.mutate()},children:[ie.isPending&&l(R,{className:`h-3.5 w-3.5 animate-spin`}),k?`Save changes`:`Create rule`]})]})]})}):l(ha,{rule:e,onCancel:D})}function ha({rule:e,onCancel:n}){let r=Object.keys(e?.conditions??{});return l(S,{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(Ce,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),l(v,{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(x,{variant:`secondary`,size:`sm`,type:`button`,onClick:n,children:`Close`})})]})})}function ga({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(we,{className:`h-3.5 w-3.5 shrink-0 text-success`}):l(Fe,{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 _a=[{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 va(e){return _a.find(t=>t.value===e)?.value}function ya(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function ba(e){return``}var xa={x:.25,y:.25,w:.5,h:.5},Sa={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Ca(){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:xa,occupancy:Sa,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function wa(e){return e.deviceId!==null}function Ta(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Ea(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Da(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 Oa(e){if(e.deviceId===null)return null;let t=e.trigger,n=Ea(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:ka(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 ka(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 Aa(e){return Math.min(1,Math.round((e+.05)*100)/100)}function ja(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 Ma(e){let t=Ca(),n=e.conditions,r=ja(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:Aa(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Aa(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Aa(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:ba(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Na(n.occupancy)},onlyRuleId:e.id}}function Na(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 Pa(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 Fa(e){return{form:Ma(e),caveats:Pa(e),ruleName:e.name}}var Ia=null;function La(e){Ia=e}function Ra(){return Ia}function za(){Ia=null}var Ba=[`n/a`,`clear`,`suppressed`,`bypassed`],Va=[`live`,`none`,`unavailable`,`unattachable`];function Ha(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ua(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Wa(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Ga(e){if(!Ha(e))return null;let t=Ua(e,`ruleId`),n=Ua(e,`ruleName`),r=Ua(e,`cooldown`),i=Ba.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Ua(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Wa(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:Wa(e,`targetIds`)}}function Ka(e){if(!Ha(e))return null;let t=Ua(e,`recordId`),n=Ua(e,`delivery`),r=Ua(e,`still`),i=Va.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=Ga(e);t!==null&&o.push(t)}let s=Ua(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Wa(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function qa(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 Ja=new Set([`sensor`,`control`,`custom`]);function Ya({form:e,cameras:n,taxonomy:r,kinds:i,kindsLoading:a,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=fe(`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(Xa,{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(ln,{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(Ar,{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(Za,{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(Tr,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):l(Er,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),t(`div`,{children:[l(`label`,{className:H,children:`Zones the subject is in`}),l(Ar,{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(b,{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 Xa({form:e,kinds:n,loading:r,onPatch:a}){let o=n.filter(e=>Ja.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(b,{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(h,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>a({sourceDeviceId:Ta(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(h,{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 Za({form:e,cameras:n,taxonomy:r,onPatch:a}){let o=e.deviceId===null?[]:[e.deviceId],s=fe(`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(Ar,{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(b,{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(h,{type:`number`,min:0,className:`w-20`,value:String(u.count),onChange:e=>d({count:Ta(e.target.value)??0})})]}),t(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,l(h,{type:`number`,min:0,className:`w-20`,value:String(u.previousCount),onChange:e=>d({previousCount:Ta(e.target.value)??0})})]}),t(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,l(h,{type:`number`,min:1,className:`w-20`,value:String(u.threshold),onChange:e=>d({threshold:Ta(e.target.value)??1})})]}),t(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[l(y,{checked:u.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function Qa({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(y,{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(b,{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(Ar,{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(y,{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(h,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[n]),onChange:t=>r({bbox:{...e.bbox,[n]:Ta(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(h,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:Da(Date.now())}),children:`Set`}):l(x,{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(b,{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 $a({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(y,{checked:e,onCheckedChange:a,"aria-label":n}),n,i&&l(v,{variant:`danger`,children:`actuates devices`})]}),l(`p`,{className:U,children:r})]})}e();var eo={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.`},to={"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 no({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:qa(e)}),t(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[l(ro,{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:eo[e.still],children:[`still `,l(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&t(v,{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(io,{outcome:e,targetName:n},e.ruleId))})]})}function ro({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(x,{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(Te,{className:`h-3 w-3`})}),n&&l(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function io({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(we,{className:`h-3.5 w-3.5 shrink-0 text-success`}):l(Fe,{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:to[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 ao=`pipeline-analytics`,oo=`nc.injectTestEvent`;function so(){let e=d(),[i,a]=s(()=>Ra()?.form??Ca()),[o]=s(()=>Ra()?.caveats??[]),[f]=s(()=>Ra()?.ruleName??null);u(()=>za(),[]);let[p,m]=s(null),[_,v]=s(!1),[y,S]=s(null),w=e=>a(t=>({...t,...e})),T=r({queryKey:sa,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===de.Camera).map(e=>({id:e.id,name:e.name}))}),E=r({queryKey:oa,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),D=r({queryKey:ia,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),O=r({queryKey:aa,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??[],P=n(()=>{let e=new Map;for(let t of O.data??[])e.set(t.id,t.name);return e},[O.data]),F=c({mutationFn:async()=>{let t=Oa(i);if(t===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:ao,action:oo,input:t})},onMutate:()=>{m(null),v(!1),S(null)},onSuccess:e=>{let t=Ka(e);m(t),v(t===null)},onError:e=>S(e instanceof Error?e.message:`The simulation failed.`)}),I=ya(i.trigger),ee=D.data?.find(e=>e.id===i.onlyRuleId);return t(z,{icon:Ee,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(He,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),l(`span`,{children:e.note})]},e.conditionId))}),t(g,{className:`space-y-4`,children:[t(`div`,{children:[l(`label`,{className:H,children:`Camera`}),l(b,{"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:Ta(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(b,{"data-testid":`simulate-trigger`,value:i.trigger,options:_a.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=va(e.target.value);if(!t)return;let n=ba(i.trigger);w({trigger:t,source:i.source===``||i.source===n?ba(t):i.source})}}),t(`p`,{className:U,children:[_a.find(e=>e.value===i.trigger)?.hint,` Only rules whose trigger is `,l(`span`,{className:`text-foreground`,children:I}),` are candidates.`]})]}),l(Ya,{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(h,{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(Dr,{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(Dr,{value:i.labelConfidence,min:0,max:1,step:.05,onChange:e=>w({labelConfidence:e})})]}),t(`div`,{children:[l(`label`,{className:H,children:`Importance`}),l(Dr,{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(Dr,{value:i.dwellSeconds,min:0,step:1,onChange:e=>w({dwellSeconds:e})})]})]})]})]}),l(Qa,{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($a,{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($a,{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($a,{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(b,{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(b,{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&&ee===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.`]})]})]}),y!==null&&l(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:y}),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(x,{size:`sm`,type:`button`,disabled:F.isPending||!wa(i),onClick:()=>F.mutate(),children:[F.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(Ee,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),_&&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(no,{result:p,targetName:e=>P.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 co({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(He,{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 lo({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(We,{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 uo({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(h,{className:`flex-1`,value:c,placeholder:`Search a camera…`,leftSlot:l(Ne,{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 fo({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(v,{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(h,{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 po({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(y,{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 mo({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(h,{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 ho({open:e,ruleName:n,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:u=!1}){return e?l(S,{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(De,{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(x,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),l(x,{size:`sm`,type:`button`,disabled:a||u,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?`Sending…`:`Produce and send`})]})]})})}):null}function go(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 _o=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function vo(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function yo(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>_o[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${vo(t.startMinute)}–${vo(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function bo(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${go(Math.round(r/1e3))} ago`}function xo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function So(e){return Array.isArray(e)?`[${e.map(So).join(`,`)}]`:xo(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${So(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function X(e,t){return So(e)===So(t)}function Co(e){return e.map(e=>({targetId:e}))}var Z=`pipeline-analytics`,wo=`nc.getTexts`,To=`nc.setLanguage`,Eo=`nc.setTextOverrides`,Do={en:`English`,it:`Italiano`};function Oo(e){return e===`en`||e===`it`}function ko(e){return e===`override`||e===`shipped`||e===`fallback`}function Ao(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jo(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 Mo(e){if(!Ao(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`||!Oo(r)||!ko(o)||i!==null&&typeof i!=`string`)return null;let s=jo(e.placeholders),c=jo(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 No(e){if(!Ao(e))return null;let{language:t,activeLanguage:n}=e;if(!Oo(t)||!Oo(n))return null;let r=jo(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Oo(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=Mo(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Po(e,t){return t.get(e.key)??e.override??e.shipped}function Fo(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 Io(e,t){return Object.keys(Fo(e,t)).length}function Lo(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 Ro(e){return e.placeholders.length===0?`No variables — this text is printed as written.`:`Variables: ${e.placeholders.map(e=>`{{${e}}}`).join(` `)}`}function zo(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 Bo=`nc.listSummaryRules`,Vo=`nc.upsertSummaryRule`,Ho=`nc.deleteSummaryRule`,Uo=`nc.testSummaryRule`,Wo=3600,Go=86400,Ko=3600,qo=3600,Jo=3*36e5,Yo=[`importance`,`recency`,`dwell`],Xo={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},Zo=[`none`,`tiles`,`all`],Qo=`none`,$o={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},es=[`en`,`it`],ts=[`deliver-without-text`,`skip`],ns=2048,rs=2e3;function is(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function as(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 os(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 ss(e){if(e!==void 0)return typeof e==`string`?e:null}function cs(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function ls(e){return Yo.some(t=>t===e)}function us(e){return e===void 0?Qo:Zo.find(t=>t===e)??null}function ds(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=as(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=ss(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 fs(e){if(!Q(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=ds(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 ps(e){if(e==null)return;if(!Q(e))return null;let t=e.classes===void 0?void 0:os(e.classes),n=e.classesExclude===void 0?void 0:os(e.classesExclude),r=e.zones===void 0?void 0:os(e.zones);if(t===null||n===null||r===null)return null;let i=cs(e.minImportance),a=cs(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 ms(e){if(e==null)return;if(!Q(e))return null;let t=ss(e.title),n=ss(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function hs(e){return es.some(t=>t===e)}function gs(e){return ts.some(t=>t===e)}function _s(e){if(e==null)return;if(!Q(e)||typeof e.enabled!=`boolean`)return null;let t=ss(e.profileId),n=ss(e.prompt);if(t===null||n===null)return null;let r=cs(e.maxImagePx),i=cs(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!hs(a))return null;let o=e.onFailure;return o!==void 0&&!gs(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 vs(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 ys(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`||!ls(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=as(e.deviceIds),u=fs(e.window),d=vs(e.targets);if(l===null||u===null||d===null)return null;let f=ps(e.filters),p=ms(e.template);if(f===null||p===null)return null;let m=ss(e.captionText),h=cs(e.generatedAt);if(m===null||h===null)return null;let g=us(e.captions);if(g===null)return null;let _=_s(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 bs(e){if(!Q(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=ys(n);if(e===null)return null;t.push(e)}return t}function xs(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=cs(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=cs(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=ss(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 Ss(){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:Qo,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function Cs(e){let t=Ss(),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 ws(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Ts(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 Es(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 Ds(e){return Co(e.targetIds)}function Os(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 ks(e){let t=Ts(e),n=Es(e),r=Os(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:ws(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Ds(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 As(e,t){let n=ks(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 js(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 ${Wo}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${Go}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 ${Ko}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 ${qo}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 ${rs} 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 ${ns} 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 Ms(e){return js(e).length===0}function Ns(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 Ps=[{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`]}],Fs=`rule`;function Is(e){return Ps.find(t=>t.key===e)?.key}function Ls(e){return e.kind===`motion`?`Motion · ${go(e.quietSeconds)} quiet · max ${go(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${yo(e.schedule)}`}function Rs(e,t){return bo(e,t,`Never run`)}function zs(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 ≥ ${go(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function Bs(e){return{windowStartMs:e-Jo,windowEndMs:e}}e();var Vs=[`rule`,`cameras`,`tiles`,`matched`,`from`,`to`,`ai`],Hs={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},Us={en:`English`,it:`Italiano`};function Ws(e){return Yo.find(t=>t===e)}function Gs(e){return Zo.find(t=>t===e)}function Ks(e){return es.find(t=>t===e)??``}function qs(e){return ts.find(t=>t===e)}function Js({rule:e,cameras:i,camerasLoading:a,targets:o,taxonomy:u,onSaved:f,onCancel:g}){let _=d(),[v,y]=s(()=>e===null?Ss():Cs(e)),[C,E]=s(null),[D,O]=s(Fs),k=e=>y(t=>({...t,...e})),j=n(()=>{let e=fe(`occupancy`,u);return e===null?[]:e.groups.flatMap(e=>e.options)},[u]),{options:M,loading:N}=an(v.deviceIds,i.map(e=>({id:e.id,name:e.name}))),F=r({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>_.trpcClient.llm.listProfiles.query({}),retry:!1}),I=(F.data??[]).filter(e=>e.supportsVision),ee=c({mutationFn:async()=>{let t=e===null?{rule:ks(v)}:{ruleId:e.id,patch:As(v,e)};await _.trpcClient.addons.custom.mutate({addonId:Z,action:Vo,input:t})},onSuccess:f,onError:e=>E(e instanceof Error?e.message:`Save failed`)}),te=v.mosaicCaptions===`all`,ne=js(v),L=Ns(v),re=Ms(v)&&!ee.isPending,ie=Ps.some(e=>e.key===D)?D:Fs;return l(S,{open:!0,onOpenChange:e=>!e&&g(),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 summary`:`Edit ${e.name}`})]}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:g,children:`Cancel`})]}),C!==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:C}),t(`div`,{className:`shrink-0 space-y-2`,children:[l(co,{problems:ne,testId:`summary-problems`}),l(lo,{warnings:L,testId:`summary-warnings`})]}),t(A,{value:ie,onValueChange:e=>O(Is(e)??D),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[l(w,{className:`mb-3 shrink-0`,children:Ps.map(e=>l(T,{value:e.key,children:e.label},e.key))}),t(m,{className:`pr-1`,children:[t(P,{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(h,{value:v.name,onChange:e=>k({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),l(`div`,{className:`pb-1.5`,children:l(po,{label:`Enabled`,checked:v.enabled,onChange:e=>k({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(uo,{cameras:i,value:v.deviceIds,loading:a,onChange:e=>k({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})})]}),l(P,{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(b,{value:v.windowKind,options:[{value:`motion`,label:`Motion — opened and closed by activity`},{value:`schedule`,label:`Schedule — fixed weekly windows`}],onChange:e=>k({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),v.windowKind===`motion`?t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Quiet period (seconds)`,value:v.quietSeconds,min:30,max:Wo,onChange:e=>k({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:v.maxWindowSeconds,min:60,max:Go,onChange:e=>k({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(Kr,{value:v.schedule,onChange:e=>k({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:v.barrierSeconds,min:0,max:Ko,onChange:e=>k({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(P,{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(ln,{options:j,value:v.classes,onChange:e=>k({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(ln,{options:j,value:v.classesExclude,onChange:e=>k({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),t(`div`,{children:[l(`label`,{className:K,children:`Zones`}),l(ln,{options:M,value:v.zones,onChange:e=>k({zones:e}),loading:N,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:v.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>k({minImportance:e}),hint:`The pipeline's own score, 0–1. Empty keeps everything.`,testId:`summary-min-importance`}),l(Y,{label:`Minimum stay (seconds)`,value:v.minDwellSeconds,min:0,max:qo,emptyPlaceholder:`any`,onChange:e=>k({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]}),l(po,{label:`Include parked objects`,checked:v.includeStationary,onChange:e=>k({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(P,{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:v.maxTiles,min:1,max:24,onChange:e=>k({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(b,{value:v.rank,options:Yo.map(e=>({value:e,label:Xo[e]})),onChange:e=>{let t=Ws(e.target.value);t!==void 0&&k({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(b,{value:v.mosaicCaptions,options:Zo.map(e=>({value:e,label:$o[e]})),onChange:e=>{let t=Gs(e.target.value);t!==void 0&&k({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(h,{value:v.captionText,disabled:!te,onChange:e=>k({captionText:e.target.value}),placeholder:`Leave empty for no caption`,"data-testid":`summary-caption`}),l(`p`,{className:q,children:te?`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(P,{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(po,{label:`Have a model describe the window`,checked:v.aiEnabled,onChange:e=>k({aiEnabled:e}),hint:`Off by default. The mosaic and the counts are delivered either way.`,testId:`summary-ai-enabled`}),!v.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(b,{value:v.aiProfileId,disabled:!v.aiEnabled,options:[{value:``,label:`The hub's default vision profile`},...I.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>k({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),l(`p`,{className:q,children:F.isError?`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`:I.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(b,{value:v.aiLanguage,disabled:!v.aiEnabled,options:[{value:``,label:`Don’t ask for a language`},...es.map(e=>({value:e,label:Us[e]}))],onChange:e=>k({aiLanguage:Ks(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:v.aiPrompt,rows:3,maxLength:rs,disabled:!v.aiEnabled,onChange:e=>k({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:v.maxAiImages,min:1,max:8,disabled:!v.aiEnabled,onChange:e=>k({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:v.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!v.aiEnabled,onChange:e=>k({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:v.aiMaxImagePx,min:64,max:ns,emptyPlaceholder:`448`,disabled:!v.aiEnabled,onChange:e=>k({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(b,{value:v.aiOnFailure,disabled:!v.aiEnabled,options:ts.map(e=>({value:e,label:Hs[e]})),onChange:e=>{let t=qs(e.target.value);t!==void 0&&k({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(P,{value:`delivery`,className:`space-y-3`,children:t(J,{title:`Delivery`,children:[l(fo,{targets:o,value:v.targetIds,onChange:e=>k({targetIds:e})}),t(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[l(Y,{label:`Priority`,value:v.priority,min:1,max:5,onChange:e=>k({priority:e??3}),testId:`summary-priority`}),l(po,{label:`Deliver a window that matched nothing`,checked:v.deliverEmpty,onChange:e=>k({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(mo,{title:v.templateTitle,body:v.templateBody,onTitleChange:e=>k({templateTitle:e}),onBodyChange:e=>k({templateBody:e}),variables:Vs,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(x,{size:`sm`,variant:`secondary`,type:`button`,onClick:g,children:`Cancel`}),t(x,{size:`sm`,type:`button`,disabled:!re,onClick:()=>ee.mutate(),children:[ee.isPending&&l(R,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}e();var Ys=[`notificationSummaries`,`listSummaryRules`],Xs=[`deviceManager`,`listAll`,`forSummaries`],Zs=`One window, one picture: every camera’s best moments as a single mosaic.`;function Qs(){let e=d(),[n,i]=s({mode:`closed`}),[a,o]=s(null),[u,f]=s(null),[p,m]=s(null),[h,_]=s(!1),v=r({queryKey:Ys,queryFn:async()=>{let t=bs(await e.trpcClient.addons.custom.mutate({addonId:Z,action:Bo,input:{}}));return _(t===null),t}}),y=r({queryKey:Xs,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).filter(e=>e.type===de.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),staleTime:6e4}),b=r({queryKey:aa,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),S=r({queryKey:oa,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),w=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:Vo,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void v.refetch()}),T=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:Ho,input:{ruleId:t}}),onSuccess:()=>{o(null),v.refetch()}}),E=c({mutationFn:async t=>xs(await e.trpcClient.addons.custom.mutate({addonId:Z,action:Uo,input:{ruleId:t,...Bs(Date.now())}})),onSuccess:e=>{f(null),m(e)}}),D=v.data??[],O=(b.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),k=new Map(O.map(e=>[e.id,e.name])),A=t(x,{size:`sm`,type:`button`,onClick:()=>i({mode:`form`,rule:null}),"data-testid":`summary-new`,children:[l(ke,{className:`h-3.5 w-3.5`}),`New summary`]});return v.isLoading?l(z,{icon:Je,title:`Summaries`,subtitle:Zs,children:l(R,{className:`h-5 w-5 animate-spin`})}):v.isError||v.data===null?l(z,{icon:Je,title:`Summaries`,subtitle:Zs,children:l(C,{title:`Summary rules are not available on this hub`,message:h?`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:Je,title:`Summaries`,subtitle:Zs,actions:A,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(x,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>m(null),children:`Dismiss`})]}),D.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(g,{children:l(N,{columns:$s({nowMs:Date.now(),targetNameById:k,confirmDeleteId:a,deletePending:T.isPending,onToggle:(e,t)=>w.mutate({ruleId:e.id,enabled:t}),onEdit:e=>{is(e)&&i({mode:`form`,rule:e})},onTest:f,onAskDelete:o,onConfirmDelete:e=>T.mutate(e.id)}),rows:D,rowKey:e=>e.id,minWidthPx:860,bordered:!1,mobileMode:`scroll`,maxBodyHeight:j})}),n.mode===`form`&&l(Js,{rule:n.rule,cameras:y.data??[],camerasLoading:y.isLoading,targets:O,taxonomy:S.data?.taxonomy,onCancel:()=>i({mode:`closed`}),onSaved:()=>{i({mode:`closed`}),v.refetch()}}),l(ho,{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 $s(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(v,{variant:`warning`,children:`disabled`}),!is(e)&&l(v,{variant:`warning`,children:`read-only`}),e.ai?.enabled===!0&&l(v,{variant:`info`,children:`AI`}),e.ai!==void 0&&!e.ai.enabled&&l(v,{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:Ls(e.window)})},{key:`filters`,header:`Keeps`,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:zs(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:Rs(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>l(y,{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(x,{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(Ee,{className:`h-3.5 w-3.5`})}),l(x,{size:`sm`,variant:`ghost`,type:`button`,disabled:!is(n),onClick:()=>e.onEdit(n),"aria-label":`edit ${n.name}`,"data-testid":`summary-edit-${n.id}`,children:l(Oe,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===n.id?t(`span`,{className:`flex items-center gap-1`,children:[l(x,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(n),"data-testid":`summary-delete-confirm-${n.id}`,children:`Delete`}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):l(x,{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(Ue,{className:`h-3.5 w-3.5`})})]})}]}var ec=e=>typeof e==`string`&&e.length>0;function tc(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 nc(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function rc(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];ec(i)&&n.push({mediaType:r,url:i})}return n}function ic(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=ec(r.label),i=ec(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 ac(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=rc(e,t.attachmentUrls),i=ic(e,t.actions),a=e.ttl&&ec(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:nc(e,t.format),priority:oc(t.priority),...ec(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&ec(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&ec(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...ec(t.tag)?{tag:t.tag}:{}}}function oc(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function sc(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 cc(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var lc={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 uc(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function dc(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])uc(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function fc(e,t,n){let r=cc(e);return uc(e,t)?{...r,body:n,attachmentUrls:{[t]:lc[t]}}:{...r,body:n}}function pc(e,t){let n=cc(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return fc(e,`image`,`Test notification with an image.`);case`gif`:return fc(e,`gif`,`Test notification with an animation.`);case`video`:return fc(e,`video`,`Test notification with a video.`);case`audio`:return fc(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=sc(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 mc={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},hc=`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 gc({target:e,kind:r,open:i,onClose:a}){let o=d(),u=n(()=>tc(r.caps),[r.caps]),h=n(()=>dc(r.caps),[r.caps]),[g,_]=s(()=>cc(r.caps)),[y,b]=s(null),C=n(()=>ac(r.caps,g),[r.caps,g]),w=g.body.length,T=w>u.bodyMaxLen,E=e=>_(t=>({...t,...e})),D=c({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:ac(r.caps,g)}),onMutate:()=>b(null),onSuccess:e=>b(e),onError:e=>b({success:!1,error:e instanceof Error?e.message:`Test failed`})}),A=e=>{_(pc(r.caps,e)),b(null)},j=(e,t,n)=>{let r=g.actions.length>0?[...g.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},E({actions:r})};return l(S,{open:i,onOpenChange:e=>!e&&a(),children:t(p,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[l(f,{children:t(O,{children:[`Test "`,e.name,`" (`,r.label,`)`]})}),t(m,{className:`space-y-4 pr-1`,children:[l(`div`,{className:`flex flex-wrap gap-1.5`,children:h.map(e=>l(x,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>A(e),children:mc[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:hc,value:g.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===g.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(v,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&l(v,{variant:`info`,children:`silent`}),e.flags?.noPush&&l(v,{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): `,g.priority]}),l(`input`,{type:`range`,min:1,max:5,step:1,value:g.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:g.format===e,onChange:()=>E({format:e})}),e]},e))})]}),t(`div`,{children:[l(`label`,{className:$,children:`Title`}),l(`input`,{className:hc,value:g.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:`${hc} min-h-[80px] resize-y`,value:g.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:hc,placeholder:`${e} URL`,value:g.attachmentUrls[e]??``,onChange:t=>E({attachmentUrls:{...g.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:hc,placeholder:`label`,value:g.actions[n]?.label??``,onChange:e=>j(n,`label`,e.target.value)}),l(`input`,{className:hc,placeholder:`url`,value:g.actions[n]?.url??``,onChange:e=>j(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:hc,value:g.clickUrl,onChange:e=>E({clickUrl:e.target.value})})]}),u.showSound&&t(`div`,{children:[l(`label`,{className:$,children:`Sound`}),l(`input`,{className:hc,value:g.sound,onChange:e=>E({sound:e.target.value})})]}),u.showTtl&&t(`div`,{children:[l(`label`,{className:$,children:`TTL (seconds)`}),l(`input`,{className:hc,type:`number`,value:g.ttl,onChange:e=>E({ttl:e.target.value})})]}),u.showTag&&t(`div`,{children:[l(`label`,{className:$,children:`Tag`}),l(`input`,{className:hc,value:g.tag,onChange:e=>E({tag:e.target.value})})]})]}),y&&l(_c,{result:y}),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(k,{children:[l(x,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),t(x,{size:`sm`,type:`button`,disabled:D.isPending||g.body.length===0,onClick:()=>D.mutate(),children:[D.isPending?l(R,{className:`h-3.5 w-3.5 animate-spin`}):l(De,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function _c({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(we,{className:`h-3.5 w-3.5 text-success`}):l(Fe,{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 vc(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 yc(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 bc(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 xc(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 Sc=[`notificationOutput`,`listTargets`],Cc=[`notificationOutput`,`listTargetKinds`],wc=[`userManagement`,`listUsers`],Tc=`ownerUserId`;function Ec(e){let t=e.config[Tc];return typeof t==`string`&&t.length>0?t:null}function Dc(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(Oc,{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(v,{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=Ec(t);return n===null?l(v,{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(y,{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(x,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(n),title:`Test`,children:l(De,{className:`h-3.5 w-3.5`})}),l(x,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onEdit(n,r),title:`Edit`,children:l(Oe,{className:`h-3.5 w-3.5`})}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(n),title:`Delete`,children:l(Ue,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function Oc({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 kc(){let e=d(),[i,a]=s({mode:`closed`}),[o,u]=s(null),f=r({queryKey:Sc,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),p=r({queryKey:Cc,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),m=n(()=>p.data??[],[p.data]),h=n(()=>{let e=new Map;for(let t of m)e.set(t.kind,t);return e},[m]),_=r({queryKey:wc,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),v=n(()=>{let e=new Map;for(let t of _.data??[])e.set(t.id,t.username);return e},[_.data]),y=c({mutationFn:t=>e.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:t.target.addonId,targetId:t.target.id,enabled:t.enabled}),onSuccess:()=>void f.refetch()}),b=c({mutationFn:t=>e.trpcClient.notificationOutput.deleteTarget.mutate({addonId:t.addonId,targetId:t.id}),onSuccess:()=>void f.refetch()}),S=o?h.get(o.kind):void 0;return t(z,{icon:Re,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(x,{size:`sm`,type:`button`,onClick:()=>a({mode:`pick-kind`}),children:[l(ke,{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(g,{children:l(N,{columns:Dc({kindByKey:h,userNameById:v,onToggle:(e,t)=>y.mutate({target:e,enabled:t}),onTest:u,onEdit:(e,t)=>a({mode:`form`,kind:t,target:e}),onDelete:e=>b.mutate(e)}),rows:f.data??[],rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),i.mode===`pick-kind`&&l(Ac,{kinds:m,onCancel:()=>a({mode:`closed`}),onPick:e=>a({mode:`form`,kind:e,target:null})}),i.mode===`form`&&l(jc,{kind:i.kind,target:i.target,users:_.data??[],onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),f.refetch()}}),o&&S&&l(gc,{target:o,kind:S,open:!0,onClose:()=>u(null)})]})}function Ac({kinds:e,onPick:r,onCancel:i}){let a=n(()=>vc(e),[e]);return t(g,{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(x,{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(Oc,{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(v,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})}function jc({kind:e,target:r,users:i,onSaved:a,onCancel:o}){let u=d(),f=n(()=>yc(e.configSchema),[e.configSchema]),p=n(()=>r?.config??{},[r]),[m,h]=s(r?.name??e.label),[v,y]=s(()=>r?xc(r.config,f):{}),[S,C]=s(null),[w,T]=s(null),[E,D]=s(r?Ec(r)??``:``),O=c({mutationFn:()=>u.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:v}),onSuccess:e=>C(e),onError:e=>T(e instanceof Error?e.message:`Discovery failed`)}),k=c({mutationFn:()=>{let{[Tc]:t,...n}=bc(v,p,f),i=E===``?n:{...n,[Tc]:E},a={id:r?.id??`${e.kind}-${Date.now()}`,name:m,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=>{h(e.suggestedName),y(t=>({...t,...e.config})),C(null)};return t(g,{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(Oc,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),r?`Edit ${r.name}`:`Add ${e.label} target`]}),l(x,{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:m,onChange:e=>h(e.target.value)})]}),t(`div`,{children:[l(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),l(b,{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(x,{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(Ne,{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(_,{schema:e.configSchema,values:v,onChange:y}),t(`div`,{className:`flex justify-end gap-2`,children:[l(x,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:`Cancel`}),t(x,{size:`sm`,type:`button`,disabled:k.isPending||m.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 Mc=`notificationTexts`,Nc=`Every sentence the Notification Center can print — and your wording for it.`;function Pc({entry:e,value:n,busy:r,onChange:i,onReset:a}){let o=zo(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(v,{variant:`info`,children:`customised`}):null,e.source===`fallback`?l(v,{variant:`warning`,children:`English fallback`}):null]}),t(`div`,{className:`flex items-start gap-2`,children:[l(h,{value:n,disabled:r,onChange:e=>i(e.target.value),className:`flex-1 font-mono text-xs`,"data-testid":`text-input-${e.key}`}),l(x,{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(Me,{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:Ro(e)}),o===null?null:l(`p`,{className:`text-xs text-warning`,children:o})]})}function Fc(){let e=d(),i=o(),[a,u]=s(null),[f,p]=s(``),[m,_]=s(new Map),[v,y]=s(!1),S=r({queryKey:[Mc,a??`hub`],queryFn:async()=>{let t=No(await e.trpcClient.addons.custom.mutate({addonId:Z,action:wo,input:a===null?{}:{language:a}}));return y(t===null),t}}),w=()=>{_(new Map),i.invalidateQueries({queryKey:[Mc]})},T=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:To,input:{language:t}}),onSuccess:w}),E=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:Eo,input:t}),onSuccess:w}),D=S.data??null,O=n(()=>D===null?[]:Lo(D.entries,f),[D,f]);if(S.isLoading)return l(z,{icon:Ye,title:`Texts`,subtitle:Nc,children:l(R,{className:`h-5 w-5 animate-spin`})});if(S.isError||D===null)return l(z,{icon:Ye,title:`Texts`,subtitle:Nc,children:l(C,{title:`The notification text catalog is not available on this hub`,message:v?`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=Fo(D.entries,m),M=Io(D.entries,m),N=D.entries.filter(e=>e.override!==null).length,P=D.languages.map(e=>({value:e,label:Do[e]})),F=(e,t)=>_(n=>new Map(n).set(e,t)),I=e=>F(e.key,e.shipped);return l(z,{icon:Ye,title:`Texts`,subtitle:Nc,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(g,{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(b,{value:D.activeLanguage,disabled:A,options:P,onChange:e=>{let t=e.target.value;Oo(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(b,{value:k,disabled:A,options:P,onChange:e=>{let t=e.target.value;Oo(t)&&(_(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(Ne,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),l(h,{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(x,{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(Pc,{entry:e,value:Po(e,m),busy:A,onChange:t=>F(e.key,t),onReset:()=>I(e)},e.key))})]})})}var Ic=`nc.listTimelapseRules`,Lc=`nc.upsertTimelapseRule`,Rc=`nc.deleteTimelapseRule`,zc=`nc.testTimelapseRule`,Bc=3600,Vc=3600,Hc=30,Uc=1,Wc=[`image`,`gif`],Gc={image:`Still frame`,gif:`Short animation (GIF)`},Kc=_e({rules:ye(le.extend({readOnly:xe().optional()}))});function qc(e){let t=Kc.safeParse(e);return t.success?t.data.rules:null}function Jc(e){return e.readOnly!==!0}var Yc=_e({produced:ve(),exportId:be().optional(),coveragePercent:ve().optional(),enqueued:ve().optional(),windowStartMs:ve().optional(),windowEndMs:ve().optional(),error:be().optional()});function Xc(e){let t=Yc.safeParse(e);return t.success?t.data:null}function Zc(){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 Qc(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 $c={windows:[{days:[1],startMinute:0,endMinute:60}]};function el(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 tl(e){let t=el(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??$c,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Co(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 nl(e,t){let n=tl(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??rl(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 rl(e){return Math.max(Uc,e/Hc)}function il(e,t,n){return t<=0||n<=0?0:e/t/n}function al(e,t){return e*t*ue}function ol(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 ${Bc}.`),(!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 ${ue}s and ${Vc}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 sl(e){return ol(e).length===0}function cl(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=al(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 ll(e){return yo(e)}function ul(e,t){return bo(e,t,`Never run`)}function dl(e){return e.denseCadenceSec===void 0?{seconds:rl(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}e();var fl=[`camera`,`rule`,`from`,`to`,`detections`,`detectionSummary`,`count_person`],pl=7;function ml(e){return Wc.find(t=>t===e)}function hl({rule:e,cameras:n,camerasLoading:r,targets:a,onSaved:o,onCancel:u}){let f=d(),[g,_]=s(()=>e===null?Zc():Qc(e)),[v,y]=s(null),C=e=>_(t=>({...t,...e})),w=c({mutationFn:async()=>{let t=e===null?{rule:tl(g)}:{ruleId:e.id,patch:nl(g,e)};await f.trpcClient.addons.custom.mutate({addonId:Z,action:Lc,input:t})},onSuccess:o,onError:e=>y(e instanceof Error?e.message:`Save failed`)}),T=ol(g),E=cl(g),D=dl(g),O=il(pl,D.seconds,g.framerate),k=sl(g)&&!w.isPending;return l(S,{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(Le,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),l(`span`,{className:`truncate`,children:e===null?`New timelapse`:`Edit ${e.name}`})]}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:u,children:`Cancel`})]}),v!==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:v}),t(m,{className:`space-y-3 pr-1`,children:[l(co,{problems:T,testId:`timelapse-problems`}),l(lo,{warnings:E,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(h,{value:g.name,onChange:e=>C({name:e.target.value}),placeholder:`e.g. Timelapse ingresso`,"data-testid":`timelapse-name`})]}),l(`div`,{className:`pb-1.5`,children:l(po,{label:`Enabled`,checked:g.enabled,onChange:e=>C({enabled:e}),testId:`timelapse-enabled`})})]})}),l(J,{title:`Cameras`,children:l(uo,{cameras:n,value:g.deviceIds,loading:r,onChange:e=>C({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(Kr,{value:g.schedule,onChange:e=>C({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:g.cadenceSec,min:2,max:Bc,onChange:e=>C({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:g.framerate,min:1,max:60,onChange:e=>C({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(b,{value:g.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:`Automatic (${D.seconds}s)`},{value:`explicit`,label:`Set it myself`}],onChange:e=>C({denseCadenceSec:e.target.value===`auto`?void 0:dl(g).seconds}),"data-testid":`timelapse-dense-mode`}),g.denseCadenceSec!==void 0&&l(h,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(g.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&C({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),t(`p`,{className:q,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,D.seconds,`s and `,g.framerate,` fps a`,` `,pl,`-second passage lasts `,O.toFixed(2),`s on screen; halving the cadence doubles that, and the quiet parts of the night do not change length.`,D.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 (${dl({...g,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),l(Y,{label:`Minimum seconds of video per detection (optional)`,value:g.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>C({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(fo,{targets:a,value:g.targetIds,onChange:e=>C({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(b,{value:g.previewMode,options:Wc.map(e=>({value:e,label:Gc[e]})),onChange:e=>{let t=ml(e.target.value);t!==void 0&&C({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),l(Y,{label:`Priority`,value:g.priority,min:1,max:5,onChange:e=>C({priority:e??3}),testId:`timelapse-priority`})]}),t(`div`,{children:[l(`label`,{className:K,children:`Caption on the preview frame`}),l(h,{value:g.previewTextSet?g.previewText:``,placeholder:`${oe} (shipped default)`,onChange:e=>C({previewText:e.target.value,previewTextSet:!0}),"data-testid":`timelapse-preview-text`}),t(`p`,{className:q,children:[g.previewTextSet&&g.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${oe}).`,g.previewTextSet&&t(i,{children:[` `,l(`button`,{type:`button`,className:`underline`,onClick:()=>C({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),l(mo,{title:g.templateTitle,body:g.templateBody,onTitleChange:e=>C({templateTitle:e}),onBodyChange:e=>C({templateBody:e}),variables:fl,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(x,{size:`sm`,variant:`secondary`,type:`button`,onClick:u,children:`Cancel`}),t(x,{size:`sm`,type:`button`,disabled:!k,onClick:()=>w.mutate(),children:[w.isPending&&l(R,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}e();var gl=[`notificationTimelapses`,`listTimelapseRules`],_l=[`deviceManager`,`listAll`,`forTimelapses`],vl=`A night of recorded footage, assembled into one short video per camera.`;function yl(){let e=d(),[n,i]=s({mode:`closed`}),[a,o]=s(null),[u,f]=s(null),[p,m]=s(null),[h,_]=s(!1),v=r({queryKey:gl,queryFn:async()=>{let t=qc(await e.trpcClient.addons.custom.mutate({addonId:Z,action:Ic,input:{}}));return _(t===null),t}}),y=r({queryKey:_l,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).filter(e=>e.type===de.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),staleTime:6e4}),S=r({queryKey:aa,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),w=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:Lc,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void v.refetch()}),T=c({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:Z,action:Rc,input:{ruleId:t}}),onSuccess:()=>{o(null),v.refetch()}}),E=c({mutationFn:async t=>Xc(await e.trpcClient.addons.custom.mutate({addonId:Z,action:zc,input:t})),onSuccess:e=>{f(null),m(e)}}),D=v.data??[],O=y.data??[],k=new Map(O.map(e=>[e.id,e.name])),A=(S.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),M=new Map(A.map(e=>[e.id,e.name]));return v.isLoading?l(z,{icon:Le,title:`Timelapses`,subtitle:vl,children:l(R,{className:`h-5 w-5 animate-spin`})}):v.isError||v.data===null?l(z,{icon:Le,title:`Timelapses`,subtitle:vl,children:l(C,{title:`Timelapse rules are not available on this hub`,message:h?`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:Le,title:`Timelapses`,subtitle:vl,actions:t(x,{size:`sm`,type:`button`,onClick:()=>i({mode:`form`,rule:null}),"data-testid":`timelapse-new`,children:[l(ke,{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(x,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>m(null),children:`Dismiss`})]}),D.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(g,{children:l(N,{columns:bl({nowMs:Date.now(),cameraNameById:k,targetNameById:M,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:D,rowKey:e=>e.id,minWidthPx:900,bordered:!1,mobileMode:`scroll`,maxBodyHeight:j})}),n.mode===`form`&&l(hl,{rule:n.rule,cameras:O,camerasLoading:y.isLoading,targets:A,onCancel:()=>i({mode:`closed`}),onSaved:()=>{i({mode:`closed`}),v.refetch()}}),l(ho,{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(b,{value:u.deviceId===null?``:String(u.deviceId),options:u.rule.deviceIds.map(e=>({value:String(e),label:k.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 bl(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(v,{variant:`warning`,children:`disabled`}),!Jc(e)&&l(v,{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:ll(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let n=dl(Qc(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:ul(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>l(y,{checked:t.enabled,disabled:!Jc(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(x,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Jc(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(Ee,{className:`h-3.5 w-3.5`})}),l(x,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Jc(n),onClick:()=>e.onEdit(n),"aria-label":`edit ${n.name}`,"data-testid":`timelapse-edit-${n.id}`,children:l(Oe,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===n.id?t(`span`,{className:`flex items-center gap-1`,children:[l(x,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(n),"data-testid":`timelapse-delete-confirm-${n.id}`,children:`Delete`}),l(x,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):l(x,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Jc(n),onClick:()=>e.onAskDelete(n.id),"aria-label":`delete ${n.name}`,"data-testid":`timelapse-delete-${n.id}`,children:l(Ue,{className:`h-3.5 w-3.5`})})]})}]}var xl=`simulate`;function Sl(){let[e,t]=ze();return l(`div`,{className:`flex flex-col p-4`,children:l(Ge,{tabs:[{id:`targets`,label:`Targets`,icon:Re,content:l(kc,{})},{id:`rules`,label:`Rules`,icon:Ce,content:l(da,{onSimulateRule:n=>{La(Fa(n));let r=new URLSearchParams(e);r.set(`tab`,xl),t(r,{replace:!0})}})},{id:xl,label:`Simulate`,icon:Ee,content:l(so,{})},{id:`history`,label:`History`,icon:qe,content:l(vt,{})},{id:`alarm`,label:`Alarm`,icon:Be,content:l(dt,{})},{id:`summaries`,label:`Summaries`,icon:Je,content:l(Qs,{})},{id:`timelapses`,label:`Timelapses`,icon:Le,content:l(yl,{})},{id:`texts`,label:`Texts`,icon:Ye,content:l(Fc,{})}]})})}export{Sl as NotificationsPage,Sl as default};
@@ -1 +0,0 @@
1
- import{K as e}from"./index-DhYfPTfU.js";var t=e(`circle-check-big`,[[`path`,{d:`M21.801 10A10 10 0 1 1 17 3.335`,key:`yps3ct`}],[`path`,{d:`m9 11 3 3L22 4`,key:`1pflzl`}]]);export{t};
@@ -1 +0,0 @@
1
- import{K as e}from"./index-DhYfPTfU.js";var t=e(`clock`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`polyline`,{points:`12 6 12 12 16 14`,key:`68esgv`}]]);export{t};
@@ -1 +0,0 @@
1
- import{K as e}from"./index-DhYfPTfU.js";var t=e(`play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]);export{t};
@@ -1 +0,0 @@
1
- import{K as e}from"./index-DhYfPTfU.js";var t=e(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]);export{t};