@camstack/addon-admin-ui 1.2.678 → 1.2.679
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.
- package/CHANGELOG.md +10 -0
- package/dist/assets/Addons-CcHG87CO.js +5 -0
- package/dist/assets/{AdminPage-BEQJlUNo.js → AdminPage-DhtpNaF0.js} +1 -1
- package/dist/assets/{AdminSectionedPage-C7Nx9jJl.js → AdminSectionedPage-dteNFZvo.js} +1 -1
- package/dist/assets/{AiProfiles-D4eTx94W.js → AiProfiles-DW84QaSf.js} +2 -2
- package/dist/assets/{BootstrapSettingsForm-C8SgY-gH.js → BootstrapSettingsForm-DTx2a3Sd.js} +1 -1
- package/dist/assets/Build-DGxdI3Hj.js +42 -0
- package/dist/assets/{Calendars-CngFbuGP.js → Calendars-CI5dIFem.js} +1 -1
- package/dist/assets/{CameraGrids-BI3PYGPr.js → CameraGrids-Cz0cgj4f.js} +1 -1
- package/dist/assets/Cluster-DdwOin66.js +1 -0
- package/dist/assets/CompositionBlockEditor-qlSsElYl.js +2 -0
- package/dist/assets/{CompositionEditorPage-C56ErWVZ.js → CompositionEditorPage-CpW6nXF5.js} +1 -1
- package/dist/assets/Data-B0cMYuLm.js +2 -0
- package/dist/assets/DeviceDetail-9y3dyWK7.js +2 -0
- package/dist/assets/{Devices-ByKU7OhR.js → Devices-Bk_TfLmI.js} +1 -1
- package/dist/assets/{EmbedDevicePage-CUljYRrr.js → EmbedDevicePage-CPlOvLlu.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-BM7zhcWx.js → EmbedPlayerPage-liQI6d7f.js} +1 -1
- package/dist/assets/{History-BCQ4IrRD.js → History-B1Q1JGWF.js} +1 -1
- package/dist/assets/Identity-DaP-TPKs.js +1 -0
- package/dist/assets/{InstancesTable-CriEfrMJ.js → InstancesTable-DMhlGx4D.js} +1 -1
- package/dist/assets/{IntegrationDetail-BCP8mmgO.js → IntegrationDetail-CGzj8QFi.js} +1 -1
- package/dist/assets/{Integrations-C30eE4UB.js → Integrations-CeWGYtB9.js} +1 -1
- package/dist/assets/{Integrations-Bqcvm_Qf.js → Integrations-DNctwKoS.js} +2 -2
- package/dist/assets/Library-4XVNGSe-.js +1 -0
- package/dist/assets/Locations-B8Y1S0hz.js +3 -0
- package/dist/assets/{Logs-DKDr8AuB.js → Logs-BhRCuJzg.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-DbmWEEiO.js → MaskShapeCanvas-BN-PRLjb.js} +1 -1
- package/dist/assets/{MotionZonesSettings-BzScgedh.js → MotionZonesSettings-D9Prrwl-.js} +1 -1
- package/dist/assets/{MyAccess-CzfNmMJl.js → MyAccess-Bxvq6s1N.js} +1 -1
- package/dist/assets/{Network-CAbg7ZpT.js → Network-DiPGmTrB.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-DTkQMaBn.js → NodeAddonsSettingsPanel-C3eW6HeG.js} +1 -1
- package/dist/assets/Notifications-DZlP-xpq.js +1 -0
- package/dist/assets/Pipeline-BOej0Ruf.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-DgBQuyh9.js → PrivacyMaskSettings-uNqMIBUf.js} +1 -1
- package/dist/assets/{Recordings-BlCEAKse.js → Recordings-DRXSsvRE.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-D5OLGtBI.js → SceneMonitorEditor-Dd67GOFm.js} +1 -1
- package/dist/assets/{ServerShell-CSTjFsEJ.js → ServerShell-9-brnTiy.js} +1 -1
- package/dist/assets/{SessionsList-C1Ao7w_G.js → SessionsList-ChVQOhw4.js} +2 -2
- package/dist/assets/{Showroom-DCYRjXXW.js → Showroom-Ccc-k5Zm.js} +1 -1
- package/dist/assets/{StorageLocationsTable-BfwKi6fr.js → StorageLocationsTable-Dge2NowU.js} +1 -1
- package/dist/assets/{System-BvNJMfpW.js → System-DRor4yxP.js} +1 -1
- package/dist/assets/{Terminal-DQ5u6n8f.js → Terminal-rDJpyrDe.js} +2 -2
- package/dist/assets/{TerminalPanel-DC4Fs74K.js → TerminalPanel-CcQHLEGZ.js} +1 -1
- package/dist/assets/{TrainingProviders-D6bLgYi2.js → TrainingProviders-BOGrjW0M.js} +1 -1
- package/dist/assets/{Viewer-BmamcoHc.js → Viewer-Dk4V-7Im.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DcrAwx-L.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BlbUc9gS.js} +1 -1
- package/dist/assets/{action-draft-Dr5Q1lmk.js → action-draft-DgC3sdIv.js} +1 -1
- package/dist/assets/{ai-page.helpers-AOJOCF6H.js → ai-page.helpers-BGxGEY-d.js} +1 -1
- package/dist/assets/{assignment-candidates-BYfez7Z_.js → assignment-candidates-BaRiMeKr.js} +1 -1
- package/dist/assets/{authed-media-DaaHSoAj.js → authed-media-DYlVx7_x.js} +1 -1
- package/dist/assets/{board-model-COsjkU2L.js → board-model-C2Tzni7-.js} +1 -1
- package/dist/assets/client-B0p6WiZb.js +1120 -0
- package/dist/assets/{command-vocab-wRSfGsbG.js → command-vocab-DNAnc4zd.js} +1 -1
- package/dist/assets/{device-detail-CT3Wq2MX.js → device-detail-DfSFMzI_.js} +1 -1
- package/dist/assets/{device-integration-icon-CK7ULj84.js → device-integration-icon-D2nTH-29.js} +1 -1
- package/dist/assets/device-picker-model-D943WJVm.js +1 -0
- package/dist/assets/{dist-BnzMSUv0.js → dist-BZGaAsKc.js} +1 -1
- package/dist/assets/dist-auYATUda.js +1120 -0
- package/dist/assets/{format-Fw8MrMCF.js → format-YT7IgtG9.js} +1 -1
- package/dist/assets/{hostInit-BHV5j57a.js → hostInit-Cm3R_dPt.js} +1 -1
- package/dist/assets/i18n-NPZM0HGc.js +1 -0
- package/dist/assets/icons-f0SVFd9I.js +1 -0
- package/dist/assets/index-Bjvuymkk.js +4 -0
- package/dist/assets/{linked-devices-model-BRVCcL_i.js → linked-devices-model-D6oZ-Tkf.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-65134e91.js → mf-entry-bootstrap-0-76eadad6.js} +2 -2
- package/dist/assets/mount-D943WJVm.js +1 -0
- package/dist/assets/{notification-rule-status-tbLfUZee.js → notification-rule-status-BRCNbkxe.js} +1 -1
- package/dist/assets/{player-overlays-8aC2r-sd.js → player-overlays-ClFSGefV.js} +1 -1
- package/dist/assets/remoteEntry-CUYE4uFU.js +1 -0
- package/dist/assets/src-DwclSIv9.js +279 -0
- package/dist/assets/{sso-popup-C_VTtoWT.js → sso-popup-Bxcrh_Ga.js} +1 -1
- package/dist/assets/{step-inspector-model-UadKxnLr.js → step-inspector-model-CdoST47D.js} +1 -1
- package/dist/assets/{use-scenes-feed-D3bzrMKu.js → use-scenes-feed-D64cvW6x.js} +1 -1
- package/dist/assets/{use-stationary-objects-Yw5gdlLl.js → use-stationary-objects-CVtFtIWB.js} +1 -1
- package/dist/assets/{useAdminDeviceRemoval-WQ4NaouA.js → useAdminDeviceRemoval-D_RkWyKn.js} +1 -1
- package/dist/assets/useEventInvalidation-D943WJVm.js +1 -0
- package/dist/assets/{useNodeUrlSelection-BSpn8JLz.js → useNodeUrlSelection-BrRsjvMi.js} +1 -1
- package/dist/assets/useTemplateSave-CGO3W8km.js +1 -0
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CTvMo-Za.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-i9bg-dgj.js} +2 -2
- package/dist/index.html +8 -8
- package/dist/server/addon.js +1500 -1078
- package/package.json +2 -2
- package/dist/assets/Addons-DKOUsYsk.js +0 -5
- package/dist/assets/Build-BuGJWdUz.js +0 -42
- package/dist/assets/Cluster-DMkIzva9.js +0 -1
- package/dist/assets/CompositionBlockEditor-BlkVIJir.js +0 -2
- package/dist/assets/Data-D-7IMZzp.js +0 -2
- package/dist/assets/DeviceDetail-CATQ56bt.js +0 -2
- package/dist/assets/Identity-D60Odj5F.js +0 -1
- package/dist/assets/Library-BbXKoa8Z.js +0 -1
- package/dist/assets/Locations-DM8nnzTd.js +0 -3
- package/dist/assets/Notifications-BnUmb5Cg.js +0 -1
- package/dist/assets/Pipeline-SaA7yA5Z.js +0 -1
- package/dist/assets/client-LrzN1ATZ.js +0 -1119
- package/dist/assets/device-picker-model-BaM_HHUO.js +0 -1
- package/dist/assets/dist-p9ea9Hzu.js +0 -1119
- package/dist/assets/i18n-DWjQ9UFE.js +0 -1
- package/dist/assets/icons-Dfx79nBH.js +0 -1
- package/dist/assets/index-BsPM4J54.js +0 -4
- package/dist/assets/mount-BaM_HHUO.js +0 -1
- package/dist/assets/remoteEntry-DuqtB7i9.js +0 -1
- package/dist/assets/src-D5UhvHcp.js +0 -279
- package/dist/assets/useEventInvalidation-BaM_HHUO.js +0 -1
- package/dist/assets/useTemplateSave-CVoxjtyr.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as e,J as t,K as n,S as r,V as i,Y as a,a as o,et as s,o as c,x as l}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{An as u,Bn as d,D as f,Fr as p,Jn as m,Ln as h,Mn as g,Mr as _,Nn as v,Oa as y,Rr as b,Sn as x,Ua as S,Ur as C,Vt as w,Wi as T,Xt as E,ct as D,dt as O,en as ee,lr as te,pi as ne,rr as re,ut as ie,vt as ae,wt as oe,yi as se}from"./player-overlays-8aC2r-sd.js";import{Fs as k,Ps as ce,p as le}from"./client-LrzN1ATZ.js";import{f as A,l as j,n as ue,o as M,u as de}from"./terminal-DU-tvcEm.js";import{t as fe}from"./file-up-2YD_M6f_.js";import{t as pe}from"./key-CH4aXNMz.js";import{t as me}from"./monitor-smartphone-DPI9EQus.js";import{t as he}from"./unlink-D3-IGpS8.js";import{$f as ge,$r as _e,A as ve,Af as ye,Ar as be,Cr as N,Df as xe,Ef as Se,Ff as Ce,Fi as P,G as we,Gf as F,If as I,Lf as Te,Li as L,Mf as Ee,Nf as De,Ni as R,Ns as z,Of as Oe,Or as ke,Pf as Ae,Pi as B,Qf as je,Qr as Me,Ri as V,Sr as Ne,Xf as Pe,Xr as Fe,Yf as Ie,Yi as Le,Zf as Re,ai as ze,bl as Be,ct as H,et as Ve,fa as U,fl as He,hl as Ue,ii as We,jf as Ge,ji as Ke,jr as qe,kf as Je,kp as W,kr as G,ma as K,oi as Ye,pa as Xe,tt as Ze,ul as Qe,yl as $e,zi as et}from"./src-D5UhvHcp.js";import{t as q}from"./i18n-DWjQ9UFE.js";import{t as J}from"./useTranslation-BJr-n0es.js";import{F as tt,b as nt,c as rt,d as it,di as at,f as ot,hi as st,ht as ct,l as lt,li as ut,o as dt,pi as ft,r as pt,s as mt,u as ht,ui as gt}from"./index-BsPM4J54.js";import{t as _t}from"./AdminSectionedPage-C7Nx9jJl.js";import{t as vt}from"./AdminPage-BEQJlUNo.js";import{t as yt}from"./InstancesTable-CriEfrMJ.js";import{C as bt,D as Y,E as xt,O as X,S as St,T as Ct,_ as wt,a as Tt,b as Et,c as Dt,d as Ot,f as kt,g as At,h as jt,i as Mt,k as Nt,l as Pt,m as Ft,n as It,o as Lt,p as Rt,s as zt,t as Bt,u as Vt,v as Ht,w as Ut,x as Wt,y as Gt}from"./SessionsList-C1Ao7w_G.js";import{n as Kt,t as qt}from"./BootstrapSettingsForm-C8SgY-gH.js";s();function Jt(){let{t:e}=J(),t=D(),i=W.useUtils(),o=Nt(),{data:s,isLoading:c}=Ee(),l=n(()=>s??[],[s]),u=W.useQueries(e=>l.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),d=W.auth.listLoginMethods.useQuery(),[f,p]=a(null),m=I({onSuccess:()=>void i.userManagement.listExternalIdentities.invalidate(),onError:e=>p(`Remove failed: ${e.message}`)}),h=n(()=>new Map((d.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[d.data]),g=l.flatMap((e,t)=>u[t]?.data??[]),_=g.map(e=>({...Wt(e,o),kind:h.get(e.provider)??e.provider})),v=async n=>{let r=g.find(e=>Et(e)===n.id);r!==void 0&&await t({title:e(`access.externalIdentitiesSection.removeSignInLink`,`Remove sign-in link`),message:e(`access.externalIdentitiesSection.willNoLongerBeAble`,`"{{ownerName}}" will no longer be able to sign in with this {{kind}} account.`,{ownerName:n.ownerName,kind:n.kind}),confirmLabel:e(`common.remove`,`Remove`),variant:`danger`})&&(p(null),m.mutate({userId:r.userId,provider:r.provider,subject:r.subject}))};return r(Y,{notice:X(f),onDismissNotice:()=>{p(null)},id:`external-identities`,title:e(`access.externalIdentitiesSection.signInLinks`,`Sign-in links`),icon:A,description:e(`access.externalIdentitiesSection.externalAccountsSingleSignOn`,`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`),children:r(Ut,{rows:_,label:`sign-in links`,isLoading:c||u.some(e=>e.isLoading),loadError:u.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:e(`common.remove`,`Remove`),icon:he,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:m.isPending}})})}s();var Yt={key:`access.nouns.linkedApp`};function Xt(e){if(e.type===`category`){let t=e.target??``;return t===`device`?q.t(`access.linkedAppsSection.allDevices`):q.t(`access.linkedAppsSection.allTarget`,{target:t})}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function Zt(){let{t:e}=J(),t=D(),i=c(),o=Ge(),[s,l]=a(null),u=()=>void i.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),d=Ae({onSuccess:u,onError:e=>l(`Revoke failed: ${e.message}`)}),f=Ct(Yt,u),p=n(()=>(o.data??[]).map(e=>St(e,e.scopes.map(Xt).join(`, `))),[o.data]),m=async n=>{await t({title:e(`access.linkedAppsSection.revokeTheLink`,`Revoke the "{{name}}" link?`,{name:n.name}),message:e(`access.linkedAppsSection.losesAccessForOnIts`,`{{name}} loses access for {{ownerName}} on its next call. Linking it again needs the account-link flow from the start.`,{name:n.name,ownerName:n.ownerName}),confirmLabel:e(`access.linkedAppsSection.revoke`,`Revoke`),variant:`danger`})&&(l(null),d.mutate({id:n.id}))},h=d.isPending?d.variables?.id??null:null;return r(Y,{notice:X(s,f.outcome),onDismissNotice:()=>{l(null),f.dismiss()},id:`linked-apps`,title:e(`access.linkedAppsSection.linkedApps`,`Linked apps`),icon:b,description:e(`access.linkedAppsSection.externalIntegrationsAlexaLinkedTo`,`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call. Already-revoked rows can be selected and removed from the list.`),children:r(Ut,{rows:p,label:e(`access.linkedAppsSection.linkedApps2`,`linked apps`),isLoading:o.isLoading,loadError:o.isError?o.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:e(`access.linkedAppsSection.revoke`,`Revoke`),icon:ee,isAvailable:e=>e.status===`active`||e.status===`revoked`,onRun:e=>void m(e),busyId:h,disabled:d.isPending||f.busy},bulk:{revoke:f,noun:Yt,isSelectable:e=>e.status===`active`||e.status===`revoked`,quickSelect:[{label:e(`access.linkedAppsSection.selectRevoked`,`Select revoked`),match:e=>e.status===`revoked`}]}})})}var Qt=5e3;function $t(){let{t}=J(),n=W.useUtils(),i=W.auth.cliLoginPending.useQuery(void 0,{refetchInterval:Qt}),a=W.auth.cliLoginDeny.useMutation({onSuccess:()=>void n.auth.cliLoginPending.invalidate()}),o=i.data??[];if(o.length===0)return null;let s=Date.now();return e(`div`,{className:`space-y-2 rounded-md border border-border bg-background-elevated p-3`,"data-testid":`pending-terminal-signins`,children:[e(`div`,{className:`flex items-center gap-2 text-xs font-medium text-foreground`,children:[r(ue,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),t(`cliLogin.pendingTitle`,`Pending terminal sign-ins`)]}),r(`ul`,{className:`space-y-1`,children:o.map(n=>{let i=pt(n.createdAt,s);return e(`li`,{className:`flex items-center justify-between gap-3 text-xs`,children:[e(`span`,{className:`min-w-0 truncate text-foreground-muted`,children:[n.userAgent??t(`cliLogin.unknownValue`,`Unknown`),` · `,n.ip??t(`cliLogin.unknownValue`,`Unknown`),` · `,i.key===`justNow`?t(`cliLogin.ageNow`,`just now`):i.key===`seconds`?t(`cliLogin.ageSeconds`,`{{count}} s ago`,{count:i.value}):t(`cliLogin.ageMinutes`,`{{count}} min ago`,{count:i.value})]}),r(F,{type:`button`,size:`sm`,variant:`ghost`,disabled:a.isPending,onClick:()=>a.mutate({requestId:n.requestId}),children:t(`cliLogin.notMe`,`Not me`)})]},n.requestId)})}),r(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`cliLogin.pendingHint`,`To approve one, open the approval page and type the code the terminal shows.`)})]})}s();var en={key:`access.nouns.session`};function tn(){let{t}=J(),i=D(),o=W.useUtils(),s=Nt(),c=W.auth.listSessions.useQuery(),[l,u]=a(null),d=()=>void o.auth.listSessions.invalidate(),f=W.auth.revokeSessions.useMutation({onSuccess:d,onError:e=>u(`Sign out failed: ${e.message}`)}),p=Ct(en,d),m=n(()=>(c.data??[]).map(e=>bt(e,s,{client:e=>wt(e).label,method:Ht})),[c.data,s]),h=async e=>{await i({title:t(`access.loginSessionsSection.signOutThisSession`,`Sign out this session`),message:t(`access.loginSessionsSection.onWillHaveToSign`,`{{ownerName}} on {{name}} will have to sign in again.`,{ownerName:e.ownerName,name:e.name}),confirmLabel:t(`access.loginSessionsSection.signOut`,`Sign out`),variant:`danger`})&&(u(null),f.mutate({id:e.id}))};return e(Y,{notice:X(l,p.outcome),onDismissNotice:()=>{u(null),p.dismiss()},id:`login-sessions`,title:t(`access.loginSessionsSection.loginSessions`,`Login sessions`),icon:me,description:t(`access.loginSessionsSection.everyBrowserAndAppSigned`,`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`),children:[r($t,{}),r(Ut,{rows:m,label:t(`common.sessionsLabel`),isLoading:c.isLoading,loadError:c.isError?c.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:t(`access.loginSessionsSection.signOut`,`Sign out`),icon:M,isAvailable:e=>e.status===`active`,onRun:e=>void h(e),busyId:f.isPending&&f.variables!==void 0&&`id`in f.variables?f.variables.id:null,disabled:f.isPending||p.busy},bulk:{revoke:p,noun:en,isSelectable:e=>e.status===`active`}})]})}var nn={"by-id":`helpers.authAuditWording.bulkNoun.credential`,"share-link":`helpers.authAuditWording.bulkNoun.shareLink`,"admin-token":`helpers.authAuditWording.bulkNoun.adminToken`,"login-session":`helpers.authAuditWording.bulkNoun.loginSession`};function Z(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function rn(e,t){let n=Z(e,`tokenId`);return Z(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function Q(e){return e.filter(e=>e!==null)}function an(e){let t=Z(e,`prefix`);return t===null?null:q.t(`helpers.authAuditWording.prefix`,{prefix:t})}function on(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:q.t(`helpers.authAuditWording.tokenCreated`,{name:rn(n,t)}),details:Q([an(n),typeof e==`number`?q.t(`helpers.authAuditWording.expires`,{at:Gt(e)}):null])}}case`admin-token-used`:{let e=Z(n,`path`);return{title:q.t(`helpers.authAuditWording.tokenUsed`,{name:rn(n,t)}),details:Q([an(n),e===null?null:q.t(`helpers.authAuditWording.call`,{path:e})])}}case`token-minted`:{let e=n.expiresAt;return{title:q.t(`helpers.authAuditWording.tokenMinted`,{name:rn(n,t)}),details:Q([typeof e==`number`?q.t(`helpers.authAuditWording.expires`,{at:Gt(e)}):null])}}case`token-revoked`:return{title:q.t(`helpers.authAuditWording.anyTokenRevoked`,{name:rn(n,t)}),details:[]};case`admin-token-revoked`:return{title:q.t(`helpers.authAuditWording.tokenRevoked`,{name:rn(n,t)}),details:Q([an(n)])};case`credentials-revoked`:{let e=Z(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=nn[e],a=i===void 0?`${e}s`:q.t(i);return{title:q.t(`helpers.authAuditWording.bulkRevoked`,{n:typeof t==`number`?String(t):`?`,noun:a}),details:Q([typeof r==`number`&&r>0?q.t(`helpers.authAuditWording.skipped`,{count:r}):null,Z(n,`ids`)===null?null:q.t(`helpers.authAuditWording.ids`,{ids:Z(n,`ids`)??``})])}}case`second-factor-skipped`:{let e=Z(n,`method`),t=Z(n,`factors`);return{title:q.t(`helpers.authAuditWording.secondFactorSkipped`),details:Q([e===null?null:q.t(`helpers.authAuditWording.signedInWith`,{method:Ht(e)}),t===null?null:q.t(`helpers.authAuditWording.skippedFactors`,{factors:t.split(`,`).join(`, `)})])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}s();var sn=100;function cn(){let{user:e}=tt();return e?.isAdmin?r(un,{}):null}function ln(){let{data:e}=Ee(),{data:t}=W.auth.listTokens.useQuery(void 0);return n(()=>{let n=new Map;for(let t of e??[])n.set(t.id,t.username);let r=new Map;for(let e of t??[])r.set(e.id,e.label);return{userNameById:n,tokenNameById:r}},[e,t])}function un(){let{t}=J(),n=W.auth.listAuthAudit.useQuery({limit:sn}),{userNameById:i,tokenNameById:a}=ln(),o=n.data??[];return e(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[e(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[r(d,{className:`h-3.5 w-3.5 text-foreground-subtle`}),r(`div`,{className:`text-xs font-semibold text-foreground`,children:t(`auth.authAuditSection.authenticationAudit`,`Authentication audit`)}),r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:t(`auth.authAuditSection.latest`,{count:sn})})]}),r(`div`,{className:`p-4`,children:n.isLoading?e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[r(p,{className:`h-3.5 w-3.5 animate-spin`}),t(`auth.authAuditSection.loadingAuditTrail`,`Loading audit trail…`)]}):n.isError?e(`div`,{className:`text-[11px] text-danger`,children:[t(`auth.authAuditSection.couldNotLoadTheAudit`,`Could not load the audit trail:`),` `,n.error?.message??t(`auth.authAuditSection.requestFailed`,`Request failed`)]}):o.length===0?e(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center space-y-1`,children:[r(`div`,{children:t(`auth.authAuditSection.noAuthenticationEventsRecordedYet`,`No authentication events recorded yet.`)}),r(`div`,{className:`text-[11px] text-foreground-subtle/90`,children:t(`auth.authAuditSection.thisTrailRecordsAdminToken`,`This trail records admin-token create/use/revoke, trusted-network 2FA skips, and credential revokes (including single share-link revoke). Browser password logins are not listed here.`)})]}):r(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:o.map(e=>r(dn,{record:e,userName:e.userId===void 0?null:i.get(e.userId)??e.userId,tokenNameById:a},e.id))})})]})}function dn({record:t,userName:n,tokenNameById:i}){let a=on(t,i);return e(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[e(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[r(`span`,{className:`font-medium text-foreground`,children:a.title}),r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Gt(t.at)})]}),e(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[n!==null&&r(`span`,{className:`text-foreground`,children:n}),t.ip!==void 0&&r(`span`,{className:`font-mono`,children:t.ip}),a.details.map(e=>r(`span`,{className:`font-mono`,children:e},e))]})]})}s();function fn(e){let{ids:t,answered:r,legacyGroupParam:i=null,groupFirst:a}=e,[o]=st(),s=o.get(rt),c=i===null?null:o.get(i),l=o.get(lt),u=n(()=>it({ids:t,requested:s,answered:r,legacyGroup:c,...a===void 0?{}:{groupFirst:a}}),[t,s,r,c,a]),d=n(()=>(e,t)=>`?${ot(o,e,i,t??null).toString()}`,[o,i]);return{...u,requestedSection:l,hrefFor:d}}s();var $={loginSessions:`login-sessions`,linkedApps:`linked-apps`,tokens:`tokens`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,externalIdentities:`external-identities`,audit:`auth-audit`},pn={[$.scopedTokens]:$.tokens,[$.adminTokens]:$.tokens,[$.shareLinks]:$.tokens};function mn(){return[{id:$.loginSessions,label:q.t(`system.access.loginSessions`,`Login sessions`),icon:me,render:()=>r(tn,{})},{id:$.linkedApps,label:q.t(`system.access.linkedApps`,`Linked apps`),icon:b,render:()=>r(Zt,{})},{id:$.tokens,label:q.t(`system.access.tokens`,`Tokens`),icon:j,render:({createRequested:e,onCreateConsumed:t})=>r(jt,{headerOwnsCreate:!0,createRequested:e,onCreateConsumed:t})},{id:$.externalIdentities,label:q.t(`system.access.signInLinks`,`Sign-in links`),icon:A,render:()=>r(Jt,{})},{id:$.audit,label:q.t(`system.access.audit`,`Audit`),icon:d,render:()=>r(cn,{})}]}function hn({createRequested:t=!1,onCreateConsumed:i}){let{t:a}=J(),o=n(()=>mn(),[]),s=fn({ids:n(()=>o.map(e=>e.id),[o]),answered:!0}),c=ft(),[l]=st(),u=l.get(`integration`),d=u===null?void 0:pn[u];if(d!==void 0){let e=new URLSearchParams(l);return e.set(`integration`,d),r(at,{to:`?${e.toString()}`,replace:!0})}let f=o.find(e=>e.id===s.selectedId)??o[0];return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`access-page`,children:[r(Fe,{appearance:`pills`,value:f?.id??$.loginSessions,onValueChange:e=>{c(`?${ot(l,e,null,null).toString()}`)},children:r(Me,{"aria-label":a(`system.access.credentialKinds`,`Credential kinds`),children:o.map(t=>e(_e,{value:t.id,"data-testid":`access-kind-${t.id}`,children:[r(t.icon,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":!0}),t.label]},t.id))})}),f===void 0?null:r(`div`,{role:`region`,"aria-label":f.label,"data-testid":`access-kind-body`,children:f.render({createRequested:t&&f.id===$.tokens,onCreateConsumed:i??(()=>void 0)})},f.id)]})}function gn(t,n){if(t===$.tokens)return e(F,{size:`sm`,type:`button`,"data-testid":`access-new-token`,onClick:n,children:[r(j,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),q.t(`system.access.newToken`,`New token`)]})}function _n(){let[e,t]=a(!1);return{createRequested:e,requestCreate:()=>t(!0),clearCreate:()=>t(!1)}}function vn(){let{t}=J();return e(`div`,{className:`space-y-3 sm:space-y-4`,children:[r(yt,{functionCap:`login-method`,icon:de,title:t(`system.authentication.connectionsTitle`,`Sign-in connections`),subtitle:t(`system.authentication.connectionsSubtitle`,`Identity providers that sign users in. Each connection has its own id, which cannot be changed later.`),emptyTitle:t(`system.authentication.connectionsEmptyTitle`,`No sign-in connections`),emptyDescription:t(`system.authentication.connectionsEmptyDescription`,`Add a connection to let users sign in through an identity provider.`),addLabel:t(`system.authentication.addConnection`,`Add connection`),install:{capability:`login-method`,label:t(`system.authentication.sectionInstall`,`Add provider`)},typedId:()=>({pattern:ct})}),r(bn,{})]})}var yn=Kt;function bn(){let{t}=J();return r(ke,{headingId:`authentication-policy`,title:t(`system.authentication.policyTitle`,`Sign-in policy`),icon:g,children:e(`div`,{className:f,children:[r(`p`,{className:`text-xs text-foreground-subtle`,children:t(`system.authentication.localAlwaysOn`,`Username and password sign-in is always on and cannot be turned off. It is not a connection, so it has no row above.`)}),r(`p`,{className:`text-xs text-foreground-subtle`,children:r(ut,{i18nKey:`system.authentication.totpNote`,components:{access:r(gt,{to:`/system/my-access?tab=sign-in`,className:`underline text-primary`}),users:r(gt,{to:`/system/identity?tab=users`,className:`underline text-primary`})}})}),r(qt,{sectionIds:[yn],hideSectionChrome:!0,emptyMessage:t(`system.authentication.policyUnavailable`,`Not available — the addon that owns these settings did not answer.`)})]})})}function xn({isPending:t,error:n,what:i,onRetry:a,children:o}){let{t:s}=J();return t?e(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,role:`status`,"data-testid":`query-pending`,children:[r(p,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),s(`certificates.queryBody.reading`,{what:i})]}):n===null?o:r(U,{title:s(`certificates.queryBody.couldNotRead`,`Could not read {{what}}`,{what:i}),message:n.message.length>0?n.message:s(`certificates.queryBody.requestFailed`,`Request failed`),onRetry:a})}function Sn(){let{t}=J(),n=W.deviceCredentials.getDeviceCaStatus.useQuery({}),i=n.data;return r(Y,{id:`device-ca`,title:t(`certificates.deviceCaCard.deviceCertificateAuthority`,`Device certificate authority`),icon:g,description:t(`certificates.deviceCaCard.signsTheCertificateEachPaired`,`Signs the certificate each paired device holds. It is created the first time a device is paired.`),children:r(xn,{isPending:n.isPending,error:n.error,what:`the device CA`,onRetry:()=>void n.refetch(),children:i!==void 0&&e(`div`,{className:`space-y-1`,"data-testid":`device-ca-status`,children:[e(G,{label:t(`certificates.deviceCaCard.state`,`State`),children:[i.state===`ready`&&r(K,{variant:`success`,children:t(`certificates.deviceCaCard.ready`,`Ready`)}),i.state===`absent`&&r(K,{variant:`default`,children:t(`certificates.deviceCaCard.notCreatedYet`,`Not created yet`)}),i.state===`unavailable`&&r(K,{variant:`danger`,children:t(`certificates.deviceCaCard.unavailable`,`Unavailable`)})]}),i.state===`ready`&&e(l,{children:[r(G,{label:t(`certificates.deviceCaCard.subject`,`Subject`),valueClassName:`font-mono`,children:i.subject}),r(G,{label:t(`certificates.deviceCaCard.fingerprintSha256`,`Fingerprint (SHA-256)`),valueClassName:`font-mono`,children:i.fingerprintSha256}),r(G,{label:t(`certificates.deviceCaCard.validUntil`,`Valid until`),children:i.validTo})]}),i.state===`unavailable`&&r(G,{label:t(`certificates.deviceCaCard.reason`,`Reason`),children:r(`span`,{className:`text-danger`,children:i.reason})})]})})})}s();function Cn(){let{t}=J(),n=W.useUtils(),i=W.deviceCredentials.getDeviceCertificateSettings.useQuery({}),[o,s]=a(null),c=W.deviceCredentials.setDeviceCertificateSettings.useMutation({onSuccess:()=>{s(null),n.deviceCredentials.getDeviceCertificateSettings.invalidate()},onError:e=>s(`Could not save: ${e.message}`)});return r(xn,{isPending:i.isPending,error:i.error,what:`the enrollment setting`,onRetry:()=>void i.refetch(),children:i.data!==void 0&&e(G,{label:t(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),actions:r(We,{checked:i.data.selfEnrollment===`allowed`,disabled:c.isPending,"aria-label":t(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),onCheckedChange:e=>c.mutate({selfEnrollment:e?`allowed`:`disabled`})}),children:[r(`span`,{className:`text-[11px] text-foreground-subtle`,children:i.data.selfEnrollment===`allowed`?t(`certificates.deviceSettingsRow.allowedAUserSignedIn`,`Allowed - a user signed in on a phone can keep it signed in. Pairing by QR works either way.`):t(`certificates.deviceSettingsRow.disabledOnlyAnAdminCan`,`Disabled - only an admin can pair a device, with a QR code.`)}),o!==null&&r(`span`,{className:`block text-[11px] text-danger`,children:o})]})})}s();function wn(e){let[t,n]=a(()=>Date.now());return i(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}s();var Tn=80,En=208;function Dn({open:t,users:n,onClose:i,onPaired:o}){let{t:s}=J(),c=W.deviceCredentials.startEnrollment.useMutation({onSuccess:o}),[l,u]=a(``),[d,f]=a(``),m=l===``?n[0]?.id??``:l,h=c.data,g=()=>{c.reset(),f(``),i()};return r(Ze,{open:t,onClose:g,title:s(`certificates.pairDeviceDialog.pairADevice`,`Pair a device`),icon:x,width:`md`,testId:`pair-device-dialog`,error:c.isError?c.error.message:null,footer:h===void 0?e(F,{type:`button`,onClick:()=>{let e=d.trim();m===``||e===``||c.mutate({userId:m,deviceName:e})},disabled:c.isPending||m===``||d.trim()===``,children:[c.isPending&&r(p,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),s(`certificates.pairDeviceDialog.createPairingCode`,`Create pairing code`)]}):r(F,{type:`button`,variant:`outline`,onClick:g,children:s(`certificates.pairDeviceDialog.done`,`Done`)}),children:h===void 0?e(`div`,{className:`space-y-3`,children:[r(`p`,{className:`text-[11px] text-foreground-subtle`,children:s(`certificates.pairDeviceDialog.createsAOneTimeCode`,`Creates a one-time code for a phone you hold. Scan it with the CamStack app on that phone; the phone then stays signed in as the chosen user until you revoke it.`)}),r(H,{label:s(`certificates.pairDeviceDialog.user`,`User`),required:!0,children:r(O,{value:m,onChange:e=>u(e.target.value),options:n.map(e=>({value:e.id,label:e.username}))})}),r(H,{label:s(`certificates.pairDeviceDialog.deviceName`,`Device name`),required:!0,description:s(`certificates.pairDeviceDialog.howThisPhoneIsListed`,`How this phone is listed, e.g. Anna's iPhone.`),children:r(ge,{value:d,maxLength:Tn,onChange:e=>f(e.target.value),placeholder:s(`certificates.pairDeviceDialog.annaSIphone`,`Anna's iPhone`),autoFocus:!0})})]}):r(On,{enrollUrl:h.enrollUrl,expiresAt:h.expiresAt,hubKnown:h.hubOrigin!==null,onRestart:()=>c.reset()})})}function On({enrollUrl:t,expiresAt:n,hubKnown:i,onRestart:a}){let{t:o}=J(),s=Lt(n,wn(1e3));return r(`div`,{className:`space-y-3`,"data-testid":`pair-issued`,children:e(`div`,{className:`flex flex-col items-center gap-3 sm:flex-row sm:items-start`,children:[r(`div`,{className:s.expired?`opacity-30`:void 0,children:r(Ke,{value:t,size:En,alt:o(`certificates.pairDeviceDialog.enrollmentQrCode`,`Enrollment QR code`)})}),e(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[r(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`certificates.pairDeviceDialog.openTheCamstackAppOn`,`Open the CamStack app on the phone and scan this code. It works once.`)}),r(`div`,{className:`text-sm font-semibold tabular-nums text-foreground`,role:`timer`,"data-testid":`pair-countdown`,children:s.expired?o(`certificates.pairDeviceDialog.expiredCreateANewCode`,`Expired - create a new code`):o(`certificates.pairDeviceDialog.expiresIn`,`Expires in {{label}}`,{label:s.label})}),e(`div`,{className:`flex items-center gap-1 rounded-md border border-border bg-background px-2 py-1`,children:[r(`code`,{className:`min-w-0 flex-1 select-all break-all font-mono text-[11px] text-foreground`,children:t}),r(Ne,{value:t,srLabel:`Enrollment link`})]}),!i&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[r(E,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),r(`span`,{children:o(`certificates.pairDeviceDialog.theHubCouldNotName`,`The hub could not name an address for this link, so the app must already know it.`)})]}),s.expired&&r(F,{type:`button`,variant:`outline`,size:`sm`,onClick:a,children:o(`certificates.pairDeviceDialog.newCode`,`New code`)})]})]})})}s();var kn={key:`access.nouns.device`};function An({pairOpen:t,onPairClose:i}){let{t:o}=J(),s=D(),c=ie(),l=W.useUtils(),u=W.deviceCredentials.listDeviceCredentials.useQuery({includeRevoked:!0}),d=Ee(),[f,p]=a(null),[m,h]=a(null),g=()=>void l.deviceCredentials.listDeviceCredentials.invalidate(),_=e=>t=>{h(null),p(`${e} failed: ${t.message}`)},v=()=>{h(null),g()},b=W.deviceCredentials.revokeDeviceCredential.useMutation({onSuccess:v,onError:_(`Revoke`)}),S=W.deviceCredentials.deleteDeviceCredential.useMutation({onSuccess:e=>{e.result!==`deleted`&&p(e.result===`live`?`Only a revoked device can be deleted: revoke it first.`:`That device no longer exists.`),v()},onError:_(`Delete`)}),C=W.deviceCredentials.renameDeviceCredential.useMutation({onSuccess:v,onError:_(`Rename`)}),w=xt(kn,e=>b.mutateAsync({id:e}),g),T=w.busy||m!==null,E=n(()=>(u.data??[]).map(It),[u.data]),O=async e=>{await s({title:o(`certificates.devicesCard.revoke`,`Revoke "{{name}}"?`,{name:e.name}),message:o(`certificates.devicesCard.sDeviceStopsSigningIn`,`{{ownerName}}'s device stops signing in at once and its open sessions end. To use it again it has to be paired anew. This cannot be undone.`,{ownerName:e.ownerName}),confirmLabel:o(`certificates.devicesCard.revoke2`,`Revoke`),variant:`danger`})&&(p(null),h(e.id),b.mutate({id:e.id}))},ne=async e=>{await s({title:o(`certificates.devicesCard.delete`,`Delete "{{name}}"?`,{name:e.name}),message:o(`certificates.devicesCard.isRemovedFromTheList`,`{{name}} is removed from the list. The audit trail keeps the revocation.`,{name:e.name}),confirmLabel:o(`common.delete`,`Delete`),variant:`danger`})&&(p(null),h(e.id),S.mutate({id:e.id}))},re=async e=>{let t=(await c({title:o(`certificates.devicesCard.renameDevice`,`Rename device`),label:o(`certificates.devicesCard.deviceName`,`Device name`),defaultValue:e.name,confirmLabel:o(`certificates.devicesCard.rename`,`Rename`)}))?.trim()??``;t===``||t===e.name||(p(null),h(e.id),C.mutate({id:e.id,deviceName:t}))},ae={label:o(`certificates.devicesCard.revoke2`,`Revoke`),icon:y,isAvailable:Tt,onRun:e=>void O(e),busyId:b.isPending?m:null,disabled:T},oe=[{label:o(`certificates.devicesCard.rename`,`Rename`),icon:te,tone:`neutral`,isAvailable:()=>!0,onRun:e=>void re(e),busyId:C.isPending?m:null,disabled:T},{label:o(`common.delete`,`Delete`),icon:ee,isAvailable:Mt,onRun:e=>void ne(e),busyId:S.isPending?m:null,disabled:T}];return e(Y,{id:`devices`,title:o(`certificates.devicesCard.devices`,`Devices`),icon:x,description:o(`certificates.devicesCard.phonesThatStaySignedIn`,`Phones that stay signed in with a certificate instead of a login. Revoking one signs it out at once; it has to be paired again.`),notice:X(f,w.outcome),onDismissNotice:()=>{p(null),w.dismiss()},children:[r(Cn,{}),r(Ut,{rows:E,label:o(`certificates.devicesCard.label`),isLoading:u.isPending,loadError:u.error===null?null:u.error.message||`Request failed`,emptyText:`No devices paired yet.`,expiresNone:`—`,action:ae,extraActions:oe,bulk:{revoke:w,noun:kn,isSelectable:Tt}}),r(Dn,{open:t,users:d.data??[],onClose:i,onPaired:g})]})}var jn=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/,Mn=/-----BEGIN ((?:RSA |EC |ENCRYPTED )?PRIVATE KEY)-----[\s\S]+?-----END \1-----/,Nn={certificate:`.pem,.crt,.cer`,privateKey:`.pem,.key`,ca:`.pem,.crt,.cer`};function Pn(e,t){if(t.trim()===``)return null;if(e===`privateKey`){let e=Mn.exec(t);return e===null?jn.test(t)?q.t(`helpers.pemFile.isCert`):q.t(`helpers.pemFile.notKey`):e[1]===`ENCRYPTED PRIVATE KEY`?q.t(`helpers.pemFile.encrypted`):null}return jn.test(t)?e===`certificate`&&Mn.test(t)?q.t(`helpers.pemFile.certHasKey`):null:Mn.test(t)?q.t(`helpers.pemFile.isKey`):q.t(`helpers.pemFile.notCert`)}function Fn(e){return e.text()}s();function In({kind:n,label:i,value:o,onChange:s,rows:c=6}){let{t:l}=J(),u=t(null),[d,f]=a(null),[p,m]=a(null),h=p??Pn(n,o),g=`pem-${n}`,_=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t!==void 0){f(t.name);try{let e=await Fn(t);m(null),s(e)}catch(e){m(`Could not read ${t.name}: ${e instanceof Error?e.message:String(e)}`)}}};return e(`div`,{className:`space-y-1`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[r(`label`,{htmlFor:g,className:`text-[11px] text-foreground-subtle`,children:i}),e(`div`,{className:`flex min-w-0 items-center gap-2`,children:[d!==null&&r(`span`,{className:`truncate font-mono text-[10px] text-foreground-subtle`,"data-testid":`${g}-file-name`,children:d}),r(ze,{ref:u,accept:Nn[n],onChange:e=>void _(e),className:`hidden`,"data-testid":`${g}-file`}),e(F,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>u.current?.click(),children:[r(fe,{className:`mr-1 h-3 w-3`}),l(`system.pemField.chooseFile`,`Choose file`)]})]})]}),r(Ye,{id:g,value:o,onChange:e=>{f(null),m(null),s(e.target.value)},rows:c,"aria-invalid":h!==null,className:`w-full rounded border border-border bg-surface px-2 py-1 font-mono text-[11px]`}),h!==null&&r(`p`,{className:`text-[11px] text-danger`,role:`alert`,children:h})]})}s();var Ln=30;function Rn(e){let t=Date.parse(e);return!Number.isNaN(t)&&Date.now()-t<Ln*864e5}function zn(e){if(e===null||e===``)return`—`;let t=e.replace(/:/g,``);return t.length<=16?e:`${t.slice(0,8)}…${t.slice(-8)}`}function Bn(){let{t}=J(),n=c(),i=Qe(void 0,{refetchInterval:15e3}),o=He({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),s=Ue({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),l=Be({onSuccess:()=>void n.invalidateQueries({queryKey:[[`localNetwork`]]})}),d=$e({onSuccess:()=>{h(!1),_(``),y(``),x(``),n.invalidateQueries({queryKey:[[`localNetwork`]]})}}),p=i.data,[m,h]=a(!1),[g,_]=a(``),[v,y]=a(``),[b,x]=a(``),S=()=>{if(!p?.caCertPem)return;let e=new Blob([p.caCertPem],{type:`application/x-pem-file`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`camstack-ca.crt`,n.click(),URL.revokeObjectURL(t)},C=p?.mode===`uploaded`?`Uploaded`:p?.mode===`generated`?`Generated local CA`:`TLS disabled`;return r(ke,{headingId:`local-access-certificate`,title:t(`system.localAccess.certificate`,`Certificate`),icon:u,children:e(`div`,{className:`${f} space-y-3`,children:[i.isError&&r(`p`,{className:`text-xs text-danger`,children:t(`system.localAccess.couldNotReadTlsStatus`,`Could not read TLS status.`)}),p?.reissueError&&r(U,{variant:`warning`,title:t(`system.localAccess.certificateReissue`,`Certificate reissue`),message:p.reissueError}),p?.restartRequired&&r(U,{variant:`warning`,title:t(`system.localAccess.restartRequired`,`Restart required`),message:t(`system.localAccess.theHttpsListenerStillServes`,`The HTTPS listener still serves the previous certificate. Restart the hub to apply it.`)}),p?.caMissing===!0&&r(U,{variant:`warning`,title:t(`system.localAccess.caMissingTitle`,`CA missing - devices cannot trust this hub`),message:t(`system.localAccess.caMissingBody`,"The uploaded certificate was not issued by a public CA and no CA was stored with it, so Download CA has nothing to hand out. Upload the certificate again together with its CA (for mkcert, the rootCA.pem in the folder `mkcert -CAROOT` prints).")}),p?.caReplacedAt!=null&&Rn(p.caReplacedAt)&&r(U,{variant:`warning`,title:t(`system.localAccess.caReplacedTitle`,`The local CA was replaced - re-install it on your devices`),message:t(`system.localAccess.caReplacedBody`,`The previous local CA had no name constraints: if its key ever leaked it could vouch for any website. The hub now uses a CA limited to private addresses and local names. Download it again and trust it on every phone and computer that used the old one (replaced {{when}}).`,{when:new Date(p.caReplacedAt).toLocaleString()})}),e(`dl`,{className:`grid grid-cols-1 gap-2 text-xs sm:grid-cols-2`,children:[e(`div`,{children:[r(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.mode`,`Mode`)}),r(`dd`,{className:`font-medium`,children:C})]}),e(`div`,{children:[r(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.validTo`,`Valid to`)}),r(`dd`,{className:`font-mono`,children:p?.validTo?new Date(p.validTo).toLocaleString():`—`})]}),e(`div`,{children:[r(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.leafSha256`,`Leaf SHA-256`)}),r(`dd`,{className:`font-mono`,title:p?.leafFingerprintSha256??void 0,children:zn(p?.leafFingerprintSha256??null)})]}),p?.storedUpload!=null&&e(`div`,{children:[r(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.storedUpload`,`Stored upload`)}),r(`dd`,{className:`font-medium`,children:t(`system.localAccess.storedUploadValue`,`valid to {{validTo}}, {{ca}}`,{validTo:new Date(p.storedUpload.validTo).toLocaleDateString(),ca:p.storedUpload.hasCa?t(`system.localAccess.storedUploadWithCa`,`with its CA`):t(`system.localAccess.storedUploadNoCa`,`no CA`)})})]}),e(`div`,{children:[r(`dt`,{className:`text-foreground-subtle`,children:t(`system.localAccess.caSha256`,`CA SHA-256`)}),r(`dd`,{className:`font-mono`,title:p?.caFingerprintSha256??void 0,children:p?.mode===`uploaded`&&p.caFingerprintSha256===null?r(`span`,{className:`font-sans text-foreground-subtle`,children:t(`system.localAccess.issuerNotIncludedInThe`,`Issuer not included in the upload (not the local CA)`)}):zn(p?.caFingerprintSha256??null)})]})]}),p&&p.sans.length>0&&r(`div`,{className:`flex flex-wrap gap-1`,children:p.sans.map(e=>r(`span`,{className:`rounded border border-border bg-surface px-1.5 py-0.5 font-mono text-[10px] text-foreground-subtle`,children:e},e))}),e(`div`,{className:`flex flex-wrap gap-2`,children:[r(N,{label:t(`system.localAccess.regenerate`,`Regenerate`),title:t(`system.localAccess.issueANewLeaf`,`Issue a new leaf?`),description:t(`system.localAccess.issuesANewLeafUnder`,`Issues a new leaf under the current local CA. Clients that trust the CA keep working. The HTTPS listener reloads.`),confirmLabel:t(`system.localAccess.regenerate`,`Regenerate`),disabled:p?.mode===`uploaded`||o.isPending,action:()=>o.mutateAsync({})}),r(F,{size:`sm`,variant:`outline`,onClick:()=>h(e=>!e),children:t(`system.localAccess.upload`,`Upload`)}),p?.caCertPem&&r(F,{size:`sm`,variant:`outline`,onClick:S,children:t(`system.localAccess.downloadCa`,`Download CA`)}),p?.mode===`uploaded`&&r(N,{label:t(`system.localAccess.revertToGenerated`,`Revert to generated`),title:t(`system.localAccess.revertTitle`,`Switch back to the generated certificate?`),description:t(`system.localAccess.keepsTheUploadedPair`,`Returns to the generated local CA. The uploaded certificate and its CA stay stored here; you can select them again.`),confirmLabel:t(`system.localAccess.revert`,`Revert`),disabled:s.isPending,action:()=>s.mutateAsync({})}),p?.mode===`generated`&&p.storedUpload!=null&&r(N,{label:t(`system.localAccess.useUploaded`,`Use uploaded certificate`),title:t(`system.localAccess.useUploadedTitle`,`Serve the stored upload again?`),description:t(`system.localAccess.useUploadedDescription`,`The stored uploaded certificate replaces the generated one on the HTTPS listener. The generated certificate stays stored.`),confirmLabel:t(`system.localAccess.useUploaded`,`Use uploaded certificate`),disabled:l.isPending,action:()=>l.mutateAsync(void 0)})]}),m&&e(`div`,{className:`space-y-2 border-t border-border pt-3`,children:[r(In,{kind:`certificate`,label:t(`system.localAccess.certificateOrFullChainPem`,`Certificate or full chain (PEM)`),value:g,onChange:_}),r(In,{kind:`privateKey`,label:t(`system.localAccess.privateKeyPem`,`Private key (PEM)`),value:v,onChange:y}),r(In,{kind:`ca`,label:t(`system.localAccess.caPemRequired`,`CA (PEM) - required unless the certificate comes from a public CA`),value:b,onChange:x,rows:4}),r(F,{size:`sm`,disabled:!g.trim()||!v.trim()||Pn(`certificate`,g)!==null||Pn(`privateKey`,v)!==null||Pn(`ca`,b)!==null||d.isPending,onClick:()=>d.mutate({certPem:g,keyPem:v,...b.trim()?{caPem:b}:{}}),children:t(`system.localAccess.saveCertificate`,`Save certificate`)}),d.isError&&r(`p`,{className:`text-xs text-danger`,children:d.error instanceof Error?d.error.message:t(`system.localAccess.uploadFailed`,`Upload failed`)})]})]})})}var Vn={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`};function Hn(e){let t=e.find(e=>e.isHub);return t?.https.kind===`served`?t.https.status.caFingerprintSha256:null}function Un({https:t,mesh:n,now:i}){let{t:a}=J(),o=Qe().data?.caCertPem??``,s=()=>{if(o===``)return;let e=URL.createObjectURL(new Blob([o],{type:`application/x-pem-file`})),t=document.createElement(`a`);t.href=e,t.download=`camstack-ca.crt`,t.click(),URL.revokeObjectURL(e)},c=n?.ca,l=c?.state===`ready`?Date.parse(c.validTo):null,u=n?.listener;return e(`div`,{className:`space-y-1`,"data-testid":`ca-strip`,children:[r(G,{label:a(`certificates.caStrip.localHttpsCaSha256`,`Local HTTPS CA (SHA-256)`),valueClassName:`font-mono`,children:e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[Hn(t)??`—`,o!==``&&e(F,{type:`button`,variant:`ghost`,size:`sm`,onClick:s,children:[r(se,{className:`h-3 w-3`,"aria-hidden":!0}),a(`certificates.caStrip.downloadCa`,`Download CA`)]})]})}),r(G,{label:a(`certificates.caStrip.clusterCaSha256`,`Cluster CA (SHA-256)`),valueClassName:`font-mono`,children:c===void 0?`—`:c.state===`ready`?c.fingerprintSha256:r(`span`,{className:`text-danger`,children:a(`certificates.caStrip.unavailable`,{reason:c.reason})})}),c?.state===`ready`&&e(G,{label:a(`certificates.caStrip.clusterCaValidUntil`,`Cluster CA valid until`),children:[c.validTo,l!==null&&!Number.isNaN(l)&&e(`span`,{className:`ml-2 text-[10px] ${Vn[Vt(l,i)]}`,children:[`(`,Dt(l,i),`)`]})]}),u!==void 0&&e(G,{label:a(`certificates.caStrip.nodeListener`,`Node listener`),children:[u.state===`open`&&r(K,{variant:`success`,children:a(`certificates.caStrip.open`,`Open`)}),u.state===`not-started`&&r(K,{variant:`default`,children:a(`certificates.caStrip.notStarted`,`Not started`)}),u.state===`closed`&&e(`span`,{className:`text-danger`,children:[a(`certificates.caStrip.closedSince`,{when:Ot(u.since)}),` `,u.reason]})]}),n!==void 0&&!n.registryAvailable&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[r(E,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),r(`span`,{children:a(`certificates.caStrip.theCertificateRegistryIsNot`,`The certificate registry is not up, so the node list below is incomplete.`)})]})]})}function Wn(e,t){let n=new Set;for(let t of e)n.add(t.nodeId);for(let e of t?.nodes??[])n.add(e.nodeId);return[...n].map(n=>{let r=e.find(e=>e.nodeId===n)??null,i=t?.nodes.find(e=>e.nodeId===n)??null;return{nodeId:n,isHub:r?.isHub??n===`hub`,online:r?.online??i?.online??!1,https:r,mesh:i}}).toSorted((e,t)=>Number(t.isHub)-Number(e.isHub)||e.nodeId.localeCompare(t.nodeId))}function Gn(e){return e.isHub?q.t(`helpers.nodesModel.hubReissued`):e.mesh===null?q.t(`helpers.nodesModel.noCertRecorded`):e.online?null:q.t(`helpers.certificateModel.nodeOffline`)}function Kn(e){return e.isHub||e.mesh===null?Gn(e):null}var qn={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`},Jn={enroll:`Issued at enrollment`,renewal:`Issued by a renewal`,boot:`Issued at boot`,pairing:`Issued at pairing`,observed:`Observed on its connection`},Yn={uploaded:`Uploaded`,generated:`Generated`,disabled:`Disabled`};function Xn(e){let t=e.https?.https;return t?.kind===`served`?zt(t.status.validTo):null}function Zn({ms:t,now:n}){return t===null?r(`span`,{className:`text-foreground-subtle`,children:`—`}):e(`div`,{children:[r(`div`,{children:Ot(t)}),r(`div`,{className:`text-[10px] ${qn[Vt(t,n)]}`,children:Dt(t,n)})]})}function Qn({row:t}){let{t:n}=J(),i=t.https?.https;return i===void 0?r(`span`,{className:`text-foreground-subtle`,children:`—`}):i.kind===`served`?e(`div`,{title:i.status.leafFingerprintSha256??``,children:[r(K,{variant:`success`,className:`text-[10px]`,children:n(`certificates.nodesColumns.served`,`Served`)}),r(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:Yn[i.status.mode]}),r(`div`,{className:`mt-1 font-mono text-[10px] text-foreground-subtle`,children:Rt(i.status.leafFingerprintSha256)}),i.status.sans.length>0&&r(`div`,{className:`mt-0.5 max-w-[14rem] truncate font-mono text-[10px] text-foreground-subtle`,title:i.status.sans.join(`, `),children:i.status.sans.join(`, `)})]}):e(`div`,{className:`max-w-[16rem]`,children:[r(K,{variant:i.kind===`unreadable`?`danger`:`warning`,className:`text-[10px]`,children:i.kind===`unreadable`?n(`certificates.nodesColumns.unreadable`,`Unreadable`):n(`certificates.nodesColumns.notServed`,`Not served`)}),r(`div`,{className:`mt-1 whitespace-normal text-[10px] text-foreground-subtle`,children:i.reason})]})}function $n({row:t}){let{t:n}=J(),i=t.mesh?.current??null;if(i===null)return r(`span`,{className:`text-foreground-subtle`,children:n(`certificates.nodesColumns.noneRecorded`,`None recorded`)});let a=t.mesh?.history.length??0;return e(`div`,{children:[r(`div`,{className:`font-mono text-[11px]`,title:i.serial,children:Ft(i.serial)}),r(`div`,{className:`font-mono text-[10px] text-foreground-subtle`,title:i.fingerprintSha256,children:Rt(i.fingerprintSha256)}),e(`div`,{className:`text-[10px] text-foreground-subtle`,children:[Jn[i.issuedVia],a>0?` · ${n(`certificates.nodesColumns.earlier`,{count:a})}`:``]})]})}function er({row:e}){let{t}=J(),n=e.mesh?.presentingCurrent??null;return n===null?r(`span`,{className:`text-foreground-subtle`,children:e.online?`—`:t(`certificates.nodesColumns.offline`,`Offline`)}):n?r(K,{variant:`success`,className:`text-[10px]`,children:t(`common.yes`,`Yes`)}):r(K,{variant:`warning`,className:`text-[10px]`,children:t(`certificates.nodesColumns.noPresentsAnother`,`No - presents another`)})}function tr(t){let n=t.icon;return e(F,{type:`button`,variant:`ghost`,size:`sm`,className:t.danger?`text-danger hover:bg-danger/10`:void 0,disabled:t.reason!==null||t.busy,title:t.reason??void 0,"aria-label":t.ariaLabel,onClick:t.onClick,children:[t.spinning?r(p,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):r(n,{className:`h-3 w-3`,"aria-hidden":!0}),t.label]})}function nr({reasons:t}){let{t:n}=J();return e(Pe,{className:`inline-block`,children:[r(je,{children:r(`span`,{className:`cursor-help text-[11px] text-foreground-subtle`,"data-testid":`hub-managed-note`,children:n(`certificates.nodesColumns.managedByTheHub`,`Managed by the hub`)})}),r(Re,{children:r(`ul`,{className:`max-w-xs space-y-1 whitespace-normal text-left text-[11px]`,children:t.map(e=>r(`li`,{children:e},e))})})]})}function rr({row:t,o:n}){let{t:i}=J(),a=t.https===null?`No HTTPS inventory for this node.`:kt(t.https).reason,o=Gn(t),s=Kn(t),c=e=>n.running?.nodeId===t.nodeId&&n.running.action===e,l=e=>!t.isHub||e===null,u=[a,o,s].filter((e,t,n)=>e!==null&&n.indexOf(e)===t);return e(`div`,{className:`flex w-44 flex-col items-end gap-1`,children:[e(`div`,{className:`flex flex-col items-end gap-0.5`,children:[l(a)&&r(tr,{label:i(`certificates.nodesColumns.renewHttps`,`Renew HTTPS`),ariaLabel:i(`certificates.nodesColumns.renewTheCertificateOn`,`Renew the certificate on {{nodeId}}`,{nodeId:t.nodeId}),icon:m,reason:a,busy:n.busy,spinning:c(`renew-https`),danger:!1,onClick:()=>n.onRenewHttps(t)}),l(o)&&r(tr,{label:c(`renew-identity`)?i(`certificates.nodesColumns.renewing`,`Renewing…`):i(`certificates.nodesColumns.renewIdentity`,`Renew identity`),ariaLabel:i(`certificates.nodesColumns.renewTheClusterCertificateOf`,`Renew the cluster certificate of {{nodeId}}`,{nodeId:t.nodeId}),icon:m,reason:o,busy:n.busy,spinning:c(`renew-identity`),danger:!1,onClick:()=>n.onRenewIdentity(t)}),l(s)&&r(tr,{label:i(`certificates.nodesColumns.revokeIdentity`,`Revoke identity`),ariaLabel:i(`certificates.nodesColumns.revokeTheClusterCertificateOf`,`Revoke the cluster certificate of {{nodeId}}`,{nodeId:t.nodeId}),icon:y,reason:s,busy:n.busy,spinning:c(`revoke-identity`),danger:!0,onClick:()=>n.onRevokeIdentity(t)})]}),t.isHub&&u.length>0&&r(nr,{reasons:u}),!t.isHub&&a!==null&&t.https!==null&&r(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`renew-reason-${t.nodeId}`,children:a}),!t.isHub&&o!==null&&r(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`mesh-reason-${t.nodeId}`,children:o})]})}function ir(t){return[{key:`node`,header:q.t(`certificates.nodesColumns.node`,`Node`),sortValue:e=>e.isHub?``:e.nodeId.toLowerCase(),render:t=>e(`div`,{className:`flex items-center gap-1.5`,children:[r(`span`,{className:`font-medium text-foreground`,children:t.nodeId}),t.nodeId===`hub`&&r(K,{variant:`info`,className:`text-[10px]`,children:q.t(`common.hubWord`)}),!t.online&&r(K,{variant:`default`,className:`text-[10px]`,children:q.t(`common.offline`)})]})},{key:`https-state`,header:`HTTPS`,notSortableReason:`A state with a reason has no single order.`,render:e=>r(Qn,{row:e})},{key:`https-expires`,header:q.t(`certificates.nodesColumns.httpsExpires`,`HTTPS expires`),sortValue:e=>Xn(e),render:e=>r(Zn,{ms:Xn(e),now:t.now})},{key:`identity`,header:q.t(`certificates.nodesColumns.identity`,`Identity`),sortValue:e=>e.mesh?.current?.serial??null,render:e=>r($n,{row:e})},{key:`identity-expires`,header:q.t(`certificates.nodesColumns.identityExpires`,`Identity expires`),sortValue:e=>e.mesh?.current?.notAfter??null,render:e=>r(Zn,{ms:e.mesh?.current?.notAfter??null,now:t.now})},{key:`presenting`,header:q.t(`certificates.nodesColumns.inUse`,`In use`),notSortableReason:`Offline nodes have no answer to order by.`,render:e=>r(er,{row:e})},{key:`actions`,header:q.t(`certificates.nodesColumns.actions`,`Actions`),align:`right`,notSortableReason:`Actions have no order.`,render:e=>r(rr,{row:e,o:t})}]}s();function ar(){let{t}=J(),i=D(),o=W.useUtils(),s=wn(6e4),c=W.certificates.listHttpsCertificates.useQuery(),l=W.certificates.getMeshCertificates.useQuery(),[u,d]=a(null),[f,p]=a(null),[m,g]=a(null),_=()=>{g(null),o.certificates.listHttpsCertificates.invalidate(),o.certificates.getMeshCertificates.invalidate()},v=e=>(t,n)=>{g(null),d(`${n.nodeId}: ${e} - ${t.message}`)},y=W.certificates.renewHttpsOnNode.useMutation({onSuccess:(e,n)=>{p({tone:`success`,message:e.restartRequired?t(`certificates.nodesCard.newCertificateIssuedRestartThe`,`{{nodeId}}: new certificate issued. Restart the node to serve it.`,{nodeId:n.nodeId}):t(`certificates.nodesCard.newCertificateIssuedAndServed`,`{{nodeId}}: new certificate issued and served.`,{nodeId:n.nodeId})}),_()},onError:v(`renewal failed`)}),b=W.certificates.renewMeshOnNode.useMutation({onSuccess:e=>{p(Pt(e)),_()},onError:v(`renewal could not start`)}),x=W.certificates.revokeMeshOnNode.useMutation({onSuccess:e=>{p({tone:`success`,message:`${e.nodeId}: ${e.next}`}),_()},onError:v(`revoke failed`)}),S=y.isPending||b.isPending||x.isPending,C=(e,t)=>{d(null),p(null),g({nodeId:e,action:t})},w=async e=>{await i({title:t(`certificates.nodesCard.renewHttpsOn`,`Renew HTTPS on "{{nodeId}}"?`,{nodeId:e.nodeId}),message:e.isHub?t(`certificates.nodesCard.aNewCertificateIsIssued`,`A new certificate is issued from the local CA. Clients that trust the CA keep working.`):t(`certificates.nodesCard.theNodeMakesANew`,`The node makes a new key, the hub signs it and the node switches over without a restart. It keeps serving what it had if anything fails.`),confirmLabel:t(`certificates.nodesCard.renew`,`Renew`)})&&(C(e.nodeId,`renew-https`),y.mutate({nodeId:e.nodeId}))},T=e=>{C(e.nodeId,`renew-identity`),b.mutate({nodeId:e.nodeId})},E=async e=>{await i({title:t(`certificates.nodesCard.revokeTheIdentityOf`,`Revoke the identity of "{{nodeId}}"?`,{nodeId:e.nodeId}),message:t(`certificates.nodesCard.isDisconnectedAtOnceAnd`,`{{nodeId}} is disconnected at once and can no longer connect. To bring it back it must be paired again from System → Cluster → Agents. It stays in the node list until you forget it on the Cluster page. This cannot be undone.`,{nodeId:e.nodeId}),confirmLabel:t(`certificates.nodesCard.revokeAndDisconnect`,`Revoke and disconnect`),variant:`danger`})&&(C(e.nodeId,`revoke-identity`),x.mutate({nodeId:e.nodeId}))},O=ir({now:s,busy:S,running:m,onRenewHttps:e=>void w(e),onRenewIdentity:T,onRevokeIdentity:e=>void E(e)}),ee=n(()=>Wn(c.data??[],l.data),[c.data,l.data]),te=l.data?.registryAvailable??!0;return r(Y,{id:`nodes`,title:t(`certificates.nodesCard.nodes`,`Nodes`),icon:h,description:t(`certificates.nodesCard.eachNodeHoldsTwoCertificates`,`Each node holds two certificates: one it serves over HTTPS, one that proves its identity to the hub. Renewing replaces a certificate without a gap; revoking an identity cuts the node off until it re-joins.`),notice:X(u,f),onDismissNotice:()=>{d(null),p(null)},children:r(xn,{isPending:c.isPending||l.isPending,error:c.error??l.error,what:`node certificates`,onRetry:()=>{c.refetch(),l.refetch()},children:e(`div`,{className:`space-y-3`,children:[r(Un,{https:c.data??[],mesh:l.data,now:s}),r(be,{columns:O,rows:ee,rowKey:e=>e.nodeId,minWidthPx:960,maxBodyHeight:qe,defaultSort:{columnKey:`node`,dir:`asc`},emptyMessage:te?t(`certificates.nodesCard.noNodesReported`,`No nodes reported.`):t(`certificates.nodesCard.theCertificateRegistryIsNot`,`The certificate registry is not available yet, so nodes cannot be listed.`)})]})})})}function or({pairOpen:t,onPairClose:n}){return e(`div`,{className:`space-y-4`,"data-testid":`certificates-page`,children:[r(An,{pairOpen:t,onPairClose:n}),r(Sn,{}),r(Bn,{}),r(ar,{})]})}function sr({userId:t,username:n,onClose:i}){let{t:a}=J(),o=D(),s=W.useUtils(),c=ye({userId:t}),l=W.auth.listLoginMethods.useQuery(),u=I({onSuccess:()=>void s.userManagement.listExternalIdentities.invalidate()}),d=new Map((l.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),f=c.data??[],m=async(e,r)=>{await o({title:a(`users.externalIdentitiesModal.removeSignInLink`,`Remove sign-in link`),message:a(`users.externalIdentitiesModal.willNoLongerBeAble`,`"{{username}}" will no longer be able to sign in with this {{label}} account.`,{username:n,label:r}),confirmLabel:a(`common.remove`,`Remove`),variant:`danger`})&&u.mutate({userId:t,provider:e.provider,subject:e.subject})};return r(R,{open:!0,onOpenChange:e=>!e&&i(),children:e(P,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[r(V,{children:e(et,{className:`flex items-center gap-2`,children:[r(b,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[a(`users.externalIdentitiesModal.linkedSignInAccounts`,`Linked sign-in accounts`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[a(`users.externalIdentitiesModal.user`,`User:`),` `,r(`span`,{className:`font-mono`,children:n})]})]})]})}),r(B,{className:`space-y-3`,children:c.isLoading?e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[r(p,{className:`h-3.5 w-3.5 animate-spin`}),a(`common.loading`,`Loading…`)]}):f.length===0?r(`p`,{className:`text-xs text-foreground-subtle`,children:a(`users.externalIdentitiesModal.noLinkedAccountsOnlyThe`,`No linked accounts. Only the user can link one, from their own profile page.`)}):r(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:f.map(t=>{let n=d.get(t.provider),i=n??t.provider;return e(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[e(`div`,{className:`flex-1 min-w-0`,children:[e(`div`,{className:`font-medium text-foreground truncate`,children:[i,n===void 0&&r(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:a(`users.externalIdentitiesModal.providerUnavailable`,`provider unavailable`)})]}),e(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[t.label??t.subject,` ·`,` `,new Date(t.linkedAt).toLocaleDateString()]})]}),e(F,{variant:`unstyled`,onClick:()=>void m(t,i),disabled:u.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[r(he,{className:`h-3 w-3`}),a(`common.remove`,`Remove`)]})]},`${t.provider}|${t.subject}`)})})}),r(L,{children:r(F,{onClick:i,variant:`secondary`,children:a(`common.close`,`Close`)})})]})})}function cr({userId:t,username:n,onClose:i}){let{t:a}=J(),o=c(),s=D(),u=Je({userId:t}),d=u.data,f=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),m=Oe({onSuccess:()=>{f(),i()}}),h=u.isLoading?`loading`:d?.enabled?`enrolled`:`not_enrolled`;return r(R,{open:!0,onOpenChange:e=>!e&&i(),children:e(P,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[r(V,{children:e(et,{className:`flex items-center gap-2`,children:[r(x,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[a(`users.totpModal.twoFactorAuthentication`,`Two-factor authentication`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[a(`users.totpModal.user`,`User:`),` `,r(`span`,{className:`font-mono`,children:n})]})]})]})}),e(B,{className:`space-y-4`,children:[h===`loading`&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[r(p,{className:`h-3.5 w-3.5 animate-spin`}),a(`users.totpModal.checkingStatus`,`Checking status…`)]}),h===`not_enrolled`&&e(`div`,{className:`rounded-md border border-border bg-surface-hover/30 px-3 py-2.5 flex items-start gap-2.5 text-xs text-foreground-subtle`,children:[r(C,{className:`h-4 w-4 mt-0.5 shrink-0`}),e(`div`,{children:[r(`div`,{className:`font-medium text-foreground`,children:a(`users.totpModal.2faNotEnrolled`,`2FA not enrolled`)}),r(`p`,{className:`mt-0.5`,children:a(`users.totpModal.onlyTheUserThemselvesCan`,`Only the user themselves can enable 2FA, from their own profile page.`)})]})]}),h===`enrolled`&&d&&e(l,{children:[e(`div`,{className:`rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5 flex items-start gap-2.5`,children:[r(T,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),e(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[r(`div`,{className:`font-medium`,children:a(`users.totpModal.2faIsActive`,`2FA is active`)}),r(`div`,{className:`text-foreground-subtle`,children:a(`common.enrolledOn`,{when:d.confirmedAt?new Date(d.confirmedAt).toLocaleString():`—`})})]})]}),r(`div`,{className:`text-[11px] text-foreground-subtle`,children:a(`users.totpModal.removingHereClearsTheServer`,`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`)}),e(`div`,{className:`flex justify-end gap-2`,children:[r(F,{onClick:i,variant:`secondary`,children:a(`common.close`,`Close`)}),e(F,{variant:`unstyled`,onClick:async()=>{await s({title:a(`users.totpModal.remove2fa`,`Remove 2FA`),message:a(`users.totpModal.removeTwoFactorAuthenticationFor`,`Remove two-factor authentication for "{{username}}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,{username:n}),confirmLabel:a(`common.remove`,`Remove`),variant:`danger`})&&m.mutate({userId:t})},disabled:m.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[m.isPending?r(p,{className:`h-3 w-3 animate-spin`}):r(oe,{className:`h-3 w-3`}),a(`users.totpModal.remove2fa`,`Remove 2FA`)]})]})]})]})]})})}s();function lr({userId:t,username:n,onClose:i}){let{t:o}=J(),{user:s,logout:c}=tt(),l=s?.id===t,u=D(),d=W.useUtils(),f=W.auth.listSessions.useQuery({userId:t}),[m,h]=a(null),g=W.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(l&&`userId`in t){c();return}d.auth.listSessions.invalidate()},onError:e=>h(`Sign out failed: ${e.message}`)}),_=async e=>{await u({title:o(`users.userSessionsModal.signOutThisSession`,`Sign out this session`),message:o(`users.userSessionsModal.onWillHaveToSign`,`"{{username}}" on {{label}} will have to sign in again.`,{username:n,label:wt(e.client).label}),confirmLabel:o(`users.userSessionsModal.signOut`,`Sign out`),variant:`danger`})&&(h(null),g.mutate({id:e.id}))},v=async()=>{await u({title:o(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),message:l?o(`users.userSessionsModal.everySessionOfYourOwn`,`Every session of your own account ends, this browser included: you will be signed out here too.`):o(`users.userSessionsModal.everySessionOfEndsAt`,`Every session of "{{username}}" ends at once; each device has to sign in again.`,{username:n}),confirmLabel:o(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),variant:`danger`})&&(h(null),g.mutate({userId:t}))},y=g.isPending&&g.variables!==void 0&&`id`in g.variables?g.variables.id:null;return r(R,{open:!0,onOpenChange:e=>!e&&i(),children:e(P,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[r(V,{children:e(et,{className:`flex items-center gap-2`,children:[r(me,{className:`h-4 w-4 text-primary`}),e(`span`,{children:[o(`users.userSessionsModal.activeSessions`,`Active sessions`),e(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[o(`users.userSessionsModal.user`,`User:`),` `,r(`span`,{className:`font-mono`,children:n})]})]})]})}),e(B,{className:`space-y-3`,children:[m!==null&&r(`div`,{className:`text-[11px] text-danger`,children:m}),r(Bt,{sessions:f.data??[],isLoading:f.isLoading,loadError:f.isError?f.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void _(e),revokingId:y})]}),e(L,{className:`justify-between`,children:[e(F,{variant:`unstyled`,onClick:()=>void v(),disabled:g.isPending||(f.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[g.isPending&&y===null?r(p,{className:`h-3 w-3 animate-spin`}):r(M,{className:`h-3 w-3`}),o(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`)]}),r(F,{onClick:i,variant:`secondary`,children:o(`common.close`,`Close`)})]})]})})}function ur({scopes:t,invalidReason:n}){let{t:i}=J(),a=ae(),s=o({queryKey:[`auth`,`previewScope`,t,!1],enabled:n===null,queryFn:()=>a.trpcClient.auth.previewScope.query({scopes:[...t],isAdmin:!1})}),{data:c}=z({projection:`slim`}),l=c?.length??null;if(n!==null)return e(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,"data-testid":`role-preview`,children:[r(v,{className:`h-3 w-3 shrink-0`}),n]});if(s.isLoading)return e(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,"data-testid":`role-preview`,children:[r(p,{className:`h-3 w-3 shrink-0 animate-spin`}),i(`users.rolePreview.resolving`)]});if(s.isError||!s.data)return r(`p`,{className:`text-[11px] text-danger`,"data-testid":`role-preview`,children:i(`users.rolePreview.couldNotResolve`)});let u=s.data.viewableDeviceCount,d=s.data.device.view.all?i(`users.rolePreview.everyDevice`,{count:u}):l===null?i(`users.rolePreview.devicesVisible`,{count:u}):i(`users.rolePreview.devicesVisibleOf`,{count:u,total:l});return e(`p`,{className:`flex items-center gap-1.5 text-[11px] ${u===0?`text-warning`:`text-foreground`}`,"data-testid":`role-preview`,children:[u===0?r(v,{className:`h-3 w-3 shrink-0`}):r(ne,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),u===0?i(`users.rolePreview.noDevice`):d]})}function dr(e){let t=le(e.scopes??[]);if(t===null)return{role:e.isAdmin?`admin`:`viewer`,mode:`except`,pickedIds:[],viewer:ce,unconfigured:!e.isAdmin};let n=vr(t);return{role:e.isAdmin?`admin`:`viewer`,mode:n.mode,pickedIds:n.pickedIds,viewer:yr(n.mode,n.pickedIds,t.features),unconfigured:!1}}function fr(e,t){return{...e,role:t}}function pr(e,t){return{...e,mode:t,viewer:yr(t,e.pickedIds,e.viewer.features)}}function mr(e,t){let n=br(t);return{...e,pickedIds:n,viewer:yr(e.mode,n,e.viewer.features)}}function hr(e,t,n){let r=e.viewer.features.filter(e=>e!==t),i=n?[...r,t]:r;return{...e,viewer:yr(e.mode,e.pickedIds,i)}}function gr(e){return e.role===`viewer`&&e.mode===`only`&&e.pickedIds.length===0?`no-allowed-device`:null}function _r(e){return gr(e)===null?e.role===`admin`?{isAdmin:!0,scopes:[]}:{isAdmin:!1,scopes:[e.viewer]}:null}function vr(e){if(e.allow===`*`)return{mode:`except`,pickedIds:e.block};let t=new Set(e.block);return{mode:`only`,pickedIds:e.allow.filter(e=>!t.has(e))}}function yr(e,t,n){let r=br(t);return e===`except`?{type:`viewer`,allow:`*`,block:r,features:[...n]}:{type:`viewer`,allow:r,block:[],features:[...n]}}function br(e){return[...new Set(e)]}s();var xr=`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`;function Sr(e,t){return e?`failed`:t===void 0?`pending`:`answered`}function Cr(e){let t=[];for(let n of e)n.parentDeviceId===null&&t.push({id:n.id,name:n.name,type:String(n.type),...n.location===null?{}:{location:n.location}});return t}function wr({user:t,isSelf:i,onClose:o,onSubmit:s,submitting:c,error:u}){let{t:d}=J(),[f,m]=a(n(()=>dr(t),[t])),h=z({projection:`slim`}),g=h.data,_=Sr(h.isError,g),v=n(()=>Cr(g??[]),[g]),y=n(()=>({state:_,devices:_===`answered`?(g??[]).map(e=>({id:e.id,name:e.name})):void 0}),[_,g]),b=gr(f),x=_r(f),C=b===`no-allowed-device`?d(`users.userAccessModal.pickAllowedDevice`):null,w=e=>{m(fr(f,e))},T=[{value:`except`,label:d(`users.userAccessModal.modeExcept`)},{value:`only`,label:d(`users.userAccessModal.modeOnly`)}];return r(R,{open:!0,onOpenChange:e=>!e&&o(),children:e(P,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[r(V,{children:r(et,{children:d(`users.userAccessModal.title`,{name:t.username})})}),e(B,{className:`space-y-4`,children:[f.unconfigured&&f.role===`viewer`&&r(U,{variant:`warning`,title:d(`users.userAccessModal.noAccessYet`),message:d(`users.userAccessModal.noAccessYetDetail`,{name:t.username})}),e(`section`,{className:`space-y-2`,children:[r(`h3`,{className:xr,children:d(`users.userAccessModal.role`)}),e(`div`,{role:`radiogroup`,"aria-label":d(`users.userAccessModal.role`),className:`grid gap-1.5 sm:grid-cols-2`,children:[r(Tr,{name:`admin`,checked:f.role===`admin`,label:d(`users.userAccessModal.admin`),description:d(`users.userAccessModal.adminDescription`),onPick:()=>w(`admin`)}),r(Tr,{name:`viewer`,checked:f.role===`viewer`,disabled:i,label:d(`users.userAccessModal.viewer`),description:d(i?`users.userAccessModal.cannotDemoteSelf`:`users.userAccessModal.viewerDescription`),onPick:()=>w(`viewer`)})]})]}),f.role===`viewer`&&e(l,{children:[e(`section`,{className:`space-y-3`,children:[r(`h3`,{className:xr,children:d(`users.userAccessModal.devices`)}),r(we,{label:d(`users.userAccessModal.whichDevices`),value:f.mode,options:T,onChange:e=>m(pr(f,e))}),r(ve,{devices:v,listState:_,fleet:y,value:[...f.pickedIds],onChange:e=>m(mr(f,e)),emptyMeansAll:f.mode===`except`,noun:`device`,testId:`viewer-device-picker`}),r(ur,{scopes:x?.scopes??[],invalidReason:C})]}),e(`section`,{className:`space-y-2`,children:[r(`h3`,{className:xr,children:d(`users.userAccessModal.features`)}),r(`div`,{className:`space-y-1`,children:k.map(t=>e(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-md p-1.5 hover:bg-surface-hover`,children:[r(S,{className:`mt-0.5`,checked:f.viewer.features.includes(t.id),onChange:e=>m(hr(f,t.id,e.target.checked))}),e(`span`,{className:`min-w-0`,children:[r(`span`,{className:`block text-[12px] font-medium text-foreground`,children:d(`users.viewerFeatures.${t.id}.label`,t.label)}),r(`span`,{className:`block text-[10px] text-foreground-subtle`,children:d(`users.viewerFeatures.${t.id}.description`,t.description)})]})]},t.id))})]})]}),u!==null&&r(U,{message:u})]}),e(L,{children:[r(F,{variant:`outline`,size:`sm`,onClick:o,children:d(`common.cancel`,`Cancel`)}),r(F,{size:`sm`,onClick:()=>x!==null&&s(x),disabled:c||x===null,children:c?r(p,{className:`h-3 w-3 animate-spin`}):d(`users.userAccessModal.saveAccess`)})]})]})})}function Tr({name:t,checked:n,disabled:i=!1,label:a,description:o,onPick:s}){return e(`label`,{className:`flex items-start gap-2 rounded-lg border p-2.5 transition-colors ${n?`border-primary bg-primary/5`:`border-border hover:bg-surface-hover`} ${i?`cursor-not-allowed opacity-60`:`cursor-pointer`}`,children:[r(Xe,{name:`user-role`,value:t,checked:n,disabled:i,onChange:s,className:`mt-0.5`}),e(`span`,{className:`min-w-0`,children:[r(`span`,{className:`block text-[12px] font-medium text-foreground`,children:a}),r(`span`,{className:`block text-[10px] text-foreground-subtle`,children:o})]})]})}s();var Er=8;function Dr(){return{username:``,password:``,isAdmin:!1}}function Or(e){return{id:e.id,username:e.username,password:``,isAdmin:e.isAdmin}}function kr(e){return e instanceof Error?e.message:q.t(`admin.system.users.genericError`)}function Ar(){let{t}=J(),n=c(),{user:o}=tt(),{state:s,openNew:u,openEdit:d,close:f}=Ve(),[m,h]=a(null),[_,v]=a(null),[y,C]=a(!1),{data:T,isLoading:E,isError:O,error:ne,refetch:ae}=Ee(),oe=D(),se=ie(),k=()=>n.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),ce=Se(),le=xe({onSuccess:k}),A=Te({onSuccess:k}),j=De({onSuccess:k}),ue=Ce(),[M,de]=a(null),[fe,he]=a(!1),[_e,ve]=a(null),[ye,N]=a(null),[P,we]=a(null),[I,L]=a(null),R=T??[],z=s.mode===`edit`?R.find(e=>e.id===s.id)??null:null,Oe=()=>{h(null),v(null),C(!1),ce.reset(),A.reset(),f()};i(()=>{if(s.mode===`closed`){h(null),v(null),C(!1);return}if(s.mode===`new`){h(e=>e!==null&&e.id===void 0?e:Dr());return}if(z===null){E||f();return}h(e=>e?.id===z.id?e:Or(z))},[s,z,E,f]);let ke=s.mode===`new`&&m!==null&&m.id===void 0||s.mode===`edit`&&m!==null&&z!==null;async function Ae(e){await oe({title:t(`admin.system.users.deleteUser`,`Delete user`),message:t(`admin.system.users.permanentlyDeleteUserThisCannot`,`Permanently delete user "{{username}}"? This cannot be undone — any active sessions will be revoked on next request.`,{username:e.username}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&(le.mutate({id:e.id}),s.mode===`edit`&&s.id===e.id&&Oe())}async function B(e){let n=await se({title:t(`admin.system.users.resetPassword`,`Reset password`),message:t(`admin.system.users.setANewPasswordFor`,`Set a new password for "{{username}}".`,{username:e.username}),label:t(`admin.system.users.newPassword`,`New password`),inputType:`password`,placeholder:t(`admin.system.users.atLeast8Characters`,`At least 8 characters`),confirmLabel:t(`admin.system.users.continue`,`Continue`),validate:e=>e.length<Er?q.t(`admin.system.users.passwordTooShort`,{min:Er}):null});n===null||n.length===0||await oe({title:t(`admin.system.users.resetPassword`,`Reset password`),message:t(`admin.system.users.resetThePasswordForThey`,`Reset the password for "{{username}}"? They will need to use the new password on their next login.`,{username:e.username}),confirmLabel:t(`common.reset`,`Reset`)})&&j.mutate({id:e.id,newPassword:n})}function je(e){ve(null),de(e)}async function Me(e,t){he(!0),ve(null);try{t.isAdmin!==e.isAdmin&&await A.mutateAsync({id:e.id,isAdmin:t.isAdmin}),await ue.mutateAsync({userId:e.id,scopes:[...t.scopes]}),de(null)}catch(e){ve(kr(e))}finally{he(!1),k()}}async function V(){if(m!==null){v(null);try{if(m.id===void 0){let e=m.username.trim();if(e===``||m.password.length<Er)return;await ce.mutateAsync({username:e,password:m.password,isAdmin:m.isAdmin})}else await A.mutateAsync({id:m.id,isAdmin:m.isAdmin});k(),Oe()}catch(e){v(kr(e))}}}function Ne(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}let Pe=ce.isPending||A.isPending,Fe=m!==null&&m.id===void 0&&m.username.trim()!==``&&m.password.length>=Er,Re=m!==null&&m.id!==void 0,ze=Pe||(m?.id===void 0?!Fe:!Re),Be=e=>le.isPending&&le.variables?.id===e.id||A.isPending&&A.variables?.id===e.id||j.isPending&&j.variables?.id===e.id,He=[{key:`username`,header:t(`admin.system.users.username`,`Username`),sortValue:e=>e.username,render:e=>r(`span`,{className:`font-medium text-foreground`,"data-testid":`user-open-${e.id}`,children:e.username})},{key:`scopes`,header:t(`admin.system.users.access`,`Access`),sortValue:e=>jr(e),render:n=>r(`span`,{onClick:e=>e.stopPropagation(),children:e(F,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>je(n),disabled:Be(n),title:t(`admin.system.users.configureAccess`,`Configure access`),"data-testid":`user-access-${n.id}`,children:[r(g,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),r(Mr,{user:n})]})})},{key:`createdAt`,header:t(`admin.system.users.created`,`Created`),nowrap:!0,sortValue:e=>e.createdAt,render:e=>r(`span`,{className:`text-foreground-subtle`,children:Ne(e.createdAt)})},{key:`actions`,header:t(`admin.system.users.actions`,`Actions`),align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:n=>{let i=Be(n),a=n.id!==o?.id&&n.totpEnabled;return e(`div`,{className:`flex items-center justify-end gap-1`,onClick:e=>e.stopPropagation(),children:[e(F,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d(n.id),disabled:i,title:t(`admin.system.users.editUser`,`Edit user`),children:[r(te,{className:`h-3 w-3`}),t(`common.edit`,`Edit`)]}),a&&e(F,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>N(n),disabled:i,title:t(`admin.system.users.removeTwoFactorAuthentication`,`Remove two-factor authentication`),children:[r(x,{className:`h-3 w-3`}),t(`admin.system.users.remove2fa`,`Remove 2FA`)]}),e(F,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>we(n),disabled:i,title:t(`admin.system.users.linkedSignInAccounts`,`Linked sign-in accounts`),children:[r(b,{className:`h-3 w-3`}),t(`admin.system.users.signInLinks`,`Sign-in links`)]}),e(F,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>L(n),disabled:i,title:t(`admin.system.users.activeSessions`,`Active sessions`),children:[r(me,{className:`h-3 w-3`}),t(`admin.system.users.sessions`,`Sessions`)]}),e(F,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void B(n),disabled:i,title:t(`admin.system.users.resetPassword`,`Reset password`),children:[r(pe,{className:`h-3 w-3`}),t(`admin.system.users.resetPassword`,`Reset password`)]}),e(F,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void Ae(n),disabled:i,title:t(`admin.system.users.deleteUser`,`Delete user`),className:`text-danger hover:bg-danger/10`,children:[i?r(p,{className:`h-3 w-3 animate-spin`}):r(ee,{className:`h-3 w-3`}),t(`common.delete`,`Delete`)]})]})}}];return e(vt,{embedded:!0,icon:w,title:t(`admin.system.users.users`,`Users`),subtitle:t(`admin.system.users.hubAccountsAdminFlagAccess`,`Hub accounts, admin flag, access scopes, sessions and sign-in links.`),actions:e(F,{size:`sm`,type:`button`,onClick:()=>{v(null),u()},children:[r(re,{className:`h-3.5 w-3.5`}),t(`admin.system.users.createUser`,`Create User`)]}),children:[O&&r(U,{title:t(`admin.system.users.couldNotLoadUsers`,`Could not load users`),message:kr(ne),onRetry:()=>void ae()}),E&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[r(p,{className:`h-3.5 w-3.5 animate-spin`}),t(`common.loading`,`Loading…`)]}),!E&&!O&&R.length===0&&r(Le,{icon:w,title:t(`admin.system.users.noUsersYet`,`No users yet`),description:t(`admin.system.users.createAUserToGrant`,`Create a user to grant hub access.`)}),!E&&!O&&R.length>0&&r(be,{columns:He,rows:R,rowKey:e=>e.id,minWidthPx:560,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>d(e.id)}),r(Ze,{open:ke,onClose:Oe,title:m?.id===void 0?t(`admin.system.users.createUser`,`Create User`):t(`admin.system.users.edit`,`Edit {{value1}}`,{value1:m.username||`user`}),icon:w,error:_,testId:`user-form-dialog`,footer:r(F,{size:`sm`,type:`button`,disabled:ze,onClick:()=>void V(),children:Pe?e(l,{children:[r(p,{className:`h-3.5 w-3.5 animate-spin`}),t(`admin.system.users.saving`,`Saving…`)]}):m?.id===void 0?t(`admin.system.users.create`,`Create`):t(`common.save`,`Save`)}),children:m!==null&&e(`div`,{className:`space-y-3`,children:[r(H,{label:t(`admin.system.users.username`,`Username`),required:m.id===void 0,children:r(ge,{value:m.username,onChange:e=>h({...m,username:e.target.value}),placeholder:`john`,autoFocus:m.id===void 0,disabled:m.id!==void 0,"data-testid":`user-form-username`})}),m.id===void 0&&r(H,{label:t(`admin.system.users.password`,`Password`),required:!0,description:t(`admin.system.users.atLeastCharacters`,`At least {{value1}} characters.`,{value1:String(Er)}),children:r(Ie,{value:m.password,onValueChange:e=>h({...m,password:e}),shown:y,onToggleShown:()=>C(e=>!e),placeholder:`••••••••`,"data-testid":`user-form-password`})}),r(H,{label:t(`admin.system.users.admin`,`Admin`),description:t(`admin.system.users.unrestrictedAccessToEveryCapability`,`Unrestricted access to every capability and device.`),children:e(`label`,{className:`inline-flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[r(S,{checked:m.isAdmin,onChange:e=>h({...m,isAdmin:e.target.checked}),className:`rounded border-border focus:ring-primary`,"data-testid":`user-form-admin`}),r(`span`,{children:t(`admin.system.users.admin`,`Admin`)})]})}),m.id!==void 0&&r(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`admin.system.users.toChangeThePasswordUse`,`To change the password, use Reset password on the user's row. Access scopes are configured from the Access column.`)})]})}),ye&&r(cr,{userId:ye.id,username:ye.username,onClose:()=>N(null)}),P&&r(sr,{userId:P.id,username:P.username,onClose:()=>we(null)}),I&&r(lr,{userId:I.id,username:I.username,onClose:()=>L(null)}),M&&r(wr,{user:M,isSelf:M.id===o?.id,onClose:()=>de(null),onSubmit:e=>void Me(M,e),submitting:fe,error:_e})]})}function jr(e){let t=dr(e);return t.role===`admin`?0:t.unconfigured?2:1}function Mr({user:t}){let{t:n}=J(),i=dr(t);if(i.role===`admin`)return r(`span`,{className:`font-medium text-foreground`,children:n(`users.accessSummary.admin`)});if(i.unconfigured)return r(`span`,{className:`font-medium text-warning`,children:n(`admin.system.users.noAccess`,`No access`)});let{allow:a,block:o,features:s}=i.viewer,c=a===`*`?n(`users.accessSummary.allDevices`):n(`users.accessSummary.devices`,{count:a.length});return e(`span`,{className:`text-foreground-subtle`,children:[r(`span`,{className:`font-medium text-foreground`,children:n(`users.accessSummary.viewer`)}),` ·`,` `,c,o.length>0&&e(l,{children:[` · `,n(`users.accessSummary.blocked`,{count:o.length})]}),s.length>0&&e(l,{children:[` · `,n(`users.accessSummary.features`,{count:s.length})]})]})}s();var Nr={"api-keys":$.tokens,"linked-sessions":$.linkedApps},Pr=`certificates`;function Fr(t){return e(F,{size:`sm`,type:`button`,"data-testid":`certificates-pair-device`,onClick:t,children:[r(x,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),q.t(`systemPage.identity.pairADevice`,`Pair a device`)]})}function Ir(){let{t:e}=J(),[t]=st(),n=_n(),[i,o]=a(!1),s=Nr[t.get(`tab`)??``];if(s!==void 0)return r(at,{to:ht(`access`,{integration:s}),replace:!0});let c=nt(`/system/identity`,{t:e,isAdmin:!0})??{icon:_,title:e(`system.identity`,`Identity & Access`)},l=t.get(`tab`)??`users`,u=t.get(`integration`),d=l===mt.access.tab?gn(u,n.requestCreate):l===`certificates`?Fr(()=>o(!0)):void 0;return r(_t,{icon:c.icon,title:c.title,defaultSection:`users`,sectionsLabel:`${c.title} sections`,actions:d,sections:[{id:`users`,label:e(`systemPage.identity.users`,`Users`),content:r(Ar,{})},{id:mt.access.tab,label:e(`systemPage.identity.tokensSessions`,`Tokens & sessions`),ownedParams:dt.concat([At.token,At.scoped,At.admin]),content:r(hn,{createRequested:n.createRequested,onCreateConsumed:n.clearCreate})},{id:Pr,label:e(`systemPage.identity.certificates`,`Certificates`),content:r(or,{pairOpen:i,onPairClose:()=>o(!1)})},{id:mt.authentication.tab,label:e(`systemPage.identity.authentication`,`Authentication`),content:r(vn,{}),ownedParams:dt}]})}export{Ir as IdentityPage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as e,J as t,K as n,Q as r,R as i,S as a,V as o,Y as s,a as c,et as l,o as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$i as f,D as p,Di as m,Fi as h,Fr as g,Ha as _,Jn as v,Kn as y,Kr as b,Kt as x,Nr as S,Q as C,Qi as w,Ua as T,Ut as E,Vn as D,Wa as O,Xt as k,Z as A,aa as j,c as M,cn as N,ct as P,di as F,dt as I,ea as L,en as R,f as z,fn as B,ia as V,l as ee,lr as H,mn as U,ot as te,pn as W,ri as ne,rr as re,u as G,ua as K,ut as ie,vn as ae,vt as oe,wt as q,yi as se,z as ce,zn as le}from"./player-overlays-8aC2r-sd.js";import{Mc as ue,ii as de,mt as fe}from"./client-LrzN1ATZ.js";import{t as pe}from"./chevron-down-CBb-F8DT.js";import{a as me,c as he,i as ge,n as _e,o as ve,r as ye,s as be,t as xe}from"./user-x-BcmVBo8D.js";import{c as Se}from"./terminal-DU-tvcEm.js";import{t as Ce}from"./crop-B-t0rzRY.js";import{$ as we,$f as J,$u as Te,Al as Ee,Ar as De,Cc as Oe,Cr as ke,Dc as Ae,Ec as je,Fi as Me,Gf as Y,Gl as Ne,Hl as Pe,Ii as Fe,Jl as Ie,Ju as Le,Kl as Re,Li as ze,Ni as Be,Ns as Ve,Oi as He,Op as Ue,Or as We,Qu as Ge,Rf as Ke,Ri as qe,Sc as Je,Tc as Ye,Uf as Xe,Wf as Ze,Wi as Qe,Wl as $e,Xl as et,Xu as tt,Yi as nt,Yu as rt,Za as it,Zl as at,Zu as ot,_c as st,ad as ct,ai as lt,bc as ut,br as dt,cp as ft,ct as pt,ed as mt,ep as ht,et as gt,fa as _t,gc as vt,hc as yt,hi as bt,id as xt,jr as St,ma as Ct,nd as wt,od as Tt,rd as Et,t as Dt,td as Ot,tt as kt,vc as At,vr as jt,wc as Mt,xc as Nt,xr as Pt,yc as Ft,zf as It,zi as Lt}from"./src-D5UhvHcp.js";import{t as X}from"./i18n-DWjQ9UFE.js";import{t as Z}from"./useTranslation-BJr-n0es.js";import"./mount-BaM_HHUO.js";import{b as Rt,di as zt,hi as Bt,li as Vt,pi as Ht}from"./index-BsPM4J54.js";import{t as Ut}from"./AdminSectionedPage-C7Nx9jJl.js";import{t as Wt}from"./use-stationary-objects-Yw5gdlLl.js";import{a as Gt,i as Kt,n as qt,r as Jt,t as Yt}from"./authed-media-DaaHSoAj.js";import{t as Xt}from"./use-scenes-feed-D3bzrMKu.js";l();function Zt({mediaId:e,base64:t,alt:n,className:r,placeholder:i}){let{src:o,failed:s}=Gt(e===void 0?void 0:Jt(e));return o===null?(e===void 0||s)&&t!==void 0&&t!==``?a(`img`,{src:`data:image/jpeg;base64,${t}`,alt:n,className:r}):i:a(`img`,{src:o,alt:n,className:r})}var Qt=`pipeline-analytics`,$t=`photo.analyze`,en=`photo.enroll`,tn=`photo.discard`,nn=18*1024*1024;function rn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function an(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function on(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function sn(e,t){let n=e[t];return typeof n==`boolean`?n:null}function cn(e){if(!rn(e))return null;let t=on(e,`x`),n=on(e,`y`),r=on(e,`width`),i=on(e,`height`);return t===null||n===null||r===null||i===null?null:{x:t,y:n,width:r,height:i}}function ln(e){if(!rn(e))return null;let t=on(e,`detectionShortSidePx`),n=on(e,`score`);if(t===null||n===null)return null;let r=on(e,`magnitude`);return{detectionShortSidePx:t,score:n,...r===null?{}:{magnitude:r}}}function un(e){if(!rn(e))return null;let t=on(e,`faceIndex`),n=on(e,`score`),r=sn(e,`enrollable`),i=cn(e.bbox),a=ln(e.quality);if(t===null||n===null||r===null||i===null||a===null)return null;let o=an(e,`refusedReason`),s=an(e,`alignedCropBase64`),c=an(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 dn(e){if(!rn(e))return null;let t=an(e,`sessionId`),n=an(e,`ranOnNodeId`),r=e.faces;if(t===null||n===null||!Array.isArray(r))return null;let i=[];for(let e of r){let t=un(e);t!==null&&i.push(t)}return{sessionId:t,ranOnNodeId:n,faces:i}}function fn(e){if(!rn(e))return null;let t=an(e,`sampleId`),n=an(e,`identityId`),r=an(e,`modelId`);return t===null||n===null||r===null?null:{sampleId:t,identityId:n,modelId:r}}function pn(e,t,n){let r={...e};return n===null||n===``?delete r[t]:r[t]=n,r}function mn(e,t){return e.filter(e=>e.enrollable&&t[e.faceIndex]!==void 0).length}function hn(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 gn(e){switch(e){case`no-embedding`:return X.t(`helpers.photoEnroll.refusal.noEmbedding`);case`no-model-id`:return X.t(`helpers.photoEnroll.refusal.noModelId`);case`no-aligned-crop`:return X.t(`helpers.photoEnroll.refusal.noAlignedCrop`);case`magnitude`:return X.t(`helpers.photoEnroll.refusal.magnitude`);default:return X.t(`helpers.photoEnroll.refusal.default`)}}function _n(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 vn(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 yn(e,t,n){return e.map(e=>e.photoIndex===t?{...e,...n}:e)}function bn(e,t){return`${e}:${t}`}function xn(e,t,n,r){let i=pn(e[t]??{},n,r),a={...e};return Object.keys(i).length===0?delete a[t]:a[t]=i,a}function Sn(e,t){let n=0;for(let r of e)r.analysis!==void 0&&(n+=mn(r.analysis.faces,t[r.photoIndex]??{}));return n}var Cn=`__new__`;function wn(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[bn(i.photoIndex,t.faceIndex)]??``).trim();if(a===``)return{kind:`error`,message:X.t(`helpers.photoEnrollBatch.newPersonNoName`,{filename:i.filename,face:t.faceIndex+1})};r.includes(a)||r.push(a)}}return{kind:`ok`,names:r}}function Tn(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[bn(e,a)]??``).trim()];s!==void 0&&(o[a]=s)}r[e]=o}return r}function En(e,t){let n=[];for(let r of e){if(r.analysis===void 0)continue;let e=hn(r.analysis.sessionId,r.analysis.faces,t[r.photoIndex]??{});for(let t of e)n.push({photoIndex:r.photoIndex,request:t})}return n}function Dn(e){return/expired/i.test(e)}function On(e){return e instanceof Error?e.message:String(e)}async function kn(e,t,n){let r=new Map(e.map(e=>[e.photoIndex,e])),i={},a=[],o=0,s=null,c=(e,t)=>{let n=r.get(e)?.filename??X.t(`helpers.photoEnrollBatch.photoFallback`,{n:e+1});return X.t(`helpers.photoEnrollBatch.faceLabel`,{filename:n,face:t+1})};for(let l of En(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=On(t);if(!Dn(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 (${On(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)}: ${On(e)}`)}}}return{enrolled:o,stampedModelId:s,failures:a,refreshedAnalyses:i}}var An=[[`faceGallery`]],jn=``;function Mn(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 Nn(e){return e instanceof Error?e.message:String(e)}function Pn({face:t,identities:r,value:i,onChange:o,disabled:s}){let{t:c}=Z(),l=n(()=>[{value:jn,label:c(`detectionIntelligence.photoEnrollDialog.ignoreThisFace`,`Ignore this face`)},...r.map(e=>({value:e.id,label:e.name})),{value:Cn,label:c(`detectionIntelligence.photoEnrollDialog.newPerson`,`+ New person…`)}],[r,c]);return e(`div`,{className:`rounded-md border border-border bg-surface p-2`,children:[a(`div`,{className:`mb-2 aspect-square w-full overflow-hidden rounded border border-border bg-surface-hover`,children:t.alignedCropBase64?a(`img`,{src:`data:image/jpeg;base64,${t.alignedCropBase64}`,alt:c(`detectionIntelligence.photoEnrollDialog.face`,`Face {{value1}}`,{value1:t.faceIndex+1}),className:`h-full w-full object-cover`}):a(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:a(_e,{className:`h-8 w-8`})})}),a(`div`,{className:`min-h-[4.75rem]`,children:t.enrollable?e(d,{children:[a(I,{options:l,value:i,disabled:s,onChange:e=>o(e.target.value),"aria-label":c(`detectionIntelligence.photoEnrollDialog.assignFace`,`Assign face {{value1}}`,{value1:t.faceIndex+1})}),e(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:[Math.round(t.quality.detectionShortSidePx),` px`,t.modelId?` · ${t.modelId}`:``]})]}):e(`div`,{className:`space-y-1`,children:[a(Ct,{variant:`warning`,className:`text-[10px]`,children:c(`detectionIntelligence.photoEnrollDialog.notUsable`,`Not usable`)}),a(`p`,{className:`text-[10px] leading-tight text-foreground-subtle`,children:gn(t.refusedReason)})]})})]})}function Fn({photo:t,identities:n,draft:r,newNames:i,disabled:o,onAssign:s,onNameChange:c,onRetry:l}){let{t:u}=Z(),d=t.analysis?.faces??[],f=r[t.photoIndex]??{};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex items-center gap-2 border-b border-border pb-1`,children:[a(`span`,{className:`truncate text-xs font-medium text-foreground`,children:t.filename}),t.status===`analyzing`||t.status===`queued`?e(`span`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,children:[a(g,{className:`h-3 w-3 animate-spin`}),` `,u(`detectionIntelligence.photoEnrollDialog.analysing`)]}):null,t.status===`analyzed`&&t.analysis!==void 0&&a(`span`,{className:`text-xs text-foreground-subtle`,children:u(`detectionIntelligence.photoEnrollDialog.facesAnalysedOn`,{count:d.length,node:t.analysis.ranOnNodeId})}),t.status===`failed`&&e(Y,{variant:`secondary`,size:`sm`,disabled:o,onClick:l,children:[a(y,{className:`h-3 w-3`}),` `,u(`common.retry`)]})]}),t.status===`failed`&&e(`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:[a(k,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),e(`span`,{children:[u(`detectionIntelligence.photoEnrollDialog.thisPhotoCouldNotBe`,`This photo could not be analysed:`),` `,t.error??u(`detectionIntelligence.photoEnrollDialog.unknownError`,`unknown error`),`. The other photos are unaffected.`]})]}),t.status===`analyzed`&&d.length===0&&a(`p`,{className:`text-xs text-foreground-subtle`,children:u(`detectionIntelligence.photoEnrollDialog.noFacesWereFoundIn`,`No faces were found in this photo. A face has to be reasonably large and facing the camera for the detector to measure it.`)}),d.length>0&&a(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(7rem,7rem))] justify-start gap-3`,children:d.map(e=>a(Pn,{face:e,identities:n,value:f[e.faceIndex]??jn,disabled:o,onChange:t=>s(e.faceIndex,t)},e.faceIndex))}),d.filter(e=>f[e.faceIndex]===Cn).map(n=>e(`div`,{className:`flex items-center gap-2`,children:[a(`span`,{className:`w-28 shrink-0 truncate text-xs text-foreground-subtle`,children:u(`detectionIntelligence.photoEnrollDialog.faceN`,{n:n.faceIndex+1})}),a(J,{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:u(`detectionIntelligence.photoEnrollDialog.newPersonNameTypeThe`,`New person name… (type the same name under another face to reuse it)`),value:i[bn(t.photoIndex,n.faceIndex)]??``,onChange:e=>c(n.faceIndex,e.target.value)})]},n.faceIndex))]})}function In({open:r,onOpenChange:o}){let{t:c}=Z(),l=oe(),d=u(),f=t(null),{data:p}=ut(),m=vt(),[h,_]=s([]),[v,y]=s(!1),[b,x]=s(null),[S,C]=s({}),[w,T]=s({}),[E,D]=s(null),O=n(()=>(p??[]).map(e=>({id:e.id,name:e.name})),[p]),A=h.some(e=>e.status===`queued`||e.status===`analyzing`),j=A||v,M=i(e=>{for(let t of e){let e=t.analysis?.sessionId;e!==void 0&&l.trpcClient.addons.custom.mutate({addonId:Qt,action:tn,input:{sessionId:e}}).catch(()=>void 0)}},[l]),N=i(()=>{_([]),C({}),T({}),x(null),D(null),f.current&&(f.current.value=``)},[]),P=i(()=>{M(h),N(),o(!1)},[M,o,h,N]),F=i(async e=>{let t=dn(await l.trpcClient.addons.custom.mutate({addonId:Qt,action:$t,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]),I=i(async e=>{_(t=>yn(t,e.photoIndex,{status:`analyzing`,error:void 0}));try{let t=await F(e);_(n=>yn(n,e.photoIndex,{status:`analyzed`,analysis:t}))}catch(t){_(n=>yn(n,e.photoIndex,{status:`failed`,error:Nn(t)}))}},[F]),L=i(async e=>{if(e.length===0)return;M(h),N();let t=_n(e,{maxCount:12,maxBytes:nn}),n=[];t.oversize.length>0&&n.push(`Over the ${Math.round(nn/(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&&x(n.join(` `));let r;try{r=await Promise.all(t.accepted.map(async(e,t)=>({photoIndex:t,filename:e.name,photoBase64:await Mn(e),status:`queued`})))}catch(e){x(Nn(e));return}_(r),await vn(r,2,e=>I(e))},[M,h,N,I]),R=Sn(h,S),z=i(async()=>{y(!0),x(null),D(null);try{let e=wn(h,S,w);if(e.kind===`error`){x(e.message);return}let t={};for(let n of e.names)t[n]=(await m.mutateAsync({name:n})).id;let n=await kn(h,Tn(S,w,t),{enroll:async e=>{let t=fn(await l.trpcClient.addons.custom.mutate({addonId:Qt,action:en,input:e}));if(t===null)throw Error(`unreadable reply`);return t},reanalyze:e=>F(e)});Object.keys(n.refreshedAnalyses).length>0&&_(e=>e.map(e=>{let t=n.refreshedAnalyses[e.photoIndex];return t===void 0?e:{...e,status:`analyzed`,analysis:t}})),d.invalidateQueries({queryKey:An}),n.failures.length>0&&x(n.failures.join(` · `)),D(n.enrolled===0?`Nothing was enrolled.`:`Enrolled ${n.enrolled} sample${n.enrolled===1?``:`s`}${n.stampedModelId===null?``:` with ${n.stampedModelId}`}.`)}catch(e){x(Nn(e))}finally{y(!1)}},[F,m,S,w,h,d,l]),B=h.filter(e=>e.status===`analyzed`).length;return a(Be,{open:r,onOpenChange:e=>e?o(!0):P(),children:e(Me,{className:`max-w-3xl`,children:[e(qe,{children:[a(Lt,{children:c(`detectionIntelligence.photoEnrollDialog.enrolFromPhotos`,`Enrol from photos`)}),a(Fe,{children:c(`detectionIntelligence.photoEnrollDialog.everyPhotoIsAnalysedWith`,`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.`)})]}),a(`div`,{className:`rounded-md border border-border bg-surface-hover px-3 py-2 text-xs text-foreground-subtle`,children:a(Vt,{i18nKey:`detectionIntelligence.photoEnrollDialog.reliableRecognition`,components:{strong:a(`strong`,{})}})}),e(`div`,{className:`flex items-center gap-2`,children:[a(lt,{ref:f,accept:`image/jpeg,image/png,image/webp`,multiple:!0,className:`hidden`,onChange:e=>void L(Array.from(e.target.files??[]))}),e(Y,{variant:`secondary`,size:`sm`,disabled:j,onClick:()=>f.current?.click(),children:[A?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(ve,{className:`h-3.5 w-3.5`}),c(`detectionIntelligence.photoEnrollDialog.choosePhotos`,`Choose photos`)]}),h.length>0&&a(`span`,{className:`text-xs text-foreground-subtle`,children:c(`detectionIntelligence.photoEnrollDialog.photosAnalysed`,{done:B,count:h.length})})]}),a(`div`,{className:`min-h-11`,"aria-live":`polite`,children:b===null?E===null?null:a(`div`,{className:`rounded-md border border-success/40 bg-success/10 px-3 py-2 text-xs text-success`,children:E}):e(`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:[a(k,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),a(`span`,{children:b})]})}),h.length>0&&a(`div`,{className:`max-h-[50vh] space-y-4 overflow-y-auto pr-1`,children:h.map(e=>a(Fn,{photo:e,identities:O,draft:S,newNames:w,disabled:j,onAssign:(t,n)=>C(r=>xn(r,e.photoIndex,t,n===jn?null:n)),onNameChange:(t,n)=>T(r=>({...r,[bn(e.photoIndex,t)]:n})),onRetry:()=>void I(e)},e.photoIndex))}),e(ze,{children:[a(Y,{variant:`secondary`,onClick:P,disabled:v,children:c(`common.close`,`Close`)}),e(Y,{variant:`primary`,onClick:()=>void z(),disabled:j||R===0,children:[v?a(g,{className:`h-3.5 w-3.5 animate-spin`}):null,c(`detectionIntelligence.photoEnrollDialog.enrolFaces`,{count:R})]})]})]})})}l();var Ln=[[`faceGallery`]];function Rn({identityId:t}){let{t:n}=Z(),r=u(),{data:i,isLoading:o}=Nt({identityId:t}),s=Oe();function c(e){s.mutate({identityId:t,sampleId:e.id},{onSettled:()=>{r.invalidateQueries({queryKey:Ln})}})}return o?e(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,children:[a(g,{className:`h-3.5 w-3.5 animate-spin`}),n(`detectionIntelligence.peopleList.loadingSamples`,`Loading samples…`)]}):!i||i.length===0?a(`p`,{className:`py-2 text-xs text-foreground-subtle`,children:n(`detectionIntelligence.peopleList.noSamplesYet`,`No samples yet.`)}):a(`div`,{className:`mt-2 grid grid-cols-4 gap-2 sm:grid-cols-6 md:grid-cols-8`,children:i.map(t=>e(`div`,{className:`group relative aspect-square overflow-hidden rounded-md border border-border bg-surface`,children:[t.base64?a(`img`,{src:`data:image/jpeg;base64,${t.base64}`,alt:n(`detectionIntelligence.peopleList.sample`,`Sample`),className:`h-full w-full object-cover`}):a(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:a(_e,{className:`h-6 w-6`})}),t.source===`photo`&&a(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 p-0.5 text-white`,title:n(`detectionIntelligence.peopleList.enrolledFromAnUploadedPhoto`,`Enrolled from an uploaded photo`),children:a(ve,{className:`h-3 w-3`})}),a(`button`,{type:`button`,onClick:()=>c(t),disabled:s.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":n(`detectionIntelligence.peopleList.removeSample`,`Remove sample`),children:a(q,{className:`h-4 w-4 text-white`})})]},t.id))})}function zn(t){return[{key:`person`,header:X.t(`detectionIntelligence.peopleList.person`,`Person`),sortValue:e=>e.name,render:t=>e(`span`,{className:`flex min-w-0 items-center gap-2`,children:[a(`span`,{className:`h-8 w-8 shrink-0 overflow-hidden rounded-full border border-border bg-surface-hover`,children:a(Zt,{mediaId:t.coverMediaId,base64:t.coverBase64,alt:t.name,className:`h-full w-full object-cover`,placeholder:a(`span`,{className:`flex h-full w-full items-center justify-center`,children:a(_e,{className:`h-4 w-4 text-foreground-subtle`})})})}),a(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name})]})},{key:`samples`,header:X.t(`detectionIntelligence.peopleList.samples`,`Samples`),align:`center`,nowrap:!0,sortValue:e=>e.sampleCount,render:e=>a(Ct,{variant:`default`,className:`text-[10px]`,children:e.sampleCount})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Actions`,render:n=>e(`span`,{className:`flex items-center justify-end gap-1`,children:[a(ht,{variant:`ghost`,size:`sm`,icon:H,"aria-label":X.t(`detectionIntelligence.peopleList.edit`,`Edit {{name}}`,{name:n.name}),onClick:e=>{e.stopPropagation(),t.onEdit(n)}}),a(ht,{variant:`ghost`,size:`sm`,icon:R,"aria-label":X.t(`detectionIntelligence.peopleList.delete`,`Delete {{name}}`,{name:n.name}),onClick:e=>{e.stopPropagation(),t.onDelete(n)}})]})}]}function Bn({mode:t,identity:n,onClose:r}){let{t:i}=Z(),c=u(),[l,d]=s(t===`edit`?n?.name??``:``),f=vt(),p=Mt();o(()=>{d(t===`edit`?n?.name??``:``)},[t,n?.id,n?.name]);let m=f.isPending||p.isPending,h=l.trim(),_=t===`edit`&&n!==null&&h===n.name,v=m||h.length===0||_;function y(){c.invalidateQueries({queryKey:Ln})}function b(){if(!v){if(t===`new`){f.mutate({name:h},{onSuccess:()=>{y(),r()}});return}if(n===null){r();return}p.mutate({id:n.id,name:h},{onSuccess:()=>{y(),r()}})}}return a(kt,{open:!0,onClose:r,title:t===`new`?`Add person`:`Edit ${n?.name??`person`}`,icon:_e,width:t===`edit`?`xl`:`lg`,testId:`people-person-form`,footer:e(Y,{variant:`primary`,size:`sm`,type:`button`,onClick:b,disabled:v,children:[m?a(g,{className:`h-3.5 w-3.5 animate-spin`}):null,t===`new`?i(`common.add`,`Add`):i(`common.save`,`Save`)]}),children:e(`div`,{className:`space-y-4`,children:[a(pt,{label:i(`detectionIntelligence.peopleList.name`,`Name`),required:!0,children:a(J,{value:l,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&b()},placeholder:i(`detectionIntelligence.peopleList.personName`,`Person name…`),autoFocus:!0})}),t===`edit`&&n!==null&&e(`div`,{children:[a(`p`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:i(`detectionIntelligence.peopleList.trainingSamples`,`Training samples`)}),a(`p`,{className:`mb-2 text-[11px] text-foreground-subtle`,children:i(`detectionIntelligence.peopleList.removeASampleToDrop`,`Remove a sample to drop it from recognition training for this person.`)}),a(Rn,{identityId:n.id})]})]})})}function Vn(){let{t}=Z(),r=u(),i=P(),{data:c,isLoading:l}=ut(),d=At(),{state:f,openNew:p,openEdit:m,close:h}=gt(),[_,v]=s(!1),y=c??[],b=dt(y,{searchText:e=>[e.name]}),x=f.mode===`edit`?y.find(e=>e.id===f.id)??null:null;o(()=>{f.mode===`edit`&&!l&&x===null&&h()},[f.mode,l,x,h]);let S=n(()=>zn({onEdit:e=>m(e.id),onDelete:e=>{(async()=>{await i({title:t(`detectionIntelligence.peopleList.deletePerson`,`Delete person`),message:t(`detectionIntelligence.peopleList.deleteAndAllTheirSamples`,`Delete {{name}} and all their samples? This cannot be undone.`,{name:e.name}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&d.mutate({id:e.id},{onSettled:()=>{r.invalidateQueries({queryKey:Ln}),f.mode===`edit`&&f.id===e.id&&h()}})})()}}),[i,h,d,f,m,r,t]);if(l)return e(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[a(g,{className:`h-4 w-4 animate-spin`}),t(`detectionIntelligence.peopleList.loadingPeople`,`Loading people…`)]});let C=f.mode===`new`||f.mode===`edit`&&x!==null;return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(Y,{variant:`primary`,size:`sm`,type:`button`,onClick:p,children:[a(re,{className:`h-3.5 w-3.5`}),t(`detectionIntelligence.peopleList.addPerson`,`Add person`)]}),e(Y,{variant:`secondary`,size:`sm`,type:`button`,onClick:()=>v(!0),children:[a(ve,{className:`h-3.5 w-3.5`}),t(`detectionIntelligence.peopleList.enrolFromAPhoto`,`Enrol from a photo`)]})]}),(y.length>0||b.active)&&a(Pt,{state:b.state,facets:b.facets,labels:{searchPlaceholder:`Search people…`,searchLabel:`Search people`,facetsLabel:`Filter`,clearLabel:`Clear`},onSearch:b.setSearch,onToggleFacet:b.toggleFacet,onClear:b.clear}),b.rows.length===0?a(nt,{icon:_e,title:b.active?t(`detectionIntelligence.peopleList.nothingMatchesTheFilter`,`Nothing matches the filter`):t(`detectionIntelligence.peopleList.noPeopleEnrolledYet`,`No people enrolled yet`),description:b.active?t(`detectionIntelligence.peopleList.clearTheSearchOrTry`,`Clear the search or try another name.`):t(`detectionIntelligence.peopleList.addAPersonOrEnrol`,`Add a person, or enrol faces from a photo.`)}):a(De,{columns:S,rows:b.rows,rowKey:e=>e.id,maxBodyHeight:St,emptyMessage:t(`detectionIntelligence.peopleList.noPeopleEnrolledYet2`,`No people enrolled yet.`),onRowClick:e=>m(e.id)}),C&&a(Bn,{mode:f.mode===`new`?`new`:`edit`,identity:x,onClose:h}),a(In,{open:_,onOpenChange:v})]})}var Hn={fromMs:null,toMs:null},Un=36e5,Wn=24*Un;function Gn(e,t){switch(e){case`24h`:return{fromMs:t-Wn,toMs:null};case`7d`:return{fromMs:t-7*Wn,toMs:null};case`30d`:return{fromMs:t-30*Wn,toMs:null};case`all`:return Hn}}function Kn(e){return e.fromMs!==null||e.toMs!==null}function qn(e,t){return Kn(t)?e.filter(e=>!(t.fromMs!==null&&e.timestamp<t.fromMs||t.toMs!==null&&e.timestamp>t.toMs)):[...e]}function Jn(e,t){return t.size===0?[...e]:e.filter(e=>t.has(e.deviceId))}function Yn(e){let t=new Set,n=[];for(let r of e)t.has(r.deviceId)||(t.add(r.deviceId),n.push(r.deviceId));return n}function Xn(e){if(!e)return null;let t=Date.parse(`${e}T00:00:00`);return Number.isNaN(t)?null:t}function Zn(e){if(!e)return null;let t=Date.parse(`${e}T23:59:59.999`);return Number.isNaN(t)?null:t}function Qn(e,t){if(!Number.isFinite(e)||e<=0)return`—`;let n=t-e;return n<6e4?X.t(`helpers.relativeTime.justNow`):n<Un?X.t(`helpers.relativeTime.minutesAgo`,{count:Math.floor(n/6e4)}):n<Wn?X.t(`helpers.relativeTime.hoursAgo`,{count:Math.floor(n/Un)}):n<7*Wn?X.t(`helpers.relativeTime.daysAgo`,{count:Math.floor(n/Wn)}):new Date(e).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}function $n(e){return!Number.isFinite(e)||e<=0?`—`:new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function er(e){return!Number.isFinite(e)||e<=0?`—`:new Date(e).toLocaleString(void 0,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function tr(e){let t=e.cropUrl!==void 0&&e.cropUrl.length>0,n=e.base64!==void 0&&e.base64.length>0;return!t&&!n}function nr(e){return e.filter(tr).map(e=>e.faceId)}function rr(e){let t=0;for(let n of e)tr(n)&&(t+=1);return t}function ir(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}l();function ar(e,t,r){let[i,a]=s(1);o(()=>{a(1)},[r]);let c=e.length,l=Math.max(1,Math.ceil(c/t)),u=Math.min(i,l);return o(()=>{u!==i&&a(u)},[u,i]),{page:u,setPage:a,pageItems:n(()=>{let n=(u-1)*t;return e.slice(n,n+t)},[e,u,t]),totalPages:l,totalItems:c,pageSize:t}}var or=2;function sr(e,t){if(t<=1)return[{kind:`page`,n:1}];if(t<=7){let e=[];for(let n=1;n<=t;n++)e.push({kind:`page`,n});return e}let n=[],r=Math.max(2,e-or),i=Math.min(t-1,e+or);n.push({kind:`page`,n:1}),r>2&&n.push({kind:`ellipsis`,side:`left`});for(let e=r;e<=i;e++)n.push({kind:`page`,n:e});return i<t-1&&n.push({kind:`ellipsis`,side:`right`}),n.push({kind:`page`,n:t}),n}function cr({currentPage:t,totalItems:n,pageSize:r,onPageChange:i,itemNoun:o=`items`}){let{t:s}=Z();if(n<=r)return null;let c=Math.ceil(n/r),l=(t-1)*r+1,u=Math.min(t*r,n),d=sr(t,c),p=`inline-flex h-7 min-w-7 items-center justify-center rounded-md px-2 text-[11px] transition-colors disabled:opacity-40`;return e(`div`,{className:`flex items-center justify-between gap-4 flex-wrap pt-2 text-[11px] text-foreground-subtle`,children:[a(`span`,{children:s(`galleryPager.showing`,{from:l,to:u,total:n,noun:o})}),e(`div`,{className:`flex items-center gap-1`,children:[a(Y,{variant:`unstyled`,type:`button`,className:`${p} hover:bg-surface-hover`,onClick:()=>i(t-1),disabled:t<=1,"aria-label":s(`galleryPager.previousPage`,`Previous page`),children:a(f,{className:`h-3.5 w-3.5`})}),d.map(e=>e.kind===`ellipsis`?a(`span`,{className:`px-1 opacity-60`,children:`…`},`ellipsis-${e.side}`):a(Y,{variant:`unstyled`,type:`button`,className:`${p} ${e.n===t?`bg-primary/12 text-primary font-medium`:`hover:bg-surface-hover hover:text-foreground`}`,onClick:()=>i(e.n),"aria-current":e.n===t?`page`:void 0,children:e.n},e.n)),a(Y,{variant:`unstyled`,type:`button`,className:`${p} hover:bg-surface-hover`,onClick:()=>i(t+1),disabled:t>=c,"aria-label":s(`galleryPager.nextPage`,`Next page`),children:a(w,{className:`h-3.5 w-3.5`})})]})]})}l();var lr=[[`faceGallery`]];function ur({faceIds:t,identities:n,onDone:r}){let{t:i}=Z(),o=u(),c=yt(),l=vt(),[d,f]=s(``),[p,m]=s(!1),[h,_]=s(null),v=t!==null&&t.length>0,y=t?.length??0;function b(){m(!1),f(``),_(null)}function x(){b(),r()}function S(e){!t||t.length===0||c.mutate({faceIds:[...t],identityId:e},{onSettled:()=>{o.invalidateQueries({queryKey:lr}),x()}})}function C(){!t||!d.trim()||l.mutate({name:d.trim()},{onSuccess:e=>{e?.id&&S(e.id)},onError:()=>{o.invalidateQueries({queryKey:lr}),x()}})}let w=c.isPending||l.isPending;return a(Be,{open:v,onOpenChange:e=>!e&&x(),children:e(Me,{children:[e(qe,{children:[a(Lt,{children:y>1?i(`detectionIntelligence.assignDialog.assignFacesToPerson`,`Assign {{value1}} faces to person`,{value1:String(y)}):i(`detectionIntelligence.assignDialog.assignFaceToPerson`,`Assign face to person`)}),a(Fe,{children:i(`detectionIntelligence.assignDialog.selectAnExistingPersonOr`,`Select an existing person or create a new one.`)})]}),a(`div`,{className:`space-y-1 max-h-56 overflow-y-auto`,children:n.map(t=>e(Y,{variant:`unstyled`,type:`button`,onClick:()=>_(t.id),className:`w-full rounded-md px-3 py-2 text-left text-xs transition-colors ${h===t.id?`bg-primary/12 text-primary`:`hover:bg-surface-hover text-foreground`}`,children:[a(`span`,{className:`font-medium`,children:t.name}),a(`span`,{className:`ml-2 text-foreground-subtle`,children:i(`detectionIntelligence.assignDialog.samples`,{count:t.sampleCount})})]},t.id))}),a(`div`,{className:`min-h-[2.75rem] border-t border-border pt-2`,children:p?a(`div`,{className:`flex items-center gap-2`,children:a(J,{placeholder:i(`detectionIntelligence.assignDialog.newPersonName`,`New person name…`),value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&C()},autoFocus:!0,className:`flex-1`})}):a(Y,{variant:`unstyled`,type:`button`,onClick:()=>{_(null),m(!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:i(`detectionIntelligence.assignDialog.newPerson`,`+ New person…`)})}),e(ze,{className:`min-h-[2.75rem]`,children:[a(Y,{variant:`secondary`,onClick:x,disabled:w,children:i(`common.cancel`,`Cancel`)}),p?e(Y,{variant:`primary`,onClick:C,disabled:w||!d.trim(),children:[w&&a(g,{className:`h-3.5 w-3.5 animate-spin`}),i(`detectionIntelligence.assignDialog.createAssign`,`Create & assign`)]}):e(Y,{variant:`primary`,onClick:()=>h&&S(h),disabled:w||!h,children:[w&&a(g,{className:`h-3.5 w-3.5 animate-spin`}),y>1?i(`detectionIntelligence.assignCount`,{count:y}):i(`common.assign`)]})]})]})})}l();function dr({cameras:n,selected:r,onChange:i}){let{t:c}=Z(),[l,u]=s(!1),d=t(null);o(()=>{if(!l)return;function e(e){d.current&&e.target instanceof Node&&!d.current.contains(e.target)&&u(!1)}function t(e){e.key===`Escape`&&u(!1)}return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[l]);function f(e){let t=new Set(r);t.has(e)?t.delete(e):t.add(e),i(t)}let p=r.size,m=p===0?`All cameras`:p===1?n.find(e=>r.has(e.id))?.name??`1 camera`:`${String(p)} cameras`;return e(`div`,{ref:d,className:`relative`,children:[e(Y,{variant:`unstyled`,type:`button`,onClick:()=>u(e=>!e),disabled:n.length===0,className:`flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition-colors disabled:opacity-40 ${p>0?`border-primary/40 bg-primary/8 text-primary`:`border-border text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[a(j,{className:`h-3.5 w-3.5`}),a(`span`,{className:`max-w-[10rem] truncate`,children:m}),a(pe,{className:`h-3 w-3 opacity-70`})]}),l&&e(`div`,{className:`absolute left-0 z-30 mt-1 max-h-64 w-[min(15rem,calc(100vw-1.5rem))] overflow-y-auto rounded-md border border-border bg-surface p-1 shadow-lg shadow-black/30`,children:[p>0&&a(Y,{variant:`unstyled`,type:`button`,onClick:()=>i(new Set),className:`mb-1 w-full rounded px-2 py-1 text-left text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:c(`detectionIntelligence.cameraMultiSelect.clearSelection`,`Clear selection`)}),n.map(t=>{let n=r.has(t.id);return e(Y,{variant:`unstyled`,type:`button`,onClick:()=>f(t.id),className:`flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors ${n?`bg-primary/10 text-primary`:`text-foreground hover:bg-surface-hover`}`,children:[a(`span`,{className:`flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-sm border ${n?`border-primary bg-primary text-white`:`border-border`}`,children:n&&a(L,{className:`h-2.5 w-2.5`})}),a(`span`,{className:`truncate`,children:t.name})]},t.id)})]})]})}l();var fr=[{label:`24h`,value:`24h`},{label:`7d`,value:`7d`},{label:`30d`,value:`30d`},{labelKey:`common.all`,value:`all`}];function pr({onChange:t}){let{t:n}=Z(),[r,i]=s(`all`),[o,c]=s(``),[l,u]=s(``);function d(e){i(e),c(``),u(``),t(Gn(e,Date.now()))}function f(e,n){i(`custom`),c(e),u(n),t({fromMs:Xn(e),toMs:Zn(n)})}let p=`rounded-md border border-border bg-surface px-2 py-1.5 text-[11px] text-foreground outline-none focus:border-primary [color-scheme:light] dark:[color-scheme:dark]`;return e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[a(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:fr.map(e=>a(Y,{variant:`unstyled`,type:`button`,onClick:()=>d(e.value),className:`rounded px-2.5 py-1 text-[11px] transition-colors ${r===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:e.labelKey===void 0?e.label:n(e.labelKey)},e.value))}),e(`div`,{className:`flex items-center gap-1`,children:[a(J,{type:`date`,"aria-label":n(`detectionIntelligence.dateRangeFilter.fromDate`,`From date`),value:o,max:l||void 0,onChange:e=>f(e.target.value,l),className:`${p} ${r===`custom`&&o?`border-primary/50`:``}`}),a(`span`,{className:`text-[11px] text-foreground-subtle`,children:`→`}),a(J,{type:`date`,"aria-label":n(`detectionIntelligence.dateRangeFilter.toDate`,`To date`),value:l,min:o||void 0,onChange:e=>f(o,e.target.value),className:`${p} ${r===`custom`&&l?`border-primary/50`:``}`})]})]})}function mr(e){return e<0?0:e>1?1:e}function hr(e,t,n){if(!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0)return null;let r=mr(e.x/t),i=mr(e.y/n),a=mr((e.x+e.w)/t),o=mr((e.y+e.h)/n);return{x:r,y:i,width:Math.max(0,a-r),height:Math.max(0,o-i)}}l();var gr=2.6;function _r({src:t,alt:n,className:r,overlay:i,fit:c=`contain`}){let[l,u]=s(!1),[d,f]=s(`50% 50%`);o(()=>{u(!1),f(`50% 50%`)},[t]);function p(e){if(!l){let t=e.currentTarget.getBoundingClientRect(),n=(e.clientX-t.left)/t.width*100,r=(e.clientY-t.top)/t.height*100;f(`${String(n)}% ${String(r)}%`)}u(e=>!e)}let m=c===`natural`;return a(`div`,{className:`relative overflow-hidden bg-background ${r??``}`,onClick:p,children:e(`div`,{className:`relative select-none transition-transform duration-200 ease-out ${m?`w-full`:`h-full w-full`} ${l?`cursor-zoom-out`:`cursor-zoom-in`}`,style:{transformOrigin:d,transform:l?`scale(${String(gr)})`:`scale(1)`},children:[a(`img`,{src:t,alt:n,draggable:!1,className:m?`block h-auto w-full object-contain`:`h-full w-full object-contain`}),i]})})}l();function vr(e){let[t,n]=s(null),[r,i]=s(null),[a,c]=s(!1);return o(()=>{if(n(null),i(null),c(!1),e===void 0)return;let t=!1,r=null;return(async()=>{try{let i=await qt(Jt(e));if(t)return;r=URL.createObjectURL(i),n(r)}catch{t||c(!0)}})(),()=>{t=!0,r&&URL.revokeObjectURL(r)}},[e]),o(()=>{if(!t)return;let e=new Image;return e.onload=()=>i({width:e.naturalWidth,height:e.naturalHeight}),e.onerror=()=>c(!0),e.src=t,()=>{e.onload=null,e.onerror=null}},[t]),{frameSrc:t,naturalWidth:r?.width??null,naturalHeight:r?.height??null,failed:a}}function yr(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 br({label:t,value:n}){return e(`div`,{className:`flex items-baseline justify-between gap-3 py-1.5 border-b border-border/60 last:border-0`,children:[a(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:t}),a(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground`,children:n})]})}function xr({box:e}){let{t}=Z();return a(`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:a(`span`,{className:`absolute -top-4 left-0 rounded bg-primary px-1 text-[9px] font-semibold uppercase tracking-wide text-white`,children:t(`detectionIntelligence.faceDetailPanel.face`,`Face`)})})}function Sr({face:t,cameraName:r,onClose:i,onAssign:o,onUnassign:c,onDelete:l,actionsPending:u}){let{t:d}=Z(),{data:f,isFetching:p}=Ft({faceId:t?.faceId??``},{enabled:t!==null}),[m,h]=s(`frame`),{frameSrc:_,naturalWidth:v,naturalHeight:y,failed:x}=vr(t?.keyFrameMediaId),S=n(()=>{let e=yr(f??[]);return e?e.url:ir(t)},[f,t]),C=n(()=>!t?.faceBbox||v===null||y===null?null:hr(t.faceBbox,v,y),[t?.faceBbox,v,y]);if(t===null)return null;let w=t.keyFrameMediaId!==void 0&&!x,T=w&&m===`frame`,O=t.assigned?t.identityName??`Assigned`:t.recognizedIdentityId?`${t.identityName??`Recognized`} (suggested)`:`Unassigned`;return a(Be,{open:!0,onOpenChange:e=>!e&&i(),children:e(Me,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":d(`detectionIntelligence.faceDetailPanel.faceDetail`,`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:[a(`header`,{className:`flex shrink-0 items-start gap-2 border-b border-border py-3 pl-4 pr-10`,children:e(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:d(`detectionIntelligence.faceDetailPanel.faceDetail`,`Face detail`)}),a(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:r})]})}),e(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[w&&e(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5 text-xs`,children:[e(Y,{variant:`unstyled`,type:`button`,onClick:()=>h(`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:[a(D,{className:`h-3.5 w-3.5`}),` `,d(`detectionIntelligence.detailPanel.fullFrame`)]}),e(Y,{variant:`unstyled`,type:`button`,onClick:()=>h(`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:[a(Ce,{className:`h-3.5 w-3.5`}),` `,d(`detectionIntelligence.detailPanel.crop`)]})]}),T&&_?a(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:a(_r,{src:_,alt:d(`detectionIntelligence.faceDetailPanel.fullFrameWithDetectedFace`,`Full frame with detected face`),fit:`natural`,className:`w-full`,overlay:C?a(xr,{box:C}):void 0})}):S?e(`div`,{className:`relative aspect-square w-full overflow-hidden rounded-lg border border-border`,children:[a(_r,{src:S,alt:d(`detectionIntelligence.faceDetailPanel.detectedFace`,`Detected face`),className:`h-full w-full`}),p&&a(`div`,{className:`absolute right-2 top-2 rounded-full bg-black/50 p-1 text-white`,children:a(g,{className:`h-3.5 w-3.5 animate-spin`})})]}):e(`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:[a(b,{className:`h-8 w-8 text-warning/70`}),a(`span`,{className:`text-[11px] font-medium uppercase tracking-wide text-warning/80`,children:d(`detectionIntelligence.faceDetailPanel.noImage`,`No image`)}),a(`span`,{className:`px-6 text-center text-[10px] text-foreground-subtle`,children:d(`detectionIntelligence.faceDetailPanel.theCropMediaForThis`,`The crop media for this face could not be resolved (a pre-fix orphan). Safe to delete.`)})]}),e(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[a(br,{label:d(`detectionIntelligence.faceDetailPanel.camera`,`Camera`),value:r}),a(br,{label:d(`detectionIntelligence.faceDetailPanel.captured`,`Captured`),value:er(t.timestamp)}),a(br,{label:d(`detectionIntelligence.faceDetailPanel.track`,`Track`),value:t.trackId}),a(br,{label:d(`detectionIntelligence.faceDetailPanel.identity`,`Identity`),value:O})]})]}),e(`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:[t.assigned?e(Y,{variant:`secondary`,onClick:()=>c(t.faceId),disabled:u,children:[a(xe,{className:`h-3.5 w-3.5`}),` `,d(`detectionIntelligence.detailPanel.detach`)]}):e(Y,{variant:`primary`,onClick:()=>o(t.faceId),disabled:u,children:[a(E,{className:`h-3.5 w-3.5`}),` `,d(`common.assign`)]}),e(Y,{variant:`secondary`,onClick:()=>l(t.faceId),disabled:u,children:[a(R,{className:`h-3.5 w-3.5`}),` `,d(`common.delete`)]})]})]})})}function Cr(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function wr(e,t){return e.faceIds.filter(e=>!t.has(e))}function Tr(e,t){return e.faceIds.filter(e=>t(e))}l();var Er=[[`faceGallery`]],Dr=20,Or=.3,kr=.9,Ar=.05,jr=.5,Mr=2,Nr=10,Pr=2;function Fr({cluster:t,face:n,active:r,onSelect:i}){let{t:o}=Z(),s=ir(n);return e(Y,{variant:`unstyled`,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 ${r?`border-primary bg-primary/8`:`border-border bg-surface hover:bg-surface-hover`}`,children:[a(`div`,{className:`h-24 w-24 shrink-0 overflow-hidden rounded bg-surface-hover`,children:s===null?a(b,{className:`h-24 w-24 p-6 text-foreground-subtle`}):a(`img`,{src:s,alt:``,loading:`lazy`,decoding:`async`,className:`h-24 w-24 object-cover`})}),a(`span`,{className:`w-24 text-[11px] leading-tight text-foreground-subtle md:w-auto`,children:o(`detectionIntelligence.similarGroupsModal.clusterMeta`,{count:t.size,percent:Math.round(t.cohesion*100)})})]})}function Ir({face:t,cameraName:n,nowMs:r,excluded:i,onToggleExclude:o,onDelete:s,deletePending:c}){let{t:l}=Z(),u=ir(t);return e(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden transition-opacity ${i?`border-border opacity-40 grayscale`:`border-border`}`,children:[e(`div`,{className:`aspect-square relative overflow-hidden bg-surface-hover`,children:[u===null?e(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-warning/5 text-foreground-subtle`,children:[a(b,{className:`h-7 w-7 text-warning/70`}),a(`span`,{className:`text-[9px] font-medium uppercase tracking-wide text-warning/80`,children:l(`detectionIntelligence.similarGroupsModal.noCrop`,`No crop`)})]}):a(_r,{src:u,alt:l(`detectionIntelligence.similarGroupsModal.faceFrom`,`Face from {{cameraName}}`,{cameraName:n}),className:`h-full w-full`}),a(Y,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),o()},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?l(`detectionIntelligence.similarGroupsModal.includeFace`,`Include face`):l(`detectionIntelligence.similarGroupsModal.excludeFace`,`Exclude face`),title:i?l(`detectionIntelligence.similarGroupsModal.include`,`Include`):l(`detectionIntelligence.similarGroupsModal.exclude`,`Exclude`),children:a(i?x:q,{className:`h-3.5 w-3.5`})})]}),e(`div`,{className:`min-w-0 px-2 pt-1.5 space-y-0.5`,children:[a(`p`,{className:`text-[10px] font-medium text-foreground truncate`,title:n,children:n}),a(`p`,{className:`text-[10px] text-foreground-subtle truncate`,children:Qn(t.timestamp,r)})]}),a(`div`,{className:`mt-1 flex min-h-[2rem] items-center justify-end border-t border-border/60 px-1 py-0.5`,children:a(Y,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),s()},disabled:c,className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-danger/10 hover:text-danger disabled:opacity-40`,"aria-label":l(`detectionIntelligence.similarGroupsModal.deleteFace`,`Delete face`),title:l(`detectionIntelligence.similarGroupsModal.deleteFace`,`Delete face`),children:c?a(g,{className:`h-4 w-4 animate-spin`}):a(R,{className:`h-4 w-4`})})})]})}function Lr({open:t,onClose:r,byId:i,cameraName:c,nowMs:l,identities:f,selectMany:p}){let{t:m}=Z(),h=u(),_=P(),y=st(),[b,x]=s(jr),[S,C]=s(Pr),[w,T]=s(null),[D,k]=s({}),[A,j]=s(null),{data:M,isFetching:N,refetch:F}=Ye({threshold:b,minClusterSize:S,limit:Dr},{enabled:t}),I=M??[];o(()=>{k({})},[b,S]),o(()=>{if(I.length===0){T(null);return}I.some(e=>e.representativeFaceId===w)||T(I[0]?.representativeFaceId??null)},[I]);let L=n(()=>I.find(e=>e.representativeFaceId===w)??null,[I,w]),R=L?D[L.representativeFaceId]??new Set:new Set,z=n(()=>L?Tr(L,e=>i.has(e)):[],[L,i]),B=L?L.faceIds.length-z.length:0,V=L?wr({...L,faceIds:z},R):[];function ee(e){if(!L)return;let t=L.representativeFaceId;k(n=>({...n,[t]:Cr(n[t]??new Set,e)}))}function H(){h.invalidateQueries({queryKey:Er})}async function U(e){await _({title:m(`detectionIntelligence.similarGroupsModal.deleteFace`,`Delete face`),message:m(`detectionIntelligence.similarGroupsModal.permanentlyDeletesThisFaceCrop`,`Permanently deletes this face crop. This cannot be undone.`),confirmLabel:m(`common.delete`,`Delete`),variant:`danger`})&&y.mutate({faceId:e},{onSettled:H})}function te(){j(null),r()}function W(){V.length!==0&&(p(V),te())}return e(Be,{open:t,onOpenChange:e=>!e&&te(),children:[e(Me,{placement:`sheet-on-mobile`,width:`lg`,"aria-label":m(`detectionIntelligence.similarGroupsModal.lookAlikeGroups`,`Look-alike groups`),className:`flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 md:max-w-4xl`,children:[e(`header`,{className:`flex shrink-0 flex-col gap-2 border-b border-border py-3 pl-4 pr-10`,children:[e(`div`,{className:`flex items-center gap-1.5 text-sm font-semibold text-foreground`,children:[a(ae,{className:`h-4 w-4 text-primary`}),` `,m(`detectionIntelligence.similarGroupsModal.title`)]}),e(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[e(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[m(`detectionIntelligence.similarGroupsModal.threshold`,`Threshold`),a(O,{min:Or,max:kr,step:Ar,value:b,onChange:e=>x(Number(e.target.value)),className:`h-1.5 w-28 cursor-pointer accent-primary`}),a(`span`,{className:`w-8 shrink-0 text-right font-mono text-[11px] tabular-nums text-foreground`,children:b.toFixed(2)})]}),e(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[m(`detectionIntelligence.similarGroupsModal.minSize`,`Min size`),a(J,{type:`number`,min:Mr,max:Nr,step:1,value:S,onChange:e=>C(Math.min(Nr,Math.max(Mr,Number(e.target.value)||Mr))),className:`w-12 rounded border border-border bg-background px-1.5 py-0.5 text-xs text-foreground`})]}),e(Y,{variant:`secondary`,onClick:()=>{k({}),F()},disabled:N,children:[N?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(v,{className:`h-3.5 w-3.5`}),m(`detectionIntelligence.similarGroupsModal.reAnalyze`,`Re-analyze`)]})]})]}),a(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden px-4 py-3 md:flex-row`,children:N&&I.length===0?e(`div`,{className:`flex flex-1 items-center justify-center gap-2 py-8 text-xs text-foreground-subtle`,children:[a(g,{className:`h-4 w-4 animate-spin`}),` `,m(`detectionIntelligence.similarGroupsModal.finding`)]}):I.length===0?a(`div`,{className:`flex flex-1 items-center justify-center py-8 text-xs text-foreground-subtle`,children:m(`detectionIntelligence.similarGroupsModal.noLookAlikeGroupsAt`,`No look-alike groups at this threshold.`)}):e(d,{children:[a(`div`,{className:`flex gap-2 overflow-x-auto pb-1 md:hidden`,children:I.map(e=>a(Fr,{cluster:e,face:i.get(e.representativeFaceId),active:e.representativeFaceId===w,onSelect:()=>T(e.representativeFaceId)},e.representativeFaceId))}),a(`div`,{className:`hidden shrink-0 flex-col gap-2 overflow-y-auto md:flex md:w-56`,children:I.map(e=>a(Fr,{cluster:e,face:i.get(e.representativeFaceId),active:e.representativeFaceId===w,onSelect:()=>T(e.representativeFaceId)},e.representativeFaceId))}),a(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:L&&e(d,{children:[B>0&&a(`p`,{className:`mb-2 text-[11px] text-foreground-subtle`,children:m(`detectionIntelligence.similarGroupsModal.hiddenCount`,{count:B})}),a(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(13rem,13rem))] justify-start gap-2`,children:z.map(e=>{let t=i.get(e);return t?a(Ir,{face:t,cameraName:c(t.deviceId),nowMs:l,excluded:R.has(e),onToggleExclude:()=>ee(e),onDelete:()=>void U(e),deletePending:y.isPending&&y.variables?.faceId===e},e):null})})]})})]})}),e(`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:[a(Y,{variant:`secondary`,onClick:W,disabled:V.length===0,children:m(`detectionIntelligence.similarGroupsModal.selectInGallery`,`Select in gallery`)}),e(Y,{variant:`primary`,onClick:()=>j(V),disabled:V.length===0,children:[a(E,{className:`h-3.5 w-3.5`}),` `,m(`detectionIntelligence.similarGroupsModal.adopt`,{count:V.length})]})]})]}),a(ur,{faceIds:A,identities:f,onDone:()=>j(null)})]})}l();var Rr=[[`faceGallery`]],zr=500,Br=120;function Vr({face:t,cameraName:n,nowMs:r,selected:i,onToggleSelect:o,onAssign:s,onOpenDetail:c}){let{t:l}=Z(),d=u(),f=je(),p=st(),m=()=>{d.invalidateQueries({queryKey:Rr})},h=()=>c(t.faceId),_=ir(t);return e(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${i?`border-primary ring-1 ring-primary`:`border-border`}`,children:[e(`div`,{className:`aspect-square relative overflow-hidden bg-surface-hover`,children:[_===null?e(`button`,{type:`button`,onClick:h,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-warning/5 text-foreground-subtle`,title:l(`detectionIntelligence.unassignedFaces.noCropImageTheFace`,`No crop image — the face's crop media is missing (a pre-fix orphan). Safe to delete.`),children:[a(b,{className:`h-7 w-7 text-warning/70`}),a(`span`,{className:`text-[9px] font-medium uppercase tracking-wide text-warning/80`,children:l(`detectionIntelligence.unassignedFaces.noCrop`,`No crop`)})]}):a(`img`,{src:_,alt:l(`detectionIntelligence.unassignedFaces.faceFrom`,`Face from {{cameraName}}`,{cameraName:n}),onClick:h,loading:`lazy`,decoding:`async`,className:`h-full w-full cursor-zoom-in object-cover`}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t.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?l(`detectionIntelligence.unassignedFaces.deselect`,`Deselect`):l(`detectionIntelligence.unassignedFaces.select`,`Select`),children:i?a(ye,{className:`h-4 w-4 text-primary`}):a(W,{className:`h-4 w-4`})})]}),e(`div`,{className:`min-w-0 px-2 pt-1.5 space-y-0.5`,children:[a(`p`,{className:`text-[10px] font-medium text-foreground truncate`,title:n,children:n}),a(`p`,{className:`text-[10px] text-foreground-subtle truncate`,children:Qn(t.timestamp,r)}),a(`p`,{className:`min-h-[0.875rem] truncate text-[10px] font-medium leading-tight ${t.identityName?`text-primary`:`invisible`}`,title:t.identityName,children:t.identityName??`\xA0`})]}),e(`div`,{className:`mt-1 flex min-h-[2rem] items-center gap-0.5 border-t border-border/60 px-1 py-0.5`,children:[t.assigned?a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),f.mutate({faceId:t.faceId},{onSettled:m})},disabled:f.isPending,className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-warning/10 hover:text-warning disabled:opacity-40`,"aria-label":l(`detectionIntelligence.unassignedFaces.detachFace`,`Detach face`),title:l(`detectionIntelligence.unassignedFaces.detach`,`Detach`),children:f.isPending?a(g,{className:`h-4 w-4 animate-spin`}):a(xe,{className:`h-4 w-4`})}):a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s(t.faceId)},className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-primary/10 hover:text-primary`,"aria-label":l(`detectionIntelligence.unassignedFaces.assignFaceToPerson`,`Assign face to person`),title:l(`detectionIntelligence.unassignedFaces.assignToPerson`,`Assign to person`),children:a(E,{className:`h-4 w-4`})}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),p.mutate({faceId:t.faceId},{onSettled:m})},disabled:p.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":l(`detectionIntelligence.unassignedFaces.deleteFace`,`Delete face`),title:l(`detectionIntelligence.unassignedFaces.deleteFace`,`Delete face`),children:p.isPending?a(g,{className:`h-4 w-4 animate-spin`}):a(R,{className:`h-4 w-4`})})]})]})}var Hr=[{labelKey:`common.all`,value:`all`},{labelKey:`detectionIntelligence.unassignedFaces.filterUnassigned`,value:`unassigned`},{labelKey:`detectionIntelligence.unassignedFaces.filterRecognized`,value:`recognized`}];function Ur(){let{t}=Z(),r=u(),[i,o]=s(`all`),[c,l]=s(Hn),[f,p]=s(new Set),[m,h]=s(new Set),[_,v]=s(null),[y,x]=s(!1),[S,C]=s(null),{data:w,isLoading:T}=Je({limit:zr,filter:i,includeCrops:!1},{refetchInterval:3e4}),{data:D=[]}=ut(),{data:O}=Ve({isCamera:!0,projection:`slim`}),k=yt(),A=je(),j=Ae(),M=st(),N=Date.now(),P=w??[],F=n(()=>{let e=new Map;for(let t of O??[])e.set(t.id,t.name);return e},[O]),I=e=>F.get(e)??t(`detectionIntelligence.cameraFallback`,{id:String(e)}),L=n(()=>Yn(P).map(e=>({id:e,name:I(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[P,F]),z=n(()=>Jn(qn(P,c),f),[P,c,f]),B=ar(z,Br,n(()=>JSON.stringify([i,c.fromMs,c.toMs,[...f].sort((e,t)=>e-t)]),[i,c.fromMs,c.toMs,f])),V=n(()=>new Map(P.map(e=>[e.faceId,e])),[P]),ee=n(()=>rr(z),[z]),H=S===null?null:V.get(S)??null,U=()=>{r.invalidateQueries({queryKey:Rr})},te=()=>h(new Set);function W(e){h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function ne(e){h(t=>{let n=new Set(t);for(let t of e)n.add(t);return n})}function re(){ne(nr(z))}let G=[...m],K=k.isPending||j.isPending||M.isPending,ie=A.isPending||M.isPending;function oe(){G.length!==0&&j.mutate({faceIds:G},{onSettled:()=>{U(),te()}})}function se(){G.length!==0&&Promise.allSettled(G.map(e=>M.mutateAsync({faceId:e}))).then(()=>{U(),te()})}function ce(e){C(null),v([e])}function le(e){A.mutate({faceId:e},{onSettled:U}),C(null)}function ue(e){M.mutate({faceId:e},{onSettled:U}),C(null)}let de=z.length!==P.length;return e(`div`,{className:`relative space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[a(`div`,{className:`flex items-center gap-1`,children:Hr.map(e=>a(`button`,{type:`button`,onClick:()=>o(e.value),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${i===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:t(e.labelKey)},e.value))}),a(pr,{onChange:l}),a(dr,{cameras:L,selected:f,onChange:p}),e(`button`,{type:`button`,onClick:()=>x(!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:[a(ae,{className:`h-3.5 w-3.5`}),` `,t(`detectionIntelligence.unassignedFaces.similarGroups`)]}),!T&&ee>0&&e(`button`,{type:`button`,onClick:re,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:t(`detectionIntelligence.unassignedFaces.selectEveryVisibleFaceWhose`,`Select every visible face whose crop image is missing so you can delete the orphans in one pass`),children:[a(b,{className:`h-3.5 w-3.5`}),` `,t(`detectionIntelligence.unassignedFaces.selectCropless`,{count:ee})]}),!T&&a(`span`,{className:`text-[10px] text-foreground-subtle ${ee>0?`ml-2`:`ml-auto`}`,children:de?t(`detectionIntelligence.unassignedFaces.ofFaces`,`{{value1}} of {{value2}} faces`,{value1:String(z.length),value2:String(P.length)}):t(`detectionIntelligence.unassignedFaces.faceCount`,{count:z.length})})]}),m.size>0&&e(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[a(`span`,{className:`text-xs font-medium text-foreground`,children:t(`common.selectedCount`,{count:m.size})}),e(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[e(Y,{variant:`primary`,onClick:()=>v(G),disabled:K,children:[a(E,{className:`h-3.5 w-3.5`}),` `,t(`common.assign`)]}),e(Y,{variant:`secondary`,onClick:oe,disabled:K,children:[j.isPending?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(xe,{className:`h-3.5 w-3.5`}),` `,t(`detectionIntelligence.unassignedFaces.detach`,`Detach`)]}),e(Y,{variant:`secondary`,onClick:se,disabled:K,children:[a(R,{className:`h-3.5 w-3.5`}),` `,t(`common.delete`)]}),a(Y,{variant:`ghost`,onClick:te,disabled:K,children:a(q,{className:`h-3.5 w-3.5`})})]})]}),T?a(we,{status:`pending`,pendingMessage:`Loading faces…`,testId:`faces-grid`}):z.length===0?a(nt,{icon:b,title:P.length>0?t(`detectionIntelligence.unassignedFaces.nothingMatchesTheFilter`,`Nothing matches the filter`):t(`detectionIntelligence.unassignedFaces.noFacesFoundForThis`,`No faces found for this filter`),description:P.length>0?t(`detectionIntelligence.unassignedFaces.widenTheDateRangeOr`,`Widen the date range or clear the camera filter.`):t(`detectionIntelligence.unassignedFaces.faceCropsAppearHereWhen`,`Face crops appear here when the detection pipeline captures them.`)}):e(d,{children:[a(we,{status:`ready`,testId:`faces-grid`,className:`grid-cols-[repeat(auto-fill,minmax(6.5rem,6.5rem))] justify-start`,children:B.pageItems.map(e=>a(Vr,{face:e,cameraName:I(e.deviceId),nowMs:N,selected:m.has(e.faceId),onToggleSelect:W,onAssign:e=>v([e]),onOpenDetail:C},e.faceId))}),a(cr,{currentPage:B.page,totalItems:B.totalItems,pageSize:B.pageSize,onPageChange:B.setPage,itemNoun:`faces`})]}),a(Sr,{face:H,cameraName:H?I(H.deviceId):``,onClose:()=>C(null),onAssign:ce,onUnassign:le,onDelete:ue,actionsPending:ie}),a(ur,{faceIds:_,identities:D,onDone:()=>{v(null),te()}}),a(Lr,{open:y,onClose:()=>x(!1),byId:V,cameraName:I,nowMs:N,identities:D,selectMany:ne})]})}function Wr(e){let{delayMs:t,invalidate:n,setTimeoutFn:r=setTimeout,clearTimeoutFn:i=clearTimeout}=e,a;function o(){a===void 0&&(a=r(()=>{a=void 0,n()},t))}function s(){a!==void 0&&(i(a),a=void 0)}return{trigger:o,cancel:s}}l();var Gr=[[`faceGallery`]],Kr=2e3;function qr(){let e=u(),n=t(e);n.current=e;let r=t(void 0);r.current||=Wr({delayMs:Kr,invalidate:()=>{n.current.invalidateQueries({queryKey:Gr})}}),o(()=>()=>r.current?.cancel(),[]),Ue(ue.PipelineAnalyticsFaceGalleryChanged,()=>{r.current?.trigger()})}function Jr(){let{t}=Z();return qr(),e(`div`,{className:`space-y-3`,children:[a(We,{headingId:`library-people`,title:t(`detectionIntelligence.people`,`People`),icon:_e,testId:`library-section-people`,children:e(`div`,{className:`${p} space-y-3`,children:[a(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`detectionIntelligence.enrolledIdentitiesUsedForFace`,`Enrolled identities used for face recognition. Open a person to rename them or remove training samples.`)}),a(Vn,{})]})}),a(We,{headingId:`library-recent-faces`,title:t(`detectionIntelligence.recentDetectedFaces`,`Recent detected faces`),icon:me,testId:`library-section-recent-faces`,children:e(`div`,{className:`${p} space-y-3`,children:[a(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`detectionIntelligence.faceCropsCapturedByThe`,`Face crops captured by the detection pipeline. Assign them to a person to build recognition training data.`)}),a(Ur,{})]})})]})}function Yr(e){let t=e.subLabel??e.label;if(t!==void 0)return t;let n=e.audioLabels?.[0]?.label;return n!==void 0&&n.length>0?n:void 0}var Xr=720*60*60*1e3;function Zr(e){let t=[];for(let n of e)t.push(...n);return t}function Qr(e,t){let n=[...e];return n.sort((e,n)=>t===`importance`?n.importance-e.importance:n.timestamp-e.timestamp),n}function $r(e,t){return e.filter(e=>!(e.importance<t.minImportance||t.cameras.size>0&&!t.cameras.has(e.deviceId)||t.classes.size>0&&!t.classes.has(e.className)))}function ei(e,t){return`${String(e)}:${t}`}function ti(e,t){let n=new Map,r=new Set;for(let i of e){let e=ei(i.deviceId,i.trackId);if(!t.has(e)||r.has(e))continue;r.add(e);let a=n.get(i.deviceId);a?a.push(i.trackId):n.set(i.deviceId,[i.trackId])}return n}function ni(e,t){return{since:e.fromMs??t-Xr,until:e.toMs??t}}var ri=[`native`,`raster`,`standin`];function ii(e){return ri.some(t=>t===e)}function ai(e){return e===`standin`?{label:X.t(`helpers.mediaProvenance.standin.label`),title:X.t(`helpers.mediaProvenance.standin.title`),tone:`warning`}:{label:X.t(`helpers.mediaProvenance.raster.label`),title:X.t(`helpers.mediaProvenance.raster.title`),tone:`info`}}function oi(e){return e===`standin`?ai(`standin`):e===`raster`?ai(`raster`):null}var si={"no-key-frame":`helpers.mediaProvenance.miss.noKeyFrame`,"no-best-seen-bbox":`helpers.mediaProvenance.miss.noBestSeenBbox`,"derive-returned-null":`helpers.mediaProvenance.miss.deriveReturnedNull`,"derive-threw":`helpers.mediaProvenance.miss.deriveThrew`,"derive-not-wired":`helpers.mediaProvenance.miss.deriveNotWired`,"no-media-store":`helpers.mediaProvenance.miss.noMediaStore`,"no-thumbnail":`helpers.mediaProvenance.miss.noThumbnail`,"standin-tile":`helpers.mediaProvenance.miss.standinTile`,"raster-tile":`helpers.mediaProvenance.miss.rasterTile`,"native-tile":`helpers.mediaProvenance.miss.nativeTile`};function ci(e){if(e===void 0)return null;let t=e.trim();if(t.length===0)return null;let n=t.split(/\s+/),r=n[0]??t,i=[];for(let e of n.slice(1)){let t=e.indexOf(`=`);t===-1?i.push({key:e,value:null}):i.push({key:e.slice(0,t),value:e.slice(t+1)})}let a=si[r];return{sentence:a===void 0?r:X.t(a),detail:i,raw:t}}function li(e){if(e===void 0||!Number.isFinite(e)||e<=0)return``;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${String(n)}m ${String(r).padStart(2,`0`)}s`}function ui({row:t,cameraName:n,nowMs:r,onOpenDetail:i,selected:o=!1,onToggleSelect:s,score:c,provenance:l,footer:u}){let{t:d}=Z(),f=Gt(t.mediaId===void 0?Kt(`track`,t.trackId):Jt(t.mediaId)),p=Math.round(t.importance*100),m=c===void 0?void 0:Math.round(c*100),h=li(t.windowMs),g=()=>i(t),_=oi(l);return e(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${o?`border-primary ring-1 ring-primary`:`border-border`}`,children:[e(`div`,{className:`aspect-video relative overflow-hidden bg-surface-hover`,children:[f.src?a(`img`,{src:f.src,alt:d(`detectionIntelligence.eventCard.eventFrom`,`Event from {{cameraName}}`,{cameraName:n}),onClick:g,className:`h-full w-full cursor-zoom-in object-cover`}):a(Y,{variant:`unstyled`,type:`button`,onClick:g,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-surface-hover text-foreground-subtle`,title:f.failed?d(`detectionIntelligence.eventCard.keyEventMediaUnavailable`,`Key-event media unavailable`):d(`detectionIntelligence.eventCard.noKeyEventMedia`,`No key-event media`),children:a(b,{className:`h-6 w-6 opacity-60`})}),s&&a(Y,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),s(ei(t.deviceId,t.trackId))},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":o?d(`detectionIntelligence.eventCard.deselect`,`Deselect`):d(`detectionIntelligence.eventCard.select`,`Select`),children:o?a(ye,{className:`h-4 w-4 text-primary`}):a(W,{className:`h-4 w-4`})}),m!==void 0&&e(`span`,{className:`absolute left-1 top-1 z-10 rounded bg-primary/85 px-1.5 py-0.5 text-[10px] font-semibold text-white tabular-nums`,title:d(`detectionIntelligence.eventCard.clipSemanticMatchScore`,`CLIP semantic-match score`),children:[String(m),`%`]}),p>0&&a(`span`,{className:`absolute right-1 top-1 z-10 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-semibold text-white`,children:String(p)}),_!==null&&a(`span`,{className:`absolute bottom-1 right-1 z-10 rounded px-1.5 py-0.5 text-[10px] font-semibold text-white ${_.tone===`warning`?`bg-warning/90`:`bg-black/70`}`,title:_.title,children:_.label}),(t.markForTrain===!0||t.retrainStatus===`trained`||t.debug===!0||t.favourited===!0)&&e(`span`,{className:`absolute bottom-1 left-1 z-10 flex gap-1`,children:[t.markForTrain===!0&&a(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:d(`detectionIntelligence.eventCard.markedForTraining`,`Marked for training`),"aria-label":d(`detectionIntelligence.eventCard.markedForTraining`,`Marked for training`),children:a(ne,{className:`h-3 w-3`})}),t.retrainStatus===`trained`&&t.markForTrain!==!0&&a(`span`,{className:`rounded bg-success/85 p-0.5 text-white`,title:d(`detectionIntelligence.eventCard.trainingComplete`,`Training complete`),"aria-label":d(`detectionIntelligence.eventCard.trainingComplete`,`Training complete`),"data-testid":`retrain-status-trained`,children:a(L,{className:`h-3 w-3`})}),t.debug===!0&&a(`span`,{className:`rounded bg-black/70 p-0.5 text-white`,title:d(`detectionIntelligence.eventCard.flaggedForDebug`,`Flagged for debug`),"aria-label":d(`detectionIntelligence.eventCard.flaggedForDebug`,`Flagged for debug`),children:a(K,{className:`h-3 w-3`})}),t.favourited===!0&&a(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:d(`detectionIntelligence.eventCard.favourited`,`Favourited`),"aria-label":d(`detectionIntelligence.eventCard.favourited`,`Favourited`),children:a(B,{className:`h-3 w-3`})})]})]}),e(Y,{variant:`unstyled`,type:`button`,onClick:g,className:`min-w-0 px-2 py-1.5 text-left space-y-0.5`,children:[e(`p`,{className:`text-[11px] font-medium text-foreground truncate`,title:t.className,children:[t.className,Yr(t)?e(`span`,{className:`text-foreground-subtle`,children:[` · `,Yr(t)]}):null]}),a(`p`,{className:`text-[10px] text-foreground-subtle truncate`,title:n,children:n}),e(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`span`,{className:`text-[10px] text-foreground-subtle truncate`,children:Qn(t.timestamp,r)}),h&&a(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:h})]})]}),u!==void 0&&a(`div`,{className:`px-2 pb-1.5`,children:u})]})}l();var di=1400,fi=`Admin-gated URL — opens only inside an authenticated session`;function pi({label:t,value:n,title:r}){let{t:c}=Z(),[l,u]=s(!1),d=ie();return o(()=>{if(!l)return;let e=setTimeout(()=>u(!1),di);return()=>clearTimeout(e)},[l]),e(Y,{variant:`unstyled`,type:`button`,onClick:i(()=>{(async()=>{try{await navigator.clipboard.writeText(n),u(!0)}catch{await d({title:c(`detectionIntelligence.copyUrlChips.copyTheMediaUrl`,`Copy the media URL`),message:c(`detectionIntelligence.copyUrlChips.clipboardAccessWasRefusedSelect`,`Clipboard access was refused. Select the URL below and copy it manually.`),label:c(`detectionIntelligence.copyUrlChips.url`,`{{label}} URL`,{label:t}),defaultValue:n,readOnly:!0,cancelLabel:c(`common.close`,`Close`)})}})()},[n,t,d,c]),title:r,"aria-label":c(`detectionIntelligence.copyUrlChips.copyUrl`,`Copy {{label}} URL`,{label:t}),className:`flex min-w-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${l?`border-success/40 bg-success/10 text-success`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[a(l?L:m,{className:`h-2.5 w-2.5 shrink-0`}),a(`span`,{className:`truncate`,children:l?c(`detectionIntelligence.copyUrlChips.copied`,`Copied`):t})]})}function mi({localUrl:t,publicUrl:n}){let{t:r}=Z();return e(`div`,{className:`flex flex-wrap gap-1`,children:[a(pi,{label:r(`detectionIntelligence.copyUrlChips.local`,`Local`),value:t,title:r(`detectionIntelligence.copyUrlChips.copyLanUrl`,`Copy LAN URL — {{AUTH_HINT}}`,{AUTH_HINT:fi})}),n&&a(pi,{label:r(`detectionIntelligence.copyUrlChips.public`,`Public`),value:n,title:r(`detectionIntelligence.copyUrlChips.copyPublicUrl`,`Copy public URL — {{AUTH_HINT}}`,{AUTH_HINT:fi})})]})}var hi={firstFrame:`First frame (track start)`,lastFrame:`Last frame (track end)`,thumbnail:`Best detection`,thumbnailSmall:`Best detection (480)`,snapshot:`Snapshot`,keyFrame:`Key frame (native-res)`,keyFrameSmall:`Key frame (960)`,crop:`Object crop`,fullFrame:`Full frame`,fullFrameBoxed:`Full frame (boxed)`,faceCrop:`Face crop`,plateCrop:`Plate crop`,confirmationCrop:`Confirmation crop (what the gate saw)`,debugCrop:`Debug crop (why this decision)`,sceneFrame:`Scene frame (clean)`,lastSceneFrame:`Last frame (clean)`};function gi(e){return e in hi}function _i(e){return gi(e)?hi[e]:e}function vi(e,t){return`${e}${t}`}l();var yi=3e4;function bi(e){let[t,n]=s(null),r=i(e=>{n(t=>t??e)},[]);return o(()=>{e||n(null)},[e]),{publicOrigin:t,probes:e?a(xi,{onOrigin:r}):null}}function xi({onOrigin:e}){let{data:t}=it({capName:`network-access`});return a(d,{children:(t??[]).map(t=>a(Si,{addonId:t.addonId,onOrigin:e},t.addonId))})}function Si({addonId:e,onOrigin:t}){let{data:n}=Ee({addonId:e},{refetchInterval:yi,retry:!1});return o(()=>{let e=n?de.safeParse(n):null,r=e?.success?e.data.endpoint?.url:void 0;if(r)try{t(new URL(r).origin)}catch{}},[n,t]),null}var Ci=typeof at==`function`,wi=`Track flags arrive with the next server update`;function Ti(){return{mutateAsync:async()=>{throw Error(`setTrackFlags unavailable`)},isPending:!1}}var Ei=Ci?at:Ti;function Di(e){if(typeof e!=`object`||!e||!(`trackId`in e)||!(`markForTrain`in e)||!(`debug`in e)||!(`favourited`in e))return null;let{trackId:t,markForTrain:n,debug:r,favourited:i}=e;return typeof t!=`string`||typeof n!=`boolean`||typeof r!=`boolean`||typeof i!=`boolean`?null:{trackId:t,markForTrain:n,debug:r,favourited:i}}l();function Oi({label:t,hint:n,checked:r,disabled:i,title:o,icon:s,onToggle:c}){return e(Y,{variant:`unstyled`,type:`button`,role:`switch`,"aria-checked":r,"aria-label":t,disabled:i,title:o,onClick:c,className:`flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left transition-colors disabled:opacity-50 ${r?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[a(`span`,{className:r?`text-primary`:`text-foreground-subtle`,children:s}),e(`span`,{className:`min-w-0 flex-1`,children:[a(`span`,{className:`block text-[11px] font-medium text-foreground`,children:t}),a(`span`,{className:`block text-[10px] text-foreground-subtle`,children:n})]}),a(`span`,{"aria-hidden":`true`,className:`h-4 w-7 shrink-0 rounded-full p-0.5 transition-colors ${r?`bg-primary`:`bg-border`}`,children:a(`span`,{className:`block h-3 w-3 rounded-full bg-white transition-transform ${r?`translate-x-3`:``}`})})]})}function ki({deviceId:t,trackId:n,markForTrain:r,debug:i,favourited:o,onChange:c}){let{t:l}=Z(),u=Ei(),d=te(),[f,p]=s(null),m=f?.markForTrain??r===!0,h=f?.debug??i===!0,g=f?.favourited??o===!0,_=!Ci||u.isPending,v=Ci?void 0:wi,y=e=>{_||(async()=>{try{let r=Di(await u.mutateAsync({deviceId:t,trackId:n,flags:e}));if(!r)return;p(r),c?.(r)}catch(e){let t=e instanceof Error?e.message:``;await d({title:l(`detectionIntelligence.trackFlagToggles.couldNotUpdateThisTrack`,`Could not update this track`),message:t===``?l(`detectionIntelligence.trackFlagToggles.couldNotUpdateThisTrack2`,`Could not update this track. Check the server logs.`):t,variant:`danger`})}})()};return e(`div`,{className:`grid gap-1.5 sm:grid-cols-2`,children:[a(Oi,{label:l(`detectionIntelligence.trackFlagToggles.markForTraining`,`Mark for training`),hint:l(`detectionIntelligence.trackFlagToggles.keepsThisTrackAndIts`,`Keeps this track and its media past retention`),checked:m,disabled:_,...v===void 0?{}:{title:v},icon:a(ne,{className:`h-4 w-4`}),onToggle:()=>y({markForTrain:!m})}),a(Oi,{label:l(`detectionIntelligence.trackFlagToggles.debug`,`Debug`),hint:l(`detectionIntelligence.trackFlagToggles.flagThisTrackForDiagnostic`,`Flag this track for diagnostic attention`),checked:h,disabled:_,...v===void 0?{}:{title:v},icon:a(K,{className:`h-4 w-4`}),onToggle:()=>y({debug:!h})}),a(Oi,{label:l(`detectionIntelligence.trackFlagToggles.favourited`,`Favourited`),hint:l(`detectionIntelligence.trackFlagToggles.keepsThisTrackAndIts`,`Keeps this track and its media past retention`),checked:g,disabled:_,...v===void 0?{}:{title:v},icon:a(B,{className:`h-4 w-4`}),onToggle:()=>y({favourited:!g})})]})}function Ai(e){let t=e.deviceKey===void 0?e.nodeId:`${e.nodeId} · ${e.deviceKey}`;return e.modelId===void 0?t:`${t} (${e.modelId})`}function ji(e){let t=e?.openedPlacement,n=e?.closedPlacement;if(t!==void 0&&n!==void 0){let e=Ai(t),r=Ai(n);return e===r?[{kind:`detected`,value:e}]:[{kind:`opened`,value:e},{kind:`closed`,value:r}]}return t===void 0?n===void 0?[]:[{kind:`closed`,value:Ai(n)}]:[{kind:`opened`,value:Ai(t)}]}var Mi=100,Ni={polyline:``,points:[],snapshots:[],start:null,end:null,peakBox:null},Pi=e=>e<0?0:e>1?1:e,Fi=e=>Math.round(e*100)/100;function Ii(e,t,n){if(e.length===0||t===null)return Ni;let{width:r,height:i}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)return Ni;let a=fe(e.map(e=>({x:e.x/r,y:e.y/i,w:e.bbox.w/r,h:e.bbox.h/i})),n?.maxPoints===void 0?void 0:{maxPoints:n.maxPoints}).nodes.map(e=>({x:Fi(e.x*Mi),y:Fi(e.y*Mi)})),o=a[0]??null,s=a[a.length-1]??null,c=a.length>=2?a.map(e=>`${e.x},${e.y}`).join(` `):``,l=(n?.snapshots??[]).map(e=>({x:Fi(Pi(e.x/r)*Mi),y:Fi(Pi(e.y/i)*Mi),mediaId:e.mediaId})),u=null,d=-1;for(let t of e){let e=Pi(t.bbox.w/r)*Pi(t.bbox.h/i);e>d&&(d=e,u=t)}return{polyline:c,points:a,snapshots:l,start:o,end:s,peakBox:u?{x:Fi(Pi(u.bbox.x/r)*Mi),y:Fi(Pi(u.bbox.y/i)*Mi),w:Fi(Pi(u.bbox.w/r)*Mi),h:Fi(Pi(u.bbox.h/i)*Mi)}:null}}var Li=typeof Pe==`function`,Ri=`Track deletion arrives with the next server update`;function zi(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var Bi=Li?Pe:zi;l();var Vi=15e3,Hi=A();function Ui({url:e,label:t}){let{src:n,failed:r}=Gt(e);return n===null?a(`div`,{className:`flex h-full w-full items-center justify-center bg-surface-hover`,children:r?a(b,{className:`h-4 w-4 text-foreground-subtle opacity-60`}):a(g,{className:`h-4 w-4 animate-spin text-foreground-subtle opacity-70`})}):a(`img`,{src:n,alt:t,className:`h-full w-full object-cover`})}var Wi=new Set([`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]),Gi=new Set([`keyFrame`,`fullFrame`,`fullFrameBoxed`,`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`,`sceneFrame`,`lastSceneFrame`]);function Ki(e){let[t,n]=s(null);return o(()=>{if(n(null),!e)return;let t=!1,r=new Image;return r.onload=()=>{t||n({width:r.naturalWidth,height:r.naturalHeight})},r.src=e,()=>{t=!0,r.onload=null}},[e]),t}function qi({overlay:t,onPickSnapshot:n}){let{t:r}=Z();return!t.polyline&&!t.peakBox&&t.snapshots.length===0?null:e(`svg`,{viewBox:`0 0 100 100`,preserveAspectRatio:`none`,className:`pointer-events-none absolute inset-0 h-full w-full`,children:[t.peakBox&&a(`rect`,{x:t.peakBox.x,y:t.peakBox.y,width:t.peakBox.w,height:t.peakBox.h,fill:`none`,stroke:`var(--color-warning)`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),t.polyline&&a(`polyline`,{points:t.polyline,fill:`none`,stroke:`var(--color-info)`,strokeWidth:2,strokeLinejoin:`round`,strokeLinecap:`round`,strokeOpacity:.85,vectorEffect:`non-scaling-stroke`}),t.points.map((e,t)=>a(`circle`,{cx:e.x,cy:e.y,r:1,fill:`var(--color-info)`,fillOpacity:.6,vectorEffect:`non-scaling-stroke`},`${String(e.x)}-${String(e.y)}-${String(t)}`)),t.snapshots.map((e,t)=>a(`circle`,{cx:e.x,cy:e.y,r:1.9,fill:`var(--color-info)`,fillOpacity:.95,stroke:`var(--color-background)`,strokeWidth:.7,vectorEffect:`non-scaling-stroke`,className:n?`pointer-events-auto cursor-pointer`:void 0,onClick:n?t=>{t.stopPropagation(),n(e.mediaId)}:void 0,children:a(`title`,{children:r(`detectionIntelligence.eventDetailPanel.snapshotCheckpointClickToView`,`Snapshot checkpoint — click to view this frame`)})},`snap-${String(e.mediaId)}-${String(t)}`)),t.start&&a(`circle`,{cx:t.start.x,cy:t.start.y,r:2.4,fill:`var(--color-success)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),t.end&&a(`circle`,{cx:t.end.x,cy:t.end.y,r:2.4,fill:`var(--color-danger)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function Ji({label:t,value:n,mono:r,wrap:i}){return e(`div`,{className:`flex items-baseline justify-between gap-3 border-b border-border/60 py-1.5 last:border-0`,children:[a(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:t}),a(`span`,{className:`min-w-0 ${i?`break-words`:`truncate`} text-right text-xs font-medium text-foreground ${r?`font-mono text-[11px]`:``}`,title:n,children:n})]})}function Yi({row:t,cameraName:r,deleteAvailable:c,onClose:l,onDeleted:u,onFlagsChanged:f}){let{t:p}=Z(),m=oe(),h=te(),_=P(),v=Bi(),y=t!==null,x=t?.deviceId??0,S=t?.trackId??``,C=t?.timestamp??0,w=t?.windowMs??0,{data:T}=$e({deviceId:x,trackId:S},{enabled:y}),{data:E}=Ie({trackId:S,deviceId:x},{enabled:y}),D=T?.bestEventId===void 0?void 0:Number(T.bestEventId),{data:O}=Re({ownerType:`object`,eventId:D??0,deviceId:x},{enabled:y&&D!==void 0&&Number.isFinite(D)}),{data:k}=It({deviceId:x},{enabled:y}),A=(k??[]).find(e=>e.addonId!==void 0)?.addonId,{data:j}=Ke({deviceId:x,since:C-Vi,until:C+w+Vi,provider:A??``},{enabled:y&&A!==void 0}),[M,N]=s(null),[I,L]=s(!1),{publicOrigin:z,probes:B}=bi(y);o(()=>{N(null)},[x,S]);let V=n(()=>{let e=E??[],t=O??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[E,O]),ee=M??V,H=Gt(ee?ee.url:void 0),U=n(()=>{let e=new Set,t=[];for(let n of[...O??[],...E??[]])e.has(n.mediaId)||(e.add(n.mediaId),t.push(n));return t},[O,E]),W=n(()=>U.find(e=>Wi.has(e.kind))??null,[U]),ne=Ki(Gt(W?W.url:void 0).src),re=n(()=>Ii(T?.positions??[],ne,{snapshots:(T?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaId:e.mediaId}))}),[T?.positions,T?.snapshots,ne]),G=i(e=>{let t=U.find(t=>t.mediaId===e);t&&N(t)},[U]);if(t===null)return null;let K=H.src,ie=ee?.kind,ae=ie!==void 0&&Gi.has(ie)&&ne!==null&&(T?.positions.length??0)>=2,q=j&&j.length>0?j[0]:null,se=()=>{q&&(L(!0),(async()=>{try{let e=await m.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:q.id});window.open(e.playbackUrl,`_blank`,`noopener`)}catch{h({title:p(`detectionIntelligence.eventDetailPanel.clipUnavailable`,`Clip unavailable`),message:p(`detectionIntelligence.eventDetailPanel.couldNotResolveClipPlayback`,`Could not resolve clip playback. Check the server logs.`),variant:`warning`})}finally{L(!1)}})())},ce=()=>{!c||v.isPending||(async()=>{if(await _({title:p(`detectionIntelligence.eventDetailPanel.deleteTrack`,`Delete track`),message:p(`detectionIntelligence.eventDetailPanel.deleteThisTrackAndEvery`,`Delete this track and every image and clip captured for it? This cannot be undone.`),confirmLabel:p(`common.delete`,`Delete`),variant:`danger`}))try{await v.mutateAsync({deviceId:t.deviceId,trackIds:[t.trackId]}),u()}catch{await h({title:p(`detectionIntelligence.eventDetailPanel.deleteFailed`,`Delete failed`),message:p(`detectionIntelligence.eventDetailPanel.failedToDeleteThisTrack`,`Failed to delete this track. Check the server logs.`),variant:`danger`})}})()},le=Math.round(t.importance*100),ue=T?.importanceReason?`${String(le)}% · ${T.importanceReason}`:`${String(le)}%`,de=T?.zonesVisited&&T.zonesVisited.length>0?T.zonesVisited.join(`, `):`—`,fe=T?.audioLabels&&T.audioLabels.length>0?T.audioLabels:t.audioLabels&&t.audioLabels.length>0?t.audioLabels:void 0,pe=fe===void 0?`—`:fe.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `),me=T?T.totalDistance.toFixed(2):`—`,he=ci(T?.previewMissReason),ge=er(T?T.firstSeen:C),_e=T?er(T.lastSeen):`—`,ve=ji(T),ye={detected:p(`detectionIntelligence.eventDetailPanel.detectedOn`,`Detected on`),opened:p(`detectionIntelligence.eventDetailPanel.openedOn`,`Opened on`),closed:p(`detectionIntelligence.eventDetailPanel.closedOn`,`Closed on`)};return a(Be,{open:!0,onOpenChange:e=>!e&&l(),children:e(Me,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":p(`detectionIntelligence.eventDetailPanel.eventDetail`,`Event detail`),className:`flex 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:h-auto 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:[a(`header`,{className:`flex shrink-0 items-start gap-2 border-b border-border py-3 pl-4 pr-10`,children:e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:[t.className,Yr(t)?e(`span`,{className:`text-foreground-subtle`,children:[` · `,Yr(t)]}):null]}),a(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:r})]})}),e(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[K?a(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:a(_r,{src:K,alt:p(`detectionIntelligence.eventDetailPanel.keyFrameFrom`,`Key frame from {{cameraName}}`,{cameraName:r}),fit:`natural`,className:`w-full`,overlay:ae?a(qi,{overlay:re,onPickSnapshot:G}):void 0})}):a(`div`,{className:`flex aspect-video w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-surface-hover text-foreground-subtle`,children:H.failed?e(d,{children:[a(b,{className:`h-8 w-8 opacity-60`}),a(`span`,{className:`text-[11px]`,children:p(`detectionIntelligence.eventDetailPanel.keyFrameMediaUnavailable`,`Key-frame media unavailable`)})]}):a(g,{className:`h-6 w-6 animate-spin opacity-70`})}),U.length>0&&a(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:U.map(t=>{let n=_i(t.kind),r=vi(Hi,t.url),i=z?vi(z,t.url):null;return e(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[a(Y,{variant:`unstyled`,type:`button`,onClick:()=>N(t),className:`relative h-16 w-full overflow-hidden rounded border border-border hover:border-primary`,title:`${n} · ${er(t.timestamp)}`,children:a(Ui,{url:t.url,label:n})}),e(`figcaption`,{className:`min-w-0 px-0.5`,children:[a(`div`,{className:`truncate text-[10px] font-medium leading-tight text-foreground`,title:n,children:n}),a(`div`,{className:`text-[10px] leading-tight text-foreground-subtle`,title:er(t.timestamp),children:$n(t.timestamp)})]}),a(mi,{localUrl:r,publicUrl:i})]},t.mediaId)})}),B,q&&e(Y,{variant:`secondary`,onClick:se,disabled:I,children:[I?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(F,{className:`h-3.5 w-3.5`}),` `,p(`detectionIntelligence.eventDetailPanel.viewClip`,`View clip`)]}),a(ki,{deviceId:t.deviceId,trackId:t.trackId,...(T?.markForTrain??t.markForTrain)===void 0?{}:{markForTrain:T?.markForTrain??t.markForTrain},...(T?.debug??t.debug)===void 0?{}:{debug:T?.debug??t.debug},...(T?.favourited??t.favourited)===void 0?{}:{favourited:T?.favourited??t.favourited},onChange:f}),he!==null&&e(`div`,{className:`rounded-lg border border-warning/40 bg-warning/8 px-3 py-2`,children:[a(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:p(`detectionIntelligence.eventDetailPanel.bestShot`,`Best shot`)}),a(`p`,{className:`mt-0.5 text-xs text-foreground`,children:he.sentence}),a(`code`,{className:`mt-1 block break-all font-mono text-[10px] text-foreground-subtle`,children:he.raw})]}),e(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.camera`,`Camera`),value:r}),ve.map(e=>a(Ji,{label:ye[e.kind],value:e.value,mono:!0,wrap:!0},e.kind)),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.class`,`Class`),value:t.className}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.label`,`Label`),value:t.label??`—`}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.subLabel`,`Sub-label`),value:t.subLabel??`—`}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.importance`,`Importance`),value:ue}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.zonesVisited`,`Zones visited`),value:de}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.audioHeard`,`Audio heard`),value:pe}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.totalDistance`,`Total distance`),value:me}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.firstSeen`,`First seen`),value:ge}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.lastSeen`,`Last seen`),value:_e}),a(Ji,{label:p(`detectionIntelligence.eventDetailPanel.track`,`Track`),value:t.trackId,mono:!0})]})]}),a(`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:a(`span`,{title:c?void 0:Ri,children:e(Y,{variant:`secondary`,onClick:ce,disabled:!c||v.isPending,children:[v.isPending?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(R,{className:`h-3.5 w-3.5`}),` `,p(`detectionIntelligence.eventDetailPanel.deleteTrack`,`Delete track`)]})})})]})})}var Xi={status:`debug.tape.status`,promote:`debug.tape.promote`,list:`debug.tape.list`,tracks:`debug.tape.tracks`,review:`debug.tape.review`,release:`debug.tape.release`,remove:`debug.tape.delete`},Zi={setRelation:`debug.gt.setRelation`,setPurity:`debug.gt.setPurity`,list:`debug.gt.list`},Qi=C(`/addon/pipeline-analytics/tape-export`),$i=10*6e4;function ea(e){return`${Qi}?tapeId=${encodeURIComponent(e)}`}var ta=`The server answered in a shape this build does not understand.`;function na(e){return e instanceof Error?e.message:X.t(`helpers.eventsDebugTapes.actionFailed`)}function ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function ia(e,t){if(!(t in e))return;let n=e[t];return n===null?null:typeof n==`number`&&Number.isFinite(n)?n:void 0}function $(e,t){let n=e[t];return typeof n==`string`?n:null}function aa(e,t){let n=e[t];return typeof n==`boolean`?n:null}function oa(e,t){if(!Array.isArray(e))return null;let n=[];for(let r of e){let e=t(r);if(e===null)return null;n.push(e)}return n}function sa(e){return e===`off`||e===`recording`||e===`refused`||e===`failing`||e===`unknown`}function ca(e){if(!ra(e))return null;let t=Q(e,`deviceId`),n=e.state,r=Q(e,`gapsSinceArmed`),i=ia(e,`segmentsHeld`),a=ia(e,`bytesLastHour`),o=ia(e,`bytesHeld`);if(t===null||!sa(n)||r===null||i===void 0||a===void 0||o===void 0)return null;let s=$(e,`reason`),c=Q(e,`segmentOriginMs`),l=Q(e,`framesPerMin`),u=Q(e,`heldFromMs`),d=Q(e,`heldToMs`),f=$(e,`shelfError`);return{deviceId:t,state:n,gapsSinceArmed:r,segmentsHeld:i,bytesLastHour:a,bytesHeld:o,...s===null?{}:{reason:s},...c===null?{}:{segmentOriginMs:c},...l===null?{}:{framesPerMin:l},...u===null?{}:{heldFromMs:u},...d===null?{}:{heldToMs:d},...f===null?{}:{shelfError:f}}}function la(e){return ra(e)?oa(e.cameras,ca):null}function ua(e){if(!ra(e))return null;let t=$(e,`id`),n=Q(e,`deviceId`),r=$(e,`scenario`),i=e.lighting,a=Q(e,`fromMs`),o=Q(e,`toMs`),s=e.state,c=Q(e,`frames`),l=Q(e,`gaps`),u=Q(e,`bytes`),d=aa(e,`reviewed`),f=aa(e,`released`),p=oa(e.tracks,e=>typeof e==`string`?e:null),m=Q(e,`tracksStillStored`);return t===null||n===null||r===null||i!==`day`&&i!==`ir`||a===null||o===null||s!==`complete`&&s!==`incomplete`||c===null||l===null||u===null||d===null||f===null||p===null||m===null?null:{id:t,deviceId:n,scenario:r,note:$(e,`note`),lighting:i,fromMs:a,toMs:o,state:s,frames:c,gaps:l,bytes:u,reviewed:d,released:f,tracks:p,tracksStillStored:m}}function da(e){return ra(e)?oa(e.tapes,ua):null}function fa(e){if(!ra(e))return null;let t=$(e,`trackId`),n=Q(e,`firstT`),r=Q(e,`lastT`),i=Q(e,`boundFrames`),a=$(e,`cls`),o=aa(e,`stillStored`);return t===null||n===null||r===null||i===null||a===null||o===null?null:{trackId:t,firstT:n,lastT:r,boundFrames:i,cls:a,stillStored:o}}function pa(e){if(!ra(e))return null;let t=$(e,`tapeId`),n=Q(e,`deviceId`),r=Q(e,`fromMs`),i=Q(e,`toMs`),a=aa(e,`reviewed`),o=oa(e.lanes,fa);return t===null||n===null||r===null||i===null||a===null||o===null?null:{tapeId:t,deviceId:n,fromMs:r,toMs:i,reviewed:a,lanes:o}}function ma(e){if(!ra(e))return null;if(e.ok===!1){let t=$(e,`reason`),n=$(e,`detail`);return t===null||n===null?null:{ok:!1,reason:t,detail:n}}if(e.ok!==!0)return null;let t=$(e,`tapeId`),n=e.state,r=Q(e,`frames`),i=Q(e,`gaps`),a=Q(e,`pinnedTracks`),o=Q(e,`bytes`);return t===null||n!==`complete`&&n!==`incomplete`||r===null||i===null||a===null||o===null?null:{ok:!0,tapeId:t,state:n,frames:r,gaps:i,pinnedTracks:a,bytes:o}}function ha(e){if(!ra(e))return null;let t=e.status;if(t===`released`){let n=Q(e,`unpinned`),r=aa(e,`pinsSettled`);return n===null||r===null?null:{status:t,unpinned:n,pinsSettled:r}}if(t===`already-released`||t===`not-found`)return{status:t};if(t===`unavailable`){let n=$(e,`reason`);return n===null?null:{status:t,reason:n}}return null}function ga(e){if(!ra(e))return null;let t=e.status;if(t===`deleted`||t===`pins-owed`||t===`not-found`)return{status:t};if(t===`unavailable`){let n=$(e,`reason`);return n===null?null:{status:t,reason:n}}return null}function _a(e){switch(e.status){case`released`:case`deleted`:return null;case`already-released`:return X.t(`helpers.eventsDebugTapes.alreadyReleased`);case`not-found`:return X.t(`helpers.eventsDebugTapes.notFound`);case`pins-owed`:return X.t(`helpers.eventsDebugTapes.pinsOwed`);case`unavailable`:return X.t(`helpers.eventsDebugTapes.unavailable`,{reason:e.reason})}}function va(e){if(!ra(e))return null;let t=$(e,`leftTrackId`),n=$(e,`rightTrackId`),r=e.relation,i=e.presence;return t===null||n===null||r!==`same-subject`&&r!==`different-subjects`?null:{leftTrackId:t,rightTrackId:n,relation:r,presence:i===`continuous`?`continuous`:null}}function ya(e){if(!ra(e))return null;let t=$(e,`sourceTrackId`),n=e.purity;return t===null||n!==`mixed`&&n!==`not-a-subject`?null:{sourceTrackId:t,purity:n,switchAtMs:Q(e,`switchAtMs`)}}function ba(e){if(!ra(e))return null;let t=oa(e.relations,va),n=oa(e.purities,ya),r=aa(e,`truncated`);return t===null||n===null||r===null?null:{relations:t,purities:n,truncated:r}}function xa(e){if(!e.truncated)return null;let t=e.relations.length+e.purities.length;return X.t(`helpers.eventsDebugTapes.truncatedMarks`,{count:t})}function Sa(e){return e.filter(e=>e.segmentsHeld===null||e.segmentsHeld>0).map(e=>({deviceId:e.deviceId,segmentsUnknown:e.segmentsHeld===null}))}function Ca(e){return e.slice(1).map((t,n)=>({trackId:e[n]??t,otherTrackId:t}))}function wa(e){return e.flatMap((t,n)=>e.slice(n+1).map(e=>({trackId:t,otherTrackId:e})))}function Ta(e,t){let n=[];for(let r of t.relations){let t=r.leftTrackId===e?r.rightTrackId:r.rightTrackId===e?r.leftTrackId:null;if(t===null)continue;let i=r.relation===`same-subject`?`same as`:`different from`;n.push(`${i} ${t}${r.presence===`continuous`?` (continuous)`:``}`)}for(let r of t.purities)r.sourceTrackId===e&&n.push(r.purity===`not-a-subject`?`not a subject`:r.switchAtMs===null?`mixed`:`mixed at switch`);return n}function Ea(e){switch(e.state){case`off`:return X.t(`helpers.eventsDebugTapes.statusOff`);case`recording`:return X.t(`helpers.eventsDebugTapes.statusRecording`);case`refused`:return X.t(`helpers.eventsDebugTapes.statusRefused`,{reason:e.reason??X.t(`helpers.eventsDebugTapes.unknownReason`)});case`failing`:return X.t(`helpers.eventsDebugTapes.statusFailing`,{reason:e.reason??X.t(`helpers.eventsDebugTapes.unknownReason`)});case`unknown`:return X.t(`helpers.eventsDebugTapes.statusUnknown`,{reason:e.reason??X.t(`helpers.eventsDebugTapes.unknownReason`)})}}var Da={"window-too-long":`A promoted window is at most 30 minutes.`,"window-in-future":`The window ends in the future.`,"window-not-recorded":`No segment covers that window — the camera was not recording then, or it is older than 24 h.`,"invalid-scenario":`The scenario must be a slug: lowercase letters, digits and dashes, 3–64 characters.`,"promotion-budget":`A promotion budget is full (60 tapes, 1 GiB, 3 000 pinned tracks). Release or delete a tape already committed as a case first.`,"empty-window":`No frame was recorded in that window.`,"shelf-unreadable":`The camera's recorded segments could not be listed, so the window cannot be proven whole.`,"not-post-processing-node":`This node does not post-process frames, so it records no tracking tapes.`,"artifacts-elsewhere":`The artifacts storage location is on another node; tapes are recorded only where it lives.`,"tapes-not-started":`The tape recorder has not started on this node (or failed to).`};function Oa(e,t){let n=Da[e]??`Refused (${e}).`;return t.length>0?`${n} ${t}`:n}function ka(e){if(e.length===0)return null;let t=new Date(e).getTime();return Number.isFinite(t)?t:null}function Aa(e){return e<1024*1024?X.t(`helpers.eventsDebugTapes.sizeKb`,{value:(e/1024).toFixed(0)}):X.t(`helpers.eventsDebugTapes.sizeMb`,{value:(e/1024/1024).toFixed(1)})}function ja(e){return e===null?`unknown`:Aa(e)}function Ma(e){return e===null?`unknown`:String(e)}function Na(e,t){let n=t.trim();return e===404?X.t(`helpers.eventsDebugTapes.exportUnknown`):e===503?n.length>0?n:X.t(`helpers.eventsDebugTapes.tapesUnavailable`):e===500?n.length>0?n:X.t(`helpers.eventsDebugTapes.exportUnreadable`):X.t(`helpers.eventsDebugTapes.downloadFailed`,{status:e})}l();function Pa({cameras:t,call:n,onPromoted:r}){let{t:i}=Z(),[o,c]=s(``),[l,u]=s(``),[d,f]=s(``),[p,m]=s(``),[h,_]=s(``),[v,y]=s(`auto`),[b,x]=s(!1),[S,C]=s(null),w=async()=>{let e=Number.parseInt(o===``?t[0]?.value??``:o,10),i=ka(l),a=ka(d);if(!Number.isFinite(e)||i===null||a===null){C(`Pick a camera and both ends of the window.`);return}x(!0),C(null);try{let t=ma(await n(Xi.promote,{deviceId:e,fromMs:i,toMs:a,scenario:p,...h.trim().length>0?{note:h.trim()}:{},...v===`day`||v===`ir`?{lighting:v}:{}}));t===null?C(ta):t.ok?(C(`Promoted ${t.tapeId}: ${String(t.frames)} frames, ${Aa(t.bytes)}, ${String(t.pinnedTracks)} tracks pinned`+(t.state===`incomplete`?` — incomplete (it has gaps) and cannot become a case.`:`.`)),r()):C(Oa(t.reason,t.detail))}catch(e){C(na(e))}finally{x(!1)}};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border px-3 py-2`,children:[a(`div`,{className:`w-40`,children:a(I,{value:o,options:[...t],onChange:e=>c(e.target.value),"aria-label":i(`eventsDebugTapesPromoteForm.camera`,`Camera`)})}),a(J,{type:`datetime-local`,"aria-label":i(`eventsDebugTapesPromoteForm.from`,`From`),value:l,onChange:e=>u(e.target.value),className:`w-48`}),a(J,{type:`datetime-local`,"aria-label":i(`eventsDebugTapesPromoteForm.to`,`To`),value:d,onChange:e=>f(e.target.value),className:`w-48`}),a(J,{"aria-label":i(`eventsDebugTapesPromoteForm.scenario`,`Scenario`),placeholder:`101-door-groups`,value:p,onChange:e=>m(e.target.value),className:`w-44`}),a(J,{"aria-label":i(`eventsDebugTapesPromoteForm.note`,`Note`),placeholder:i(`eventsDebugTapesPromoteForm.optionalNote`,`optional note`),value:h,onChange:e=>_(e.target.value),className:`w-52`}),a(`div`,{className:`w-28`,children:a(I,{value:v,"aria-label":i(`eventsDebugTapesPromoteForm.lighting`,`Lighting`),options:[{value:`auto`,label:i(`eventsDebugTapesPromoteForm.lightingAuto`,`Lighting: auto`)},{value:`day`,label:i(`eventsDebugTapes.dayMode`)},{value:`ir`,label:`IR`}],onChange:e=>y(e.target.value)})}),e(Y,{onClick:()=>void w(),disabled:b||t.length===0,children:[b?a(g,{className:`h-3.5 w-3.5 animate-spin`}):null,` `,i(`eventsDebugTapes.promoteWindow`)]}),a(`p`,{className:`w-full text-xs text-foreground-subtle`,children:i(`eventsDebugTapesPromoteForm.aPromotedTapeMayBe`,`A promoted tape may be shared as a test case — keep the scenario slug and note free of names or other personal data.`)}),S!==null&&a(`p`,{className:`w-full text-xs text-foreground`,children:S})]})}var Fa=`pipeline-analytics`,Ia=`debug.listTracks`,La=`debug.analyze`,Ra=C(`/addon/pipeline-analytics/debug-export`);function za(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ba(e,t){let n=e[t];return typeof n==`string`?n:null}function Va(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Ha(e,t){let n=e[t];return typeof n==`boolean`?n:null}function Ua(e){return e===`error`||e===`warn`||e===`info`}function Wa(e){if(!za(e))return null;let t=Ba(e,`code`),n=Ba(e,`detail`),r=e.severity;return t===null||n===null||!Ua(r)?null:{code:t,severity:r,detail:n}}function Ga(e){if(!za(e))return null;let t=Ba(e,`trackId`),n=Va(e,`deviceId`),r=Ba(e,`className`),i=Va(e,`firstSeen`),a=Va(e,`lastSeen`),o=Va(e,`durationMs`),s=Ha(e,`active`);if(t===null||n===null||r===null||i===null||a===null||o===null||s===null)return null;let c=Ba(e,`label`),l=Ba(e,`subLabel`),u=Ba(e,`previewMissReason`),d=Ha(e,`markForTrain`),f=Ha(e,`favourited`);return{trackId:t,deviceId:n,className:r,...c===null?{}:{label:c},...l===null?{}:{subLabel:l},firstSeen:i,lastSeen:a,durationMs:o,active:s,timestamp:i,windowMs:o,importance:Va(e,`importance`)??0,bestEventId:Ba(e,`bestEventId`)??``,...d===null?{}:{markForTrain:d},...f===null?{}:{favourited:f},debug:!0,...u===null||u.length===0?{}:{previewMissReason:u}}}function Ka(e){let t=Ga(e);if(t===null||!za(e))return null;let n=Va(e,`mediaCount`),r=Va(e,`eventCount`),i=Va(e,`positionCount`);if(n===null||r===null||i===null)return null;let a=e.mediaKinds,o=e.findings;if(!Array.isArray(a)||!Array.isArray(o))return null;let s=a.filter(e=>typeof e==`string`),c=[];for(let e of o){let t=Wa(e);t!==null&&c.push(t)}let l=e.thumbnailProvenance;return{...t,mediaCount:n,mediaKinds:s,eventCount:r,positionCount:i,findings:c,...ii(l)?{thumbnailProvenance:l}:{}}}function qa(e){if(!za(e))return null;let t=Ha(e,`truncated`),n=e.tracks;if(t===null||!Array.isArray(n))return null;let r=[];for(let e of n){let t=Ga(e);if(t===null)return null;r.push(t)}return{tracks:r,truncated:t}}function Ja(e){if(!za(e))return null;let t=e.reports,n=e.vanished;if(!Array.isArray(t)||!Array.isArray(n))return null;let r=[];for(let e of t){let t=Ka(e);if(t===null)return null;r.push(t)}return{reports:r,vanished:n.filter(e=>typeof e==`string`)}}var Ya={MEDIA_EVICTED_OR_NEVER:`no media`,MISSING_KEYFRAME:`no keyframe`,MISSING_FIRSTFRAME:`no first frame`,MISSING_LASTFRAME:`no last frame`,MISSING_THUMBNAIL:`no thumbnail`,MISSING_BEST_CROP:`no crop`,SHORT_TRACK:`very short`,ZERO_EVENTS:`no events`,ZERO_POSITIONS:`no trajectory`,NO_PERIODIC_SNAPSHOTS:`no snapshots`,LASTFRAME_STALE:`stale last frame`,MEDIA_STOPPED_EARLY:`media stopped early`,NO_BEST_EVENT:`no best event`,LOW_BEST_SCORE:`low score`,UNSCORED_LABEL:`unscored label`,BEST_SHOT_STANDIN:`stand-in best shot`,BEST_SHOT_RASTER:`low-res best shot`};function Xa(e){return Ya[e]??e}var Za={error:0,warn:1,info:2};function Qa(e){return e.toSorted((e,t)=>Za[e.severity]-Za[t.severity]||e.code.localeCompare(t.code))}function $a(e){return e.length===0?Ra:`${Ra}?deviceIds=${e.join(`,`)}`}function eo(e){if(e<1e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.round(e/1e3);if(t<60)return`${String(t)}s`;let n=Math.floor(t/60);return`${String(n)}m ${String(t%60).padStart(2,`0`)}s`}function to(e,t){return`${String(e)}:${t}`}function no(e,t){let n=[],r=new Set;for(let i of e){let e=to(i.deviceId,i.trackId);!t.has(e)||r.has(e)||(r.add(e),n.push({deviceId:i.deviceId,trackId:i.trackId}))}return n}l();function ro({tapeId:t,call:n,onClose:r,onChanged:i}){let{t:o}=Z(),l=c({queryKey:[`events-debug`,`tapes`,`tracks`,t],queryFn:async()=>pa(await n(Xi.tracks,{tapeId:t}))}),u=l.data??null,d=c({queryKey:[`events-debug`,`tapes`,`marks`,t],enabled:u!==null,queryFn:async()=>u===null?null:ba(await n(Zi.list,{deviceId:u.deviceId,since:u.fromMs-$i,until:u.toMs+$i,limit:5e3}))}),[f,p]=s([]),[m,h]=s(``),[g,_]=s(null),v=e=>p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),y=async e=>{_(null);try{for(let[t,r]of e)await n(t,r);p([]),await d.refetch(),i()}catch(e){_(na(e))}};if(u===null)return l.isLoading?a(`p`,{className:`text-xs`,children:o(`eventsDebugTapesReview.loadingTheTape`,`Loading the tape…`)}):a(_t,{message:ta});let b=u.deviceId,x=(e,t)=>y(e.map(e=>[Zi.setRelation,{deviceId:b,...e,relation:t}])),S=e=>{let t=Number.parseFloat(m),n=e===`mixed`&&Number.isFinite(t)?u.fromMs+t*1e3:void 0;return y(f.map(t=>[Zi.setPurity,{deviceId:b,trackId:t,purity:e,...n===void 0?{}:{switchAtMs:Math.round(n)}}]))},C=d.data==null?null:xa(d.data);return e(`div`,{className:`space-y-2 rounded-md border border-primary/40 px-3 py-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[a(`span`,{className:`text-xs font-medium`,children:o(`eventsDebugTapes.reviewLanes`,{id:u.tapeId,count:u.lanes.length})}),a(Y,{disabled:f.length<2,onClick:()=>void x(Ca(f),`same-subject`),children:o(`eventsDebugTapesReview.sameSubject`,`Same subject`)}),a(Y,{variant:`secondary`,disabled:f.length<2,onClick:()=>void x(wa(f),`different-subjects`),children:o(`eventsDebugTapesReview.differentSubjects`,`Different subjects`)}),a(J,{"aria-label":o(`eventsDebugTapesReview.changedAtSFromTape`,`Changed at (s from tape start)`),placeholder:o(`eventsDebugTapesReview.changedAtS`,`changed at s`),value:m,onChange:e=>h(e.target.value),className:`w-28`}),a(Y,{variant:`secondary`,disabled:f.length!==1,onClick:()=>void S(`mixed`),children:o(`eventsDebugTapesReview.mixed`,`Mixed`)}),a(Y,{variant:`secondary`,disabled:f.length===0,onClick:()=>void S(`not-a-subject`),children:o(`eventsDebugTapesReview.notASubject`,`Not a subject`)}),a(Y,{variant:u.reviewed?`secondary`:`primary`,onClick:()=>void y([[Xi.review,{tapeId:u.tapeId,reviewed:!u.reviewed}]]).then(()=>l.refetch()),children:u.reviewed?o(`eventsDebugTapesReview.markNotReviewed`,`Mark not reviewed`):o(`eventsDebugTapesReview.markReviewed`,`Mark reviewed`)}),a(Y,{variant:`ghost`,onClick:r,children:o(`common.close`,`Close`)})]}),g!==null&&a(_t,{message:g}),C!==null&&a(_t,{variant:`warning`,message:C}),a(`ul`,{className:`space-y-1`,children:u.lanes.toSorted((e,t)=>e.firstT-t.firstT).map(e=>a(io,{lane:e,marks:d.data===null||d.data===void 0?[]:Ta(e.trackId,d.data),selected:f.includes(e.trackId),onToggle:()=>v(e.trackId)},e.trackId))})]})}function io({lane:t,marks:n,selected:r,onToggle:i}){let{t:o}=Z(),{src:s}=Gt(t.stillStored?Kt(`track`,t.trackId):void 0);return e(`li`,{className:`flex items-center gap-2 text-xs`,children:[a(T,{"aria-label":o(`eventsDebugTapesReview.select`,`select {{trackId}}`,{trackId:t.trackId}),checked:r,onChange:i}),s===null?a(`div`,{className:`h-10 w-10 rounded bg-surface-hover`}):a(`img`,{src:s,alt:t.trackId,className:`h-10 w-10 rounded object-cover`}),a(`span`,{className:`font-mono`,children:t.trackId}),a(`span`,{children:t.cls}),a(`span`,{className:`text-foreground-subtle`,children:o(`eventsDebugTapes.laneFrames`,{range:`${eo(t.firstT)} → ${eo(t.lastT)}`,count:t.boundFrames})}),!t.stillStored&&a(`span`,{className:`text-foreground-subtle`,children:o(`eventsDebugTapesReview.notStoredMarkedThroughThe`,`not stored — marked through the tape`)}),n.map(e=>a(Ct,{variant:`info`,children:e},e))]})}l();var ao=`camstack_admin_token`;function oo(){let e=oe();return(t,n)=>e.trpcClient.addons.custom.mutate({addonId:Fa,action:t,input:n})}async function so(e,t){let n=localStorage.getItem(ao),r={};n!==null&&(r.Authorization=`Bearer ${n}`);let i=await fetch(ea(e),{headers:r});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(Na(i.status,e))}let a=await i.blob(),o=i.headers.get(`content-disposition`),s=(o===null?null:/filename="?([^";]+)"?/i.exec(o))?.[1]?.trim()??t,c=URL.createObjectURL(a),l=document.createElement(`a`);l.href=c,l.download=s,l.click(),setTimeout(()=>URL.revokeObjectURL(c),6e4)}function co(){let{t:e}=Z(),[t,n]=s(!1);return a(bt,{expanded:t,onExpandedChange:n,header:a(`span`,{className:`text-sm font-medium text-foreground`,children:e(`eventsDebugTapes.trackingTapes`,`Tracking tapes`)}),children:a(lo,{})})}function lo(){let{t}=Z(),r=oo(),i=Ve({isCamera:!0,projection:`slim`}),o=n(()=>{let e=new Map;for(let t of i.data??[])e.set(t.id,t.name);return n=>e.get(n)??t(`cameraLoad.deviceLabel`,{deviceId:n})},[i.data,t]),l=c({queryKey:[`events-debug`,`tapes`,`status`],queryFn:async()=>la(await r(Xi.status,{}))}),u=c({queryKey:[`events-debug`,`tapes`,`list`],queryFn:async()=>da(await r(Xi.list,{}))}),[d,f]=s(null),[p,m]=s(null),h=async e=>{m(null);try{await so(e.id,`${e.scenario}.tape-bundle.json.gz`)}catch(e){m(na(e))}},g=async e=>{let t=ha(await r(Xi.release,{tapeId:e.id}));if(t===null)throw Error(ta);let n=_a(t);if(n!==null)throw Error(n);await u.refetch()},_=async e=>{let t=ga(await r(Xi.remove,{tapeId:e.id}));if(t===null)throw Error(ta);let n=_a(t);if(n!==null)throw Error(n);await u.refetch()};return e(`div`,{className:`space-y-3`,children:[a(`p`,{className:`text-xs text-foreground-subtle`,children:a(Vt,{i18nKey:`eventsDebugTapes.intro`,components:{b:a(`strong`,{}),code:a(`code`,{})}})}),p!==null&&a(_t,{message:p}),l.isLoading&&a(`p`,{className:`text-xs text-foreground-subtle`,children:t(`eventsDebugTapes.loadingCameraStatus`,`Loading camera status…`)}),l.data===null&&a(_t,{message:`The server answered in a shape this build does not understand.`}),e(`table`,{className:`w-full text-xs`,children:[a(`thead`,{children:e(`tr`,{className:`text-left text-foreground-subtle`,children:[a(`th`,{children:t(`eventsDebugTapes.camera`,`Camera`)}),a(`th`,{children:t(`eventsDebugTapes.state`,`State`)}),a(`th`,{children:t(`eventsDebugTapes.framesMin`,`Frames/min`)}),a(`th`,{children:t(`eventsDebugTapes.lastHour`,`Last hour`)}),a(`th`,{children:t(`eventsDebugTapes.held`,`Held`)}),a(`th`,{children:t(`eventsDebugTapes.gaps`,`Gaps`)})]})}),a(`tbody`,{children:(l.data??[]).map(n=>e(`tr`,{children:[a(`td`,{children:o(n.deviceId)}),a(`td`,{children:a(Ct,{variant:n.state===`recording`?`success`:n.state===`off`?`default`:n.state===`unknown`?`warning`:`danger`,children:Ea(n)})}),a(`td`,{children:n.framesPerMin===void 0?`—`:String(Math.round(n.framesPerMin))}),a(`td`,{title:n.shelfError,children:ja(n.bytesLastHour)}),a(`td`,{title:n.shelfError,children:t(`eventsDebugTapes.segsHeld`,{count:Ma(n.segmentsHeld),size:ja(n.bytesHeld)})}),a(`td`,{children:String(n.gapsSinceArmed)})]},n.deviceId))})]}),a(Pa,{cameras:Sa(l.data??[]).map(e=>({value:String(e.deviceId),label:e.segmentsUnknown?t(`eventsDebugTapes.segmentsUnknown`,`{{value1}} (segments unknown)`,{value1:o(e.deviceId)}):o(e.deviceId)})),call:r,onPromoted:()=>void u.refetch()}),u.isLoading&&a(`p`,{className:`text-xs text-foreground-subtle`,children:t(`eventsDebugTapes.loadingPromotedTapes`,`Loading promoted tapes…`)}),u.data===null&&a(_t,{message:`The server answered in a shape this build does not understand.`}),e(`table`,{className:`w-full text-xs`,children:[a(`thead`,{children:e(`tr`,{className:`text-left text-foreground-subtle`,children:[a(`th`,{children:t(`eventsDebugTapes.scenario`,`Scenario`)}),a(`th`,{children:t(`eventsDebugTapes.camera`,`Camera`)}),a(`th`,{children:t(`eventsDebugTapes.window`,`Window`)}),a(`th`,{children:t(`eventsDebugTapes.state`,`State`)}),a(`th`,{children:t(`eventsDebugTapes.tracks`,`Tracks`)}),a(`th`,{})]})}),a(`tbody`,{children:(u.data??[]).map(n=>e(`tr`,{children:[a(`td`,{children:n.scenario}),a(`td`,{children:o(n.deviceId)}),e(`td`,{children:[new Date(n.fromMs).toLocaleString(),` · `,eo(n.toMs-n.fromMs),` `,`· `,n.lighting]}),e(`td`,{children:[a(Ct,{variant:n.state===`complete`?`success`:`warning`,children:n.state}),` `,n.reviewed&&a(Ct,{variant:`info`,children:t(`eventsDebugTapes.reviewed`)}),` `,n.released&&a(Ct,{children:t(`eventsDebugTapes.released`)})]}),a(`td`,{children:t(`eventsDebugTapes.storedOf`,{stored:String(n.tracksStillStored),total:String(n.tracks.length)})}),e(`td`,{className:`space-x-1 text-right`,children:[a(Y,{variant:`secondary`,"aria-label":t(`eventsDebugTapes.review`,`Review {{scenario}}`,{scenario:n.scenario}),onClick:()=>f(n.id),children:t(`eventsDebugTapes.review2`,`Review`)}),a(Y,{variant:`ghost`,"aria-label":t(`eventsDebugTapes.download`,`Download {{scenario}}`,{scenario:n.scenario}),onClick:()=>void h(n),children:a(se,{className:`h-3.5 w-3.5`})}),a(ke,{label:t(`eventsDebugTapes.release`,`Release`),icon:S,title:t(`eventsDebugTapes.release2`,`Release {{scenario}}?`,{scenario:n.scenario}),description:t(`eventsDebugTapes.releasingReturnsThisTapeS`,`Releasing returns this tape's pinned tracks to ordinary retention — they can be pruned from then on. The promoted bundle itself is kept until deleted.`),confirmLabel:t(`eventsDebugTapes.release`,`Release`),triggerVariant:`ghost`,confirmVariant:`danger`,disabled:n.released,action:()=>g(n)}),a(ke,{label:t(`common.delete`,`Delete`),icon:R,title:t(`eventsDebugTapes.delete`,`Delete {{scenario}}?`,{scenario:n.scenario}),description:t(`eventsDebugTapes.deletingRemovesThePromotedBundle`,`Deleting removes the promoted bundle and its index row for good. Its tracks' pins are released first — this cannot be undone.`),confirmLabel:t(`common.delete`,`Delete`),triggerVariant:`ghost`,confirmVariant:`danger`,action:()=>_(n)})]})]},n.id))})]}),d!==null&&a(ro,{tapeId:d,call:r,onClose:()=>f(null),onChanged:()=>void u.refetch()})]})}l();var uo=`all`,fo=`The server answered in a shape this build does not understand.`,po={error:`danger`,warn:`warning`,info:`info`};function mo({findings:e}){let{t}=Z();return e.length===0?a(Ct,{variant:`success`,children:t(`eventsDebug.noAnomalyFound`,`no anomaly found`)}):a(`div`,{className:`flex flex-wrap gap-1`,children:Qa(e).map(e=>a(Ct,{variant:po[e.severity],title:e.detail,children:Xa(e.code)},e.code))})}function ho({track:t,report:n,analyzing:r}){let{t:i}=Z(),o=ci(n?.previewMissReason??t.previewMissReason);return e(`div`,{className:`space-y-1 border-t border-border pt-1.5`,children:[n===void 0?a(`span`,{className:`text-[10px] text-foreground-subtle`,children:r?i(`eventsDebug.analysing`,`analysing…`):i(`eventsDebug.notAnalysed`,`not analysed`)}):e(d,{children:[a(mo,{findings:n.findings}),a(`p`,{className:`text-[10px] text-foreground-subtle`,title:n.mediaKinds.length>0?n.mediaKinds.join(`, `):i(`eventsDebug.noMediaOfAnyKind`,`no media of any kind`),children:i(`eventsDebug.reportCounts`,{media:String(n.mediaCount),events:String(n.eventCount),positions:String(n.positionCount)})})]}),o!==null&&a(`p`,{className:`text-[10px] text-foreground-subtle`,title:o.raw,children:o.sentence})]})}function go(){let{t}=Z(),r=oe(),[i,o]=s(uo),[l,u]=s(!1),[d,f]=s(null),[p,m]=s(new Set),[h,_]=s(null),[y,b]=s(null),[S,C]=s(null),[w,T]=s([]),E=Ei(),D=Ve({isCamera:!0,projection:`slim`}),O=n(()=>[{value:uo,label:t(`eventsDebug.allCameras`,`All cameras`)},...(D.data??[]).map(e=>({value:String(e.id),label:e.name}))],[D.data,t]),k=n(()=>{let e=new Map;for(let t of D.data??[])e.set(t.id,t.name);return e},[D.data]),A=e=>k.get(e)??t(`eventsDebug.cameraFallback`,{deviceId:e}),j=n(()=>i===uo?[]:[Number.parseInt(i,10)],[i]),M=c({queryKey:[`events-debug`,`list`,j],queryFn:async()=>qa(await r.trpcClient.addons.custom.mutate({addonId:Fa,action:Ia,input:j.length===0?{}:{deviceIds:j}}))}),N=n(()=>(M.data?.tracks??[]).map(e=>e.trackId),[M.data]),P=c({queryKey:[`events-debug`,`analyze`,N],enabled:N.length>0,queryFn:async()=>Ja(await r.trpcClient.addons.custom.mutate({addonId:Fa,action:La,input:{trackIds:N}}))}),F=n(()=>{let e=new Map;for(let t of P.data?.reports??[])e.set(t.trackId,t);return e},[P.data]),R=M.data?.tracks??[],z=M.data===null||P.data===null,V=()=>{M.refetch(),P.refetch()},ee=e=>{m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},H=()=>{m(new Set(R.map(e=>to(e.deviceId,e.trackId))))},U=()=>m(new Set),te=async(e,t)=>{let n=e===`analyzed`?{debug:!1}:{favourited:!0},r=0,i=[];for(let e of t)try{await E.mutateAsync({deviceId:e.deviceId,trackId:e.trackId,flags:n}),r+=1}catch{i.push(e.trackId)}return{applied:r,refused:i}},W=e=>{if(!Ci||y!==null)return;let t=no(R,p);t.length!==0&&(b(e),C(null),(async()=>{let n=await te(e,t);b(null);let r=new Set(n.refused);m(new Set(t.filter(e=>r.has(e.trackId)).map(e=>to(e.deviceId,e.trackId)))),e===`analyzed`&&T(t.filter(e=>!r.has(e.trackId))),n.refused.length>0&&C(`${String(n.refused.length)} of ${String(t.length)} were refused by the server and are still selected. Check the hub log.`),M.refetch()})())},ne=()=>{let e=w;e.length===0||y!==null||(b(`analyzed`),C(null),(async()=>{for(let t of e)try{await E.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,flags:{debug:!0}})}catch{C(`Some tracks could not be re-marked. Refresh and try again.`)}b(null),T([]),M.refetch()})())},re=async()=>{u(!0),f(null);try{await Yt($a(j),`camstack-debug.zip`)}catch(e){f(e instanceof Error?e.message:`Export failed.`)}finally{u(!1)}},G=y!==null;return e(`section`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(`div`,{className:`w-44`,children:a(I,{value:i,options:O,onChange:e=>o(e.target.value)})}),e(Y,{variant:`secondary`,onClick:V,disabled:M.isFetching,children:[M.isFetching?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(v,{className:`h-3.5 w-3.5`}),t(`common.refresh`,`Refresh`)]}),e(Y,{onClick:()=>void re(),disabled:l||R.length===0,children:[l?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(se,{className:`h-3.5 w-3.5`}),t(`eventsDebug.exportAll`,{count:String(R.length)})]}),R.length>0&&p.size<R.length&&a(Y,{variant:`ghost`,onClick:H,children:t(`eventsDebug.selectAll`,`Select all`)})]}),a(`p`,{className:`text-xs text-foreground-subtle`,children:a(Vt,{i18nKey:`eventsDebug.debugMarkNote`,components:{code:a(`code`,{}),strong:a(`strong`,{})}})}),a(co,{}),M.isError&&a(_t,{message:t(`eventsDebug.couldNotLoadTheMarked`,`Could not load the marked tracks.`)}),z&&!M.isError&&a(_t,{message:fo}),d!==null&&a(_t,{message:d}),S!==null&&a(_t,{message:S}),M.data?.truncated===!0&&a(_t,{message:t(`eventsDebug.aCameraFilledThePer`,`A camera filled the per-camera cap — some marked tracks are not listed. Un-mark a few, or filter to one camera.`)}),(P.data?.vanished.length??0)>0&&a(`p`,{className:`text-xs text-foreground-subtle`,children:t(`eventsDebug.vanished`,{count:String(P.data?.vanished.length)})}),p.size>0&&e(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[a(`span`,{className:`text-xs font-medium text-foreground`,children:t(`common.selectedCount`,{count:p.size})}),e(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[a(`span`,{title:Ci?void 0:`Track flags arrive with the next server update`,children:e(Y,{variant:`secondary`,onClick:()=>W(`keep`),disabled:!Ci||G,children:[y===`keep`?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(B,{className:`h-3.5 w-3.5`}),` `,t(`eventsDebug.keep`,`Keep`)]})}),a(`span`,{title:Ci?void 0:`Track flags arrive with the next server update`,children:e(Y,{onClick:()=>W(`analyzed`),disabled:!Ci||G,children:[y===`analyzed`?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(L,{className:`h-3.5 w-3.5`}),` `,t(`eventsDebug.analyzed`,`Analyzed`)]})}),a(Y,{variant:`ghost`,onClick:U,disabled:G,children:a(q,{className:`h-3.5 w-3.5`})})]})]}),w.length>0&&e(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-border bg-surface px-3 py-2`,children:[a(`span`,{className:`text-xs text-foreground`,children:t(`eventsDebug.markedAnalyzed`,{count:String(w.length)})}),e(Y,{variant:`ghost`,onClick:ne,disabled:G,children:[a(x,{className:`h-3.5 w-3.5`}),` `,t(`eventsDebug.undo`)]}),a(Y,{variant:`ghost`,onClick:()=>T([]),disabled:G,children:a(q,{className:`h-3.5 w-3.5`})})]}),M.isLoading?a(we,{status:`pending`,pendingMessage:`Loading…`,testId:`debug-tracks-grid`}):R.length===0?a(nt,{icon:K,title:t(`eventsDebug.noTrackIsMarkedFor`,`No track is marked for debug`),description:t(`eventsDebug.markOneFromATrack`,`Mark one from a track's actions on the Feed to see it here.`)}):a(we,{status:`ready`,testId:`debug-tracks-grid`,children:R.map(e=>{let t=F.get(e.trackId);return a(ui,{row:e,cameraName:A(e.deviceId),nowMs:e.lastSeen,selected:p.has(to(e.deviceId,e.trackId)),onToggleSelect:ee,onOpenDetail:_,...t?.thumbnailProvenance===void 0?{}:{provenance:t.thumbnailProvenance},footer:a(ho,{track:e,report:t,analyzing:P.isFetching})},to(e.deviceId,e.trackId))})}),h&&a(Yi,{row:h,cameraName:A(h.deviceId),deleteAvailable:Li,onClose:()=>_(null),onDeleted:()=>{_(null),M.refetch()},onFlagsChanged:e=>{e.debug||(_(null),M.refetch())}})]})}var _o=200,vo=3e4,yo=[];function bo(e){let t=oe(),n=e.deviceIds.length>0,r=[...e.deviceIds].sort((e,t)=>e-t),{data:i,isLoading:a}=c({queryKey:[`events-feed`,r,e.since,e.until,e.minImportance??null,e.classFilter??null],enabled:n,staleTime:vo,refetchInterval:vo,queryFn:async()=>(await t.trpcClient.pipelineAnalytics.getKeyEventsBatch.query({deviceIds:r,since:e.since,until:e.until,limit:_o,...e.minImportance===void 0?{}:{minImportance:e.minImportance},...e.classFilter===void 0?{}:{classFilter:e.classFilter}})).map(e=>e.events.map(t=>({...t,deviceId:e.deviceId})))});return{rows:Qr(Zr(i??yo),`importance`),isLoading:n&&a}}l();var xo=[`events-feed`],So=2e3;function Co(e){let n=u(),r=e?.paused===!0,a=t(n);a.current=n;let c=t(r);c.current=r;let[l,d]=s(!1),f=i(()=>{a.current.invalidateQueries({queryKey:xo})},[]),p=t(void 0);p.current||=Wr({delayMs:So,invalidate:()=>{c.current?d(!0):f()}}),o(()=>()=>p.current?.cancel(),[]),o(()=>{r||!l||(d(!1),f())},[r,l,f]);let m=i(()=>{d(!1),f()},[f]);return Ue(ue.PipelineAnalyticsDetectionEvent,()=>{p.current?.trigger()}),Ue(ue.PipelineAnalyticsTrackEnded,()=>{p.current?.trigger()}),{pending:l,refreshNow:m}}l();function wo({groups:t,selected:r,onChange:i,loading:o=!1}){let{t:c}=Z(),l=jt(),[u,d]=s(!1),[f,p]=s(``),[m,h]=s(new Set),g=f.trim().toLowerCase(),_=e=>g.length===0||Xe(e,c).toLowerCase().includes(g),v=n(()=>t.map(e=>({macro:e.macro,subs:e.subs.filter(t=>_(t)||_(e.macro))})).filter(e=>_(e.macro)||e.subs.length>0),[t,g]),y=e=>h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),b=e=>{let t=new Set(r),n=r.has(e.macro.kind)&&e.subs.every(e=>r.has(e.kind)),a=[e.macro.kind,...e.subs.map(e=>e.kind)];if(n)for(let e of a)t.delete(e);else for(let e of a)t.add(e);i(t)},x=e=>{let t=new Set(r);t.has(e)?t.delete(e):t.add(e),i(t)},S=()=>i(new Set),C=r.size;return e(`div`,{className:`relative`,children:[e(Y,{variant:`unstyled`,type:`button`,onClick:()=>d(e=>!e),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${C>0?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[a(N,{className:`h-3.5 w-3.5`}),C>0?c(`detectionIntelligence.eventKindFilter.kinds`,`Kinds ({{value1}})`,{value1:String(C)}):c(`detectionIntelligence.eventKindFilter.kinds2`,`Kinds`),a(pe,{className:`h-3 w-3`})]}),u&&e(`div`,{className:`absolute z-20 mt-1 max-h-80 w-64 overflow-auto rounded-md border border-border bg-surface p-2 shadow-lg`,children:[e(`div`,{className:`mb-2 flex items-center gap-1 rounded border border-border px-1.5`,children:[a(le,{className:`h-3.5 w-3.5 text-foreground-subtle`}),a(J,{type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:c(`detectionIntelligence.eventKindFilter.searchKinds`,`Search kinds…`),className:`w-full bg-transparent py-1 text-xs outline-none`}),C>0&&a(Y,{variant:`unstyled`,type:`button`,onClick:S,className:`text-[10px] text-foreground-subtle hover:text-foreground`,children:c(`detectionIntelligence.eventKindFilter.clear`,`Clear`)})]}),v.length===0&&a(`div`,{className:`px-1 py-2 text-[11px] text-foreground-subtle`,children:o?c(`detectionIntelligence.eventKindFilter.loadingKinds`,`Loading kinds…`):g.length>0?c(`detectionIntelligence.eventKindFilter.noKindMatchesThatSearch`,`No kind matches that search.`):c(`detectionIntelligence.eventKindFilter.theseCamerasAdvertiseNoEvent`,`These cameras advertise no event kinds.`)}),v.map(t=>{let n=Ze(t.macro.iconId),i=m.has(t.macro.kind)||g.length>0,o=r.has(t.macro.kind);return e(`div`,{className:`mb-0.5`,children:[e(`div`,{className:`flex items-center gap-1`,children:[t.subs.length>0?a(Y,{variant:`unstyled`,type:`button`,onClick:()=>y(t.macro.kind),className:`text-foreground-subtle hover:text-foreground`,"aria-label":c(`detectionIntelligence.eventKindFilter.expand`,`Expand`),children:a(i?pe:w,{className:`h-3 w-3`})}):a(`span`,{className:`w-3`}),e(`label`,{className:`flex flex-1 cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[a(T,{checked:o,onChange:()=>b(t),className:`accent-primary`}),a(n,{className:`h-3.5 w-3.5`,style:{color:l(t.macro.kind)}}),a(`span`,{className:`font-medium`,children:Xe(t.macro,c)})]})]}),i&&t.subs.map(t=>{let n=Ze(t.iconId);return e(`label`,{className:`ml-5 flex cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[a(T,{checked:r.has(t.kind),onChange:()=>x(t.kind),className:`accent-primary`}),a(n,{className:`h-3.5 w-3.5`,style:{color:l(t.kind)}}),a(`span`,{children:Xe(t,c)})]},t.kind)})]},t.macro.kind)})]})]})}function To(e,t){let n=new Map;for(let r of e)if(!(t.size>0&&!t.has(r.deviceId)))for(let e of r.kinds)n.has(e.kind)||n.set(e.kind,e);return n}function Eo(e,t){return{...t,kind:e,labelKey:`eventKind.${e}`,label:e.charAt(0).toUpperCase()+e.slice(1),iconId:e,parentKind:null,level:`macro`}}var Do=new Set([`detection`,`package`]);function Oo(e,t){return[...To(e,t).values()].filter(e=>e.parentKind===null&&Do.has(e.category)).sort((e,t)=>e.label.localeCompare(t.label))}function ko(e,t){let n=To(e,t),r=new Map,i=new Map;for(let e of n.values()){if(e.parentKind===null){i.set(e.kind,e);continue}let t=r.get(e.parentKind);t===void 0?r.set(e.parentKind,[e]):t.push(e)}for(let[e,t]of r){if(i.has(e))continue;let n=t[0];n!==void 0&&i.set(e,Eo(e,n))}return[...i.values()].map(e=>({macro:e,subs:[...r.get(e.kind)??[]].sort((e,t)=>e.label.localeCompare(t.label))})).sort((e,t)=>e.macro.label.localeCompare(t.macro.label))}l();function Ao(){let[e,n]=s(!1),r=t(null),[a,c]=s(0),l=i(e=>{r.current!==e&&(r.current=e,c(e=>e+1))},[]);return o(()=>{let e=r.current;if(!e||typeof IntersectionObserver>`u`){n(!1);return}let t=new IntersectionObserver(e=>{let t=e[e.length-1];t&&n(!t.isIntersecting)},{rootMargin:`64px 0px 0px 0px`,threshold:0});return t.observe(e),()=>t.disconnect()},[a]),{ref:l,scrolledPast:e}}l();var jo=[`events-feed`],Mo=60,No=[{value:`importance`,labelKey:`detectionIntelligence.eventsSection.sortImportance`,icon:he},{value:`time`,labelKey:`detectionIntelligence.eventsSection.sortRecent`,icon:h}];function Po(){let{t}=Z(),r=u(),i=te(),c=P(),[l,f]=s(Hn),[p,m]=s(new Set),[h,v]=s(new Set),[y,b]=s(0),[x,S]=s(`time`),[C,w]=s(new Set),[T,E]=s(null),[D,k]=s(()=>Date.now());o(()=>{let e=setInterval(()=>k(Date.now()),6e4);return()=>clearInterval(e)},[]);let{since:A,until:j}=n(()=>ni({fromMs:l.fromMs,toMs:l.toMs},D),[l.fromMs,l.toMs,D]),M=Ao(),{pending:N,refreshNow:F}=Co({paused:T!==null||C.size>0||M.scrolledPast}),{data:I=[]}=Ve({isCamera:!0,projection:`slim`}),L=n(()=>I.map(e=>e.id),[I]),{data:z,isLoading:B}=Ne({deviceIds:L},{enabled:L.length>0,staleTime:5*6e4}),V=n(()=>ko(z??[],p),[z,p]),ee=Bi(),H=ee.isPending,{rows:U,isLoading:W}=bo({deviceIds:L,since:A,until:j,minImportance:y>0?y:void 0,classFilter:h.size===1?[...h][0]:void 0}),ne=n(()=>{let e=new Map;for(let t of I??[])e.set(t.id,t.name);return e},[I]),re=e=>ne.get(e)??t(`detectionIntelligence.cameraFallback`,{id:String(e)}),G=n(()=>Yn(U).map(e=>({id:e,name:re(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[U,ne]),K=n(()=>Qr($r(U,{cameras:p,classes:h,minImportance:y}),x),[U,p,h,y,x]),ie=ar(K,Mo,n(()=>JSON.stringify([[...p].sort((e,t)=>e-t),[...h].sort(),y,x,A,j]),[p,h,y,x,A,j])),ae=()=>{r.invalidateQueries({queryKey:jo})},oe=()=>w(new Set);function se(e){w(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function ce(){if(C.size===0||!Li)return;let e=ti(U,C),n=[...e.values()].reduce((e,t)=>e+t.length,0);n!==0&&(async()=>{await c({title:t(`detectionIntelligence.eventsSection.deleteTitle`,{count:n}),message:t(`detectionIntelligence.eventsSection.deleteMessage`,{count:n}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&le(e)})()}function le(e){let n=[...e];Promise.allSettled(n.map(([e,t])=>ee.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{ae();let r=[],a=new Set;if(e.forEach((e,t)=>{let i=n[t];if(!i)return;let[o,s]=i;if(e.status===`fulfilled`)for(let e of s)a.add(ei(o,e));else r.push(o)}),w(e=>{let t=new Set(e);for(let e of a)t.delete(e);return t}),r.length>0){let e=r.map(e=>re(e)).join(`, `);i({title:t(`detectionIntelligence.eventsSection.someTracksWereNotDeleted`,`Some tracks were not deleted`),message:t(`detectionIntelligence.eventsSection.failedToDeleteTracksOn`,`Failed to delete tracks on: {{names}}. They remain selected — retry, or check the server logs.`,{names:e}),variant:`danger`})}})}let ue=K.length!==U.length;return e(`div`,{className:`relative space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[a(pr,{onChange:f}),a(dr,{cameras:G,selected:p,onChange:m}),a(wo,{groups:V,selected:h,onChange:v,loading:B}),e(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[a(`span`,{children:t(`detectionIntelligence.eventsSection.minScore`,`Min score`)}),a(O,{min:0,max:1,step:.05,value:y,onChange:e=>b(Number(e.target.value)),className:`h-1 w-24 cursor-pointer accent-primary`,"aria-label":t(`detectionIntelligence.eventsSection.minimumImportance`,`Minimum importance`)}),a(`span`,{className:`w-6 tabular-nums text-foreground`,children:Math.round(y*100)})]}),a(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:No.map(n=>{let r=n.icon;return e(`button`,{type:`button`,onClick:()=>S(n.value),className:`flex items-center gap-1 rounded px-2 py-1 text-[11px] transition-colors ${x===n.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[a(r,{className:`h-3.5 w-3.5`}),` `,t(n.labelKey)]},n.value)})}),!W&&a(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:ue?t(`detectionIntelligence.eventsSection.ofEvents`,`{{value1}} of {{value2}} events`,{value1:String(K.length),value2:String(U.length)}):t(`detectionIntelligence.eventsSection.eventCount`,{count:K.length})})]}),C.size>0&&e(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[a(`span`,{className:`text-xs font-medium text-foreground`,children:t(`common.selectedCount`,{count:C.size})}),e(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[a(`span`,{title:Li?void 0:`Track deletion arrives with the next server update`,children:e(Y,{variant:`secondary`,onClick:ce,disabled:!Li||H,children:[H?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(R,{className:`h-3.5 w-3.5`}),` `,t(`common.delete`,`Delete`)]})}),a(Y,{variant:`ghost`,onClick:oe,disabled:H,children:a(q,{className:`h-3.5 w-3.5`})})]})]}),N&&a(`div`,{className:`sticky top-2 z-20 flex justify-center`,children:a(`button`,{type:`button`,onClick:F,className:`rounded-full border border-primary/40 bg-surface px-3 py-1 text-[11px] font-medium text-primary shadow-sm hover:bg-primary/10`,children:t(`detectionIntelligence.eventsSection.newEventsRefresh`,`New events — refresh`)})}),W?a(we,{status:`pending`,pendingMessage:`Loading events…`,testId:`events-grid`}):K.length===0?a(nt,{icon:_,title:ue?t(`detectionIntelligence.eventsSection.nothingMatchesTheFilter`,`Nothing matches the filter`):t(`detectionIntelligence.eventsSection.noKeyEventsInThis`,`No key events in this window`),description:ue?t(`detectionIntelligence.eventsSection.widenTheDateRangeClear`,`Widen the date range, clear cameras or kinds, or lower the min score.`):t(`detectionIntelligence.eventsSection.capturedTracksAppearHereWhen`,`Captured tracks appear here when the pipeline scores a key event.`)}):e(d,{children:[a(`div`,{ref:M.ref,"aria-hidden":!0,className:`h-0`}),a(we,{status:`ready`,testId:`events-grid`,children:ie.pageItems.map(e=>a(ui,{row:e,cameraName:re(e.deviceId),nowMs:D,selected:C.has(ei(e.deviceId,e.trackId)),onToggleSelect:se,onOpenDetail:E},ei(e.deviceId,e.trackId)))}),a(cr,{currentPage:ie.page,totalItems:ie.totalItems,pageSize:ie.pageSize,onPageChange:ie.setPage,itemNoun:`events`})]}),T&&a(Yi,{row:T,cameraName:re(T.deviceId),deleteAvailable:Li,onClose:()=>E(null),onDeleted:()=>{ae(),E(null)},onFlagsChanged:e=>{E(t=>t&&t.trackId===e.trackId?{...t,markForTrain:e.markForTrain,debug:e.debug,favourited:e.favourited}:t)}})]})}var Fo=`/addon/training`;function Io(){let{t}=Z(),n=Ht();return e(Qe,{className:`flex flex-col gap-3 border-border bg-surface p-3 sm:flex-row sm:items-center sm:gap-4`,"data-testid":`events-feed-retrain-cta`,children:[e(`div`,{className:`flex min-w-0 flex-1 items-start gap-2.5`,children:[a(ne,{className:`mt-0.5 h-4 w-4 shrink-0 text-primary`,"aria-hidden":!0}),e(`div`,{className:`min-w-0 space-y-0.5`,children:[a(`p`,{className:`text-xs font-medium text-foreground`,children:t(`detectionIntelligence.retrainTabCallout.trainingFromThisFeed`,`Training from this feed`)}),a(`p`,{className:`${ce} leading-relaxed`,children:t(`detectionIntelligence.retrainTabCallout.markATrackWithThe`,`Mark a track with the graduation-cap control on its card. On Training you correct frames, build collections, and start cloud fine-tunes.`)})]})]}),a(Y,{variant:`outline`,size:`sm`,className:`shrink-0 self-start sm:self-center`,onClick:()=>n(Fo),children:t(`detectionIntelligence.retrainTabCallout.openTraining`,`Open Training`)})]})}l();var Lo=50,Ro=350,zo=[{value:`loose`,labelKey:`detectionIntelligence.semanticEventSearch.looseLabel`,titleKey:`detectionIntelligence.semanticEventSearch.looseTitle`},{value:`balanced`,labelKey:`detectionIntelligence.semanticEventSearch.balancedLabel`,titleKey:`detectionIntelligence.semanticEventSearch.balancedTitle`},{value:`strict`,labelKey:`detectionIntelligence.semanticEventSearch.strictLabel`,titleKey:`detectionIntelligence.semanticEventSearch.strictTitle`}];function Bo(e){let t=String(e.id);return{id:t,trackId:e.trackId??t,deviceId:e.deviceId,timestamp:e.timestamp,className:e.className,label:e.label,subLabel:e.subLabel,importance:e.importance??0,bestEventId:t,mediaId:e.keyFrameMediaId??e.mediaId,windowMs:void 0}}function Vo({onActiveChange:r}){let i=t(null);ft(i);let{t:c}=Z(),[l,u]=s(``),[d,f]=s(`loose`),[p,m]=s(null),[h,_]=s(null),[v,y]=s(null),b=He(l,Ro).trim(),x=b.length>0;o(()=>{r(x)},[x,r]);let[S,C]=s(()=>Date.now());o(()=>{let e=setInterval(()=>C(Date.now()),6e4);return()=>clearInterval(e)},[]);let{data:w=[]}=Ve({isCamera:!0,projection:`slim`}),T=n(()=>{let e=new Map;for(let t of w)e.set(t.id,t.name);return e},[w]),E=e=>T.get(e)??c(`detectionIntelligence.cameraFallback`,{id:String(e)}),D=n(()=>w.map(e=>e.id),[w]),{data:O}=Ne({deviceIds:D},{enabled:D.length>0,staleTime:5*6e4}),k=n(()=>Oo(O??[],new Set(h===null?[]:[h])),[O,h]);o(()=>{p!==null&&(k.some(e=>e.kind===p)||m(null))},[k,p]);let{data:A,isFetching:j,isError:M,error:N}=et({text:b,strictness:d,limit:Lo,classFilter:p??void 0,deviceId:h??void 0},{enabled:x}),P=n(()=>[...A??[]].sort((e,t)=>t.score-e.score).map(e=>({...Bo(e),score:e.score})),[A]);function F(e){m(t=>t===e?null:e)}return e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(`div`,{className:`relative min-w-[16rem] flex-1`,children:[a(le,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle`}),a(J,{ref:i,type:`text`,value:l,onChange:e=>u(e.target.value),placeholder:c(`detectionIntelligence.semanticEventSearch.semanticSearchDescribeWhatYou`,`Semantic search — describe what you're looking for…`),className:`h-9 w-full rounded-md border border-border bg-background pl-8 pr-8 text-sm text-foreground placeholder:text-foreground-subtle focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary`,"aria-label":c(`detectionIntelligence.semanticEventSearch.semanticEventSearch`,`Semantic event search`)}),l&&a(`button`,{type:`button`,onClick:()=>u(``),className:`absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":c(`detectionIntelligence.semanticEventSearch.clearSearch`,`Clear search`),children:a(q,{className:`h-3.5 w-3.5`})})]}),j&&x&&a(g,{className:`h-4 w-4 shrink-0 animate-spin text-foreground-subtle`})]}),e(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[a(`div`,{className:`flex items-center gap-1`,children:k.map(e=>a(`button`,{type:`button`,onClick:()=>F(e.kind),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${p===e.kind?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:Xe(e)},e.kind))}),e(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[a(`span`,{children:c(`detectionIntelligence.semanticEventSearch.camera`,`Camera`)}),a(I,{value:h===null?``:String(h),onChange:e=>_(e.target.value===``?null:Number(e.target.value)),className:`h-7 text-xs`,"aria-label":c(`detectionIntelligence.semanticEventSearch.filterByCamera`,`Filter by camera`),options:[{value:``,label:c(`detectionIntelligence.semanticEventSearch.all`,`All`)},...w.map(e=>({value:String(e.id),label:e.name}))]})]}),e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[a(`span`,{children:c(`detectionIntelligence.semanticEventSearch.match`,`Match`)}),a(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:zo.map(e=>a(`button`,{type:`button`,onClick:()=>f(e.value),className:`rounded px-2 py-1 text-[11px] transition-colors ${d===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,title:c(e.titleKey),children:c(e.labelKey)},e.value))})]}),x&&!j&&!M&&a(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:c(`common.matches`,{count:P.length})})]})]}),x&&e(`div`,{className:`space-y-3`,children:[M&&e(`p`,{className:`py-4 text-xs text-danger`,children:[c(`detectionIntelligence.semanticEventSearch.searchFailed`,`Search failed:`),` `,N instanceof Error?N.message:c(`detectionIntelligence.semanticEventSearch.unknownError`,`unknown error`),`. Check that the CLIP embedding step is enabled.`]}),!M&&j&&P.length===0&&a(we,{status:`pending`,pendingMessage:`Searching…`,testId:`semantic-events-grid`}),!M&&!j&&P.length===0&&a(we,{status:`empty`,emptyMessage:c(`detectionIntelligence.semanticEventSearch.noSemanticMatchesForTry`,`No semantic matches for “{{debounced}}”. Try a looser match threshold or a different phrasing.`,{debounced:b}),testId:`semantic-events-grid`}),!M&&P.length>0&&a(we,{status:`ready`,testId:`semantic-events-grid`,children:P.map(e=>a(ui,{row:e,cameraName:E(e.deviceId),nowMs:S,score:e.score,onOpenDetail:y},e.id))})]}),v&&a(Yi,{row:v,cameraName:E(v.deviceId),deleteAvailable:Li,onClose:()=>y(null),onDeleted:()=>y(null)})]})}l();function Ho(e,t){let n=Math.max(0,Math.round((e-t)/6e4));if(n<1)return X.t(`helpers.relativeTime.justNow`);if(n<60)return`${String(n)}m`;let r=Math.floor(n/60);return`${String(r)}h ${String(n%60)}m`}function Uo({row:t,cameraName:n,nowMs:r}){let{t:i}=Z(),o=Gt(t.keyFrameMediaId===void 0?void 0:Jt(t.keyFrameMediaId));return e(`div`,{className:`flex flex-col overflow-hidden rounded-md border border-border bg-surface`,children:[e(`div`,{className:`relative aspect-video overflow-hidden bg-surface-hover`,children:[o.src?a(`img`,{src:o.src,alt:i(`detectionIntelligence.stationarySection.parkedOn`,`Parked {{className}} on {{cameraName}}`,{className:t.className,cameraName:n}),className:`h-full w-full object-cover`}):a(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:a(U,{className:`h-6 w-6`})}),a(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium capitalize text-white`,children:t.label??t.className})]}),e(`div`,{className:`flex flex-col gap-0.5 p-1.5`,children:[a(`span`,{className:`truncate text-[11px] text-foreground`,children:n}),a(`span`,{className:`text-[10px] text-foreground-subtle`,children:i(`common.parkedSince`,{since:Ho(r,t.becameStationaryAt)})})]})]})}function Wo(){let{t}=Z(),[r,i]=s(!1),o=Date.now(),{data:c=[]}=Ve({isCamera:!0,projection:`slim`}),l=n(()=>c.map(e=>e.id),[c]),u=n(()=>{let e=new Map;for(let t of c)e.set(t.id,t.name);return e},[c]),{rows:d,unreadableCount:f}=Wt(l);return d.length===0&&f===0?null:e(`div`,{className:`rounded-md border border-border bg-surface/40`,children:[e(Y,{variant:`unstyled`,type:`button`,onClick:()=>i(e=>!e),className:`flex w-full items-center gap-2 px-3 py-2 text-left`,children:[a(r?pe:w,{className:`h-4 w-4 text-foreground-subtle`}),a(U,{className:`h-4 w-4 text-foreground-subtle`}),a(`span`,{className:`text-sm font-semibold text-foreground`,children:t(`detectionIntelligence.stationarySection.stationary`,`Stationary`)}),a(`span`,{className:`rounded-full bg-surface-hover px-2 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:d.length}),a(`span`,{className:`ml-2 text-[11px] text-foreground-subtle`,children:t(`detectionIntelligence.stationarySection.parkedObjectsKeptOutOf`,`Parked objects — kept out of the event feed`)}),f>0?a(`span`,{className:`ml-2 text-[11px] text-warning`,children:t(`detectionIntelligence.stationarySection.unreadable`,{count:f})}):null]}),r&&a(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] gap-2 p-3 pt-0`,children:d.map(e=>a(Uo,{row:e,cameraName:u.get(e.deviceId)??`Camera #${String(e.deviceId)}`,nowMs:o},e.id))})]})}l();function Go(){let[t,n]=s(!1);return e(`section`,{className:`space-y-3`,children:[a(Io,{}),a(Vo,{onActiveChange:n}),!t&&a(Wo,{}),!t&&a(Po,{})]})}function Ko(){let{t:e}=Z(),[t]=Bt();return t.get(`section`)===`retrain`?a(zt,{to:`/addon/training`,replace:!0}):a(Ut,{sectionsOnly:!0,paramName:`section`,defaultSection:`feed`,sectionsLabel:`Events sections`,sections:[{id:`feed`,label:e(`events.feed`,`Feed`),content:a(Go,{})},{id:`debug`,label:e(`events.debug`,`Debug`),content:a(go,{})}]})}function qo(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}l();var Jo=[[`plateGallery`]];function Yo({plateIds:t,vehicles:n,onDone:r}){let{t:i}=Z(),o=u(),c=Le(),l=tt(),[d,f]=s(``),[p,m]=s(!1),[h,_]=s(null),v=t!==null&&t.length>0,y=t?.length??0;function b(){m(!1),f(``),_(null)}function x(){b(),r()}function S(e){!t||t.length===0||c.mutate({plateIds:[...t],vehicleId:e},{onSettled:()=>{o.invalidateQueries({queryKey:Jo}),x()}})}function C(){!t||!d.trim()||l.mutate({name:d.trim()},{onSuccess:e=>{e?.id&&S(e.id)},onError:()=>{o.invalidateQueries({queryKey:Jo}),x()}})}let w=c.isPending||l.isPending;return a(Be,{open:v,onOpenChange:e=>!e&&x(),children:e(Me,{children:[e(qe,{children:[a(Lt,{children:y>1?i(`detectionIntelligence.assignPlateDialog.assignPlatesToVehicle`,`Assign {{value1}} plates to vehicle`,{value1:String(y)}):i(`detectionIntelligence.assignPlateDialog.assignPlateToVehicle`,`Assign plate to vehicle`)}),a(Fe,{children:i(`detectionIntelligence.assignPlateDialog.selectAnExistingVehicleOr`,`Select an existing vehicle or create a new one.`)})]}),a(`div`,{className:`space-y-1 max-h-56 overflow-y-auto`,children:n.map(t=>e(Y,{variant:`unstyled`,type:`button`,onClick:()=>_(t.id),className:`w-full rounded-md px-3 py-2 text-left text-xs transition-colors ${h===t.id?`bg-primary/12 text-primary`:`hover:bg-surface-hover text-foreground`}`,children:[a(`span`,{className:`font-medium`,children:t.name}),a(`span`,{className:`ml-2 text-foreground-subtle`,children:i(`detectionIntelligence.assignPlateDialog.plates`,{count:t.sampleCount})})]},t.id))}),p?a(`div`,{className:`flex items-center gap-2 pt-2 border-t border-border`,children:a(J,{placeholder:i(`detectionIntelligence.assignPlateDialog.newVehicleName`,`New vehicle name…`),value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&C()},autoFocus:!0,className:`flex-1`})}):a(Y,{variant:`unstyled`,type:`button`,onClick:()=>{_(null),m(!0)},className:`mt-2 w-full rounded-md border border-dashed border-border px-3 py-2 text-left text-xs text-foreground-subtle hover:border-primary hover:text-primary transition-colors`,children:i(`detectionIntelligence.assignPlateDialog.newVehicle`,`+ New vehicle…`)}),e(ze,{children:[a(Y,{variant:`secondary`,onClick:x,disabled:w,children:i(`common.cancel`,`Cancel`)}),p?e(Y,{variant:`primary`,onClick:C,disabled:w||!d.trim(),children:[w&&a(g,{className:`h-3.5 w-3.5 animate-spin`}),i(`detectionIntelligence.assignPlateDialog.createAssign`,`Create & assign`)]}):e(Y,{variant:`primary`,onClick:()=>h&&S(h),disabled:w||!h,children:[w&&a(g,{className:`h-3.5 w-3.5 animate-spin`}),y>1?i(`detectionIntelligence.assignCount`,{count:y}):i(`common.assign`)]})]})]})})}l();var Xo=[[`plateGallery`]];function Zo(e){let[t,n]=s(null),[r,i]=s(null),[a,c]=s(!1);return o(()=>{if(n(null),i(null),c(!1),e===void 0)return;let t=!1,r=null;return(async()=>{try{let i=await qt(Jt(e));if(t)return;r=URL.createObjectURL(i),n(r)}catch{t||c(!0)}})(),()=>{t=!0,r&&URL.revokeObjectURL(r)}},[e]),o(()=>{if(!t)return;let e=new Image;return e.onload=()=>i({width:e.naturalWidth,height:e.naturalHeight}),e.onerror=()=>c(!0),e.src=t,()=>{e.onload=null,e.onerror=null}},[t]),{frameSrc:t,naturalWidth:r?.width??null,naturalHeight:r?.height??null,failed:a}}function Qo(e){let t=e.filter(e=>e.url.length>0);return t.length===0?null:t.find(e=>/crop|plate/i.test(e.kind))??t[0]}function $o({label:t,value:n,mono:r}){return e(`div`,{className:`flex items-baseline justify-between gap-3 py-1.5 border-b border-border/60 last:border-0`,children:[a(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:t}),a(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground ${r?`font-mono`:``}`,title:n,children:n})]})}function es({box:e}){let{t}=Z();return a(`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:a(`span`,{className:`absolute -top-4 left-0 rounded bg-primary px-1 text-[9px] font-semibold uppercase tracking-wide text-white`,children:t(`detectionIntelligence.plateDetailPanel.plate`,`Plate`)})})}function ts({plate:t,cameraName:r,onClose:i,onAssign:c,onUnassign:l,onDelete:d,actionsPending:f}){let{t:p}=Z(),m=u(),{data:h,isFetching:_}=Te({plateId:t?.plateId??``},{enabled:t!==null}),v=rt(),[y,x]=s(`frame`),[S,C]=s(!1),[w,T]=s(``),{frameSrc:O,naturalWidth:k,naturalHeight:A,failed:j}=Zo(t?.keyFrameMediaId);o(()=>{C(!1),T(``),x(`frame`)},[t?.plateId]);let M=n(()=>{let e=Qo(h??[]);return e?e.url:qo(t)},[h,t]),N=n(()=>!t?.plateBbox||k===null||A===null?null:hr(t.plateBbox,k,A),[t?.plateBbox,k,A]);if(t===null)return null;let P=t.keyFrameMediaId!==void 0&&!j,F=P&&y===`frame`,I=t.assigned?t.vehicleName??`Assigned`:t.recognizedVehicleId?`${t.vehicleName??`Recognized`} (suggested)`:`Unassigned`,z=`${String(Math.round(t.score*100))}%${t.corrected?` · corrected`:``}`;function B(){t&&(T(t.text),C(!0))}function V(){if(!t)return;let e=w.trim().toUpperCase();if(!e||e===t.text){C(!1);return}v.mutate({plateId:t.plateId,text:e},{onSettled:()=>{m.invalidateQueries({queryKey:Xo}),C(!1)}})}return a(Be,{open:!0,onOpenChange:e=>!e&&i(),children:e(Me,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":p(`detectionIntelligence.plateDetailPanel.plateDetail`,`Plate detail`),className:`flex 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:h-auto 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:[a(`header`,{className:`flex shrink-0 items-start gap-2 border-b border-border py-3 pl-4 pr-10`,children:e(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate font-mono text-sm font-semibold tracking-wide text-foreground`,children:t.text||p(`detectionIntelligence.plateDetailPanel.plateDetail`,`Plate detail`)}),a(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:r})]})}),e(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[P&&e(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5 text-xs`,children:[e(Y,{variant:`unstyled`,type:`button`,onClick:()=>x(`frame`),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-1 transition-colors ${y===`frame`?`bg-primary/12 font-medium text-primary`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[a(D,{className:`h-3.5 w-3.5`}),` `,p(`detectionIntelligence.detailPanel.fullFrame`)]}),e(Y,{variant:`unstyled`,type:`button`,onClick:()=>x(`crop`),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-1 transition-colors ${y===`crop`?`bg-primary/12 font-medium text-primary`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[a(Ce,{className:`h-3.5 w-3.5`}),` `,p(`detectionIntelligence.detailPanel.crop`)]})]}),F&&O?a(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:a(_r,{src:O,alt:p(`detectionIntelligence.plateDetailPanel.fullFrameWithDetectedPlate`,`Full frame with detected plate`),fit:`natural`,className:`w-full`,overlay:N?a(es,{box:N}):void 0})}):M?e(`div`,{className:`relative aspect-[2/1] w-full overflow-hidden rounded-lg border border-border bg-background`,children:[a(_r,{src:M,alt:p(`detectionIntelligence.plateDetailPanel.detectedPlate`,`Detected plate`),className:`h-full w-full`}),_&&a(`div`,{className:`absolute right-2 top-2 rounded-full bg-black/50 p-1 text-white`,children:a(g,{className:`h-3.5 w-3.5 animate-spin`})})]}):e(`div`,{className:`flex aspect-[2/1] w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-warning/5 text-foreground-subtle`,children:[a(b,{className:`h-8 w-8 text-warning/70`}),a(`span`,{className:`text-[11px] font-medium uppercase tracking-wide text-warning/80`,children:p(`detectionIntelligence.plateDetailPanel.noImage`,`No image`)}),a(`span`,{className:`px-6 text-center text-[10px] text-foreground-subtle`,children:p(`detectionIntelligence.plateDetailPanel.theCropMediaForThis`,`The crop media for this plate could not be resolved. Safe to delete.`)})]}),a(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-2`,children:e(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:p(`detectionIntelligence.plateDetailPanel.plateText`,`Plate text`)}),S?e(`div`,{className:`flex min-w-0 flex-1 items-center justify-end gap-1.5`,children:[a(J,{value:w,onChange:e=>T(e.target.value),onKeyDown:e=>{e.key===`Enter`&&V(),e.key===`Escape`&&C(!1)},className:`h-7 max-w-[10rem] text-right font-mono text-xs uppercase`,autoFocus:!0}),a(Y,{variant:`unstyled`,type:`button`,onClick:V,disabled:v.isPending,className:`text-success hover:text-success/80 disabled:opacity-50`,"aria-label":p(`detectionIntelligence.plateDetailPanel.saveCorrectedText`,`Save corrected text`),children:v.isPending?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(L,{className:`h-3.5 w-3.5`})}),a(Y,{variant:`unstyled`,type:`button`,onClick:()=>C(!1),className:`text-foreground-subtle hover:text-foreground`,"aria-label":p(`common.cancel`,`Cancel`),children:a(q,{className:`h-3.5 w-3.5`})})]}):e(Y,{variant:`unstyled`,type:`button`,onClick:B,className:`group flex min-w-0 items-center gap-1.5`,title:p(`detectionIntelligence.plateDetailPanel.correctTheOcrReading`,`Correct the OCR reading`),children:[a(`span`,{className:`truncate font-mono text-sm font-semibold tracking-wide text-foreground`,children:t.text||`—`}),a(H,{className:`h-3 w-3 shrink-0 text-foreground-subtle group-hover:text-foreground`})]})]})}),e(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[a($o,{label:p(`detectionIntelligence.plateDetailPanel.camera`,`Camera`),value:r}),a($o,{label:p(`detectionIntelligence.plateDetailPanel.captured`,`Captured`),value:er(t.timestamp)}),a($o,{label:p(`detectionIntelligence.plateDetailPanel.confidence`,`Confidence`),value:z}),a($o,{label:p(`detectionIntelligence.plateDetailPanel.vehicle`,`Vehicle`),value:I}),a($o,{label:p(`detectionIntelligence.plateDetailPanel.track`,`Track`),value:t.trackId,mono:!0})]})]}),e(`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:[t.assigned?e(Y,{variant:`secondary`,onClick:()=>l(t.plateId),disabled:f,children:[a(xe,{className:`h-3.5 w-3.5`}),` `,p(`detectionIntelligence.detailPanel.detach`)]}):e(Y,{variant:`primary`,onClick:()=>c(t.plateId),disabled:f,children:[a(E,{className:`h-3.5 w-3.5`}),` `,p(`common.assign`)]}),e(Y,{variant:`secondary`,onClick:()=>d(t.plateId),disabled:f,children:[a(R,{className:`h-3.5 w-3.5`}),` `,p(`common.delete`)]})]})]})})}l();var ns=[[`plateGallery`]],rs=500,is=120;function as({plate:t,cameraName:n,nowMs:r,selected:i,onToggleSelect:o,onAssign:s,onOpenDetail:c}){let{t:l}=Z(),d=u(),f=ct(),p=ot(),m=()=>{d.invalidateQueries({queryKey:ns})},h=()=>c(t.plateId),_=qo(t);return e(`div`,{className:`relative flex flex-col overflow-hidden rounded-md border bg-surface ${i?`border-primary ring-1 ring-primary`:`border-border`}`,children:[e(`div`,{className:`relative aspect-[2/1] overflow-hidden bg-surface-hover`,children:[_===null?e(`button`,{type:`button`,onClick:h,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-warning/5 text-foreground-subtle`,title:l(`detectionIntelligence.recentPlates.noCropImageThePlate`,`No crop image — the plate's crop media is missing. Safe to delete.`),children:[a(b,{className:`h-7 w-7 text-warning/70`}),a(`span`,{className:`text-[9px] font-medium uppercase tracking-wide text-warning/80`,children:l(`detectionIntelligence.recentPlates.noCrop`,`No crop`)})]}):a(`img`,{src:_,alt:l(`detectionIntelligence.recentPlates.plateFrom`,`Plate {{text}} from {{cameraName}}`,{text:t.text,cameraName:n}),onClick:h,className:`h-full w-full cursor-zoom-in object-cover`}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o(t.plateId)},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?l(`detectionIntelligence.recentPlates.deselect`,`Deselect`):l(`detectionIntelligence.recentPlates.select`,`Select`),children:i?a(ye,{className:`h-4 w-4 text-primary`}):a(W,{className:`h-4 w-4`})}),t.corrected&&e(`span`,{className:`absolute right-0 top-0 z-10 flex items-center gap-0.5 rounded-bl-md bg-primary/80 px-1 py-0.5 text-[8px] font-semibold uppercase tracking-wide text-white`,title:l(`detectionIntelligence.recentPlates.manuallyCorrected`,`Manually corrected`),children:[a(be,{className:`h-3 w-3`}),` `,l(`detectionIntelligence.recentPlates.fixed`)]})]}),e(`div`,{className:`min-w-0 px-2 pt-1.5 space-y-0.5`,children:[a(`p`,{className:`truncate font-mono text-xs font-bold tracking-wide text-foreground`,title:t.text,children:t.text||`—`}),a(`p`,{className:`truncate text-[10px] text-foreground-subtle`,title:n,children:n}),a(`p`,{className:`truncate text-[10px] text-foreground-subtle`,children:Qn(t.timestamp,r)}),t.vehicleName&&a(`p`,{className:`truncate text-[10px] font-medium text-primary`,title:t.vehicleName,children:t.vehicleName})]}),e(`div`,{className:`mt-1 flex items-center gap-0.5 border-t border-border/60 px-1 py-0.5`,children:[t.assigned?a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),f.mutate({plateId:t.plateId},{onSettled:m})},disabled:f.isPending,className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-warning/10 hover:text-warning disabled:opacity-40`,"aria-label":l(`detectionIntelligence.recentPlates.detachPlate`,`Detach plate`),title:l(`detectionIntelligence.recentPlates.detach`,`Detach`),children:f.isPending?a(g,{className:`h-4 w-4 animate-spin`}):a(xe,{className:`h-4 w-4`})}):a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s(t.plateId)},className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-primary/10 hover:text-primary`,"aria-label":l(`detectionIntelligence.recentPlates.assignPlateToVehicle`,`Assign plate to vehicle`),title:l(`detectionIntelligence.recentPlates.assignToVehicle`,`Assign to vehicle`),children:a(E,{className:`h-4 w-4`})}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),p.mutate({plateId:t.plateId},{onSettled:m})},disabled:p.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":l(`detectionIntelligence.recentPlates.deletePlate`,`Delete plate`),title:l(`detectionIntelligence.recentPlates.deletePlate`,`Delete plate`),children:p.isPending?a(g,{className:`h-4 w-4 animate-spin`}):a(R,{className:`h-4 w-4`})})]})]})}var os=[{labelKey:`common.all`,value:`all`},{labelKey:`detectionIntelligence.recentPlates.filterUnassigned`,value:`unassigned`},{labelKey:`detectionIntelligence.recentPlates.filterAssigned`,value:`assigned`}];function ss(e,t){return t===`unassigned`?e.filter(e=>!e.assigned):t===`assigned`?e.filter(e=>e.assigned):e}function cs(){let{t}=Z(),r=u(),[i,o]=s(`all`),[c,l]=s(Hn),[f,p]=s(new Set),[m,h]=s(new Set),[_,v]=s(null),[y,x]=s(null),{data:S,isLoading:C}=mt({limit:rs,includeCrops:!1},{refetchInterval:3e4}),{data:w=[]}=wt(),{data:T}=Ve({isCamera:!0,projection:`slim`}),D=ct(),O=Tt(),k=ot(),A=Date.now(),j=S??[],M=n(()=>{let e=new Map;for(let t of T??[])e.set(t.id,t.name);return e},[T]),N=e=>M.get(e)??t(`detectionIntelligence.cameraFallback`,{id:String(e)}),P=n(()=>Yn(j).map(e=>({id:e,name:N(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[j,M]),F=n(()=>Jn(qn(ss(j,i),c),f),[j,i,c,f]),I=ar(F,is,n(()=>JSON.stringify([i,c.fromMs,c.toMs,[...f].sort((e,t)=>e-t)]),[i,c.fromMs,c.toMs,f])),L=n(()=>new Map(j.map(e=>[e.plateId,e])),[j]),z=y===null?null:L.get(y)??null,B=()=>{r.invalidateQueries({queryKey:ns})},V=()=>h(new Set);function ee(e){h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}let H=[...m],U=O.isPending||k.isPending,te=D.isPending||k.isPending;function W(){H.length!==0&&O.mutate({plateIds:H},{onSettled:()=>{B(),V()}})}function ne(){H.length!==0&&Promise.allSettled(H.map(e=>k.mutateAsync({plateId:e}))).then(()=>{B(),V()})}function re(e){x(null),v([e])}function G(e){D.mutate({plateId:e},{onSettled:B}),x(null)}function K(e){k.mutate({plateId:e},{onSettled:B}),x(null)}let ie=F.length!==j.length;return e(`div`,{className:`relative space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[a(`div`,{className:`flex items-center gap-1`,children:os.map(e=>a(`button`,{type:`button`,onClick:()=>o(e.value),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${i===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:t(e.labelKey)},e.value))}),a(pr,{onChange:l}),a(dr,{cameras:P,selected:f,onChange:p}),!C&&a(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:ie?t(`detectionIntelligence.recentPlates.ofPlates`,`{{value1}} of {{value2}} plates`,{value1:String(F.length),value2:String(j.length)}):t(`detectionIntelligence.recentPlates.plateCount`,{count:F.length})})]}),m.size>0&&e(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[a(`span`,{className:`text-xs font-medium text-foreground`,children:t(`common.selectedCount`,{count:m.size})}),e(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[e(Y,{variant:`primary`,onClick:()=>v(H),disabled:U,children:[a(E,{className:`h-3.5 w-3.5`}),` `,t(`common.assign`)]}),e(Y,{variant:`secondary`,onClick:W,disabled:U,children:[O.isPending?a(g,{className:`h-3.5 w-3.5 animate-spin`}):a(xe,{className:`h-3.5 w-3.5`}),` `,t(`detectionIntelligence.recentPlates.detach`,`Detach`)]}),e(Y,{variant:`secondary`,onClick:ne,disabled:U,children:[a(R,{className:`h-3.5 w-3.5`}),` `,t(`common.delete`)]}),a(Y,{variant:`ghost`,onClick:V,disabled:U,children:a(q,{className:`h-3.5 w-3.5`})})]})]}),C?a(we,{status:`pending`,pendingMessage:`Loading plates…`,testId:`plates-grid`}):F.length===0?a(nt,{icon:b,title:j.length>0?t(`detectionIntelligence.recentPlates.nothingMatchesTheFilter`,`Nothing matches the filter`):t(`detectionIntelligence.recentPlates.noPlatesRecognizedYet`,`No plates recognized yet`),description:j.length>0?t(`detectionIntelligence.recentPlates.widenTheDateRangeOr`,`Widen the date range or clear the camera filter.`):t(`detectionIntelligence.recentPlates.plateReadsAppearHereWhen`,`Plate reads appear here when the detection pipeline OCRs a vehicle.`)}):e(d,{children:[a(we,{status:`ready`,testId:`plates-grid`,children:I.pageItems.map(e=>a(as,{plate:e,cameraName:N(e.deviceId),nowMs:A,selected:m.has(e.plateId),onToggleSelect:ee,onAssign:e=>v([e]),onOpenDetail:x},e.plateId))}),a(cr,{currentPage:I.page,totalItems:I.totalItems,pageSize:I.pageSize,onPageChange:I.setPage,itemNoun:`plates`})]}),a(ts,{plate:z,cameraName:z?N(z.deviceId):``,onClose:()=>x(null),onAssign:re,onUnassign:G,onDelete:K,actionsPending:te}),a(Yo,{plateIds:_,vehicles:w,onDone:()=>{v(null),V()}})]})}l();var ls=[[`plateGallery`]];function us({vehicleId:t}){let{t:n}=Z(),r=u(),{data:i,isLoading:o}=Ot({vehicleId:t}),s=Et();function c(e){s.mutate({vehicleId:t,sampleId:e.id},{onSettled:()=>{r.invalidateQueries({queryKey:ls})}})}return o?e(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,children:[a(g,{className:`h-3.5 w-3.5 animate-spin`}),n(`detectionIntelligence.vehiclesList.loadingPlates`,`Loading plates…`)]}):!i||i.length===0?a(`p`,{className:`py-2 text-xs text-foreground-subtle`,children:n(`detectionIntelligence.vehiclesList.noPlatesYet`,`No plates yet.`)}):a(`div`,{className:`mt-2 grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-6`,children:i.map(t=>e(`div`,{className:`group relative overflow-hidden rounded-md border border-border bg-surface`,children:[e(`div`,{className:`relative aspect-[2/1] overflow-hidden bg-surface-hover`,children:[t.base64?a(`img`,{src:`data:image/jpeg;base64,${t.base64}`,alt:t.text,className:`h-full w-full object-cover`}):a(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:a(V,{className:`h-6 w-6`})}),a(`button`,{type:`button`,onClick:()=>c(t),disabled:s.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":n(`detectionIntelligence.vehiclesList.removePlateSample`,`Remove plate sample`),children:a(q,{className:`h-4 w-4 text-white`})})]}),a(`p`,{className:`truncate px-1.5 py-1 text-center font-mono text-[11px] font-semibold tracking-wide text-foreground`,title:t.text,children:t.text})]},t.id))})}function ds(t){return[{key:`vehicle`,header:X.t(`detectionIntelligence.vehiclesList.vehicle`,`Vehicle`),sortValue:e=>e.name,render:t=>e(`span`,{className:`flex min-w-0 items-center gap-2`,children:[a(`span`,{className:`h-8 w-12 shrink-0 overflow-hidden rounded border border-border bg-surface-hover`,children:a(Zt,{mediaId:t.coverMediaId,base64:t.coverBase64,alt:t.name,className:`h-full w-full object-cover`,placeholder:a(`span`,{className:`flex h-full w-full items-center justify-center`,children:a(V,{className:`h-4 w-4 text-foreground-subtle`})})})}),a(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name})]})},{key:`samples`,header:X.t(`detectionIntelligence.vehiclesList.plates`,`Plates`),align:`center`,nowrap:!0,sortValue:e=>e.sampleCount,render:e=>a(Ct,{variant:`default`,className:`text-[10px]`,children:e.sampleCount})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Actions`,render:n=>e(`span`,{className:`flex items-center justify-end gap-1`,children:[a(ht,{variant:`ghost`,size:`sm`,icon:H,"aria-label":X.t(`detectionIntelligence.vehiclesList.edit`,`Edit {{name}}`,{name:n.name}),onClick:e=>{e.stopPropagation(),t.onEdit(n)}}),a(ht,{variant:`ghost`,size:`sm`,icon:R,"aria-label":X.t(`detectionIntelligence.vehiclesList.delete`,`Delete {{name}}`,{name:n.name}),onClick:e=>{e.stopPropagation(),t.onDelete(n)}})]})}]}function fs({mode:t,vehicle:n,onClose:r}){let{t:i}=Z(),c=u(),[l,d]=s(t===`edit`?n?.name??``:``),f=tt(),p=xt();o(()=>{d(t===`edit`?n?.name??``:``)},[t,n?.id,n?.name]);let m=f.isPending||p.isPending,h=l.trim(),_=t===`edit`&&n!==null&&h===n.name,v=m||h.length===0||_;function y(){c.invalidateQueries({queryKey:ls})}function b(){if(!v){if(t===`new`){f.mutate({name:h},{onSuccess:()=>{y(),r()}});return}if(n===null){r();return}p.mutate({id:n.id,name:h},{onSuccess:()=>{y(),r()}})}}return a(kt,{open:!0,onClose:r,title:t===`new`?`Add vehicle`:`Edit ${n?.name??`vehicle`}`,icon:V,width:t===`edit`?`xl`:`lg`,testId:`vehicles-vehicle-form`,footer:e(Y,{variant:`primary`,size:`sm`,type:`button`,onClick:b,disabled:v,children:[m?a(g,{className:`h-3.5 w-3.5 animate-spin`}):null,t===`new`?i(`common.add`,`Add`):i(`common.save`,`Save`)]}),children:e(`div`,{className:`space-y-4`,children:[a(pt,{label:i(`detectionIntelligence.vehiclesList.name`,`Name`),required:!0,children:a(J,{value:l,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&b()},placeholder:i(`detectionIntelligence.vehiclesList.vehicleName`,`Vehicle name…`),autoFocus:!0})}),t===`edit`&&n!==null&&e(`div`,{children:[a(`p`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:i(`detectionIntelligence.vehiclesList.plateSamples`,`Plate samples`)}),a(`p`,{className:`mb-2 text-[11px] text-foreground-subtle`,children:i(`detectionIntelligence.vehiclesList.removeAPlateCropTo`,`Remove a plate crop to drop it from recognition for this vehicle. Assign new plates from Recent recognized plates.`)}),a(us,{vehicleId:n.id})]})]})})}function ps(){let{t}=Z(),r=u(),i=P(),{data:s,isLoading:c}=wt(),l=Ge(),{state:d,openNew:f,openEdit:p,close:m}=gt(),h=s??[],_=dt(h,{searchText:e=>[e.name]}),v=d.mode===`edit`?h.find(e=>e.id===d.id)??null:null;o(()=>{d.mode===`edit`&&!c&&v===null&&m()},[d.mode,c,v,m]);let y=n(()=>ds({onEdit:e=>p(e.id),onDelete:e=>{(async()=>{await i({title:t(`detectionIntelligence.vehiclesList.deleteVehicle`,`Delete vehicle`),message:t(`detectionIntelligence.vehiclesList.deleteAndAllItsPlate`,`Delete {{name}} and all its plate samples? This cannot be undone.`,{name:e.name}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&l.mutate({id:e.id},{onSettled:()=>{r.invalidateQueries({queryKey:ls}),d.mode===`edit`&&d.id===e.id&&m()}})})()}}),[i,m,l,d,p,r,t]);if(c)return e(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[a(g,{className:`h-4 w-4 animate-spin`}),t(`detectionIntelligence.vehiclesList.loadingVehicles`,`Loading vehicles…`)]});let b=d.mode===`new`||d.mode===`edit`&&v!==null;return e(`div`,{className:`space-y-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-2`,children:e(Y,{variant:`primary`,size:`sm`,type:`button`,onClick:f,children:[a(re,{className:`h-3.5 w-3.5`}),t(`detectionIntelligence.vehiclesList.addVehicle`,`Add vehicle`)]})}),(h.length>0||_.active)&&a(Pt,{state:_.state,facets:_.facets,labels:{searchPlaceholder:`Search vehicles…`,searchLabel:`Search vehicles`,facetsLabel:`Filter`,clearLabel:`Clear`},onSearch:_.setSearch,onToggleFacet:_.toggleFacet,onClear:_.clear}),_.rows.length===0?a(nt,{icon:V,title:_.active?t(`detectionIntelligence.vehiclesList.nothingMatchesTheFilter`,`Nothing matches the filter`):t(`detectionIntelligence.vehiclesList.noVehiclesEnrolledYet`,`No vehicles enrolled yet`),description:_.active?t(`detectionIntelligence.vehiclesList.clearTheSearchOrTry`,`Clear the search or try another name.`):t(`detectionIntelligence.vehiclesList.addAVehicleThenAssign`,`Add a vehicle, then assign plate crops from Recent recognized plates.`)}):a(De,{columns:y,rows:_.rows,rowKey:e=>e.id,maxBodyHeight:St,emptyMessage:t(`detectionIntelligence.vehiclesList.noVehiclesEnrolledYet2`,`No vehicles enrolled yet.`),onRowClick:e=>p(e.id)}),b&&a(fs,{mode:d.mode===`new`?`new`:`edit`,vehicle:v,onClose:m})]})}l();var ms=[[`plateGallery`]],hs=2e3;function gs(){let e=u(),n=t(e);n.current=e;let r=t(void 0);r.current||=Wr({delayMs:hs,invalidate:()=>{n.current.invalidateQueries({queryKey:ms})}}),o(()=>()=>r.current?.cancel(),[]),Ue(ue.PipelineAnalyticsPlateGalleryChanged,()=>{r.current?.trigger()})}function _s(){let{t}=Z();return gs(),e(`div`,{className:`space-y-3`,children:[a(We,{headingId:`library-vehicles`,title:t(`plates.vehicles`,`Vehicles`),icon:V,testId:`library-section-vehicles`,children:e(`div`,{className:`${p} space-y-3`,children:[a(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`plates.enrolledVehicleIdentitiesUsedFor`,`Enrolled vehicle identities used for plate recognition. Open a vehicle to rename it or remove plate samples.`)}),a(ps,{})]})}),a(We,{headingId:`library-recent-plates`,title:t(`plates.recentRecognizedPlates`,`Recent recognized plates`),icon:ge,testId:`library-section-recent-plates`,children:e(`div`,{className:`${p} space-y-3`,children:[a(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`plates.licensePlatesReadByThe`,`License plates read by the detection pipeline. Assign them to a vehicle, correct the OCR text, or delete.`)}),a(cs,{})]})})]})}function vs(e){return e.states.length===0?3:e.latched?0:e.verdict===`diverged`?1:e.verdict===`unknown`?2:4}function ys(e){let t=[e.divergedAt,e.restoredAt].filter(e=>typeof e==`number`);return t.length===0?null:Math.max(...t)}function bs(e,t){let n=new Map(e.map(e=>[e.deviceId,e.deviceName])),r=[];for(let e of t)for(let t of e.monitors)r.push({deviceId:e.deviceId,deviceName:n.get(e.deviceId)??`Camera ${e.deviceId}`,monitor:t});return r.toSorted((e,t)=>{let n=vs(e.monitor)-vs(t.monitor);if(n!==0)return n;let r=ys(e.monitor)??-1,i=ys(t.monitor)??-1;if(r!==i)return i-r;let a=e.deviceName.localeCompare(t.deviceName);return a===0?e.monitor.label.localeCompare(t.monitor.label):a})}l();var xs={alarm:`danger`,ok:`success`,unknown:`default`},Ss={alarm:`Alarm`,ok:`OK`,unknown:`Unknown`};function Cs(e,t){let n=ys(e);return n===null?`—`:X.t(`scenes.transitionAgo`,{duration:G(Math.max(0,t-n))})}function ws(e){return M(e.monitor).tone}function Ts(e){let t=Number(e);return Number.isFinite(t)&&t>0?t:null}function Es(){let{t}=Z(),i=Ve({isCamera:!0,projection:`slim`}),c=n(()=>(i.data??[]).map(e=>({deviceId:e.id,deviceName:e.name})).sort((e,t)=>e.deviceName.localeCompare(t.deviceName)),[i.data]),l=n(()=>c.map(e=>e.deviceId),[c]),u=Xt(l),d=n(()=>bs(c,u.results),[c,u.results]),f=dt(d,{searchText:e=>[e.monitor.label,e.deviceName],facetValue:ws}),{state:p,openNew:m,openEdit:h,close:g}=gt(),[_,v]=s(null);o(()=>{if(p.mode===`new`){v(e=>e??l[0]??null);return}v(null)},[p.mode,l]);let y=p.mode===`edit`?Ts(p.id):null,b=y===null?``:c.find(e=>e.deviceId===y)?.deviceName??`#${y}`,x=Date.now(),S=[{key:`label`,header:t(`scenes.scene`,`Scene`),sortValue:e=>e.monitor.label,render:e=>a(`span`,{className:`font-medium`,children:e.monitor.label})},{key:`camera`,header:t(`scenes.camera`,`Camera`),nowrap:!0,sortValue:e=>e.deviceName,render:e=>e.deviceName},{key:`state`,header:t(`scenes.state`,`State`),nowrap:!0,sortValue:e=>ws(e),render:e=>{let t=M(e.monitor);return a(Ct,{variant:xs[t.tone],children:t.text})}},{key:`status`,header:t(`scenes.whatItSays`,`What it says`),notSortableReason:`Status is a live sentence, not a comparable value`,render:e=>a(`span`,{className:`text-xs text-foreground-muted`,children:z(e.monitor,x)})},{key:`coverage`,header:t(`scenes.variants`,`Variants`),notSortableReason:`Coverage is a summary string`,render:e=>a(`span`,{className:`text-xs text-foreground-muted`,children:ee(e.monitor)})},{key:`transition`,header:t(`scenes.lastChange`,`Last change`),align:`right`,nowrap:!0,sortValue:e=>ys(e.monitor)??0,render:e=>a(`span`,{className:`text-xs tabular-nums text-foreground-muted`,children:Cs(e.monitor,x)})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Actions`,render:e=>a(Y,{variant:`ghost`,onClick:()=>h(String(e.deviceId)),children:t(`scenes.open`,`Open`)})}];return e(`section`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4`,children:[a(`p`,{className:`text-xs text-foreground-subtle`,children:t(`scenes.aSceneWatchesOneRegion`,`A scene watches one region of one camera and tells you when it stops looking like the picture you captured — a wheelie bin, a gate, a parking space.`)}),e(Y,{onClick:m,disabled:c.length===0,className:`shrink-0`,children:[a(re,{className:`mr-1 h-3.5 w-3.5`}),t(`scenes.newScene`,`New scene`)]})]}),u.unreachableCount>0?a(`p`,{className:`text-xs text-warning`,children:t(`scenes.unreachable`,{count:u.unreachableCount})}):null,(d.length>0||f.active)&&a(Pt,{state:f.state,facets:f.facets,labels:{searchPlaceholder:`Search scenes…`,searchLabel:`Search scenes`,facetsLabel:`State`,clearLabel:`Clear`},facetLabel:e=>Ss[e]??e,onSearch:f.setSearch,onToggleFacet:f.toggleFacet,onClear:f.clear}),a(Qe,{variant:`flat`,className:`p-0`,children:a(De,{columns:S,rows:f.rows,rowKey:e=>`${e.deviceId}:${e.monitor.id}`,minWidthPx:880,bordered:!1,maxBodyHeight:St,emptyMessage:u.isLoading?t(`scenes.loadingScenes`,`Loading scenes…`):f.active?t(`scenes.nothingMatchesTheFilter`,`Nothing matches the filter`):t(`scenes.noScenesYetPressNew`,`No scenes yet. Press “New scene”, pick a camera, then draw a box around the thing you want watched.`)})}),p.mode===`new`?e(kt,{open:!0,onClose:g,title:t(`scenes.whichCamera`,`Which camera?`),icon:j,width:`sm`,testId:`scenes-camera-picker`,footer:a(Y,{onClick:()=>{_!==null&&h(String(_))},disabled:_===null,children:t(`scenes.continue`,`Continue`)}),children:[a(`p`,{className:`mb-3 text-xs text-foreground-subtle`,children:t(`scenes.aSceneLivesOnOne`,`A scene lives on one camera. Pick the one that can see the thing.`)}),a(I,{value:_===null?``:String(_),onChange:e=>v(Number(e.target.value)),"aria-label":t(`scenes.camera`,`Camera`),options:c.map(e=>({value:String(e.deviceId),label:e.deviceName}))})]}):null,y===null?null:e(kt,{open:!0,onClose:g,title:t(`scenes.scenes`,`Scenes — {{editingName}}`,{editingName:b}),icon:j,width:`lg`,testId:`scenes-editor`,children:[a(`p`,{className:`mb-3 text-xs text-foreground-subtle`,children:t(`scenes.drawABoxNameIt`,`Draw a box, name it, then capture what “normal” looks like. Daylight is enough — the night reference is optional, and “Settings” on each scene tunes how fussy and how often it checks.`)}),a(r,{fallback:a(`p`,{className:`text-xs text-foreground-muted`,children:t(`scenes.loadingTheEditor`,`Loading the editor…`)}),children:a(Dt,{deviceId:y})})]})]})}function Ds(){let{t:e}=Z(),t=Rt(`/library`,{t:e,isAdmin:!0})??{icon:Se,title:e(`nav.library`,`Library`)};return a(Ut,{icon:t.icon,title:t.title,subtitle:e(`library.peopleVehiclesCapturedEventsAnd`,`People, vehicles, captured events and scenes — what detection has recognised.`),defaultSection:`people`,sectionsLabel:`${t.title} sections`,sections:[{id:`people`,label:e(`library.people`,`People`),content:a(Jr,{})},{id:`vehicles`,label:e(`library.vehicles`,`Vehicles`),content:a(_s,{})},{id:`events`,label:e(`library.events`,`Events`),content:a(Ko,{}),ownedParams:[`section`]},{id:`scenes`,label:e(`library.scenes`,`Scenes`),content:a(Es,{})}]})}export{Ds as LibraryPage};
|