@camstack/addon-admin-ui 1.2.44 → 1.2.45

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 (90) hide show
  1. package/dist/assets/{AddLocationWizard-BTZGumQZ.js → AddLocationWizard-DwiJEwmB.js} +1 -1
  2. package/dist/assets/{AddonCollectionPage-Di5Xrp_m.js → AddonCollectionPage-C-sV4fIE.js} +1 -1
  3. package/dist/assets/{Addons-lsoIV9oO.js → Addons-Bj2e32kO.js} +1 -1
  4. package/dist/assets/{AdminTabs-kARKgSfA.js → AdminTabs-DCAQ34eW.js} +1 -1
  5. package/dist/assets/{AiProfiles-MlGoD_8p.js → AiProfiles-BJwPlJEb.js} +1 -1
  6. package/dist/assets/{BrokerForm-CrIS0s8n.js → BrokerForm-DZ83yAiW.js} +1 -1
  7. package/dist/assets/{Build-DlTRwfFZ.js → Build-hqC1_9r_.js} +1 -1
  8. package/dist/assets/{Capabilities-7RlPGLor.js → Capabilities-DYCNCy2C.js} +1 -1
  9. package/dist/assets/{CapabilityBadges-2EmnO8G2.js → CapabilityBadges-CfOevyl9.js} +1 -1
  10. package/dist/assets/{Cluster-CwiDHLtM.js → Cluster-CiJw1tTY.js} +1 -1
  11. package/dist/assets/{ClusterRecordingTab-Db-Bocu-.js → ClusterRecordingTab-BwcbpIiG.js} +1 -1
  12. package/dist/assets/{Dashboard-2atv2VqM.js → Dashboard-F_NYL9_0.js} +1 -1
  13. package/dist/assets/{Data-CS6YMa0T.js → Data-C891Mq8c.js} +1 -1
  14. package/dist/assets/{DetectionIntelligence-BvrZ6lId.js → DetectionIntelligence-B140cLaE.js} +1 -1
  15. package/dist/assets/{DeviceAggregateSection-27FMZ9K_.js → DeviceAggregateSection-CqXb8OlC.js} +1 -1
  16. package/dist/assets/{DeviceDetail-Bo0NH4bJ.js → DeviceDetail-DUs1WsF0.js} +1 -1
  17. package/dist/assets/{Devices-BHUqJY8_.js → Devices-179tBCuu.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-DPJO3IhK.js → EmbedPlayerPage-BU7GeV3g.js} +1 -1
  19. package/dist/assets/{Events-BM4Iii6s.js → Events-raCaU5X3.js} +1 -1
  20. package/dist/assets/{FormBuilder-DVeGFYfC.js → FormBuilder-CQPeVoyZ.js} +1 -1
  21. package/dist/assets/{Identity-CcwftWOj.js → Identity-CIajGxd0.js} +1 -1
  22. package/dist/assets/{IntegrationDetail-Dry3_99f.js → IntegrationDetail-BVkPsTEt.js} +1 -1
  23. package/dist/assets/{Integrations-B6k5_wOv.js → Integrations-BQXHkcJu.js} +1 -1
  24. package/dist/assets/{Integrations-DkUWSB02.js → Integrations-bKHN6L6j.js} +1 -1
  25. package/dist/assets/{Logs-PMovoa0Y.js → Logs-OlvU8Myc.js} +1 -1
  26. package/dist/assets/{MotionZonesSettings-C2vDMHJL.js → MotionZonesSettings-DrBBWPoz.js} +1 -1
  27. package/dist/assets/{MyAccess-Cs6eq2-c.js → MyAccess-kU61J5nx.js} +1 -1
  28. package/dist/assets/{Network-D_SCmMyP.js → Network-XAie7-vc.js} +1 -1
  29. package/dist/assets/{NodeAddonsSettingsPanel-BlyHfNhI.js → NodeAddonsSettingsPanel-Dup84Hcy.js} +1 -1
  30. package/dist/assets/{NodeInferenceDevices-oarn8hlp.js → NodeInferenceDevices-C61KVRFZ.js} +1 -1
  31. package/dist/assets/{Notifications-DoN-8973.js → Notifications-5jSvbck-.js} +1 -1
  32. package/dist/assets/{Pipeline-p574dCOj.js → Pipeline-B0fH3vgZ.js} +1 -1
  33. package/dist/assets/{Plates-CsjcJca9.js → Plates-CHYS-eHp.js} +1 -1
  34. package/dist/assets/{PrivacyMaskSettings-DBQUKaZk.js → PrivacyMaskSettings-CKx4w-TC.js} +1 -1
  35. package/dist/assets/{ProviderIcon-BgWd6Q6y.js → ProviderIcon-xTtXx3zj.js} +1 -1
  36. package/dist/assets/{Recordings-BRrY3RSV.js → Recordings-DB3LVKyX.js} +1 -1
  37. package/dist/assets/{ScanNetworkModal-BNOs-5Pu.js → ScanNetworkModal-CauWfDR6.js} +1 -1
  38. package/dist/assets/{Settings-C75SkS-F.js → Settings-D6f3sP3y.js} +1 -1
  39. package/dist/assets/{Showroom-DdObmy7y.js → Showroom-l9Xg2vRn.js} +1 -1
  40. package/dist/assets/{Terminal-BVjrJ7CD.js → Terminal-CWAHPGYc.js} +2 -2
  41. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DX_jC4cU.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BDKT2siH.js} +1 -1
  42. package/dist/assets/{boxes-EJ44QmcB.js → boxes-DSSHwgkj.js} +1 -1
  43. package/dist/assets/{build-cluster-graph-C0x-c3Ga.js → build-cluster-graph-CY_MeFyL.js} +1 -1
  44. package/dist/assets/circle-check-big-Bf0ewxaf.js +1 -0
  45. package/dist/assets/{circle-x-DeKeWOQP.js → circle-x-CZOmp7In.js} +1 -1
  46. package/dist/assets/clock-i-Al31lJ.js +1 -0
  47. package/dist/assets/{copy-BnqnJJii.js → copy-iAdKX02A.js} +1 -1
  48. package/dist/assets/{debounced-invalidate-VwkHLgll.js → debounced-invalidate-IzluQKKm.js} +1 -1
  49. package/dist/assets/{dist-BeQy-G-q.js → dist-BrD5LzQi.js} +1 -1
  50. package/dist/assets/{dist-DKv4DXHX.js → dist-CLRQNGYv.js} +2 -2
  51. package/dist/assets/{download-BMdWBa0i.js → download-C8A3QjNx.js} +1 -1
  52. package/dist/assets/{face-bbox-BoNuiD4H.js → face-bbox-DNeyfPs5.js} +1 -1
  53. package/dist/assets/{hostInit-DGv-dvhD.js → hostInit-B7p5ig8j.js} +1 -1
  54. package/dist/assets/{index-hx46EQ2Q.js → index-Dg1Uu8YH.js} +3 -3
  55. package/dist/assets/{key-round-C5_OEg-t.js → key-round-b-yFAbkx.js} +1 -1
  56. package/dist/assets/{mf-entry-bootstrap-0-e9617fff.js → mf-entry-bootstrap-0-c6c17c10.js} +2 -2
  57. package/dist/assets/{pencil-BDu3jFTf.js → pencil-D6ny7fbm.js} +1 -1
  58. package/dist/assets/play-CSzv0kMk.js +1 -0
  59. package/dist/assets/{player-overlays-DY9yZWwy.js → player-overlays-BfbNCp8v.js} +1 -1
  60. package/dist/assets/plus-Ct8CXOT7.js +1 -0
  61. package/dist/assets/{radio-BeBZYuWV.js → radio-X72WUypz.js} +1 -1
  62. package/dist/assets/{refresh-cw-Thof86m5.js → refresh-cw-CSup0Ybd.js} +1 -1
  63. package/dist/assets/remoteEntry-DiBMNlUL.js +1 -0
  64. package/dist/assets/rotate-ccw-PrFzYuvu.js +1 -0
  65. package/dist/assets/rotate-cw-DTN0bra-.js +1 -0
  66. package/dist/assets/search-DM6VGLFN.js +1 -0
  67. package/dist/assets/{send-DfcZY06l.js → send-IMkq2UdA.js} +1 -1
  68. package/dist/assets/{server-CmxlFNY4.js → server-DPDg3vKu.js} +1 -1
  69. package/dist/assets/{square-check-big-C2YMlSs_.js → square-check-big-B03NkszD.js} +1 -1
  70. package/dist/assets/square-gf10c5Em.js +1 -0
  71. package/dist/assets/{src-B0rBXgwn.js → src-B0nZ9rxd.js} +1 -1
  72. package/dist/assets/{src-DBiS7XSK.js → src-B5uaqYy4.js} +10 -10
  73. package/dist/assets/{undo-2-CqS7hfeB.js → undo-2-se0alJPw.js} +1 -1
  74. package/dist/assets/{upload-DITxhgrd.js → upload-CxxAxkr4.js} +1 -1
  75. package/dist/assets/{useEventInvalidation-BQwnAmzP.js → useEventInvalidation-DwiztDPv.js} +1 -1
  76. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-B2KuIPLN.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DKcJvK59.js} +2 -2
  77. package/dist/assets/{wifi-DVU3ne3Z.js → wifi-BeWxYg9K.js} +1 -1
  78. package/dist/assets/{zap-BYzTVz4S.js → zap-CK7p8C80.js} +1 -1
  79. package/dist/index.html +5 -5
  80. package/dist/server/addon.js +23 -1
  81. package/package.json +1 -1
  82. package/dist/assets/circle-check-big-BfL5fNrT.js +0 -1
  83. package/dist/assets/clock-C9UGuliq.js +0 -1
  84. package/dist/assets/play-BixlufCw.js +0 -1
  85. package/dist/assets/plus-Dq-PbOCp.js +0 -1
  86. package/dist/assets/remoteEntry-C55vQOg2.js +0 -1
  87. package/dist/assets/rotate-ccw-CqGydvBo.js +0 -1
  88. package/dist/assets/rotate-cw-DDRuRsDp.js +0 -1
  89. package/dist/assets/search-BDuPBZ3d.js +0 -1
  90. package/dist/assets/square-D3uqfcIw.js +0 -1
