@camstack/addon-admin-ui 1.2.374 → 1.2.376

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 (88) hide show
  1. package/dist/assets/{AddonAssetIcon-B3Nf3xlx.js → AddonAssetIcon-Cud5lR3B.js} +1 -1
  2. package/dist/assets/AddonIntegrationBody-BJoK1WtG.js +1 -0
  3. package/dist/assets/Addons-0I-H6wRy.js +4 -0
  4. package/dist/assets/{AdminTabs-BcE-Q0tO.js → AdminTabs-DW1QntZA.js} +1 -1
  5. package/dist/assets/AiProfiles-C7wn83G9.js +3 -0
  6. package/dist/assets/{BrokerForm-nF-ssRGh.js → BrokerForm-DcikWKOe.js} +1 -1
  7. package/dist/assets/{Build-CuTxMnpV.js → Build-BuOzMfAD.js} +4 -4
  8. package/dist/assets/{Calendars-B3HYs0JU.js → Calendars-BNl-qJy5.js} +1 -1
  9. package/dist/assets/Cluster-BxwWtO0x.js +1 -0
  10. package/dist/assets/ClusterStepModel-COyT2Do_.js +1 -0
  11. package/dist/assets/{CompositionEditor-BS_jFILf.js → CompositionEditor-BPUfy0TZ.js} +1 -1
  12. package/dist/assets/{CompositionEditorPage-d2NmF7hL.js → CompositionEditorPage-DxvwB3Qy.js} +1 -1
  13. package/dist/assets/Data-DL7sR8sH.js +1 -0
  14. package/dist/assets/DetectionIntelligence-BlLb-7CS.js +1 -0
  15. package/dist/assets/DeviceDetail-BMkuPSGu.js +2 -0
  16. package/dist/assets/{DeviceDoActionFields-C3lawEZ6.js → DeviceDoActionFields-PTEW3aqC.js} +1 -1
  17. package/dist/assets/{Devices-Bi_w3OGa.js → Devices-UQMmWlzH.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-CDnqLk2A.js → EmbedPlayerPage-CqIDyxIL.js} +1 -1
  19. package/dist/assets/Events-Bkn2VPhI.js +1 -0
  20. package/dist/assets/Identity-BsjuGmza.js +1 -0
  21. package/dist/assets/IntegrationDetail-Bagk_zPv.js +1 -0
  22. package/dist/assets/Integrations-DeSeAkOe.js +1 -0
  23. package/dist/assets/Integrations-DfhbAB6e.js +1 -0
  24. package/dist/assets/Locations-6d5dgF9l.js +3 -0
  25. package/dist/assets/{Logs-B_2PKsST.js → Logs-BQyecoHW.js} +1 -1
  26. package/dist/assets/MyAccess-SDzBPB3d.js +2 -0
  27. package/dist/assets/Network-DLpptopR.js +1 -0
  28. package/dist/assets/{NodeAddonsSettingsPanel-xFAQ20so.js → NodeAddonsSettingsPanel-9YJiVbGW.js} +1 -1
  29. package/dist/assets/Notifications-DnG1GBXi.js +1 -0
  30. package/dist/assets/{Plates-DcCJBtJq.js → Plates-C0I3ZvkE.js} +1 -1
  31. package/dist/assets/Recordings-Cvuw6tle.js +1 -0
  32. package/dist/assets/{ScanNetworkModal-DuIQym22.js → ScanNetworkModal-HuKKCk0w.js} +1 -1
  33. package/dist/assets/{Scenes-CgiGYYQy.js → Scenes-BYjFKWR7.js} +1 -1
  34. package/dist/assets/SessionsList-D_o5ldnu.js +2 -0
  35. package/dist/assets/{Showroom-CF1Qu7mr.js → Showroom-CQvaY_jP.js} +1 -1
  36. package/dist/assets/{System-DvOg-3a-.js → System-DcPLWIa8.js} +1 -1
  37. package/dist/assets/{Terminal-742YDR-F.js → Terminal-BWRiENjg.js} +5 -5
  38. package/dist/assets/{Viewer-0fo1xtXq.js → Viewer-Cft96zqh.js} +1 -1
  39. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-u191sqrt.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Dd-TqyZf.js} +1 -1
  40. package/dist/assets/{authed-media-BaRjbtMq.js → authed-media-BrQwnIKg.js} +1 -1
  41. package/dist/assets/{debounced-invalidate-BOR3Wuyx.js → debounced-invalidate-B1K_w6Jo.js} +1 -1
  42. package/dist/assets/{device-integration-icon-5T12cCTw.js → device-integration-icon-DjhcO5Mw.js} +1 -1
  43. package/dist/assets/device-picker-model-CH-I2K5P.js +1 -0
  44. package/dist/assets/{face-bbox-BEIyL1yX.js → face-bbox-blnk4r2t.js} +1 -1
  45. package/dist/assets/{hostInit-C3KwadjS.js → hostInit-B4sEmccI.js} +1 -1
  46. package/dist/assets/index-BFj2tWAZ.js +4 -0
  47. package/dist/assets/index-Cs7_OxI3.css +2 -0
  48. package/dist/assets/location-owned-usage-Bi8xehnJ.js +1 -0
  49. package/dist/assets/{mf-entry-bootstrap-0-801b692c.js → mf-entry-bootstrap-0-2aaecc24.js} +2 -2
  50. package/dist/assets/mount-CH-I2K5P.js +1 -0
  51. package/dist/assets/notification-schedule-field-Ir3FHTsJ.js +1 -0
  52. package/dist/assets/remoteEntry-BVsqlEoo.js +1 -0
  53. package/dist/assets/{src-BTX2jfA7.js → src-D6dd9GMR.js} +16 -16
  54. package/dist/assets/{use-scenes-feed-DqzF-2_b.js → use-scenes-feed-nkW4bIU9.js} +1 -1
  55. package/dist/assets/{use-stationary-objects-BPLoE6ig.js → use-stationary-objects-DCqSZqWi.js} +1 -1
  56. package/dist/assets/useEventInvalidation-CH-I2K5P.js +1 -0
  57. package/dist/assets/{useNodeUrlSelection-s67zn-kU.js → useNodeUrlSelection-B0_QlYa-.js} +1 -1
  58. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Ds3l678P.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-gh0BZGsc.js} +2 -2
  59. package/dist/index.html +6 -6
  60. package/dist/server/addon.js +1 -1
  61. package/package.json +1 -1
  62. package/dist/assets/AddonIntegrationBody-BhLL7FoP.js +0 -1
  63. package/dist/assets/Addons-BX4RGdki.js +0 -4
  64. package/dist/assets/AiProfiles-Bu0zedHk.js +0 -3
  65. package/dist/assets/Cluster-CjOkqkYw.js +0 -1
  66. package/dist/assets/ClusterStepModel-B9pwzZ_M.js +0 -1
  67. package/dist/assets/Data-BjabNrW5.js +0 -1
  68. package/dist/assets/DetectionIntelligence-Drsxk61A.js +0 -1
  69. package/dist/assets/DeviceDetail-UKHvJh8G.js +0 -2
  70. package/dist/assets/Events-BoFeLCPi.js +0 -1
  71. package/dist/assets/Identity-riQA9K3r.js +0 -1
  72. package/dist/assets/IntegrationDetail-DYz00LhA.js +0 -1
  73. package/dist/assets/Integrations-Dj59hlDo.js +0 -1
  74. package/dist/assets/Integrations-x5pgUuxU.js +0 -1
  75. package/dist/assets/Locations-BveQrqYZ.js +0 -3
  76. package/dist/assets/MyAccess-C_eIFq1z.js +0 -2
  77. package/dist/assets/Network-CpuyFLhq.js +0 -1
  78. package/dist/assets/Notifications-DbeLe6-5.js +0 -1
  79. package/dist/assets/Recordings-1_ShsTqb.js +0 -1
  80. package/dist/assets/SessionsList-B-6hhNIP.js +0 -2
  81. package/dist/assets/device-picker-model-D8gNhpYS.js +0 -1
  82. package/dist/assets/index-BWu66tVw.js +0 -4
  83. package/dist/assets/index-MfQ6ok9_.css +0 -2
  84. package/dist/assets/location-owned-usage-B6a7vInb.js +0 -1
  85. package/dist/assets/mount-D8gNhpYS.js +0 -1
  86. package/dist/assets/notification-schedule-field-CyG86j1n.js +0 -1
  87. package/dist/assets/remoteEntry-CUnRKStz.js +0 -1
  88. package/dist/assets/useEventInvalidation-D8gNhpYS.js +0 -1
