@camstack/addon-admin-ui 1.2.52 → 1.2.53

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 (101) hide show
  1. package/dist/assets/{AddLocationWizard-ByfVTf7z.js → AddLocationWizard-CTZRH8Z5.js} +1 -1
  2. package/dist/assets/{AddonCollectionPage-BuFuYYvJ.js → AddonCollectionPage-D-p4HN2Y.js} +1 -1
  3. package/dist/assets/{Addons-DDEVSb9E.js → Addons-hLgZ2H01.js} +1 -1
  4. package/dist/assets/{AdminTabs-Bpp49XUt.js → AdminTabs-DyjWcTkF.js} +1 -1
  5. package/dist/assets/{AiProfiles-DyI1sGHM.js → AiProfiles-5buIYxWX.js} +1 -1
  6. package/dist/assets/{BrokerForm-CN34GcQh.js → BrokerForm-D-nVBA-o.js} +1 -1
  7. package/dist/assets/{Build-6KbkAmwC.js → Build-gYggCQtz.js} +5 -5
  8. package/dist/assets/{Capabilities-D-DpTlWs.js → Capabilities-BNz3VrvR.js} +1 -1
  9. package/dist/assets/{CapabilityBadges-CHhrKMvk.js → CapabilityBadges-Dy-fCgkC.js} +1 -1
  10. package/dist/assets/{Cluster-CM4RcSfn.js → Cluster-79wiomQQ.js} +1 -1
  11. package/dist/assets/{Data-BsrNNDe4.js → Data-CxIEICSc.js} +1 -1
  12. package/dist/assets/{DetectionIntelligence-wwS6t-iu.js → DetectionIntelligence-Bow03mZW.js} +1 -1
  13. package/dist/assets/DeviceAggregateSection-D3GgzLed.js +1 -0
  14. package/dist/assets/{DeviceDetail-BRqNfgrV.js → DeviceDetail-xGas7OKY.js} +2 -2
  15. package/dist/assets/{Devices-C_Iy-1DY.js → Devices-BQFYrt_N.js} +1 -1
  16. package/dist/assets/EmbedPlayerPage-C-lzc6gT.js +1 -0
  17. package/dist/assets/Events-CVnzxEgV.js +1 -0
  18. package/dist/assets/{FormBuilder-8G0bykRV.js → FormBuilder-9AyvljDu.js} +1 -1
  19. package/dist/assets/{Identity-CKFcxYAD.js → Identity-DdsiRBNP.js} +1 -1
  20. package/dist/assets/{IntegrationDetail-CYO9evSX.js → IntegrationDetail-Dmbq_Wgu.js} +1 -1
  21. package/dist/assets/{Integrations-DvDVnh_e.js → Integrations-2hJS885p.js} +1 -1
  22. package/dist/assets/{Integrations-DIbr02Wd.js → Integrations-Dy6aGdNk.js} +1 -1
  23. package/dist/assets/{Logs-DSbrNopM.js → Logs-2uU6ZNE6.js} +1 -1
  24. package/dist/assets/{MotionZonesSettings-DhmylyWm.js → MotionZonesSettings-TAZs0iQF.js} +1 -1
  25. package/dist/assets/{MyAccess-2qf_vuZX.js → MyAccess-DcPz5T-h.js} +1 -1
  26. package/dist/assets/{Network-DM6W1cMH.js → Network-BOtKpCey.js} +1 -1
  27. package/dist/assets/NodeAddonsSettingsPanel-BEd9xkul.js +1 -0
  28. package/dist/assets/{NodeInferenceDevices-D0dCWFuM.js → NodeInferenceDevices-Bo3q56ME.js} +1 -1
  29. package/dist/assets/Notifications-CwTETm0t.js +1 -0
  30. package/dist/assets/{Pipeline-C36d_bUf.js → Pipeline-DhHsaSYf.js} +1 -1
  31. package/dist/assets/{Plates-CaE-1mzS.js → Plates-VOllqnia.js} +1 -1
  32. package/dist/assets/{PrivacyMaskSettings-CKW0LV6c.js → PrivacyMaskSettings-CyiOeki9.js} +1 -1
  33. package/dist/assets/{ProviderIcon-CtnmYlEc.js → ProviderIcon-lr-CBThV.js} +1 -1
  34. package/dist/assets/{Recordings-DN7GpdSr.js → Recordings-cNKeFWdX.js} +1 -1
  35. package/dist/assets/{ScanNetworkModal-D_uWkwpW.js → ScanNetworkModal-C8eQs-oa.js} +1 -1
  36. package/dist/assets/{Settings-BHNismMH.js → Settings-DUnGk-Ze.js} +1 -1
  37. package/dist/assets/{Showroom-DAfTzeRJ.js → Showroom-CXqbw81j.js} +1 -1
  38. package/dist/assets/{Terminal-ChPkNmcT.js → Terminal-DCg-c08F.js} +1 -1
  39. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C4v0_fvJ.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BwtyD_uY.js} +1 -1
  40. package/dist/assets/{bell-ring-B89FuVzx.js → bell-ring-Bva0sp7P.js} +1 -1
  41. package/dist/assets/{boxes-E67TckHL.js → boxes-DaaA1U2C.js} +1 -1
  42. package/dist/assets/{build-cluster-graph-C9P8BH_Y.js → build-cluster-graph-DmatAPiL.js} +1 -1
  43. package/dist/assets/circle-check-big-B89lSUUk.js +1 -0
  44. package/dist/assets/{circle-x-BOCM3Jay.js → circle-x-DukPu47a.js} +1 -1
  45. package/dist/assets/clock-DhfaWKQT.js +1 -0
  46. package/dist/assets/{copy-BAh4BimG.js → copy-CDwMOr_d.js} +1 -1
  47. package/dist/assets/{debounced-invalidate-B6n92LfS.js → debounced-invalidate-DdpdBiw5.js} +1 -1
  48. package/dist/assets/{dist-DMs8CJMG.js → dist-C61wZXG_.js} +1 -1
  49. package/dist/assets/dist-DqDvuSSn.js +345 -0
  50. package/dist/assets/{download-NchcTrNY.js → download-BgcYzk2Q.js} +1 -1
  51. package/dist/assets/{face-bbox-CxWVEvLH.js → face-bbox-CwWXxJeF.js} +1 -1
  52. package/dist/assets/{hard-drive-v3gsMgpj.js → hard-drive-DBS5CobV.js} +1 -1
  53. package/dist/assets/{hostInit-BsdExvxu.js → hostInit-BRYz12QA.js} +1 -1
  54. package/dist/assets/{index-DOGqQOnC.js → index-fyPDUdJN.js} +3 -3
  55. package/dist/assets/{key-round-B8nOHuYS.js → key-round-zsF7PT11.js} +1 -1
  56. package/dist/assets/{mf-entry-bootstrap-0-fb7d830c.js → mf-entry-bootstrap-0-5949baa8.js} +2 -2
  57. package/dist/assets/{pencil-sz3vITXt.js → pencil-DoFsGHJs.js} +1 -1
  58. package/dist/assets/play-Bhpu49mx.js +1 -0
  59. package/dist/assets/{player-overlays-35cjLMFQ.js → player-overlays-C-3liTTP.js} +1 -1
  60. package/dist/assets/plus-C9xW_jEC.js +1 -0
  61. package/dist/assets/power-dfEFBp4-.js +1 -0
  62. package/dist/assets/{radio-DyOU1pqI.js → radio-BLrBPWuP.js} +1 -1
  63. package/dist/assets/{refresh-cw-yJ3BGqhW.js → refresh-cw-DcXpV7xr.js} +1 -1
  64. package/dist/assets/remoteEntry-Cyq1R_C0.js +1 -0
  65. package/dist/assets/rotate-ccw-CkObSlR8.js +1 -0
  66. package/dist/assets/rotate-cw-DMKQK91h.js +1 -0
  67. package/dist/assets/search-CBZXGB7v.js +1 -0
  68. package/dist/assets/{send-ibgpXPAd.js → send-lVWoIHYN.js} +1 -1
  69. package/dist/assets/{server-W3u0QEGh.js → server-CrysozOm.js} +1 -1
  70. package/dist/assets/square-C1CVou2Z.js +1 -0
  71. package/dist/assets/{square-check-big-N3hx4ccu.js → square-check-big-CItT96VK.js} +1 -1
  72. package/dist/assets/src-9rmmBstM.js +345 -0
  73. package/dist/assets/src-BFsyqPDw.js +67 -0
  74. package/dist/assets/{undo-2-03JG1b2r.js → undo-2-BJ4kacMc.js} +1 -1
  75. package/dist/assets/{upload-PhcvMnIf.js → upload-Cug_X6EC.js} +1 -1
  76. package/dist/assets/{useEventInvalidation-ChMOpmx7.js → useEventInvalidation-BwhFlT4Q.js} +1 -1
  77. package/dist/assets/{video-D3jIKSxB.js → video-CDgzsesk.js} +1 -1
  78. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-2K3VQBSZ.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-B8LLmlIG.js} +2 -2
  79. package/dist/assets/{wifi-D-m2AtcE.js → wifi-B6L90xdN.js} +1 -1
  80. package/dist/assets/{zap-FMbpMlZh.js → zap-RxnCgRQ7.js} +1 -1
  81. package/dist/index.html +5 -5
  82. package/dist/server/addon.js +73 -10
  83. package/package.json +1 -1
  84. package/dist/assets/DeviceAggregateSection-m7QBjvw1.js +0 -1
  85. package/dist/assets/EmbedPlayerPage-BzJREYPg.js +0 -1
  86. package/dist/assets/Events-CIAJeuGc.js +0 -1
  87. package/dist/assets/NodeAddonsSettingsPanel-OlYGh17A.js +0 -1
  88. package/dist/assets/Notifications-B57yS_N9.js +0 -1
  89. package/dist/assets/circle-check-big-6KqLnh7I.js +0 -1
  90. package/dist/assets/clock-BB5ZlM4P.js +0 -1
  91. package/dist/assets/dist-ujytOS_T.js +0 -345
  92. package/dist/assets/play-BO_n_04H.js +0 -1
  93. package/dist/assets/plus-CzPndm5P.js +0 -1
  94. package/dist/assets/power-DFi-GnjG.js +0 -1
  95. package/dist/assets/remoteEntry-DhlUKvH0.js +0 -1
  96. package/dist/assets/rotate-ccw-B2UqNaB5.js +0 -1
  97. package/dist/assets/rotate-cw-Ceq0Xutw.js +0 -1
  98. package/dist/assets/search-Djlmih4W.js +0 -1
  99. package/dist/assets/square-BhLZ-0MF.js +0 -1
  100. package/dist/assets/src-C9Wl4IAv.js +0 -345
  101. package/dist/assets/src-DfTnwu3m.js +0 -67