@@ -1 +1 @@
1
- import{$n as e,Do as t,Eo as n,Ho as r,Jo as i,Ko as a,Oo as o,Ro as s,S as c,So as l,To as u,Uo as d,Vo as f,Wo as p,Xo as m,Yo as h,lo as g,oa as _,qo as v,zo as y}from"./src-DBiS7XSK.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{C as ee,P as te,b as ne,c as j,o as M,s as re}from"./src-B0rBXgwn.js";import{p as N}from"./player-overlays-DY9yZWwy.js";import{t as P}from"./circle-check-big-BfL5fNrT.js";import{t as F}from"./copy-BnqnJJii.js";import{t as ie}from"./pencil-BDu3jFTf.js";import{t as I}from"./plus-Dq-PbOCp.js";import{t as ae}from"./refresh-cw-Thof86m5.js";import{t as oe}from"./search-BDuPBZ3d.js";import{t as se}from"./send-DfcZY06l.js";import{G as ce,H as le,P as ue,S as L,Y as de,f as R,i as fe,o as pe,s as z}from"./index-hx46EQ2Q.js";import{t as B}from"./AdminPage-Dq33XE9j.js";import{t as me}from"./AdminTabs-kARKgSfA.js";var he=ce(`bell-off`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742`,key:`178tsu`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05`,key:`1hqiys`}]]),ge=ce(`bell-ring`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M22 8c0-2.3-.8-4.3-2-6`,key:`5bb3ad`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}],[`path`,{d:`M4 2C2.8 3.7 2 5.7 2 8`,key:`tap9e0`}]]),V=ce(`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`}]]),_e=ce(`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`}]]);b();var H=e=>typeof e==`string`&&e.length>0;function ve(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 ye(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function be(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];H(i)&&n.push({mediaType:r,url:i})}return n}function xe(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=H(r.label),i=H(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 Se(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=be(e,t.attachmentUrls),i=xe(e,t.actions),a=e.ttl&&H(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:ye(e,t.format),priority:Ce(t.priority),...H(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&H(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&H(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...H(t.tag)?{tag:t.tag}:{}}}function Ce(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function we(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 Te(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Ee={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 De(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function Oe(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])De(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function ke(e,t,n){let r=Te(e);return De(e,t)?{...r,body:n,attachmentUrls:{[t]:Ee[t]}}:{...r,body:n}}function Ae(e,t){let n=Te(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return ke(e,`image`,`Test notification with an image.`);case`gif`:return ke(e,`gif`,`Test notification with an animation.`);case`video`:return ke(e,`video`,`Test notification with a video.`);case`audio`:return ke(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=we(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}var je={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},U=`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`,W=`block text-[11px] font-medium text-foreground mb-1`;function Me({target:e,kind:t,open:n,onClose:i}){let a=N(),o=S(()=>ve(t.caps),[t.caps]),c=S(()=>Oe(t.caps),[t.caps]),[l,u]=D(()=>Te(t.caps)),[p,g]=D(null),_=S(()=>Se(t.caps,l),[t.caps,l]),v=l.body.length,b=v>o.bodyMaxLen,C=e=>u(t=>({...t,...e})),w=O({mutationFn:()=>a.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:Se(t.caps,l)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:`Test failed`})}),T=e=>{u(Ae(t.caps,e)),g(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(s,{open:n,onOpenChange:e=>!e&&i(),children:x(y,{width:`lg`,className:`!max-w-2xl`,children:[k(r,{children:x(d,{children:[`Test "`,e.name,`" (`,t.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(m,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>T(e),children:je[e]},e))}),x(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[o.levels.length>0&&x(`div`,{children:[k(`label`,{className:W,children:`Level`}),x(`select`,{className:U,value:l.level,onChange:e=>C({level:e.target.value}),children:[k(`option`,{value:``,children:`— derive from priority —`}),o.levels.map(e=>x(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=o.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(h,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&k(h,{variant:`info`,children:`silent`}),e.flags?.noPush&&k(h,{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:W,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`})]})]}),o.formats.length>0&&x(`div`,{children:[k(`label`,{className:W,children:`Format`}),k(`div`,{className:`flex flex-wrap gap-2`,children:o.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:W,children:`Title`}),k(`input`,{className:U,value:l.title,onChange:e=>C({title:e.target.value})})]}),x(`div`,{children:[x(`label`,{className:W,children:[`Body`,` `,x(`span`,{className:b?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,o.bodyMaxLen,b?` — overflow`:``,`)`]})]}),k(`textarea`,{className:`${U} min-h-[80px] resize-y`,value:l.body,onChange:e=>C({body:e.target.value})})]}),o.attachmentSlots.length>0&&x(`div`,{children:[x(`label`,{className:W,children:[`Attachments`,` `,x(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,o.attachmentMode,`, max `,o.attachmentMax,o.attachmentMaxBytes?`, ≤${Math.round(o.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),k(`div`,{className:`space-y-1.5`,children:o.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:U,placeholder:`${e} URL`,value:l.attachmentUrls[e]??``,onChange:t=>C({attachmentUrls:{...l.attachmentUrls,[e]:t.target.value}})})]},e))})]}),o.showActions&&x(`div`,{children:[x(`label`,{className:W,children:[`Actions (up to `,o.maxActions,`)`]}),k(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(o.maxActions,3)},(e,t)=>x(`div`,{className:`flex items-center gap-2`,children:[k(`input`,{className:U,placeholder:`label`,value:l.actions[t]?.label??``,onChange:e=>E(t,`label`,e.target.value)}),k(`input`,{className:U,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:[o.showClickUrl&&x(`div`,{children:[k(`label`,{className:W,children:`Click URL`}),k(`input`,{className:U,value:l.clickUrl,onChange:e=>C({clickUrl:e.target.value})})]}),o.showSound&&x(`div`,{children:[k(`label`,{className:W,children:`Sound`}),k(`input`,{className:U,value:l.sound,onChange:e=>C({sound:e.target.value})})]}),o.showTtl&&x(`div`,{children:[k(`label`,{className:W,children:`TTL (seconds)`}),k(`input`,{className:U,type:`number`,value:l.ttl,onChange:e=>C({ttl:e.target.value})})]}),o.showTag&&x(`div`,{children:[k(`label`,{className:W,children:`Tag`}),k(`input`,{className:U,value:l.tag,onChange:e=>C({tag:e.target.value})})]})]}),p&&k(Ne,{result:p}),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(_,null,2)})]})]}),x(f,{children:[k(m,{variant:`secondary`,size:`sm`,type:`button`,onClick:i,children:`Close`}),x(m,{size:`sm`,type:`button`,disabled:w.isPending||l.body.length===0,onClick:()=>w.mutate(),children:[w.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(se,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function Ne({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(P,{className:`h-3.5 w-3.5 text-success`}):k(ue,{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 Pe(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 Fe(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 Ie(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 Le(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 Re=[`notificationOutput`,`listTargets`],ze=[`notificationOutput`,`listTargetKinds`],Be=[`userManagement`,`listUsers`],Ve=`ownerUserId`;function He(e){let t=e.config[Ve];return typeof t==`string`&&t.length>0?t:null}function Ue(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(We,{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(h,{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=He(t);return n===null?k(h,{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(p,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let n=e.kindByKey.get(t.kind);return x(`span`,{className:`flex items-center justify-end gap-1`,children:[k(m,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>e.onTest(t),title:`Test`,children:k(se,{className:`h-3.5 w-3.5`})}),k(m,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>n&&e.onEdit(t,n),title:`Edit`,children:k(ie,{className:`h-3.5 w-3.5`})}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:k(z,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function We({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 Ge(){let e=N(),[t,n]=D({mode:`closed`}),[r,a]=D(null),o=C({queryKey:Re,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),s=C({queryKey:ze,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]),u=S(()=>{let e=new Map;for(let t of c)e.set(t.kind,t);return e},[c]),d=C({queryKey:Be,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),f=S(()=>{let e=new Map;for(let t of d.data??[])e.set(t.id,t.username);return e},[d.data]),p=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()}),_=r?u.get(r.kind):void 0;return x(B,{icon:le,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(m,{size:`sm`,type:`button`,onClick:()=>n({mode:`pick-kind`}),children:[k(I,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[o.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),o.isError&&!o.isLoading&&k(g,{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(i,{children:k(l,{columns:Ue({kindByKey:u,userNameById:f,onToggle:(e,t)=>p.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(Ke,{kinds:c,onCancel:()=>n({mode:`closed`}),onPick:e=>n({mode:`form`,kind:e,target:null})}),t.mode===`form`&&k(qe,{kind:t.kind,target:t.target,users:d.data??[],onCancel:()=>n({mode:`closed`}),onSaved:()=>{n({mode:`closed`}),o.refetch()}}),r&&_&&k(Me,{target:r,kind:_,open:!0,onClose:()=>a(null)})]})}function Ke({kinds:e,onPick:t,onCancel:n}){let r=S(()=>Pe(e),[e]);return x(i,{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(m,{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(We,{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(h,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})}function qe({kind:e,target:t,users:n,onSaved:r,onCancel:o}){let s=N(),l=S(()=>Fe(e.configSchema),[e.configSchema]),u=S(()=>t?.config??{},[t]),[d,f]=D(t?.name??e.label),[p,h]=D(()=>t?Le(t.config,l):{}),[g,_]=D(null),[v,y]=D(null),[b,C]=D(t?He(t)??``:``),w=O({mutationFn:()=>s.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:p}),onSuccess:e=>_(e),onError:e=>y(e instanceof Error?e.message:`Discovery failed`)}),T=O({mutationFn:()=>{let{[Ve]:n,...r}=Ie(p,u,l),i=b===``?r:{...r,[Ve]:b},a={id:t?.id??`${e.kind}-${Date.now()}`,name:d,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:i};return s.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:a})},onSuccess:r,onError:e=>y(e instanceof Error?e.message:`Save failed`)}),E=e=>{f(e.suggestedName),h(t=>({...t,...e.config})),_(null)};return x(i,{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(We,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),t?`Edit ${t.name}`:`Add ${e.label} target`]}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,children:`Cancel`})]}),v&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:v}),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:d,onChange:e=>f(e.target.value)})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),k(a,{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(m,{size:`sm`,variant:`outline`,type:`button`,disabled:w.isPending,onClick:()=>{y(null),w.mutate()},children:[w.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(oe,{className:`h-3.5 w-3.5`}),`Discover`]}),g&&g.length===0&&k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),g&&g.length>0&&k(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:g.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}`))})]}),l.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(c,{schema:e.configSchema,values:p,onChange:h}),x(`div`,{className:`flex justify-end gap-2`,children:[k(m,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:`Cancel`}),x(m,{size:`sm`,type:`button`,disabled:T.isPending||d.trim().length===0,onClick:()=>{y(null),T.mutate()},children:[T.isPending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),t?`Save changes`:`Create target`]})]})]})}var Je=[{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`}],Ye={sequences:[],buttons:[]};function Xe(e){return e===void 0?Ye:{sequences:[...e.onTrigger??[]],buttons:[...e.buttons??[]]}}function Ze(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 Qe(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 $e(e){return{name:`sequence ${String(e+1)}`,enabled:!1,actions:[]}}function et(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequence:t}}function tt(){return{kind:`wait`,seconds:5}}var G=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,K=`block text-[11px] font-medium text-foreground`;function nt({value:e,onChange:t,devices:n}){let r=Qe(e),i=(n,r)=>t({...e,sequences:e.sequences.map((e,t)=>t===n?r:e)}),a=(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(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t({...e,sequences:[...e.sequences,$e(e.sequences.length)]}),children:[k(I,{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,a)=>k(rt,{sequence:r,devices:n,onChange:e=>i(a,e),onRemove:()=>t({...e,sequences:e.sequences.filter((e,t)=>t!==a)})},`seq-${String(a)}`))]}),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(m,{size:`sm`,variant:`ghost`,type:`button`,disabled:e.sequences.length===0,onClick:()=>t({...e,buttons:[...e.buttons,et(e.buttons.length,e.sequences[0]?.name??``)]}),children:[k(I,{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(pe,{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(ot,{button:n,sequenceNames:e.sequences.map(e=>e.name),onChange:e=>a(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function rt({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:K,children:`Name`}),k(v,{className:`mt-1`,value:e.name,onChange:t=>n({...e,name:t.target.value})})]}),x(`div`,{className:`w-28`,children:[k(`label`,{className:K,children:`Min delay (s)`}),k(`input`,{type:`number`,min:0,className:G,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(p,{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(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove`,children:k(z,{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(it,{step:r,devices:t,onChange:e=>i(a,e),onRemove:()=>n({...e,actions:e.actions.filter((e,t)=>t!==a)})},`step-${String(a)}`)),x(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({...e,actions:[...e.actions,tt()]}),children:[k(I,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function it({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:K,children:`Step`}),x(`select`,{className:G,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:K,children:`Seconds`}),k(`input`,{type:`number`,min:0,max:300,className:G,value:e.seconds,onChange:e=>n({kind:`wait`,seconds:Number(e.target.value)})})]}):k(at,{step:e,devices:t,onChange:n}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove step`,children:k(z,{className:`h-3.5 w-3.5`})})]})}function at({step:e,devices:t,onChange:n}){let r=N(),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:K,children:`Device`}),x(`select`,{className:G,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:K,children:`Capability`}),x(`select`,{className:G,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:K,children:`Method`}),k(v,{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:K,children:`Arguments (JSON)`}),k(v,{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 ot({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:K,children:`Label`}),k(v,{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:K,children:`Runs`}),x(`select`,{className:G,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:K,children:`Icon`}),x(`select`,{className:G,value:e.icon??``,onChange:t=>{let r={...e};if(t.target.value===``)delete r.icon;else{let e=Je.find(e=>e.value===t.target.value);e!==void 0&&(r.icon=e.value)}n(r)},children:[k(`option`,{value:``,children:`None`}),Je.map(e=>k(`option`,{value:e.value,children:e.label},e.value))]})]}),x(`div`,{className:`flex items-center gap-2 pb-1`,children:[k(p,{checked:e.destructive===!0,onCheckedChange:t=>{let r={...e};t?r.destructive=!0:delete r.destructive,n(r)}}),k(h,{variant:e.destructive===!0?`danger`:`default`,children:`Destructive style`})]}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove`,children:k(z,{className:`h-3.5 w-3.5`})})]})}var st={search:``,types:[],selectedOnly:!1};function ct(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 lt(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 ut(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 dt(e,t){let n=new Set(t);for(let t of e)n.add(t.id);return[...n]}function ft(e,t){let n=new Set(e.map(e=>e.id));return t.filter(e=>!n.has(e))}function pt(e,t){return e.length===0?`Every device (${String(t)}) — no restriction`:`${String(e.length)} of ${String(t)} selected`}b();function mt({devices:e,value:t,onChange:n,loading:r=!1}){let[i,a]=D(st),o=S(()=>ct(e),[e]),s=S(()=>lt(e,i,t),[e,i,t]),c=S(()=>ut(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:pt(t,e.length)}),x(`div`,{className:`flex items-center gap-1`,children:[k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n(dt(s,t)),children:`Select shown`}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n(ft(s,t)),children:`Clear shown`})]})]}),x(`div`,{className:`flex flex-wrap items-center gap-2`,children:[k(v,{className:`min-w-[10rem] flex-1`,value:i.search,placeholder:`Search by name…`,leftSlot:k(oe,{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(h,{variant:`default`,children:e.type})]},e.id))})]},e.location??`__unplaced`))})]})}function q(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var ht=q({devices:!0}),gt=q({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),_t=q({zonesExclude:!0}),vt=q({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),yt=q({minDwellSeconds:!0}),bt=q({source:!0}),xt=q({crossing:!0}),St=q({packagePhase:!0}),Ct=q({zones:!0}),wt=q({plates:!0}),Tt=q({occupancy:!0}),Et=q({deviceState:!0});function Dt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Ot(e,t){let n=e[t];return typeof n==`number`?n:void 0}var kt=[{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:`schedule`,label:`Schedule`}];function At(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function jt(e,t){let n=e.filter(t),r=new Set(kt.map(e=>e.id)),i=[];for(let e of kt){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:At(e),descriptors:n.filter(t=>t.group===e)});return i}b();function Mt(e,t){let n=N().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 Nt(e){let t=N().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 Pt(){let t=e();return S(()=>({options:(t.data??[]).map(e=>({value:e.name,label:e.name})),loading:t.isLoading}),[t.data,t.isLoading])}function Ft(){let e=_({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 It({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 Lt=[{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.`}];function Rt(e){return Lt.find(t=>t.value===e)?.label??e}function zt(e){return Lt.find(t=>t.value===e)?.value}var Bt=[{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 Vt(e){return Bt.find(t=>t.value===e)?.value}var Ht=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function Ut(e){let t=Ht.find(t=>t.value===e)?.value;return t===``?void 0:t}var Wt=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function Gt(e){let t=Wt.find(t=>t.value===e)?.value;return t===``?void 0:t}var Kt=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],qt=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],Jt=[{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 Yt(e){let t=Jt.find(t=>t.value===e)?.value;return t===``||t===void 0?void 0:t}var Xt=[{value:`any`,label:`Any of`},{value:`all`,label:`All of`}],Zt=[{value:1,label:`1 — Min`},{value:2,label:`2 — Low`},{value:3,label:`3 — Default`},{value:4,label:`4 — High`},{value:5,label:`5 — Max`}];function Qt(){return{name:``,enabled:!0,delivery:`immediate`,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,actions:Ye,deviceIds:[]}}function $t(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,actions:Xe(e.actions),deviceIds:e.conditions.devices??[]}}function en(e){return e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&Qe(e.actions).length===0}function tn(e,t){return e.appliesTo.includes(t)}var nn={source:`any`};function rn(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||nn[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}function an(e,t,n){let r=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&tn(e,t)).map(e=>e.id)),i={};for(let[t,n]of Object.entries(e))r!==null&&!r.has(t)||rn(t,n)||(i[t]=n);return i}function on(e){return e!==void 0&&e.windows.length>0}function sn(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=Ze(e.actions),s=(n.length===0||n.some(t=>t.id===`schedule`&&tn(t,e.delivery)))&&on(e.schedule)?e.schedule:void 0;return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...an(e.conditions,e.delivery,n),...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:{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:t?.throttle??{cooldownSec:60,scope:`rule-device`},priority:e.priority,...a?{template:a}:{},...e.snoozeAllowGlobal?{snoozeAllowGlobal:!0}:{},...o===void 0?{}:{actions:o}}}function cn(e,t){return e.options&&e.options.length>0?e.options:t}var ln=[{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 un(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var dn=[{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`]}],fn=`rule`;function pn(e){return dn.find(t=>t.key===e)?.key}b();var J=`block text-[11px] font-medium text-foreground`,Y=`text-[10px] text-foreground-subtle mt-0.5`;function mn({cameras:e,value:t,onChange:n}){if(e.length===0)return k(`p`,{className:Y,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 hn({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(fe,{className:`h-3 w-3`})})]},e))}),k(v,{value:r,placeholder:t,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),a())},onBlur:a})]})}function gn({picker:e,value:t,onChange:n}){let r=S(()=>re(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 X({value:e,min:t,max:n,step:r,onChange:i}){return x(`div`,{className:`mt-1 flex items-center gap-2`,children:[k(v,{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 _n({value:e,onChange:t,options:n}){let r=e??``,i=n&&n.length>0?n:Jt,o=i.find(e=>e.value===r);return x(`div`,{className:`mt-1 space-y-1`,children:[k(a,{value:r,options:i.map(e=>({value:e.value,label:e.label})),onChange:e=>t(Yt(e.target.value))}),o!==void 0&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:o.hint})]})}function vn({deviceIds:e,cameras:t,value:n,onChange:r}){let i=n?.ids??[],o=n?.match??`any`,s=e=>r(e.length>0?{ids:e,match:o}:void 0),c=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(a,{value:o,options:Xt.map(e=>({value:e.value,label:e.label})),onChange:e=>c(e.target.value===`all`?`all`:`any`)})}),k(Z,{deviceIds:e,cameras:t,value:i,onChange:s})]})}function Z({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=Mt(e,t);return k(It,{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 yn({value:e,onChange:t}){let{options:n,loading:r}=Pt();return k(It,{options:n,value:e,onChange:t,loading:r,emptyHint:`No identities in the face gallery yet — type a name.`,placeholder:`Identity name…`})}function bn({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=Nt(e);return k(It,{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 xn=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}],Sn={op:`became-occupied`,count:1,sustainSeconds:15};function Cn({deviceIds:e,cameras:t,classOptions:n,value:r,onChange:i}){let{options:o,loading:s}=Mt(e,t),c=r??Sn,l=e=>i({...c,...e}),u=c.op===`became-occupied`||c.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(a,{value:c.zoneId??``,options:[{value:``,label:s?`Loading zones…`:`— whole frame —`},...o.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({zoneId:e.target.value===``?void 0:e.target.value})})}),k(`div`,{className:`min-w-[9rem]`,children:k(a,{value:c.className??``,options:[{value:``,label:`— any class —`},...n.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({className:e.target.value===``?void 0:e.target.value})})}),k(`div`,{className:`min-w-[9rem]`,children:k(a,{value:c.op,options:xn.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=xn.find(t=>t.value===e.target.value);t&&l({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:[u?`Threshold`:`Count`,k(v,{type:`number`,min:0,className:`w-16`,value:String(c.count),onChange:e=>l({count:Math.max(0,Number(e.target.value)||0)})})]}),x(`label`,{className:`flex items-center gap-1`,children:[`Hold for`,k(v,{type:`number`,min:0,max:3600,className:`w-16`,value:String(c.sustainSeconds),onChange:e=>l({sustainSeconds:Math.min(3600,Math.max(0,Number(e.target.value)||0))})}),`s`]}),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 wn({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=Ft().filter(e=>!n.includes(e));return x(`div`,{className:`mt-1 space-y-1.5`,children:[k(hn,{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(v,{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 Tn({gateable:e,value:t,onChange:n}){let r=e.find(e=>e.id===t?.deviceId),i=new Set(t?.states??[]),o=e=>{let t=Number(e);if(!Number.isFinite(t)||t===0)return n(void 0);n({deviceId:t,states:[]})},s=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(a,{value:t===void 0?``:String(t.deviceId),options:[{value:``,label:`— no device gate —`},...e.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>o(e.target.value)}),r!==void 0&&k(`div`,{className:`flex flex-wrap gap-1.5`,children:r.states.map(e=>k(`button`,{type:`button`,onClick:()=>s(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 En=[{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 Dn(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function On(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 kn(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function An({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,kn()],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:Y,children:`Always active — add a window to restrict when the rule fires.`}):n.map((e,t)=>k(jn,{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(I,{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 jn({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:Dn(e.startMinute),onChange:n=>t({...e,startMinute:On(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:Dn(e.endMinute),onChange:n=>t({...e,endMinute:On(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(z,{className:`h-3.5 w-3.5`})})]}),k(`div`,{className:`flex flex-wrap gap-1`,children:En.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))})]})}b();function Mn({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(()=>jt(e,e=>e.id!==`devices`&&M(e.id)),[e]),d=S(()=>jt(e,e=>e.id!==`devices`&&!M(e.id)),[e]),[f,p]=D(()=>{if(Pn(r,i))return!0;try{return localStorage.getItem(Nn)===`1`}catch{return!1}}),m=()=>{let e=!f;p(e);try{localStorage.setItem(Nn,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=tn(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:J,children:e.label}),!s&&x(h,{variant:`default`,children:[`not for `,e.appliesTo.join(` / `)]})]}),s?k(Fn,{descriptor:e,taxonomy:t,conditions:r,schedule:i,cameras:a,gateable:o,onFieldChange:l,onScheduleChange:c}):k(`p`,{className:Y,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:m,"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:f?`▾ Hide advanced configurations`:`▸ Show more configurations`}),f&&g(d)]})}var Nn=`camstack.nc.showAdvanced`;function Pn(e,t){for(let[t,n]of Object.entries(e))if(!M(t)&&n!==void 0&&!(Array.isArray(n)&&n.length===0))return!0;return t!==void 0&&t.windows.length>0}function Fn({descriptor:e,taxonomy:t,conditions:n,schedule:r,cameras:i,gateable:o,onFieldChange:s,onScheduleChange:c}){switch(e.valueType){case`deviceIdList`:{if(!ht(e.id))break;let t=e.id;return k(mn,{cameras:i,value:n[t]??[],onChange:e=>s(t,e.length>0?e:void 0)})}case`stringList`:{if(!gt(e.id))break;let r=e.id,i=e=>s(r,e.length>0?e:void 0);if(r===`identities`||r===`identitiesExclude`)return k(yn,{value:Dt(n,r),onChange:i});if(r===`eventTypeTokens`)return k(bn,{deviceIds:n.devices??[],value:Dt(n,r),onChange:i});let a=j(r,t);return a===null?k(hn,{value:Dt(n,r),placeholder:`Add value…`,onChange:i}):k(gn,{picker:a,value:Dt(n,r),onChange:i})}case`zoneIdList`:{if(!_t(e.id))break;let t=e.id;return k(Z,{deviceIds:n.devices??[],cameras:i,value:Dt(n,t),onChange:e=>s(t,e.length>0?e:void 0)})}case`number01`:{if(!vt(e.id))break;let t=e.id;return k(X,{value:Ot(n,t),min:0,max:1,step:.05,onChange:e=>s(t,e)})}case`number`:{if(!yt(e.id))break;let t=e.id;return k(X,{value:Ot(n,t),min:0,step:1,onChange:e=>s(t,e)})}case`sourceSelect`:{if(!bt(e.id))break;let t=e.id;return k(a,{value:n[t]??`any`,options:cn(e,Kt).map(e=>({value:e.value,label:e.label})),onChange:e=>s(t,Rn(e.target.value))})}case`deviceState`:if(!Et(e.id))break;return k(Tn,{gateable:o,value:n.deviceState,onChange:e=>s(`deviceState`,e)});case`crossingSelect`:{if(!xt(e.id))break;let t=e.id;return k(_n,{value:n[t],onChange:e=>s(t,e),...e.options?{options:e.options}:{}})}case`packagePhase`:{if(!St(e.id))break;let t=e.id;return k(a,{value:n[t]??``,options:[{value:``,label:`— any phase —`},...cn(e,qt).map(e=>({value:e.value,label:e.label}))],onChange:e=>s(t,zn(e.target.value))})}case`zoneSelection`:{if(!Ct(e.id))break;let t=e.id;return k(vn,{deviceIds:n.devices??[],cameras:i,value:n[t],onChange:e=>s(t,e)})}case`plateMatcher`:{if(!wt(e.id))break;let t=e.id;return k(wn,{value:n[t],onChange:e=>s(t,e)})}case`occupancy`:{if(!Tt(e.id))break;let r=e.id;return k(Cn,{deviceIds:n.devices??[],cameras:i,classOptions:In(t),value:n[r],onChange:e=>s(r,e)})}case`schedule`:return k(An,{value:r,onChange:c});default:break}return k(Ln,{descriptor:e,conditions:n})}function In(e){let t=j(`classes`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Ln({descriptor:e,conditions:t}){let n=Object.entries(t).find(([t])=>t===e.id);return x(`p`,{className:Y,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 Rn(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function zn(e){return qt.find(t=>t.value===e)?.value}b();var Bn=[`notificationRules`,`listSnoozes`],Vn=3e4;function Hn(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function Un(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 Wn({rules:e}){let t=N(),n=E(),r=C({queryKey:Bn,refetchInterval:Vn,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),a=O({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>n.invalidateQueries({queryKey:Bn})}),o=S(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),s=Date.now(),c=(r.data??[]).filter(e=>s>=e.startedAt&&s<e.expiresAt);return c.length===0?null:x(i,{className:`p-4`,children:[x(`div`,{className:`flex items-center gap-2 mb-3`,children:[k(he,{className:`h-4 w-4 text-foreground-subtle`}),k(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),k(`div`,{className:`space-y-2`,children:c.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??`?`}`:o.get(e.ruleId??``)??`A rule`}),e.global&&k(h,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),!e.summary&&k(h,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),x(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,Un(Hn(e,s))]})]}),k(m,{size:`sm`,variant:`outline`,disabled:a.isPending,onClick:()=>a.mutate(e.id),children:`End now`})]},e.id))})]})}b();var Gn=[`notificationRules`,`listRules`],Kn=[`notificationOutput`,`listTargets`,`forRules`],qn=[`notificationRules`,`getConditionCatalog`],Jn=[`deviceManager`,`listAll`,`forRules`],Yn=[`deviceManager`,`listAll`,`forRuleActions`],Xn=[`deviceManager`,`gateableDevices`],Zn=ee.options;function Qn({onSimulateRule:e}={}){let t=N(),[n,r]=D({mode:`closed`}),[a,o]=D(null),s=C({queryKey:Gn,queryFn:async()=>(await t.trpcClient.notificationRules.listRules.query({})).rules}),c=C({queryKey:Kn,queryFn:()=>t.trpcClient.notificationOutput.listTargets.query({})}),u=C({queryKey:qn,queryFn:()=>t.trpcClient.notificationRules.getConditionCatalog.query({})}),d=C({queryKey:Xn,queryFn:async()=>{let e=await t.trpcClient.deviceManager.listAll.query({}),n=[];for(let r of e){let e=ne(await t.trpcClient.deviceManager.loadRuntimeState.query({deviceId:r.id}),Zn);e.length>0&&n.push({id:r.id,name:r.name,states:e})}return n},staleTime:6e4}),f=C({queryKey:Yn,queryFn:async()=>(await t.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}),p=C({queryKey:Jn,queryFn:async()=>(await t.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===te.Camera).map(e=>({id:e.id,name:e.name}))}),h=S(()=>{let e=new Map;for(let t of c.data??[])e.set(t.id,t.name);return e},[c.data]),_=O({mutationFn:e=>t.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void s.refetch()}),v=O({mutationFn:e=>t.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>{o(null),s.refetch()}}),y=s.data??[];return x(B,{icon:ge,title:`Notification Rules`,subtitle:`Author rules that turn detections, doorbell presses and package events into notifications. Each rule picks a trigger, matches conditions and fans out to one or more delivery targets.`,actions:x(m,{size:`sm`,type:`button`,onClick:()=>r({mode:`form`,rule:null}),children:[k(I,{className:`h-3.5 w-3.5`}),`New rule`]}),children:[k(Wn,{rules:y}),s.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),s.isError&&!s.isLoading&&k(g,{title:`Failed to load rules`,message:s.error instanceof Error?s.error.message:`Unknown error`,onRetry:()=>void s.refetch()}),!s.isLoading&&!s.isError&&y.length===0&&k(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification rules yet. Click "New rule" to author one.`}),y.length>0&&k(i,{children:k(l,{columns:$n({targetNameById:h,confirmDeleteId:a,deletePending:v.isPending,onToggle:(e,t)=>_.mutate({ruleId:e.id,enabled:t}),onEdit:e=>r({mode:`form`,rule:e}),onDuplicate:e=>r({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:o,onConfirmDelete:e=>v.mutate(e.id),...e?{onTest:e}:{}}),rows:y,rowKey:e=>e.id,minWidthPx:760,bordered:!1})}),n.mode===`form`&&k(er,{rule:n.rule,targets:c.data??[],actuatable:f.data??[],catalog:u.data?.catalog??[],taxonomy:u.data?.taxonomy,cameras:p.data??[],gateable:d.data??[],onCancel:()=>r({mode:`closed`}),onSaved:()=>{r({mode:`closed`}),s.refetch()}})]})}function $n(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(h,{variant:`warning`,children:`disabled`})]})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:Rt(e.delivery)})},{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(p,{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(m,{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(V,{className:`h-3.5 w-3.5`})}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onEdit(t),title:`Edit`,children:k(ie,{className:`h-3.5 w-3.5`})}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:k(F,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?x(w,{children:[x(m,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),children:[e.deletePending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),`Confirm`]}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(t.id),title:`Delete`,children:k(z,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function er({rule:e,targets:r,catalog:i,taxonomy:c,cameras:l,gateable:d,actuatable:f,onSaved:g,onCancel:_}){let b=N(),S=e!=null&&e.id.length>0,[w,T]=D(()=>e?$t(e):Qt()),[E,A]=D(null),[ee,te]=D(null),[ne,j]=D(fn),M=e=>T(t=>({...t,...e})),re=S&&e?{throttle:e.throttle}:void 0,P=O({mutationFn:async()=>{let t=sn(w,re,i);S&&e?await b.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t}):await b.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:g,onError:e=>A(e instanceof Error?e.message:`Save failed`)}),F=O({mutationFn:async()=>{let e=sn(w,re,i);return(await b.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>te(null),onSuccess:e=>te(e),onError:e=>A(e instanceof Error?e.message:`Test failed`)}),ie=w.targetIds.map(e=>r.find(t=>t.id===e)?.name??e),I=e=>M({targetIds:w.targetIds.includes(e)?w.targetIds.filter(t=>t!==e):[...w.targetIds,e]}),ae=C({queryKey:[`userManagement`,`listUsers`],queryFn:()=>b.trpcClient.userManagement.listUsers.query()}).data,oe=e=>M({targetUsers:w.targetUsers.includes(e)?w.targetUsers.filter(t=>t!==e):[...w.targetUsers,e]}),se=Lt.find(e=>e.value===w.delivery)?.hint;return k(s,{open:!0,onOpenChange:e=>!e&&_(),children:x(y,{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(ge,{className:`h-4 w-4 text-foreground-subtle`}),S?`Edit ${e?.name}`:`New notification rule`]}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:_,children:`Cancel`})]}),E&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:E}),x(u,{value:ne,onValueChange:e=>j(pn(e)??ne),children:[k(t,{className:`mb-3`,children:dn.map(e=>k(o,{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(v,{value:w.name,onChange:e=>M({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(p,{checked:w.enabled,onCheckedChange:e=>M({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),k(a,{value:w.delivery,onChange:e=>{let t=zt(e.target.value);t&&M({delivery:t})},options:Lt.map(e=>({value:e.value,label:e.label}))}),se&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:se})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),r.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:r.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:w.targetIds.includes(e.id),onChange:()=>I(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&k(h,{variant:`warning`,children:`disabled`})]},e.id))})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(ae??[]).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:(ae??[]).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:w.targetUsers.includes(e.id),onChange:()=>oe(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&k(h,{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(mt,{devices:f,value:w.deviceIds,onChange:e=>M({deviceIds:e}),loading:f.length===0})}),k(n,{value:`actions`,className:`space-y-4`,children:k(nt,{value:w.actions,onChange:e=>M({actions:e}),devices:f})}),k(n,{value:`advanced`,className:`space-y-4`,children:x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(p,{checked:w.snoozeAllowGlobal,onCheckedChange:e=>M({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`}),`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(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(a,{value:String(w.priority),onChange:e=>M({priority:Number(e.target.value)}),options:Zt.map(e=>({value:String(e.value),label:e.label}))})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),k(a,{value:w.mediaAttach,onChange:e=>{let t=Vt(e.target.value);t&&M({mediaAttach:t})},options:Bt.map(e=>({value:e.value,label:e.label}))}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Bt.find(e=>e.value===w.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:w.mediaZoneCrop,onChange:e=>M({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:w.mediaGif,onChange:e=>M({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:w.mediaClip,onChange:e=>M({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(w.mediaGif||w.mediaClip)&&x(`div`,{className:`mt-2`,children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),k(a,{value:w.mediaProfile??``,onChange:e=>M({mediaProfile:Gt(e.target.value)}),options:Wt.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(a,{value:w.mediaClipSpeed===void 0?``:String(w.mediaClipSpeed),onChange:e=>M({mediaClipSpeed:un(e.target.value)}),options:ln.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.`})]})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),k(a,{value:w.mediaFrame??``,onChange:e=>M({mediaFrame:Ut(e.target.value)}),options:Ht.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(v,{value:w.templateTitle,onChange:e=>M({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:w.templateBody,onChange:e=>M({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:`Conditions`}),i.length===0?k(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):k(Mn,{catalog:i,taxonomy:c,delivery:w.delivery,conditions:w.conditions,schedule:w.schedule,cameras:l,gateable:d,onConditionsChange:e=>M({conditions:e}),onScheduleChange:e=>M({schedule:e})})]}),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(m,{size:`sm`,variant:`outline`,type:`button`,disabled:F.isPending||!en(w),onClick:()=>{A(null),F.mutate()},children:[F.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(V,{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.`}),ee!==null&&k(tr,{delivery:w.delivery,results:ee,targetNames:ie})]})]})]}),x(`div`,{className:`flex justify-end gap-2 mt-4`,children:[k(m,{variant:`secondary`,size:`sm`,type:`button`,onClick:_,children:`Cancel`}),x(m,{size:`sm`,type:`button`,disabled:P.isPending||!en(w),onClick:()=>{A(null),P.mutate()},children:[P.isPending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),S?`Save changes`:`Create rule`]})]})]})})}function tr({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(P,{className:`h-3.5 w-3.5 shrink-0 text-success`}):k(ue,{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))})]})}b();var nr=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],rr=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],ir=[50,100,250,500];function ar(){return{ruleId:``,deviceId:``,status:``,windowHours:24,limit:100}}function or(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function sr(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function cr(){let e=N(),[t,n]=D(ar),r=e=>n(t=>({...t,...e})),o=C({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),s=C({queryKey:[`deviceManager`,`listAll`,`forHistory`],queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===te.Camera).map(e=>({id:e.id,name:e.name}))}),c=Date.now(),u=C({queryKey:[`notificationRules`,`getHistory`,t],retry:!1,queryFn:async()=>{let n=t.windowHours>0?c-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)}:{},...or(t.status)?{status:or(t.status)}:{},...n===void 0?{}:{since:n}}})).entries}}),d=S(()=>{let e=new Map;for(let t of s.data??[])e.set(t.id,t.name);return e},[s.data]),f=e=>d.get(e)??`Camera #${String(e)}`,p=u.data??[],m=u.isError;return x(B,{icon:_e,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(a,{value:t.ruleId,onChange:e=>r({ruleId:e.target.value}),options:[{value:``,label:`All rules`},...(o.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(a,{value:t.deviceId,onChange:e=>r({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(s.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(a,{value:t.status,onChange:e=>r({status:e.target.value}),options:rr.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(a,{value:String(t.windowHours),onChange:e=>r({windowHours:Number(e.target.value)}),options:nr.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(a,{value:String(t.limit),onChange:e=>r({limit:Number(e.target.value)}),options:ir.map(e=>({value:String(e),label:String(e)}))})]})]}),u.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),m&&!u.isLoading&&k(i,{children:x(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[k(_e,{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 u.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(ae,{className:`h-3 w-3`}),` Retry`]})]})}),!m&&!u.isLoading&&p.length===0&&k(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!m&&p.length>0&&k(i,{children:k(l,{columns:lr(f),rows:p,rowKey:e=>e.id,minWidthPx:720,bordered:!1})})]})}function lr(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(h,{variant:sr(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:`—`})}]}var ur={home:`Home`,away:`Away`,night:`Night`,vacation:`Vacation`,custom_bypass:`Custom`};function dr(e){return ur[e]??e}function fr(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 pr(e,t){return e.ruleCount===0?`Arms nothing — no enabled rule is gated on this mode.`:e.allDevices?`Every device — ${hr(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${hr(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(e=>t.get(e)??`Device ${e}`).join(`, `)}function mr(e){return e.ruleCount===0}function hr(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function gr(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}b();var _r=[`notificationRules`,`getAlarmConfig`],vr=[`notificationOutput`,`listTargets`],yr=[`deviceManager`,`listAll`,`alarm-coverage`],br=600,xr=3600;function Sr({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(v,{type:`number`,min:0,max:r,value:s??String(n),disabled:a,onChange:e=>c(e.target.value),onBlur:()=>{let e=s===null?null:gr(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:fr(n,i)})]}),k(`p`,{className:`text-xs text-foreground-subtle`,children:t})]})}function Cr(){let e=N(),t=E(),n=C({queryKey:_r,queryFn:async()=>e.trpcClient.notificationRules.getAlarmConfig.query({})}),r=C({queryKey:vr,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),a=C({queryKey:yr,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).map(e=>({id:e.id,name:e.name}))}),o=O({mutationFn:t=>e.trpcClient.notificationRules.setAlarmConfig.mutate({patch:t}),onSuccess:()=>t.invalidateQueries({queryKey:_r})}),s=S(()=>{let e=new Map;for(let t of a.data??[])e.set(t.id,t.name);return e},[a.data]);if(n.isLoading)return k(B,{icon:R,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(L,{className:`h-5 w-5 animate-spin`})});let c=n.data;if(c===void 0||n.isError)return k(B,{icon:R,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(g,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(c.deviceId===null)return k(B,{icon:R,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(i,{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 l=c.settings,u=o.isPending,d=r.data??[],f=l.announceTargets,m=e=>{o.mutate(e)},_=e=>{m({announceTargets:f.includes(e)?f.filter(t=>t!==e):[...f,e]})};return k(B,{icon:R,title:`Alarm`,subtitle:`Panel delays, and what each mode actually arms.`,children:x(`div`,{className:`flex flex-col gap-4`,children:[o.isError?k(g,{title:`Could not save`,message:String(o.error)}):null,x(i,{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(Sr,{label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,value:l.exitDelaySec,max:br,zeroMeans:`arms immediately`,disabled:u,onCommit:e=>m({exitDelaySec:e})}),k(Sr,{label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,value:l.entryDelaySec,max:br,zeroMeans:`fires immediately`,disabled:u,onCommit:e=>m({entryDelaySec:e})}),k(Sr,{label:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,value:l.triggeredDurationSec,max:xr,zeroMeans:`until disarmed`,disabled:u,onCommit:e=>m({triggeredDurationSec:e})})]})]}),x(i,{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(p,{checked:l.announceArm,disabled:u,onCheckedChange:e=>m({announceArm:e}),"data-testid":`alarm-announce-toggle`})]}),l.announceArm?x(`div`,{className:`mt-3 flex flex-col gap-2`,children:[d.length===0?k(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification targets are configured — nothing can be sent.`}):d.map(e=>x(`label`,{className:`flex items-center gap-2 text-sm`,children:[k(`input`,{type:`checkbox`,checked:f.includes(e.id),disabled:u,onChange:()=>_(e.id),"data-testid":`alarm-target-${e.id}`}),k(`span`,{children:e.name}),e.enabled?null:k(h,{variant:`warning`,children:`disabled`})]},e.id)),f.length===0?k(`p`,{className:`text-xs text-warning`,children:`No target selected — the announcement will not be sent.`}):null]}):null]}),x(i,{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:c.coverage.map(e=>x(`div`,{className:`flex items-start gap-3 rounded border border-border p-2`,"data-mode":e.mode,"data-empty":mr(e)?`true`:`false`,children:[k(`div`,{className:`w-20 shrink-0 text-sm font-medium`,children:dr(e.mode)}),k(`div`,{className:`flex-1 text-sm text-foreground-subtle`,children:pr(e,s)}),mr(e)?k(pe,{className:`h-4 w-4 shrink-0 text-warning`}):null]},e.mode))})]})]})})}var wr=[{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 Tr(e){return wr.find(t=>t.value===e)?.value}function Er(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Dr(e){return``}var Or={x:.25,y:.25,w:.5,h:.5},kr={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Ar(){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:Or,occupancy:kr,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function jr(e){return e.deviceId!==null}function Q(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Mr(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Nr(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 Pr(e){if(e.deviceId===null)return null;let t=e.trigger,n=Mr(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:Fr(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 Fr(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 Ir(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Lr(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 Rr(e){let t=Ar(),n=e.conditions,r=Lr(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:Ir(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Ir(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Ir(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:Dr(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:zr(n.occupancy)},onlyRuleId:e.id}}function zr(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 Br(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 Vr(e){return{form:Rr(e),caveats:Br(e),ruleName:e.name}}var Hr=null;function Ur(e){Hr=e}function Wr(){return Hr}function Gr(){Hr=null}var Kr=[`n/a`,`clear`,`suppressed`,`bypassed`],qr=[`live`,`none`,`unavailable`,`unattachable`];function Jr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Yr(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Xr(e){if(!Jr(e))return null;let t=$(e,`ruleId`),n=$(e,`ruleName`),r=$(e,`cooldown`),i=Kr.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=$(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Yr(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:Yr(e,`targetIds`)}}function Zr(e){if(!Jr(e))return null;let t=$(e,`recordId`),n=$(e,`delivery`),r=$(e,`still`),i=qr.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=Xr(e);t!==null&&o.push(t)}let s=$(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Yr(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Qr(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 $r=new Set([`sensor`,`control`,`custom`]);function ei({form:e,cameras:t,taxonomy:n,kinds:r,kindsLoading:i,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=j(`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(ti,{form:e,kinds:r,loading:i,onPatch:o})]});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:J,children:`Audio classes`}),k(It,{options:n,value:e.classNames,onChange:e=>o({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:J,children:`Zones`}),k(Z,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({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(ni,{form:e,cameras:t,taxonomy:n,onPatch:o})]}):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:J,children:`Detected classes`}),c===null?k(hn,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):k(gn,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),x(`div`,{children:[k(`label`,{className:J,children:`Zones the subject is in`}),k(Z,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({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(a,{value:e.packagePhase,options:[{value:``,label:`— none —`},{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`}],onChange:e=>o({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function ti({form:e,kinds:t,loading:n,onPatch:r}){let i=t.filter(e=>$r.has(e.category)),o=i.find(t=>t.kind===e.sensorKind);return x(w,{children:[x(`div`,{children:[k(`label`,{className:J,children:`Event kind`}),k(a,{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:J,children:`Source device`}),k(v,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>r({sourceDeviceId:Q(e.target.value)??null})}),k(`p`,{className:Y,children:o===void 0?`The linked device whose state changed. Filled in for you when you pick a kind.`:`Filled in from "${o.label}" — contributed by device #${o.source.deviceId} via the ${o.source.capName} capability.`})]}),x(`div`,{children:[k(`label`,{className:J,children:`Event type token`}),k(v,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>r({eventType:e.target.value})}),k(`p`,{className:Y,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 ni({form:e,cameras:t,taxonomy:n,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId],o=j(`classes`,n),s=o===null?[]:o.groups.flatMap(e=>e.options),c=e.occupancy,l=e=>r({occupancy:{...c,...e}});return x(w,{children:[x(`div`,{children:[k(`label`,{className:J,children:`Zone`}),k(Z,{deviceIds:i,cameras:t,value:c.zoneId===``?[]:[c.zoneId],onChange:e=>l({zoneId:e[e.length-1]??``})}),k(`p`,{className:Y,children:`Leave empty for the whole frame.`})]}),x(`div`,{className:`max-w-[14rem]`,children:[k(`label`,{className:J,children:`Class`}),k(a,{value:c.className,options:[{value:``,label:`— any class —`},...s.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({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(v,{type:`number`,min:0,className:`w-20`,value:String(c.count),onChange:e=>l({count:Q(e.target.value)??0})})]}),x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,k(v,{type:`number`,min:0,className:`w-20`,value:String(c.previousCount),onChange:e=>l({previousCount:Q(e.target.value)??0})})]}),x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,k(v,{type:`number`,min:1,className:`w-20`,value:String(c.threshold),onChange:e=>l({threshold:Q(e.target.value)??1})})]}),x(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[k(p,{checked:c.occupied,onCheckedChange:e=>l({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function ri({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(p,{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(a,{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(Z,{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(p,{checked:e.bboxEnabled,onCheckedChange:e=>n({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),k(`p`,{className:Y,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(v,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:r=>n({bbox:{...e.bbox,[t]:Q(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:J,children:`Happened at`}),x(`div`,{className:`flex items-center gap-2`,children:[k(v,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>n({timestampLocal:e.target.value})}),e.timestampLocal===``?k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:Nr(Date.now())}),children:`Set`}):k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:``}),children:`Now`})]}),k(`p`,{className:Y,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:J,children:`Detection source`}),k(a,{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 ii({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(p,{checked:e,onCheckedChange:i,"aria-label":t}),t,r&&k(h,{variant:`danger`,children:`actuates devices`})]}),k(`p`,{className:Y,children:n})]})}b();var ai={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.`},oi={"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 si({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:Qr(e)}),x(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[k(ci,{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:ai[e.still],children:[`still `,k(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&x(h,{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(li,{outcome:e,targetName:t},e.ruleId))})]})}function ci({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(m,{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(F,{className:`h-3 w-3`})}),t&&k(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function li({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(P,{className:`h-3.5 w-3.5 shrink-0 text-success`}):k(ue,{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:oi[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 ui=`pipeline-analytics`,di=`nc.injectTestEvent`;function fi(){let e=N(),[t,n]=D(()=>Wr()?.form??Ar()),[r]=D(()=>Wr()?.caveats??[]),[o]=D(()=>Wr()?.ruleName??null);A(()=>Gr(),[]);let[s,c]=D(null),[l,u]=D(!1),[d,f]=D(null),p=e=>n(t=>({...t,...e})),h=C({queryKey:Jn,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===te.Camera).map(e=>({id:e.id,name:e.name}))}),_=C({queryKey:qn,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),y=C({queryKey:Gn,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),b=C({queryKey:Kn,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??[],ee=_.data?.taxonomy,ne=T.data??[],j=S(()=>{let e=new Map;for(let t of b.data??[])e.set(t.id,t.name);return e},[b.data]),M=O({mutationFn:async()=>{let n=Pr(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:ui,action:di,input:n})},onMutate:()=>{c(null),u(!1),f(null)},onSuccess:e=>{let t=Zr(e);c(t),u(t===null)},onError:e=>f(e instanceof Error?e.message:`The simulation failed.`)}),re=Er(t.trigger),P=y.data?.find(e=>e.id===t.onlyRuleId);return x(B,{icon:V,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(g,{title:`Failed to load cameras`,message:h.error instanceof Error?h.error.message:`Unknown error`,onRetry:()=>void h.refetch()}),o!==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:o}),`. 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(pe,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),k(`span`,{children:e.note})]},e.conditionId))}),x(i,{className:`space-y-4`,children:[x(`div`,{children:[k(`label`,{className:J,children:`Camera`}),k(a,{"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:Q(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),k(`p`,{className:Y,children:`The camera the event is attributed to — what a notification shows.`})]}),x(`div`,{children:[k(`label`,{className:J,children:`Trigger`}),k(a,{"data-testid":`simulate-trigger`,value:t.trigger,options:wr.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=Tr(e.target.value);if(!n)return;let r=Dr(t.trigger);p({trigger:n,source:t.source===``||t.source===r?Dr(n):t.source})}}),x(`p`,{className:Y,children:[wr.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,k(`span`,{className:`text-foreground`,children:re}),` are candidates.`]})]}),k(ei,{form:t,cameras:E,taxonomy:ee,kinds:ne,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:Y,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:J,children:`Label (identity name / plate / subclass)`}),k(v,{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:J,children:`Detection confidence`}),k(X,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>p({confidence:e})})]}),x(`div`,{children:[k(`label`,{className:J,children:`Label-match confidence`}),k(X,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>p({labelConfidence:e})})]}),x(`div`,{children:[k(`label`,{className:J,children:`Importance`}),k(X,{value:t.importance,min:0,max:1,step:.05,onChange:e=>p({importance:e})})]}),x(`div`,{children:[k(`label`,{className:J,children:`Dwell (seconds)`}),k(X,{value:t.dwellSeconds,min:0,step:1,onChange:e=>p({dwellSeconds:e})})]})]})]})]}),k(ri,{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(ii,{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(ii,{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(ii,{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:J,children:`Still image`}),k(a,{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:J,children:`Evaluate only one rule`}),k(a,{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&&P===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(m,{size:`sm`,type:`button`,disabled:M.isPending||!jr(t),onClick:()=>M.mutate(),children:[M.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(V,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),l&&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.`}),s!==null&&k(si,{result:s,targetName:e=>j.get(e)??e})]})}var pi=`simulate`;function mi(){let[e,t]=de();return k(`div`,{className:`flex flex-col p-4`,children:k(me,{tabs:[{id:`targets`,label:`Targets`,icon:le,content:k(Ge,{})},{id:`rules`,label:`Rules`,icon:ge,content:k(Qn,{onSimulateRule:n=>{Ur(Vr(n));let r=new URLSearchParams(e);r.set(`tab`,pi),t(r,{replace:!0})}})},{id:pi,label:`Simulate`,icon:V,content:k(fi,{})},{id:`history`,label:`History`,icon:_e,content:k(cr,{})},{id:`alarm`,label:`Alarm`,icon:R,content:k(Cr,{})}]})})}export{mi as NotificationsPage,mi as default};
1
+ import{$n as e,Do as t,Eo as n,Ho as r,Jo as i,Ko as a,Oo as o,Ro as s,S as c,So as l,To as u,Uo as d,Vo as f,Wo as p,Xo as m,Yo as h,lo as g,oa as _,qo as v,zo as y}from"./src-B5uaqYy4.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{C as ee,P as te,b as ne,c as j,o as M,s as re}from"./src-B0nZ9rxd.js";import{p as N}from"./player-overlays-BfbNCp8v.js";import{t as P}from"./circle-check-big-Bf0ewxaf.js";import{t as F}from"./copy-iAdKX02A.js";import{t as ie}from"./pencil-D6ny7fbm.js";import{t as I}from"./plus-Ct8CXOT7.js";import{t as ae}from"./refresh-cw-CSup0Ybd.js";import{t as oe}from"./search-DM6VGLFN.js";import{t as se}from"./send-IMkq2UdA.js";import{G as ce,H as le,P as ue,S as L,Y as de,f as R,i as fe,o as pe,s as z}from"./index-Dg1Uu8YH.js";import{t as B}from"./AdminPage-Dq33XE9j.js";import{t as me}from"./AdminTabs-DCAQ34eW.js";var he=ce(`bell-off`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742`,key:`178tsu`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05`,key:`1hqiys`}]]),ge=ce(`bell-ring`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M22 8c0-2.3-.8-4.3-2-6`,key:`5bb3ad`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}],[`path`,{d:`M4 2C2.8 3.7 2 5.7 2 8`,key:`tap9e0`}]]),V=ce(`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`}]]),_e=ce(`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`}]]);b();var H=e=>typeof e==`string`&&e.length>0;function ve(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 ye(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function be(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];H(i)&&n.push({mediaType:r,url:i})}return n}function xe(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=H(r.label),i=H(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 Se(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=be(e,t.attachmentUrls),i=xe(e,t.actions),a=e.ttl&&H(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:ye(e,t.format),priority:Ce(t.priority),...H(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&H(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&H(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...H(t.tag)?{tag:t.tag}:{}}}function Ce(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function we(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 Te(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Ee={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 De(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function Oe(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])De(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function ke(e,t,n){let r=Te(e);return De(e,t)?{...r,body:n,attachmentUrls:{[t]:Ee[t]}}:{...r,body:n}}function Ae(e,t){let n=Te(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return ke(e,`image`,`Test notification with an image.`);case`gif`:return ke(e,`gif`,`Test notification with an animation.`);case`video`:return ke(e,`video`,`Test notification with a video.`);case`audio`:return ke(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=we(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}var je={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},U=`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`,W=`block text-[11px] font-medium text-foreground mb-1`;function Me({target:e,kind:t,open:n,onClose:i}){let a=N(),o=S(()=>ve(t.caps),[t.caps]),c=S(()=>Oe(t.caps),[t.caps]),[l,u]=D(()=>Te(t.caps)),[p,g]=D(null),_=S(()=>Se(t.caps,l),[t.caps,l]),v=l.body.length,b=v>o.bodyMaxLen,C=e=>u(t=>({...t,...e})),w=O({mutationFn:()=>a.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:Se(t.caps,l)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:`Test failed`})}),T=e=>{u(Ae(t.caps,e)),g(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(s,{open:n,onOpenChange:e=>!e&&i(),children:x(y,{width:`lg`,className:`!max-w-2xl`,children:[k(r,{children:x(d,{children:[`Test "`,e.name,`" (`,t.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(m,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>T(e),children:je[e]},e))}),x(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[o.levels.length>0&&x(`div`,{children:[k(`label`,{className:W,children:`Level`}),x(`select`,{className:U,value:l.level,onChange:e=>C({level:e.target.value}),children:[k(`option`,{value:``,children:`— derive from priority —`}),o.levels.map(e=>x(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=o.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(h,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&k(h,{variant:`info`,children:`silent`}),e.flags?.noPush&&k(h,{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:W,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`})]})]}),o.formats.length>0&&x(`div`,{children:[k(`label`,{className:W,children:`Format`}),k(`div`,{className:`flex flex-wrap gap-2`,children:o.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:W,children:`Title`}),k(`input`,{className:U,value:l.title,onChange:e=>C({title:e.target.value})})]}),x(`div`,{children:[x(`label`,{className:W,children:[`Body`,` `,x(`span`,{className:b?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,o.bodyMaxLen,b?` — overflow`:``,`)`]})]}),k(`textarea`,{className:`${U} min-h-[80px] resize-y`,value:l.body,onChange:e=>C({body:e.target.value})})]}),o.attachmentSlots.length>0&&x(`div`,{children:[x(`label`,{className:W,children:[`Attachments`,` `,x(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,o.attachmentMode,`, max `,o.attachmentMax,o.attachmentMaxBytes?`, ≤${Math.round(o.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),k(`div`,{className:`space-y-1.5`,children:o.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:U,placeholder:`${e} URL`,value:l.attachmentUrls[e]??``,onChange:t=>C({attachmentUrls:{...l.attachmentUrls,[e]:t.target.value}})})]},e))})]}),o.showActions&&x(`div`,{children:[x(`label`,{className:W,children:[`Actions (up to `,o.maxActions,`)`]}),k(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(o.maxActions,3)},(e,t)=>x(`div`,{className:`flex items-center gap-2`,children:[k(`input`,{className:U,placeholder:`label`,value:l.actions[t]?.label??``,onChange:e=>E(t,`label`,e.target.value)}),k(`input`,{className:U,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:[o.showClickUrl&&x(`div`,{children:[k(`label`,{className:W,children:`Click URL`}),k(`input`,{className:U,value:l.clickUrl,onChange:e=>C({clickUrl:e.target.value})})]}),o.showSound&&x(`div`,{children:[k(`label`,{className:W,children:`Sound`}),k(`input`,{className:U,value:l.sound,onChange:e=>C({sound:e.target.value})})]}),o.showTtl&&x(`div`,{children:[k(`label`,{className:W,children:`TTL (seconds)`}),k(`input`,{className:U,type:`number`,value:l.ttl,onChange:e=>C({ttl:e.target.value})})]}),o.showTag&&x(`div`,{children:[k(`label`,{className:W,children:`Tag`}),k(`input`,{className:U,value:l.tag,onChange:e=>C({tag:e.target.value})})]})]}),p&&k(Ne,{result:p}),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(_,null,2)})]})]}),x(f,{children:[k(m,{variant:`secondary`,size:`sm`,type:`button`,onClick:i,children:`Close`}),x(m,{size:`sm`,type:`button`,disabled:w.isPending||l.body.length===0,onClick:()=>w.mutate(),children:[w.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(se,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function Ne({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(P,{className:`h-3.5 w-3.5 text-success`}):k(ue,{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 Pe(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 Fe(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 Ie(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 Le(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 Re=[`notificationOutput`,`listTargets`],ze=[`notificationOutput`,`listTargetKinds`],Be=[`userManagement`,`listUsers`],Ve=`ownerUserId`;function He(e){let t=e.config[Ve];return typeof t==`string`&&t.length>0?t:null}function Ue(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(We,{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(h,{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=He(t);return n===null?k(h,{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(p,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let n=e.kindByKey.get(t.kind);return x(`span`,{className:`flex items-center justify-end gap-1`,children:[k(m,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>e.onTest(t),title:`Test`,children:k(se,{className:`h-3.5 w-3.5`})}),k(m,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>n&&e.onEdit(t,n),title:`Edit`,children:k(ie,{className:`h-3.5 w-3.5`})}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:k(z,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function We({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 Ge(){let e=N(),[t,n]=D({mode:`closed`}),[r,a]=D(null),o=C({queryKey:Re,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),s=C({queryKey:ze,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]),u=S(()=>{let e=new Map;for(let t of c)e.set(t.kind,t);return e},[c]),d=C({queryKey:Be,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),f=S(()=>{let e=new Map;for(let t of d.data??[])e.set(t.id,t.username);return e},[d.data]),p=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()}),_=r?u.get(r.kind):void 0;return x(B,{icon:le,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(m,{size:`sm`,type:`button`,onClick:()=>n({mode:`pick-kind`}),children:[k(I,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[o.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),o.isError&&!o.isLoading&&k(g,{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(i,{children:k(l,{columns:Ue({kindByKey:u,userNameById:f,onToggle:(e,t)=>p.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(Ke,{kinds:c,onCancel:()=>n({mode:`closed`}),onPick:e=>n({mode:`form`,kind:e,target:null})}),t.mode===`form`&&k(qe,{kind:t.kind,target:t.target,users:d.data??[],onCancel:()=>n({mode:`closed`}),onSaved:()=>{n({mode:`closed`}),o.refetch()}}),r&&_&&k(Me,{target:r,kind:_,open:!0,onClose:()=>a(null)})]})}function Ke({kinds:e,onPick:t,onCancel:n}){let r=S(()=>Pe(e),[e]);return x(i,{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(m,{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(We,{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(h,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})}function qe({kind:e,target:t,users:n,onSaved:r,onCancel:o}){let s=N(),l=S(()=>Fe(e.configSchema),[e.configSchema]),u=S(()=>t?.config??{},[t]),[d,f]=D(t?.name??e.label),[p,h]=D(()=>t?Le(t.config,l):{}),[g,_]=D(null),[v,y]=D(null),[b,C]=D(t?He(t)??``:``),w=O({mutationFn:()=>s.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:p}),onSuccess:e=>_(e),onError:e=>y(e instanceof Error?e.message:`Discovery failed`)}),T=O({mutationFn:()=>{let{[Ve]:n,...r}=Ie(p,u,l),i=b===``?r:{...r,[Ve]:b},a={id:t?.id??`${e.kind}-${Date.now()}`,name:d,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:i};return s.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:a})},onSuccess:r,onError:e=>y(e instanceof Error?e.message:`Save failed`)}),E=e=>{f(e.suggestedName),h(t=>({...t,...e.config})),_(null)};return x(i,{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(We,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),t?`Edit ${t.name}`:`Add ${e.label} target`]}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,children:`Cancel`})]}),v&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:v}),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:d,onChange:e=>f(e.target.value)})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),k(a,{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(m,{size:`sm`,variant:`outline`,type:`button`,disabled:w.isPending,onClick:()=>{y(null),w.mutate()},children:[w.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(oe,{className:`h-3.5 w-3.5`}),`Discover`]}),g&&g.length===0&&k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),g&&g.length>0&&k(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:g.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}`))})]}),l.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(c,{schema:e.configSchema,values:p,onChange:h}),x(`div`,{className:`flex justify-end gap-2`,children:[k(m,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:`Cancel`}),x(m,{size:`sm`,type:`button`,disabled:T.isPending||d.trim().length===0,onClick:()=>{y(null),T.mutate()},children:[T.isPending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),t?`Save changes`:`Create target`]})]})]})}var Je=[{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`}],Ye={sequences:[],buttons:[]};function Xe(e){return e===void 0?Ye:{sequences:[...e.onTrigger??[]],buttons:[...e.buttons??[]]}}function Ze(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 Qe(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 $e(e){return{name:`sequence ${String(e+1)}`,enabled:!1,actions:[]}}function et(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequence:t}}function tt(){return{kind:`wait`,seconds:5}}var G=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,K=`block text-[11px] font-medium text-foreground`;function nt({value:e,onChange:t,devices:n}){let r=Qe(e),i=(n,r)=>t({...e,sequences:e.sequences.map((e,t)=>t===n?r:e)}),a=(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(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t({...e,sequences:[...e.sequences,$e(e.sequences.length)]}),children:[k(I,{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,a)=>k(rt,{sequence:r,devices:n,onChange:e=>i(a,e),onRemove:()=>t({...e,sequences:e.sequences.filter((e,t)=>t!==a)})},`seq-${String(a)}`))]}),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(m,{size:`sm`,variant:`ghost`,type:`button`,disabled:e.sequences.length===0,onClick:()=>t({...e,buttons:[...e.buttons,et(e.buttons.length,e.sequences[0]?.name??``)]}),children:[k(I,{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(pe,{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(ot,{button:n,sequenceNames:e.sequences.map(e=>e.name),onChange:e=>a(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function rt({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:K,children:`Name`}),k(v,{className:`mt-1`,value:e.name,onChange:t=>n({...e,name:t.target.value})})]}),x(`div`,{className:`w-28`,children:[k(`label`,{className:K,children:`Min delay (s)`}),k(`input`,{type:`number`,min:0,className:G,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(p,{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(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove`,children:k(z,{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(it,{step:r,devices:t,onChange:e=>i(a,e),onRemove:()=>n({...e,actions:e.actions.filter((e,t)=>t!==a)})},`step-${String(a)}`)),x(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({...e,actions:[...e.actions,tt()]}),children:[k(I,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function it({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:K,children:`Step`}),x(`select`,{className:G,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:K,children:`Seconds`}),k(`input`,{type:`number`,min:0,max:300,className:G,value:e.seconds,onChange:e=>n({kind:`wait`,seconds:Number(e.target.value)})})]}):k(at,{step:e,devices:t,onChange:n}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove step`,children:k(z,{className:`h-3.5 w-3.5`})})]})}function at({step:e,devices:t,onChange:n}){let r=N(),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:K,children:`Device`}),x(`select`,{className:G,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:K,children:`Capability`}),x(`select`,{className:G,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:K,children:`Method`}),k(v,{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:K,children:`Arguments (JSON)`}),k(v,{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 ot({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:K,children:`Label`}),k(v,{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:K,children:`Runs`}),x(`select`,{className:G,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:K,children:`Icon`}),x(`select`,{className:G,value:e.icon??``,onChange:t=>{let r={...e};if(t.target.value===``)delete r.icon;else{let e=Je.find(e=>e.value===t.target.value);e!==void 0&&(r.icon=e.value)}n(r)},children:[k(`option`,{value:``,children:`None`}),Je.map(e=>k(`option`,{value:e.value,children:e.label},e.value))]})]}),x(`div`,{className:`flex items-center gap-2 pb-1`,children:[k(p,{checked:e.destructive===!0,onCheckedChange:t=>{let r={...e};t?r.destructive=!0:delete r.destructive,n(r)}}),k(h,{variant:e.destructive===!0?`danger`:`default`,children:`Destructive style`})]}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove`,children:k(z,{className:`h-3.5 w-3.5`})})]})}var st={search:``,types:[],selectedOnly:!1};function ct(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 lt(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 ut(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 dt(e,t){let n=new Set(t);for(let t of e)n.add(t.id);return[...n]}function ft(e,t){let n=new Set(e.map(e=>e.id));return t.filter(e=>!n.has(e))}function pt(e,t){return e.length===0?`Every device (${String(t)}) — no restriction`:`${String(e.length)} of ${String(t)} selected`}b();function mt({devices:e,value:t,onChange:n,loading:r=!1}){let[i,a]=D(st),o=S(()=>ct(e),[e]),s=S(()=>lt(e,i,t),[e,i,t]),c=S(()=>ut(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:pt(t,e.length)}),x(`div`,{className:`flex items-center gap-1`,children:[k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n(dt(s,t)),children:`Select shown`}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n(ft(s,t)),children:`Clear shown`})]})]}),x(`div`,{className:`flex flex-wrap items-center gap-2`,children:[k(v,{className:`min-w-[10rem] flex-1`,value:i.search,placeholder:`Search by name…`,leftSlot:k(oe,{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(h,{variant:`default`,children:e.type})]},e.id))})]},e.location??`__unplaced`))})]})}function q(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var ht=q({devices:!0}),gt=q({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),_t=q({zonesExclude:!0}),vt=q({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),yt=q({minDwellSeconds:!0}),bt=q({source:!0}),xt=q({crossing:!0}),St=q({packagePhase:!0}),Ct=q({zones:!0}),wt=q({plates:!0}),Tt=q({occupancy:!0}),Et=q({deviceState:!0});function Dt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Ot(e,t){let n=e[t];return typeof n==`number`?n:void 0}var kt=[{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:`schedule`,label:`Schedule`}];function At(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function jt(e,t){let n=e.filter(t),r=new Set(kt.map(e=>e.id)),i=[];for(let e of kt){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:At(e),descriptors:n.filter(t=>t.group===e)});return i}b();function Mt(e,t){let n=N().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 Nt(e){let t=N().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 Pt(){let t=e();return S(()=>({options:(t.data??[]).map(e=>({value:e.name,label:e.name})),loading:t.isLoading}),[t.data,t.isLoading])}function Ft(){let e=_({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 It({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 Lt=[{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.`}];function Rt(e){return Lt.find(t=>t.value===e)?.label??e}function zt(e){return Lt.find(t=>t.value===e)?.value}var Bt=[{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 Vt(e){return Bt.find(t=>t.value===e)?.value}var Ht=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function Ut(e){let t=Ht.find(t=>t.value===e)?.value;return t===``?void 0:t}var Wt=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function Gt(e){let t=Wt.find(t=>t.value===e)?.value;return t===``?void 0:t}var Kt=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],qt=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],Jt=[{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 Yt(e){let t=Jt.find(t=>t.value===e)?.value;return t===``||t===void 0?void 0:t}var Xt=[{value:`any`,label:`Any of`},{value:`all`,label:`All of`}],Zt=[{value:1,label:`1 — Min`},{value:2,label:`2 — Low`},{value:3,label:`3 — Default`},{value:4,label:`4 — High`},{value:5,label:`5 — Max`}];function Qt(){return{name:``,enabled:!0,delivery:`immediate`,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,actions:Ye,deviceIds:[]}}function $t(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,actions:Xe(e.actions),deviceIds:e.conditions.devices??[]}}function en(e){return e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&Qe(e.actions).length===0}function tn(e,t){return e.appliesTo.includes(t)}var nn={source:`any`};function rn(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||nn[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}function an(e,t,n){let r=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&tn(e,t)).map(e=>e.id)),i={};for(let[t,n]of Object.entries(e))r!==null&&!r.has(t)||rn(t,n)||(i[t]=n);return i}function on(e){return e!==void 0&&e.windows.length>0}function sn(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=Ze(e.actions),s=(n.length===0||n.some(t=>t.id===`schedule`&&tn(t,e.delivery)))&&on(e.schedule)?e.schedule:void 0;return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...an(e.conditions,e.delivery,n),...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:{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:t?.throttle??{cooldownSec:60,scope:`rule-device`},priority:e.priority,...a?{template:a}:{},...e.snoozeAllowGlobal?{snoozeAllowGlobal:!0}:{},...o===void 0?{}:{actions:o}}}function cn(e,t){return e.options&&e.options.length>0?e.options:t}var ln=[{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 un(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var dn=[{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`]}],fn=`rule`;function pn(e){return dn.find(t=>t.key===e)?.key}b();var J=`block text-[11px] font-medium text-foreground`,Y=`text-[10px] text-foreground-subtle mt-0.5`;function mn({cameras:e,value:t,onChange:n}){if(e.length===0)return k(`p`,{className:Y,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 hn({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(fe,{className:`h-3 w-3`})})]},e))}),k(v,{value:r,placeholder:t,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),a())},onBlur:a})]})}function gn({picker:e,value:t,onChange:n}){let r=S(()=>re(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 X({value:e,min:t,max:n,step:r,onChange:i}){return x(`div`,{className:`mt-1 flex items-center gap-2`,children:[k(v,{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 _n({value:e,onChange:t,options:n}){let r=e??``,i=n&&n.length>0?n:Jt,o=i.find(e=>e.value===r);return x(`div`,{className:`mt-1 space-y-1`,children:[k(a,{value:r,options:i.map(e=>({value:e.value,label:e.label})),onChange:e=>t(Yt(e.target.value))}),o!==void 0&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:o.hint})]})}function vn({deviceIds:e,cameras:t,value:n,onChange:r}){let i=n?.ids??[],o=n?.match??`any`,s=e=>r(e.length>0?{ids:e,match:o}:void 0),c=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(a,{value:o,options:Xt.map(e=>({value:e.value,label:e.label})),onChange:e=>c(e.target.value===`all`?`all`:`any`)})}),k(Z,{deviceIds:e,cameras:t,value:i,onChange:s})]})}function Z({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=Mt(e,t);return k(It,{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 yn({value:e,onChange:t}){let{options:n,loading:r}=Pt();return k(It,{options:n,value:e,onChange:t,loading:r,emptyHint:`No identities in the face gallery yet — type a name.`,placeholder:`Identity name…`})}function bn({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=Nt(e);return k(It,{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 xn=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}],Sn={op:`became-occupied`,count:1,sustainSeconds:15};function Cn({deviceIds:e,cameras:t,classOptions:n,value:r,onChange:i}){let{options:o,loading:s}=Mt(e,t),c=r??Sn,l=e=>i({...c,...e}),u=c.op===`became-occupied`||c.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(a,{value:c.zoneId??``,options:[{value:``,label:s?`Loading zones…`:`— whole frame —`},...o.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({zoneId:e.target.value===``?void 0:e.target.value})})}),k(`div`,{className:`min-w-[9rem]`,children:k(a,{value:c.className??``,options:[{value:``,label:`— any class —`},...n.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({className:e.target.value===``?void 0:e.target.value})})}),k(`div`,{className:`min-w-[9rem]`,children:k(a,{value:c.op,options:xn.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=xn.find(t=>t.value===e.target.value);t&&l({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:[u?`Threshold`:`Count`,k(v,{type:`number`,min:0,className:`w-16`,value:String(c.count),onChange:e=>l({count:Math.max(0,Number(e.target.value)||0)})})]}),x(`label`,{className:`flex items-center gap-1`,children:[`Hold for`,k(v,{type:`number`,min:0,max:3600,className:`w-16`,value:String(c.sustainSeconds),onChange:e=>l({sustainSeconds:Math.min(3600,Math.max(0,Number(e.target.value)||0))})}),`s`]}),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 wn({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=Ft().filter(e=>!n.includes(e));return x(`div`,{className:`mt-1 space-y-1.5`,children:[k(hn,{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(v,{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 Tn({gateable:e,value:t,onChange:n}){let r=e.find(e=>e.id===t?.deviceId),i=new Set(t?.states??[]),o=e=>{let t=Number(e);if(!Number.isFinite(t)||t===0)return n(void 0);n({deviceId:t,states:[]})},s=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(a,{value:t===void 0?``:String(t.deviceId),options:[{value:``,label:`— no device gate —`},...e.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>o(e.target.value)}),r!==void 0&&k(`div`,{className:`flex flex-wrap gap-1.5`,children:r.states.map(e=>k(`button`,{type:`button`,onClick:()=>s(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 En=[{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 Dn(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function On(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 kn(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function An({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,kn()],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:Y,children:`Always active — add a window to restrict when the rule fires.`}):n.map((e,t)=>k(jn,{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(I,{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 jn({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:Dn(e.startMinute),onChange:n=>t({...e,startMinute:On(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:Dn(e.endMinute),onChange:n=>t({...e,endMinute:On(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(z,{className:`h-3.5 w-3.5`})})]}),k(`div`,{className:`flex flex-wrap gap-1`,children:En.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))})]})}b();function Mn({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(()=>jt(e,e=>e.id!==`devices`&&M(e.id)),[e]),d=S(()=>jt(e,e=>e.id!==`devices`&&!M(e.id)),[e]),[f,p]=D(()=>{if(Pn(r,i))return!0;try{return localStorage.getItem(Nn)===`1`}catch{return!1}}),m=()=>{let e=!f;p(e);try{localStorage.setItem(Nn,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=tn(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:J,children:e.label}),!s&&x(h,{variant:`default`,children:[`not for `,e.appliesTo.join(` / `)]})]}),s?k(Fn,{descriptor:e,taxonomy:t,conditions:r,schedule:i,cameras:a,gateable:o,onFieldChange:l,onScheduleChange:c}):k(`p`,{className:Y,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:m,"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:f?`▾ Hide advanced configurations`:`▸ Show more configurations`}),f&&g(d)]})}var Nn=`camstack.nc.showAdvanced`;function Pn(e,t){for(let[t,n]of Object.entries(e))if(!M(t)&&n!==void 0&&!(Array.isArray(n)&&n.length===0))return!0;return t!==void 0&&t.windows.length>0}function Fn({descriptor:e,taxonomy:t,conditions:n,schedule:r,cameras:i,gateable:o,onFieldChange:s,onScheduleChange:c}){switch(e.valueType){case`deviceIdList`:{if(!ht(e.id))break;let t=e.id;return k(mn,{cameras:i,value:n[t]??[],onChange:e=>s(t,e.length>0?e:void 0)})}case`stringList`:{if(!gt(e.id))break;let r=e.id,i=e=>s(r,e.length>0?e:void 0);if(r===`identities`||r===`identitiesExclude`)return k(yn,{value:Dt(n,r),onChange:i});if(r===`eventTypeTokens`)return k(bn,{deviceIds:n.devices??[],value:Dt(n,r),onChange:i});let a=j(r,t);return a===null?k(hn,{value:Dt(n,r),placeholder:`Add value…`,onChange:i}):k(gn,{picker:a,value:Dt(n,r),onChange:i})}case`zoneIdList`:{if(!_t(e.id))break;let t=e.id;return k(Z,{deviceIds:n.devices??[],cameras:i,value:Dt(n,t),onChange:e=>s(t,e.length>0?e:void 0)})}case`number01`:{if(!vt(e.id))break;let t=e.id;return k(X,{value:Ot(n,t),min:0,max:1,step:.05,onChange:e=>s(t,e)})}case`number`:{if(!yt(e.id))break;let t=e.id;return k(X,{value:Ot(n,t),min:0,step:1,onChange:e=>s(t,e)})}case`sourceSelect`:{if(!bt(e.id))break;let t=e.id;return k(a,{value:n[t]??`any`,options:cn(e,Kt).map(e=>({value:e.value,label:e.label})),onChange:e=>s(t,Rn(e.target.value))})}case`deviceState`:if(!Et(e.id))break;return k(Tn,{gateable:o,value:n.deviceState,onChange:e=>s(`deviceState`,e)});case`crossingSelect`:{if(!xt(e.id))break;let t=e.id;return k(_n,{value:n[t],onChange:e=>s(t,e),...e.options?{options:e.options}:{}})}case`packagePhase`:{if(!St(e.id))break;let t=e.id;return k(a,{value:n[t]??``,options:[{value:``,label:`— any phase —`},...cn(e,qt).map(e=>({value:e.value,label:e.label}))],onChange:e=>s(t,zn(e.target.value))})}case`zoneSelection`:{if(!Ct(e.id))break;let t=e.id;return k(vn,{deviceIds:n.devices??[],cameras:i,value:n[t],onChange:e=>s(t,e)})}case`plateMatcher`:{if(!wt(e.id))break;let t=e.id;return k(wn,{value:n[t],onChange:e=>s(t,e)})}case`occupancy`:{if(!Tt(e.id))break;let r=e.id;return k(Cn,{deviceIds:n.devices??[],cameras:i,classOptions:In(t),value:n[r],onChange:e=>s(r,e)})}case`schedule`:return k(An,{value:r,onChange:c});default:break}return k(Ln,{descriptor:e,conditions:n})}function In(e){let t=j(`classes`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Ln({descriptor:e,conditions:t}){let n=Object.entries(t).find(([t])=>t===e.id);return x(`p`,{className:Y,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 Rn(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function zn(e){return qt.find(t=>t.value===e)?.value}b();var Bn=[`notificationRules`,`listSnoozes`],Vn=3e4;function Hn(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function Un(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 Wn({rules:e}){let t=N(),n=E(),r=C({queryKey:Bn,refetchInterval:Vn,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),a=O({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>n.invalidateQueries({queryKey:Bn})}),o=S(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),s=Date.now(),c=(r.data??[]).filter(e=>s>=e.startedAt&&s<e.expiresAt);return c.length===0?null:x(i,{className:`p-4`,children:[x(`div`,{className:`flex items-center gap-2 mb-3`,children:[k(he,{className:`h-4 w-4 text-foreground-subtle`}),k(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),k(`div`,{className:`space-y-2`,children:c.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??`?`}`:o.get(e.ruleId??``)??`A rule`}),e.global&&k(h,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),!e.summary&&k(h,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),x(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,Un(Hn(e,s))]})]}),k(m,{size:`sm`,variant:`outline`,disabled:a.isPending,onClick:()=>a.mutate(e.id),children:`End now`})]},e.id))})]})}b();var Gn=[`notificationRules`,`listRules`],Kn=[`notificationOutput`,`listTargets`,`forRules`],qn=[`notificationRules`,`getConditionCatalog`],Jn=[`deviceManager`,`listAll`,`forRules`],Yn=[`deviceManager`,`listAll`,`forRuleActions`],Xn=[`deviceManager`,`gateableDevices`],Zn=ee.options;function Qn({onSimulateRule:e}={}){let t=N(),[n,r]=D({mode:`closed`}),[a,o]=D(null),s=C({queryKey:Gn,queryFn:async()=>(await t.trpcClient.notificationRules.listRules.query({})).rules}),c=C({queryKey:Kn,queryFn:()=>t.trpcClient.notificationOutput.listTargets.query({})}),u=C({queryKey:qn,queryFn:()=>t.trpcClient.notificationRules.getConditionCatalog.query({})}),d=C({queryKey:Xn,queryFn:async()=>{let e=await t.trpcClient.deviceManager.listAll.query({}),n=[];for(let r of e){let e=ne(await t.trpcClient.deviceManager.loadRuntimeState.query({deviceId:r.id}),Zn);e.length>0&&n.push({id:r.id,name:r.name,states:e})}return n},staleTime:6e4}),f=C({queryKey:Yn,queryFn:async()=>(await t.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}),p=C({queryKey:Jn,queryFn:async()=>(await t.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===te.Camera).map(e=>({id:e.id,name:e.name}))}),h=S(()=>{let e=new Map;for(let t of c.data??[])e.set(t.id,t.name);return e},[c.data]),_=O({mutationFn:e=>t.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void s.refetch()}),v=O({mutationFn:e=>t.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>{o(null),s.refetch()}}),y=s.data??[];return x(B,{icon:ge,title:`Notification Rules`,subtitle:`Author rules that turn detections, doorbell presses and package events into notifications. Each rule picks a trigger, matches conditions and fans out to one or more delivery targets.`,actions:x(m,{size:`sm`,type:`button`,onClick:()=>r({mode:`form`,rule:null}),children:[k(I,{className:`h-3.5 w-3.5`}),`New rule`]}),children:[k(Wn,{rules:y}),s.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),s.isError&&!s.isLoading&&k(g,{title:`Failed to load rules`,message:s.error instanceof Error?s.error.message:`Unknown error`,onRetry:()=>void s.refetch()}),!s.isLoading&&!s.isError&&y.length===0&&k(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification rules yet. Click "New rule" to author one.`}),y.length>0&&k(i,{children:k(l,{columns:$n({targetNameById:h,confirmDeleteId:a,deletePending:v.isPending,onToggle:(e,t)=>_.mutate({ruleId:e.id,enabled:t}),onEdit:e=>r({mode:`form`,rule:e}),onDuplicate:e=>r({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:o,onConfirmDelete:e=>v.mutate(e.id),...e?{onTest:e}:{}}),rows:y,rowKey:e=>e.id,minWidthPx:760,bordered:!1})}),n.mode===`form`&&k(er,{rule:n.rule,targets:c.data??[],actuatable:f.data??[],catalog:u.data?.catalog??[],taxonomy:u.data?.taxonomy,cameras:p.data??[],gateable:d.data??[],onCancel:()=>r({mode:`closed`}),onSaved:()=>{r({mode:`closed`}),s.refetch()}})]})}function $n(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(h,{variant:`warning`,children:`disabled`})]})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:Rt(e.delivery)})},{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(p,{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(m,{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(V,{className:`h-3.5 w-3.5`})}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onEdit(t),title:`Edit`,children:k(ie,{className:`h-3.5 w-3.5`})}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:k(F,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?x(w,{children:[x(m,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),children:[e.deletePending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),`Confirm`]}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(t.id),title:`Delete`,children:k(z,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function er({rule:e,targets:r,catalog:i,taxonomy:c,cameras:l,gateable:d,actuatable:f,onSaved:g,onCancel:_}){let b=N(),S=e!=null&&e.id.length>0,[w,T]=D(()=>e?$t(e):Qt()),[E,A]=D(null),[ee,te]=D(null),[ne,j]=D(fn),M=e=>T(t=>({...t,...e})),re=S&&e?{throttle:e.throttle}:void 0,P=O({mutationFn:async()=>{let t=sn(w,re,i);S&&e?await b.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t}):await b.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:g,onError:e=>A(e instanceof Error?e.message:`Save failed`)}),F=O({mutationFn:async()=>{let e=sn(w,re,i);return(await b.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>te(null),onSuccess:e=>te(e),onError:e=>A(e instanceof Error?e.message:`Test failed`)}),ie=w.targetIds.map(e=>r.find(t=>t.id===e)?.name??e),I=e=>M({targetIds:w.targetIds.includes(e)?w.targetIds.filter(t=>t!==e):[...w.targetIds,e]}),ae=C({queryKey:[`userManagement`,`listUsers`],queryFn:()=>b.trpcClient.userManagement.listUsers.query()}).data,oe=e=>M({targetUsers:w.targetUsers.includes(e)?w.targetUsers.filter(t=>t!==e):[...w.targetUsers,e]}),se=Lt.find(e=>e.value===w.delivery)?.hint;return k(s,{open:!0,onOpenChange:e=>!e&&_(),children:x(y,{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(ge,{className:`h-4 w-4 text-foreground-subtle`}),S?`Edit ${e?.name}`:`New notification rule`]}),k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:_,children:`Cancel`})]}),E&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:E}),x(u,{value:ne,onValueChange:e=>j(pn(e)??ne),children:[k(t,{className:`mb-3`,children:dn.map(e=>k(o,{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(v,{value:w.name,onChange:e=>M({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(p,{checked:w.enabled,onCheckedChange:e=>M({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),k(a,{value:w.delivery,onChange:e=>{let t=zt(e.target.value);t&&M({delivery:t})},options:Lt.map(e=>({value:e.value,label:e.label}))}),se&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:se})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),r.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:r.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:w.targetIds.includes(e.id),onChange:()=>I(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&k(h,{variant:`warning`,children:`disabled`})]},e.id))})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(ae??[]).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:(ae??[]).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:w.targetUsers.includes(e.id),onChange:()=>oe(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&k(h,{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(mt,{devices:f,value:w.deviceIds,onChange:e=>M({deviceIds:e}),loading:f.length===0})}),k(n,{value:`actions`,className:`space-y-4`,children:k(nt,{value:w.actions,onChange:e=>M({actions:e}),devices:f})}),k(n,{value:`advanced`,className:`space-y-4`,children:x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(p,{checked:w.snoozeAllowGlobal,onCheckedChange:e=>M({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`}),`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(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(a,{value:String(w.priority),onChange:e=>M({priority:Number(e.target.value)}),options:Zt.map(e=>({value:String(e.value),label:e.label}))})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),k(a,{value:w.mediaAttach,onChange:e=>{let t=Vt(e.target.value);t&&M({mediaAttach:t})},options:Bt.map(e=>({value:e.value,label:e.label}))}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Bt.find(e=>e.value===w.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:w.mediaZoneCrop,onChange:e=>M({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:w.mediaGif,onChange:e=>M({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:w.mediaClip,onChange:e=>M({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(w.mediaGif||w.mediaClip)&&x(`div`,{className:`mt-2`,children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),k(a,{value:w.mediaProfile??``,onChange:e=>M({mediaProfile:Gt(e.target.value)}),options:Wt.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(a,{value:w.mediaClipSpeed===void 0?``:String(w.mediaClipSpeed),onChange:e=>M({mediaClipSpeed:un(e.target.value)}),options:ln.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.`})]})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),k(a,{value:w.mediaFrame??``,onChange:e=>M({mediaFrame:Ut(e.target.value)}),options:Ht.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(v,{value:w.templateTitle,onChange:e=>M({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:w.templateBody,onChange:e=>M({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:`Conditions`}),i.length===0?k(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):k(Mn,{catalog:i,taxonomy:c,delivery:w.delivery,conditions:w.conditions,schedule:w.schedule,cameras:l,gateable:d,onConditionsChange:e=>M({conditions:e}),onScheduleChange:e=>M({schedule:e})})]}),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(m,{size:`sm`,variant:`outline`,type:`button`,disabled:F.isPending||!en(w),onClick:()=>{A(null),F.mutate()},children:[F.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(V,{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.`}),ee!==null&&k(tr,{delivery:w.delivery,results:ee,targetNames:ie})]})]})]}),x(`div`,{className:`flex justify-end gap-2 mt-4`,children:[k(m,{variant:`secondary`,size:`sm`,type:`button`,onClick:_,children:`Cancel`}),x(m,{size:`sm`,type:`button`,disabled:P.isPending||!en(w),onClick:()=>{A(null),P.mutate()},children:[P.isPending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),S?`Save changes`:`Create rule`]})]})]})})}function tr({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(P,{className:`h-3.5 w-3.5 shrink-0 text-success`}):k(ue,{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))})]})}b();var nr=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],rr=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],ir=[50,100,250,500];function ar(){return{ruleId:``,deviceId:``,status:``,windowHours:24,limit:100}}function or(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function sr(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function cr(){let e=N(),[t,n]=D(ar),r=e=>n(t=>({...t,...e})),o=C({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),s=C({queryKey:[`deviceManager`,`listAll`,`forHistory`],queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===te.Camera).map(e=>({id:e.id,name:e.name}))}),c=Date.now(),u=C({queryKey:[`notificationRules`,`getHistory`,t],retry:!1,queryFn:async()=>{let n=t.windowHours>0?c-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)}:{},...or(t.status)?{status:or(t.status)}:{},...n===void 0?{}:{since:n}}})).entries}}),d=S(()=>{let e=new Map;for(let t of s.data??[])e.set(t.id,t.name);return e},[s.data]),f=e=>d.get(e)??`Camera #${String(e)}`,p=u.data??[],m=u.isError;return x(B,{icon:_e,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(a,{value:t.ruleId,onChange:e=>r({ruleId:e.target.value}),options:[{value:``,label:`All rules`},...(o.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(a,{value:t.deviceId,onChange:e=>r({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(s.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(a,{value:t.status,onChange:e=>r({status:e.target.value}),options:rr.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(a,{value:String(t.windowHours),onChange:e=>r({windowHours:Number(e.target.value)}),options:nr.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(a,{value:String(t.limit),onChange:e=>r({limit:Number(e.target.value)}),options:ir.map(e=>({value:String(e),label:String(e)}))})]})]}),u.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),m&&!u.isLoading&&k(i,{children:x(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[k(_e,{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 u.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(ae,{className:`h-3 w-3`}),` Retry`]})]})}),!m&&!u.isLoading&&p.length===0&&k(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!m&&p.length>0&&k(i,{children:k(l,{columns:lr(f),rows:p,rowKey:e=>e.id,minWidthPx:720,bordered:!1})})]})}function lr(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(h,{variant:sr(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:`—`})}]}var ur={home:`Home`,away:`Away`,night:`Night`,vacation:`Vacation`,custom_bypass:`Custom`};function dr(e){return ur[e]??e}function fr(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 pr(e,t){return e.ruleCount===0?`Arms nothing — no enabled rule is gated on this mode.`:e.allDevices?`Every device — ${hr(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${hr(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(e=>t.get(e)??`Device ${e}`).join(`, `)}function mr(e){return e.ruleCount===0}function hr(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function gr(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}b();var _r=[`notificationRules`,`getAlarmConfig`],vr=[`notificationOutput`,`listTargets`],yr=[`deviceManager`,`listAll`,`alarm-coverage`],br=600,xr=3600;function Sr({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(v,{type:`number`,min:0,max:r,value:s??String(n),disabled:a,onChange:e=>c(e.target.value),onBlur:()=>{let e=s===null?null:gr(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:fr(n,i)})]}),k(`p`,{className:`text-xs text-foreground-subtle`,children:t})]})}function Cr(){let e=N(),t=E(),n=C({queryKey:_r,queryFn:async()=>e.trpcClient.notificationRules.getAlarmConfig.query({})}),r=C({queryKey:vr,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),a=C({queryKey:yr,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).map(e=>({id:e.id,name:e.name}))}),o=O({mutationFn:t=>e.trpcClient.notificationRules.setAlarmConfig.mutate({patch:t}),onSuccess:()=>t.invalidateQueries({queryKey:_r})}),s=S(()=>{let e=new Map;for(let t of a.data??[])e.set(t.id,t.name);return e},[a.data]);if(n.isLoading)return k(B,{icon:R,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(L,{className:`h-5 w-5 animate-spin`})});let c=n.data;if(c===void 0||n.isError)return k(B,{icon:R,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(g,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(c.deviceId===null)return k(B,{icon:R,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(i,{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 l=c.settings,u=o.isPending,d=r.data??[],f=l.announceTargets,m=e=>{o.mutate(e)},_=e=>{m({announceTargets:f.includes(e)?f.filter(t=>t!==e):[...f,e]})};return k(B,{icon:R,title:`Alarm`,subtitle:`Panel delays, and what each mode actually arms.`,children:x(`div`,{className:`flex flex-col gap-4`,children:[o.isError?k(g,{title:`Could not save`,message:String(o.error)}):null,x(i,{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(Sr,{label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,value:l.exitDelaySec,max:br,zeroMeans:`arms immediately`,disabled:u,onCommit:e=>m({exitDelaySec:e})}),k(Sr,{label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,value:l.entryDelaySec,max:br,zeroMeans:`fires immediately`,disabled:u,onCommit:e=>m({entryDelaySec:e})}),k(Sr,{label:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,value:l.triggeredDurationSec,max:xr,zeroMeans:`until disarmed`,disabled:u,onCommit:e=>m({triggeredDurationSec:e})})]})]}),x(i,{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(p,{checked:l.announceArm,disabled:u,onCheckedChange:e=>m({announceArm:e}),"data-testid":`alarm-announce-toggle`})]}),l.announceArm?x(`div`,{className:`mt-3 flex flex-col gap-2`,children:[d.length===0?k(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification targets are configured — nothing can be sent.`}):d.map(e=>x(`label`,{className:`flex items-center gap-2 text-sm`,children:[k(`input`,{type:`checkbox`,checked:f.includes(e.id),disabled:u,onChange:()=>_(e.id),"data-testid":`alarm-target-${e.id}`}),k(`span`,{children:e.name}),e.enabled?null:k(h,{variant:`warning`,children:`disabled`})]},e.id)),f.length===0?k(`p`,{className:`text-xs text-warning`,children:`No target selected — the announcement will not be sent.`}):null]}):null]}),x(i,{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:c.coverage.map(e=>x(`div`,{className:`flex items-start gap-3 rounded border border-border p-2`,"data-mode":e.mode,"data-empty":mr(e)?`true`:`false`,children:[k(`div`,{className:`w-20 shrink-0 text-sm font-medium`,children:dr(e.mode)}),k(`div`,{className:`flex-1 text-sm text-foreground-subtle`,children:pr(e,s)}),mr(e)?k(pe,{className:`h-4 w-4 shrink-0 text-warning`}):null]},e.mode))})]})]})})}var wr=[{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 Tr(e){return wr.find(t=>t.value===e)?.value}function Er(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Dr(e){return``}var Or={x:.25,y:.25,w:.5,h:.5},kr={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Ar(){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:Or,occupancy:kr,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function jr(e){return e.deviceId!==null}function Q(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Mr(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Nr(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 Pr(e){if(e.deviceId===null)return null;let t=e.trigger,n=Mr(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:Fr(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 Fr(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 Ir(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Lr(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 Rr(e){let t=Ar(),n=e.conditions,r=Lr(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:Ir(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Ir(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Ir(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:Dr(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:zr(n.occupancy)},onlyRuleId:e.id}}function zr(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 Br(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 Vr(e){return{form:Rr(e),caveats:Br(e),ruleName:e.name}}var Hr=null;function Ur(e){Hr=e}function Wr(){return Hr}function Gr(){Hr=null}var Kr=[`n/a`,`clear`,`suppressed`,`bypassed`],qr=[`live`,`none`,`unavailable`,`unattachable`];function Jr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Yr(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Xr(e){if(!Jr(e))return null;let t=$(e,`ruleId`),n=$(e,`ruleName`),r=$(e,`cooldown`),i=Kr.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=$(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Yr(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:Yr(e,`targetIds`)}}function Zr(e){if(!Jr(e))return null;let t=$(e,`recordId`),n=$(e,`delivery`),r=$(e,`still`),i=qr.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=Xr(e);t!==null&&o.push(t)}let s=$(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Yr(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Qr(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 $r=new Set([`sensor`,`control`,`custom`]);function ei({form:e,cameras:t,taxonomy:n,kinds:r,kindsLoading:i,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=j(`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(ti,{form:e,kinds:r,loading:i,onPatch:o})]});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:J,children:`Audio classes`}),k(It,{options:n,value:e.classNames,onChange:e=>o({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:J,children:`Zones`}),k(Z,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({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(ni,{form:e,cameras:t,taxonomy:n,onPatch:o})]}):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:J,children:`Detected classes`}),c===null?k(hn,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):k(gn,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),x(`div`,{children:[k(`label`,{className:J,children:`Zones the subject is in`}),k(Z,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({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(a,{value:e.packagePhase,options:[{value:``,label:`— none —`},{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`}],onChange:e=>o({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function ti({form:e,kinds:t,loading:n,onPatch:r}){let i=t.filter(e=>$r.has(e.category)),o=i.find(t=>t.kind===e.sensorKind);return x(w,{children:[x(`div`,{children:[k(`label`,{className:J,children:`Event kind`}),k(a,{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:J,children:`Source device`}),k(v,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>r({sourceDeviceId:Q(e.target.value)??null})}),k(`p`,{className:Y,children:o===void 0?`The linked device whose state changed. Filled in for you when you pick a kind.`:`Filled in from "${o.label}" — contributed by device #${o.source.deviceId} via the ${o.source.capName} capability.`})]}),x(`div`,{children:[k(`label`,{className:J,children:`Event type token`}),k(v,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>r({eventType:e.target.value})}),k(`p`,{className:Y,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 ni({form:e,cameras:t,taxonomy:n,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId],o=j(`classes`,n),s=o===null?[]:o.groups.flatMap(e=>e.options),c=e.occupancy,l=e=>r({occupancy:{...c,...e}});return x(w,{children:[x(`div`,{children:[k(`label`,{className:J,children:`Zone`}),k(Z,{deviceIds:i,cameras:t,value:c.zoneId===``?[]:[c.zoneId],onChange:e=>l({zoneId:e[e.length-1]??``})}),k(`p`,{className:Y,children:`Leave empty for the whole frame.`})]}),x(`div`,{className:`max-w-[14rem]`,children:[k(`label`,{className:J,children:`Class`}),k(a,{value:c.className,options:[{value:``,label:`— any class —`},...s.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({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(v,{type:`number`,min:0,className:`w-20`,value:String(c.count),onChange:e=>l({count:Q(e.target.value)??0})})]}),x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,k(v,{type:`number`,min:0,className:`w-20`,value:String(c.previousCount),onChange:e=>l({previousCount:Q(e.target.value)??0})})]}),x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,k(v,{type:`number`,min:1,className:`w-20`,value:String(c.threshold),onChange:e=>l({threshold:Q(e.target.value)??1})})]}),x(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[k(p,{checked:c.occupied,onCheckedChange:e=>l({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function ri({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(p,{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(a,{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(Z,{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(p,{checked:e.bboxEnabled,onCheckedChange:e=>n({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),k(`p`,{className:Y,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(v,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:r=>n({bbox:{...e.bbox,[t]:Q(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:J,children:`Happened at`}),x(`div`,{className:`flex items-center gap-2`,children:[k(v,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>n({timestampLocal:e.target.value})}),e.timestampLocal===``?k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:Nr(Date.now())}),children:`Set`}):k(m,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:``}),children:`Now`})]}),k(`p`,{className:Y,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:J,children:`Detection source`}),k(a,{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 ii({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(p,{checked:e,onCheckedChange:i,"aria-label":t}),t,r&&k(h,{variant:`danger`,children:`actuates devices`})]}),k(`p`,{className:Y,children:n})]})}b();var ai={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.`},oi={"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 si({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:Qr(e)}),x(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[k(ci,{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:ai[e.still],children:[`still `,k(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&x(h,{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(li,{outcome:e,targetName:t},e.ruleId))})]})}function ci({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(m,{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(F,{className:`h-3 w-3`})}),t&&k(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function li({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(P,{className:`h-3.5 w-3.5 shrink-0 text-success`}):k(ue,{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:oi[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 ui=`pipeline-analytics`,di=`nc.injectTestEvent`;function fi(){let e=N(),[t,n]=D(()=>Wr()?.form??Ar()),[r]=D(()=>Wr()?.caveats??[]),[o]=D(()=>Wr()?.ruleName??null);A(()=>Gr(),[]);let[s,c]=D(null),[l,u]=D(!1),[d,f]=D(null),p=e=>n(t=>({...t,...e})),h=C({queryKey:Jn,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===te.Camera).map(e=>({id:e.id,name:e.name}))}),_=C({queryKey:qn,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),y=C({queryKey:Gn,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),b=C({queryKey:Kn,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??[],ee=_.data?.taxonomy,ne=T.data??[],j=S(()=>{let e=new Map;for(let t of b.data??[])e.set(t.id,t.name);return e},[b.data]),M=O({mutationFn:async()=>{let n=Pr(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:ui,action:di,input:n})},onMutate:()=>{c(null),u(!1),f(null)},onSuccess:e=>{let t=Zr(e);c(t),u(t===null)},onError:e=>f(e instanceof Error?e.message:`The simulation failed.`)}),re=Er(t.trigger),P=y.data?.find(e=>e.id===t.onlyRuleId);return x(B,{icon:V,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(g,{title:`Failed to load cameras`,message:h.error instanceof Error?h.error.message:`Unknown error`,onRetry:()=>void h.refetch()}),o!==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:o}),`. 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(pe,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),k(`span`,{children:e.note})]},e.conditionId))}),x(i,{className:`space-y-4`,children:[x(`div`,{children:[k(`label`,{className:J,children:`Camera`}),k(a,{"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:Q(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),k(`p`,{className:Y,children:`The camera the event is attributed to — what a notification shows.`})]}),x(`div`,{children:[k(`label`,{className:J,children:`Trigger`}),k(a,{"data-testid":`simulate-trigger`,value:t.trigger,options:wr.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=Tr(e.target.value);if(!n)return;let r=Dr(t.trigger);p({trigger:n,source:t.source===``||t.source===r?Dr(n):t.source})}}),x(`p`,{className:Y,children:[wr.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,k(`span`,{className:`text-foreground`,children:re}),` are candidates.`]})]}),k(ei,{form:t,cameras:E,taxonomy:ee,kinds:ne,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:Y,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:J,children:`Label (identity name / plate / subclass)`}),k(v,{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:J,children:`Detection confidence`}),k(X,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>p({confidence:e})})]}),x(`div`,{children:[k(`label`,{className:J,children:`Label-match confidence`}),k(X,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>p({labelConfidence:e})})]}),x(`div`,{children:[k(`label`,{className:J,children:`Importance`}),k(X,{value:t.importance,min:0,max:1,step:.05,onChange:e=>p({importance:e})})]}),x(`div`,{children:[k(`label`,{className:J,children:`Dwell (seconds)`}),k(X,{value:t.dwellSeconds,min:0,step:1,onChange:e=>p({dwellSeconds:e})})]})]})]})]}),k(ri,{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(ii,{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(ii,{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(ii,{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:J,children:`Still image`}),k(a,{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:J,children:`Evaluate only one rule`}),k(a,{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&&P===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(m,{size:`sm`,type:`button`,disabled:M.isPending||!jr(t),onClick:()=>M.mutate(),children:[M.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(V,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),l&&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.`}),s!==null&&k(si,{result:s,targetName:e=>j.get(e)??e})]})}var pi=`simulate`;function mi(){let[e,t]=de();return k(`div`,{className:`flex flex-col p-4`,children:k(me,{tabs:[{id:`targets`,label:`Targets`,icon:le,content:k(Ge,{})},{id:`rules`,label:`Rules`,icon:ge,content:k(Qn,{onSimulateRule:n=>{Ur(Vr(n));let r=new URLSearchParams(e);r.set(`tab`,pi),t(r,{replace:!0})}})},{id:pi,label:`Simulate`,icon:V,content:k(fi,{})},{id:`history`,label:`History`,icon:_e,content:k(cr,{})},{id:`alarm`,label:`Alarm`,icon:R,content:k(Cr,{})}]})})}export{mi as NotificationsPage,mi as default};