@@ -1 +0,0 @@
1
- import{I as e,Q as t,S as n,W as r,b as i,o as a,q as o,x as s,z as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{Z as l,gt as u,ht as d,st as f,vt as p}from"./player-overlays-B7T46vDu.js";import{$r as m,Cn as h,Dn as g,En as _,Fc as v,Gr as y,In as b,Jc as x,Jr as S,Ju as C,Kd as w,Kr as T,Mc as E,Nc as D,Pc as O,Qr as k,Sn as A,Td as j,Tn as M,Ud as N,Xr as ee,Yr as P,Zd as F,Zr as I,_f as L,ai as R,bf as te,ei as z,gd as B,hd as V,id as H,ii as U,kr as W,md as G,nd as ne,ni as re,qd as ie,qn as K,qr as ae,ri as oe,td as se,ti as ce,xc as le,xn as q,yf as ue,yu as de,zd as J}from"./src-BTX2jfA7.js";import{t as fe}from"./archive-MsQRiIew.js";import{t as pe}from"./circle-slash-CGPkHspT.js";import{a as me,c as he,l as ge,n as _e,o as ve,s as ye,t as be,u as xe}from"./location-owned-usage-B6a7vInb.js";import{n as Se,t as Y}from"./format-size-DKWzYrUJ.js";import"./mount-D8gNhpYS.js";import{t as Ce}from"./AdminPage-BSFohA3i.js";import{n as we}from"./authed-media-BaRjbtMq.js";import{t as Te}from"./AdminTabs-BcE-Q0tO.js";var Ee=p(`calendar-clock`,[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`,key:`1osxxc`}],[`path`,{d:`M3 10h5`,key:`r794hk`}],[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]),De=p(`cloud-upload`,[[`path`,{d:`M12 13v8`,key:`1l5pq0`}],[`path`,{d:`M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242`,key:`1pljnt`}],[`path`,{d:`m8 17 4-4 4 4`,key:`1quai1`}]]);t();function Oe(){let e=a(),t=K(),{data:i,isLoading:c,isError:l}=v({}),u=O(),d=r(()=>u.data??[],[u.data]),{data:f}=le({},{refetchOnWindowFocus:!1}),p=r(()=>be(i??[],f?.locations),[i,f?.locations]),{data:m}=D({},{refetchOnWindowFocus:!1}),h=r(()=>me(m),[m]),[g,_]=o(null),[y,b]=o(null),S=E({onSuccess:()=>{e.invalidateQueries({queryKey:[[`storage`,`listLocations`]]})}}),C=x({onSuccess:()=>{e.invalidateQueries({queryKey:[[`storage`,`listLocations`]]})}}),w=async(e,n)=>{ge(n)&&!await t({title:`Disable "${e.displayName}"?`,message:`${he(n).consequence}\n\nNothing is deleted — set the location back to Read-only or Active to bring its footage back.`,confirmLabel:`Disable`,variant:`danger`})||C.mutate(ye(e,{mode:n}))},T=async e=>{if(await t({title:`Delete location "${e.displayName}"?`,message:`This removes the location record. Files on disk are not deleted; the underlying directory or remote path stays untouched.`,confirmLabel:`Delete`,variant:`danger`}))try{await S.mutateAsync({id:e.id})}catch(n){await t({title:`Delete anyway?`,message:`${n instanceof Error?n.message:String(n)}\n\nForcing the delete removes the record only. Anything still on that location becomes unreachable — index rows naming it stop resolving, and playback of those segments goes silently black rather than erroring.`,confirmLabel:`Force delete`,variant:`danger`})&&S.mutate({id:e.id,force:!0})}},k=r(()=>{let e=new Map;for(let t of i??[]){let n=e.get(t.type);n?n.push(t):e.set(t.type,[t])}return e},[i]),A=c||u.isLoading,j=l||u.isError;return n(Ce,{children:[A&&s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Loading locations…`}),j&&s(`div`,{className:`text-xs text-danger`,children:`Failed to load storage locations.`}),!A&&!j&&n(`div`,{className:`space-y-3`,children:[d.length===0&&s(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-4 text-center text-[11px] text-foreground-subtle italic`,children:`No storage locations declared by any installed addon.`}),d.map(e=>s(_e,{type:e.id,displayName:e.displayName,description:e.description,cardinality:e.cardinality,locations:k.get(e.id)??[],onAdd:e=>_(e),onEdit:e=>b(e),onDelete:e=>{T(e)},ownedBytesById:p,drainById:h,onSetMode:(e,t)=>{w(e,t)}},e.id))]}),g!==null&&s(xe,{initialType:g,onClose:()=>_(null),onCreated:()=>{e.invalidateQueries({queryKey:[[`storage`,`listLocations`]]}),_(null)}}),y!==null&&s(ve,{location:y,onClose:()=>b(null),onSaved:()=>{e.invalidateQueries({queryKey:[[`storage`,`listLocations`]]}),b(null)}})]})}t();var ke=[[`backup`,`listDestinations`]],Ae=[`backup`,`listArchives`];function je({destinationId:t,restoreSupported:i,onOpenRestoreWizard:c}){let l=a(),u=K(),{data:d,isLoading:p,isError:m}=I({destinationId:t}),h=d??[],g=T({onSuccess:()=>{l.invalidateQueries({queryKey:[[...Ae]]}),l.invalidateQueries({queryKey:ke})}}),_=e(async e=>{await u({title:`Delete this archive?`,message:`Permanently deletes "${e.label??e.id}" and frees ${Y(e.sizeBytes)}.`,confirmLabel:`Delete`,variant:`danger`})&&g.mutate({destinationId:t,backupId:e.id})},[u,t,g]),[v,y]=o(null),b=e(async e=>{y(e.id);try{let n=await we(Me(t,e.id)),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${e.label??e.id}.tar.gz${e.encryption===void 0?``:`.csbk`}`,document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(r)}finally{y(null)}},[t]),x=r(()=>[...h].toSorted((e,t)=>t.createdAt-e.createdAt),[h]);return p?s(`div`,{className:`text-xs text-foreground-subtle animate-pulse py-2`,children:`Loading archives…`}):m?s(`div`,{className:`text-xs text-danger py-2`,children:`Failed to read manifest for this destination`}):x.length===0?s(`div`,{className:`text-xs text-foreground-subtle italic py-2`,children:`No archives at this destination yet.`}):s(`div`,{className:`rounded border border-border bg-surface overflow-x-auto`,children:n(`table`,{className:`w-full text-xs min-w-[640px]`,children:[s(`thead`,{children:n(`tr`,{className:`text-foreground-subtle bg-background/30`,children:[s(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:`When`}),s(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:`Label`}),s(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:`Includes`}),s(`th`,{className:`text-right px-3 py-1.5 font-medium`,children:`Size`}),s(`th`,{className:`text-right px-3 py-1.5 font-medium w-52`,children:`Actions`})]})}),s(`tbody`,{children:x.map(e=>n(`tr`,{className:`border-t border-border hover:bg-primary/5`,children:[s(`td`,{className:`px-3 py-1.5 text-foreground tabular-nums`,children:Ne(e.createdAt)}),s(`td`,{className:`px-3 py-1.5 text-foreground`,children:n(`span`,{className:`inline-flex items-center gap-1`,children:[e.encryption!==void 0&&s(G,{className:`h-3 w-3 text-success`,"aria-label":`encrypted — restore needs backup key ${e.encryption.keyId}`}),e.label??s(`span`,{className:`text-foreground-subtle italic`,children:`—`})]})}),s(`td`,{className:`px-3 py-1.5 text-foreground-subtle`,children:e.locations.join(`, `)}),s(`td`,{className:`px-3 py-1.5 text-foreground text-right tabular-nums`,children:Y(e.sizeBytes)}),s(`td`,{className:`px-3 py-1.5`,children:n(`div`,{className:`flex items-center justify-end gap-1`,children:[n(`button`,{onClick:()=>{b(e)},disabled:v===e.id,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-foreground-subtle hover:text-foreground hover:bg-primary/10 disabled:opacity-50`,title:`Download archive`,children:[v===e.id?s(B,{className:`h-3 w-3 animate-spin`}):s(J,{className:`h-3 w-3`}),`Download`]}),i&&c&&n(`button`,{onClick:()=>c({destinationId:t,archiveId:e.id}),className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-primary hover:bg-primary/10`,title:`Restore from this archive`,children:[s(C,{className:`h-3 w-3`}),`Restore`]}),s(`button`,{onClick:()=>{_(e)},disabled:g.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Delete archive`,children:g.isPending?s(B,{className:`h-3 w-3 animate-spin`}):s(f,{className:`h-3 w-3`})})]})})]},e.id))})]})})}function Me(e,t){return l(`/api/backup/download/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}function Ne(e){return new Date(e).toLocaleString(void 0,{day:`2-digit`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`})}t();var Pe=[[`backup`,`listSchedules`]];function Fe({onEdit:e,onOpenRestoreWizard:t}){let{data:i,isLoading:a,isError:c}=z(),l=i??[],u=k().data??[],d=r(()=>{let e=new Map;for(let t of u)e.set(t.id,t);return e},[u]),[f,p]=o(null),m=e=>{p(t=>t===e?null:e)};return a?s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Loading backup entries…`}):c?s(`div`,{className:`text-xs text-danger`,children:`Failed to load backup entries`}):l.length===0?s(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-8 text-center`,children:s(`p`,{className:`text-xs text-foreground-subtle`,children:`No backup entries yet. Create one to schedule backups across one or more storage locations.`})}):s(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:n(`table`,{className:`w-full text-xs min-w-[820px]`,children:[s(`thead`,{children:n(`tr`,{className:`text-foreground-subtle border-b border-border bg-background/40`,children:[s(`th`,{className:`text-left px-3 py-2 font-medium w-6`}),s(`th`,{className:`text-left px-3 py-2 font-medium`,children:`Entry`}),s(`th`,{className:`text-left px-3 py-2 font-medium w-20`,children:`Enabled`}),s(`th`,{className:`text-left px-3 py-2 font-medium`,children:`Locations`}),s(`th`,{className:`text-left px-3 py-2 font-medium w-24`,children:`Retention`}),s(`th`,{className:`text-left px-3 py-2 font-medium w-48`,children:`Schedule`}),s(`th`,{className:`text-right px-3 py-2 font-medium w-52`,children:`Actions`})]})}),s(`tbody`,{children:l.map(n=>s(Ie,{row:n,destById:d,isOpen:f===n.id,onToggle:()=>m(n.id),onEdit:()=>e(n),...t?{onOpenRestoreWizard:t}:{}},n.id))})]})})}function Ie({row:t,destById:l,isOpen:p,onToggle:m,onEdit:h,onOpenRestoreWizard:g}){let _=a(),v=K(),y=R({onSuccess:()=>{_.invalidateQueries({queryKey:Pe})}}),b=ae({onSuccess:()=>{_.invalidateQueries({queryKey:Pe})}}),x=U({onMutate:()=>{_.invalidateQueries({queryKey:[[`backup`,`listRuns`]]})},onSuccess:()=>{_.invalidateQueries({queryKey:[[`backup`,`listArchives`]]}),_.invalidateQueries({queryKey:[[`backup`,`listDestinations`]]}),_.invalidateQueries({queryKey:[[`backup`,`listRuns`]]})}}),[S,C]=o(String(t.retentionCount));c(()=>{C(String(t.retentionCount))},[t.retentionCount]);let w=r(()=>({id:t.id,label:t.label,cron:t.cron,locationIds:[...t.locationIds],retentionCount:t.retentionCount,...t.dataSources?{dataSources:[...t.dataSources]}:{}}),[t]),T=e(e=>{y.mutate({...w,enabled:e})},[y,w]),E=e(()=>{let e=Number.parseInt(S,10);if(Number.isNaN(e)||e<1){C(String(t.retentionCount));return}e!==t.retentionCount&&y.mutate({...w,enabled:t.enabled,retentionCount:e})},[y,w,S,t.retentionCount,t.enabled]),D=e(()=>{t.locationIds.length!==0&&x.mutate({destinations:[...t.locationIds],...t.dataSources&&t.dataSources.length>0?{locations:[...t.dataSources]}:{},label:t.label,retentionCount:t.retentionCount})},[x,t]),O=e(async()=>{await v({title:`Delete backup entry?`,message:`"${t.label||t.id}" will stop running. Existing archives are kept.`,confirmLabel:`Delete`,variant:`warning`})&&b.mutate({id:t.id})},[v,b,t.id,t.label]),k=t.cron.trim().length>0,A=y.isPending||b.isPending;return n(i,{children:[n(`tr`,{className:`border-t border-border first:border-t-0 hover:bg-primary/5`,children:[s(`td`,{className:`px-2 py-2`,children:s(`button`,{onClick:m,className:`inline-flex items-center justify-center rounded p-1 text-foreground-subtle hover:bg-primary/10 hover:text-foreground`,title:p?`Hide archives`:`Show archives`,children:s(p?u:d,{className:`h-3.5 w-3.5`})})}),s(`td`,{className:`px-3 py-2`,children:n(`button`,{onClick:h,className:`text-left hover:underline focus:outline-none`,children:[s(`div`,{className:`text-foreground font-medium`,children:t.label||`(unnamed)`}),t.lastRunAt!==void 0&&n(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`last run `,new Date(t.lastRunAt).toLocaleString()]})]})}),s(`td`,{className:`px-3 py-2`,children:s(`label`,{className:`inline-flex items-center cursor-pointer`,children:s(`input`,{type:`checkbox`,className:`accent-primary`,checked:t.enabled,disabled:A,onChange:e=>T(e.target.checked)})})}),s(`td`,{className:`px-3 py-2`,children:n(`div`,{className:`flex flex-wrap gap-1`,children:[t.locationIds.length===0&&s(`span`,{className:`text-[11px] text-danger italic`,children:`No locations`}),t.locationIds.map(e=>s(`span`,{className:`inline-flex items-center rounded border border-border bg-background px-1.5 py-0.5 text-[10px] text-foreground`,title:e,children:l.get(e)?.displayName??e},e))]})}),s(`td`,{className:`px-3 py-2`,children:s(`input`,{type:`number`,min:1,max:1e3,value:S,disabled:A,onChange:e=>C(e.target.value),onBlur:E,onKeyDown:e=>{e.key===`Enter`&&e.target.blur(),e.key===`Escape`&&C(String(t.retentionCount))},className:`w-16 rounded border border-border bg-background px-2 py-1 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`})}),s(`td`,{className:`px-3 py-2`,children:n(`button`,{onClick:h,className:`group flex flex-col items-start gap-0.5 text-left`,title:`Edit schedule`,children:[n(`span`,{className:`inline-flex items-center gap-1`,children:[s(Ee,{className:`h-3 w-3 text-foreground-subtle group-hover:text-foreground`}),s(`span`,{className:`font-mono text-[11px] text-foreground`,children:k?t.cron:`Manual`})]}),k&&t.nextRunAt!==void 0&&n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`next `,new Date(t.nextRunAt).toLocaleString()]})]})}),s(`td`,{className:`px-3 py-2`,children:n(`div`,{className:`flex items-center justify-end gap-1.5`,children:[n(`button`,{onClick:D,disabled:x.isPending||t.locationIds.length===0,className:`inline-flex items-center gap-1 rounded bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,title:`Run this entry now`,children:[x.isPending?s(B,{className:`h-3 w-3 animate-spin`}):s(ne,{className:`h-3 w-3`}),`Run now`]}),s(`button`,{onClick:h,className:`inline-flex items-center justify-center rounded border border-border p-1 text-foreground-subtle hover:text-foreground hover:bg-primary/5`,title:`Edit entry`,children:s(H,{className:`h-3 w-3`})}),s(`button`,{onClick:()=>{O()},disabled:A,className:`inline-flex items-center justify-center rounded border border-border p-1 text-foreground-subtle hover:text-danger hover:border-danger/40 disabled:opacity-50`,title:`Delete entry`,children:s(f,{className:`h-3 w-3`})})]})})]}),p&&s(`tr`,{className:`border-t border-border bg-background/30`,children:n(`td`,{colSpan:7,className:`px-4 py-3 space-y-4`,children:[t.locationIds.length===0&&s(`p`,{className:`text-xs text-foreground-subtle italic`,children:`This entry has no locations selected.`}),t.locationIds.map(e=>n(`div`,{className:`space-y-1.5`,children:[s(`div`,{className:`text-[11px] font-medium text-foreground-subtle`,children:l.get(e)?.displayName??e}),s(je,{destinationId:e,restoreSupported:l.get(e)?.restoreSupported??!0,...g?{onOpenRestoreWizard:g}:{}})]},e))]})})]})}t();function X(e){return e===null?`—`:new Date(e).toLocaleString()}function Le(e){let t=new Blob([`${e.secretKey}\n`],{type:`text/plain`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=`camstack-backup-key-${e.keyId}.txt`,r.click(),URL.revokeObjectURL(n)}function Re({revealed:e,onDone:t}){let[r,i]=o(!1),[a,c]=o(!1);return s(q,{open:!0,onOpenChange:e=>!e&&r&&t(),children:n(h,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`border-danger/40`,"aria-labelledby":`backup-key-title`,children:[s(_,{children:n(g,{id:`backup-key-title`,children:[`Your backup key (`,e.keyId,`)`]})}),n(A,{className:`space-y-3`,children:[n(`p`,{className:`flex items-start gap-2 rounded-md border border-danger/40 bg-danger/10 p-2 text-xs text-foreground`,children:[s(de,{className:`mt-0.5 h-4 w-4 shrink-0 text-danger`}),s(`span`,{children:`This key is shown only once. CamStack does not keep it — not the hub, not its database, not its backups. Without it, an encrypted backup cannot be restored by anyone, including you. Store it in a password manager or print it, away from this server.`})]}),s(`div`,{className:`break-all rounded-md border border-border bg-background p-2 font-mono text-xs text-foreground select-all`,children:e.secretKey}),n(`div`,{className:`flex flex-wrap gap-2`,children:[n(b,{size:`sm`,variant:`outline`,onClick:()=>{navigator.clipboard?.writeText(e.secretKey).then(()=>c(!0))},children:[s(N,{className:`mr-1 h-3.5 w-3.5`}),a?`Copied`:`Copy`]}),n(b,{size:`sm`,variant:`outline`,onClick:()=>Le(e),children:[s(J,{className:`mr-1 h-3.5 w-3.5`}),`Download as file`]})]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[s(`input`,{type:`checkbox`,checked:r,onChange:e=>i(e.target.checked),className:`accent-primary`}),`I have stored this key somewhere safe, off this server.`]})]}),s(M,{children:s(b,{size:`sm`,disabled:!r,onClick:t,children:`I have stored it`})})]})})}function ze(){let e=P(),t=oe(),r=S(),a=K(),[c,l]=o(null),[u,d]=o(null),f=e.data?.enabled??!1,p=e.data?.active??null,m=(e.data?.keys??[]).filter(e=>e.retiredAt!==null),h=async()=>{if(await a({title:f?`Replace the backup key`:`Encrypt backups`,message:f?`A new key is generated and shown once; new backups are encrypted to it. Older backups keep needing the key they were made with — keep that one too.`:`A backup key is generated and shown once. Every new backup is encrypted to it, and restoring one will ask for it. Existing backups stay as they are.`,confirmLabel:f?`Generate a new key`:`Generate the key`,variant:`warning`})){d(null);try{let e=await t.mutateAsync({});l({keyId:e.keyId,secretKey:e.secretKey})}catch(e){d(e instanceof Error?e.message:String(e))}}},g=async()=>{if(await a({title:`Turn backup encryption off`,message:`New backups will be written unencrypted. Existing encrypted backups still need their key to be restored.`,confirmLabel:`Turn off`,variant:`danger`})){d(null);try{await r.mutateAsync({}),e.refetch()}catch(e){d(e instanceof Error?e.message:String(e))}}};return n(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-4`,children:[n(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[n(`div`,{className:`flex items-center gap-2`,children:[f?s(G,{className:`h-4 w-4 text-success`}):s(V,{className:`h-4 w-4 text-foreground-subtle`}),s(`h2`,{className:`text-sm font-semibold text-foreground`,children:`Encryption`}),s(`span`,{className:`text-xs text-foreground-subtle`,children:f&&p!==null?`On — key ${p.keyId}, since ${X(p.createdAt)}`:`Off — backups are not encrypted`})]}),s(`div`,{className:`flex gap-2`,children:f?n(i,{children:[s(b,{size:`sm`,variant:`outline`,disabled:t.isPending,onClick:()=>void h(),children:`Replace key`}),s(b,{size:`sm`,variant:`outline`,disabled:r.isPending,onClick:()=>void g(),children:`Turn off`})]}):s(b,{size:`sm`,disabled:t.isPending,onClick:()=>void h(),children:`Enable encryption`})})]}),s(`p`,{className:`text-xs text-foreground-subtle`,children:`Archives are encrypted on this server before they reach any destination. The server keeps only a public key, so it can encrypt scheduled backups but cannot decrypt them — only your backup key can. Covers the database snapshot, config.yaml, addon data (HomeKit pairing, Matter fabric, Tailscale state) and TLS.`}),m.length>0&&n(`div`,{className:`text-xs`,children:[s(`p`,{className:`text-foreground-subtle`,children:`Older keys (backups made with them still need them):`}),s(`ul`,{className:`font-mono text-foreground`,children:m.map(e=>n(`li`,{children:[e.keyId,` · `,X(e.createdAt),` → `,X(e.retiredAt)]},e.keyId))})]}),u!==null&&s(`p`,{className:`text-xs text-danger`,children:u}),c!==null&&s(Re,{revealed:c,onDone:()=>{l(null),e.refetch()}})]})}t();var Be=[{id:`manual`,label:`Manual only`,cron:``},{id:`hourly`,label:`Every hour`,cron:`0 * * * *`,description:`On the hour`},{id:`every-3h`,label:`Every 3 hours`,cron:`0 */3 * * *`,description:`00:00, 03:00, 06:00, 09:00 …`},{id:`every-6h`,label:`Every 6 hours`,cron:`0 */6 * * *`,description:`00:00, 06:00, 12:00, 18:00`},{id:`daily-3am`,label:`Daily at 03:00`,cron:`0 3 * * *`,description:`Every night at 3 AM`},{id:`weekly-sun`,label:`Weekly Sunday 03:00`,cron:`0 3 * * 0`,description:`Sunday morning at 3 AM`}];function Ve(e){let t=e.trim();for(let e of Be)if(e.cron===t)return e.id;return`custom`}function He({value:e,onChange:t,previewCount:r=5,disabled:i=!1}){let a=Ve(e),[l,u]=o(a===`custom`);c(()=>{a!==`custom`&&u(!1)},[a]);let d=Ge(e,250),f=ce({cron:d,count:r},{enabled:d.trim().length>0}),p=f.data??null,m=e=>{u(!1),t(e.cron)},h=l||a===`custom`;return n(`div`,{className:`space-y-3`,children:[n(`div`,{className:`space-y-1`,children:[s(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:`Schedule preset`}),n(`div`,{className:`flex flex-wrap gap-1.5`,children:[Be.map(e=>s(`button`,{type:`button`,onClick:()=>m(e),disabled:i,className:`rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 `+(!l&&a===e.id?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground`),title:e.description??e.label,children:e.label},e.id)),s(`button`,{type:`button`,onClick:()=>{u(!0),e.trim().length===0&&t(`0 3 * * *`)},disabled:i,className:`rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 `+(h?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground`),children:`Custom…`})]})]}),h&&n(`div`,{className:`space-y-1`,children:[s(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:`Cron expression (5-field POSIX)`}),s(`input`,{type:`text`,value:e,onChange:e=>t(e.target.value),disabled:i,placeholder:`0 3 * * *`,spellCheck:!1,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`}),n(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`Format: `,s(`span`,{className:`font-mono`,children:`minute hour day-of-month month day-of-week`}),` · all times server-local`]})]}),s(Ue,{cron:d,preview:p,loading:f.isFetching})]})}function Ue({cron:e,preview:t,loading:r}){return r&&t===null?n(`div`,{className:`flex items-center gap-2 rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle`,children:[s(B,{className:`h-3 w-3 animate-spin`}),`Validating…`]}):t===null?null:t.ok?t.nextRuns.length===0?s(`div`,{className:`rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle`,children:`No future runs match this expression.`}):n(`div`,{className:`space-y-1`,children:[s(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:`Next runs`}),s(`ul`,{className:`rounded border border-border bg-background/40 divide-y divide-border`,children:t.nextRuns.map((e,t)=>n(`li`,{className:`flex items-center justify-between px-3 py-1.5 text-[11px]`,children:[s(`span`,{className:`text-foreground tabular-nums`,children:new Date(e).toLocaleString()}),s(`span`,{className:`text-foreground-subtle text-[10px] tabular-nums`,children:We(e)})]},`${e}-${t}`))})]}):s(`div`,{className:`rounded border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:t.error??`Invalid cron expression`})}function We(e){let t=e-Date.now();if(t<=0)return`now`;let n=Math.floor(t/1e3);if(n<60)return`in ${n}s`;let r=Math.floor(n/60);if(r<60)return`in ${r}m`;let i=Math.floor(r/60);return i<24?`in ${i}h`:`in ${Math.floor(i/24)}d`}function Ge(e,t){let[n,i]=o(e),a=r(()=>e,[e]);return c(()=>{let e=setTimeout(()=>i(a),t);return()=>clearTimeout(e)},[a,t]),n}t();var Ke=[[`backup`,`listSchedules`]];function qe({entry:e,onClose:t,onSaved:i}){let c=a(),l=k(),u=l.data??[],[d,f]=o(e?.label??``),[p,m]=o(e?.cron??`0 3 * * *`),[v,y]=o(e?.enabled??!0),[x,S]=o(String(e?.retentionCount??7)),[C,w]=o(new Set(e?.locationIds??[])),T=R({onSuccess:()=>{c.invalidateQueries({queryKey:Ke}),i()}}),E=e=>{w(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},D=Number.parseInt(x,10),O=r(()=>d.trim().length>0&&C.size>0&&!Number.isNaN(D)&&D>=1&&D<=1e3,[d,C,D]),j=()=>{O&&T.mutate({...e?{id:e.id}:{},label:d.trim(),cron:p.trim(),enabled:v,locationIds:Array.from(C),retentionCount:D})},N=T.error instanceof Error?T.error.message:null;return s(q,{open:!0,onOpenChange:e=>!e&&t(),children:n(h,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(_,{children:s(g,{children:e?`Edit backup entry`:`New backup entry`})}),n(A,{className:`space-y-4`,children:[n(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Name`}),s(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),placeholder:`Nightly offsite`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),n(`div`,{className:`space-y-1.5`,children:[n(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:[`Locations (`,C.size,` selected)`]}),l.isLoading&&n(`div`,{className:`flex items-center gap-2 px-1 py-2 text-xs text-foreground-subtle`,children:[s(B,{className:`h-3.5 w-3.5 animate-spin`}),`Loading locations…`]}),!l.isLoading&&u.length===0&&s(`div`,{className:`rounded border border-border bg-background px-3 py-2 text-xs text-foreground-subtle italic`,children:"No `backups` storage locations configured. Add one in Settings → Storage first."}),u.length>0&&s(`div`,{className:`rounded border border-border bg-background divide-y divide-border max-h-52 overflow-y-auto`,children:u.map(e=>n(`label`,{className:`flex items-center justify-between px-3 py-2 text-xs hover:bg-primary/5 cursor-pointer`,children:[n(`div`,{className:`flex items-center gap-2`,children:[s(`input`,{type:`checkbox`,checked:C.has(e.id),onChange:()=>E(e.id),className:`accent-primary`}),s(`span`,{className:`text-foreground`,children:e.displayName})]}),n(`div`,{className:`flex items-center gap-1.5`,children:[s(`span`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle bg-surface border border-border rounded px-1.5 py-0.5`,children:e.kind}),s(`span`,{className:`text-[10px] text-foreground-subtle font-mono`,children:e.id})]})]},e.id))})]}),n(`div`,{className:`grid grid-cols-2 gap-3`,children:[n(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Retention (archives kept)`}),s(`input`,{type:`number`,min:1,max:1e3,value:x,onChange:e=>S(e.target.value),className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`})]}),n(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Enabled`}),n(`label`,{className:`inline-flex items-center gap-2 py-1.5 cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:v,onChange:e=>y(e.target.checked),className:`accent-primary`}),s(`span`,{className:`text-xs text-foreground-subtle`,children:`Run on schedule`})]})]})]}),n(`div`,{className:`space-y-1.5 border-t border-border pt-3`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Schedule`}),s(He,{value:p,onChange:m,disabled:T.isPending})]}),N&&s(`div`,{className:`rounded border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:N})]}),n(M,{children:[s(b,{variant:`outline`,size:`sm`,onClick:t,children:`Cancel`}),n(b,{size:`sm`,onClick:j,disabled:!O||T.isPending,children:[T.isPending&&s(B,{className:`h-3.5 w-3.5 animate-spin`}),e?`Save`:`Create entry`]})]})]})})}t();var Je=2e3,Ye=5e3;function Z(e){return e.state===`queued`||e.state===`running`}function Xe(e){if(e.state===`queued`)return{title:`Cancel queued backup run?`,message:`This run has not started. Cancelling removes it from the queue — nothing has been written, nothing is deleted.`,confirmLabel:`Cancel run`,variant:`warning`};let t=e.completedDestinationIds.length;return{title:`Stop this backup run?`,message:`The half-written staging archive is deleted and the destination currently uploading discards its partial copy. ${t>0?`${t===1?`The 1 destination`:`The ${t} destinations`} that already completed KEEP${t===1?`S`:``} the archive.`:`No destination has completed yet, so nothing will be kept.`}`,confirmLabel:`Stop run`,variant:`danger`}}function Ze(){let t=K(),[n,r]=o(null),i=m(void 0,{refetchInterval:e=>(e.state.data??[]).some(Z)?Je:Ye}),a=y({onSettled:()=>{r(null),i.refetch()}}),c=e(async e=>{await t(Xe(e))&&(r(e.id),a.mutate({runId:e.id}))},[t,a]);return s(Qe,{queryState:i.isError?`error`:i.data===void 0?`pending`:`ready`,runs:i.data??[],cancelingId:n,onCancelRequest:e=>{c(e)},now:Date.now()})}function Qe({queryState:e,runs:t,cancelingId:r,onCancelRequest:i,now:a}){let o=e===`ready`&&t.some(Z),c=t.filter(e=>e.state===`running`),l=t.filter(e=>e.state===`queued`),u=t.filter(e=>!Z(e)),d=[...c,...l,...u];return n(`section`,{className:`rounded-lg border border-border bg-surface`,children:[n(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border`,children:[s(`h2`,{className:`text-xs font-semibold text-foreground`,children:`Runs`}),o&&n(`span`,{className:`inline-flex items-center gap-1 text-[10px] font-medium text-primary`,title:`A backup run is in progress`,children:[s(`span`,{className:`h-1.5 w-1.5 rounded-full bg-primary animate-pulse`}),`live`]}),s(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:`One run executes at a time — queued runs wait in line.`})]}),e===`pending`&&s(`div`,{className:`px-3 py-2.5 text-xs text-foreground-subtle animate-pulse`,children:`Checking for backup runs…`}),e===`error`&&s(`div`,{className:`px-3 py-2.5 text-xs text-danger`,children:`Could not read backup runs — the orchestrator did not answer.`}),e===`ready`&&t.length===0&&s(`div`,{className:`px-3 py-2.5 text-xs text-foreground-subtle italic`,children:`No backup runs yet. Runs appear here the moment one starts — manual or scheduled.`}),e===`ready`&&t.length>0&&s(`div`,{className:`overflow-x-auto`,children:n(`table`,{className:`w-full text-xs min-w-[720px]`,children:[s(`thead`,{children:n(`tr`,{className:`text-foreground-subtle bg-background/30`,children:[s(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:`Run`}),s(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:`State`}),s(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:`Progress`}),s(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:`Destinations`}),s(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:`Timing`}),s(`th`,{className:`text-right px-3 py-1.5 font-medium w-28`,children:`Actions`})]})}),s(`tbody`,{children:d.map(e=>s($e,{run:e,canceling:r===e.id,onCancelRequest:i,now:a},e.id))})]})})]})}function $e({run:e,canceling:t,onCancelRequest:r,now:i}){let a=Z(e);return n(`tr`,{className:`border-t border-border hover:bg-primary/5 align-top`,children:[n(`td`,{className:`px-3 py-2`,children:[s(`div`,{className:`text-foreground`,children:e.label??s(`span`,{className:`text-foreground-subtle italic`,children:`manual`})}),s(`div`,{className:`text-[10px] text-foreground-subtle font-mono`,title:e.id,children:e.id.slice(0,8)})]}),n(`td`,{className:`px-3 py-2`,children:[s(et,{run:e}),e.state===`failed`&&e.error!==void 0&&s(`div`,{className:`mt-1 text-[10px] text-danger max-w-56 truncate`,title:e.error,children:e.error})]}),s(`td`,{className:`px-3 py-2`,children:s(tt,{run:e})}),s(`td`,{className:`px-3 py-2`,children:s(nt,{run:e})}),s(`td`,{className:`px-3 py-2 text-foreground-subtle tabular-nums`,children:s(rt,{run:e,now:i})}),s(`td`,{className:`px-3 py-2`,children:s(`div`,{className:`flex justify-end`,children:a&&n(`button`,{onClick:()=>r(e),disabled:t,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,title:e.state===`queued`?`Remove this run from the queue before it starts`:`Stop this run — the half-written archive is discarded`,children:[t?s(B,{className:`h-3 w-3 animate-spin`}):s(L,{className:`h-3 w-3`}),e.state===`queued`?`Cancel`:`Stop`]})})})]})}function et({run:e}){switch(e.state){case`queued`:return n(`span`,{className:`inline-flex items-center gap-1 rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:[s(w,{className:`h-3 w-3`}),`Queued`]});case`running`:return n(`span`,{className:`inline-flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,children:[s(B,{className:`h-3 w-3 animate-spin`}),e.phase===`uploading`?`Uploading`:`Building archive`]});case`succeeded`:return n(`span`,{className:`inline-flex items-center gap-1 rounded bg-success/10 px-1.5 py-0.5 text-[10px] font-medium text-success`,children:[s(F,{className:`h-3 w-3`}),`Succeeded`]});case`failed`:return n(`span`,{className:`inline-flex items-center gap-1 rounded bg-danger/10 px-1.5 py-0.5 text-[10px] font-medium text-danger`,children:[s(ie,{className:`h-3 w-3`}),`Failed`]});case`cancelled`:return n(`span`,{className:`inline-flex items-center gap-1 rounded bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300`,title:`Stopped before completing every destination — not a success`,children:[s(pe,{className:`h-3 w-3`}),`Stopped`]})}}function tt({run:e}){if(e.state===`queued`)return s(`span`,{className:`text-foreground-subtle`,children:e.queuePosition===void 0?s(`span`,{className:`italic`,children:`waiting its turn`}):n(`span`,{className:`inline-flex items-center gap-1`,children:[s(`span`,{className:e.queuePosition===1?`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`:`rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium`,children:it(e.queuePosition)}),`in line`]})});if(e.state===`running`&&e.phase===`building`)return n(`span`,{className:`inline-flex items-center gap-1.5 text-foreground`,children:[s(Se,{className:`h-3 w-3 text-primary`}),s(`span`,{className:`tabular-nums font-medium animate-pulse`,children:Y(e.stagedBytes)}),s(`span`,{className:`text-foreground-subtle`,children:`staged so far`})]});if(e.state===`running`){let t=e.archiveSizeBytes;return n(`span`,{className:`inline-flex items-center gap-1.5 text-foreground`,children:[s(De,{className:`h-3 w-3 text-primary`}),n(`span`,{className:`tabular-nums font-medium`,children:[Y(e.uploadedBytes),t===void 0?``:` / ${Y(t)}`]}),s(`span`,{className:`text-foreground-subtle`,children:`to current destination`})]})}let t=e.archiveSizeBytes??(e.stagedBytes>0?e.stagedBytes:void 0);return t===void 0?s(`span`,{className:`text-foreground-subtle italic`,children:`—`}):n(`span`,{className:`tabular-nums text-foreground`,children:[Y(t),` archive`]})}function nt({run:e}){let t=e.destinationIds.length,r=e.completedDestinationIds.length,i=e.failedDestinationIds.length;return t===0?s(`span`,{className:`text-foreground-subtle italic`,children:`not resolved yet`}):n(`div`,{className:`flex flex-col gap-0.5`,children:[n(`span`,{className:`text-foreground-subtle`,title:e.destinationIds.join(`, `),children:[t,` target`,t===1?``:`s`]}),n(`span`,{className:`inline-flex items-center gap-2 text-[10px]`,children:[r>0&&n(`span`,{className:`text-success`,title:`Kept their archive: ${e.completedDestinationIds.join(`, `)}`,children:[`✓ `,r,` completed`]}),i>0&&n(`span`,{className:`text-danger`,title:`Failed: ${e.failedDestinationIds.join(`, `)}`,children:[`✗ `,i,` failed`]})]})]})}function rt({run:e,now:t}){return e.state===`queued`?n(`span`,{children:[`queued `,Q(t-e.requestedAt),` ago`]}):e.startedAt===void 0?s(`span`,{children:`—`}):e.finishedAt===void 0?n(`span`,{children:[`running for `,Q(t-e.startedAt)]}):n(`div`,{className:`flex flex-col gap-0.5`,children:[s(`span`,{children:at(e.finishedAt)}),n(`span`,{className:`text-[10px]`,children:[`took `,Q(e.finishedAt-e.startedAt)]})]})}function it(e){if(e<=1)return`next`;let t=e%100;if(t>=11&&t<=13)return`${e}th`;switch(e%10){case 1:return`${e}st`;case 2:return`${e}nd`;case 3:return`${e}rd`;default:return`${e}th`}}function Q(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${String(t%60).padStart(2,`0`)}s`:`${Math.floor(n/60)}h ${String(n%60).padStart(2,`0`)}m`}function at(e){return new Date(e).toLocaleString(void 0,{day:`2-digit`,month:`short`,hour:`2-digit`,minute:`2-digit`})}t();var ot=[[`backup`,`list`]];function st({initialDestinationId:e,initialArchiveId:t,onClose:i,onScheduled:l}){let u=a(),[d,f]=o(e&&t?2:1),[p,m]=o(e),[v,y]=o(t),[x,S]=o(new Set),[w,T]=o(``),{data:E}=k(),D=E??[],{data:O,isLoading:j}=I({destinationId:p??``},{enabled:!!p}),N=O??[];c(()=>{if(p!==void 0)return;let e=D.filter(e=>e.restoreSupported);e.length===1&&m(e[0].id)},[p,D]);let{data:P}=ee({destinationId:p??``,backupId:v??``},{enabled:!!p&&!!v}),F=r(()=>P?.locations??[],[P]);c(()=>{F.length!==0&&S(e=>e.size===0?new Set(F):e)},[F]);let L=re({onSuccess:()=>{u.invalidateQueries({queryKey:ot}),l(),i()}}),R=e=>{S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},z=N.find(e=>e.id===v),V=z?.encryption!==void 0,H=!!p&&!!v,U=x.size>0,W=H&&U&&!L.isPending&&(!V||w.trim().length>0),G=()=>{!p||!v||L.mutate({destinationId:p,backupId:v,locations:[...x],...V?{backupSecretKey:w.trim()}:{}})};return s(q,{open:!0,onOpenChange:e=>!e&&i(),children:n(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(_,{children:[s(g,{children:`Restore Backup`}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[`Step `,d,` of 3 —`,` `,d===1?`pick source`:d===2?`pick locations`:`confirm`]})]}),n(A,{children:[d===1&&s(ct,{destinations:D,destinationId:p,onPickDestination:e=>{m(e),y(void 0),S(new Set)},archives:N,archivesLoading:j,archiveId:v,onPickArchive:y}),d===2&&s(lt,{locations:F,picked:x,onToggle:R}),d===3&&s(ut,{destinationName:D.find(e=>e.id===p)?.displayName??p??``,archive:z,picked:[...x]}),d===3&&z?.encryption!==void 0&&s(dt,{keyId:z.encryption.keyId,value:w,onChange:T}),d===3&&L.error&&s(`p`,{role:`alert`,className:`px-4 pb-2 text-xs text-danger`,children:L.error.message})]}),n(M,{className:`justify-between`,children:[s(`div`,{children:d>1&&n(b,{variant:`outline`,size:`sm`,onClick:()=>f(e=>e===3?2:1),children:[s(te,{className:`h-3 w-3`}),`Back`]})}),n(`div`,{className:`flex items-center gap-2`,children:[s(b,{variant:`outline`,size:`sm`,onClick:i,children:`Cancel`}),d<3?n(b,{size:`sm`,disabled:d===1&&!H||d===2&&!U,onClick:()=>f(e=>e===1?2:3),children:[`Next`,s(ue,{className:`h-3 w-3`})]}):n(b,{size:`sm`,onClick:G,disabled:!W,children:[L.isPending?s(B,{className:`h-3.5 w-3.5 animate-spin`}):s(C,{className:`h-3.5 w-3.5`}),`Schedule Restore`]})]})]})]})})}function ct({destinations:e,destinationId:t,onPickDestination:r,archives:i,archivesLoading:a,archiveId:o,onPickArchive:c}){let l=e.filter(e=>e.restoreSupported);return n(`div`,{className:`p-4 space-y-3`,children:[n(`div`,{className:`space-y-1.5`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Destination`}),n(`select`,{value:t??``,onChange:e=>r(e.target.value),className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,children:[s(`option`,{value:``,disabled:!0,children:`Select destination…`}),l.map(e=>n(`option`,{value:e.id,children:[e.displayName,` (`,e.kind,`)`]},e.id))]})]}),n(`div`,{className:`space-y-1.5`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Archive`}),!t&&s(`div`,{className:`text-xs text-foreground-subtle italic`,children:`Pick a destination first.`}),t&&a&&s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Reading archives…`}),t&&!a&&i.length===0&&s(`div`,{className:`text-xs text-foreground-subtle italic`,children:`No archives available at this destination.`}),t&&i.length>0&&s(`div`,{className:`rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto`,children:i.map(e=>{let t=o===e.id;return n(`label`,{className:`flex items-center justify-between px-3 py-2 text-xs cursor-pointer ${t?`bg-primary/10`:`hover:bg-primary/5`}`,children:[n(`div`,{className:`flex items-center gap-2`,children:[s(`input`,{type:`radio`,name:`archive`,checked:t,onChange:()=>c(e.id),className:`accent-primary`}),n(`div`,{children:[n(`div`,{className:`flex items-center gap-1 font-medium text-foreground`,children:[e.encryption!==void 0&&s(G,{className:`h-3 w-3 text-success`,"aria-label":`encrypted (key ${e.encryption.keyId})`}),e.label??e.id]}),s(`div`,{className:`text-[10px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})]})]}),s(`span`,{className:`text-[10px] text-foreground-subtle tabular-nums`,children:Y(e.sizeBytes)})]},e.id)})})]})]})}function lt({locations:e,picked:t,onToggle:r}){return e.length===0?s(`div`,{className:`p-4`,children:s(`div`,{className:`text-xs text-foreground-subtle`,children:`Loading archive manifest… If this persists, the archive may predate manifests — restoring will apply everything in the tarball.`})}):n(`div`,{className:`p-4 space-y-3`,children:[s(`div`,{className:`rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-700 dark:text-amber-300`,children:`Selected entries will overwrite live data on the next server restart. Unchecked entries stay current.`}),n(`div`,{className:`space-y-1.5`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Apply`}),s(`div`,{className:`rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto`,children:e.map(e=>n(`label`,{className:`flex items-center gap-2 px-3 py-2 text-xs hover:bg-primary/5 cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:t.has(e),onChange:()=>r(e),className:`accent-primary`}),s(`span`,{className:`font-mono text-foreground`,children:e}),s(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:pt(e)})]},e))})]})]})}function ut({destinationName:e,archive:t,picked:r}){return n(`div`,{className:`p-4 space-y-3 text-xs`,children:[s(`div`,{className:`rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-amber-700 dark:text-amber-300`,children:`Restore is applied at next server boot. Active connections will drop when you restart.`}),n(`dl`,{className:`space-y-1.5`,children:[s($,{term:`Destination`,value:e}),s($,{term:`Archive`,value:t?.label??t?.id??`—`}),t&&s($,{term:`Created`,value:`${new Date(t.createdAt).toLocaleString()} · ${Y(t.sizeBytes)}`}),s($,{term:`Locations`,value:r.length>0?r.join(`, `):`— (full archive)`})]})]})}function dt({keyId:e,value:t,onChange:r}){return n(`div`,{className:`space-y-1.5 px-4 pb-3`,children:[s(`label`,{htmlFor:`restore-backup-key`,className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:`Backup key`}),s(`input`,{id:`restore-backup-key`,type:`password`,autoComplete:`off`,spellCheck:!1,value:t,onChange:e=>r(e.target.value),placeholder:`camstack-backup-secret-v1:…`,className:`w-full rounded border border-border bg-background px-2 py-1.5 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`}),n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`This archive is encrypted to backup key `,s(`span`,{className:`font-mono`,children:e}),`. Paste the secret key shown when that key was created. It is used to decrypt the archive on this server and is not stored.`]})]})}function $({term:e,value:t}){return n(`div`,{className:`flex justify-between gap-3`,children:[s(`dt`,{className:`text-foreground-subtle`,children:e}),s(`dd`,{className:`text-foreground font-mono text-right truncate`,children:t})]})}var ft={db:`Database`,addons:`Addon configs`,"addons-data":`Addon data`,tls:`TLS certificates`,cache:`Cache`,data:`Top-level data`};function pt(e){return ft[e]??``}t();function mt(){let e=K(),t=W(),[r,i]=o(null),[a,c]=o(!1),[l,u]=o(!1),[d,f]=o(void 0),p=async()=>{await e({title:`Restart server now?`,message:`Active connections will drop and the apply-backup hook will run before boot.`,confirmLabel:`Restart`,variant:`warning`})&&t.mutate({confirm:!0})};return n(Ce,{children:[n(`div`,{className:`flex items-center justify-end gap-2 flex-wrap`,children:[n(`button`,{onClick:()=>c(!0),className:`inline-flex items-center gap-1.5 rounded-lg bg-surface border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5 hover:border-primary/30`,children:[s(C,{className:`h-3.5 w-3.5`}),`Restore…`]}),n(`button`,{onClick:()=>f(null),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90`,children:[s(se,{className:`h-3.5 w-3.5`}),`New entry`]})]}),l&&s(`div`,{className:`rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-xs text-amber-700 dark:text-amber-300`,children:n(`div`,{className:`flex items-center justify-between gap-3`,children:[n(`div`,{className:`flex items-center gap-2`,children:[s(C,{className:`h-3.5 w-3.5`}),s(`span`,{children:`Restore scheduled. Restart the server to apply.`})]}),n(`button`,{onClick:()=>{p()},disabled:t.isPending,className:`inline-flex items-center gap-1.5 rounded bg-amber-500/20 px-2 py-1 font-medium text-amber-800 dark:text-amber-200 hover:bg-amber-500/30 disabled:opacity-50`,children:[t.isPending?s(B,{className:`h-3.5 w-3.5 animate-spin`}):s(C,{className:`h-3.5 w-3.5`}),`Restart Now`]})]})}),s(ze,{}),s(Ze,{}),s(Fe,{onEdit:e=>f(e),onOpenRestoreWizard:e=>i(e)}),d!==void 0&&s(qe,{entry:d,onClose:()=>f(void 0),onSaved:()=>f(void 0)}),(r||a)&&s(st,{...r?{initialDestinationId:r.destinationId,initialArchiveId:r.archiveId}:{},onClose:()=>{i(null),c(!1)},onScheduled:()=>u(!0)})]})}function ht(){return s(`div`,{className:`flex flex-col p-4`,children:s(Te,{tabs:[{id:`storage`,label:`Storage`,icon:j,content:s(Oe,{})},{id:`backup`,label:`Backup`,icon:fe,content:s(mt,{})}]})})}export{ht as DataPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,b as a,o,q as s,x as c,z as l}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as u,ct as d,ft as f,gt as p,ht as m,st as h,vt as g}from"./player-overlays-B7T46vDu.js";import{Ba as _,Cn as v,Dn as y,En as b,Fn as x,Ga as S,Ha as C,Hl as w,In as T,Ja as E,Ju as D,Ka as O,Ou as k,Tn as A,Ua as j,Va as M,Wa as ee,Wu as N,Xa as P,Ya as F,Yu as I,Za as L,_u as R,gd as z,hu as B,id as V,iu as H,la as te,nf as U,qa as ne,qn as W,td as G,tr as K,tu as re,wn as q,xn as J,yu as Y,za as ie}from"./src-BTX2jfA7.js";import{t as ae}from"./crop-DEIlVeIH.js";import{a as oe,c as se,f as ce,i as le,l as ue,m as de,n as X,o as fe,p as Z,r as pe,s as me,t as he,u as ge}from"./debounced-invalidate-BOR3Wuyx.js";import{t as _e}from"./user-round-9bUOIzu8.js";import{n as ve,r as ye,t as be}from"./face-bbox-BEIyL1yX.js";import{vi as xe}from"./client-BBcQuaON.js";import{tt as Se}from"./index-BWu66tVw.js";import{t as Ce}from"./AdminPage-BSFohA3i.js";import{n as we,r as Te}from"./authed-media-BaRjbtMq.js";var Ee=g(`image-plus`,[[`path`,{d:`M16 5h6`,key:`1vod17`}],[`path`,{d:`M19 2v6`,key:`4bpg5p`}],[`path`,{d:`M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5`,key:`1ue2ih`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}]]);n();var De=`pipeline-analytics`,Oe=`photo.analyze`,ke=`photo.enroll`,Ae=`photo.discard`,je=18*1024*1024;function Me(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function $(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Ne(e,t){let n=e[t];return typeof n==`boolean`?n:null}function Pe(e){if(!Me(e))return null;let t=$(e,`x`),n=$(e,`y`),r=$(e,`width`),i=$(e,`height`);return t===null||n===null||r===null||i===null?null:{x:t,y:n,width:r,height:i}}function Fe(e){if(!Me(e))return null;let t=$(e,`detectionShortSidePx`),n=$(e,`score`);if(t===null||n===null)return null;let r=$(e,`magnitude`);return{detectionShortSidePx:t,score:n,...r===null?{}:{magnitude:r}}}function Ie(e){if(!Me(e))return null;let t=$(e,`faceIndex`),n=$(e,`score`),r=Ne(e,`enrollable`),i=Pe(e.bbox),a=Fe(e.quality);if(t===null||n===null||r===null||i===null||a===null)return null;let o=Q(e,`refusedReason`),s=Q(e,`alignedCropBase64`),c=Q(e,`modelId`);return{faceIndex:t,bbox:i,score:n,enrollable:r,quality:a,...o===null?{}:{refusedReason:o},...s===null?{}:{alignedCropBase64:s},...c===null?{}:{modelId:c}}}function Le(e){if(!Me(e))return null;let t=Q(e,`sessionId`),n=Q(e,`ranOnNodeId`),r=e.faces;if(t===null||n===null||!Array.isArray(r))return null;let i=[];for(let e of r){let t=Ie(e);t!==null&&i.push(t)}return{sessionId:t,ranOnNodeId:n,faces:i}}function Re(e){if(!Me(e))return null;let t=Q(e,`sampleId`),n=Q(e,`identityId`),r=Q(e,`modelId`);return t===null||n===null||r===null?null:{sampleId:t,identityId:n,modelId:r}}function ze(e,t,n){let r={...e};return n===null||n===``?delete r[t]:r[t]=n,r}function Be(e,t){return e.filter(e=>e.enrollable&&t[e.faceIndex]!==void 0).length}function Ve(e,t,n){let r=[];for(let i of t){if(!i.enrollable)continue;let t=n[i.faceIndex];t!==void 0&&r.push({sessionId:e,faceIndex:i.faceIndex,identityId:t})}return r}function He(e){switch(e){case`no-embedding`:return`Too small or too indistinct for the recognizer to measure — try a photo where this face is larger.`;case`no-model-id`:return`The recognizer did not report which model it used, so this face cannot be enrolled safely.`;case`no-aligned-crop`:return`The recognizer produced no aligned crop for this face, so there is nothing to store.`;case`magnitude`:return`Refused by the quality gate: the features look degenerate, and a sample like this matches everybody.`;default:return`This face is not usable as a sample.`}}function Ue(e,t){let n=[],r=[];for(let i of e)i.size>t.maxBytes?n.push(i.name):r.push(i);return{accepted:r.slice(0,t.maxCount),oversize:n,overflow:r.slice(t.maxCount).map(e=>e.name)}}async function We(e,t,n){let r=Array(e.length),i=e.map((e,t)=>({item:e,index:t})),a=0,o=async()=>{for(;;){let e=i[a];if(a+=1,e===void 0)return;r[e.index]=await n(e.item,e.index)}},s=Array.from({length:Math.max(1,Math.min(t,e.length))},()=>o());return await Promise.all(s),r}function Ge(e,t,n){return e.map(e=>e.photoIndex===t?{...e,...n}:e)}function Ke(e,t){return`${e}:${t}`}function qe(e,t,n,r){let i=ze(e[t]??{},n,r),a={...e};return Object.keys(i).length===0?delete a[t]:a[t]=i,a}function Je(e,t){let n=0;for(let r of e)r.analysis!==void 0&&(n+=Be(r.analysis.faces,t[r.photoIndex]??{}));return n}var Ye=`__new__`;function Xe(e,t,n){let r=[];for(let i of e){if(i.analysis===void 0)continue;let e=t[i.photoIndex]??{};for(let t of i.analysis.faces){if(!t.enrollable||e[t.faceIndex]!==`__new__`)continue;let a=(n[Ke(i.photoIndex,t.faceIndex)]??``).trim();if(a===``)return{kind:`error`,message:`${i.filename}: face ${t.faceIndex+1} is set to a new person but has no name.`};r.includes(a)||r.push(a)}}return{kind:`ok`,names:r}}function Ze(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=Number(i),o={};for(let[r,i]of Object.entries(a)){let a=Number(r);if(i!==`__new__`){o[a]=i;continue}let s=n[(t[Ke(e,a)]??``).trim()];s!==void 0&&(o[a]=s)}r[e]=o}return r}function Qe(e,t){let n=[];for(let r of e){if(r.analysis===void 0)continue;let e=Ve(r.analysis.sessionId,r.analysis.faces,t[r.photoIndex]??{});for(let t of e)n.push({photoIndex:r.photoIndex,request:t})}return n}function $e(e){return/expired/i.test(e)}function et(e){return e instanceof Error?e.message:String(e)}async function tt(e,t,n){let r=new Map(e.map(e=>[e.photoIndex,e])),i={},a=[],o=0,s=null,c=(e,t)=>`${r.get(e)?.filename??`photo ${e+1}`}, face ${t+1}`;for(let l of Qe(e,t)){let e=i[l.photoIndex],t=e===void 0?l.request:{...l.request,sessionId:e.sessionId};try{let e=await n.enroll(t);o+=1,s=e.modelId}catch(t){let u=et(t);if(!$e(u)||e!==void 0){a.push(`${c(l.photoIndex,l.request.faceIndex)}: ${u}`);continue}let d=r.get(l.photoIndex);if(d===void 0){a.push(`${c(l.photoIndex,l.request.faceIndex)}: ${u}`);continue}let f;try{f=await n.reanalyze(d)}catch(e){a.push(`${c(l.photoIndex,l.request.faceIndex)}: the analysis expired and re-analysing failed (${et(e)})`);continue}if(i[l.photoIndex]=f,f.faces.find(e=>e.faceIndex===l.request.faceIndex&&e.enrollable)===void 0){a.push(`${c(l.photoIndex,l.request.faceIndex)}: the analysis expired, and re-analysing no longer finds this face — assign it again from the fresh result`);continue}try{let e=await n.enroll({...l.request,sessionId:f.sessionId});o+=1,s=e.modelId}catch(e){a.push(`${c(l.photoIndex,l.request.faceIndex)}: ${et(e)}`)}}}return{enrolled:o,stampedModelId:s,failures:a,refreshedAnalyses:i}}var nt=[[`faceGallery`]],rt=``;function it(e){return new Promise((t,n)=>{let r=new FileReader;r.addEventListener(`error`,()=>n(Error(`the file could not be read`)),{once:!0}),r.addEventListener(`load`,()=>{let e=r.result;if(typeof e!=`string`){n(Error(`the file could not be read`));return}let i=e.indexOf(`,`);t(i>=0?e.slice(i+1):e)},{once:!0}),r.readAsDataURL(e)})}function at(e){return e instanceof Error?e.message:String(e)}function ot({face:e,identities:t,value:n,onChange:o,disabled:s}){let l=i(()=>[{value:rt,label:`Ignore this face`},...t.map(e=>({value:e.id,label:e.name})),{value:Ye,label:`+ New person…`}],[t]);return r(`div`,{className:`rounded-md border border-border bg-surface p-2`,children:[c(`div`,{className:`mb-2 aspect-square w-full overflow-hidden rounded border border-border bg-surface-hover`,children:e.alignedCropBase64?c(`img`,{src:`data:image/jpeg;base64,${e.alignedCropBase64}`,alt:`Face ${e.faceIndex+1}`,className:`h-full w-full object-cover`}):c(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:c(_e,{className:`h-8 w-8`})})}),c(`div`,{className:`min-h-[4.75rem]`,children:e.enrollable?r(a,{children:[c(x,{options:l,value:n,disabled:s,onChange:e=>o(e.target.value),"aria-label":`Assign face ${e.faceIndex+1}`}),r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:[Math.round(e.quality.detectionShortSidePx),` px`,e.modelId?` · ${e.modelId}`:``]})]}):r(`div`,{className:`space-y-1`,children:[c(K,{variant:`warning`,className:`text-[10px]`,children:`Not usable`}),c(`p`,{className:`text-[10px] leading-tight text-foreground-subtle`,children:He(e.refusedReason)})]})})]})}function st({photo:e,identities:t,draft:n,newNames:i,disabled:a,onAssign:o,onNameChange:s,onRetry:l}){let u=e.analysis?.faces??[],d=n[e.photoIndex]??{};return r(`div`,{className:`space-y-2`,children:[r(`div`,{className:`flex items-center gap-2 border-b border-border pb-1`,children:[c(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.filename}),e.status===`analyzing`||e.status===`queued`?r(`span`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,children:[c(z,{className:`h-3 w-3 animate-spin`}),` analysing…`]}):null,e.status===`analyzed`&&e.analysis!==void 0&&r(`span`,{className:`text-xs text-foreground-subtle`,children:[u.length,` face`,u.length===1?``:`s`,` · analysed on`,` `,e.analysis.ranOnNodeId]}),e.status===`failed`&&r(T,{variant:`secondary`,size:`sm`,disabled:a,onClick:l,children:[c(D,{className:`h-3 w-3`}),` Retry`]})]}),e.status===`failed`&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:[c(Y,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),r(`span`,{children:[`This photo could not be analysed: `,e.error??`unknown error`,`. The other photos are unaffected.`]})]}),e.status===`analyzed`&&u.length===0&&c(`p`,{className:`text-xs text-foreground-subtle`,children:`No faces were found in this photo. A face has to be reasonably large and facing the camera for the detector to measure it.`}),u.length>0&&c(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(7rem,7rem))] justify-start gap-3`,children:u.map(e=>c(ot,{face:e,identities:t,value:d[e.faceIndex]??rt,disabled:a,onChange:t=>o(e.faceIndex,t)},e.faceIndex))}),u.filter(e=>d[e.faceIndex]===Ye).map(t=>r(`div`,{className:`flex items-center gap-2`,children:[r(`span`,{className:`w-28 shrink-0 truncate text-xs text-foreground-subtle`,children:[`Face `,t.faceIndex+1]}),c(`input`,{className:`h-7 flex-1 rounded-md border border-border bg-surface px-2.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`New person name… (type the same name under another face to reuse it)`,value:i[Ke(e.photoIndex,t.faceIndex)]??``,onChange:e=>s(t.faceIndex,e.target.value)})]},t.faceIndex))]})}function ct({open:n,onOpenChange:a}){let l=u(),d=o(),f=t(null),{data:p}=ee(),m=_(),[h,g]=s([]),[x,S]=s(!1),[C,w]=s(null),[E,D]=s({}),[O,k]=s({}),[j,M]=s(null),N=i(()=>(p??[]).map(e=>({id:e.id,name:e.name})),[p]),P=h.some(e=>e.status===`queued`||e.status===`analyzing`),F=P||x,I=e(e=>{for(let t of e){let e=t.analysis?.sessionId;e!==void 0&&l.trpcClient.addons.custom.mutate({addonId:De,action:Ae,input:{sessionId:e}}).catch(()=>void 0)}},[l]),L=e(()=>{g([]),D({}),k({}),w(null),M(null),f.current&&(f.current.value=``)},[]),R=e(()=>{I(h),L(),a(!1)},[I,a,h,L]),B=e(async e=>{let t=Le(await l.trpcClient.addons.custom.mutate({addonId:De,action:Oe,input:{photoBase64:e.photoBase64,filename:e.filename}}));if(t===null)throw Error(`the server replied with something this page could not read`);return t},[l]),V=e(async e=>{g(t=>Ge(t,e.photoIndex,{status:`analyzing`,error:void 0}));try{let t=await B(e);g(n=>Ge(n,e.photoIndex,{status:`analyzed`,analysis:t}))}catch(t){g(n=>Ge(n,e.photoIndex,{status:`failed`,error:at(t)}))}},[B]),H=e(async e=>{if(e.length===0)return;I(h),L();let t=Ue(e,{maxCount:12,maxBytes:je}),n=[];t.oversize.length>0&&n.push(`Over the ${Math.round(je/(1024*1024))} MB limit and skipped: ${t.oversize.join(`, `)}.`),t.overflow.length>0&&n.push(`A batch holds at most 12 photos — not analysed: ${t.overflow.join(`, `)}. Enrol them in a second round.`),n.length>0&&w(n.join(` `));let r;try{r=await Promise.all(t.accepted.map(async(e,t)=>({photoIndex:t,filename:e.name,photoBase64:await it(e),status:`queued`})))}catch(e){w(at(e));return}g(r),await We(r,2,e=>V(e))},[I,h,L,V]),te=Je(h,E),U=e(async()=>{S(!0),w(null),M(null);try{let e=Xe(h,E,O);if(e.kind===`error`){w(e.message);return}let t={};for(let n of e.names)t[n]=(await m.mutateAsync({name:n})).id;let n=await tt(h,Ze(E,O,t),{enroll:async e=>{let t=Re(await l.trpcClient.addons.custom.mutate({addonId:De,action:ke,input:e}));if(t===null)throw Error(`unreadable reply`);return t},reanalyze:e=>B(e)});Object.keys(n.refreshedAnalyses).length>0&&g(e=>e.map(e=>{let t=n.refreshedAnalyses[e.photoIndex];return t===void 0?e:{...e,status:`analyzed`,analysis:t}})),d.invalidateQueries({queryKey:nt}),n.failures.length>0&&w(n.failures.join(` · `)),M(n.enrolled===0?`Nothing was enrolled.`:`Enrolled ${n.enrolled} sample${n.enrolled===1?``:`s`}${n.stampedModelId===null?``:` with ${n.stampedModelId}`}.`)}catch(e){w(at(e))}finally{S(!1)}},[B,m,E,O,h,d,l]),ne=h.filter(e=>e.status===`analyzed`).length;return c(J,{open:n,onOpenChange:e=>e?a(!0):R(),children:r(v,{className:`max-w-3xl`,children:[r(b,{children:[c(y,{children:`Enrol from photos`}),c(q,{children:`Every photo is analysed with the same face detector the cameras use, and all the faces found are reviewed below in one pass, grouped by photo. Assign each face to a person, or leave it ignored.`})]}),r(`div`,{className:`rounded-md border border-border bg-surface-hover px-3 py-2 text-xs text-foreground-subtle`,children:[`For reliable recognition use `,c(`strong`,{children:`at least 3 photos per person`}),`, taken at different times, with different poses and lighting — you can select them all at once. Several frames from the same moment count as one — they do not add information.`]}),r(`div`,{className:`flex items-center gap-2`,children:[c(`input`,{ref:f,type:`file`,accept:`image/jpeg,image/png,image/webp`,multiple:!0,className:`hidden`,onChange:e=>void H(Array.from(e.target.files??[]))}),r(T,{variant:`secondary`,size:`sm`,disabled:F,onClick:()=>f.current?.click(),children:[P?c(z,{className:`h-3.5 w-3.5 animate-spin`}):c(Ee,{className:`h-3.5 w-3.5`}),`Choose photos`]}),h.length>0&&r(`span`,{className:`text-xs text-foreground-subtle`,children:[ne,`/`,h.length,` photo`,h.length===1?``:`s`,` analysed`]})]}),c(`div`,{className:`min-h-11`,"aria-live":`polite`,children:C===null?j===null?null:c(`div`,{className:`rounded-md border border-success/40 bg-success/10 px-3 py-2 text-xs text-success`,children:j}):r(`div`,{className:`flex items-start gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:[c(Y,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),c(`span`,{children:C})]})}),h.length>0&&c(`div`,{className:`max-h-[50vh] space-y-4 overflow-y-auto pr-1`,children:h.map(e=>c(st,{photo:e,identities:N,draft:E,newNames:O,disabled:F,onAssign:(t,n)=>D(r=>qe(r,e.photoIndex,t,n===rt?null:n)),onNameChange:(t,n)=>k(r=>({...r,[Ke(e.photoIndex,t)]:n})),onRetry:()=>void V(e)},e.photoIndex))}),r(A,{children:[c(T,{variant:`secondary`,onClick:R,disabled:x,children:`Close`}),r(T,{variant:`primary`,onClick:()=>void U(),disabled:F||te===0,children:[x?c(z,{className:`h-3.5 w-3.5 animate-spin`}):null,`Enrol `,te,` face`,te===1?``:`s`]})]})]})})}n();var lt=[[`faceGallery`]];function ut({identityId:e}){let t=o(),{data:n,isLoading:i}=S({identityId:e}),a=ne();function s(n){a.mutate({identityId:e,sampleId:n.id},{onSettled:()=>{t.invalidateQueries({queryKey:lt})}})}return i?r(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,children:[c(z,{className:`h-3.5 w-3.5 animate-spin`}),`Loading samples…`]}):!n||n.length===0?c(`p`,{className:`py-2 text-xs text-foreground-subtle`,children:`No samples yet.`}):c(`div`,{className:`mt-2 grid grid-cols-4 gap-2 sm:grid-cols-6 md:grid-cols-8`,children:n.map(e=>r(`div`,{className:`group relative aspect-square overflow-hidden rounded-md border border-border bg-surface`,children:[e.base64?c(`img`,{src:`data:image/jpeg;base64,${e.base64}`,alt:`Sample`,className:`h-full w-full object-cover`}):c(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:c(_e,{className:`h-6 w-6`})}),e.source===`photo`&&c(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 p-0.5 text-white`,title:`Enrolled from an uploaded photo`,children:c(Ee,{className:`h-3 w-3`})}),c(`button`,{type:`button`,onClick:()=>s(e),disabled:a.isPending,className:`absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 transition-opacity group-hover:opacity-100 disabled:cursor-not-allowed`,"aria-label":`Remove sample`,children:c(H,{className:`h-4 w-4 text-white`})})]},e.id))})}function dt({identity:e,expanded:t,onToggle:n}){let i=o(),[l,u]=s(``),[d,f]=s(!1),[g,_]=s(!1),x=E(),S=C();function D(){u(e.name),f(!0)}function O(){f(!1),u(``)}function k(){let t=l.trim();if(!t||t===e.name){O();return}x.mutate({id:e.id,name:t},{onSettled:()=>{i.invalidateQueries({queryKey:lt}),O()}})}function j(){S.mutate({id:e.id},{onSettled:()=>{i.invalidateQueries({queryKey:lt}),_(!1)}})}return r(`div`,{className:`rounded-md border border-border bg-surface`,children:[r(`div`,{className:`flex items-center gap-2 px-3 py-2`,children:[c(`div`,{className:`h-8 w-8 shrink-0 overflow-hidden rounded-full border border-border bg-surface-hover`,children:c(ve,{mediaId:e.coverMediaId,base64:e.coverBase64,alt:e.name,className:`h-full w-full object-cover`,placeholder:c(`div`,{className:`flex h-full w-full items-center justify-center`,children:c(_e,{className:`h-4 w-4 text-foreground-subtle`})})})}),c(`div`,{className:`flex flex-1 min-w-0 items-center gap-2`,children:d?r(a,{children:[c(w,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&k(),e.key===`Escape`&&O()},className:`h-6 text-xs`,autoFocus:!0}),c(`button`,{type:`button`,onClick:k,disabled:x.isPending,className:`text-success hover:text-success/80 disabled:opacity-50`,"aria-label":`Confirm rename`,children:c(U,{className:`h-3.5 w-3.5`})}),c(`button`,{type:`button`,onClick:O,className:`text-foreground-subtle hover:text-foreground`,"aria-label":`Cancel rename`,children:c(H,{className:`h-3.5 w-3.5`})})]}):c(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name})}),c(K,{variant:`default`,className:`text-[10px]`,children:e.sampleCount}),!d&&r(`div`,{className:`flex items-center gap-1`,children:[c(`button`,{type:`button`,onClick:D,className:`p-1 rounded hover:bg-surface-hover text-foreground-subtle hover:text-foreground`,"aria-label":`Rename`,children:c(V,{className:`h-3.5 w-3.5`})}),c(`button`,{type:`button`,onClick:()=>_(!0),className:`p-1 rounded hover:bg-danger/10 text-foreground-subtle hover:text-danger`,"aria-label":`Delete`,children:c(h,{className:`h-3.5 w-3.5`})})]}),c(`button`,{type:`button`,onClick:n,className:`p-1 rounded hover:bg-surface-hover text-foreground-subtle`,"aria-label":t?`Collapse`:`Expand`,children:c(t?p:m,{className:`h-3.5 w-3.5`})})]}),t&&c(`div`,{className:`border-t border-border px-3 pb-3 pt-2`,children:c(ut,{identityId:e.id})}),c(J,{open:g,onOpenChange:e=>!e&&_(!1),children:r(v,{children:[r(b,{children:[c(y,{children:`Delete person`}),r(q,{children:[`Delete `,c(`strong`,{children:e.name}),` and all their samples? This cannot be undone.`]})]}),r(A,{children:[c(T,{variant:`secondary`,onClick:()=>_(!1),children:`Cancel`}),r(T,{variant:`danger`,onClick:j,disabled:S.isPending,children:[S.isPending?c(z,{className:`h-3.5 w-3.5 animate-spin`}):null,`Delete`]})]})]})})]})}function ft(){let e=o(),[t,n]=s(``),i=_();function a(){let r=t.trim();r&&i.mutate({name:r},{onSettled:()=>{e.invalidateQueries({queryKey:lt}),n(``)}})}return r(`div`,{className:`flex items-center gap-2 pt-2`,children:[c(w,{placeholder:`New person name…`,value:t,onChange:e=>n(e.target.value),onKeyDown:e=>{e.key===`Enter`&&a()},className:`h-7 text-xs flex-1`}),r(T,{variant:`primary`,size:`sm`,onClick:a,disabled:i.isPending||!t.trim(),children:[i.isPending?c(z,{className:`h-3.5 w-3.5 animate-spin`}):c(G,{className:`h-3.5 w-3.5`}),`Add`]})]})}function pt(){let{data:e,isLoading:t}=ee(),[n,i]=s(null),[a,o]=s(!1);function l(e){i(t=>t===e?null:e)}return t?r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[c(z,{className:`h-4 w-4 animate-spin`}),`Loading people…`]}):r(`div`,{className:`space-y-2`,children:[(!e||e.length===0)&&c(`p`,{className:`py-2 text-xs text-foreground-subtle`,children:`No people enrolled yet. Add one below.`}),e?.map(e=>c(dt,{identity:e,expanded:n===e.id,onToggle:()=>l(e.id)},e.id)),c(ft,{}),c(`div`,{className:`pt-1`,children:r(T,{variant:`secondary`,size:`sm`,onClick:()=>o(!0),children:[c(Ee,{className:`h-3.5 w-3.5`}),`Enrol from a photo`]})}),c(ct,{open:a,onOpenChange:o})]})}function mt(e){let t=e.cropUrl!==void 0&&e.cropUrl.length>0,n=e.base64!==void 0&&e.base64.length>0;return!t&&!n}function ht(e){return e.filter(mt).map(e=>e.faceId)}function gt(e){let t=0;for(let n of e)mt(n)&&(t+=1);return t}function _t(e){return e==null?null:e.cropUrl!==void 0&&e.cropUrl.length>0?e.cropUrl:e.base64!==void 0&&e.base64.length>0?`data:image/jpeg;base64,${e.base64}`:null}n();var vt=[[`faceGallery`]];function yt({faceIds:e,identities:t,onDone:n}){let i=o(),a=ie(),l=_(),[u,d]=s(``),[f,p]=s(!1),[m,h]=s(null),g=e!==null&&e.length>0,x=e?.length??0;function S(){p(!1),d(``),h(null)}function C(){S(),n()}function E(t){!e||e.length===0||a.mutate({faceIds:[...e],identityId:t},{onSettled:()=>{i.invalidateQueries({queryKey:vt}),C()}})}function D(){!e||!u.trim()||l.mutate({name:u.trim()},{onSuccess:e=>{e?.id&&E(e.id)},onError:()=>{i.invalidateQueries({queryKey:vt}),C()}})}let O=a.isPending||l.isPending;return c(J,{open:g,onOpenChange:e=>!e&&C(),children:r(v,{children:[r(b,{children:[c(y,{children:x>1?`Assign ${String(x)} faces to person`:`Assign face to person`}),c(q,{children:`Select an existing person or create a new one.`})]}),c(`div`,{className:`space-y-1 max-h-56 overflow-y-auto`,children:t.map(e=>r(`button`,{type:`button`,onClick:()=>h(e.id),className:`w-full rounded-md px-3 py-2 text-left text-xs transition-colors ${m===e.id?`bg-primary/12 text-primary`:`hover:bg-surface-hover text-foreground`}`,children:[c(`span`,{className:`font-medium`,children:e.name}),r(`span`,{className:`ml-2 text-foreground-subtle`,children:[e.sampleCount,` samples`]})]},e.id))}),c(`div`,{className:`min-h-[2.75rem] border-t border-border pt-2`,children:f?c(`div`,{className:`flex items-center gap-2`,children:c(w,{placeholder:`New person name…`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&D()},autoFocus:!0,className:`flex-1`})}):c(`button`,{type:`button`,onClick:()=>{h(null),p(!0)},className:`w-full rounded-md border border-dashed border-border px-3 py-2 text-left text-xs text-foreground-subtle transition-colors hover:border-primary hover:text-primary`,children:`+ New person…`})}),r(A,{className:`min-h-[2.75rem]`,children:[c(T,{variant:`secondary`,onClick:C,disabled:O,children:`Cancel`}),f?r(T,{variant:`primary`,onClick:D,disabled:O||!u.trim(),children:[O&&c(z,{className:`h-3.5 w-3.5 animate-spin`}),`Create & assign`]}):r(T,{variant:`primary`,onClick:()=>m&&E(m),disabled:O||!m,children:[O&&c(z,{className:`h-3.5 w-3.5 animate-spin`}),`Assign`,x>1?` ${String(x)}`:``]})]})]})})}n();function bt(e){let[t,n]=s(null),[r,i]=s(null),[a,o]=s(!1);return l(()=>{if(n(null),i(null),o(!1),e===void 0)return;let t=!1,r=null;return(async()=>{try{let i=await we(Te(e));if(t)return;r=URL.createObjectURL(i),n(r)}catch{t||o(!0)}})(),()=>{t=!0,r&&URL.revokeObjectURL(r)}},[e]),l(()=>{if(!t)return;let e=new Image;return e.onload=()=>i({width:e.naturalWidth,height:e.naturalHeight}),e.onerror=()=>o(!0),e.src=t,()=>{e.onload=null,e.onerror=null}},[t]),{frameSrc:t,naturalWidth:r?.width??null,naturalHeight:r?.height??null,failed:a}}function xt(e){let t=e.filter(e=>e.url.length>0);return t.length===0?null:t.find(e=>/crop|face/i.test(e.kind))??t[0]}function St({label:e,value:t}){return r(`div`,{className:`flex items-baseline justify-between gap-3 py-1.5 border-b border-border/60 last:border-0`,children:[c(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:e}),c(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground`,children:t})]})}function Ct({box:e}){return c(`div`,{className:`pointer-events-none absolute rounded-[3px] border-2 border-primary shadow-[0_0_0_9999px_rgba(0,0,0,0.28)]`,style:{left:`${String(e.x*100)}%`,top:`${String(e.y*100)}%`,width:`${String(e.width*100)}%`,height:`${String(e.height*100)}%`},children:c(`span`,{className:`absolute -top-4 left-0 rounded bg-primary px-1 text-[9px] font-semibold uppercase tracking-wide text-white`,children:`Face`})})}function wt({face:e,cameraName:t,onClose:n,onAssign:a,onUnassign:o,onDelete:l,actionsPending:u}){let{data:d,isFetching:p}=j({faceId:e?.faceId??``},{enabled:e!==null}),[m,g]=s(`frame`),{frameSrc:_,naturalWidth:y,naturalHeight:b,failed:x}=bt(e?.keyFrameMediaId),S=i(()=>{let t=xt(d??[]);return t?t.url:_t(e)},[d,e]),C=i(()=>!e?.faceBbox||y===null||b===null?null:be(e.faceBbox,y,b),[e?.faceBbox,y,b]);if(e===null)return null;let w=e.keyFrameMediaId!==void 0&&!x,E=w&&m===`frame`,D=e.assigned?e.identityName??`Assigned`:e.recognizedIdentityId?`${e.identityName??`Recognized`} (suggested)`:`Unassigned`;return c(J,{open:!0,onOpenChange:e=>!e&&n(),children:r(v,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":`Face detail`,className:`flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 bottom-0 left-0 right-0 top-auto w-full max-w-full translate-x-0 translate-y-0 rounded-b-none md:bottom-auto md:left-1/2 md:right-auto md:top-1/2 md:w-[calc(100vw-2rem)] md:max-w-xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:max-h-[calc(100dvh-2rem)]`,children:[c(`header`,{className:`flex shrink-0 items-start gap-2 border-b border-border py-3 pl-4 pr-10`,children:r(`div`,{className:`min-w-0`,children:[c(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:`Face detail`}),c(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:t})]})}),r(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[w&&r(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5 text-xs`,children:[r(`button`,{type:`button`,onClick:()=>g(`frame`),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-1 transition-colors ${m===`frame`?`bg-primary/12 font-medium text-primary`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[c(N,{className:`h-3.5 w-3.5`}),` Full frame`]}),r(`button`,{type:`button`,onClick:()=>g(`crop`),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-1 transition-colors ${m===`crop`?`bg-primary/12 font-medium text-primary`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[c(ae,{className:`h-3.5 w-3.5`}),` Crop`]})]}),E&&_?c(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:c(X,{src:_,alt:`Full frame with detected face`,fit:`natural`,className:`w-full`,overlay:C?c(Ct,{box:C}):void 0})}):S?r(`div`,{className:`relative aspect-square w-full overflow-hidden rounded-lg border border-border`,children:[c(X,{src:S,alt:`Detected face`,className:`h-full w-full`}),p&&c(`div`,{className:`absolute right-2 top-2 rounded-full bg-black/50 p-1 text-white`,children:c(z,{className:`h-3.5 w-3.5 animate-spin`})})]}):r(`div`,{className:`flex aspect-square w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-warning/5 text-foreground-subtle`,children:[c(f,{className:`h-8 w-8 text-warning/70`}),c(`span`,{className:`text-[11px] font-medium uppercase tracking-wide text-warning/80`,children:`No image`}),c(`span`,{className:`px-6 text-center text-[10px] text-foreground-subtle`,children:`The crop media for this face could not be resolved (a pre-fix orphan). Safe to delete.`})]}),r(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[c(St,{label:`Camera`,value:t}),c(St,{label:`Captured`,value:Z(e.timestamp)}),c(St,{label:`Track`,value:e.trackId}),c(St,{label:`Identity`,value:D})]})]}),r(`footer`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]`,children:[e.assigned?r(T,{variant:`secondary`,onClick:()=>o(e.faceId),disabled:u,children:[c(ye,{className:`h-3.5 w-3.5`}),` Detach`]}):r(T,{variant:`primary`,onClick:()=>a(e.faceId),disabled:u,children:[c(B,{className:`h-3.5 w-3.5`}),` Assign`]}),r(T,{variant:`secondary`,onClick:()=>l(e.faceId),disabled:u,children:[c(h,{className:`h-3.5 w-3.5`}),` Delete`]})]})]})})}function Tt(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function Et(e,t){return e.faceIds.filter(e=>!t.has(e))}function Dt(e,t){return e.faceIds.filter(e=>t(e))}n();var Ot=[[`faceGallery`]],kt=20,At=.3,jt=.9,Mt=.05,Nt=.5,Pt=2,Ft=10,It=2;function Lt({cluster:e,face:t,active:n,onSelect:i}){let a=_t(t);return r(`button`,{type:`button`,onClick:i,className:`flex shrink-0 flex-col items-center gap-1.5 rounded-md border p-2 text-center transition-colors md:w-full md:flex-row md:gap-2.5 md:text-left ${n?`border-primary bg-primary/8`:`border-border bg-surface hover:bg-surface-hover`}`,children:[c(`div`,{className:`h-24 w-24 shrink-0 overflow-hidden rounded bg-surface-hover`,children:a===null?c(f,{className:`h-24 w-24 p-6 text-foreground-subtle`}):c(`img`,{src:a,alt:``,loading:`lazy`,decoding:`async`,className:`h-24 w-24 object-cover`})}),r(`span`,{className:`w-24 text-[11px] leading-tight text-foreground-subtle md:w-auto`,children:[e.size,` faces · `,Math.round(e.cohesion*100),`% alike`]})]})}function Rt({face:e,cameraName:t,nowMs:n,excluded:i,onToggleExclude:a,onDelete:o,deletePending:s}){let l=_t(e);return r(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden transition-opacity ${i?`border-border opacity-40 grayscale`:`border-border`}`,children:[r(`div`,{className:`aspect-square relative overflow-hidden bg-surface-hover`,children:[l===null?r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-warning/5 text-foreground-subtle`,children:[c(f,{className:`h-7 w-7 text-warning/70`}),c(`span`,{className:`text-[9px] font-medium uppercase tracking-wide text-warning/80`,children:`No crop`})]}):c(X,{src:l,alt:`Face from ${t}`,className:`h-full w-full`}),c(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a()},className:`absolute right-1 top-1 z-10 rounded-full bg-black/50 p-1.5 text-white hover:bg-black/70`,"aria-label":i?`Include face`:`Exclude face`,title:i?`Include`:`Exclude`,children:c(i?R:H,{className:`h-3.5 w-3.5`})})]}),r(`div`,{className:`min-w-0 px-2 pt-1.5 space-y-0.5`,children:[c(`p`,{className:`text-[10px] font-medium text-foreground truncate`,title:t,children:t}),c(`p`,{className:`text-[10px] text-foreground-subtle truncate`,children:ce(e.timestamp,n)})]}),c(`div`,{className:`mt-1 flex min-h-[2rem] items-center justify-end border-t border-border/60 px-1 py-0.5`,children:c(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o()},disabled:s,className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-danger/10 hover:text-danger disabled:opacity-40`,"aria-label":`Delete face`,title:`Delete face`,children:s?c(z,{className:`h-4 w-4 animate-spin`}):c(h,{className:`h-4 w-4`})})})]})}function zt({open:e,onClose:t,byId:n,cameraName:u,nowMs:d,identities:f,selectMany:p}){let m=o(),h=W(),g=M(),[_,y]=s(Nt),[b,x]=s(It),[S,C]=s(null),[w,E]=s({}),[D,O]=s(null),{data:A,isFetching:j,refetch:ee}=F({threshold:_,minClusterSize:b,limit:kt},{enabled:e}),N=A??[];l(()=>{E({})},[_,b]),l(()=>{if(N.length===0){C(null);return}N.some(e=>e.representativeFaceId===S)||C(N[0]?.representativeFaceId??null)},[N]);let P=i(()=>N.find(e=>e.representativeFaceId===S)??null,[N,S]),L=P?w[P.representativeFaceId]??new Set:new Set,R=i(()=>P?Dt(P,e=>n.has(e)):[],[P,n]),V=P?P.faceIds.length-R.length:0,H=P?Et({...P,faceIds:R},L):[];function te(e){if(!P)return;let t=P.representativeFaceId;E(n=>({...n,[t]:Tt(n[t]??new Set,e)}))}function U(){m.invalidateQueries({queryKey:Ot})}async function ne(e){await h({title:`Delete face`,message:`Permanently deletes this face crop. This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&g.mutate({faceId:e},{onSettled:U})}function G(){O(null),t()}function K(){H.length!==0&&(p(H),G())}return r(J,{open:e,onOpenChange:e=>!e&&G(),children:[r(v,{placement:`sheet-on-mobile`,width:`lg`,"aria-label":`Look-alike groups`,className:`flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 md:max-w-4xl`,children:[r(`header`,{className:`flex shrink-0 flex-col gap-2 border-b border-border py-3 pl-4 pr-10`,children:[r(`div`,{className:`flex items-center gap-1.5 text-sm font-semibold text-foreground`,children:[c(k,{className:`h-4 w-4 text-primary`}),` Look-alike groups`]}),r(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[r(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Threshold`,c(`input`,{type:`range`,min:At,max:jt,step:Mt,value:_,onChange:e=>y(Number(e.target.value)),className:`h-1.5 w-28 cursor-pointer accent-primary`}),c(`span`,{className:`w-8 shrink-0 text-right font-mono text-[11px] tabular-nums text-foreground`,children:_.toFixed(2)})]}),r(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Min size`,c(`input`,{type:`number`,min:Pt,max:Ft,step:1,value:b,onChange:e=>x(Math.min(Ft,Math.max(Pt,Number(e.target.value)||Pt))),className:`w-12 rounded border border-border bg-background px-1.5 py-0.5 text-xs text-foreground`})]}),r(T,{variant:`secondary`,onClick:()=>{E({}),ee()},disabled:j,children:[j?c(z,{className:`h-3.5 w-3.5 animate-spin`}):c(I,{className:`h-3.5 w-3.5`}),`Re-analyze`]})]})]}),c(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden px-4 py-3 md:flex-row`,children:j&&N.length===0?r(`div`,{className:`flex flex-1 items-center justify-center gap-2 py-8 text-xs text-foreground-subtle`,children:[c(z,{className:`h-4 w-4 animate-spin`}),` Finding similar faces…`]}):N.length===0?c(`div`,{className:`flex flex-1 items-center justify-center py-8 text-xs text-foreground-subtle`,children:`No look-alike groups at this threshold.`}):r(a,{children:[c(`div`,{className:`flex gap-2 overflow-x-auto pb-1 md:hidden`,children:N.map(e=>c(Lt,{cluster:e,face:n.get(e.representativeFaceId),active:e.representativeFaceId===S,onSelect:()=>C(e.representativeFaceId)},e.representativeFaceId))}),c(`div`,{className:`hidden shrink-0 flex-col gap-2 overflow-y-auto md:flex md:w-56`,children:N.map(e=>c(Lt,{cluster:e,face:n.get(e.representativeFaceId),active:e.representativeFaceId===S,onSelect:()=>C(e.representativeFaceId)},e.representativeFaceId))}),c(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:P&&r(a,{children:[V>0&&r(`p`,{className:`mb-2 text-[11px] text-foreground-subtle`,children:[V,` not loaded — excluded from actions`]}),c(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(13rem,13rem))] justify-start gap-2`,children:R.map(e=>{let t=n.get(e);return t?c(Rt,{face:t,cameraName:u(t.deviceId),nowMs:d,excluded:L.has(e),onToggleExclude:()=>te(e),onDelete:()=>void ne(e),deletePending:g.isPending&&g.variables?.faceId===e},e):null})})]})})]})}),r(`footer`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]`,children:[c(T,{variant:`secondary`,onClick:K,disabled:H.length===0,children:`Select in gallery`}),r(T,{variant:`primary`,onClick:()=>O(H),disabled:H.length===0,children:[c(B,{className:`h-3.5 w-3.5`}),` Adopt (`,H.length,`)`]})]})]}),c(yt,{faceIds:D,identities:f,onDone:()=>O(null)})]})}n();var Bt=[[`faceGallery`]],Vt=500,Ht=120;function Ut({face:e,cameraName:t,nowMs:n,selected:i,onToggleSelect:a,onAssign:s,onOpenDetail:l}){let u=o(),p=P(),m=M(),g=()=>{u.invalidateQueries({queryKey:Bt})},_=()=>l(e.faceId),v=_t(e);return r(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${i?`border-primary ring-1 ring-primary`:`border-border`}`,children:[r(`div`,{className:`aspect-square relative overflow-hidden bg-surface-hover`,children:[v===null?r(`button`,{type:`button`,onClick:_,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-warning/5 text-foreground-subtle`,title:`No crop image — the face's crop media is missing (a pre-fix orphan). Safe to delete.`,children:[c(f,{className:`h-7 w-7 text-warning/70`}),c(`span`,{className:`text-[9px] font-medium uppercase tracking-wide text-warning/80`,children:`No crop`})]}):c(`img`,{src:v,alt:`Face from ${t}`,onClick:_,loading:`lazy`,decoding:`async`,className:`h-full w-full cursor-zoom-in object-cover`}),c(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),a(e.faceId)},className:`absolute left-0 top-0 z-10 rounded-br-md bg-black/50 p-1.5 text-white hover:bg-black/70`,"aria-label":i?`Deselect`:`Select`,children:i?c(de,{className:`h-4 w-4 text-primary`}):c(d,{className:`h-4 w-4`})})]}),r(`div`,{className:`min-w-0 px-2 pt-1.5 space-y-0.5`,children:[c(`p`,{className:`text-[10px] font-medium text-foreground truncate`,title:t,children:t}),c(`p`,{className:`text-[10px] text-foreground-subtle truncate`,children:ce(e.timestamp,n)}),c(`p`,{className:`min-h-[0.875rem] truncate text-[10px] font-medium leading-tight ${e.identityName?`text-primary`:`invisible`}`,title:e.identityName,children:e.identityName??`\xA0`})]}),r(`div`,{className:`mt-1 flex min-h-[2rem] items-center gap-0.5 border-t border-border/60 px-1 py-0.5`,children:[e.assigned?c(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),p.mutate({faceId:e.faceId},{onSettled:g})},disabled:p.isPending,className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-warning/10 hover:text-warning disabled:opacity-40`,"aria-label":`Detach face`,title:`Detach`,children:p.isPending?c(z,{className:`h-4 w-4 animate-spin`}):c(ye,{className:`h-4 w-4`})}):c(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),s(e.faceId)},className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-primary/10 hover:text-primary`,"aria-label":`Assign face to person`,title:`Assign to person`,children:c(B,{className:`h-4 w-4`})}),c(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),m.mutate({faceId:e.faceId},{onSettled:g})},disabled:m.isPending,className:`ml-auto rounded p-1.5 text-foreground-subtle transition-colors hover:bg-danger/10 hover:text-danger disabled:opacity-40`,"aria-label":`Delete face`,title:`Delete face`,children:m.isPending?c(z,{className:`h-4 w-4 animate-spin`}):c(h,{className:`h-4 w-4`})})]})]})}var Wt=[{label:`All`,value:`all`},{label:`Unassigned`,value:`unassigned`},{label:`Recognized`,value:`recognized`}];function Gt(){let e=o(),[t,n]=s(`all`),[l,u]=s(me),[d,p]=s(new Set),[m,g]=s(new Set),[_,v]=s(null),[y,b]=s(!1),[x,S]=s(null),{data:C,isLoading:w}=O({limit:Vt,filter:t,includeCrops:!1},{refetchInterval:3e4}),{data:E=[]}=ee(),{data:D}=te({isCamera:!0,projection:`slim`}),A=ie(),j=P(),N=L(),F=M(),I=Date.now(),R=C??[],V=i(()=>{let e=new Map;for(let t of D??[])e.set(t.id,t.name);return e},[D]),U=e=>V.get(e)??`Camera #${String(e)}`,ne=i(()=>se(R).map(e=>({id:e,name:U(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[R,V]),W=i(()=>ue(ge(R,l),d),[R,l,d]),G=fe(W,Ht,i(()=>JSON.stringify([t,l.fromMs,l.toMs,[...d].sort((e,t)=>e-t)]),[t,l.fromMs,l.toMs,d])),K=i(()=>new Map(R.map(e=>[e.faceId,e])),[R]),re=i(()=>gt(W),[W]),q=x===null?null:K.get(x)??null,J=()=>{e.invalidateQueries({queryKey:Bt})},Y=()=>g(new Set);function ae(e){g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function ce(e){g(t=>{let n=new Set(t);for(let t of e)n.add(t);return n})}function de(){ce(ht(W))}let X=[...m],Z=A.isPending||N.isPending||F.isPending,he=j.isPending||F.isPending;function _e(){X.length!==0&&N.mutate({faceIds:X},{onSettled:()=>{J(),Y()}})}function ve(){X.length!==0&&Promise.allSettled(X.map(e=>F.mutateAsync({faceId:e}))).then(()=>{J(),Y()})}function be(e){S(null),v([e])}function xe(e){j.mutate({faceId:e},{onSettled:J}),S(null)}function Se(e){F.mutate({faceId:e},{onSettled:J}),S(null)}let Ce=W.length!==R.length;return r(`div`,{className:`relative space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[c(`div`,{className:`flex items-center gap-1`,children:Wt.map(e=>c(`button`,{type:`button`,onClick:()=>n(e.value),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${t===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:e.label},e.value))}),c(pe,{onChange:u}),c(le,{cameras:ne,selected:d,onChange:p}),r(`button`,{type:`button`,onClick:()=>b(!0),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${y?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[c(k,{className:`h-3.5 w-3.5`}),` Similar groups`]}),!w&&re>0&&r(`button`,{type:`button`,onClick:de,className:`ml-auto flex items-center gap-1 rounded-md px-2.5 py-1 text-xs text-warning/90 transition-colors hover:bg-warning/10`,title:`Select every visible face whose crop image is missing so you can delete the orphans in one pass`,children:[c(f,{className:`h-3.5 w-3.5`}),` Select `,re,` crop-less`]}),!w&&c(`span`,{className:`text-[10px] text-foreground-subtle ${re>0?`ml-2`:`ml-auto`}`,children:Ce?`${String(W.length)} of ${String(R.length)} faces`:`${String(W.length)} face${W.length===1?``:`s`}`})]}),m.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[m.size,` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[r(T,{variant:`primary`,onClick:()=>v(X),disabled:Z,children:[c(B,{className:`h-3.5 w-3.5`}),` Assign`]}),r(T,{variant:`secondary`,onClick:_e,disabled:Z,children:[N.isPending?c(z,{className:`h-3.5 w-3.5 animate-spin`}):c(ye,{className:`h-3.5 w-3.5`}),` `,`Detach`]}),r(T,{variant:`secondary`,onClick:ve,disabled:Z,children:[c(h,{className:`h-3.5 w-3.5`}),` Delete`]}),c(T,{variant:`ghost`,onClick:Y,disabled:Z,children:c(H,{className:`h-3.5 w-3.5`})})]})]}),w&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[c(z,{className:`h-4 w-4 animate-spin`}),` Loading faces…`]}),!w&&W.length===0&&c(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:R.length>0?`No faces match the current date / camera filters.`:`No faces found for this filter.`}),!w&&W.length>0&&r(a,{children:[c(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(6.5rem,6.5rem))] justify-start gap-2`,children:G.pageItems.map(e=>c(Ut,{face:e,cameraName:U(e.deviceId),nowMs:I,selected:m.has(e.faceId),onToggleSelect:ae,onAssign:e=>v([e]),onOpenDetail:S},e.faceId))}),c(oe,{currentPage:G.page,totalItems:G.totalItems,pageSize:G.pageSize,onPageChange:G.setPage,itemNoun:`faces`})]}),c(wt,{face:q,cameraName:q?U(q.deviceId):``,onClose:()=>S(null),onAssign:be,onUnassign:xe,onDelete:Se,actionsPending:he}),c(yt,{faceIds:_,identities:E,onDone:()=>{v(null),Y()}}),c(zt,{open:y,onClose:()=>b(!1),byId:K,cameraName:U,nowMs:I,identities:E,selectMany:ce})]})}n();var Kt=[[`faceGallery`]],qt=2e3;function Jt(){let e=o(),n=t(e);n.current=e;let r=t(void 0);r.current||=he({delayMs:qt,invalidate:()=>{n.current.invalidateQueries({queryKey:Kt})}}),l(()=>()=>r.current?.cancel(),[]),re(xe.PipelineAnalyticsFaceGalleryChanged,()=>{r.current?.trigger()})}function Yt(){return Jt(),c(Ce,{icon:Se,title:`Faces`,subtitle:`Manage enrolled identities and assign detected face crops to people.`,children:r(`section`,{className:`space-y-3`,children:[r(`div`,{children:[c(`h2`,{className:`text-sm font-semibold text-foreground mb-1`,children:`People`}),c(`p`,{className:`text-xs text-foreground-subtle mb-3`,children:`Enrolled identities used for face recognition. Expand a row to view or remove training samples.`}),c(pt,{})]}),r(`div`,{className:`pt-4 border-t border-border`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground mb-1`,children:`Recent detected faces`}),c(`p`,{className:`text-xs text-foreground-subtle mb-3`,children:`Face crops captured by the detection pipeline. Assign them to a person to build recognition training data.`}),c(Gt,{})]})]})})}export{Yt as DetectionIntelligencePage};
@@ -1,2 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,a,b as o,o as s,q as c,t as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{B as f,D as p,E as m,G as h,R as g,T as _,U as v,W as y,X as b,_t as x,at as S,lt as C,m as w,mt as T,q as E,r as D,st as O,t as k,ut as A,vt as j}from"./player-overlays-B7T46vDu.js";import{$ as M,$t as N,$u as ee,A as P,As as F,B as te,Cn as I,Cs as L,Dn as R,Ed as z,Ei as B,En as ne,Es as re,Fi as V,Fn as H,Fs as U,Ft as ie,Gt as ae,Hd as oe,Hl as W,Hn as se,Ht as ce,Id as le,In as G,Jd as ue,Js as de,Jt as fe,Ju as pe,Ks as K,Kt as me,L as he,La as ge,Li as _e,Ln as ve,M as ye,Mn as be,Mt as xe,Mu as Se,Nn as Ce,On as we,Or as Te,Ou as Ee,Pa as De,Pi as q,Pt as Oe,Q as ke,Qo as Ae,Ri as je,S as Me,Sn as Ne,Ss as Pe,T as Fe,Tf as Ie,Ti as Le,Tn as Re,Ts as ze,Tt as Be,Ul as Ve,Ut as He,Uu as Ue,Vd as We,Vu as Ge,Wo as Ke,Wr as qe,Xi as Je,Xs as Ye,Xt as Xe,Xu as Ze,Y as Qe,Yl as $e,Ys as et,Yt as tt,Yu as nt,Z as rt,Zd as it,Zl as at,Zt as ot,_d as st,_t as ct,a as lt,aa as ut,ad as dt,an as ft,at as pt,b as mt,bi as ht,bn as gt,c as _t,ca as vt,cd as yt,co as bt,ct as xt,cu as St,d as Ct,df as wt,dn as Tt,du as Et,en as Dt,es as Ot,ff as kt,ft as At,gd as jt,gt as Mt,ha as Nt,i as Pt,ic as Ft,in as It,it as Lt,iu as Rt,j as zt,ja as Bt,ji as Vt,jn as Ht,k as Ut,kn as Wt,l as Gt,la as Kt,lo as qt,lt as Jt,mf as Yt,mt as Xt,na as Zt,nf as Qt,nr as $t,nt as en,nu as tn,o as nn,oa as rn,od as an,on,pt as sn,q as cn,qi as ln,ql as un,qn as dn,qs as fn,qt as pn,r as mn,rn as hn,ro as gn,rr as _n,s as vn,sd as yn,sn as bn,so as xn,su as Sn,ta as Cn,tn as wn,tr as Tn,tt as En,ua as Dn,ud as On,uf as kn,ur as An,ut as jn,va as Mn,vd as Nn,vt as Pn,w as Fn,wa as In,x as Ln,xi as Rn,xn as zn,y as Bn,yc as Vn,z as Hn,zi as Un,zt as Wn}from"./src-BTX2jfA7.js";import{t as Gn}from"./archive-MsQRiIew.js";import{t as Kn}from"./boxes-CBxcgWPC.js";import{t as qn}from"./circle-slash-CGPkHspT.js";import{_ as Jn,a as Yn,c as Xn,d as Zn,f as Qn,g as $n,h as er,i as tr,l as nr,m as rr,n as ir,o as ar,p as or,s as sr,t as cr,u as lr,v as ur,y as dr}from"./ClusterStepModel-B9pwzZ_M.js";import{t as fr}from"./layers-DSe93_v-.js";import{An as pr,Er as J,Fn as mr,Fr as hr,Nn as gr,Pn as _r,Pr as vr,Tr as Y,Yn as yr,_ as br,an as xr,b as Sr,br as Cr,di as wr,dr as Tr,f as Er,fn as Dr,g as Or,hn as kr,in as Ar,m as jr,on as Mr,p as Nr,pn as Pr,pr as Fr,rn as Ir,rr as Lr,sn as Rr,sr as zr,u as Br,ui as Vr,vr as Hr,wr as Ur,xr as X}from"./client-BBcQuaON.js";import{t as Z}from"./useTranslation-Bc5yH9V9.js";import"./mount-D8gNhpYS.js";import{$ as Wr,A as Gr,B as Kr,D as qr,E as Jr,G as Yr,J as Xr,K as Zr,M as Qr,O as $r,Q as ei,R as ti,U as ni,V as ri,W as ii,Y as ai,Z as oi,_ as si,et as ci,j as li,k as ui,nt as di,x as fi,y as pi,z as mi}from"./index-BWu66tVw.js";import{C as hi,D as gi,E as _i,S as vi,_ as yi,a as bi,b as xi,c as Si,d as Ci,f as wi,g as Ti,h as Ei,i as Di,l as Oi,m as ki,n as Ai,o as ji,p as Mi,r as Ni,s as Pi,t as Fi,u as Ii,v as Li,x as Ri,y as zi}from"./CompositionEditor-BS_jFILf.js";import{t as Bi}from"./authed-media-BaRjbtMq.js";import"./useEventInvalidation-D8gNhpYS.js";import{t as Vi}from"./use-stationary-objects-BPLoE6ig.js";import"./device-picker-model-D8gNhpYS.js";var Hi=j(`arrow-left-right`,[[`path`,{d:`M8 3 4 7l4 4`,key:`9rb6wj`}],[`path`,{d:`M4 7h16`,key:`6tx8e3`}],[`path`,{d:`m16 21 4-4-4-4`,key:`siv7j2`}],[`path`,{d:`M20 17H4`,key:`h6l3hr`}]]),Ui=j(`disc`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Wi=j(`ear`,[[`path`,{d:`M6 8.5a6.5 6.5 0 1 1 13 0c0 6-6 6-6 10a3.5 3.5 0 1 1-7 0`,key:`1dfaln`}],[`path`,{d:`M15 8.5a2.5 2.5 0 0 0-5 0v1a2 2 0 1 1 0 4`,key:`1qnva7`}]]);n();function Gi(e){if(typeof e!=`object`||!e)return null;let t=e,n=t.id,r=t.label;if(typeof n!=`string`||typeof r!=`string`)return null;let i=t.available===!0,a=t.enabled,o=t.unavailableReason;return{id:n,label:r,costWhenOff:typeof t.costWhenOff==`string`?t.costWhenOff:``,on:i&&typeof a==`boolean`?a:null,available:i,unavailableReason:typeof o==`string`?o:null}}function Ki(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(Gi).filter(e=>e!==null);return n.length===0?null:n}var qi=[[/privacy|mask/i,`privacy`],[/microphone|mic\b/i,`microphone`],[/speaker|broker audio|stream audio/i,`speaker`],[/audio/i,`listening`],[/object|detect/i,`detection`],[/event/i,`archive`],[/record/i,`recording`],[/notif/i,`notifications`],[/stream|broker/i,`stream`]];function Ji(e){for(let[t,n]of qi)if(t.test(e))return n;return`generic`}function Yi(e){let t=e.filter(e=>e.on===!1).map(e=>e.id),n=e.filter(e=>e.on===null).map(e=>e.id),r=t=>t.map(t=>e.find(e=>e.id===t)?.label??t).join(`, `),i=[];return t.length>0&&i.push(`Off: ${r(t)}`),n.length>0&&i.push(`Unknown: ${r(n)}`),{offIds:t,unknownIds:n,summary:i.length===0?`All camera functions on`:i.join(` · `)}}var Xi={stream:Ze,detection:di,privacy:T,microphone:A,speaker:Et,listening:Wi,archive:Gn,recording:Ui,notifications:kn,generic:Se};function Zi({deviceId:t}){let n=s(),i=Number.isFinite(t),[a,o]=c(null),[l,d]=c(!1),f=re({deviceId:t},{enabled:i});mn([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let p=Ki(f.data),m=Ye({onError:(e,r)=>{console.error(`[CameraFunctionSwitches] switch write failed — reverting`,{tags:{deviceId:t},meta:{switchId:r.switchId,error:e instanceof Error?e.message:String(e)}}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSwitches`]]}),o({id:r.switchId,message:e instanceof Error?e.message:String(e)})},onSuccess:()=>{o(null),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`]]}),n.invalidateQueries({queryKey:[[`deviceManager`]]}),n.invalidateQueries({queryKey:[[`recording`]]})}}),h=e(e=>{!e.available||e.on===null||m.mutate({deviceId:t,switchId:e.id,enabled:!e.on})},[t,m]);if(p===null)return null;let g=Yi(p),_=e=>a?.id===e.id?a.message:null;return r(tt,{open:l,onOpenChange:d,children:[r(ot,{"aria-label":`Camera functions`,title:g.summary,className:`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors ${a===null?g.offIds.length>0?`border-warning/40 text-warning hover:bg-warning/10`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`:`border-danger/50 text-danger bg-danger/5`}`,children:[u(Se,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden lg:inline`,children:`Functions`}),g.offIds.length>0&&r(`span`,{className:`rounded bg-warning/20 px-1 text-[9px] font-semibold uppercase tracking-wide`,children:[g.offIds.length,` off`]})]}),r(Xe,{align:`end`,className:`min-w-[240px] max-h-[60vh] overflow-y-auto p-1`,children:[u(`div`,{className:`px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle`,children:`Camera functions`}),u(`ul`,{className:`space-y-0.5`,children:p.map(e=>u(`li`,{children:u(Qi,{row:e,failure:_(e),onToggle:()=>h(e)})},e.id))})]})]})}function Qi({row:e,failure:t,onToggle:n}){let i=Xi[Ji(e.label)],a=e.on===null,o=e.on===!1,s=t===null?a?e.unavailableReason??`The source that owns this did not answer.`:e.costWhenOff:`Write failed: ${t}`,c=t===null?a?e.unavailableReason??`unknown`:null:`write failed`;return r(`button`,{type:`button`,role:`switch`,"aria-label":e.label,"aria-checked":e.on===!0,disabled:!e.available,onClick:n,title:s,className:`flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-[12px] text-foreground transition-colors hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed`,children:[u(i,{className:`h-3.5 w-3.5 shrink-0 ${t===null?a?`text-foreground-subtle/50`:o?`text-warning`:`text-success`:`text-danger`}`}),r(`span`,{className:`flex-1 min-w-0 truncate`,children:[e.label,c!==null&&r(`span`,{className:`ml-1 text-[10px] text-foreground-subtle`,children:[`· `,c]})]}),u(`span`,{className:`shrink-0 rounded px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${a?`bg-surface-hover text-foreground-subtle/60`:o?`bg-warning/20 text-warning`:`bg-success/20 text-success`}`,children:a?`—`:o?`off`:`on`})]})}function $i({deviceId:e}){let t=Lt(S().trpcClient,e);return t===null?null:r(`a`,{href:t.url,target:`_blank`,rel:`noopener noreferrer`,title:`${t.label} — ${t.host}`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[u(le,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:t.label})]})}function ea({parentDeviceId:e}){let{t}=Z(),n=oi(),i=S(),{data:a,isLoading:o,isError:s}=ri(e),{data:c}=ut({deviceId:e},{enabled:Number.isFinite(e)});if(o)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[10px] text-foreground-subtle`,children:t(`common.loading`,{defaultValue:`Loading…`})})});if(s)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[10px] text-warning`,children:t(`integrations.childrenLoadError`,{defaultValue:`Failed to load children`})})});let l=(a??[]).filter(e=>e.display?.hidden!==!0);if(l.length===0)return null;let d=M(c?.stableId??``,l,c?.childLayout),f=d.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>u(rt,{trpc:i.trpcClient,device:{...t,name:pt(t,m)},variant:`minimal`,onNavigate:p},e),g=f.some(e=>!!e.role),_=f.some(e=>!e.role),v=g&&!_?t(`device.accessories`,{defaultValue:`Accessories`}):!g&&_?t(`device.adoptedDevices`,{defaultValue:`Adopted devices`}):t(`device.children`,{defaultValue:`Children`}),y=f.length>0?r(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5`,children:v}),u(`div`,{className:`space-y-1`,children:f.map(e=>h(e.id,e))})]}):null,b=d.disabledSection===void 0?null:u(ke,{title:t(`device.disabledSection`,{defaultValue:`Disabled`}),count:d.disabledSection.children.length,defaultOpen:!1,children:u(`div`,{className:`opacity-60 space-y-1`,children:d.disabledSection.children.map(e=>h(e.id,e))})},d.disabledSection.title);if(d.sections.length===0)return b===null?y:r(`div`,{className:`space-y-2`,children:[y,b]});let x=_&&!g;return r(`div`,{className:`space-y-2`,children:[x?y:null,d.sections.map(e=>u(ke,{title:e.title,count:e.children.length,defaultOpen:e.defaultOpen,children:e.children.map(e=>h(e.id,e))},e.title)),x?null:y,b]})}function ta({deviceId:e}){let t=S(),{data:n,isLoading:r}=Kr(e),{data:i,isLoading:a}=ri(e),o=r||a,s=(i??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,name:e.name,features:e.features,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),c=typeof n?.linkDeviceId==`number`?n.linkDeviceId:null,l=typeof n?.primaryChildEntityId==`string`?n.primaryChildEntityId:null;return o?u(`div`,{className:`h-full min-h-32 w-full animate-pulse rounded-lg bg-surface`,"aria-hidden":`true`}):u(`div`,{className:`flex h-full w-full flex-col`,children:u(xt,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}n();function na({dev:e,busy:t,setBusy:n}){let i=e?.motionTrigger,a=E(e?.state.motionTrigger),[o,s]=c(!1);if(!i)return null;let l=a?.enabled===!0,d=a!==void 0,f=async()=>{if(t||!d)return;let e=!l;n(!0),s(!0);try{await i.setMotionTrigger({enabled:e})}finally{n(!1),s(!1)}};return r(`button`,{type:`button`,onClick:()=>{f()},disabled:t||!d,title:d?l?`Disable trigger on motion`:`Enable trigger on motion`:`Awaiting state…`,"aria-pressed":l,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${l?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground`}`,children:[u(Ie,{className:`h-3 w-3`}),u(`span`,{children:o?l?`Disabling…`:`Enabling…`:d?l?`On motion: on`:`On motion: off`:`On motion: …`})]})}n();function Q({deviceId:e,deviceType:t,features:n}){let i=S(),a=At(t)?.HeroCard??sn,o=h(i.trpcClient,e),s=E(o?.state.deviceStatus),[l,d]=c(!1),f=s!==void 0&&s.online===!1,p=f?s.lastChangedAt:null;return r(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:[f?u(`div`,{className:`flex justify-center`,children:u(jn,{lastChangedAt:p})}):null,u(a,{trpc:i.trpcClient,deviceId:e,features:n}),u(`div`,{className:`flex justify-center`,children:u(na,{dev:o,busy:l,setBusy:d})})]})}function ra({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:u(Xt,{trpc:S().trpcClient,deviceId:e,features:t})})}function ia({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:u(sn,{trpc:S().trpcClient,deviceId:e,features:t})})}function aa(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function oa(e){if(!e)return null;let t=aa(e.data);return t===null?e.eventType:`Button ${String(t)} · ${e.eventType}`}var sa=1e3,ca=60*sa,la=60*ca,ua=24*la;function da(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<sa?`just now`:n<ca?`${String(Math.floor(n/sa))}s ago`:n<la?`${String(Math.floor(n/ca))}m ago`:n<ua?`${String(Math.floor(n/la))}h ago`:`${String(Math.floor(n/ua))}d ago`}n();var fa=1500,pa=15e3,ma=1e3;function ha({deviceId:e}){let n=h(S().trpcClient,e)?.state.eventEmitter,i=E(n);d(()=>{if(!n)return;n.refresh();let e=setInterval(()=>{n.refresh()},pa);return()=>{clearInterval(e)}},[n]);let a=i?.lastEvent??null,o=a?.seq??null,s=t(null),[l,f]=c(!1);d(()=>{if(o===null)return;let e=s.current;if(s.current=o,e===null||e===o)return;f(!0);let t=setTimeout(()=>{f(!1)},fa);return()=>{clearTimeout(t)}},[o]);let[p,m]=c(()=>Date.now());d(()=>{let e=setInterval(()=>{m(Date.now())},ma);return()=>{clearInterval(e)}},[]);let g=oa(a),_=i?.eventTypes??[],v=i?.eventCountSinceStart??0,y=i!==void 0,b=aa(a?.data);return r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 p-4`,children:[u(`div`,{"data-testid":`event-emitter-indicator`,"data-flashing":String(l),className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${l?`border-primary bg-primary/20 text-primary shadow-lg shadow-primary/30 scale-105`:`border-border bg-surface text-foreground-subtle`}`,"aria-live":`polite`,title:g??`No press recorded`,children:u(l?yn:z,{className:`h-10 w-10`})}),r(`div`,{className:`text-center`,children:[b!==null&&u(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-primary`,children:`Button ${String(b)}`}),u(`div`,{"data-testid":`event-emitter-headline`,className:`text-sm font-semibold ${g?`text-foreground`:`text-foreground-subtle`}`,children:g??(y?`No press recorded`:`Awaiting state…`)}),u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:a?da(a.timestamp,p):`Waiting for the first event`})]}),_.length>0&&u(`div`,{className:`flex max-w-full flex-wrap justify-center gap-1`,children:_.map(e=>u(`span`,{"data-testid":`event-emitter-chip`,className:`rounded-full border px-2 py-0.5 text-[10px] font-medium ${e===a?.eventType?`border-primary bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle`}`,children:e},e))}),u(`div`,{className:`text-[10px] text-foreground-subtle`,children:`${String(v)} ${v===1?`event`:`events`} since start`})]})}function ga({deviceName:e,deviceType:t,provider:n,isOnline:i,features:a}){return r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface p-6 text-center`,children:[u(Zr,{type:n,size:`lg`}),r(`div`,{children:[u(`div`,{className:`text-sm font-semibold text-foreground`,children:e}),u(`div`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5`,children:t})]}),r(`div`,{className:`flex items-center gap-2 flex-wrap justify-center`,children:[u(ye,{status:i?`online`:`offline`}),a.length>0&&u(Xr,{capabilities:a})]}),u(`div`,{className:`text-[10px] text-foreground-subtle italic max-w-xs mt-1`,children:`No live view for this device type. Use the Config tab or the shortcut row to interact.`})]})}n();function _a({deviceId:e}){let t=s(),n=q({deviceId:e},{refetchInterval:1e4,retry:!1}),a=V({onSuccess:()=>{t.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),t.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),o=i(()=>va(n.data??[]),[n.data]);return r(`div`,{className:`flex h-full w-full flex-col gap-3 p-3 sm:p-4`,children:[r(`div`,{className:`flex flex-wrap items-stretch gap-2 sm:gap-3`,children:[u(ya,{label:`Discovered`,value:o.total,icon:u(an,{className:`h-3.5 w-3.5`})}),u(ya,{label:`Adopted`,value:o.adopted,accent:`success`}),u(ya,{label:`Available`,value:o.available,accent:o.available>0?`primary`:void 0}),r(`button`,{type:`button`,onClick:()=>{a.mutateAsync({deviceId:e}).catch(()=>{})},disabled:a.isPending,className:`inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 self-stretch shrink-0`,children:[a.isPending?u(jt,{className:`h-3.5 w-3.5 animate-spin`}):u(nt,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:`Discover`})]})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-foreground-subtle border-t border-border-subtle pt-2`,children:[u(ba,{icon:u(Sn,{className:`h-3 w-3 text-emerald-500`}),label:`${o.online} online`}),u(ba,{icon:u(yt,{className:`h-3 w-3 text-amber-500`}),label:`${o.sleeping} sleeping`}),u(ba,{icon:u(St,{className:`h-3 w-3 text-destructive`}),label:`${o.offline} offline`}),o.unknown>0?u(ba,{icon:u(ue,{className:`h-3 w-3 text-foreground-subtle`}),label:`${o.unknown} unknown`}):null]})]})}function va(e){let t={total:e.length,adopted:0,available:0,online:0,sleeping:0,offline:0,unknown:0};for(let n of e)n.alreadyAdopted?t.adopted+=1:t.available+=1,t[n.status]+=1;return t}function ya({label:e,value:t,icon:n,accent:i}){return r(`div`,{className:`flex flex-1 basis-[140px] min-w-0 flex-col gap-1 rounded-lg border px-2 py-1.5 sm:px-3 sm:py-2 ${i===`success`?`bg-emerald-500/10 border-emerald-500/30 text-emerald-500`:i===`primary`?`bg-primary/10 border-primary/30 text-primary`:`bg-surface-hover border-border text-foreground`}`,children:[r(`div`,{className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate`,children:[n,u(`span`,{className:`truncate`,children:e})]}),u(`div`,{className:`text-xl sm:text-2xl font-semibold tabular-nums leading-none`,children:t})]})}function ba({icon:e,label:t}){return r(`span`,{className:`inline-flex items-center gap-1`,children:[e,u(`span`,{children:t})]})}var xa={[J.Switch]:Q,[J.Siren]:Q,[J.Light]:Q,[J.Sensor]:Q,[J.Button]:Q,[J.Hub]:_a,[J.Cover]:ra,[J.Valve]:Q,[J.Humidifier]:Q,[J.WaterHeater]:Q,[J.Container]:ta,[J.Lock]:Q,[J.Fan]:Q,[J.Thermostat]:Q,[J.Climate]:Q,[J.MediaPlayer]:Q,[J.Control]:Q,[J.AlarmPanel]:Q,[J.EventEmitter]:ha,[J.Notifier]:ia,[J.Script]:Q,[J.Automation]:Q,[J.Presence]:Q,[J.Update]:Q,[J.Vacuum]:Q,[J.LawnMower]:Q,[J.Weather]:Q,[J.Image]:Q,[J.PetFeeder]:Q};function Sa(e){return xa[e]??ga}function Ca(e){return u(Sa(e.deviceType),{...e})}function wa(e){return nn(S().trpcClient,e)}n();function Ta(n){let[r,i]=c(`idle`),[a,o]=c(null),s=t(null),l=t(null),u=t(null),f=t(!0),p=bt(),m=xn(),h=qt(),g=e(()=>{if(s.current){try{s.current.close()}catch{}s.current=null}if(l.current){for(let e of l.current.getTracks())try{e.stop()}catch{}l.current=null}u.current=null},[]),_=e(async()=>{if(r===`idle`)return;i(`stopping`);let e=u.current;if(e&&n!==null)try{await Promise.race([h.mutateAsync({deviceId:n,sessionId:e}),new Promise((e,t)=>setTimeout(()=>t(Error(`server stopSession timeout`)),2e3))])}catch(e){console.warn(`[intercom] server stopSession failed (continuing teardown)`,e)}g(),f.current&&(i(`idle`),o(null))},[r,n,h,g]),v=e(async()=>{if(n===null||r!==`idle`&&r!==`error`)return;o(null);let e=null,t=null,a=null;try{i(`requesting-mic`),e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),l.current=e,i(`starting`);let r=await p.mutateAsync({deviceId:n});a=r.sessionId,u.current=a,i(`connecting`),t=new RTCPeerConnection,s.current=t,t.oniceconnectionstatechange=()=>{if(!f.current)return;let e=t.iceConnectionState;e===`connected`||e===`completed`?i(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&f.current&&(o(e===`failed`?`WebRTC connection failed`:null),_())};for(let n of e.getAudioTracks())t.addTrack(n,e);await t.setRemoteDescription({type:`offer`,sdp:r.sdpOffer});let c=await t.createAnswer();await t.setLocalDescription(c);let d=t.localDescription?.sdp??c.sdp??``;await m.mutateAsync({deviceId:n,sessionId:a,sdpAnswer:d})}catch(r){let c=r instanceof Error?r.message:String(r);if(console.warn(`[intercom] start failed`,r),t)try{t.close()}catch{}if(e)for(let t of e.getTracks())try{t.stop()}catch{}if(s.current=null,l.current=null,a!==null)try{await h.mutateAsync({deviceId:n,sessionId:a})}catch{}u.current=null,f.current&&(o(c),i(`error`))}},[n,r,p,m,h,_]);return d(()=>(f.current=!0,()=>{f.current=!1;let e=u.current;if(e!==null&&n!==null&&h.mutate({deviceId:n,sessionId:e}),s.current){try{s.current.close()}catch{}s.current=null}if(l.current){for(let e of l.current.getTracks())try{e.stop()}catch{}l.current=null}u.current=null}),[n]),{state:r,error:a,start:v,stop:_,isTalking:r===`talking`}}n();var Ea=0;function $(){return++Ea}function Da(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function Oa(e){return[``,`Commands`,` help Show this help`,` examples Show usage examples for the current scope`,` context Show every available variable + full API surface`,` clear Clear terminal (also Ctrl+L)`,``,`Shortcuts`,` Enter Execute expression`,` Arrow Up/Down Navigate command history`,` Ctrl+L Clear terminal`,``,`Try: ${{system:` sm.summary() // fleet overview`,device:` device.state.battery.value?.sleeping // sync read`,provider:` devices.map(d => d.name)`,addon:` manifest.version`}[e.type]}`,``,`Top-level objects: sm (SystemMirror), DeviceType, Math, JSON, Date, …`]}function ka(e){switch(e.type){case`device`:return[``,`── State (sync, zero round-trip) ─────────────────────────`,` device.state.battery.value`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,``,`── Actions (async, through wrapper chain) ────────────────`,` await device.snapshot.getSnapshot({})`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.switch.setState({ on: true })`,``,`── Wait for condition ───────────────────────────────────`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`── Subscribe to changes ─────────────────────────────────`,` const off = device.state.battery.subscribe(s => console.log(s))`,``,`── Quick info ───────────────────────────────────────────`,` info.name device name`,` info.addonId owning addon`,` sm.dump(deviceId) full debug dump`];case`system`:return[``,`── Lookups ──────────────────────────────────────────────`,` sm.getDeviceById(8)`,` sm.getDeviceByName('Sala da pranzo')`,` sm.getDevicesByAddon('reolink')`,` sm.getDevicesByType(DeviceType.Camera)`,``,`── Filters (typed query) ────────────────────────────────`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] })`,` sm.query({ name: /^Cam-/ })`,``,`── Cross-device ─────────────────────────────────────────`,` sm.whereState('battery', s => s.percentage < 20).length`,` sm.mapState('battery', s => s.percentage)`,` sm.countByCap('snapshot')`,``,`── Batch action ─────────────────────────────────────────`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,``,`── Listen ───────────────────────────────────────────────`,` sm.listenCap('motion', (id, s) => console.log(id, s))`,` sm.onDeviceAdded((id, info) => console.log('+', info.name))`,``,`── Diagnostics ──────────────────────────────────────────`,` sm.summary()`,` sm.dump(8)`];case`provider`:return[``,` devices.map(d => d.name)`,` await getIntegration()`,` sm.getDevicesByAddon('<this-addon-id>').length`];case`addon`:return[``,` manifest.name`,` manifest.version`,` declaration`]}}function Aa(e){let t=[``,`Scope: ${e.type}`,``];switch(e.type){case`system`:return[...t,`Primary API — sm (SystemMirror):`,` sm.getDeviceById(id) DeviceProxy | null (sync)`,` sm.getDeviceByName(name) DeviceProxy | null`,` sm.getDeviceByStableId(sid) DeviceProxy | null`,` sm.getAllDevices() readonly DeviceProxy[]`,` sm.getDeviceInfo(id) DeviceInfo | null`,` sm.summary() fleet stats`,``,`Filters — sm.query({...}):`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] }) // ALL caps required`,` sm.query({ anyCap: ['ptz', 'motion'] }) // ANY cap`,` sm.query({ name: { contains: 'sala' } }) // case-insensitive`,` sm.query({ name: /^Cam-\\d+$/ })`,` sm.query({ type: DeviceType.Camera })`,` sm.query({ parentDeviceId: 8 }) // accessories of cam 8`,` sm.query({ where: (info, dev) => dev.state.battery.value?.sleeping })`,``,`State queries:`,` sm.whereState('battery', s => s.percentage < 20)`,` sm.mapState('battery', s => s.percentage)`,` sm.findState('motion', s => s.detected)`,` sm.countByCap('snapshot')`,``,`Listeners (return unsubscribe fn):`,` sm.listen((id, cap, slice) => …) // every state change`,` sm.listenCap('motion', (id, slice) => …)`,` sm.listenDevice(8, (id, cap, slice) => …)`,` sm.onDeviceAdded((id, info) => …)`,` sm.onDeviceRemoved((id, info) => …)`,``,`Wait primitives:`,` await sm.waitForState(8, 'battery', s => !s.sleeping, 30_000)`,` await sm.waitForDevice(99, 30_000)`,``,`Batch:`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,` await sm.forEachCap('reboot', d => d.reboot.reboot({}))`,``,`Diagnostics:`,` sm.dump(8) debug dump (one device)`,` sm.dump() full fleet dump`,` sm.summary() breakdown by cap/addon/type`,``,`Legacy: deviceRegistry, addonRegistry, eventBus, devices(), addons()`];case`device`:return[...t,`Pre-bound variables:`,` device DeviceProxy for this device (sync state + async methods)`,` deviceId number`,` info DeviceInfo metadata (name, addonId, type, online, …)`,` sm SystemMirror (full cluster view)`,` rawDevice legacy IDevice instance (escape hatch)`,``,`Reactive state (sync, zero round-trip):`,` device.state.battery.value BatteryStatus | undefined`,` device.state.battery.value?.sleeping`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,` device.state.switch.value?.on`,` device.state.brightness.value?.percentage`,` device.state.doorbell.value?.lastPressedAt`,``,`Cap actions (async, through wrapper chain):`,` await device.snapshot.getSnapshot({})`,` await device.snapshot.getSnapshot({ streamId: 'high' })`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.ptz.goToPreset({ presetId: 'home' })`,` await device.switch.setState({ on: true })`,` await device.brightness.setBrightness({ percentage: 60 })`,` await device.reboot.reboot({})`,``,`Subscribe to slice changes:`,` const off = device.state.battery.subscribe(s => console.log(s))`,` // off() to unsubscribe`,``,`Wait for a state condition:`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`Diagnostics:`,` info.name device name`,` info.addonId which addon owns it`,` info.online transport health`,` sm.dump(deviceId) full debug dump (binding + state + info)`];case`provider`:return[...t,`Pre-bound variables:`,` devices Devices belonging to this provider (raw IDevice[])`,` getIntegration() Integration metadata`,``,`For typed device access use the SystemMirror:`,` await getSystemMirror()`,` sm.getDevicesByAddon('this-addon-id')`];case`addon`:return[...t,`Pre-bound variables:`,` manifest { name, version, ... }`,` declaration addon declaration`,` source addon source location`,``,`Examples:`,` manifest.name`,` manifest.version`]}}function ja({scope:n,greeting:i,className:a}){let o=S(),[s,f]=c(()=>{let e=[];return i&&e.push({id:$(),kind:`info`,text:i}),e.push({id:$(),kind:`info`,text:`scope: ${Da(n)} — type help or context for available commands`}),e}),[p,m]=c(``),[h,g]=c([]),[_,v]=c(-1),y=t(null),b=t(null);d(()=>{let e=b.current;e&&(e.scrollTop=e.scrollHeight)},[s]);let x=e(()=>{y.current?.focus()},[]),C=l({mutationFn:e=>o.trpcClient.repl.execute.mutate({code:e,scope:n}),onSuccess:e=>{let t=e??{},n=typeof t.output==`string`?t.output:e==null?`undefined`:typeof e==`string`?e:JSON.stringify(e,null,2),r=t.type===`error`;f(e=>[...e,{id:$(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);f(e=>[...e,{id:$(),kind:`error`,text:t}])}});function w(e){let t=e.trim();if(t){if(t===`clear`){f([{id:$(),kind:`info`,text:`scope: ${Da(n)}`}]),m(``);return}if(t===`help`){f(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Oa(n).map(e=>({id:$(),kind:`info`,text:e}))]),m(``);return}if(t===`context`){f(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Aa(n).map(e=>({id:$(),kind:`info`,text:e}))]),m(``);return}if(t===`examples`){f(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...ka(n).map(e=>({id:$(),kind:`info`,text:e}))]),m(``);return}g(e=>[...e,t]),v(-1),f(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`}]),m(``),C.mutate(t)}}function T(e){if(e.key===`Enter`){e.preventDefault(),w(p);return}if(e.key===`ArrowUp`){if(e.preventDefault(),h.length===0)return;let t=_===-1?h.length-1:Math.max(0,_-1);v(t),m(h[t]??``);return}if(e.key===`ArrowDown`){if(e.preventDefault(),_===-1)return;let t=_+1;t>=h.length?(v(-1),m(``)):(v(t),m(h[t]??``));return}e.ctrlKey&&e.key===`l`&&(e.preventDefault(),f([{id:$(),kind:`info`,text:`scope: ${Da(n)}`}]))}let E={input:`text-zinc-300`,result:`text-emerald-300`,error:`text-red-300`,info:`text-zinc-400`};return r(`div`,{className:`flex flex-col bg-[#0c0a09] rounded-lg border border-border overflow-hidden font-mono text-xs ${a??``}`,onClick:x,children:[r(`div`,{ref:b,className:`flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]`,children:[s.map(e=>u(`pre`,{className:`whitespace-pre-wrap break-words leading-relaxed ${E[e.kind]}`,children:e.text},e.id)),C.isPending&&u(`span`,{className:`text-zinc-500 animate-pulse`,children:`…thinking`})]}),r(`div`,{className:`flex items-center gap-2 border-t border-zinc-800 px-3 py-2 bg-[#0c0a09]`,children:[u(`span`,{className:`text-emerald-400 flex-shrink-0 select-none font-bold`,children:`>`}),u(`input`,{ref:y,value:p,onChange:e=>m(e.target.value),onKeyDown:T,disabled:C.isPending,placeholder:`device.state.battery.value`,autoFocus:!0,className:`flex-1 bg-transparent text-zinc-100 placeholder:text-zinc-600 focus:outline-none caret-emerald-400 disabled:opacity-50`,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`})]})]})}function Ma(e,t){return e===null?null:{playbackUrl:e.url,...e.format===void 0?{}:{playbackFormat:e.format},playbackAuthToken:t,...e.label===void 0?{}:{playbackLabel:e.label}}}n();function Na({deviceId:e,intercomAvailable:t=!1}){let n=S(),r=typeof window<`u`?b():``,a=Number.isFinite(e),s=wa(a?e:null),c=Vi(a?[e]:[]),l=i(()=>{if(!a)return;let e=[];for(let t of c.rows){let n=lt(t);n!==null&&e.push(n)}return e},[a,c.rows]),{streams:d,pipelineMetrics:f,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:_,getIceCandidates:v,closeSession:x,getSessionState:C,applyDownlinkProbe:w}=xe(n.trpcClient,a?e:null),T=y(a?e:null,{width:Ra}),E=Ta(a&&t?e:null),O=E.state===`requesting-mic`||E.state===`starting`||E.state===`connecting`||E.state===`stopping`,k=E.isTalking||O,A=()=>{E.state===`idle`||E.state===`error`?E.start():E.state!==`stopping`&&E.stop()},j=D(),M=be(),N=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,ee=Ma(M.request,N),P=j.length>0?u(o,{children:j.map(e=>u(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return u(Ln,{serverUrl:r,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:_,getIceCandidates:v,closeSession:x,getSessionState:C,applyDownlinkProbe:w,...ee===null?{}:{...ee,onExitPlayback:()=>M.clear()},streams:d,pipelineMetrics:f,phase:s.phase,detections:s,...l===void 0?{}:{stationaryObjects:l},defaultShowDetections:!0,defaultShowMotion:!0,showPlayStop:!0,snapshotSrc:T.src,...T.src?{posterUrl:T.src}:{},snapshotLoading:T.loading,onRefreshSnapshot:T.refresh,intercomAvailable:t,intercomShown:k,onIntercomToggle:A,extraOverlay:P,chromeless:!0,className:`h-full`})}function Pa({deviceId:e,containerDeviceId:t}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full`,children:u(Pn,{...t===void 0?{deviceId:e}:{containerDeviceId:t},limit:50,maxHeight:`max-h-full`,showScope:!1,showFilters:!1})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}function Fa({deviceId:e}){if(!Number.isFinite(e))return r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]});let t=[`CamStack REPL — device #${e}`,``,` device.state.battery.value sync state read`,` await device.snapshot.getSnapshot({}) cap action`,``,` type 'examples' for more, 'context' for the full API`].join(`
2
- `);return u(ja,{scope:{type:`device`,deviceId:e},greeting:t,className:`h-full border-0 rounded-none`})}function Ia({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(ct,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}function La({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(Mt,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}var Ra=960;function za(e){return new Set(e.filter(e=>{let t=e.nativeAddonId?.trim()??``;return t!==``&&t!==`composer`}).map(e=>e.capName))}function Ba(e){return e.kind===`known`?null:e}function Va(e,t){return e.composable.kind===`known`?e.composable.value.has(t)?{kind:`present`,mode:`add`}:{kind:`absent`}:e.composable}function Ha(e){if(e.deviceType!==J.Camera)return{kind:`absent`};switch(e.cameraSensors){case`pending`:return{kind:`pending`};case`unknown`:return{kind:`unknown`,reason:`camera sensors could not be checked`};case`absent`:return{kind:`absent`};case`present`:return{kind:`present`,mode:`add`}}}function Ua(e,t){if(e===`motion`)return Ha(t);let n=Ba(t.nativeCaps);if(n!==null)return n;let r=t.nativeCaps.kind===`known`?t.nativeCaps.value:new Set;switch(e){case`doorbell`:return r.has(`doorbell`)?{kind:`absent`}:Va(t,`doorbell`);case`battery`:return r.has(`battery`)?{kind:`present`,mode:`replace`}:Va(t,`battery`);case`consumables`:return r.has(`consumables`)?{kind:`absent`}:Va(t,`consumables`)}}function Wa({onAdvanced:e}){let{t}=Z();return e===void 0?null:u(`button`,{type:`button`,className:`rounded text-left text-[11px] text-primary hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary`,onClick:e,children:t(`customize.advancedLink`)})}function Ga(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};let t=e.data;if(t===void 0)return{kind:`pending`};if(t.state===`not-loaded`)return{kind:`not-loaded`,reason:t.reason};if(t.view===null)return{kind:`none`};let n=zr(t.view.block);return n===null?{kind:`unknown`,reason:`block ${t.view.block.id} is not a composition`}:{kind:`present`,view:t.view,composition:n}}function Ka(e){return e.kind===`present`?e.composition:null}function qa(e,t){let{hidden:n,...r}=e??{},i=t?{...r,hidden:!0}:r;return Object.keys(i).length===0?null:i}function Ja(e){return typeof e.linkDeviceId==`number`}var Ya=new Set(Object.values(Y));function Xa(e){return Ya.has(e)}var Za={[J.Switch]:[Y.Siren,Y.Floodlight,Y.Spotlight,Y.PirSensor,Y.Chime,Y.Autotrack,Y.Nightvision,Y.PrivacyMask,Y.BinaryHelper],[J.Light]:[Y.Floodlight,Y.Spotlight,Y.Nightvision],[J.Siren]:[Y.Siren],[J.Button]:[Y.Doorbell],[J.Sensor]:[Y.MotionSensor,Y.ContactSensor,Y.LeakSensor,Y.SmokeSensor,Y.COSensor,Y.GasSensor,Y.TamperSensor,Y.VibrationSensor,Y.ConnectivitySensor,Y.SoundSensor,Y.BinarySensor,Y.TemperatureSensor,Y.HumiditySensor,Y.AmbientLightSensor,Y.PressureSensor,Y.WindSensor,Y.RainSensor,Y.UvSensor,Y.SolarRadiationSensor,Y.SoilMoistureSensor,Y.PowerSensor,Y.EnergySensor,Y.VoltageSensor,Y.CurrentSensor,Y.AirQualitySensor,Y.BatterySensor,Y.NumericSensor,Y.EnumSensor,Y.DateTimeSensor,Y.GenericSensor],[J.Control]:[Y.NumericControl,Y.SelectControl,Y.TextControl,Y.DateTimeControl],[J.Notifier]:[Y.MobilePushNotifier,Y.MessagingNotifier,Y.EmailNotifier,Y.GenericNotifier]};function Qa(e){for(let t of Object.values(J))if(t===e)return!0;return!1}function $a(e){return Qa(e)?Za[e]??[]:[]}function eo(e,t){let n=$a(t);return e==null||e===``||n.includes(e)?n:[...n,e]}n();function to({device:e}){let{t}=Z(),n=s(),[i,a]=c(null),o=()=>a(null),l={onSuccess:()=>{o(),n.invalidateQueries({queryKey:[[`deviceManager`]]})},onError:e=>a(e.message)},d=Bt(),f=In(),h=e.display?.hidden===!0;return r(`section`,{"aria-label":t(`customize.identity.title`),className:`${p} ${m}`,children:[r(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[u(ii,{deviceId:e.id,initialName:e.name,label:t(`customize.identity.name`),layout:`stacked`,onError:a,onSaved:o,onCancel:o}),u(ni,{deviceId:e.id,initialLocation:e.location,label:t(`customize.identity.room`),layout:`stacked`,onError:a,onSaved:o,onCancel:o}),u(Yr,{label:t(`customize.identity.hidden`),layout:`stacked`,value:u(wn,{"aria-label":t(`deviceDisplay.hideFromLists`),checked:h,disabled:f.isPending,onChange:t=>f.mutate({deviceId:e.id,display:qa(e.display,t.target.checked)},l)})}),u(Yr,{label:t(`customize.identity.role`),layout:`stacked`,value:Ja(e)?u(`span`,{children:no(e.role,t(`customize.identity.noRole`))}):u(H,{"aria-label":t(`customize.identity.role`),value:e.role??``,disabled:d.isPending,options:[{value:``,label:t(`customize.identity.noRole`)},...eo(e.role,e.type).map(e=>({value:e,label:no(e,t(`customize.identity.noRole`))}))],onChange:t=>d.mutate({deviceId:e.id,role:t.target.value===``?null:t.target.value},l)})})]}),i!==null&&u(`p`,{role:`alert`,className:`mt-2 text-xs text-danger break-words`,children:i})]})}function no(e,t){return e==null||e===``?t:Xa(e)?un(e).label:e}function ro(e,t){if(e.kind!==`known`||typeof t!=`string`||t.length===0)return null;let n=_n(e.value,t),r=new Map(e.value.map(e=>[e.id,e])),i=new Map;for(let e of n){let t=r.get(e)?.parentDeviceId,n=t==null?void 0:r.get(t);n!==void 0&&n.type===`container`&&i.set(e,n.name)}return{location:t,ids:n,containers:i}}function io(e,t,n){return $t(e,t?.ids??new Set,n)}function ao(e,t){return e?.containers.get(t)??null}function oo(e,t){return e===null||t.length===0?e:{...e,ids:new Set([...e.ids].filter(e=>!t.includes(e)))}}function so(e,t,n){return e.kind===`known`?io(e.value,t,n).suggested.length:0}function co(e,t){let n=[t,e.detail].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function lo({location:e,devices:t,action:n,onPick:i,onPickAll:a}){let{t:o}=Z();if(t.length===0)return null;let s=o(`customize.suggest.heading`,{location:e});return r(`section`,{"aria-label":s,className:`flex flex-col gap-1`,children:[r(`div`,{className:`flex min-h-7 items-center gap-2`,children:[u(`h3`,{className:`${f} min-w-0 flex-1`,children:s}),a!==void 0&&t.length>1&&u(G,{variant:`ghost`,size:`sm`,onClick:a,children:o(`customize.suggest.addAll`,{count:t.length})})]}),u(`ul`,{className:`flex flex-col divide-y divide-border rounded-md border border-border`,children:t.map(e=>{let t=co(e,e.container===null||e.name.includes(e.container)?null:o(`customize.suggest.in`,{container:e.container}));return r(`li`,{className:`${_} flex items-center gap-3`,children:[r(`div`,{className:`min-w-0 flex-1`,children:[u(`div`,{className:`text-xs text-foreground break-words`,children:e.name}),t!==null&&u(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t})]}),u(G,{variant:`outline`,size:`sm`,"aria-label":o(n===`add`?`customize.suggest.addNamed`:`customize.suggest.useNamed`,{name:e.name}),onClick:()=>i(e.id),children:o(n===`add`?`customize.suggest.add`:`customize.suggest.use`)})]},e.id)})})]})}n();function uo(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function fo({excludeDeviceIds:e,room:t,onSelect:n}){let{t:a}=Z(),s=Kt({projection:`slim`}),c=s.status===`success`?s.data:null,l=i(()=>{if(c===null)return[];let t=new Set(e);return Si(c).filter(e=>!t.has(e.id))},[c,e]),d=i(()=>new Map(l.map(e=>[e.id,e])),[l]),f=i(()=>io(l,t,e=>e.id),[l,t]),p=i(()=>f.others.map(e=>({id:e.id,name:e.name,type:e.type,...e.location===null?{}:{location:e.location}})),[f.others]);if(s.status===`error`)return u(Ce,{title:a(`customize.picker.devicesFailed`),message:s.error?.message??``});let m=e=>{let t=d.get(e);t!==void 0&&n(t)};return r(o,{children:[t!==null&&u(lo,{location:t.location,devices:f.suggested.map(e=>({id:e.id,name:e.name,container:ao(t,e.id),detail:e.type})),action:`use`,onPick:m}),p.length===0&&f.suggested.length>0?null:u(Ct,{devices:p,listState:uo(s.status),value:[],onChange:e=>{let t=e.at(-1);t!==void 0&&m(t)},noun:`device`,emptyLabel:a(`customize.assign.none`),showAll:!0,testId:`customize-field-device-picker`})]})}function po({open:e,title:t,targetKind:n,excludeDeviceIds:i,room:a=null,confirmLabel:s,extra:l,extraComplete:d=!0,onConfirm:f,onClose:p}){let{t:m}=Z(),[h,g]=c(null),[_,v]=c(null),y=()=>{g(null),v(null),p()};return u(zn,{open:e,onOpenChange:e=>e?void 0:y(),children:r(I,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[u(ne,{children:u(R,{children:t})}),u(Ne,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:e&&r(o,{children:[r(`section`,{"aria-label":m(`customize.assign.stepDevice`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepDevice`)}),h===null?u(fo,{excludeDeviceIds:i,room:a,onSelect:g}):r(`p`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[h.name,u(G,{variant:`ghost`,size:`sm`,onClick:()=>{g(null),v(null)},children:m(`customize.assign.change`)})]})]}),h!==null&&r(`section`,{"aria-label":m(`customize.assign.stepField`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepField`)}),u(bi,{device:h,targetKind:n,selected:_===null?null:{cap:_.cap,path:_.path},onPick:v,onBack:()=>{g(null),v(null)}})]}),h!==null&&l!==void 0&&r(`section`,{"aria-label":m(`customize.assign.stepDetails`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepDetails`)}),l]})]})}),r(Re,{children:[u(G,{variant:`ghost`,onClick:y,children:m(`customize.assign.cancel`)}),u(G,{disabled:_===null||!d,onClick:()=>{_!==null&&(f(_),g(null),v(null))},children:s})]})]})})}function mo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ho(e,t){let n=Pi(e,t);return n===void 0?{kind:`absent`}:{kind:`value`,value:n}}function go(e,t,n){return mo(t)?ho(t,n):e.status===`error`?{kind:`unknown`,reason:e.error?.message??`the value could not be read`}:e.status===`pending`||e.data===void 0?{kind:`pending`}:e.data===null?{kind:`absent`}:ho(e.data,n)}function _o(e,t,n){let r=e?`active`:`muted`;return t.cap===`contact`&&t.path===`entryOpen`?{text:e?n.open:n.closed,tone:r}:hr[t.cap]===t.path?{text:e?n.active:n.inactive,tone:r}:{text:String(e),tone:`normal`}}function vo(e,t,n){switch(e.kind){case`pending`:return{text:`…`,tone:`muted`};case`unknown`:return{text:`?`,title:e.reason,tone:`warning`};case`absent`:return{text:`—`,tone:`muted`};case`value`:{let r=e.value;return r===null?{text:`—`,tone:`muted`}:typeof r==`boolean`?_o(r,t,n):typeof r==`number`?{text:t.path===`percentage`?`${Math.round(r)} %`:String(r),tone:`normal`}:typeof r==`string`?{text:r,tone:`normal`}:{text:JSON.stringify(r),tone:`normal`}}}}var yo=0;function bo(e){let t=S(),n=ge({deviceId:e?.deviceId??yo,capName:e?.cap??``},{enabled:e!==null}),r=vn(t.trpcClient,e?.deviceId??null,e?.cap??``);return e===null?{kind:`absent`}:go({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}},r,e.path)}var xo={muted:`text-foreground-subtle`,active:`text-success`,normal:`text-foreground`,warning:`text-warning`};function So({target:e}){let{t}=Z(),n=bo(e);return e===null?null:u(Co,{display:vo(n,e,{active:t(`customize.assign.value.active`),inactive:t(`customize.assign.value.inactive`),open:t(`customize.assign.value.open`),closed:t(`customize.assign.value.closed`)})})}function Co({display:e}){return u(`span`,{className:`text-xs ${xo[e.tone]}`,title:e.title,children:e.text})}function wo({name:e,detail:t,meta:n,value:i,shown:a,problem:o,onRemove:s,removeLabel:c,busy:l=!1}){return r(`li`,{className:`${_} grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)_1.75rem]`,children:[r(`div`,{className:`min-w-0`,children:[u(`div`,{className:`text-xs text-foreground break-words`,children:e}),t!==null&&u(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t}),o!==void 0&&u(`div`,{role:`alert`,className:`text-[11px] text-warning break-words`,children:o})]}),u(`div`,{className:`row-start-2 col-start-1 text-[11px] text-foreground-subtle empty:hidden sm:row-start-auto sm:col-start-auto sm:empty:block`,children:n}),u(`div`,{className:`row-start-3 col-start-1 empty:hidden sm:row-start-auto sm:col-start-auto sm:empty:block`,children:a===void 0?u(So,{target:i}):a!==null&&u(Co,{display:a})}),u(`div`,{className:`row-start-1 col-start-2 flex justify-end sm:row-start-auto sm:col-start-auto`,children:s!==void 0&&u(Ve,{icon:Rt,variant:`ghost`,size:`sm`,"aria-label":c,disabled:l,onClick:s})})]})}function To({id:e,...t}){return u(Oe,{headingId:`customize-${e}`,...t})}function Eo({id:e,icon:t,title:n,headerControl:i,addLabel:a,onAdd:s,addDisabled:c=!1,notices:l,suggestion:d,children:f}){let{t:p}=Z(),m=s!==void 0&&a!==void 0;return r(To,{id:e,icon:t,title:n,actions:r(o,{children:[i,m&&!c&&d!==void 0&&d.count>0&&r(G,{variant:`ghost`,size:`sm`,onClick:d.onOpen,children:[u(Ee,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),p(`customize.suggest.hint`,{count:d.count,location:d.location})]}),m&&u(G,{variant:`outline`,size:`sm`,disabled:c,onClick:s,children:a})]}),children:[l!==void 0&&u(`div`,{className:`flex flex-col gap-1 px-3 pt-2 empty:hidden sm:px-4`,children:l}),u(`ul`,{className:`flex flex-col divide-y divide-border`,children:f})]})}function Do({availability:e}){let{t}=Z();return e.kind===`pending`?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.assign.checking`)}):e.kind===`unknown`?u(`p`,{role:`alert`,className:`text-xs text-warning`,children:t(`customize.assign.unknown`,{reason:e.reason})}):null}function Oo(e,t){if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};let n=e.data;return e.status===`pending`||n===void 0?{kind:`pending`}:{kind:`known`,value:t(n)}}var ko=[{id:`motion`,labelKey:`customize.assign.filters.motion`,caps:[`motion`]},{id:`contact`,labelKey:`customize.assign.filters.contact`,caps:[`contact`]},{id:`all`,labelKey:`customize.assign.filters.all`,caps:vr}];function Ao(e,t){return t!==null&&e.includes(t)?t:vr.find(t=>e.includes(t))??null}function jo(e,t){let n=[e,t].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function Mo(e,t){if(e.id===t.hostId||e.type===J.Container||t.excludeCameras&&e.isCamera)return!1;let n=X({addonId:e.addonId,stableId:e.stableId});return!t.assigned.has(n)}function No(e){return e.devices.flatMap(t=>{if(!Mo(t,e))return[];let n=e.capIndex.get(t.id)??[],r=Ao(n,e.preferredCap);if(r===null)return[];let i=hr[r];return[{deviceId:t.id,ref:{addonId:t.addonId,stableId:t.stableId},name:t.name,detail:jo(t.integration,t.location),meta:r,caps:n,value:i===void 0?null:{deviceId:t.id,cap:r,path:i}}]}).toSorted((e,t)=>e.name.localeCompare(t.name))}function Po(e,t,n){let r=Bn(t);return e.filter(e=>{if(n!==null&&!e.caps.some(e=>n.caps.includes(e)))return!1;if(r.length===0)return!0;let t=mt({id:e.deviceId,name:e.name,...e.detail===null?{}:{detail:e.detail},...e.meta===null?{}:{type:e.meta}});return r.every(e=>t.includes(e))})}function Fo(e){let t=e.find(e=>e.query.status===`error`);if(t!==void 0)return{kind:`unknown`,reason:t.query.error?.message??`the request failed`};if(e.some(e=>e.query.status!==`success`||e.query.data===void 0))return{kind:`pending`};let n=new Map;for(let t of e)for(let e of t.query.data??[])n.set(e,[...n.get(e)??[],t.cap]);return{kind:`known`,value:n}}function Io(e,t){let n=tn.useQueries(n=>e.map(e=>n.deviceManager.listDeviceIdsByCaps({capNames:[e]},{enabled:t})));return Fo(e.map((e,t)=>{let r=n[t];return{cap:e,query:r===void 0?{status:`pending`}:{status:r.status,data:r.data,error:r.error===null?null:{message:r.error.message}}}}))}n();function Lo(e,t){let n=Qe(e,t);return n.kind===`resolved`?n.integration.name:null}function Ro(e){let t=Kt({projection:`slim`},{enabled:e}),{data:n}=gn(void 0,{enabled:e}),r=t.error===null||t.error===void 0?null:t.error.message;return i(()=>Oo({status:t.status,data:t.data,error:r===null?null:{message:r}},e=>e.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,type:e.type,location:e.location,isCamera:e.isCamera,integration:Lo(e,n),parentDeviceId:e.parentDeviceId,primaryChildEntityId:e.primaryChildEntityId??null,role:e.role??null}))),[t.status,t.data,r,n])}function zo(e){let t=Ro(e.enabled),n=Io(vr,e.enabled);return t.kind===`unknown`?t:n.kind===`unknown`?n:t.kind===`pending`||n.kind===`pending`?{kind:`pending`}:{kind:`known`,value:No({devices:t.value,capIndex:n.value,hostId:e.hostId,excludeCameras:e.excludeCameras,assigned:e.assigned,preferredCap:e.preferredCap})}}n();function Bo(e,t){let n=typeof e==`string`&&e.length>0,r=Ro(t&&n);return i(()=>t?ro(r,e):null,[t,r,e])}function Vo(){let{t:e}=Z(),t=dn();return(n,r)=>t({title:e(`customize.assign.removeConfirm.title`),message:r?`${e(`customize.assign.removeConfirm.message`,{what:n})} ${e(`customize.assign.removeConfirm.last`)}`:e(`customize.assign.removeConfirm.message`,{what:n}),confirmLabel:e(`customize.assign.removeConfirm.confirm`),variant:`danger`})}n();function Ho(e){return e===null?null:Ei(e,`replace`)?`replace`:Ei(e,`add`)?`add`:null}function Uo({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Vo(),[l,d]=c(!1),[f,p]=c(null),m=Ka(t.state),h=zi(m,`battery`),g=Ho(h),_=g===null?null:yi(h?.fields.percentage),v=Ro(_!==null),y=oo(Bo(e.location,n.kind===`present`&&h===null),[e.id]);if(n.kind===`absent`)return null;let b=n.kind===`present`?n.mode:null,x=t.state.kind===`none`||t.state.kind===`present`,S=_===null||v.kind!==`known`?null:v.value.find(e=>X({addonId:e.addonId,stableId:e.stableId})===X(_.source))??null,C=_===null?``:S?.name??X(_.source),w=async e=>{let n=await t.save(e);p(n.kind===`refused`?n.reason:null)},T=async()=>{if(m===null)return;let e=hi(m,`battery`);await s(a(`customize.battery.removeWhat`,{name:C}),e===null)&&await w(e)},E=b!==null&&x&&h===null&&!t.saving;return r(o,{children:[r(Eo,{id:`battery`,icon:Yt,title:a(`customize.battery.title`),addLabel:a(b===`replace`?`customize.battery.replace`:`customize.battery.add`),onAdd:E?()=>d(!0):void 0,...y===null?{}:{suggestion:{count:y.ids.size,location:y.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Do,{availability:n}),_!==null&&v.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:v.reason})}),f!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:f})]}),children:[b===`replace`&&x&&u(wo,{name:a(`customize.battery.native`),detail:null,meta:a(h===null?`customize.assign.native`:`customize.battery.nativeReplaced`),value:h===null?{deviceId:e.id,cap:`battery`,path:`percentage`}:null,removeLabel:``}),h===null&&b===`add`&&x&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)}),_!==null&&u(wo,{name:C,detail:`${_.cap}.${_.fieldPath}`,meta:a(g===`replace`?`customize.assign.replaces`:`customize.assign.adds`),value:S===null?null:{deviceId:S.id,cap:_.cap,path:_.fieldPath},problem:S===null&&v.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:x?()=>void T():void 0,removeLabel:a(`customize.assign.removeNamed`,{name:C}),busy:t.saving}),h!==null&&_===null&&u(wo,{name:a(`customize.battery.otherFormula`),detail:null,meta:u(Wa,{onAdvanced:i}),value:{deviceId:e.id,cap:`battery`,path:`percentage`},removeLabel:``})]}),u(po,{open:l,title:a(b===`replace`?`customize.battery.replace`:`customize.battery.add`),targetKind:`number`,excludeDeviceIds:[e.id],room:y,confirmLabel:a(`customize.assign.add`),onConfirm:e=>{d(!1);let n=b===null?null:Ii({percentage:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},mode:b});n===null?p(a(`customize.assign.pickUnusable`)):w(vi(m,t.target,n))},onClose:()=>d(!1)})]})}n();function Wo(e,t){let n=e.source;if(n===null||t.kind!==`known`)return null;let r=X(n.source);return t.value.find(e=>X({addonId:e.addonId,stableId:e.stableId})===r)??null}function Go(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;return Number.isFinite(t)?t:null}function Ko({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Vo(),[l,d]=c(!1),[f,p]=c(``),[m,h]=c(`percent`),[g,_]=c(null),v=Ka(t.state),y=zi(v,`consumables`),b=wi(y),x=Ro(b.some(e=>e.source!==null)),S=b.flatMap(e=>{let t=Wo(e,x);return t===null?[]:[t.id]}),C=oo(Bo(e.location,n.kind===`present`),[e.id,...S]);if(n.kind===`absent`)return null;let w=t.state.kind===`none`||t.state.kind===`present`,T=n.kind===`present`&&w&&!t.saving,E=Ti(f),D=b.find(e=>e.key===E)??null,O=D!==null,k=f.trim()!==``&&E===``,A=async e=>{let n=await t.save(e);_(n.kind===`refused`?n.reason:null)},j=()=>{d(!1),p(``),h(`percent`)},M=async e=>{if(y===null||v===null)return;let n=Li(y,e.key),r=n===null?hi(v,`consumables`):vi(v,t.target,n);await s(a(`customize.consumables.removeWhat`,{name:e.label}),r===null)&&await A(r)},N=r(`div`,{className:`flex flex-wrap items-end gap-2`,children:[r(`label`,{className:`flex w-full flex-col gap-1 text-[11px] text-foreground-subtle sm:w-56`,children:[a(`customize.consumables.name`),u(W,{"aria-label":a(`customize.consumables.name`),value:f,onChange:e=>p(e.target.value)})]}),r(`label`,{className:`flex w-full flex-col gap-1 text-[11px] text-foreground-subtle sm:w-40`,children:[a(`customize.consumables.unit`),u(H,{"aria-label":a(`customize.consumables.unit`),value:m,options:Oi.map(e=>({value:e,label:a(`customize.consumables.units.${e}`)})),onChange:e=>{let t=Oi.find(t=>t===e.target.value);t!==void 0&&h(t)}})]}),O&&u(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:a(`customize.consumables.takenBy`,{name:D.label})}),k&&u(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:a(`customize.consumables.keyless`)})]});return r(o,{children:[r(Eo,{id:`consumables`,icon:dt,title:a(`customize.consumables.title`),addLabel:a(`customize.consumables.add`),onAdd:T?()=>d(!0):void 0,...C===null?{}:{suggestion:{count:C.ids.size,location:C.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Do,{availability:n}),x.kind===`unknown`&&b.some(e=>e.source!==null)&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:x.reason})}),g!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:g})]}),children:[b.map(e=>{let n=e.source;if(e.unit===null||n===null)return u(wo,{name:e.label,detail:a(`customize.consumables.otherFormula`),meta:u(Wa,{onAdvanced:i}),value:null,removeLabel:``},e.key);let r=Wo(e,x),o=r?.name??X(n.source);return u(wo,{name:e.label,detail:`${a(`customize.consumables.units.${e.unit}`)} · ${o}`,meta:`${n.cap}.${n.fieldPath}`,value:r===null?null:{deviceId:r.id,cap:n.cap,path:n.fieldPath},problem:r===null&&x.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:w?()=>void M(e):void 0,removeLabel:a(`customize.assign.removeNamed`,{name:e.label}),busy:t.saving},e.key)}),b.length===0&&n.kind===`present`&&w&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)})]}),u(po,{open:l,title:a(`customize.consumables.pickTitle`),targetKind:`number`,excludeDeviceIds:[e.id],room:C,confirmLabel:a(`customize.assign.add`),extra:N,extraComplete:E!==``&&!O,onConfirm:e=>{let n=Go(e.value);if(n!==null&&(n<0||m===`percent`&&n>100)){j(),_(a(`customize.consumables.outOfRange`,{value:n}));return}let r=Ci(y,{key:E,label:f,remaining:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},unit:m});j(),r===null?_(a(`customize.assign.pickUnusable`)):A(vi(v,t.target,r))},onClose:j})]})}n();function qo(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function Jo(e){return e.map(e=>({id:e.deviceId,name:e.name,...e.meta===null?{}:{type:e.meta},...e.detail===null?{}:{location:e.detail.includes(` · `)?e.detail.split(` · `).at(-1)??null:e.detail},...e.detail===null?{}:{detail:e.detail}}))}function Yo({open:e,title:t,selection:n,candidates:a,filters:o,room:s=null,confirmLabel:l,onConfirm:f,onClose:p}){let{t:m}=Z(),[h,g]=c(null),[_,v]=c([]),y=o?.find(e=>e.id===h)??o?.[0]??null,b=a.kind===`known`?a.value:[],x=a.kind===`known`?Po(a.value,``,y):[],S=io(b,s,e=>e.deviceId).suggested,C=io(x,s,e=>e.deviceId).others,w=i(()=>Jo(C),[C]),T=qo(a),E=b.filter(e=>_.includes(e.deviceId));d(()=>{e||(v([]),g(null))},[e]);let D=()=>{v([]),g(null),p()},O=e=>{e.length!==0&&(f(e),v([]),g(null))},k=()=>O(E);return u(zn,{open:e,onOpenChange:e=>e?void 0:D(),children:r(I,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[u(ne,{children:u(R,{children:t})}),r(Ne,{className:`flex flex-col gap-2 p-2 sm:p-4`,children:[o!==void 0&&o.length>0&&u(`div`,{className:`flex flex-wrap gap-1`,role:`tablist`,"aria-label":m(`customize.assign.filtersLabel`),children:o.map(e=>u(`button`,{type:`button`,role:`tab`,"aria-selected":(y?.id??null)===e.id,className:`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${(y?.id??null)===e.id?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:bg-surface-hover`}`,onClick:()=>g(e.id),children:m(e.labelKey)},e.id))}),s!==null&&u(lo,{location:s.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:ao(s,e.deviceId),detail:e.detail})),action:`add`,onPick:e=>O(S.filter(t=>t.deviceId===e)),...n===`multi`?{onPickAll:()=>O(S)}:{}}),a.kind===`unknown`?u(`p`,{role:`alert`,className:`text-xs text-warning`,children:m(`customize.assign.unknown`,{reason:a.reason})}):w.length===0&&S.length>0?null:u(Ct,{devices:w,listState:T,value:_,onChange:e=>v(n===`single`?e.length>0?[e[e.length-1]]:[]:e),noun:`device`,emptyLabel:m(`customize.assign.none`),showAll:!0,testId:`customize-device-picker`})]}),r(Re,{children:[u(G,{variant:`ghost`,onClick:D,children:m(`customize.picker.cancel`)}),u(G,{disabled:E.length===0,onClick:k,children:l(E.length)})]})]})})}function Xo(e){if(e===null)return[];let t=ki(e);return Mi(e).map(e=>{let n=X(e);return{key:n,ref:e,caps:t.filter(e=>X(e.source)===n).map(e=>e.cap)}})}function Zo(e,t){let n=ki(e);if(n.length===0)return!1;let{enabled:r,...i}=e,{enabled:a,...o}=Mr({camera:t,sources:n,enabled:!0});return Ri(i,o)}function Qo(e){return e?.enabled!==!1}function $o(e,t,n){let r=[...e===null?[]:ki(e),...n.flatMap(e=>Rr(e.ref,e.caps))];return r.length===0?null:Mr({camera:t,sources:r,enabled:Qo(e)})}function es(e,t,n){let r=ki(e).filter(e=>X(e.source)!==n);return r.length===0?null:Mr({camera:t,sources:r,enabled:Qo(e)})}function ts(e,t){return{...e,enabled:t}}n();function ns({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Vo(),[l,d]=c(!1),[f,p]=c(null),m=Ka(t.state),h=zi(m,`doorbell`),g=h===null||Zo(h,t.target),_=g?Xo(h):[],v=Ro(_.length>0),y=n.kind===`present`&&g,b=Bo(e.location,y),x=zo({hostId:e.id,excludeCameras:!1,assigned:new Set(_.map(e=>e.key)),preferredCap:null,enabled:l||b!==null});if(n.kind===`absent`)return null;let S=t.state.kind===`none`||t.state.kind===`present`,C=S&&!t.saving,w=n.kind===`present`&&C&&g,T=async e=>{let n=e===null?m===null?null:hi(m,`doorbell`):vi(m,t.target,e),r=await t.save(n);p(r.kind===`refused`?r.reason:null)},E=async(e,n)=>{if(h===null||m===null)return;let r=es(h,t.target,e.key),i=r===null&&hi(m,`doorbell`)===null;await s(a(`customize.doorbell.removeWhat`,{name:n}),i)&&await T(r)},D=e=>v.kind===`known`?v.value.find(t=>X({addonId:t.addonId,stableId:t.stableId})===e.key)??null:null;return r(o,{children:[r(Eo,{id:`doorbell`,icon:wt,title:a(`customize.doorbell.title`),headerControl:h===null?void 0:r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground`,children:[u(wn,{"aria-label":a(`customize.doorbell.active`),checked:h.enabled!==!1,disabled:!C,onChange:e=>void T(ts(h,e.target.checked))}),a(`customize.doorbell.active`)]}),addLabel:a(`customize.doorbell.add`),onAdd:w?()=>d(!0):void 0,...b===null?{}:{suggestion:{count:so(x,b,e=>e.deviceId),location:b.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Do,{availability:n}),v.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:v.reason})}),f!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:f})]}),children:[_.map(e=>{let n=D(e),r=n?.name??e.key,i=Ao(e.caps,null),o=i===null?void 0:hr[i];return u(wo,{name:r,detail:n===null?null:jo(n.integration,n.location),meta:e.caps.join(`, `),value:n!==null&&i!==null&&o!==void 0?{deviceId:n.id,cap:i,path:o}:null,problem:n===null&&v.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:S?()=>void E(e,r):void 0,removeLabel:a(`customize.assign.removeNamed`,{name:r}),busy:t.saving},e.key)}),!g&&u(wo,{name:a(`customize.doorbell.otherFormula`),detail:null,meta:u(Wa,{onAdvanced:i}),value:null,removeLabel:``}),h===null&&n.kind===`present`&&S&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)})]}),u(Yo,{open:l,title:a(`customize.doorbell.pickTitle`),selection:`multi`,candidates:x,room:b,confirmLabel:e=>a(`customize.assign.addCount`,{count:e}),onConfirm:e=>{d(!1),T($o(h,t.target,e.map(e=>({ref:e.ref,caps:e.caps}))))},onClose:()=>d(!1)})]})}function rs(e){return e.slot===`linked-devices`}function is(e){if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};if(e.status===`pending`||e.data===void 0)return{kind:`pending`};for(let t of e.data)if(t.state===`ok`&&t.slot===`linked-devices`&&rs(t.value))return{kind:`present`,slot:t,value:t.value};let t=e.data.find(e=>e.state===`unreachable`);return t!==void 0&&t.state===`unreachable`?{kind:`unknown`,reason:t.reason}:{kind:`absent`}}function as(e,t){let n=t.trackedDeviceIds??[],r=e=>t=>({deviceId:t.deviceId,name:t.name,health:t.health,implied:e,tracked:n.includes(t.deviceId)});return[...e.sources.map(r(!1)),...(e.impliedSources??[]).map(r(!0))]}function os(e,t){let n=new Set([...e.sources,...e.impliedSources??[]].map(e=>e.deviceId));return(t.trackedDeviceIds??[]).filter(e=>!n.has(e))}function ss(e,t){return{...e,deviceIds:[...e.deviceIds,...t.filter(t=>!e.deviceIds.includes(t))]}}function cs(e,t){return{...e,deviceIds:e.deviceIds.filter(e=>e!==t),...e.trackedDeviceIds===void 0?{}:{trackedDeviceIds:e.trackedDeviceIds.filter(e=>e!==t)}}}function ls(e,t,n){let r=e.trackedDeviceIds??[],i=n?[...r.filter(e=>e!==t),t]:r.filter(e=>e!==t);return{...e,trackedDeviceIds:i}}function us(e,t,n){return e.flatMap(e=>{let r=t.get(e.deviceId);return n.has(e.deviceId)||r===void 0?[]:[{deviceId:e.deviceId,ref:{addonId:r.addonId,stableId:r.stableId},name:e.parentName===null?e.name:`${e.parentName} · ${e.name}`,detail:jo(r.integration,e.location),meta:e.type,caps:[],value:null}]})}n();function ds(e){return e==null?null:e.message}function fs({device:e}){let{t}=Z(),n=s(),i=Vo(),a=yr.includes(e.type),[l,d]=c(!1),[f,p]=c(!1),[m,h]=c(null),g=je({deviceId:e.id},{enabled:a}),_=is({status:g.status,data:g.data,error:ds(g.error)===null?null:{message:ds(g.error)??``}}),v=_.kind===`present`?_.slot.slotRef:``,y=_.kind===`present`?[...as(_.slot,_.value).map(e=>e.deviceId),...os(_.slot,_.value)]:[],b=Un(),x=Ro(a&&_.kind===`present`&&(l||y.length>0)),S=Bo(e.location,a&&_.kind===`present`),C=_e({deviceId:e.id,slotRef:v},{enabled:(l||S!==null)&&_.kind===`present`});if(!a||_.kind===`absent`)return null;if(_.kind!==`present`)return u(Eo,{id:`linked`,icon:Nn,title:t(`customize.linked.title`),notices:_.kind===`pending`?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.assign.checking`)}):u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:t(`customize.assign.unknown`,{reason:_.reason})}),children:null});let w=_.value,T=new Map(x.kind===`known`?x.value.map(e=>[e.id,e]):[]),E=w.trackedDeviceIds!==void 0,D=(e,t)=>{let n=T.get(e.deviceId);return{...e,name:e.name??n?.name??null,type:n?.type??null,detail:n===void 0?null:jo(n.integration,n.location),orphan:t}},O=[...as(_.slot,w).map(e=>D(e,!1)),...os(_.slot,w).map(e=>D({deviceId:e,name:null,health:`ok`,implied:!1,tracked:!0},!0))],k=new Set(y),A=x.kind===`unknown`?x:C.status===`error`?{kind:`unknown`,reason:ds(C.error)??`the request failed`}:x.kind===`pending`||C.status===`pending`||C.data===void 0?{kind:`pending`}:{kind:`known`,value:us(C.data.candidates,T,k)},j=async r=>{if(f){h(t(`customize.saveInFlight`));return}p(!0),h(null);try{await b.mutateAsync({deviceId:e.id,slotRef:_.slot.slotRef,value:r}),await g.refetch(),await n.invalidateQueries({queryKey:[[`deviceManager`]]})}catch(e){h(e instanceof Error?e.message:String(e))}finally{p(!1)}},M=async e=>{await i(t(`customize.linked.removeWhat`,{name:e.name??`#${e.deviceId}`}),!1)&&await j(cs(w,e.deviceId))},N=[{key:`device`,header:t(`customize.linked.device`),cell:e=>r(`div`,{className:`flex flex-col min-w-0`,children:[u(`span`,{className:`truncate text-xs text-foreground`,children:e.name??`#${e.deviceId}`}),e.detail!==null&&u(`span`,{className:`truncate text-[11px] text-foreground-subtle`,children:e.detail}),e.orphan&&u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t(`customize.linked.notLinked`)}),e.health!==`ok`&&u(`span`,{role:`alert`,className:`text-[11px] text-warning`,children:t(`customize.linked.health.${e.health}`)})]})},{key:`type`,header:t(`customize.linked.type`),headerClassName:`hidden sm:table-cell`,cellClassName:`hidden sm:table-cell text-xs text-foreground-subtle`,cell:e=>e.type===null?`—`:$e(e.type).label},{key:`controls`,header:t(`customize.linked.controls`),headerClassName:`hidden md:table-cell`,cellClassName:`hidden md:table-cell text-xs text-foreground-subtle`,cell:e=>e.orphan?`—`:t(`customize.linked.yes`)},...E?[{key:`tracked`,header:t(`customize.linked.tracked`),cellClassName:`text-right`,headerClassName:`text-right`,cell:e=>u(Dt,{checked:e.tracked,disabled:f,"aria-label":t(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void j(ls(w,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:u(Ve,{icon:Rt,variant:`ghost`,size:`sm`,"aria-label":t(`customize.assign.removeNamed`,{name:e.name??e.deviceId}),disabled:f,onClick:t=>{t.stopPropagation(),M(e)}})}];return r(o,{children:[u(Eo,{id:`linked`,icon:Nn,title:t(`customize.linked.title`),addLabel:t(`customize.linked.add`),onAdd:f?void 0:()=>d(!0),...S===null?{}:{suggestion:{count:so(A,S,e=>e.deviceId),location:S.location,onOpen:()=>d(!0)}},notices:r(o,{children:[x.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:t(`customize.assign.devicesUnreadable`,{reason:x.reason})}),m!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:m})]}),children:r(`li`,{className:`list-none px-3 py-2 sm:px-4`,children:[O.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`customize.assign.none`)}):u(cn,{mode:`generic`,items:O,getKey:e=>String(e.deviceId),getSearchText:e=>[e.name??``,e.detail??``,e.type??``,String(e.deviceId)].join(` `),getFilterType:e=>e.type===null?null:$e(e.type).label,columns:N,searchPlaceholder:t(`customize.assign.search`),emptyLabel:t(`customize.assign.none`)}),O.some(e=>!e.orphan)&&u(`p`,{className:`mt-2 text-[10px] text-foreground-subtle`,children:t(`customize.linked.controlsAlways`)}),E&&u(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:t(`customize.linked.trackedHint`)})]})}),u(Yo,{open:l,title:t(`customize.linked.pickTitle`),selection:`multi`,candidates:A,room:S,confirmLabel:e=>t(`customize.assign.addCount`,{count:e}),onConfirm:e=>{d(!1),j(ss(w,e.map(e=>e.deviceId)))},onClose:()=>d(!1)})]})}function ps(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.sensors:[]}function ms(e){return{addonId:e.addonId,stableId:e.stableId,mode:e.mode}}function hs(e){return e.length===0?null:{sensors:[...e]}}function gs(e,t){let n=new Set(e.map(mr));return hs([...e.map(ms),...t.filter(e=>!n.has(mr(e))).map(e=>({...e,mode:_r}))])}function _s(e,t,n){return hs(e.map(e=>mr(e)===t?{...ms(e),mode:n}:ms(e)))}function vs(e,t){return hs(e.filter(e=>mr(e)!==t).map(ms))}function ys(e){return e?.state===`configured`&&e.cameraMotion!==void 0}function bs(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.cameraMotion??`always`:`always`}function xs(e){return e===null||e.state===`unreadable`?!1:e.state===`not-configured`||ys(e)}function Ss(e){return e?.state===`configured`&&(e.notForwarded!==void 0||e.notEnforced!==void 0)}function Cs(e,t,n){if(e!==`present`||t===null||n)return{kind:`none`};let r=t.cameraLevel;return r===void 0?{kind:`unknown`}:{kind:`level`,detected:r.detected,atMs:r.atMs}}n();var ws=5e3;function Ts(e){return e.state===`missing`||e.state===`unreadable`?e.stableId:e.name}function Es({device:e,availability:n,sensors:i}){let{t:a}=Z(),s=Vo(),l=K(),[f,p]=c(!1),[m,h]=c(null),g=t(!1),[_,v]=c(!1),[y,b]=c(!1),x=i.status,S=t(i.refetch);S.current=i.refetch,d(()=>{let e=setInterval(()=>{g.current||S.current()},ws);return()=>clearInterval(e)},[]);let C=ps(x);d(()=>{x!==null&&b(!1)},[x]);let w=i.presence===`present`&&xs(x)&&!y?C:null,T=Ro(C!==null&&C.length>0),E=Bo(e.location,w!==null&&n.kind===`present`),D=zo({hostId:e.id,excludeCameras:!0,assigned:new Set((C??[]).map(mr)),preferredCap:`motion`,enabled:f||E!==null});if(n.kind===`absent`)return null;let O=ys(x),k=Ss(x)?`passes`:bs(x),A=Cs(i.presence,x,y),j=A.kind===`none`?null:A.kind===`unknown`?{text:`?`,tone:`warning`,title:a(`customize.motion.cameraLevelUnknown`)}:{text:a(A.detected?`customize.assign.value.active`:`customize.assign.value.inactive`),tone:A.detected?`active`:`muted`,title:a(`customize.motion.cameraLevelOwn`,{at:new Date(A.atMs).toLocaleTimeString()})},M=_||l.isPending,N=async t=>{if(g.current){h(a(`customize.saveInFlight`));return}g.current=!0,v(!0);try{await l.mutateAsync({deviceId:e.id,config:t}),h(null),await i.refetch()===`failed`&&b(!0)}catch(e){h(e instanceof Error?e.message:String(e))}finally{g.current=!1,v(!1)}},ee=async e=>{w!==null&&await s(a(`customize.motion.removeWhat`,{name:Ts(e)}),!1)&&await N(vs(w,mr(e)))},P=e=>{if(T.kind!==`known`||!(`deviceId`in e))return null;let t=T.value.find(t=>t.id===e.deviceId);return t===void 0?null:jo(t.integration,t.location)};return r(o,{children:[r(Eo,{id:`motion`,icon:Ie,title:a(`customize.motion.title`),addLabel:a(`customize.motion.add`),onAdd:w!==null&&n.kind===`present`?()=>p(!0):void 0,addDisabled:M,...E===null?{}:{suggestion:{count:so(D,E,e=>e.deviceId),location:E.location,onOpen:()=>p(!0)}},notices:r(o,{children:[u(Do,{availability:n}),i.presence===`pending`&&n.kind!==`pending`&&u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:a(`customize.motion.reading`)}),x?.state===`unreadable`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.motion.unreadable`,{reason:x.reason})}),x?.state===`configured`&&!xs(x)&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.olderOrchestrator`)}),y&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.refetchFailed`)}),x?.state===`configured`&&x.notForwarded!==void 0&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.notForwarded.${x.notForwarded}`)}),x?.state===`configured`&&x.notEnforced!==void 0&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.notEnforced`)}),T.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:T.reason})}),m!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:m})]}),children:[u(wo,{name:a(`customize.motion.camera`),detail:null,meta:k===null?a(`customize.assign.native`):`${a(`customize.motion.cameraState.${k}`)} · ${a(`customize.assign.native`)}`,value:null,shown:j,removeLabel:``}),(C??[]).map(e=>{let t=mr(e),n=Ts(e),r=e.state===`ready`?Ao(e.caps,`motion`):null,i=r===null?void 0:hr[r];return u(wo,{name:n,detail:P(e),meta:O&&w!==null?u(H,{"aria-label":a(`customize.motion.modeFor`,{name:n}),value:e.mode,disabled:M,options:gr.options.map(e=>({value:e,label:a(`customize.motion.mode.${e}`)})),onChange:e=>{let n=gr.safeParse(e.target.value);n.success&&w!==null&&N(_s(w,t,n.data))}}):a(`customize.motion.mode.${e.mode}`),value:r!==null&&i!==void 0&&`deviceId`in e?{deviceId:e.deviceId,cap:r,path:i}:null,problem:e.state===`ready`?void 0:e.reason===e.state?a(`customize.motion.state.${e.state}`):`${a(`customize.motion.state.${e.state}`)}: ${e.reason}`,onRemove:w===null?void 0:()=>void ee(e),removeLabel:a(`customize.assign.removeNamed`,{name:n}),busy:M},t)})]}),u(Yo,{open:f,title:a(`customize.motion.pickTitle`),selection:`multi`,candidates:D,room:E,filters:ko,confirmLabel:e=>a(`customize.assign.addCount`,{count:e}),onConfirm:e=>{if(p(!1),w===null)return;let t=gs(w,e.map(e=>e.ref));if(t!==null&&t.sensors.length>8){h(a(`customize.motion.tooMany`,{max:8}));return}N(t)},onClose:()=>p(!1)})]})}var Ds={"numeric-sensor":{fieldPath:`value`,unitField:`unit`},"temperature-sensor":{fieldPath:`celsius`,unitField:`unit`},"humidity-sensor":{fieldPath:`percent`,unitField:`unit`},"pressure-sensor":{fieldPath:`hpa`,unitField:`unit`},"ambient-light-sensor":{fieldPath:`lux`,unitField:`unit`}},Os=new Set([J.Camera]);function ks(e){return e.unitField===null?[e.fieldPath]:[e.fieldPath,e.unitField]}function As(e,t){if(Os.has(e))return{kind:`absent`};let n=null;for(let[e,r]of Object.entries(Ds))if(t.has(e)){n={cap:e,fieldPath:r.fieldPath,unitField:r.unitField};break}let r=null;for(let e of Ir)if(t.has(e)){let t=hr[e];if(t!==void 0){r={cap:e,fieldPath:t};break}}return n===null&&r===null?{kind:`absent`}:{kind:`present`,convert:n,invert:r}}function js(e){return Pr(e.from,e.to)?Ar(e):null}function Ms(e){return xr(e)}var Ns=/^convert\(v,\s*"[^"]*",\s*"[^"]*"\)$/;function Ps(e){return e!==void 0&&Ns.test(e.expr)}function Fs(e){return e===void 0||e.expr===`!v`||Ns.test(e.expr)?!1:e.bindings.v!==void 0}function Is(e){let t=e.expr.trim();if(t===``)return{kind:`refused`,reason:`expression is empty`};let n={kind:`expression`,expr:t,bindings:{v:{kind:`from`,source:e.self,cap:e.cap,fieldPath:e.fieldPath}}},r=Dr({source:n,now:Date.now(),read:()=>({state:`fresh`,value:e.probe})});return r.state===`unavailable`?{kind:`refused`,reason:r.reason}:{kind:`ok`,feature:{kind:`fields`,cap:e.cap,fields:{[e.fieldPath]:n}}}}function Ls(e,t,n){if(e===null)return null;let r=zi(e,n.cap);if(r===null)return e;let i=new Set(ks(n)),a=Object.fromEntries(Object.entries(r.fields).filter(([e])=>!i.has(e)));return Object.keys(a).length===0?hi(e,n.cap):vi(e,t,{kind:`fields`,cap:n.cap,...r.enabled===void 0?{}:{enabled:r.enabled},fields:a,...r.items===void 0?{}:{items:r.items}})}n();function Rs(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`unit`);return typeof t==`string`?t:void 0}function zs(e,t){if(typeof e!=`object`||!e)return;let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Bs(e,t){let n=zi(e,t.cap);if(n===null)return;let r=n.fields[t.fieldPath];return r!==void 0&&r.kind===`expression`?r:void 0}function Vs(e,t){let n=Bs(e,t);return n===void 0||!Ps(n)?null:/^convert\(v,\s*"[^"]*",\s*"([^"]*)"\)$/.exec(n.expr)?.[1]??null}function Hs(e,t){let n=Bs(e,t);return n===void 0||!Fs(n)?null:n.expr}function Us(e,t,n){let r=zi(e,t);if(r===null)return!1;let i=r.fields[n];return i!==void 0&&i.kind===`expression`&&i.expr===`!v`}function Ws(e){return typeof e==`number`||typeof e==`boolean`||typeof e==`string`?String(e):e===null?`null`:JSON.stringify(e)}function Gs({device:e,target:t,handle:n,facts:i}){let{t:a}=Z(),o=S(),[s,l]=c(null),[d,f]=c(``),[h,g]=c(null),_=i.nativeCaps.kind===`known`?i.nativeCaps.value:null,v=_===null?null:As(e.type,_),y=v?.kind===`present`?v.convert?.cap??``:``,b=vn(o.trpcClient,e.id,y);if(i.nativeCaps.kind===`pending`)return u(`section`,{className:`${p} ${m}`,children:u(Do,{availability:{kind:`pending`}})});if(i.nativeCaps.kind===`unknown`)return u(`section`,{className:`${p} ${m}`,children:u(Do,{availability:{kind:`unknown`,reason:i.nativeCaps.reason}})});if(v===null||v.kind===`absent`)return null;let x=Ka(n.state),C=v.convert,w=v.invert,T=C===null?void 0:Rs(b),E=T===void 0?void 0:Lr(T)??T,D=E===void 0?void 0:kr(E),O=C===null?null:Vs(x,C),k=C===null?null:Hs(x,C),A=h??k??``,j=w===null?!1:Us(x,w.cap,w.fieldPath),M=n.state.kind===`none`||n.state.kind===`present`,N=C===null?0:zs(b,C.fieldPath)??0,ee=C!==null&&A.trim()!==``?{kind:`expression`,expr:A.trim(),bindings:{v:{kind:`from`,source:t,cap:C.cap,fieldPath:C.fieldPath}}}:null,P=ee===null||C===null?null:Ai(ee,new Map([[Cr(t,C.cap),b===void 0?{kind:`pending`}:{kind:`value`,slice:b}]]),Date.now()),F=async e=>{let t=await n.save(e);l(t.kind===`refused`?t.reason:null)},te=async()=>{if(C===null||E===void 0||d===``)return;let e=js({self:t,cap:C.cap,fieldPath:C.fieldPath,from:E,to:d,unitField:C.unitField});if(e===null){l(a(`customize.numericTransforms.convertRefused`));return}g(null),await F(vi(x,t,e))},I=async()=>{C!==null&&(await F(Ls(x,t,C)),f(``))},L=async()=>{if(C===null)return;let e=Is({self:t,cap:C.cap,fieldPath:C.fieldPath,expr:A,probe:N});if(e.kind===`refused`){l(e.reason);return}f(``),await F(vi(x,t,e.feature))},R=async()=>{C!==null&&(await F(Ls(x,t,C)),g(``))},z=async()=>{if(w===null)return;let e=Ms({self:t,cap:w.cap});if(e===null){l(a(`customize.numericTransforms.invertRefused`));return}await F(vi(x,t,e))},B=async()=>{w===null||x===null||await F(hi(x,w.cap))};return u(To,{id:`numeric-transforms`,icon:Hi,title:a(`customize.numericTransforms.title`),testId:`numeric-transforms-card`,children:r(`div`,{className:`${m} flex flex-col gap-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.blurb`)}),s!==null&&u(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:s}),C!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-convert`,children:[u(`label`,{className:`text-[11px] font-medium text-foreground`,children:a(`customize.numericTransforms.publishUnit`)}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:E===void 0?a(`customize.numericTransforms.fromUnknown`):a(`customize.numericTransforms.fromUnit`,{unit:E})}),u(`div`,{className:`w-full sm:max-w-xs`,children:u(Gt,{dimension:D,value:d===``?O??``:d,onChange:e=>{f(e),e!==``&&g(``)},disabled:!M||n.saving||E===void 0,"aria-label":a(`customize.numericTransforms.toUnit`),inheritLabel:a(`customize.numericTransforms.pickUnit`),emptyReason:a(`customize.numericTransforms.fromUnknown`)})}),r(`div`,{className:`flex flex-wrap gap-2`,children:[u(G,{size:`sm`,disabled:!M||n.saving||E===void 0||d===``||d===E,onClick:()=>void te(),children:a(`customize.numericTransforms.applyConvert`)}),O!==null&&u(G,{size:`sm`,variant:`outline`,disabled:!M||n.saving,onClick:()=>void I(),children:a(`customize.numericTransforms.clearConvert`)})]})]}),C!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-script`,children:[u(Ni,{label:a(`customize.numericTransforms.script`),value:A,bindings:[`v`],onChange:e=>{g(e),e.trim()!==``&&f(``)}}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.scriptBlurb`)}),P!==null&&u(`p`,{role:`status`,className:`text-[11px] font-mono text-foreground`,"data-testid":`numeric-script-preview`,children:P.kind===`value`?a(`customize.numericTransforms.preview`,{source:Ws(N),result:Ws(P.value)}):P.kind===`waiting`?a(`customize.numericTransforms.previewWaiting`):P.kind===`unavailable`?a(`customize.numericTransforms.previewError`,{reason:P.reason}):a(`customize.numericTransforms.previewRuntimeOnly`)}),r(`div`,{className:`flex flex-wrap gap-2`,children:[u(G,{size:`sm`,disabled:!M||n.saving||A.trim()===``,onClick:()=>void L(),children:a(`customize.numericTransforms.applyScript`)}),k!==null&&u(G,{size:`sm`,variant:`outline`,disabled:!M||n.saving,onClick:()=>void R(),children:a(`customize.numericTransforms.clearScript`)})]})]}),w!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-invert`,children:[u(`label`,{className:`text-[11px] font-medium text-foreground`,children:a(`customize.numericTransforms.invert`)}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.invertBlurb`)}),u(`div`,{className:`flex flex-wrap gap-2`,children:j?u(G,{size:`sm`,variant:`outline`,disabled:!M||n.saving,onClick:()=>void B(),children:a(`customize.numericTransforms.clearInvert`)}):u(G,{size:`sm`,disabled:!M||n.saving,onClick:()=>void z(),children:a(`customize.numericTransforms.applyInvert`)})})]})]})})}n();function Ks(e){return e instanceof Error?e.message:String(e)}function qs(e){let n=Le({addonId:e.addonId,stableId:e.stableId}),r=ht(),i=Vt(),a=Rn(),o=Ga({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}}),{t:s}=Z(),l=t(!1),[u,d]=c(!1),f=async e=>{let t=xi(o,e);try{switch(t.kind){case`refused`:return{kind:`refused`,reason:t.reason};case`noop`:return{kind:`saved`};case`create`:await r.mutateAsync({block:t.input});break;case`update`:await i.mutateAsync({blockId:t.blockId,expectedUpdatedAt:t.expectedUpdatedAt,block:{composition:t.composition}});break;case`delete`:await a.mutateAsync({blockId:t.blockId});break}return await n.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Ks(e)}}};return{target:e,state:o,saving:u||r.isPending||i.isPending||a.isPending,save:async e=>{if(l.current)return{kind:`refused`,reason:s(`customize.saveInFlight`)};l.current=!0,d(!0);try{return await f(e)}finally{l.current=!1,d(!1)}}}}var Js=`pipeline-orchestrator`;function Ys(e){return e.status===`pending`?`pending`:e.status===`error`?`unknown`:e.data===void 0?`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function Xs(e,t){return e===`absent`?`absent`:Ys(t)}async function Zs(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function Qs(e,t){let n=ve(Js),r=L({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>Zs(r.refetch);return t?{presence:Xs(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,refetch:i}:{presence:`absent`,status:null,refetch:i}}function $s(e,t){let n=B({deviceType:e.type}),r=Zt({deviceId:e.id}),i=vt({deviceId:e.id}),a=Oo(n,e=>new Set(e.caps.map(e=>e.cap))),o=Oo(r,e=>za(e.entries)),s=Oo(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}var ec={kind:`unknown`,reason:`the composer reports no value for this field`};function tc(e,t){let n=X(e);return t.get(n)??n}function nc(e,t,n){let r=n.nativeCaps.has(e.cap)?`replaced`:`added`,i=t.filter(t=>t.cap===e.cap&&t.origin===`composed`);if(e.cap===`doorbell`){let t=Mi(e).map(e=>tc(e,n.sourceNames)).join(` + `),a=i.find(e=>e.field===`lastPressedAt`);return[{key:`doorbell`,label:`doorbell`,origin:{kind:r,from:t},value:a?.value??ec}]}return e.cap===`consumables`?wi(e).map(e=>{let t=t=>Hr(Fr,e.key,t),a=i.find(e=>e.field===t(`level`)||e.field===t(`remaining.value`)),o=e.source===null?``:tc(e.source.source,n.sourceNames);return{key:`consumables.${e.key}`,label:`consumables · ${e.label}`,origin:{kind:r,from:o},value:a?.value??ec}}):i.map(e=>({key:e.key,label:`${e.cap}.${e.field}`,origin:{kind:r,from:e.from},value:e.value}))}function rc(e){let t=Di({composition:e.composition,nativeCaps:e.nativeCaps,state:e.state,nativeFields:new Map,snapshot:null,sourceNames:e.sourceNames});return e.composition.features.flatMap(n=>n.kind===`fields`?nc(n,t,e):[])}function ic(e,t){if(e?.state!==`configured`||e.sensors.length===0)return null;let n=e.cameraMotion===`never`?[]:[t.camera],r=e.sensors.map(e=>t.sensor(e.state===`missing`||e.state===`unreadable`?e.stableId:e.name,e.mode));return[...n,...r].join(` + `)}var ac=`${_} grid grid-cols-1 gap-x-3 gap-y-0.5 items-baseline sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_minmax(0,1.5fr)]`,oc=`font-mono text-[11px] text-foreground break-words`,sc=`text-[11px] text-foreground-subtle break-words`,cc=`text-[11px] break-words sm:text-right`;function lc({device:e,composition:t,state:n,nativeCaps:i,cameraSensors:a}){let{t:o}=Z(),s=t!==null&&n!==null,c=Ro(s),l=new Map(c.kind===`known`?c.value.map(e=>[X({addonId:e.addonId,stableId:e.stableId}),e.name]):[]),d=s&&i.kind===`known`?rc({composition:t,nativeCaps:i.value,state:n,sourceNames:l}):[],f=s&&i.kind===`known`&&d.length===0&&t.features.length>0,p=ic(a,{camera:o(`customize.changes.motion.camera`),sensor:(e,t)=>o(`customize.changes.motion.${t}`,{name:e})}),m=s&&i.kind!==`known`;return d.length===0&&p===null&&!m&&!f?null:r(To,{id:`changes`,icon:st,title:o(`customize.changes.title`),children:[m&&u(`p`,{role:i.kind===`unknown`?`alert`:`status`,className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:i.kind===`unknown`?o(`customize.changes.unknown`,{reason:i.reason}):o(`customize.changes.reading`)}),f&&u(`p`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:o(`customize.changes.noRows`)}),r(`ul`,{className:`divide-y divide-border`,children:[d.map(e=>r(`li`,{className:ac,children:[u(`span`,{className:oc,children:e.label}),u(`span`,{className:sc,children:c.kind===`known`?o(`customize.changes.origin.${e.origin.kind}`,{from:e.origin.from}):o(`customize.changes.originUnread.${c.kind}`,{kind:o(`customize.changes.kind.${e.origin.kind}`),reason:c.kind===`unknown`?c.reason:``})}),u(`span`,{className:cc,children:u(uc,{value:e.value})})]},e.key)),p!==null&&r(`li`,{className:ac,children:[u(`span`,{className:oc,children:`motion`}),u(`span`,{className:sc,children:p}),u(`span`,{className:cc,children:u(So,{target:{deviceId:e.id,cap:`motion`,path:`detected`}})})]})]})]})}function uc({value:e}){let{t}=Z();switch(e.kind){case`value`:return r(`span`,{children:[ji(e.value,!0),e.staleReason!==null&&r(`span`,{className:`text-warning`,children:[` `,`·`,` `,t(`customize.changes.value.stale`,{reason:e.staleReason})]})]});case`unavailable`:return u(`span`,{className:`text-warning`,children:t(`customize.changes.value.unavailable`,{reason:e.reason})});case`unknown`:return u(`span`,{className:`text-foreground-subtle`,children:t(`customize.changes.value.unknown`,{reason:e.reason})});case`off`:return u(`span`,{className:`text-foreground-subtle`,children:t(`customize.status.off`)})}}n();function dc({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=Z(),i=ut({deviceId:e}),a=i.data;return a==null?i.status===`error`?u(Ce,{title:r(`customize.deviceUnreadable`),message:i.error?.message??``,onRetry:()=>void i.refetch()}):a===null?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.noSuchDevice`,{deviceId:e})}):u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.loadingDevice`)}):a.addonId===`composer`?u(fc,{device:a}):u(pc,{device:a,target:{addonId:a.addonId,stableId:a.stableId},activeSubTab:t,onSubTabChange:n})}function fc({device:e}){let{t}=Z(),n=e.stableId.startsWith(`composed-`)?e.stableId.slice(Tr.length):null;return r(`section`,{className:`${p} ${m} flex flex-col gap-2`,children:[u(`p`,{className:`text-xs text-foreground`,children:t(`customize.composed.body`)}),n!==null&&u(ai,{className:`text-[11px] text-primary hover:underline`,to:fi(n),children:t(`customize.composed.edit`)})]})}function pc({device:e,target:t,activeSubTab:n,onSubTabChange:i}){let a=qs(t),o=ve(`composer`),{t:s}=Z(),c=Qs(e.id,e.type===J.Camera),l=$s(e,Ka(a.state)),d={deviceType:e.type,composable:l.composable,nativeCaps:l.nativeCaps,cameraSensors:c.presence},f=()=>i(si),p=a.state.kind===`none`||a.state.kind===`present`;return n===`advanced`?r(`div`,{className:`flex flex-col gap-3`,children:[u(hc,{state:a.state}),p&&u(mc,{device:e,target:t,handle:a,facts:l,onDone:()=>i(`main`)})]}):r(`div`,{className:`flex flex-col gap-3`,children:[u(to,{device:e}),o===`absent`&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:s(`customize.composerAbsent`)}),a.state.kind!==`none`&&u(hc,{state:a.state}),u(ns,{device:e,handle:a,availability:Ua(`doorbell`,d),onAdvanced:f}),u(Es,{device:e,handle:a,availability:Ua(`motion`,d),sensors:c}),u(Uo,{device:e,handle:a,availability:Ua(`battery`,d),onAdvanced:f}),u(Ko,{device:e,handle:a,availability:Ua(`consumables`,d),onAdvanced:f}),u(Gs,{device:e,target:t,handle:a,facts:l}),u(fs,{device:e}),u(lc,{device:e,composition:Ka(a.state),state:a.state.kind===`present`?a.state.view.state:null,nativeCaps:l.nativeCaps,cameraSensors:c.status}),r(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[p?u(Wa,{onAdvanced:f}):u(`span`,{}),u(gc,{handle:a})]})]})}function mc({device:e,target:t,handle:n,facts:r,onDone:i}){let a=n.state.kind===`present`?n.state:null;return u(Fi,{initial:a===null?gi(t):_i(a.composition,``),blockId:a===null?null:a.view.block.id,deviceType:e.type,targetName:e.name,nativeCaps:r.nativeCaps,targetFields:r.wireable,onCancel:i,save:async e=>{let t=await n.save(e);return t.kind===`saved`&&i(),t}})}function hc({state:e}){let{t}=Z();switch(e.kind){case`pending`:return u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.pending`)});case`unknown`:return u(Ce,{title:t(`customize.status.unknownTitle`),message:e.reason});case`not-loaded`:return u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.notLoaded`,{reason:e.reason})});case`none`:return null;case`present`:{let n=e.view.block;return r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(Tn,{variant:n.status===`running`?`success`:n.status===`failed`?`danger`:`warning`,children:t(`customize.blockStatus.${n.status}`)}),!n.enabled&&u(Tn,{variant:`default`,children:t(`customize.status.off`)}),n.lastError!==void 0&&u(`span`,{className:`text-[11px] text-foreground-muted break-words`,children:n.lastError}),e.view.state.kind===`unreachable`&&u(`span`,{className:`text-[11px] text-warning`,children:t(`customize.status.composerUnreachable`,{reason:e.view.state.error})})]})}}}function gc({handle:e}){let{t}=Z(),n=dn(),[i,a]=c(null);if(e.state.kind!==`present`)return null;let o=async()=>{if(!await n({title:t(`customize.remove.title`),message:t(`customize.remove.message`),confirmLabel:t(`customize.remove.confirm`),variant:`danger`}))return;let r=await e.save(null);a(r.kind===`refused`?r.reason:null)};return r(`div`,{className:`flex flex-col items-start gap-1`,children:[u(G,{variant:`danger`,size:`sm`,disabled:e.saving,onClick:()=>void o(),children:t(`customize.remove.button`)}),i!==null&&u(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:i})]})}var _c=`overview`;function vc(e,t){return e.some(e=>e.id===t)?t:_c}function yc({deviceId:e}){let t=s(),n=Number.isFinite(e),{data:i}=ut({deviceId:e},{enabled:n}),a=typeof i?.type==`string`?i.type:`camera`;mn([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:o,isLoading:c,isError:l,error:d}=Zt({deviceId:e},{enabled:n}),{data:f}=Dn({deviceType:a},{enabled:!!a}),p=De({onSuccess:()=>{t.invalidateQueries({queryKey:[[`deviceManager`,`getBindings`]]})}});if(c)return u(`div`,{className:`p-4`,children:u(`div`,{className:`h-20 rounded-lg border border-border bg-surface animate-pulse`})});if(l)return r(`div`,{className:`p-4 text-xs text-red-400`,children:[`Failed to load bindings: `,d instanceof Error?d.message:String(d)]});let m=new Map,h={};for(let e of f??[])h[e.capName]=e.wrappers;for(let e of o?.entries??[])m.set(e.capName,{...e,wrappers:h[e.capName]??[]});for(let e of f??[])m.has(e.capName)||m.set(e.capName,{capName:e.capName,kind:`unbound`,providerAddonId:``,providerNodeId:``,nativeAddonId:``,wrappers:e.wrappers});let g=[...m.values()].toSorted((e,t)=>e.capName.localeCompare(t.capName));if(g.length===0)return r(`div`,{className:`flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle`,children:[u(Kn,{className:`h-8 w-8 opacity-40`}),u(`p`,{className:`text-xs`,children:`No capability providers applicable to this device yet.`}),u(`p`,{className:`text-[10px] opacity-60`,children:`Native providers show up here as soon as the owning addon registers them.`})]});let _=g.filter(e=>e.kind!==`unbound`).length;return r(`div`,{className:`flex flex-col gap-3 p-1`,children:[r(`div`,{className:`text-[11px] text-foreground-subtle`,children:[u(`span`,{className:`font-medium text-foreground`,children:_}),` of `,g.length,` capabilit`,g.length===1?`y`:`ies`,` bound — rows marked `,u(`em`,{children:`unbound`}),` have a wrapper available you can activate.`]}),u(ie,{columns:[{key:`capability`,header:`Capability`,render:e=>u(`span`,{className:`font-mono text-foreground`,children:e.capName})},{key:`kind`,header:`Kind`,render:e=>u(bc,{kind:e.kind})},{key:`provider`,header:`Active Provider`,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.providerAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`node`,header:`Node`,render:e=>e.providerNodeId?u(xc,{nodeId:e.providerNodeId}):u(`span`,{className:`text-[10px] opacity-40`,children:`—`})},{key:`native`,header:`Native`,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.nativeAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`wrapper`,header:`Wrapper`,render:t=>{let n=t.kind===`wrapped`?t.providerAddonId:null;return u(Sc,{wrappers:t.wrappers,activeWrapperId:n,disabled:p.isPending,onPick:r=>{let i=n===r;p.mutate({deviceId:e,capName:t.capName,wrapperAddonId:r,active:!i})}})}}],rows:g,rowKey:e=>e.capName,minWidthPx:720})]})}function bc({kind:e}){return e===`native`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-success/30 text-success bg-success/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(Ge,{className:`h-3 w-3`}),`native`]}):e===`wrapped`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-primary/30 text-primary bg-primary/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(fr,{className:`h-3 w-3`}),`wrapped`]}):e===`linked`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-warning/30 text-warning bg-warning/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(Nn,{className:`h-3 w-3`}),`linked`]}):r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-border text-foreground-subtle/70 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(On,{className:`h-3 w-3`}),`unbound`]})}function xc({nodeId:e}){return u(`span`,{className:`inline-flex items-center rounded-md border border-border px-1.5 py-0.5 font-mono text-[10px] ${e===`hub`?`text-foreground-subtle`:`text-foreground`}`,children:e})}function Sc({wrappers:e,activeWrapperId:t,disabled:n,onPick:i}){return e.length===0?u(`span`,{className:`text-[10px] opacity-40`,children:`none available`}):u(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>{let a=e===t;return r(`button`,{disabled:n,onClick:()=>i(e),title:a?`Click to deactivate (revert to native)`:`Activate wrapper ${e}`,className:`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px] transition-colors disabled:opacity-50 ${a?`border-primary/40 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(a?Qt:C,{className:`h-3 w-3`}),e]},e)})})}function Cc({deviceId:e,activeSubTab:t,onSubTabChange:n,deviceType:i,isAdmin:a}){return r(`div`,{className:`flex flex-col gap-3`,children:[ui(i,a)&&u(Wt,{deviceId:e,readOnly:!0}),u(qr,{deviceId:e,activeSubTab:t,onSubTabChange:n})]})}n();var wc=new Set([`package-detection`]);function Tc(e){return e?.settings!==void 0&&Object.keys(e.settings).length>0?`accelerator`:`camera`}function Ec(e){return e===`camera`?`this camera`:e===`node`?`node pin`:`hardware default`}function Dc(e){let{stored:t,draft:n,below:r,boundKeys:i}=e,a=n?.modelId===void 0?t?.modelId:n.modelId??void 0,o=Br(n?.settings??t?.settings,r,i),s={...a===void 0?{}:{modelId:a},...o===void 0?{}:{settings:o}};return Object.keys(s).length>0?s:null}function Oc(e,t){return(e?.modelId??null)===(t?.modelId??null)&&jr(e?.settings??{},t?.settings??{})}function kc({deviceId:e}){let t=s(),n=S().trpcClient,l=Pe({deviceId:e},{refetchOnMount:`always`}),d=ze({deviceId:e},{refetchOnMount:`always`}),p=U(void 0,{refetchOnMount:`always`}),m=pr(An({addonId:`pipeline-orchestrator`}).data??null);mn([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:h}=at(),_=i(()=>{let e=new Set((p.data??[]).map(e=>e.nodeId));return h.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[p.data,h]),v=_.map(e=>e.id).join(`,`),y=a({enabled:_.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,v],queryFn:async()=>{let e={};for(let t of _)try{e[t.id]=await n.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),b=a({enabled:_.length>0,queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`],`camera-step`,v],queryFn:async()=>{let e={};for(let t of _)try{e[t.id]=(await n.pipelineOrchestrator.getNodeInferenceDevices.query({nodeId:t.id})).devices}catch{e[t.id]=[]}return e}}),x=()=>{t.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]}),t.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStepOverrides`]]})},C=et({onSuccess:x}),w=fn(),T=de(),[E,D]=c(null),[O,k]=c(null),[A,j]=c(null),[M,N]=c(!1),[ee,F]=c(null),te=y.data??{},I=b.data??{},L=d.data??{},R=l.data??null,z=_.map(e=>te[e.id]).find(e=>e!==void 0)??null,B=i(()=>z?Me(z):[],[z]),ne=i(()=>nr(B),[B]),[re,V]=c(!1),H=i(()=>ar(_,I,re),[_,I,re]),ie=i(()=>ar(_,I,!0),[_,I]),ae=i(()=>ar(_,I).length,[_,I]),oe=(e,t)=>Xn(te[e.nodeId],t),W=(e,t)=>L[e.nodeId]?.[e.deviceKey]?.[t],se=(e,t)=>ur(I[e.nodeId]??[],e.deviceKey,t)??{},ce=e=>{if(wc.has(e))return{kind:`zone-driven`};let t=Xn(z,e)?.enabledByDefault??!0,n=R?.stepToggles?.[e];return{kind:`gate`,effectiveOn:n??t,defaultOn:t,explicit:n!==void 0}},le=(e,t,n)=>{let r=n?.stepId===t?n:null;return{node:se(e,t),camera:r?.camera??R?.stepSettings?.[t],accelerator:r?.perAccelerator[e.id]?.settings??W(e,t)?.settings}},G=(e,t,n)=>{let r=n?.stepId===t?n.perAccelerator[e.id]?.modelId:void 0;return r===void 0?W(e,t)?.modelId:r??void 0},ue=(e,t)=>{let n=oe(t,e),r=ce(e),i=ir(e),a=Zn(te[t.nodeId],t,W(t,`object-detection`)?.modelId),o=le(t,e,null),s=Nr(o.node,o.camera,o.accelerator);return sr({addon:n,acc:t,gatedOn:r.kind===`gate`?r.effectiveOn:!0,model:n?rr(n,t,{nodePin:t.device.steps?.[e]?.modelId,cameraPin:W(t,e)?.modelId}):{modelId:void 0,source:`default`},...er(e,s,a)&&a?{rootName:a.name}:{},...i?{clusterModelId:m[e]??i.defaultModelId}:{}})},fe=ne.map(({node:e})=>({addonId:e.addonId,name:e.addonName,fieldLabels:or(Xn(z,e.addonId))}));return p.isLoading||_.length>0&&(y.isLoading||b.isLoading)?u(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:`Loading pipeline…`}):_.length===0?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`No pipeline node is online.`}):z===null?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`Catalog unavailable.`}):u(Yn,{tree:B,searchRows:fe,accelerators:H,cellState:ue,stepBadge:e=>u(P,{gate:ce(e)}),disabledCount:lr(Object.fromEntries(_.map(e=>[e.id,I[e.id]??[]]))),showDisabled:re,onShowDisabledChange:V,dirty:E!==null,onDiscard:()=>D(null),summary:r(`span`,{className:g,children:[`This camera is balanced across `,ae,` accelerator`,ae===1?``:`s`,` at every session start · ovr = this camera overrides the node`]}),label:`Detection steps of this camera`,renderDetail:({stepId:t,accelerator:n,matchedField:i,closeButton:a,onEscape:s,headingRef:c})=>{let l=n??H[0],d=l?oe(l,t)??Xn(z,t):null;if(d===null||l===void 0)return u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`No step selected.`});let p=E?.stepId===t?E:null,m=ft(d),h=Sr(m),_=le(l,t,p),v=Nr(_.node,_.camera,_.accelerator),y=Zn(te[l.nodeId],l,W(l,`object-detection`)?.modelId),b=rr(d,l,{nodePin:l.device.steps?.[t]?.modelId,cameraPin:G(l,t,p)}).modelId,S=Nr(_.node,_.camera),P=Er(_.accelerator,S,h),I=ir(t),L=ce(t),B=m.find(e=>`label`in e&&e.label===i)?.key??null,ne=n===null?null:`${t}|${n.id}`,re=n===null?`camera`:O?.key===ne?O.scope:Tc(W(n,t)),V=e=>{F(null),D(n=>e(n?.stepId===t?n:{stepId:t,perAccelerator:{}}))},U=(e,t)=>V(n=>({...n,perAccelerator:{...n.perAccelerator,[e.id]:{...n.perAccelerator[e.id],...t}}})),ae=e=>V(n=>{let r=_.accelerator??{},i=Or(n.camera??R?.stepSettings?.[t],e,r,h),a={...n.perAccelerator};for(let r of ie){let i=n.perAccelerator[r.id]?.settings??W(r,t)?.settings;i!==void 0&&(a[r.id]={...a[r.id],settings:br(i,e,h)})}return{...n,camera:i,perAccelerator:a}}),ue=async()=>{if(p!==null){N(!0);try{let n=R?.stepSettings?.[t];p.camera!==void 0&&!jr(p.camera,n??{})&&await T.mutateAsync({deviceId:e,addonId:t,settings:Object.keys(p.camera).length>0?{...p.camera}:null});let r=p.camera??n;for(let n of ie){let i=p.perAccelerator[n.id];if(i===void 0)continue;let a=W(n,t),o=Dc({stored:a,draft:i,below:Nr(se(n,t),r),boundKeys:h});Oc(o,a)||await w.mutateAsync({deviceId:e,agentNodeId:n.nodeId,deviceKey:n.deviceKey,addonId:t,patch:o})}D(null),F({kind:`saved`})}catch(e){F({kind:`error`,error:e instanceof Error?e.message:`Save failed`})}finally{N(!1),x()}}},de=p===null?0:+(p.camera!==void 0&&!jr(p.camera,R?.stepSettings?.[t]??{}))+Object.values(p.perAccelerator).length,fe=e=>{let n=oe(e,t)??d,i=G(e,t,p),a=e.device.steps?.[t]?.modelId,s=rr(n,e,{nodePin:a,cameraPin:i}),c=le(e,t,p),l=Zn(te[e.nodeId],e,W(e,`object-detection`)?.modelId),f=er(t,Nr(c.node,c.camera,c.accelerator),l),m=Qn(n,e)?f&&l?u(hn,{rootModel:l,stepModelId:s.modelId}):void 0:r(o,{children:[`No `,e.device.format,` build of this step — it does not run on this accelerator.`]});return{label:e.label,format:e.device.format,modelId:s.modelId,source:s.source,sourceLabel:Ec(s.source),models:Tt(n.models??[],e.device.format),defaultModelId:n.defaultModelIdByFormat?.[e.device.format]??n.defaultModelId,expanded:A===e.id,onToggle:()=>j(t=>t===e.id?null:e.id),onChangeModel:t=>U(e,{modelId:t}),...i===void 0?{}:{onReset:()=>U(e,{modelId:null}),resetLabel:a===void 0?`Reset to hardware default`:`Reset to node pin`},...m===void 0?{}:{note:m},changed:p?.perAccelerator[e.id]?.modelId!==void 0}},pe=I===null&&m.length>0?n===null?u(`p`,{className:g,children:`Applies to: all accelerators of this camera.`}):r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(`span`,{className:`text-[11px] font-medium text-foreground`,children:`Applies to`}),u(Ut,{label:`Settings apply to`,options:[{value:`accelerator`,label:`This accelerator`},{value:`camera`,label:`All accelerators of this camera`}],value:re,onChange:e=>ne!==null&&k({key:ne,scope:e})})]}):void 0;return u(Fe,{ref:c,title:n===null?`${d.name} · this camera`:`${d.name} · ${n.label}`,subtitle:n===null?`${d.slot} · every accelerator this camera runs on`:`${d.slot} · ${n.device.format}`,leading:a,onEscape:s,headerActions:u(zt,{gate:L,busy:C.isPending,onSet:n=>C.mutate({deviceId:e,addonId:t,enabled:n})}),saveBar:{dirtyCount:de,saving:M,status:ee?.kind??null,...ee?.error===void 0?{}:{error:ee.error},onSave:()=>void ue(),onDiscard:()=>D(null),...pe===void 0?{}:{scope:pe}},children:r(`div`,{className:`space-y-3`,children:[r(`section`,{className:`space-y-2`,"aria-label":`Model`,children:[u(`h3`,{className:f,children:`Model`}),I===null?n===null?u($n,{rows:H.map(e=>{let n=rr(oe(e,t)??d,e,{nodePin:e.device.steps?.[t]?.modelId,cameraPin:G(e,t,p)});return{id:e.id,label:e.label,modelId:n.modelId,sourceLabel:Ec(n.source)}})}):u(Fn,{...fe(n)},n.id):u(cr,{step:I,engineFormat:l.device.format,runnableModelIds:Tt(d.models??[],l.device.format).map(e=>e.id)})]}),I===null&&(m.length>0||y!==void 0)&&u(`section`,{"aria-label":`Settings`,className:`border-t border-border/60 pt-2`,children:u(Ac,{addon:d,fields:m,layers:_,scope:re,viewed:n,modelId:It(d,b,v,y),root:y,pinned:n===null?[]:P,highlightKey:B,onChangeCamera:e=>V(t=>({...t,camera:e})),onChangeAccelerator:e=>U(l,{settings:e}),onApplyToAll:ae,onFollowNode:()=>U(l,{settings:P.reduce((e,t)=>br(e,t,h),{..._.accelerator})})})}),u(Jn,{addonId:t,highlightLabel:i})]})})}})}function Ac({addon:e,fields:t,layers:n,scope:i,viewed:a,modelId:o,root:s,pinned:c,highlightKey:l,onChangeCamera:d,onChangeAccelerator:f,onApplyToAll:p,onFollowNode:m}){tr(l===null?null:bn(l));let h=a!==null&&n.accelerator!==void 0;return u(on,{addon:e,fields:t,layers:{node:n.node,...n.camera===void 0?{}:{camera:n.camera},...h?{accelerator:n.accelerator}:{}},target:i,labels:{...a===null?{}:{accelerator:`This accelerator`},camera:`All accelerators`,node:`Node`},modelId:o,...s===void 0?{}:{rootModel:s},pinnedKeys:c,highlightKey:l,onChangeLayer:i===`camera`?d:f,...c.length>0?{headerActions:r(`button`,{type:`button`,className:w,onClick:m,children:[`Follow the node for `,c.length,` pinned field`,c.length===1?``:`s`]})}:{},fieldActions:(e,t)=>a!==null&&t===`accelerator`?u(`button`,{type:`button`,className:w,onClick:()=>p(e),children:`Apply to all accelerators`}):null})}var jc=[{id:`object-detection`,label:`Object detection`,icon:`scan-search`},{id:`tracking`,label:`Tracking`,icon:`route`},{id:`motion`,label:`Motion`,icon:`activity`},{id:`stationary`,label:`Stationary`,icon:`square-parking`},{id:`zones`,label:`Zones`,icon:`shapes`},{id:`audio`,label:`Audio`,icon:`volume-2`},{id:`cluster`,label:`Cluster`,icon:`server`}],Mc={"pipeline-object-detection":`object-detection`,"detection-sensitivity":`object-detection`,"onboard-object-detection":`object-detection`,tracking:`tracking`,"tracking-core":`tracking`,"motion-tuning":`motion`,"stationary-objects":`stationary`,occupancy:`stationary`,zones:`zones`,"pipeline-audio":`audio`,"cluster-assignment":`cluster`,"orchestrator-live":`cluster`};function Nc(e){return Mc[e]??`object-detection`}n();var Pc=`steps`,Fc=`settings`,Ic=new Set([Pc,Fc]);function Lc(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function Rc({deviceId:t,activeSubTab:n,onSubTabChange:i}){return r(ae,{value:n&&Ic.has(n)?n:Pc,onValueChange:e(e=>{i?.(e)},[i]),className:`flex flex-col`,children:[r(pn,{className:`flex-shrink-0`,children:[u(fe,{value:Pc,children:`Steps`}),u(fe,{value:Fc,children:`Settings`})]}),u(me,{value:Pc,children:u(kc,{deviceId:t})}),u(me,{value:Fc,children:u(qr,{deviceId:t,sectionFilter:Lc,subTabGrouping:{groupOf:e=>Nc(e.id),tabs:jc}})})]})}var zc=`Notifications`,Bc=`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`;function Vc(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:zc,on:r===null?null:i??r,available:r!==null,costWhenOff:Bc}}function Hc(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}n();function Uc(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function Wc({deviceId:t}){let n=s(),i=Number.isFinite(t),[a,o]=c(null),[l,d]=c(null),f=Vc({mutedDeviceIds:Uc(Ae({},{enabled:i}).data),deviceId:t,pendingOn:l}),p=Ot({onError:e=>{console.error(`[DeviceNotificationMute] mute write failed — reverting`,{tags:{deviceId:t},meta:{error:e instanceof Error?e.message:String(e)}}),d(null),o(e instanceof Error?e.message:String(e)),n.invalidateQueries({queryKey:[[`notificationRules`,`listDeviceMutes`]]})},onSuccess:()=>{o(null),d(null),n.invalidateQueries({queryKey:[[`notificationRules`]]})}}),m=e(()=>{let e=Hc(f,t);e!==null&&(d(!e.muted),p.mutate(e))},[t,p,f]),h=f.on===null,g=f.on===!1,_=g?kt:wt;return r(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r(`div`,{className:`border-b border-border px-4 py-2 flex items-center justify-between gap-2`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:`Notifications`}),g&&u(`span`,{className:`rounded bg-warning/20 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-warning`,children:`muted`})]}),r(`div`,{className:`px-4 py-3 flex items-start gap-3`,children:[r(`button`,{type:`button`,role:`switch`,"aria-label":f.label,"aria-checked":f.on===!0,disabled:!f.available||p.isPending,onClick:m,title:h?`Notification mute — state unknown; the notification centre did not answer.`:g?`Muted. ${f.costWhenOff}`:`Notifying. Muting it: ${f.costWhenOff}`,className:`inline-flex items-center gap-1.5 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors disabled:cursor-not-allowed ${a===null?h?`border-dashed border-border text-foreground-subtle/50`:g?`border-warning/40 text-warning hover:bg-warning/10`:`border-success/30 text-success hover:bg-success/10`:`border-danger/50 text-danger bg-danger/5`}`,children:[u(_,{className:`h-3.5 w-3.5`}),u(`span`,{children:h?`Unknown`:g?`Muted`:`Notifying`})]}),u(`p`,{className:`flex-1 text-[11px] leading-relaxed text-foreground-subtle`,children:a===null?h?`The notification centre did not answer, so this device’s mute state is unknown.`:f.costWhenOff:`Write failed: ${a}`})]})]})}function Gc(e,t){return{switchId:e,label:Vr[e].label,detail:t===void 0||t.length===0?null:t}}function Kc(e){let t=new Map;for(let n of e.switches)n.deviceId===e.sourceId&&(t.has(n.switchId)||t.set(n.switchId,n));return t}function qc(e){let t=Kc(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>Gc(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>Gc(e.switchId,e.detail));return{inheritedId:e.sourceId,retiredId:e.targetId,swapped:e.swapped,verdict:r.length===0?`quiet`:`still-live`,stillLive:r,neverOffered:i}}n();function Jc(e,t){return e.filter(e=>e.isCamera&&e.id!==t).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}function Yc({deviceId:e,deviceName:t}){let{t:n}=Z(),a=dn(),[o,s]=c(null),l=Kt({isCamera:!0,projection:`slim`}),d=Nt(),f=l.data!==void 0,p=i(()=>l.data===void 0?[]:Jc(l.data,e),[l.data,e]),m=p.find(e=>e.id===o)??null,h=d.data===void 0?null:qc(d.data),g=d.error===null?null:d.error.message,_=async()=>{m===null||m.id===e||await a({title:n(`deviceMigrate.confirmTitle`,`Replace “{{source}}” with “{{target}}”?`,{source:t,target:m.name}),message:n(`deviceMigrate.confirmMessage`,`“{{target}}” takes over number {{sourceId}}. That number is what every recording, event, rule, zone and home-automation export of “{{source}}” is filed under, so all of it follows the number to the new hardware and keeps working. “{{source}}” is switched off and handed number {{targetId}} in exchange. This swaps two device identities and cannot be undone from here.`,{source:t,target:m.name,sourceId:e,targetId:m.id}),confirmLabel:n(`deviceMigrate.confirmAction`,`Migrate`),variant:`danger`})&&d.mutate({sourceId:e,targetId:m.id})};return r(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[r(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[r(`div`,{className:`min-w-0`,children:[u(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:n(`deviceMigrate.title`,`Migrate to…`)}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.subtitle`,`Replace this camera with other hardware you have already adopted. The new camera inherits number {{deviceId}}, so recordings, rules and integrations follow it.`,{deviceId:e})})]}),r(`div`,{className:`flex shrink-0 items-center gap-2`,children:[r(`select`,{"aria-label":n(`deviceMigrate.pickerLabel`,`Replacement camera`),className:`rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground disabled:opacity-50`,disabled:!f||p.length===0||d.isPending,value:o===null?``:String(o),onChange:e=>{let t=e.target.value;s(t===``?null:Number(t))},children:[u(`option`,{value:``,children:f?n(`deviceMigrate.pickerPlaceholder`,`Select a camera…`):n(`deviceMigrate.pickerPending`,`Reading the fleet…`)}),p.map(e=>r(`option`,{value:String(e.id),children:[e.name,` (#`,e.id,`)`]},e.id))]}),r(`button`,{type:`button`,disabled:m===null||d.isPending,onClick:()=>{_()},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[u(Hi,{className:`h-3 w-3`}),d.isPending?n(`deviceMigrate.running`,`Migrating…`):n(`deviceMigrate.action`,`Migrate`)]})]})]}),f&&p.length===0&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.noTargets`,`No other camera is adopted, so there is nothing to migrate to.`)}),g!==null&&u(`p`,{className:`mt-2 text-[11px] text-danger`,children:n(`deviceMigrate.failed`,`Migration failed: {{error}}`,{error:g})}),h!==null&&u(Xc,{report:h})]})}function Xc({report:e}){let{t}=Z(),n=e.verdict===`quiet`;return r(`div`,{className:`mt-3 space-y-2 border-t border-border pt-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`deviceMigrate.swapped`,`The replacement now answers on number {{inheritedId}}; the old camera was handed number {{retiredId}}.`,{inheritedId:e.inheritedId,retiredId:e.retiredId})}),n?r(`div`,{className:`flex items-start gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2`,children:[u(it,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-success`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.quiet`,`Every function on the replaced camera was switched off — the old hardware is quiet.`)})]}):r(`div`,{className:`rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:[r(`div`,{className:`flex items-start gap-2`,children:[u(Ze,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.stillLive`,`The replaced camera could not be reached, so these functions are STILL RUNNING on the old hardware. Nothing here failed to migrate — but until you unplug it or reach it physically, it can still produce data.`)})]}),u(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.stillLive.map(e=>r(`li`,{className:`text-[11px] text-foreground`,children:[u(`span`,{className:`font-medium`,children:e.label}),e.detail!==null&&r(`span`,{className:`text-foreground-subtle`,children:[` — `,e.detail]})]},e.switchId))})]}),e.neverOffered.length>0&&r(`div`,{className:`rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`flex items-start gap-2`,children:[u(qn,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`deviceMigrate.neverOffered`,`The replaced camera never offered these, so there was nothing to switch off. They are not running.`)})]}),u(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.neverOffered.map(e=>u(`li`,{className:`text-[11px] text-foreground-subtle`,children:e.label},e.switchId))})]})]})}n();function Zc({deviceId:e}){let[t,n]=c(null),i=ln({onSuccess:e=>{n(e.changed?`Re-aligned with source — ${e.rebuiltChildren} child${e.rebuiltChildren===1?``:`ren`} rebuilt.`:`Already up to date.`)},onError:e=>n(`Re-sync failed: ${e.message}`)});return r(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[r(`div`,{className:`flex items-center justify-between gap-3`,children:[r(`div`,{children:[u(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:`Re-sync`}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:`Re-align this device's type, role, capabilities and units with its source.`})]}),r(`button`,{type:`button`,disabled:i.isPending,onClick:()=>{n(null),i.mutate({camDeviceId:e})},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[u(nt,{className:`h-3 w-3 ${i.isPending?`animate-spin`:``}`}),i.isPending?`Re-syncing…`:`Re-sync`]})]}),t!==null&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:t})]})}function Qc(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function $c({device:e}){let t=oi(),n=typeof e.id==`number`?e.id:null,i=String(e.type??``),a=i===J.Camera,o=i===J.Hub,s=e.features??[],c=s.includes(Ur.Resyncable),{data:l}=Ke({deviceId:n??0},{enabled:n!==null&&a,refetchInterval:5e3}),d=l?.streams??{},f=Object.entries(d),p=s.includes(Ur.DoorbellButton),m=Pt(p?{deviceId:n??void 0,historyLimit:10}:void 0),h=m.latest?Date.now()-m.latest.timestamp<3e4:!1;return r(`div`,{className:`space-y-5`,children:[o&&n!==null&&u(te,{deviceId:n,onOpenChild:e=>t(`/devices/${e}`)}),c&&n!==null&&u(Zc,{deviceId:n}),a&&n!==null&&u(Yc,{deviceId:n,deviceName:String(e.name??``)}),n!==null&&u(Wc,{deviceId:n}),a&&n!==null&&u(gt,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:n}),p&&u(Hn,{history:m.history,latestIsFresh:h}),a&&n!==null&&u(gt,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:n}),a&&f.length>0&&r(`div`,{className:`@container rounded-lg border border-border bg-surface overflow-hidden`,style:{containerType:`inline-size`},children:[u(`div`,{className:`border-b border-border px-4 py-2`,children:u(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:`Stream Network`})}),u(`div`,{className:`divide-y divide-border`,children:f.map(([e,t])=>r(`div`,{className:`px-4 py-2.5`,children:[r(`div`,{className:`flex items-center gap-2 mb-2`,children:[u(Sn,{className:`h-3 w-3 text-foreground-subtle`}),u(`span`,{className:`text-[11px] font-medium text-foreground`,children:e})]}),r(`div`,{className:`grid grid-cols-2 @[640px]:grid-cols-4 gap-2`,children:[u(el,{label:`Nominal`,value:Qc(t.nominalBitrateKbps??0)}),u(el,{label:`Observed`,value:Qc(t.observedBitrateKbps??0)}),u(el,{label:`Peak`,value:Qc(t.peakBitrateKbps??0)}),u(el,{label:`Packet Loss`,value:`${(t.packetLossPercent??0).toFixed(2)}%`,warning:(t.packetLossPercent??0)>1})]})]},e))})]}),u(mi,{}),n!==null&&u(Jr,{deviceId:n})]})}function el({label:e,value:t,warning:n}){return r(`div`,{children:[u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e}),u(`p`,{className:`text-xs font-medium ${n?`text-warning`:`text-foreground`}`,children:t})]})}var tl=[{id:`overview`,label:`Overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,label:`Config`,cameraOnly:!1,adminOnly:!1},{id:pi,label:`Customize`,cameraOnly:!1,adminOnly:!0},{id:`detection-pipeline`,label:`Detection pipeline`,cameraOnly:!0,adminOnly:!1},{id:`bindings`,label:`Bindings`,cameraOnly:!0,adminOnly:!1}];function nl(e,t){let n=e===J.Camera;return tl.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)).map(({id:e,label:t})=>({id:e,label:t}))}function rl({provider:e,integrationId:t,name:n}){let r=oi(),i=t===null?`/integrations`:`/integrations/${t}`,a=n===null?`Open integrations`:`Open integration ${n}`;return u(`button`,{type:`button`,onClick:()=>r(i),className:`shrink-0 rounded-md transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/50`,title:a,"aria-label":a,children:u(Zr,{type:e,size:`lg`})})}n();var il=[{id:`logs`,icon:Ue,label:`Logs`},{id:`repl`,icon:ci,label:`REPL`},{id:`events`,icon:kn,label:`Events`},{id:`state`,icon:We,label:`State`}];function al(){let n=ei(),a=Number(n.deviceId),l=Number.isFinite(a),d=oi(),f=s(),p=dn(),m=S(),{user:h}=ti(),g=h?.isAdmin===!0,[_,y]=Wr(),b=_.get(`tab`)??`overview`,C=_.get(`sub`),[w,T]=c(`logs`),E=`device-detail.left-col-width-px`,[D,A]=c(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(E),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),j=t(D);j.current=D;function M(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??D??0,r=Math.max(330,Math.floor(window.innerWidth*.7)),i=e=>{A(Math.max(280,Math.min(r,n+(e.clientX-t))))},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a);let e=j.current;if(e!==null)try{window.localStorage.setItem(E,String(Math.round(e)))}catch{}document.body.style.userSelect=``,document.body.style.cursor=``};document.body.style.userSelect=`none`,document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)}let{data:P,isLoading:te,isError:I}=ut({deviceId:a},{enabled:l,refetchInterval:5e3,retry:1}),{data:L}=rn({deviceId:a},{enabled:l}),R=i(()=>{let e=L?.settings?.sections??[],t=L?.live?.sections??[],n=[...e,...t],r=new Set;for(let e of n)e.location===`top-tab`&&e.tab&&r.add(e.tab===`zones`?`detection-pipeline`:e.tab);return n.some(Qr)&&r.add(Gr),[...r].map(e=>e===`export`?{id:e,label:li,isAddonContrib:!0}:{id:e,label:wr[e]?.label??e,isAddonContrib:!0})},[L]),z=P,B=String(z?.name??n.deviceId??`Device`),ne=z?.online===!0,re=ne?`online`:`offline`,V=String(z?.addonId??`rtsp`),H=z?.features??[],U=z?.type,ie=U===J.Camera,{data:ae}=ri(l?a:0),oe=U===J.Container,W=i(()=>(ae??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[ae]),le=i(()=>oe?Jt(W,typeof z?.linkDeviceId==`number`?z.linkDeviceId:null,typeof z?.primaryChildEntityId==`string`?z.primaryChildEntityId:null)?.id??null:null,[oe,W,z?.linkDeviceId,z?.primaryChildEntityId]),{data:G}=rn({deviceId:le??0},{enabled:le!==null}),ue=i(()=>{if(le===null)return[];let e=G?.settings?.sections??[],t=G?.live?.sections??[],n=new Set;for(let r of[...e,...t])r.location===`top-tab`&&r.tab&&n.add(r.tab);return[...n].map(e=>({id:e,label:wr[e]?.label??e,isAddonContrib:!0,childDeviceId:le}))},[le,G]),de=typeof z?.parentDeviceId==`number`?z.parentDeviceId:null,{data:fe}=ut({deviceId:de??0},{enabled:de!==null}),K=N(),me=z?.disabled!==!0,ge=i(()=>{let e=L?.settings?.sections??[],t=L?.live?.sections??[];return $r([...e,...t],U,g,L!==void 0)},[L,U,g]),_e=i(()=>{let e=new Set,t=[];for(let n of[...nl(U,g),...R,...ue])n.id===`config`&&!ge||e.has(n.id)||(e.add(n.id),t.push(n));return t},[U,g,R,ue,ge]),ve=i(()=>vc(_e,b),[_e,b]),be=e(e=>{y(t=>{let n=new URLSearchParams(t);e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`);for(let e of dr)n.delete(e);return n},{replace:!0})},[y]),xe=e(e=>{y(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[y]),Se=(ae??[]).length>0,Ce=i(()=>il.filter(({featureGate:e})=>!e||H.includes(e)),[H]),{data:Ee}=gn(void 0),De=i(()=>z?Qe(z,Ee):null,[z,Ee]),q=De?.kind===`resolved`?De.integration:null,Oe=q===null?De?.kind===`unknown`?`Loading integration…`:De?.kind===`orphan`?`Missing integration`:`No integration`:q.name,ke=q!==null&&q.addonId===V?q.name:V,Ae=Mn({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]}),d(q?.id?`/integrations/${q.id}`:`/integrations`)}}),je=Cn({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Me=Je({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ne=Vn(),Pe=Te({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Fe=H.includes(Ur.Rebootable),Ie=H.includes(Ur.BatteryOperated),Le=en(m.trpcClient,Ie&&l?a:null),Re=En(m.trpcClient,l?a:null),[ze,Be]=c(!1),Ve=async()=>{if(!ze){Be(!0);try{let e=B.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await Bi(`${v}/${String(a)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Be(!1)}}},Ue=je.isPending||Me.isPending,{data:We}=F({deviceId:a},{enabled:l,refetchInterval:1e4}),Ge=We?.agentNodeId??null,Ke=typeof Ge==`string`&&Ge.length>0&&!Ge.startsWith(`addon:`)?Ge:void 0,{data:Ye}=Ft({deviceId:a,...Ke?{nodeId:Ke}:{}},{enabled:l,refetchInterval:3e3,retry:!1}),{data:Xe}=qe({deviceId:a},{enabled:l,refetchInterval:3e3,retry:!1}),Ze=Xe?.level?.dbfs??null;function $e(){if(!l)return null;switch(ve){case`overview`:return u($c,{device:z??{}});case`config`:return u(Cc,{deviceId:a,activeSubTab:C,onSubTabChange:xe,deviceType:U,isAdmin:g});case`detection-pipeline`:return u(Rc,{deviceId:a,activeSubTab:C,onSubTabChange:xe});case`bindings`:return u(yc,{deviceId:a});case pi:return u(dc,{deviceId:a,activeSubTab:C,onSubTabChange:xe});default:{let e=ve,t=R.some(t=>t.id===e),n=ue.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??a;if(e===`export`)return u(qr,{deviceId:a,sectionFilter:Qr,activeSubTab:C,onSubTabChange:xe});let i=u(qr,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:C,onSubTabChange:xe});return n!==void 0&&r!==a?u(se,{deviceId:r,children:i}):i}}}return l?te?r(`div`,{className:`flex flex-col h-full`,children:[r(`div`,{className:`border-b border-border bg-surface px-6 py-4`,children:[u(`div`,{className:`h-4 w-48 rounded bg-surface-hover animate-pulse mb-3`}),u(`div`,{className:`h-8 w-64 rounded bg-surface-hover animate-pulse`})]}),u(`div`,{className:`flex-1 p-6`,children:u(`div`,{className:`h-40 rounded-lg border border-border bg-surface animate-pulse`})})]}):I||!P?r(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[u(`p`,{className:`text-lg font-semibold text-foreground`,children:`Device not found`}),r(`p`,{className:`text-xs`,children:[`No device with ID`,` `,r(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`,children:[`#`,a]})]}),u(`button`,{onClick:()=>d(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Back to Integrations`})]}):r(`div`,{className:`absolute inset-0 flex flex-col overflow-clip`,children:[r(`div`,{className:`border-b border-border bg-surface px-6 py-3 flex-shrink-0`,children:[u(`div`,{className:`mb-2`,children:u(Wn,{items:[{label:`Integrations`,onClick:()=>d(`/integrations`)},q===null?{label:Oe}:{label:Oe,onClick:()=>d(`/integrations/${q.id}`)},{label:B}]})}),r(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[q!==null&&u(rl,{provider:q.addonId,integrationId:q.id,name:q.name}),r(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`h1`,{className:`text-sm sm:text-base font-semibold text-foreground truncate`,children:B}),u(ye,{status:re}),Ie&&u(He,{status:Le,variant:`full`}),u(ce,{status:Re})]}),de!==null&&fe&&r(`button`,{type:`button`,onClick:()=>d(`/devices/${de}`),className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1`,title:`Open parent device ${fe.name}`,children:[u(`span`,{children:`↑`}),u(`span`,{className:`truncate`,children:String(fe.name??`Device #${de}`)})]}),u(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:H.length>0&&u(Xr,{capabilities:H})})]}),Ye&&u(`div`,{className:`hidden lg:flex`,children:u(ol,{metrics:Ye,dbfs:Ze})}),r(`div`,{className:`flex items-center gap-1 shrink-0`,children:[r(`button`,{onClick:async()=>{me?await p({title:`Disable "${B}"?`,message:`The device will stop processing streams and events. You can re-enable it later.`,confirmLabel:`Disable`,variant:`danger`})&&Me.mutate({deviceId:a}):je.mutate({deviceId:a})},disabled:Ue,title:me?`Disable device`:`Enable device`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border transition-colors disabled:opacity-50 ${me?`border-success/30 text-success hover:bg-success/10`:`border-border text-foreground-subtle/50 hover:text-foreground hover:bg-surface-hover`}`,children:[u(ee,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:Ue?`Updating…`:me?`Enabled`:`Disabled`})]}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),ie&&r(o,{children:[u(Zi,{deviceId:a}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),u($i,{deviceId:a}),u(he,{triggerClassName:`ml-1`,items:[{id:`snapshot`,label:`Take snapshot`,description:`Fetch a fresh frame and download it.`,icon:x,disabled:ze,onClick:()=>{Ve()}},{id:`reboot`,label:`Reboot device`,description:`Camera goes offline for ~30 seconds.`,icon:pe,hidden:!Fe,disabled:Ne.isPending,danger:!0,onClick:async()=>{await p({title:`Reboot "${B}"?`,message:`The camera will go offline for around 30 seconds while the firmware reboots.`,confirmLabel:`Reboot`,variant:`danger`})&&Ne.mutate({deviceId:a})}},{id:`restart-addon`,label:`Restart addon`,description:`Bounces every device served by ${ke}.`,icon:nt,disabled:Pe.isPending,danger:!0,onClick:async()=>{await p({title:`Restart "${ke}"?`,message:`Restarting the addon will briefly disconnect every device served by it (not just "${B}"). Streams will reconnect automatically.`,confirmLabel:`Restart`,variant:`danger`})&&Pe.mutate({addonId:V})}},{id:`delete`,label:`Delete device`,description:`Remove the device and all its settings.`,icon:O,separatorBefore:!0,disabled:Ae.isPending,danger:!0,onClick:async()=>{await p({title:`Delete "${B}"?`,message:`This will remove the device and all its settings. This action cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&Ae.mutate({deviceId:a})}}]})]})]})]}),u(se,{deviceId:a,device:z??void 0,children:u(Ht,{children:u(we,{children:u(k,{children:u(_t,{children:r(`main`,{className:K?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[r(`div`,{className:K?`flex flex-col bg-surface`:`${D===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-hidden`,style:!K&&D!==null?{width:`${String(D)}px`}:void 0,children:[u(`div`,{className:ie?`flex-shrink-0 border-b border-border-subtle bg-black`:K?`flex-shrink-0 border-b border-border-subtle bg-surface`:`max-h-[55%] shrink-0 overflow-y-auto border-b border-border-subtle bg-surface`,children:ie?u(Na,{deviceId:a,intercomAvailable:H.includes(Ur.TwoWayAudio)}):u(Ca,{deviceId:a,deviceName:B,deviceType:U??`unknown`,provider:V,isOnline:ne,features:H})}),r(`div`,{className:K?`flex flex-col border-b border-border`:`flex-1 min-h-0 flex flex-col overflow-hidden`,children:[u(`div`,{className:`flex-shrink-0 border-b border-border-subtle px-2 py-1.5`,children:u(`div`,{className:`flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5`,children:Ce.map(({id:e,label:t,icon:n})=>r(`button`,{onClick:()=>T(e),title:t,className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${w===e?`bg-primary/15 text-primary`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(n,{className:`h-3 w-3`}),t]},e))})}),r(`div`,{className:K?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[w===`logs`&&u(Pa,{deviceId:a,containerDeviceId:U===`container`?a:void 0}),w===`repl`&&u(Fa,{deviceId:a}),w===`events`&&u(Ia,{deviceId:a}),w===`state`&&u(La,{deviceId:a})]})]})]}),!K&&u(`div`,{role:`separator`,"aria-orientation":`vertical`,title:`Drag to resize`,onMouseDown:M,className:`flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10`,children:u(`span`,{className:`absolute inset-y-0 -left-1 -right-1`})}),r(`div`,{className:K?`flex flex-col`:`flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden`,children:[u(`div`,{className:`flex-shrink-0 border-b border-border bg-surface px-4`,children:u(`div`,{className:`flex flex-nowrap overflow-x-auto md:flex-wrap md:overflow-x-visible items-center gap-0`,children:_e.map(e=>{let t=ve===e.id;return r(`button`,{onClick:()=>be(e.id),className:`relative flex-shrink-0 px-3 py-2 text-xs font-medium transition-colors ${t?`text-primary`:`text-foreground-subtle hover:text-foreground`}`,children:[e.label,t&&u(`span`,{className:`absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary`})]},e.id)})})}),r(`div`,{className:K?`p-3 flex flex-col gap-3`:`flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3`,children:[ve===`overview`&&Se&&u(ea,{parentDeviceId:a}),$e()]})]})]})})})})})})]}):r(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[u(`p`,{className:`text-lg font-semibold text-foreground`,children:`Invalid device id`}),r(`p`,{className:`text-xs`,children:[`The URL segment`,` `,u(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`,children:n.deviceId}),` `,`is not a number.`]}),u(`button`,{onClick:()=>d(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Back to Integrations`})]})}function ol({metrics:e,dbfs:t}){let n=Be(e.phase??`idle`);return r(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[r(`div`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`h-1.5 w-1.5 rounded-full ${n.dotClass}`}),u(`span`,{className:`text-[10px] font-medium ${n.textColor}`,children:n.label})]}),u(`div`,{className:`h-3 w-px bg-border`}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[u(Ie,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:(e.actualFps??0).toFixed(1)}),u(`span`,{children:`fps`})]}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[u(oe,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:(e.avgInferenceTimeMs??0).toFixed(0)}),u(`span`,{children:`ms`})]}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,title:`Current audio level (dBFS)`,children:[u(Et,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:t==null?`—`:t.toFixed(0)}),u(`span`,{children:`dB`})]}),(e.queueDepth??0)>0&&r(`span`,{className:`text-[10px] text-warning tabular-nums`,children:[`q:`,e.queueDepth]})]})}export{al as DeviceDetailPage};