@@ -0,0 +1 @@
1
+ import{$o as e,Io as t,Lo as n,No as r,Qn as i,Qo as a,Ro as o,S as s,aa as c,bo as l,cs as u,is as d,ls as f,ns as p,os as m,rs as h,ss as g,ts as _,us as v,zo as y}from"./src-BFsyqPDw.js";import{Q as b,S as x,W as S,a as C,b as w,i as T,o as E,q as D,t as O,x as k,z as A}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DTufy7Ue.js";import{M as j,O as M,U as N,c as P,d as F,f as ee,g as I,h as te,j as ne,l as re,m as ie,o as ae,p as oe,s as se,u as ce}from"./src-9rmmBstM.js";import{p as L}from"./player-overlays-C-3liTTP.js";import{n as R,t as le}from"./bell-ring-Bva0sp7P.js";import{t as ue}from"./circle-check-big-B89lSUUk.js";import{t as de}from"./copy-CDwMOr_d.js";import{t as fe}from"./pencil-DoFsGHJs.js";import{t as z}from"./plus-C9xW_jEC.js";import{t as pe}from"./refresh-cw-DcXpV7xr.js";import{t as me}from"./rotate-ccw-CkObSlR8.js";import{t as he}from"./search-CBZXGB7v.js";import{t as ge}from"./send-lVWoIHYN.js";import{t as _e}from"./zap-RxnCgRQ7.js";import{J as ve,N as ye,S as B,V as be,W as xe,f as Se,i as Ce,o as we,s as Te}from"./index-fyPDUdJN.js";import{t as V}from"./AdminPage-Dq33XE9j.js";import{t as Ee}from"./AdminTabs-DyjWcTkF.js";var De=xe(`flask-conical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),Oe=xe(`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`}]]),ke=xe(`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`}]]);b();var Ae={home:`Home`,away:`Away`,night:`Night`};function je(e){return Ae[e]??e}function Me(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 Ne(e,t){return e.ruleCount===0?`Arms nothing — no enabled rule is gated on this mode.`:e.allDevices?`Every device — ${Le(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${Le(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(e=>t.get(e)??`Device ${e}`).join(`, `)}function Pe(e,t){if(e.length===0)return``;let n=e.map(e=>`${t.get(e.deviceId)??`Device ${e.deviceId}`} (${Fe[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var Fe={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function Ie(e){return e.ruleCount===0}function Le(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function Re(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 ze=[`notificationRules`,`getAlarmConfig`],Be=[`notificationOutput`,`listTargets`],Ve=[`deviceManager`,`listAll`,`alarm-coverage`],He=600,Ue=3600;function We({label:e,hint:t,value:n,max:r,zeroMeans:i,disabled:a,onCommit:o}){let[s,c]=D(null);return x(`div`,{className:`flex flex-col gap-1`,children:[k(`label`,{className:`text-sm font-medium`,children:e}),x(`div`,{className:`flex items-center gap-2`,children:[k(g,{type:`number`,min:0,max:r,value:s??String(n),disabled:a,onChange:e=>c(e.target.value),onBlur:()=>{let e=s===null?null:Re(s,r);c(null),e!==null&&e!==n&&o(e)},className:`w-28`,"data-testid":`alarm-delay-${e.toLowerCase().replace(/\s+/g,`-`)}`}),k(`span`,{className:`text-sm text-foreground-subtle`,children:Me(n,i)})]}),k(`p`,{className:`text-xs text-foreground-subtle`,children:t})]})}function Ge(){let e=L(),t=E(),n=C({queryKey:ze,queryFn:async()=>e.trpcClient.notificationRules.getAlarmConfig.query({})}),r=C({queryKey:Be,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),i=C({queryKey:Ve,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).map(e=>({id:e.id,name:e.name}))}),a=O({mutationFn:t=>e.trpcClient.notificationRules.setAlarmConfig.mutate({patch:t}),onSuccess:()=>t.invalidateQueries({queryKey:ze})}),o=S(()=>{let e=new Map;for(let t of i.data??[])e.set(t.id,t.name);return e},[i.data]);if(n.isLoading)return k(V,{icon:Se,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(B,{className:`h-5 w-5 animate-spin`})});let s=n.data;if(s===void 0||n.isError)return k(V,{icon:Se,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(l,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(s.deviceId===null)return k(V,{icon:Se,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(u,{className:`p-4`,children:k(`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 c=s.settings,p=a.isPending,m=r.data??[],h=c.announceTargets,g=e=>{a.mutate(e)},_=e=>{g({announceTargets:h.includes(e)?h.filter(t=>t!==e):[...h,e]})};return k(V,{icon:Se,title:`Alarm`,subtitle:`Panel delays, and what each mode actually arms.`,children:x(`div`,{className:`flex flex-col gap-4`,children:[a.isError?k(l,{title:`Could not save`,message:String(a.error)}):null,x(u,{className:`p-4`,children:[k(`h3`,{className:`text-sm font-semibold mb-3`,children:`Delays`}),x(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[k(We,{label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,value:c.exitDelaySec,max:He,zeroMeans:`arms immediately`,disabled:p,onCommit:e=>g({exitDelaySec:e})}),k(We,{label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,value:c.entryDelaySec,max:He,zeroMeans:`fires immediately`,disabled:p,onCommit:e=>g({entryDelaySec:e})}),k(We,{label:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,value:c.triggeredDurationSec,max:Ue,zeroMeans:`until disarmed`,disabled:p,onCommit:e=>g({triggeredDurationSec:e})})]})]}),x(u,{className:`p-4`,children:[x(`div`,{className:`flex items-start justify-between gap-4`,children:[x(`div`,{children:[k(`h3`,{className:`text-sm font-semibold`,children:`Announce when a mode is armed`}),k(`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.`})]}),k(d,{checked:c.announceArm,disabled:p,onCheckedChange:e=>g({announceArm:e}),"data-testid":`alarm-announce-toggle`})]}),c.announceArm?x(`div`,{className:`mt-3 flex flex-col gap-2`,children:[m.length===0?k(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification targets are configured — nothing can be sent.`}):m.map(e=>x(`label`,{className:`flex items-center gap-2 text-sm`,children:[k(`input`,{type:`checkbox`,checked:h.includes(e.id),disabled:p,onChange:()=>_(e.id),"data-testid":`alarm-target-${e.id}`}),k(`span`,{children:e.name}),e.enabled?null:k(f,{variant:`warning`,children:`disabled`})]},e.id)),h.length===0?k(`p`,{className:`text-xs text-warning`,children:`No target selected — the announcement will not be sent.`}):null]}):null]}),x(u,{className:`p-4`,children:[k(`h3`,{className:`text-sm font-semibold mb-1`,children:`What each mode arms`}),k(`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.`}),k(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-coverage`,children:s.coverage.map(e=>x(`div`,{className:`flex items-start gap-3 rounded border border-border p-2`,"data-mode":e.mode,"data-empty":Ie(e)?`true`:`false`,children:[k(`div`,{className:`w-20 shrink-0 text-sm font-medium`,children:je(e.mode)}),x(`div`,{className:`flex-1 text-sm text-foreground-subtle`,children:[Ne(e,o),e.skippedDevices.length>0?k(`div`,{className:`mt-0.5 text-xs text-warning`,"data-testid":`alarm-skipped`,children:Pe(e.skippedDevices,o)}):null]}),Ie(e)?k(we,{className:`h-4 w-4 shrink-0 text-warning`}):null]},e.mode))})]})]})})}b();var Ke=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],qe=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],Je=[50,100,250,500];function Ye(){return{ruleId:``,deviceId:``,status:``,windowHours:24,limit:100}}function Xe(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Ze(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Qe(){let e=L(),[t,n]=D(Ye),i=e=>n(t=>({...t,...e})),a=C({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),o=C({queryKey:[`deviceManager`,`listAll`,`forHistory`],queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===N.Camera).map(e=>({id:e.id,name:e.name}))}),s=Date.now(),c=C({queryKey:[`notificationRules`,`getHistory`,t],retry:!1,queryFn:async()=>{let n=t.windowHours>0?s-t.windowHours*36e5:void 0;return(await e.trpcClient.notificationRules.getHistory.query({filter:{limit:t.limit,...t.ruleId?{ruleId:t.ruleId}:{},...t.deviceId?{deviceId:Number(t.deviceId)}:{},...Xe(t.status)?{status:Xe(t.status)}:{},...n===void 0?{}:{since:n}}})).entries}}),l=S(()=>{let e=new Map;for(let t of o.data??[])e.set(t.id,t.name);return e},[o.data]),d=e=>l.get(e)??`Camera #${String(e)}`,f=c.data??[],p=c.isError;return x(V,{icon:Oe,title:`Delivery history`,subtitle:`A searchable log of every notification the rules delivered (or failed to deliver).`,children:[x(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),k(m,{value:t.ruleId,onChange:e=>i({ruleId:e.target.value}),options:[{value:``,label:`All rules`},...(a.data??[]).map(e=>({value:e.id,label:e.name}))]})]}),x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),k(m,{value:t.deviceId,onChange:e=>i({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(o.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),k(m,{value:t.status,onChange:e=>i({status:e.target.value}),options:qe.map(e=>({value:e.value,label:e.label}))})]}),x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),k(m,{value:String(t.windowHours),onChange:e=>i({windowHours:Number(e.target.value)}),options:Ke.map(e=>({value:String(e.value),label:e.label}))})]}),x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),k(m,{value:String(t.limit),onChange:e=>i({limit:Number(e.target.value)}),options:Je.map(e=>({value:String(e),label:String(e)}))})]})]}),c.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(B,{className:`h-6 w-6 animate-spin text-primary`})}),p&&!c.isLoading&&k(u,{children:x(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[k(Oe,{className:`h-6 w-6 text-foreground-subtle`}),k(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),k(`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.`}),x(`button`,{type:`button`,onClick:()=>void c.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:[k(pe,{className:`h-3 w-3`}),` Retry`]})]})}),!p&&!c.isLoading&&f.length===0&&k(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!p&&f.length>0&&k(u,{children:k(r,{columns:$e(d),rows:f,rowKey:e=>e.id,minWidthPx:720,bordered:!1})})]})}function $e(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>k(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`Subject`,render:e=>x(`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=>x(`span`,{className:`flex items-center gap-1.5`,children:[k(f,{variant:Ze(e.status),children:e.status}),e.attempts>1?x(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:`Detail`,render:e=>e.error?k(`span`,{className:`text-[11px] text-danger`,children:e.error}):k(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}function et(e){let t=[],n=e.find(e=>e.type===N.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===N.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 tt(e,t){let n=t.build(),r=new Set(e.sequences.map(e=>e.name.trim())),i=n.name;for(let e=2;r.has(i);e+=1)i=`${n.name} ${String(e)}`;return{...e,sequences:[...e.sequences,{...n,name:i}]}}var nt=[{value:`acknowledge`,label:`Acknowledge`},{value:`dismiss`,label:`Dismiss`},{value:`silence`,label:`Silence`},{value:`view`,label:`View`},{value:`play`,label:`Play`},{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:`light`,label:`Light`},{value:`alert`,label:`Alert`}],rt={sequences:[],buttons:[]};function it(e){return e===void 0?rt:{sequences:[...e.onTrigger??[]],buttons:[...e.buttons??[]]}}function at(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 ot(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 st(e){return{name:`sequence ${String(e+1)}`,enabled:!1,actions:[]}}function ct(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequence:t}}function lt(){return{kind:`wait`,seconds:5}}var H=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,U=`block text-[11px] font-medium text-foreground`;function ut({value:e,onChange:t,devices:n}){let r=ot(e),i=et(n),a=(n,r)=>t({...e,sequences:e.sequences.map((e,t)=>t===n?r:e)}),o=(n,r)=>t({...e,buttons:e.buttons.map((e,t)=>t===n?r:e)});return x(`div`,{className:`space-y-4`,children:[r.length>0&&k(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:r.map(e=>k(`p`,{children:e.message},e.message))}),x(`section`,{className:`space-y-2`,children:[x(`div`,{className:`flex items-center justify-between`,children:[x(`div`,{children:[k(`h4`,{className:`text-xs font-semibold text-foreground`,children:`What this rule does`}),k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`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.`})]}),x(`div`,{className:`flex items-center gap-1`,children:[i.map(n=>x(v,{size:`sm`,variant:`ghost`,type:`button`,title:n.hint,onClick:()=>t(tt(e,n)),children:[k(_e,{className:`h-3.5 w-3.5`}),` `,n.label]},n.id)),x(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t({...e,sequences:[...e.sequences,st(e.sequences.length)]}),children:[k(z,{className:`h-3.5 w-3.5`}),` Sequence`]})]})]}),e.sequences.length===0?k(`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((r,i)=>k(dt,{sequence:r,devices:n,onChange:e=>a(i,e),onRemove:()=>t({...e,sequences:e.sequences.filter((e,t)=>t!==i)})},`seq-${String(i)}`))]}),x(`section`,{className:`space-y-2`,children:[x(`div`,{className:`flex items-center justify-between`,children:[x(`div`,{children:[k(`h4`,{className:`text-xs font-semibold text-foreground`,children:`Buttons on the notification`}),k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Each button runs one of the sequences above when tapped.`})]}),x(v,{size:`sm`,variant:`ghost`,type:`button`,disabled:e.sequences.length===0,onClick:()=>t({...e,buttons:[...e.buttons,ct(e.buttons.length,e.sequences[0]?.name??``)]}),children:[k(z,{className:`h-3.5 w-3.5`}),` Button`]})]}),e.buttons.length>0&&x(`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:[k(we,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),x(`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 `,k(`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?k(`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?k(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No buttons. The notification arrives with nothing to tap.`}):e.buttons.map((n,r)=>k(mt,{button:n,sequenceNames:e.sequences.map(e=>e.name),onChange:e=>o(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function dt({sequence:e,devices:t,onChange:n,onRemove:r}){let i=(t,r)=>n({...e,actions:e.actions.map((e,n)=>n===t?r:e)});return x(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:[x(`div`,{className:`flex flex-wrap items-end gap-2`,children:[x(`div`,{className:`min-w-0 flex-1`,children:[k(`label`,{className:U,children:`Name`}),k(g,{className:`mt-1`,value:e.name,onChange:t=>n({...e,name:t.target.value})})]}),x(`div`,{className:`w-28`,children:[k(`label`,{className:U,children:`Min delay (s)`}),k(`input`,{type:`number`,min:0,className:H,value:e.minDelaySec??``,onChange:t=>{let r=t.target.value,i={...e};r===``?delete i.minDelaySec:i.minDelaySec=Number(r),n(i)}})]}),x(`div`,{className:`flex items-center gap-2 pb-1`,children:[k(d,{checked:e.enabled,onCheckedChange:t=>n({...e,enabled:t})}),k(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.enabled?`Runs on match`:`Only when a button is tapped`})]}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove`,children:k(Te,{className:`h-3.5 w-3.5`})})]}),x(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[e.actions.map((r,a)=>k(ft,{step:r,devices:t,onChange:e=>i(a,e),onRemove:()=>n({...e,actions:e.actions.filter((e,t)=>t!==a)})},`step-${String(a)}`)),x(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({...e,actions:[...e.actions,lt()]}),children:[k(z,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function ft({step:e,devices:t,onChange:n,onRemove:r}){return x(`div`,{className:`flex flex-wrap items-end gap-2`,children:[x(`div`,{className:`w-24`,children:[k(`label`,{className:U,children:`Step`}),x(`select`,{className:H,value:e.kind,onChange:e=>n(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[k(`option`,{value:`cap`,children:`Do`}),k(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?x(`div`,{className:`w-28`,children:[k(`label`,{className:U,children:`Seconds`}),k(`input`,{type:`number`,min:0,max:300,className:H,value:e.seconds,onChange:e=>n({kind:`wait`,seconds:Number(e.target.value)})})]}):k(pt,{step:e,devices:t,onChange:n}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove step`,children:k(Te,{className:`h-3.5 w-3.5`})})]})}function pt({step:e,devices:t,onChange:n}){let r=L(),i=C({queryKey:[`deviceManager`,`getBindings`,e.deviceId],enabled:e.deviceId>0,staleTime:6e4,queryFn:async()=>{let t=await r.trpcClient.deviceManager.getBindings.query({deviceId:e.deviceId});return[...new Set(t.entries.map(e=>e.capName))].sort((e,t)=>e.localeCompare(t))}}).data??[];return x(w,{children:[x(`div`,{className:`min-w-[9rem] flex-1`,children:[k(`label`,{className:U,children:`Device`}),x(`select`,{className:H,value:String(e.deviceId),onChange:t=>n({...e,deviceId:Number(t.target.value),cap:``}),children:[k(`option`,{value:`0`,children:`Select…`}),t.map(e=>k(`option`,{value:String(e.id),children:e.name},e.id))]})]}),x(`div`,{className:`min-w-[8rem] flex-1`,children:[k(`label`,{className:U,children:`Capability`}),x(`select`,{className:H,value:e.cap,disabled:i.length===0,onChange:t=>n({...e,cap:t.target.value,method:``}),children:[k(`option`,{value:``,children:i.length===0?`No devices bound`:`Select…`}),i.map(e=>k(`option`,{value:e,children:e},e))]})]}),x(`div`,{className:`min-w-[7rem] flex-1`,children:[k(`label`,{className:U,children:`Method`}),k(g,{className:`mt-1`,value:e.method,placeholder:`arm`,onChange:t=>n({...e,method:t.target.value})})]}),x(`div`,{className:`min-w-[8rem] flex-1`,children:[k(`label`,{className:U,children:`Arguments (JSON)`}),k(g,{className:`mt-1`,value:e.args===void 0?``:JSON.stringify(e.args),placeholder:`{"mode":"away"}`,onChange:t=>{let r=t.target.value.trim();if(r===``){let t={...e};delete t.args,n(t);return}try{let t=JSON.parse(r);typeof t==`object`&&t&&!Array.isArray(t)&&n({...e,args:t})}catch{}}})]})]})}function mt({button:e,sequenceNames:t,onChange:n,onRemove:r}){return x(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[x(`div`,{className:`min-w-[7rem] flex-1`,children:[k(`label`,{className:U,children:`Label`}),k(g,{className:`mt-1`,value:e.label,onChange:t=>n({...e,label:t.target.value})})]}),x(`div`,{className:`min-w-[8rem] flex-1`,children:[k(`label`,{className:U,children:`Runs`}),x(`select`,{className:H,value:e.sequence,onChange:t=>n({...e,sequence:t.target.value}),children:[!t.includes(e.sequence)&&x(`option`,{value:e.sequence,children:[e.sequence,` (missing)`]}),t.map(e=>k(`option`,{value:e,children:e},e))]})]}),x(`div`,{className:`w-32`,children:[k(`label`,{className:U,children:`Icon`}),x(`select`,{className:H,value:e.icon??``,onChange:t=>{let r={...e};if(t.target.value===``)delete r.icon;else{let e=nt.find(e=>e.value===t.target.value);e!==void 0&&(r.icon=e.value)}n(r)},children:[k(`option`,{value:``,children:`None`}),nt.map(e=>k(`option`,{value:e.value,children:e.label},e.value))]})]}),x(`div`,{className:`flex items-center gap-2 pb-1`,children:[k(d,{checked:e.destructive===!0,onCheckedChange:t=>{let r={...e};t?r.destructive=!0:delete r.destructive,n(r)}}),k(f,{variant:e.destructive===!0?`danger`:`default`,children:`Destructive style`})]}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove`,children:k(Te,{className:`h-3.5 w-3.5`})})]})}function W(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var ht=W({devices:!0}),gt=W({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),_t=W({zonesExclude:!0}),vt=W({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),yt=W({minDwellSeconds:!0}),bt=W({source:!0}),xt=W({crossing:!0}),St=W({packagePhase:!0}),Ct=W({zones:!0}),wt=W({plates:!0}),Tt=W({occupancy:!0}),Et=W({audio:!0}),Dt=W({systemEvent:!0}),Ot=W({deviceState:!0});function kt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function At(e,t){let n=e[t];return typeof n==`number`?n:void 0}var jt=[{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 Mt(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Nt(e,t){let n=e.filter(t),r=new Set(jt.map(e=>e.id)),i=[];for(let e of jt){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:Mt(e),descriptors:n.filter(t=>t.group===e)});return i}b();function Pt(e,t){let n=L().trpcClient,r=T({queries:e.map(e=>({queryKey:[[`nc-pickers`,`zones`],{deviceId:e}],staleTime:3e4,queryFn:async()=>({deviceId:e,zones:(await n.zones.listZones.query({deviceId:e})).map(e=>({id:e.id,name:e.name}))})}))});return S(()=>{let e=[],n=new Set;for(let i of r){if(!i.data)continue;let r=t.find(e=>e.id===i.data.deviceId)?.name;for(let t of i.data.zones)n.has(t.id)||(n.add(t.id),e.push({value:t.id,label:t.name,...r===void 0?{}:{hint:r}}))}return{options:e,loading:r.some(e=>e.isLoading)}},[r,t])}function Ft(e){let t=L().trpcClient,n=T({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 S(()=>{let e=new Map;for(let t of n)for(let n of t.data??[])e.has(n.kind)||e.set(n.kind,n.label);let t=[...e.entries()].map(([e,t])=>({value:e,label:t}));return t.sort((e,t)=>e.label.localeCompare(t.label)),{options:t,loading:n.some(e=>e.isLoading)}},[n])}function It(){let e=i();return S(()=>({options:(e.data??[]).map(e=>({value:e.name,label:e.name})),loading:e.isLoading}),[e.data,e.isLoading])}function Lt(){let e=c({limit:200});return S(()=>{let t=new Set;for(let n of e.data??[])n.text.trim().length>0&&t.add(n.text);return[...t].sort()},[e.data])}function G({options:e,value:t,onChange:n,loading:r,emptyHint:i,placeholder:a,noFreeText:o=!1}){let[s,c]=D(``),l=S(()=>new Set(e.map(e=>e.value)),[e]),u=S(()=>new Set(t),[t]),d=t.filter(e=>!l.has(e)),f=e=>{n(u.has(e)?t.filter(t=>t!==e):[...t,e])},p=()=>{let e=s.trim();e.length===0||t.includes(e)||(n([...t,e]),c(``))};return x(`div`,{className:`mt-1 space-y-1.5`,children:[d.length>0&&k(`div`,{className:`flex flex-wrap gap-1`,children:d.map(e=>x(`button`,{type:`button`,onClick:()=>n(t.filter(t=>t!==e)),className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,title:`Custom value — click to remove`,children:[e,` ×`]},e))}),e.length>0?k(`div`,{className:`max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>x(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:u.has(e.value),onChange:()=>f(e.value),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.label}),e.hint!==void 0&&k(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.hint})]},e.value))}):k(`p`,{className:`text-[10px] text-foreground-subtle`,children:r===!0?`Loading…`:i}),!o&&k(`input`,{value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),p())},placeholder:a,className:`w-full rounded-md border border-border bg-background px-2 py-1 text-xs text-foreground placeholder:text-foreground-subtle`})]})}var Rt=[{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 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 zt(e){return Rt.find(t=>t.value===e)?.label??e}function Bt(e){return Rt.find(t=>t.value===e)?.value}function Vt(e){return Rt.some(t=>t.value===e)}function K(e){return e===`system-event`}var Ht=[{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.`},{key:`detection`,label:`Detections & devices`,blurb:`Rules driven by what the cameras and sensors SEE — detections, tracks, doorbell presses and package events.`},{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.`}];function Ut(e){return Ht.find(t=>t.key===e)?.key}function Wt(e,t){return t===`all`?!0:t===`system`?K(e):!K(e)}function Gt(e){return e===`system`?`system-event`:`immediate`}var Kt=[{value:0,label:`No cooldown`},{value:30,label:`30 seconds`},{value:60,label:`1 minute`},{value:300,label:`5 minutes`},{value:600,label:`10 minutes`},{value:1800,label:`30 minutes`},{value:3600,label:`1 hour`}];function qt(e){let t=Kt.find(t=>t.value===e);return t?t.label:e%3600==0?`${e/3600} hours`:e%60==0?`${e/60} minutes`:`${e} seconds`}function Jt(e){return Kt.some(t=>t.value===e)?Kt:[...Kt,{value:e,label:qt(e)}].toSorted((e,t)=>e.value-t.value)}function Yt(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}var Xt=[{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 Zt(e){return Xt.find(t=>t.value===e)?.value}var Qt=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function $t(e){let t=Qt.find(t=>t.value===e)?.value;return t===``?void 0:t}var en=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function tn(e){let t=en.find(t=>t.value===e)?.value;return t===``?void 0:t}var nn=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],rn=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],an=[{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 on(e){let t=an.find(t=>t.value===e)?.value;return t===``||t===void 0?void 0:t}var sn=[{value:`any`,label:`Any of`},{value:`all`,label:`All of`}],cn=[{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`}],ln=[10,30,60],un=[5,10,15,30,60,120,240,480];function dn(e){return e>=60&&e%60==0?`${e/60} h`:`${e} min`}var fn=new Set([`alarm-triggered`,`alarm-armed`,`alarm-disarmed`]),pn=`alarm-panel`;function mn(e,t){for(let t of e.systemEvent?.kinds??[])if(fn.has(t))return!0;for(let e of t)for(let t of e.actions)if(t.kind===`cap`&&t.cap===pn)return!0;return!1}function hn(e=`immediate`){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:{},schedule:void 0,snoozeAllowGlobal:!1,snoozeOptions:void 0,actions:rt,deviceIds:[],cooldownSec:60}}function gn(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,snoozeOptions:e.snoozeOptions,actions:it(e.actions),deviceIds:e.conditions.devices??[],cooldownSec:e.throttle.cooldownSec}}function _n(e){return Vt(e.delivery)&&(!K(e.delivery)||vn(e)>0)&&e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&ot(e.actions).length===0}function vn(e){return e.conditions.systemEvent?.kinds.length??0}function yn(e,t){return e.appliesTo.includes(t)}var bn={source:`any`};function xn(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||bn[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 Sn=ne.filter(e=>e.id===`audio`);function Cn(e){if(e.length===0)return e;let t=new Set(e.map(e=>e.id)),n=Sn.filter(e=>!t.has(e.id));return n.length===0?e:[...e,...n]}function wn(e,t,n){let r=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&yn(e,t)).map(e=>e.id)),i={};for(let[t,n]of Object.entries(e))r!==null&&!r.has(t)||xn(t,n)||(i[t]=n);return i}function Tn(e){return e!==void 0&&e.windows.length>0}function En(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=at(e.actions),s=(n.length===0||n.some(t=>t.id===`schedule`&&yn(t,e.delivery)))&&Tn(e.schedule)?e.schedule:void 0,c=n.length===0?!0:n.some(t=>t.id===`devices`&&yn(t,e.delivery));return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...wn(e.conditions,e.delivery,n),...c&&e.deviceIds.length>0?{devices:[...e.deviceIds]}:{}},...s?{schedule:s}:{},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:K(e.delivery)?{attach:`none`}:{attach:e.mediaAttach,...e.mediaZoneCrop?{zoneCrop:!0}:{},...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}},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.snoozeOptions===void 0?{}:{snoozeOptions:[...e.snoozeOptions]},...o===void 0?{}:{actions:o}}}function Dn(e,t){return e.options&&e.options.length>0?e.options:t}var On=[{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 kn(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var An=[{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`]}];function jn(e){return K(e)?An.filter(e=>e.key!==`devices`).map(e=>e.key===`conditions`?{...e,label:`Events`}:e):An}var Mn=`rule`;function Nn(e){return An.find(t=>t.key===e)?.key}b();var q=`block text-[11px] font-medium text-foreground`,J=`text-[10px] text-foreground-subtle mt-0.5`;function Pn({cameras:e,value:t,onChange:n}){if(e.length===0)return k(`p`,{className:J,children:`No cameras available — the rule applies to all devices.`});let r=e=>n(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return k(`div`,{className:`mt-1 max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>x(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>r(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.name})]},e.id))})}function Fn({value:e,placeholder:t,onChange:n}){let[r,i]=D(``),a=()=>{let t=r.trim();if(t.length===0||e.includes(t)){i(``);return}n([...e,t]),i(``)},o=t=>n(e.filter(e=>e!==t));return x(`div`,{className:`mt-1 space-y-1.5`,children:[e.length>0&&k(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>x(`span`,{className:`inline-flex items-center gap-1 rounded bg-surface-hover px-1.5 py-0.5 text-[11px] text-foreground`,children:[e,k(`button`,{type:`button`,onClick:()=>o(e),"aria-label":`remove ${e}`,className:`text-foreground-subtle hover:text-danger`,children:k(Ce,{className:`h-3 w-3`})})]},e))}),k(g,{value:r,placeholder:t,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),a())},onBlur:a})]})}function In({picker:e,value:t,onChange:n}){let r=S(()=>se(e),[e]),i=S(()=>new Set(t),[t]),a=t.filter(e=>!r.has(e)),o=e=>{n(i.has(e)?t.filter(t=>t!==e):[...t,e])};return x(`div`,{className:`space-y-2`,children:[a.length>0&&k(`div`,{className:`flex flex-wrap gap-1`,children:a.map(e=>x(`button`,{type:`button`,onClick:()=>n(t.filter(t=>t!==e)),className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,title:`Custom value — click to remove`,children:[e,` ×`]},e))}),e.groups.map(e=>x(`div`,{children:[k(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-muted mb-1`,children:e.fallbackLabel}),k(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map(e=>{let t=i.has(e.value);return k(`button`,{type:`button`,"aria-pressed":t,onClick:()=>o(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 Ln({value:e,min:t,max:n,step:r,onChange:i}){return x(`div`,{className:`mt-1 flex items-center gap-2`,children:[k(g,{type:`number`,value:e??``,min:t,max:n,step:r,className:`max-w-[8rem]`,onChange:e=>{let t=e.target.value;if(t===``){i(void 0);return}let n=Number(t);i(Number.isFinite(n)?n:void 0)}}),e!==void 0&&n!==void 0&&k(`input`,{type:`range`,min:t,max:n,step:r,value:e,onChange:e=>i(Number(e.target.value)),className:`flex-1 accent-primary`,"aria-label":`value`})]})}function Rn({value:e,onChange:t,options:n}){let r=e??``,i=n&&n.length>0?n:an,a=i.find(e=>e.value===r);return x(`div`,{className:`mt-1 space-y-1`,children:[k(m,{value:r,options:i.map(e=>({value:e.value,label:e.label})),onChange:e=>t(on(e.target.value))}),a!==void 0&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:a.hint})]})}function zn({deviceIds:e,cameras:t,value:n,onChange:r}){let i=n?.ids??[],a=n?.match??`any`,o=e=>r(e.length>0?{ids:e,match:a}:void 0),s=e=>r(i.length>0?{ids:i,match:e}:void 0);return x(`div`,{className:`mt-1 space-y-1.5`,children:[k(`div`,{className:`max-w-[10rem]`,children:k(m,{value:a,options:sn.map(e=>({value:e.value,label:e.label})),onChange:e=>s(e.target.value===`all`?`all`:`any`)})}),k(Bn,{deviceIds:e,cameras:t,value:i,onChange:o})]})}function Bn({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=Pt(e,t);return k(G,{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 Vn({value:e,onChange:t}){let{options:n,loading:r}=It();return k(G,{options:n,value:e,onChange:t,loading:r,emptyHint:`No identities in the face gallery yet — type a name.`,placeholder:`Identity name…`})}function Hn({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=Ft(e);return k(G,{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 Un=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}],Wn={op:`became-occupied`,count:1,sustainSeconds:15};function Gn({deviceIds:e,cameras:t,classOptions:n,value:r,onChange:i}){let{options:a,loading:o}=Pt(e,t),s=r??Wn,c=e=>i({...s,...e}),l=s.op===`became-occupied`||s.op===`became-free`;return x(`div`,{className:`mt-1 space-y-1.5`,children:[x(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[k(`div`,{className:`min-w-[10rem]`,children:k(m,{value:s.zoneId??``,options:[{value:``,label:o?`Loading zones…`:`— whole frame —`},...a.map(e=>({value:e.value,label:e.label}))],onChange:e=>c({zoneId:e.target.value===``?void 0:e.target.value})})}),k(`div`,{className:`min-w-[9rem]`,children:k(m,{value:s.className??``,options:[{value:``,label:`— any class —`},...n.map(e=>({value:e.value,label:e.label}))],onChange:e=>c({className:e.target.value===``?void 0:e.target.value})})}),k(`div`,{className:`min-w-[9rem]`,children:k(m,{value:s.op,options:Un.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Un.find(t=>t.value===e.target.value);t&&c({op:t.value})}})})]}),x(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[x(`label`,{className:`flex items-center gap-1`,children:[l?`Threshold`:`Count`,k(g,{type:`number`,min:0,className:`w-16`,value:String(s.count),onChange:e=>c({count:Math.max(0,Number(e.target.value)||0)})})]}),x(`label`,{className:`flex items-center gap-1`,children:[`Hold for`,k(g,{type:`number`,min:0,max:3600,className:`w-16`,value:String(s.sustainSeconds),onChange:e=>c({sustainSeconds:Math.min(3600,Math.max(0,Number(e.target.value)||0))})}),`s`]}),r===void 0?null:k(`button`,{type:`button`,onClick:()=>i(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),k(`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.`})]})}function Kn({taxonomy:e,value:t,onChange:n}){let r=oe(t),i=e=>n(te(t,e)),{choices:a,unknownLabels:o}=ee(e,r.labels);return x(`div`,{className:`mt-1 space-y-2`,children:[k(`div`,{className:`flex flex-wrap gap-1`,children:a.map(e=>{let t=ie(r.labels,e.value),n=e.unknown?`border-dashed border-warning text-warning`:t?`border-primary bg-primary/15 text-foreground`:`border-border text-foreground hover:bg-surface-hover`;return x(`button`,{type:`button`,"aria-pressed":t,title:e.unknown?`Stored by the rule — not offered by this hub`:void 0,onClick:()=>i({labels:I(r.labels,e.value)}),className:`rounded border px-1.5 py-0.5 text-[10px] ${n}`,children:[k(`span`,{"aria-hidden":`true`,children:e.icon}),` `,e.label]},e.value)})}),o.length>0&&x(`p`,{className:`text-[10px] text-warning`,children:[`Kept from the rule, unknown to this hub: `,o.join(`, `)]}),k(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:r.dbThreshold===void 0?x(`button`,{type:`button`,onClick:()=>i({dbThreshold:-30}),className:`rounded border border-border px-2 py-0.5 text-[11px] text-foreground hover:bg-surface-hover`,children:[`Add a level threshold (`,-30,` dBFS)`]}):x(`label`,{className:`flex items-center gap-1`,children:[`Louder than`,k(g,{type:`number`,min:re,max:0,step:3,className:`w-20`,value:String(r.dbThreshold),onChange:e=>i({dbThreshold:Number(e.target.value)})}),`dBFS`,k(`button`,{type:`button`,onClick:()=>i({dbThreshold:void 0}),className:`underline hover:text-foreground`,children:`any level`})]})}),x(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[x(`label`,{className:`flex items-center gap-1`,children:[`Hits`,k(g,{type:`number`,min:1,max:100,step:5,className:`w-16`,value:String(r.hitPercent),onChange:e=>i({hitPercent:Number(e.target.value)})}),`% (default `,ce.hitPercent,`)`]}),x(`label`,{className:`flex items-center gap-1`,children:[`over`,k(g,{type:`number`,min:1,max:300,step:5,className:`w-16`,value:String(r.samplingSeconds),onChange:e=>i({samplingSeconds:Number(e.target.value)})}),`s (default `,ce.samplingSeconds,`)`]}),t===void 0?null:k(`button`,{type:`button`,onClick:()=>n(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),F(t)?k(`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,x(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`dBFS is negative-going: 0 is full scale, `,re,` is silence — so `,`−`,`30 is loud and `,`−`,`60 is faint. The window must be FULL before it can match.`]})]})}function qn({value:e,onChange:t}){let n=e?.values??[],r=e?.maxDistance??1,i=e=>t(e.length>0?{values:e,maxDistance:r}:void 0),a=e=>t(n.length>0?{values:n,maxDistance:e}:void 0),o=Lt().filter(e=>!n.includes(e));return x(`div`,{className:`mt-1 space-y-1.5`,children:[k(Fn,{value:n,placeholder:`Plate text…`,onChange:i}),o.length>0&&x(`div`,{className:`flex flex-wrap items-center gap-1`,children:[k(`span`,{className:`text-[10px] text-foreground-subtle`,children:`Seen:`}),o.slice(0,12).map(e=>k(`button`,{type:`button`,onClick:()=>i([...n,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))]}),x(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Max distance`,k(g,{type:`number`,min:0,max:3,step:1,value:r,className:`max-w-[5rem]`,onChange:e=>{let t=Number(e.target.value);a(Number.isFinite(t)?Math.max(0,Math.min(3,t)):1)}})]})]})}function Jn({gateable:e,value:t,onChange:n}){let r=e.find(e=>e.id===t?.deviceId),i=new Set(t?.states??[]),a=e=>{let t=Number(e);if(!Number.isFinite(t)||t===0)return n(void 0);n({deviceId:t,states:[]})},o=e=>{if(t===void 0)return;let r=new Set(i);r.has(e)?r.delete(e):r.add(e),n(r.size===0?void 0:{deviceId:t.deviceId,states:[...r]})};return x(`div`,{className:`mt-1 space-y-2`,children:[k(m,{value:t===void 0?``:String(t.deviceId),options:[{value:``,label:`— no device gate —`},...e.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>a(e.target.value)}),r!==void 0&&k(`div`,{className:`flex flex-wrap gap-1.5`,children:r.states.map(e=>k(`button`,{type:`button`,onClick:()=>o(e),className:i.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))}),r!==void 0&&r.states.length===0&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`This device reports no state the gate can read, so it cannot arm a rule.`}),t!==void 0&&k(`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.`})]})}var Yn=[{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 Xn(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Zn(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 Qn(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function $n({value:e,onChange:t}){let n=e?.windows??[],r=e?.invert??!1,i=(n,r)=>{if(n.length===0){t(void 0);return}t({windows:n,...r?{invert:!0}:{},...e?.timezone?{timezone:e.timezone}:{}})},a=()=>i([...n,Qn()],r),o=e=>i(n.filter((t,n)=>n!==e),r),s=(e,t)=>i(n.map((n,r)=>r===e?t:n),r);return x(`div`,{className:`mt-1 space-y-2`,children:[n.length===0?k(`p`,{className:J,children:`Always active — add a window to restrict when the rule fires.`}):n.map((e,t)=>k(er,{window:e,onChange:e=>s(t,e),onRemove:()=>o(t)},t)),x(`div`,{className:`flex items-center gap-3`,children:[x(`button`,{type:`button`,onClick:a,className:`flex items-center gap-1 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground`,children:[k(z,{className:`h-3 w-3`}),` Add window`]}),n.length>0&&x(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[k(`input`,{type:`checkbox`,checked:r,onChange:e=>i([...n],e.target.checked),className:`accent-primary`}),`Active outside the windows`]})]})]})}function er({window:e,onChange:t,onRemove:n}){let r=n=>{let r=e.days.includes(n)?e.days.filter(e=>e!==n):[...e.days,n];r.length!==0&&t({...e,days:r})};return x(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[x(`div`,{className:`flex items-center gap-2 text-xs`,children:[k(`input`,{type:`time`,value:Xn(e.startMinute),onChange:n=>t({...e,startMinute:Zn(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),k(`span`,{className:`text-foreground-subtle`,children:`→`}),k(`input`,{type:`time`,value:Xn(e.endMinute),onChange:n=>t({...e,endMinute:Zn(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),k(`span`,{className:`flex-1`}),k(`button`,{type:`button`,onClick:n,"aria-label":`Remove window`,className:`text-foreground-subtle hover:text-danger`,children:k(Te,{className:`h-3.5 w-3.5`})})]}),k(`div`,{className:`flex flex-wrap gap-1`,children:Yn.map(t=>k(`button`,{type:`button`,onClick:()=>r(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 tr=[{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:`alarm`,label:`Alarm`,hint:`The alarm panel going off, being armed, or being disarmed.`,kinds:[{value:`alarm-triggered`,label:`Alarm triggered`},{value:`alarm-armed`,label:`Alarm armed`},{value:`alarm-disarmed`,label:`Alarm disarmed`}]},{id:`updates`,label:`Updates`,hint:`A newer version of an addon or of the server itself is available.`,kinds:[{value:`addon-update-available`,label:`Addon update available`},{value:`server-update-available`,label:`Server update available`}]}],nr=tr.flatMap(e=>e.kinds);function rr(e){return nr.find(t=>t.value===e)?.label??e}function ir(e){return{devices:e.some(e=>e.startsWith(`device-`)||e.startsWith(`stream-`)||e===`alarm-triggered`),deviceTypes:e.some(e=>e.startsWith(`device-`)),nodes:e.some(e=>e.startsWith(`node-`)||e===`addon-update-available`),packages:e.some(e=>e.endsWith(`update-available`))}}var ar=Object.values(N).map(e=>({value:e,label:or(e)})).toSorted((e,t)=>e.label.localeCompare(t.label));function or(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function sr(e,t){let n=e?.kinds??[],r=n.includes(t)?n.filter(e=>e!==t):nr.filter(e=>e.value===t||n.includes(e.value)).map(e=>e.value);if(r.length!==0)return ur(e,r)}function cr(e,t){let n=e?.kinds??[];if(n.length===0)return;let r=lr(t,`deviceIds`,e?.deviceIds),i=lr(t,`deviceTypes`,e?.deviceTypes),a=lr(t,`nodeIds`,e?.nodeIds),o=lr(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 lr(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 ur(e,t){let n=ir(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 dr(e,t=2){if(e===void 0||e.length===0)return`No event selected`;let n=e.slice(0,t).map(rr).join(`, `),r=e.length-Math.min(t,e.length);return r>0?`${n} +${r}`:n}function fr(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(or).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(` · `)}b();var pr=[`nc-pickers`,`nodes`],mr=[`nc-pickers`,`addon-packages`];function hr(){let e=L().trpcClient,t=C({queryKey:pr,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 gr(){let e=L().trpcClient,t=C({queryKey:mr,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 _r({value:e,cameras:t,onChange:n}){let r=S(()=>e?.kinds??[],[e]),i=ir(r),a=hr(),o=gr();return x(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[tr.map(t=>x(`div`,{children:[k(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:t.label}),k(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:t.kinds.map(t=>{let i=r.includes(t.value);return k(`button`,{type:`button`,role:`checkbox`,"aria-checked":i,"aria-label":t.label,onClick:()=>n(sr(e,t.value)),className:i?`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)})}),k(`p`,{className:J,children:t.hint})]},t.id)),r.length===0&&k(`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.`}),i.deviceTypes&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these device types (optional)`}),k(G,{options:ar,value:e?.deviceTypes??[],onChange:t=>n(cr(e,{deviceTypes:t})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`}),k(`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.`})]}),i.devices&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these cameras (optional)`}),k(Pn,{cameras:t,value:e?.deviceIds??[],onChange:t=>n(cr(e,{deviceIds:t}))}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to watch every camera.`})]}),i.nodes&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these nodes (optional)`}),k(G,{options:a.options,value:e?.nodeIds??[],onChange:t=>n(cr(e,{nodeIds:t})),loading:a.loading,emptyHint:`No nodes reported — the rule watches every node.`,placeholder:`Node id…`}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to watch every node.`})]}),i.packages&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these packages (optional)`}),k(G,{options:o.options,value:e?.packageNames??[],onChange:t=>n(cr(e,{packageNames:t})),loading:o.loading,emptyHint:`No installed packages listed — the rule watches every package.`,placeholder:`Package name…`}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to be told about every addon and server update.`})]})]})}b();function vr({catalog:e,taxonomy:t,delivery:n,conditions:r,schedule:i,cameras:a,gateable:o,onConditionsChange:s,onScheduleChange:c}){let l=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,s(n)},u=S(()=>Nt(e,e=>e.id!==`devices`&&br(e,n)),[e,n]),d=S(()=>Nt(e,e=>e.id!==`devices`&&!br(e,n)),[e,n]),[p,m]=D(()=>{if(xr(r,i))return!0;try{return localStorage.getItem(yr)===`1`}catch{return!1}}),h=()=>{let e=!p;m(e);try{localStorage.setItem(yr,e?`1`:`0`)}catch{}},g=e=>e.map(e=>x(`div`,{className:`space-y-2.5`,children:[k(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:e.label}),e.descriptors.map(e=>{let s=yn(e,n);return x(`div`,{className:s?``:`opacity-50`,"data-testid":`condition-${e.id}`,children:[x(`div`,{className:`flex items-center justify-between gap-2`,children:[k(`label`,{className:q,children:e.label}),!s&&x(f,{variant:`default`,children:[`not for `,e.appliesTo.join(` / `)]})]}),s?k(Sr,{descriptor:e,taxonomy:t,conditions:r,schedule:i,cameras:a,gateable:o,onFieldChange:l,onScheduleChange:c}):k(`p`,{className:J,children:`Not evaluated for the selected trigger — switch the trigger to use it.`}),s&&e.description&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.description})]},e.id)})]},e.id));return x(`div`,{className:`space-y-4`,children:[g(u),d.length>0&&k(`button`,{type:`button`,onClick:h,"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:p?`▾ Hide advanced configurations`:`▸ Show more configurations`}),p&&g(d)]})}var yr=`camstack.nc.showAdvanced`;function br(e,t){return t===`system-event`?e.id===`systemEvent`:ae(e.id)}function xr(e,t){for(let[t,n]of Object.entries(e))if(!ae(t)&&t!==`systemEvent`&&n!==void 0&&!(Array.isArray(n)&&n.length===0))return!0;return t!==void 0&&t.windows.length>0}function Sr({descriptor:e,taxonomy:t,conditions:n,schedule:r,cameras:i,gateable:a,onFieldChange:o,onScheduleChange:s}){switch(e.valueType){case`deviceIdList`:{if(!ht(e.id))break;let t=e.id;return k(Pn,{cameras:i,value:n[t]??[],onChange:e=>o(t,e.length>0?e:void 0)})}case`stringList`:{if(!gt(e.id))break;let r=e.id,i=e=>o(r,e.length>0?e:void 0);if(r===`identities`||r===`identitiesExclude`)return k(Vn,{value:kt(n,r),onChange:i});if(r===`eventTypeTokens`)return k(Hn,{deviceIds:n.devices??[],value:kt(n,r),onChange:i});let a=P(r,t);return a===null?k(Fn,{value:kt(n,r),placeholder:`Add value…`,onChange:i}):k(In,{picker:a,value:kt(n,r),onChange:i})}case`zoneIdList`:{if(!_t(e.id))break;let t=e.id;return k(Bn,{deviceIds:n.devices??[],cameras:i,value:kt(n,t),onChange:e=>o(t,e.length>0?e:void 0)})}case`number01`:{if(!vt(e.id))break;let t=e.id;return k(Ln,{value:At(n,t),min:0,max:1,step:.05,onChange:e=>o(t,e)})}case`number`:{if(!yt(e.id))break;let t=e.id;return k(Ln,{value:At(n,t),min:0,step:1,onChange:e=>o(t,e)})}case`sourceSelect`:{if(!bt(e.id))break;let t=e.id;return k(m,{value:n[t]??`any`,options:Dn(e,nn).map(e=>({value:e.value,label:e.label})),onChange:e=>o(t,Tr(e.target.value))})}case`systemEvent`:{if(!Dt(e.id))break;let t=e.id;return k(_r,{value:n[t],cameras:i,onChange:e=>o(t,e)})}case`deviceState`:if(!Ot(e.id))break;return k(Jn,{gateable:a,value:n.deviceState,onChange:e=>o(`deviceState`,e)});case`crossingSelect`:{if(!xt(e.id))break;let t=e.id;return k(Rn,{value:n[t],onChange:e=>o(t,e),...e.options?{options:e.options}:{}})}case`packagePhase`:{if(!St(e.id))break;let t=e.id;return k(m,{value:n[t]??``,options:[{value:``,label:`— any phase —`},...Dn(e,rn).map(e=>({value:e.value,label:e.label}))],onChange:e=>o(t,Er(e.target.value))})}case`zoneSelection`:{if(!Ct(e.id))break;let t=e.id;return k(zn,{deviceIds:n.devices??[],cameras:i,value:n[t],onChange:e=>o(t,e)})}case`plateMatcher`:{if(!wt(e.id))break;let t=e.id;return k(qn,{value:n[t],onChange:e=>o(t,e)})}case`occupancy`:{if(!Tt(e.id))break;let r=e.id;return k(Gn,{deviceIds:n.devices??[],cameras:i,classOptions:Cr(t),value:n[r],onChange:e=>o(r,e)})}case`audio`:{if(!Et(e.id))break;let r=e.id;return k(Kn,{taxonomy:t,value:n[r],onChange:e=>o(r,e)})}case`schedule`:return k($n,{value:r,onChange:s});default:break}return k(wr,{descriptor:e,conditions:n})}function Cr(e){let t=P(`classes`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function wr({descriptor:e,conditions:t}){let n=Object.entries(t).find(([t])=>t===e.id);return x(`p`,{className:J,children:[n!==void 0&&n[1]!==void 0?`Authored elsewhere and preserved — this admin editor cannot change it yet.`:`Not editable here yet — this condition has no admin editor.`,` `,x(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function Tr(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Er(e){return rn.find(t=>t.value===e)?.value}var Dr={search:``,types:[],selectedOnly:!1};function Or(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 kr(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 Ar(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 jr(e,t){let n=new Set(t);for(let t of e)n.add(t.id);return[...n]}function Mr(e,t){let n=new Set(e.map(e=>e.id));return t.filter(e=>!n.has(e))}function Nr(e,t){return e.length===0?`Every device (${String(t)}) — no restriction`:`${String(e.length)} of ${String(t)} selected`}b();function Pr({devices:e,value:t,onChange:n,loading:r=!1}){let[i,a]=D(Dr),o=S(()=>Or(e),[e]),s=S(()=>kr(e,i,t),[e,i,t]),c=S(()=>Ar(s),[s]),l=e=>a(t=>({...t,types:t.types.includes(e)?t.types.filter(t=>t!==e):[...t.types,e]})),u=e=>n(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return r?k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Loading devices…`}):x(`div`,{className:`space-y-3`,children:[x(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[k(`p`,{className:`text-[11px] text-foreground-subtle`,children:Nr(t,e.length)}),x(`div`,{className:`flex items-center gap-1`,children:[k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n(jr(s,t)),children:`Select shown`}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n(Mr(s,t)),children:`Clear shown`})]})]}),x(`div`,{className:`flex flex-wrap items-center gap-2`,children:[k(g,{className:`min-w-[10rem] flex-1`,value:i.search,placeholder:`Search by name…`,leftSlot:k(he,{className:`h-3.5 w-3.5 text-foreground-subtle`}),onChange:e=>a(t=>({...t,search:e.target.value}))}),x(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[k(`input`,{type:`checkbox`,checked:i.selectedOnly,onChange:e=>a(t=>({...t,selectedOnly:e.target.checked}))}),`Selected only`]})]}),k(`div`,{className:`flex flex-wrap gap-1`,children:o.map(e=>x(`button`,{type:`button`,onClick:()=>l(e.type),className:i.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,` `,k(`span`,{className:`text-foreground-subtle`,children:e.count})]},e.type))}),s.length===0?k(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No device matches this filter.`}):k(`div`,{className:`max-h-72 space-y-2 overflow-y-auto`,children:c.map(e=>x(`div`,{children:[k(`p`,{className:`px-1 pb-1 text-[10px] uppercase tracking-wide text-foreground-subtle`,children:e.location??`No location`}),k(`div`,{className:`divide-y divide-border rounded-md border border-border`,children:e.devices.map(e=>x(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>u(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.name}),k(f,{variant:`default`,children:e.type})]},e.id))})]},e.location??`__unplaced`))})]})}b();var Fr=[`notificationRules`,`listSnoozes`],Ir=3e4;function Lr(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function Rr(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 zr({rules:e}){let t=L(),n=E(),r=C({queryKey:Fr,refetchInterval:Ir,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),i=O({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>n.invalidateQueries({queryKey:Fr})}),a=S(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),o=Date.now(),s=(r.data??[]).filter(e=>o>=e.startedAt&&o<e.expiresAt);return x(u,{className:`p-4`,children:[x(`div`,{className:`flex items-center gap-2 mb-3`,children:[k(R,{className:`h-4 w-4 text-foreground-subtle`}),k(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),s.length===0&&k(`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.`}),k(`div`,{className:`space-y-2`,children:s.map(e=>x(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[x(`div`,{className:`min-w-0`,children:[x(`div`,{className:`flex items-center gap-2`,children:[k(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:a.get(e.ruleId??``)??`A rule`}),e.global&&k(f,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&k(f,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&k(f,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),x(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,Rr(Lr(e,o))]})]}),k(v,{size:`sm`,variant:`outline`,disabled:i.isPending,onClick:()=>i.mutate(e.id),children:`End now`})]},e.id))})]})}b();var Br=[`notificationRules`,`listRules`],Vr=[`notificationOutput`,`listTargets`,`forRules`],Hr=[`notificationRules`,`getConditionCatalog`],Ur=[`deviceManager`,`listAll`,`forRules`],Wr=[`deviceManager`,`listAll`,`forRuleActions`],Gr=[`deviceManager`,`gateableDevices`],Kr=j.options;function qr({onSimulateRule:e}={}){let n=L(),[i,a]=D({mode:`closed`}),[s,c]=D(null),[d,f]=D(`all`),p=C({queryKey:Br,queryFn:async()=>(await n.trpcClient.notificationRules.listRules.query({})).rules}),m=C({queryKey:Vr,queryFn:()=>n.trpcClient.notificationOutput.listTargets.query({})}),h=C({queryKey:Hr,queryFn:()=>n.trpcClient.notificationRules.getConditionCatalog.query({})}),g=C({queryKey:Gr,queryFn:async()=>{let e=await n.trpcClient.deviceManager.listAll.query({}),t=[];for(let r of e){let e=M(await n.trpcClient.deviceManager.loadRuntimeState.query({deviceId:r.id}),Kr);e.length>0&&t.push({id:r.id,name:r.name,states:e})}return t},staleTime:6e4}),_=C({queryKey:Wr,queryFn:async()=>(await n.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}),b=C({queryKey:Ur,queryFn:async()=>(await n.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===N.Camera).map(e=>({id:e.id,name:e.name}))}),w=S(()=>{let e=new Map;for(let t of m.data??[])e.set(t.id,t.name);return e},[m.data]),T=O({mutationFn:e=>n.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void p.refetch()}),E=O({mutationFn:e=>n.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>{c(null),p.refetch()}}),A=p.data??[],j=S(()=>A.filter(e=>Wt(e.delivery,d)),[A,d]),P=S(()=>{let e=new Map;for(let t of Ht)e.set(t.key,A.filter(e=>Wt(e.delivery,t.key)).length);return e},[A]),F=Ht.find(e=>e.key===d)??Ht[0],ee=d===`system`;return x(V,{icon:le,title:`Notification Rules`,subtitle:F.blurb,actions:x(v,{size:`sm`,type:`button`,onClick:()=>a({mode:`form`,rule:null,delivery:Gt(d)}),children:[k(z,{className:`h-3.5 w-3.5`}),ee?`New system rule`:`New rule`]}),children:[k(t,{value:d,onValueChange:e=>f(Ut(e)??d),children:k(o,{className:`mb-3`,children:Ht.map(e=>x(y,{value:e.key,children:[e.label,k(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:P.get(e.key)??0})]},e.key))})}),k(zr,{rules:A}),p.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(B,{className:`h-6 w-6 animate-spin text-primary`})}),p.isError&&!p.isLoading&&k(l,{title:`Failed to load rules`,message:p.error instanceof Error?p.error.message:`Unknown error`,onRetry:()=>void p.refetch()}),!p.isLoading&&!p.isError&&j.length===0&&k(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:ee?`No system-event rules yet. Click "New system rule" to be told when a camera drops, a node leaves or an update lands.`:`No ${d===`all`?`notification`:`detection`} rules yet. Click "New rule" to author one.`}),j.length>0&&k(u,{children:k(r,{columns:ee?Yr({targetNameById:w,confirmDeleteId:s,deletePending:E.isPending,onToggle:(e,t)=>T.mutate({ruleId:e.id,enabled:t}),onEdit:e=>a({mode:`form`,rule:e}),onDuplicate:e=>a({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:c,onConfirmDelete:e=>E.mutate(e.id)}):Jr({targetNameById:w,confirmDeleteId:s,deletePending:E.isPending,onToggle:(e,t)=>T.mutate({ruleId:e.id,enabled:t}),onEdit:e=>a({mode:`form`,rule:e}),onDuplicate:e=>a({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:c,onConfirmDelete:e=>E.mutate(e.id),...e?{onTest:e}:{}}),rows:j,rowKey:e=>e.id,minWidthPx:760,bordered:!1})}),i.mode===`form`&&k(Xr,{rule:i.rule,...i.delivery?{newRuleDelivery:i.delivery}:{},targets:m.data??[],actuatable:_.data??[],catalog:Cn(h.data?.catalog??[]),taxonomy:h.data?.taxonomy,cameras:b.data??[],gateable:g.data??[],onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),p.refetch()}})]})}function Jr(e){return[{key:`name`,header:`Rule`,render:e=>x(`span`,{className:`flex items-center gap-2`,children:[k(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&k(f,{variant:`warning`,children:`disabled`}),mn(e.conditions,e.actions?.onTrigger??[])&&k(f,{variant:`info`,children:`Snooze disabilitato (regola allarme)`})]})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:e=>x(`span`,{className:`flex items-center gap-1.5`,children:[k(`span`,{className:`text-[11px] text-foreground-subtle`,children:zt(e.delivery)}),!Vt(e.delivery)&&k(f,{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 k(`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=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>k(d,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>x(`span`,{className:`flex items-center justify-end gap-1`,children:[e.onTest&&k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:`Test — simulate an event this rule should match`,"aria-label":`test ${t.name}`,children:k(De,{className:`h-3.5 w-3.5`})}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onEdit(t),title:`Edit`,children:k(fe,{className:`h-3.5 w-3.5`})}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:k(de,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?x(w,{children:[x(v,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),children:[e.deletePending&&k(B,{className:`h-3.5 w-3.5 animate-spin`}),`Confirm`]}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(t.id),title:`Delete`,children:k(Te,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function Yr(e){let t=Jr(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:dr(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:fr(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 k(`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=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:qt(e.throttle.cooldownSec)})},...n(`enabled`),...n(`actions`)]}function Xr({rule:r,newRuleDelivery:i,targets:s,catalog:c,taxonomy:l,cameras:u,gateable:p,actuatable:h,onSaved:_,onCancel:b}){let S=L(),T=r!=null&&r.id.length>0,[E,A]=D(()=>r?gn(r):hn(i)),[j,M]=D(null),[N,P]=D(null),[F,ee]=D(Mn),I=e=>A(t=>({...t,...e})),te=T&&r?{throttle:r.throttle}:void 0,ne=O({mutationFn:async()=>{let e=En(E,te,c);T&&r?await S.trpcClient.notificationRules.updateRule.mutate({ruleId:r.id,patch:e}):await S.trpcClient.notificationRules.createRule.mutate({rule:e})},onSuccess:_,onError:e=>M(e instanceof Error?e.message:`Save failed`)}),re=O({mutationFn:async()=>{let e=En(E,te,c);return(await S.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>P(null),onSuccess:e=>P(e),onError:e=>M(e instanceof Error?e.message:`Test failed`)}),ie=E.targetIds.map(e=>s.find(t=>t.id===e)?.name??e),ae=e=>I({targetIds:E.targetIds.includes(e)?E.targetIds.filter(t=>t!==e):[...E.targetIds,e]}),oe=C({queryKey:[`userManagement`,`listUsers`],queryFn:()=>S.trpcClient.userManagement.listUsers.query()}).data,se=e=>I({targetUsers:E.targetUsers.includes(e)?E.targetUsers.filter(t=>t!==e):[...E.targetUsers,e]}),ce=Rt.find(e=>e.value===E.delivery)?.hint,R=K(E.delivery),ue=mn(E.conditions,E.actions.sequences),de=jn(E.delivery),fe=de.some(e=>e.key===F)?F:Mn;return Vt(E.delivery)?k(a,{open:!0,onOpenChange:e=>!e&&b(),children:x(e,{width:`lg`,placement:`sheet-on-mobile`,children:[x(`div`,{className:`flex items-center justify-between mb-3`,children:[x(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[k(le,{className:`h-4 w-4 text-foreground-subtle`}),T?`Edit ${r?.name}`:`New notification rule`]}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:b,children:`Cancel`})]}),j&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:j}),x(t,{value:fe,onValueChange:e=>ee(Nn(e)??F),children:[k(o,{className:`mb-3`,children:de.map(e=>k(y,{value:e.key,children:e.label},e.key))}),x(n,{value:`rule`,className:`space-y-4`,children:[x(`div`,{className:`flex items-end gap-3`,children:[x(`div`,{className:`min-w-0 flex-1`,children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),k(g,{value:E.name,onChange:e=>I({name:e.target.value}),placeholder:`e.g. Front door package`})]}),x(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[k(d,{checked:E.enabled,onCheckedChange:e=>I({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),k(m,{value:E.delivery,onChange:e=>{let t=Bt(e.target.value);t&&I({delivery:t})},options:Rt.map(e=>({value:e.value,label:e.label}))}),ce&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:ce})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),s.length===0?k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery targets configured. Add one under the Targets tab first.`}):k(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:s.map(e=>x(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:E.targetIds.includes(e.id),onChange:()=>ae(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&k(f,{variant:`warning`,children:`disabled`})]},e.id))})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(oe??[]).length===0?k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No users to notify.`}):k(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:(oe??[]).map(e=>x(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:E.targetUsers.includes(e.id),onChange:()=>se(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&k(f,{variant:`info`,children:`admin`})]},e.id))}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Delivers to the targets each user owns, only for cameras that user can access.`})]})]}),k(n,{value:`devices`,className:`space-y-4`,children:k(Pr,{devices:h,value:E.deviceIds,onChange:e=>I({deviceIds:e}),loading:h.length===0})}),k(n,{value:`actions`,className:`space-y-4`,children:k(ut,{value:E.actions,onChange:e=>I({actions:e}),devices:h})}),x(n,{value:`advanced`,className:`space-y-4`,children:[x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown`}),k(m,{value:String(E.cooldownSec),onChange:e=>{let t=Yt(e.target.value);t!==void 0&&I({cooldownSec:t})},options:Jt(E.cooldownSec).map(e=>({value:String(e.value),label:e.label}))}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:R?`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.`})]}),x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(d,{checked:E.snoozeAllowGlobal,onCheckedChange:e=>I({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:ue}),`Anyone may snooze this rule for everyone`]}),k(`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.`})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),ue?k(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Snooze disabilitato (regola allarme). Questa regola riguarda — o attiva — il pannello allarme, e nessuna finestra di silenzio può metterla a tacere: né un pulsante, né una pausa aperta dall'app su questa camera o su tutto il feed.`}):x(w,{children:[k(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:un.map(e=>{let t=E.snoozeOptions??ln,n=t.includes(e);return k(v,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>I({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:dn(e)},e)})}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E.snoozeOptions===void 0?`Non impostato — la notifica offre i valori predefiniti (${ln.map(dn).join(`, `)}). Una pausa aperta da un pulsante silenzia questa camera per questa classe di soggetto, solo per chi ha ricevuto la notifica, e non manda il riepilogo.`:E.snoozeOptions.length===0?`Nessun pulsante di pausa su questa regola. È una scelta esplicita: la notifica non si può mettere a tacere dalla schermata di blocco.`:`Massimo quattro. Ogni pulsante toglie spazio ai pulsanti di azione della regola — ntfy ne accetta tre in tutto.`}),E.snoozeOptions!==void 0&&k(v,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>I({snoozeOptions:void 0}),children:`Torna ai valori predefiniti`})]})]})]}),x(n,{value:`notification`,className:`space-y-4`,children:[x(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),k(m,{value:String(E.priority),onChange:e=>I({priority:Number(e.target.value)}),options:cn.map(e=>({value:String(e.value),label:e.label}))})]}),R&&k(`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.`}),!R&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),k(m,{value:E.mediaAttach,onChange:e=>{let t=Zt(e.target.value);t&&I({mediaAttach:t})},options:Xt.map(e=>({value:e.value,label:e.label}))}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Xt.find(e=>e.value===E.mediaAttach)?.description}),x(`div`,{className:`mt-2 space-y-1`,children:[x(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[k(`input`,{type:`checkbox`,checked:E.mediaZoneCrop,onChange:e=>I({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),`Crop the image to the rule's zone`]}),x(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[k(`input`,{type:`checkbox`,checked:E.mediaGif,onChange:e=>I({mediaGif:e.target.checked}),className:`accent-primary`}),`Attach a GIF around the event`]}),x(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[k(`input`,{type:`checkbox`,checked:E.mediaClip,onChange:e=>I({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(E.mediaGif||E.mediaClip)&&x(`div`,{className:`mt-2`,children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),k(m,{value:E.mediaProfile??``,onChange:e=>I({mediaProfile:tn(e.target.value)}),options:en.map(e=>({value:e.value,label:e.label}))}),k(`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.`}),k(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),k(m,{value:E.mediaClipSpeed===void 0?``:String(E.mediaClipSpeed),onChange:e=>I({mediaClipSpeed:kn(e.target.value)}),options:On.map(e=>({value:e.value,label:e.label}))}),k(`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.`})]})]}),!R&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),k(m,{value:E.mediaFrame??``,onChange:e=>I({mediaFrame:$t(e.target.value)}),options:Qt.map(e=>({value:e.value,label:e.label}))}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`What the attached still shows. "Automatic" leaves it to the attachment mode above.`})]})]}),x(`div`,{className:`space-y-2`,children:[x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notification title`}),k(g,{value:E.templateTitle,onChange:e=>I({templateTitle:e.target.value}),placeholder:`{{camera}} — {{class}}`})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notification body`}),k(`textarea`,{value:E.templateBody,onChange:e=>I({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`})]}),x(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`Leave blank to use the backend default text. Supported variables include`,` `,k(`code`,{children:`{{camera}}`}),`, `,k(`code`,{children:`{{class}}`}),`, `,k(`code`,{children:`{{label}}`}),`,`,` `,k(`code`,{children:`{{zone}}`}),`, `,k(`code`,{children:`{{confidence}}`}),`,`,` `,k(`code`,{children:`{{time}}`}),`.`]})]})]}),x(n,{value:`conditions`,className:`space-y-4`,children:[x(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[k(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:R?`Which system events`:`Conditions`}),R&&k(`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.`}),c.length===0?k(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):k(vr,{catalog:c,taxonomy:l,delivery:E.delivery,conditions:E.conditions,schedule:E.schedule,cameras:u,gateable:p,onConditionsChange:e=>I({conditions:e}),onScheduleChange:e=>I({schedule:e})})]}),!R&&x(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[x(`div`,{className:`flex items-center justify-between gap-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),x(v,{size:`sm`,variant:`outline`,type:`button`,disabled:re.isPending||!_n(E),onClick:()=>{M(null),re.mutate()},children:[re.isPending?k(B,{className:`h-3.5 w-3.5 animate-spin`}):k(De,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),N!==null&&k(Qr,{delivery:E.delivery,results:N,targetNames:ie})]})]})]}),x(`div`,{className:`flex justify-end gap-2 mt-4`,children:[k(v,{variant:`secondary`,size:`sm`,type:`button`,onClick:b,children:`Cancel`}),x(v,{size:`sm`,type:`button`,disabled:ne.isPending||!_n(E),onClick:()=>{M(null),ne.mutate()},children:[ne.isPending&&k(B,{className:`h-3.5 w-3.5 animate-spin`}),T?`Save changes`:`Create rule`]})]})]})}):k(Zr,{rule:r,onCancel:b})}function Zr({rule:t,onCancel:n}){let r=Object.keys(t?.conditions??{});return k(a,{open:!0,onOpenChange:e=>!e&&n(),children:x(e,{width:`lg`,placement:`sheet-on-mobile`,children:[x(`div`,{className:`flex items-center justify-between mb-3`,children:[x(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[k(le,{className:`h-4 w-4 text-foreground-subtle`}),t?.name??`Rule`]}),k(f,{variant:`warning`,children:`read-only`})]}),x(`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 `,k(`code`,{children:t?.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.`]}),x(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[x(`div`,{className:`flex gap-2`,children:[k(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),k(`dd`,{className:`text-foreground`,children:t?.delivery})]}),x(`div`,{className:`flex gap-2`,children:[k(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),k(`dd`,{className:`text-foreground`,children:t?.enabled?`yes`:`no`})]}),x(`div`,{className:`flex gap-2`,children:[k(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),k(`dd`,{className:`text-foreground`,children:t?.targets.length??0})]}),x(`div`,{className:`flex gap-2`,children:[k(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),k(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):`none`})]})]}),k(`div`,{className:`flex justify-end gap-2 mt-4`,children:k(v,{variant:`secondary`,size:`sm`,type:`button`,onClick:n,children:`Close`})})]})})}function Qr({delivery:e,results:t,targetNames:n}){if(e===`device-event`)return k(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`});if(t.length===0)return k(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`No records in the last 60 minutes matched — nothing to evaluate.`});let r=t.filter(e=>e.wouldFire).length;return x(`div`,{className:`mt-2 space-y-1.5`,children:[x(`div`,{className:`text-[11px] text-foreground-subtle`,children:[r,` of `,t.length,` evaluated record`,t.length===1?``:`s`,` would fire.`]}),k(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>x(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?k(ue,{className:`h-3.5 w-3.5 shrink-0 text-success`}):k(ye,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),k(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),x(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),k(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`object`}),e.wouldFire?x(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,n.join(`, `)||`targets`]}):e.failedCondition&&x(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}var $r=[{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 ei(e){return $r.find(t=>t.value===e)?.value}function ti(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function ni(e){return``}var ri={x:.25,y:.25,w:.5,h:.5},ii={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function ai(){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:ri,occupancy:ii,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function oi(e){return e.deviceId!==null}function Y(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function si(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function ci(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 li(e){if(e.deviceId===null)return null;let t=e.trigger,n=si(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:ui(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 ui(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 di(e){return Math.min(1,Math.round((e+.05)*100)/100)}function fi(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 pi(e){let t=ai(),n=e.conditions,r=fi(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:di(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:di(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:di(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:ni(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:mi(n.occupancy)},onlyRuleId:e.id}}function mi(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 hi(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.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 gi(e){return{form:pi(e),caveats:hi(e),ruleName:e.name}}var _i=null;function vi(e){_i=e}function yi(){return _i}function bi(){_i=null}var xi=[`n/a`,`clear`,`suppressed`,`bypassed`],Si=[`live`,`none`,`unavailable`,`unattachable`];function Ci(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e,t){let n=e[t];return typeof n==`string`?n:void 0}function wi(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Ti(e){if(!Ci(e))return null;let t=X(e,`ruleId`),n=X(e,`ruleName`),r=X(e,`cooldown`),i=xi.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=X(e,`failedCondition`),o=Array.isArray(e.matchedOn)?wi(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:wi(e,`targetIds`)}}function Ei(e){if(!Ci(e))return null;let t=X(e,`recordId`),n=X(e,`delivery`),r=X(e,`still`),i=Si.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=Ti(e);t!==null&&o.push(t)}let s=X(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:wi(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Di(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 Oi=new Set([`sensor`,`control`,`custom`]);function ki({form:e,cameras:t,taxonomy:n,kinds:r,kindsLoading:i,onPatch:a}){let o=e.deviceId===null?[]:[e.deviceId],s=P(`classes`,n);if(e.trigger===`device-event`)return x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),k(Ai,{form:e,kinds:r,loading:i,onPatch:a})]});if(e.trigger===`audio-event`){let n=r.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),x(`div`,{children:[k(`label`,{className:q,children:`Audio classes`}),k(G,{options:n,value:e.classNames,onChange:e=>a({classNames:e}),loading:i,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…`})]}),x(`div`,{children:[k(`label`,{className:q,children:`Zones`}),k(Bn,{deviceIds:o,cameras:t,value:e.zones,onChange:e=>a({zones:e})})]})]})}return e.trigger===`occupancy-event`?x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),k(ji,{form:e,cameras:t,taxonomy:n,onPatch:a})]}):x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),x(`div`,{children:[k(`label`,{className:q,children:`Detected classes`}),s===null?k(Fn,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>a({classNames:e})}):k(In,{picker:s,value:e.classNames,onChange:e=>a({classNames:e})})]}),x(`div`,{children:[k(`label`,{className:q,children:`Zones the subject is in`}),k(Bn,{deviceIds:o,cameras:t,value:e.zones,onChange:e=>a({zones:e})})]}),e.trigger===`package-event`&&x(`div`,{className:`max-w-[14rem]`,children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),k(m,{value:e.packagePhase,options:[{value:``,label:`— none —`},{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`}],onChange:e=>a({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function Ai({form:e,kinds:t,loading:n,onPatch:r}){let i=t.filter(e=>Oi.has(e.category)),a=i.find(t=>t.kind===e.sensorKind);return x(w,{children:[x(`div`,{children:[k(`label`,{className:q,children:`Event kind`}),k(m,{value:e.sensorKind,options:[{value:``,label:n?`Loading kinds…`:`— pick a kind —`},...i.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=i.find(t=>t.kind===e.target.value);r({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!n&&i.length===0&&k(`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.`})]}),x(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[x(`div`,{children:[k(`label`,{className:q,children:`Source device`}),k(g,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>r({sourceDeviceId:Y(e.target.value)??null})}),k(`p`,{className:J,children:a===void 0?`The linked device whose state changed. Filled in for you when you pick a kind.`:`Filled in from "${a.label}" — contributed by device #${a.source.deviceId} via the ${a.source.capName} capability.`})]}),x(`div`,{children:[k(`label`,{className:q,children:`Event type token`}),k(g,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>r({eventType:e.target.value})}),k(`p`,{className:J,children:`Only event-emitter sources carry one. A passive sensor emits none, and a rule gating on a token would fail closed for it.`})]})]})]})}function ji({form:e,cameras:t,taxonomy:n,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId],a=P(`classes`,n),o=a===null?[]:a.groups.flatMap(e=>e.options),s=e.occupancy,c=e=>r({occupancy:{...s,...e}});return x(w,{children:[x(`div`,{children:[k(`label`,{className:q,children:`Zone`}),k(Bn,{deviceIds:i,cameras:t,value:s.zoneId===``?[]:[s.zoneId],onChange:e=>c({zoneId:e[e.length-1]??``})}),k(`p`,{className:J,children:`Leave empty for the whole frame.`})]}),x(`div`,{className:`max-w-[14rem]`,children:[k(`label`,{className:q,children:`Class`}),k(m,{value:s.className,options:[{value:``,label:`— any class —`},...o.map(e=>({value:e.value,label:e.label}))],onChange:e=>c({className:e.target.value})})]}),x(`div`,{className:`flex flex-wrap items-end gap-3`,children:[x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count now`,k(g,{type:`number`,min:0,className:`w-20`,value:String(s.count),onChange:e=>c({count:Y(e.target.value)??0})})]}),x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,k(g,{type:`number`,min:0,className:`w-20`,value:String(s.previousCount),onChange:e=>c({previousCount:Y(e.target.value)??0})})]}),x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,k(g,{type:`number`,min:1,className:`w-20`,value:String(s.threshold),onChange:e=>c({threshold:Y(e.target.value)??1})})]}),x(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[k(d,{checked:s.occupied,onCheckedChange:e=>c({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function Mi({form:e,cameras:t,onPatch:n}){let r=e.deviceId===null?[]:[e.deviceId];return x(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[k(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Advanced`}),x(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(d,{checked:e.crossingEnabled,onCheckedChange:e=>n({crossingEnabled:e}),"aria-label":`zone crossing`}),`This event is a confirmed zone crossing`]}),e.crossingEnabled&&x(`div`,{className:`mt-1 space-y-1.5`,children:[k(`div`,{className:`max-w-[12rem]`,children:k(m,{value:e.crossingDirection,options:[{value:`enter`,label:`Entered the zone`},{value:`exit`,label:`Left the zone`}],onChange:e=>n({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),k(Bn,{deviceIds:r,cameras:t,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>n({crossingZoneId:e[e.length-1]??``})})]})]}),x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(d,{checked:e.bboxEnabled,onCheckedChange:e=>n({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),k(`p`,{className:J,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&k(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,k(g,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:r=>n({bbox:{...e.bbox,[t]:Y(r.target.value)??0}})})]},t))})]}),x(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[x(`div`,{children:[k(`label`,{className:q,children:`Happened at`}),x(`div`,{className:`flex items-center gap-2`,children:[k(g,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>n({timestampLocal:e.target.value})}),e.timestampLocal===``?k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:ci(Date.now())}),children:`Set`}):k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:``}),children:`Now`})]}),k(`p`,{className:J,children:`Empty = now. Set it to a time inside (or outside) a rule's schedule window to test the schedule without waiting for the hour.`})]}),x(`div`,{children:[k(`label`,{className:q,children:`Detection source`}),k(m,{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;n({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function Ni({checked:e,label:t,hint:n,danger:r=!1,onChange:i}){return x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(d,{checked:e,onCheckedChange:i,"aria-label":t}),t,r&&k(f,{variant:`danger`,children:`actuates devices`})]}),k(`p`,{className:J,children:n})]})}b();var Pi={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.`},Fi={"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 Ii({result:e,targetName:t}){return x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[k(`p`,{className:`text-xs font-medium text-foreground`,children:Di(e)}),x(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[k(Li,{recordId:e.recordId}),x(`span`,{children:[`delivery `,k(`span`,{className:`text-foreground`,children:e.delivery})]}),x(`span`,{children:[`candidates `,k(`span`,{className:`text-foreground`,children:e.candidates})]}),x(`span`,{title:Pi[e.still],children:[`still `,k(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&x(f,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&k(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>k(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?x(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`No rule was evaluated. Either no enabled rule declares the`,` `,k(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):k(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>k(Ri,{outcome:e,targetName:t},e.ruleId))})]})}function Li({recordId:e}){let[t,n]=D(!1);return x(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[k(`code`,{className:`text-[10px] text-foreground`,children:e}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{n(!0),setTimeout(()=>n(!1),1500)},()=>n(!1))},title:`Copy record id`,children:k(de,{className:`h-3 w-3`})}),t&&k(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function Ri({outcome:e,targetName:t}){return x(`li`,{className:`space-y-1 px-2.5 py-2`,children:[x(`div`,{className:`flex items-center gap-2`,children:[e.matched?k(ue,{className:`h-3.5 w-3.5 shrink-0 text-success`}):k(ye,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),k(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),x(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:Fi[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&k(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?`Did not match. The engine reported no failing condition id.`:x(w,{children:[`Did not match — first failing condition`,` `,k(`code`,{className:`text-foreground`,children:e.failedCondition}),`.`]})}),e.matched&&x(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[e.enqueued,` outbox row`,e.enqueued===1?``:`s`,` enqueued`,e.targetIds.length>0?` → ${e.targetIds.map(t).join(`, `)}`:` — no target resolved, so nothing will be delivered`,`.`]}),e.matchedOn!==void 0&&e.matchedOn.length>0&&x(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:[`matched on: `,e.matchedOn.join(`, `)]})]})}b();var zi=`pipeline-analytics`,Bi=`nc.injectTestEvent`;function Vi(){let e=L(),[t,n]=D(()=>yi()?.form??ai()),[r]=D(()=>yi()?.caveats??[]),[i]=D(()=>yi()?.ruleName??null);A(()=>bi(),[]);let[a,o]=D(null),[s,c]=D(!1),[d,f]=D(null),p=e=>n(t=>({...t,...e})),h=C({queryKey:Ur,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===N.Camera).map(e=>({id:e.id,name:e.name}))}),_=C({queryKey:Hr,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),y=C({queryKey:Br,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),b=C({queryKey:Vr,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),w=t.deviceId,T=C({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:w}],enabled:w!==null,staleTime:6e4,queryFn:async()=>w===null?[]:(await e.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[w]})).flatMap(e=>[...e.kinds])}),E=h.data??[],j=_.data?.taxonomy,M=T.data??[],P=S(()=>{let e=new Map;for(let t of b.data??[])e.set(t.id,t.name);return e},[b.data]),F=O({mutationFn:async()=>{let n=li(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:zi,action:Bi,input:n})},onMutate:()=>{o(null),c(!1),f(null)},onSuccess:e=>{let t=Ei(e);o(t),c(t===null)},onError:e=>f(e instanceof Error?e.message:`The simulation failed.`)}),ee=ti(t.trigger),I=y.data?.find(e=>e.id===t.onlyRuleId);return x(V,{icon:De,title:`Simulate an event`,subtitle:`Inject a synthetic detection, doorbell press or occupancy edge and see exactly which rules match it, which condition each one fails on, and what would be delivered. Nothing is persisted — no track, no event row, no media.`,children:[h.isError&&k(l,{title:`Failed to load cameras`,message:h.error instanceof Error?h.error.message:`Unknown error`,onRetry:()=>void h.refetch()}),i!==null&&x(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:[`Seeded from the rule `,k(`span`,{className:`font-medium`,children:i}),`. Only that rule will be evaluated — clear "Evaluate only one rule" below to run the whole rule set.`]}),r.length>0&&k(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:r.map(e=>x(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[k(we,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),k(`span`,{children:e.note})]},e.conditionId))}),x(u,{className:`space-y-4`,children:[x(`div`,{children:[k(`label`,{className:q,children:`Camera`}),k(m,{"data-testid":`simulate-camera`,value:t.deviceId===null?``:String(t.deviceId),options:[{value:``,label:E.length===0?`Loading cameras…`:`— pick a camera —`},...E.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{p({deviceId:Y(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),k(`p`,{className:J,children:`The camera the event is attributed to — what a notification shows.`})]}),x(`div`,{children:[k(`label`,{className:q,children:`Trigger`}),k(m,{"data-testid":`simulate-trigger`,value:t.trigger,options:$r.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=ei(e.target.value);if(!n)return;let r=ni(t.trigger);p({trigger:n,source:t.source===``||t.source===r?ni(n):t.source})}}),x(`p`,{className:J,children:[$r.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,k(`span`,{className:`text-foreground`,children:ee}),` are candidates.`]})]}),k(ki,{form:t,cameras:E,taxonomy:j,kinds:M,kindsLoading:T.isLoading,onPatch:p}),x(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[k(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),x(`div`,{className:`mt-2 space-y-3`,children:[k(`p`,{className:J,children:`Every field here can be left EMPTY, and empty is a real state: a rule with a minimum confidence FAILS on a subject that carries none. Leave one blank to reproduce exactly that.`}),x(`div`,{children:[k(`label`,{className:q,children:`Label (identity name / plate / subclass)`}),k(g,{value:t.label,placeholder:`e.g. Marco, AB123CD`,onChange:e=>p({label:e.target.value})})]}),x(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[x(`div`,{children:[k(`label`,{className:q,children:`Detection confidence`}),k(Ln,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>p({confidence:e})})]}),x(`div`,{children:[k(`label`,{className:q,children:`Label-match confidence`}),k(Ln,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>p({labelConfidence:e})})]}),x(`div`,{children:[k(`label`,{className:q,children:`Importance`}),k(Ln,{value:t.importance,min:0,max:1,step:.05,onChange:e=>p({importance:e})})]}),x(`div`,{children:[k(`label`,{className:q,children:`Dwell (seconds)`}),k(Ln,{value:t.dwellSeconds,min:0,step:1,onChange:e=>p({dwellSeconds:e})})]})]})]})]}),k(Mi,{form:t,cameras:E,onPatch:p}),x(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),k(Ni,{checked:t.bypassCooldown,label:`Ignore the cooldown`,hint:`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`,onChange:e=>p({bypassCooldown:e})}),k(Ni,{checked:t.bypassMute,label:`Ignore mutes and snoozes`,hint:`A muted camera or a snoozed rule drops the event before any rule is consulted.`,onChange:e=>p({bypassMute:e})}),k(Ni,{checked:t.runActions,danger:!0,label:`Run the rule's actions — this actuates real devices`,hint:`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`,onChange:e=>p({runActions:e})}),x(`div`,{className:`max-w-[14rem]`,children:[k(`label`,{className:q,children:`Still image`}),k(m,{value:t.still,options:[{value:`live`,label:`Live snapshot of the camera`},{value:`none`,label:`No image`}],onChange:e=>p({still:e.target.value===`none`?`none`:`live`})})]}),x(`div`,{children:[k(`label`,{className:q,children:`Evaluate only one rule`}),k(m,{value:t.onlyRuleId,options:[{value:``,label:`— every enabled rule —`},...(y.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>p({onlyRuleId:e.target.value})}),t.onlyRuleId.length>0&&I===void 0&&x(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,k(`code`,{children:t.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),d!==null&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:d}),x(`div`,{className:`flex items-center justify-between gap-2`,children:[k(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`}),x(v,{size:`sm`,type:`button`,disabled:F.isPending||!oi(t),onClick:()=>F.mutate(),children:[F.isPending?k(B,{className:`h-3.5 w-3.5 animate-spin`}):k(De,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),s&&k(`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.`}),a!==null&&k(Ii,{result:a,targetName:e=>P.get(e)??e})]})}var Z=e=>typeof e==`string`&&e.length>0;function Hi(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 Ui(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Wi(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Z(i)&&n.push({mediaType:r,url:i})}return n}function Gi(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Z(r.label),i=Z(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 Ki(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Wi(e,t.attachmentUrls),i=Gi(e,t.actions),a=e.ttl&&Z(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:Ui(e,t.format),priority:qi(t.priority),...Z(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Z(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Z(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Z(t.tag)?{tag:t.tag}:{}}}function qi(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function Ji(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 Yi(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Xi={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 Zi(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function Qi(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])Zi(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function $i(e,t,n){let r=Yi(e);return Zi(e,t)?{...r,body:n,attachmentUrls:{[t]:Xi[t]}}:{...r,body:n}}function ea(e,t){let n=Yi(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return $i(e,`image`,`Test notification with an image.`);case`gif`:return $i(e,`gif`,`Test notification with an animation.`);case`video`:return $i(e,`video`,`Test notification with a video.`);case`audio`:return $i(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=Ji(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}b();var ta={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},Q=`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 na({target:t,kind:n,open:r,onClose:i}){let o=L(),s=S(()=>Hi(n.caps),[n.caps]),c=S(()=>Qi(n.caps),[n.caps]),[l,u]=D(()=>Yi(n.caps)),[d,m]=D(null),g=S(()=>Ki(n.caps,l),[n.caps,l]),y=l.body.length,b=y>s.bodyMaxLen,C=e=>u(t=>({...t,...e})),w=O({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:t.addonId,targetId:t.id,sample:Ki(n.caps,l)}),onMutate:()=>m(null),onSuccess:e=>m(e),onError:e=>m({success:!1,error:e instanceof Error?e.message:`Test failed`})}),T=e=>{u(ea(n.caps,e)),m(null)},E=(e,t,n)=>{let r=l.actions.length>0?[...l.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},C({actions:r})};return k(a,{open:r,onOpenChange:e=>!e&&i(),children:x(e,{width:`lg`,className:`!max-w-2xl`,children:[k(p,{children:x(h,{children:[`Test "`,t.name,`" (`,n.label,`)`]})}),x(`div`,{className:`space-y-4 max-h-[60vh] overflow-y-auto pr-1`,children:[k(`div`,{className:`flex flex-wrap gap-1.5`,children:c.map(e=>k(v,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>T(e),children:ta[e]},e))}),x(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.levels.length>0&&x(`div`,{children:[k(`label`,{className:$,children:`Level`}),x(`select`,{className:Q,value:l.level,onChange:e=>C({level:e.target.value}),children:[k(`option`,{value:``,children:`— derive from priority —`}),s.levels.map(e=>x(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=s.levels.find(e=>e.id===l.level);return e?x(`div`,{className:`mt-1 space-y-1`,children:[e.description&&k(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),x(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&k(f,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&k(f,{variant:`info`,children:`silent`}),e.flags?.noPush&&k(f,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&x(`p`,{className:`text-[10px] text-warning`,children:[`Requires target config: `,e.requires.join(`, `)]})]}):null})()]}),x(`div`,{children:[x(`label`,{className:$,children:[`Priority (ordinal): `,l.priority]}),k(`input`,{type:`range`,min:1,max:5,step:1,value:l.priority,onChange:e=>C({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),s.formats.length>0&&x(`div`,{children:[k(`label`,{className:$,children:`Format`}),k(`div`,{className:`flex flex-wrap gap-2`,children:s.formats.map(e=>x(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[k(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:l.format===e,onChange:()=>C({format:e})}),e]},e))})]}),x(`div`,{children:[k(`label`,{className:$,children:`Title`}),k(`input`,{className:Q,value:l.title,onChange:e=>C({title:e.target.value})})]}),x(`div`,{children:[x(`label`,{className:$,children:[`Body`,` `,x(`span`,{className:b?`text-danger`:`text-foreground-subtle`,children:[`(`,y,`/`,s.bodyMaxLen,b?` — overflow`:``,`)`]})]}),k(`textarea`,{className:`${Q} min-h-[80px] resize-y`,value:l.body,onChange:e=>C({body:e.target.value})})]}),s.attachmentSlots.length>0&&x(`div`,{children:[x(`label`,{className:$,children:[`Attachments`,` `,x(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,s.attachmentMode,`, max `,s.attachmentMax,s.attachmentMaxBytes?`, ≤${Math.round(s.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),k(`div`,{className:`space-y-1.5`,children:s.attachmentSlots.map(e=>x(`div`,{className:`flex items-center gap-2`,children:[k(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),k(`input`,{className:Q,placeholder:`${e} URL`,value:l.attachmentUrls[e]??``,onChange:t=>C({attachmentUrls:{...l.attachmentUrls,[e]:t.target.value}})})]},e))})]}),s.showActions&&x(`div`,{children:[x(`label`,{className:$,children:[`Actions (up to `,s.maxActions,`)`]}),k(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(s.maxActions,3)},(e,t)=>x(`div`,{className:`flex items-center gap-2`,children:[k(`input`,{className:Q,placeholder:`label`,value:l.actions[t]?.label??``,onChange:e=>E(t,`label`,e.target.value)}),k(`input`,{className:Q,placeholder:`url`,value:l.actions[t]?.url??``,onChange:e=>E(t,`url`,e.target.value)})]},t))})]}),x(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.showClickUrl&&x(`div`,{children:[k(`label`,{className:$,children:`Click URL`}),k(`input`,{className:Q,value:l.clickUrl,onChange:e=>C({clickUrl:e.target.value})})]}),s.showSound&&x(`div`,{children:[k(`label`,{className:$,children:`Sound`}),k(`input`,{className:Q,value:l.sound,onChange:e=>C({sound:e.target.value})})]}),s.showTtl&&x(`div`,{children:[k(`label`,{className:$,children:`TTL (seconds)`}),k(`input`,{className:Q,type:`number`,value:l.ttl,onChange:e=>C({ttl:e.target.value})})]}),s.showTag&&x(`div`,{children:[k(`label`,{className:$,children:`Tag`}),k(`input`,{className:Q,value:l.tag,onChange:e=>C({tag:e.target.value})})]})]}),d&&k(ra,{result:d}),x(`details`,{className:`text-[10px]`,children:[k(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),k(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(g,null,2)})]})]}),x(_,{children:[k(v,{variant:`secondary`,size:`sm`,type:`button`,onClick:i,children:`Close`}),x(v,{size:`sm`,type:`button`,disabled:w.isPending||l.body.length===0,onClick:()=>w.mutate(),children:[w.isPending?k(B,{className:`h-3.5 w-3.5 animate-spin`}):k(ge,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function ra({result:e}){let t=e.renderedAs;return x(`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:[x(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?k(ue,{className:`h-3.5 w-3.5 text-success`}):k(ye,{className:`h-3.5 w-3.5 text-danger`}),k(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&k(`p`,{className:`mt-1 text-danger`,children:e.error}),t&&x(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[k(`dt`,{children:`Resolved level`}),k(`dd`,{className:`text-foreground`,children:t.level}),k(`dt`,{children:`Format sent`}),k(`dd`,{className:`text-foreground`,children:t.format}),k(`dt`,{children:`Attachments sent`}),k(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),k(`dt`,{children:`Actions sent`}),k(`dd`,{className:`text-foreground`,children:t.actionsSent}),k(`dt`,{children:`Truncated`}),k(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),k(`dt`,{children:`Dropped`}),k(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function ia(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 aa(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 oa(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 sa(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))r[t]=n.has(t)?``:i;return r}b();var ca=[`notificationOutput`,`listTargets`],la=[`notificationOutput`,`listTargetKinds`],ua=[`userManagement`,`listUsers`],da=`ownerUserId`;function fa(e){let t=e.config[da];return typeof t==`string`&&t.length>0?t:null}function pa(e){return[{key:`name`,header:`Target`,render:t=>{let n=e.kindByKey.get(t.kind);return x(`span`,{className:`flex items-center gap-2`,children:[k(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:n?.label??t.kind,children:k(ma,{kind:n,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),k(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name}),!t.enabled&&k(f,{variant:`warning`,children:`disabled`})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>k(`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=fa(t);return n===null?k(f,{variant:`default`,children:`system`}):k(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>k(d,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let n=e.kindByKey.get(t.kind);return x(`span`,{className:`flex items-center justify-end gap-1`,children:[k(v,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>e.onTest(t),title:`Test`,children:k(ge,{className:`h-3.5 w-3.5`})}),k(v,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>n&&e.onEdit(t,n),title:`Edit`,children:k(fe,{className:`h-3.5 w-3.5`})}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:k(Te,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function ma({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?k(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):k(`span`,{className:n,children:e?.icon??`🔔`})}function ha(){let e=L(),[t,n]=D({mode:`closed`}),[i,a]=D(null),o=C({queryKey:ca,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),s=C({queryKey:la,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),c=S(()=>s.data??[],[s.data]),d=S(()=>{let e=new Map;for(let t of c)e.set(t.kind,t);return e},[c]),f=C({queryKey:ua,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),p=S(()=>{let e=new Map;for(let t of f.data??[])e.set(t.id,t.username);return e},[f.data]),m=O({mutationFn:t=>e.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:t.target.addonId,targetId:t.target.id,enabled:t.enabled}),onSuccess:()=>void o.refetch()}),h=O({mutationFn:t=>e.trpcClient.notificationOutput.deleteTarget.mutate({addonId:t.addonId,targetId:t.id}),onSuccess:()=>void o.refetch()}),g=i?d.get(i.kind):void 0;return x(V,{icon:be,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:x(v,{size:`sm`,type:`button`,onClick:()=>n({mode:`pick-kind`}),children:[k(z,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[o.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(B,{className:`h-6 w-6 animate-spin text-primary`})}),o.isError&&!o.isLoading&&k(l,{title:`Failed to load targets`,message:o.error instanceof Error?o.error.message:`Unknown error`,onRetry:()=>void o.refetch()}),!o.isLoading&&!o.isError&&(o.data??[]).length===0&&k(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification targets yet. Click "Add target" to configure one.`}),(o.data??[]).length>0&&k(u,{children:k(r,{columns:pa({kindByKey:d,userNameById:p,onToggle:(e,t)=>m.mutate({target:e,enabled:t}),onTest:a,onEdit:(e,t)=>n({mode:`form`,kind:t,target:e}),onDelete:e=>h.mutate(e)}),rows:o.data??[],rowKey:e=>e.id,minWidthPx:720,bordered:!1})}),t.mode===`pick-kind`&&k(ga,{kinds:c,onCancel:()=>n({mode:`closed`}),onPick:e=>n({mode:`form`,kind:e,target:null})}),t.mode===`form`&&k(_a,{kind:t.kind,target:t.target,users:f.data??[],onCancel:()=>n({mode:`closed`}),onSaved:()=>{n({mode:`closed`}),o.refetch()}}),i&&g&&k(na,{target:i,kind:g,open:!0,onClose:()=>a(null)})]})}function ga({kinds:e,onPick:t,onCancel:n}){let r=S(()=>ia(e),[e]);return x(u,{className:`p-4 space-y-4`,children:[x(`div`,{className:`flex items-center justify-between`,children:[k(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:n,children:`Cancel`})]}),r.length===0&&k(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`}),r.map(e=>x(`div`,{children:[k(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),k(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(n=>x(`button`,{type:`button`,onClick:()=>t(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:[k(ma,{kind:n,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),k(`span`,{className:`font-medium text-foreground`,children:n.label}),n.supportsDiscovery&&k(f,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})}function _a({kind:e,target:t,users:n,onSaved:r,onCancel:i}){let a=L(),o=S(()=>aa(e.configSchema),[e.configSchema]),c=S(()=>t?.config??{},[t]),[l,d]=D(t?.name??e.label),[f,p]=D(()=>t?sa(t.config,o):{}),[h,g]=D(null),[_,y]=D(null),[b,C]=D(t?fa(t)??``:``),w=O({mutationFn:()=>a.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:f}),onSuccess:e=>g(e),onError:e=>y(e instanceof Error?e.message:`Discovery failed`)}),T=O({mutationFn:()=>{let{[da]:n,...r}=oa(f,c,o),i=b===``?r:{...r,[da]:b},s={id:t?.id??`${e.kind}-${Date.now()}`,name:l,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:i};return a.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:s})},onSuccess:r,onError:e=>y(e instanceof Error?e.message:`Save failed`)}),E=e=>{d(e.suggestedName),p(t=>({...t,...e.config})),g(null)};return x(u,{className:`p-4 space-y-4`,children:[x(`div`,{className:`flex items-center justify-between`,children:[x(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[k(ma,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),t?`Edit ${t.name}`:`Add ${e.label} target`]}),k(v,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),_&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),k(`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:l,onChange:e=>d(e.target.value)})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),k(m,{value:b,options:[{value:``,label:`System (shared, admin-managed)`},...n.map(e=>({value:e.id,label:e.username}))],onChange:e=>C(e.target.value)}),k(`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&&x(`div`,{className:`space-y-2`,children:[x(v,{size:`sm`,variant:`outline`,type:`button`,disabled:w.isPending,onClick:()=>{y(null),w.mutate()},children:[w.isPending?k(B,{className:`h-3.5 w-3.5 animate-spin`}):k(he,{className:`h-3.5 w-3.5`}),`Discover`]}),h&&h.length===0&&k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),h&&h.length>0&&k(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:h.map((e,t)=>x(`button`,{type:`button`,onClick:()=>E(e),className:`flex w-full items-center justify-between px-3 py-1.5 text-xs hover:bg-surface-hover`,children:[k(`span`,{className:`text-foreground`,children:e.suggestedName}),k(`span`,{className:`text-[10px] text-primary`,children:`use`})]},`${e.suggestedName}-${t}`))})]}),o.length>0&&t&&k(`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.`}),k(s,{schema:e.configSchema,values:f,onChange:p}),x(`div`,{className:`flex justify-end gap-2`,children:[k(v,{variant:`secondary`,size:`sm`,type:`button`,onClick:i,children:`Cancel`}),x(v,{size:`sm`,type:`button`,disabled:T.isPending||l.trim().length===0,onClick:()=>{y(null),T.mutate()},children:[T.isPending&&k(B,{className:`h-3.5 w-3.5 animate-spin`}),t?`Save changes`:`Create target`]})]})]})}var va=`pipeline-analytics`,ya=`nc.getTexts`,ba=`nc.setLanguage`,xa=`nc.setTextOverrides`,Sa={en:`English`,it:`Italiano`};function Ca(e){return e===`en`||e===`it`}function wa(e){return e===`override`||e===`shipped`||e===`fallback`}function Ta(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ea(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 Da(e){if(!Ta(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`||!Ca(r)||!wa(o)||i!==null&&typeof i!=`string`)return null;let s=Ea(e.placeholders),c=Ea(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 Oa(e){if(!Ta(e))return null;let{language:t,activeLanguage:n}=e;if(!Ca(t)||!Ca(n))return null;let r=Ea(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Ca(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=Da(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function ka(e,t){return t.get(e.key)??e.override??e.shipped}function Aa(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 ja(e,t){return Object.keys(Aa(e,t)).length}function Ma(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 Na(e){return e.placeholders.length===0?`No variables — this text is printed as written.`:`Variables: ${e.placeholders.map(e=>`{{${e}}}`).join(` `)}`}function Pa(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.`}b();var Fa=`notificationTexts`,Ia=`Every sentence the Notification Center can print — and your wording for it.`;function La({entry:e,value:t,busy:n,onChange:r,onReset:i}){let a=Pa(e),o=e.override!==null;return x(`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:[x(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[k(`code`,{className:`text-xs font-medium`,children:e.key}),o?k(f,{variant:`info`,children:`customised`}):null,e.source===`fallback`?k(f,{variant:`warning`,children:`English fallback`}):null]}),x(`div`,{className:`flex items-start gap-2`,children:[k(g,{value:t,disabled:n,onChange:e=>r(e.target.value),className:`flex-1 font-mono text-xs`,"data-testid":`text-input-${e.key}`}),k(v,{variant:`ghost`,size:`sm`,disabled:n||!o&&t===e.shipped,onClick:i,title:`Reset to the shipped wording`,"data-testid":`text-reset-${e.key}`,children:k(me,{className:`h-3.5 w-3.5`})})]}),x(`p`,{className:`text-xs text-foreground-subtle`,children:[k(`span`,{className:`font-medium`,children:`Shipped:`}),` `,k(`span`,{className:`font-mono`,children:e.shipped})]}),k(`p`,{className:`text-xs text-foreground-subtle`,children:Na(e)}),a===null?null:k(`p`,{className:`text-xs text-warning`,children:a})]})}function Ra(){let e=L(),t=E(),[n,r]=D(null),[i,a]=D(``),[o,s]=D(new Map),[c,d]=D(!1),f=C({queryKey:[Fa,n??`hub`],queryFn:async()=>{let t=Oa(await e.trpcClient.addons.custom.mutate({addonId:va,action:ya,input:n===null?{}:{language:n}}));return d(t===null),t}}),p=()=>{s(new Map),t.invalidateQueries({queryKey:[Fa]})},h=O({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:va,action:ba,input:{language:t}}),onSuccess:p}),_=O({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:va,action:xa,input:t}),onSuccess:p}),y=f.data??null,b=S(()=>y===null?[]:Ma(y.entries,i),[y,i]);if(f.isLoading)return k(V,{icon:ke,title:`Texts`,subtitle:Ia,children:k(B,{className:`h-5 w-5 animate-spin`})});if(f.isError||y===null)return k(V,{icon:ke,title:`Texts`,subtitle:Ia,children:k(l,{title:`The notification text catalog is not available on this hub`,message:c?`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 w=y.language,T=h.isPending||_.isPending,A=Aa(y.entries,o),j=ja(y.entries,o),M=y.entries.filter(e=>e.override!==null).length,N=y.languages.map(e=>({value:e,label:Sa[e]})),P=(e,t)=>s(n=>new Map(n).set(e,t)),F=e=>P(e.key,e.shipped);return k(V,{icon:ke,title:`Texts`,subtitle:Ia,children:x(`div`,{className:`flex flex-col gap-4`,children:[h.isError?k(l,{title:`Could not change the language`,message:String(h.error)}):null,_.isError?k(l,{title:`Could not save`,message:String(_.error)}):null,x(u,{className:`p-4`,children:[x(`div`,{className:`flex flex-wrap items-end gap-6`,children:[x(`div`,{className:`flex flex-col gap-1`,children:[k(`label`,{className:`text-sm font-medium`,children:`Hub language`}),k(`div`,{className:`w-44`,children:k(m,{value:y.activeLanguage,disabled:T,options:N,onChange:e=>{let t=e.target.value;Ca(t)&&h.mutate(t)},"data-testid":`texts-hub-language`})}),k(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),x(`div`,{className:`flex flex-col gap-1`,children:[k(`label`,{className:`text-sm font-medium`,children:`Editing`}),k(`div`,{className:`w-44`,children:k(m,{value:w,disabled:T,options:N,onChange:e=>{let t=e.target.value;Ca(t)&&(s(new Map),r(t))},"data-testid":`texts-editing-language`})}),k(`p`,{className:`text-xs text-foreground-subtle`,children:w===y.activeLanguage?`${M} of ${y.entries.length} texts customised.`:`This hub does not speak this language — these words are not in use yet.`})]})]}),k(`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.`})]}),x(`div`,{className:`flex items-center gap-3`,children:[x(`div`,{className:`relative flex-1`,children:[k(he,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),k(g,{value:i,placeholder:`Search a key or a sentence…`,onChange:e=>a(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),x(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[b.length,` of `,y.entries.length]}),x(v,{disabled:T||j===0,onClick:()=>_.mutate({language:w,overrides:A}),"data-testid":`texts-save`,children:[T?k(B,{className:`h-3.5 w-3.5 animate-spin`}):null,j===0?`Save`:`Save ${j}`]})]}),k(`div`,{className:`flex flex-col gap-2`,"data-testid":`texts-rows`,children:b.length===0?k(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):b.map(e=>k(La,{entry:e,value:ka(e,o),busy:T,onChange:t=>P(e.key,t),onReset:()=>F(e)},e.key))})]})})}var za=`simulate`;function Ba(){let[e,t]=ve();return k(`div`,{className:`flex flex-col p-4`,children:k(Ee,{tabs:[{id:`targets`,label:`Targets`,icon:be,content:k(ha,{})},{id:`rules`,label:`Rules`,icon:le,content:k(qr,{onSimulateRule:n=>{vi(gi(n));let r=new URLSearchParams(e);r.set(`tab`,za),t(r,{replace:!0})}})},{id:za,label:`Simulate`,icon:De,content:k(Vi,{})},{id:`history`,label:`History`,icon:Oe,content:k(Qe,{})},{id:`alarm`,label:`Alarm`,icon:Se,content:k(Ge,{})},{id:`texts`,label:`Texts`,icon:ke,content:k(Ra,{})}]})})}export{Ba as NotificationsPage,Ba as default};