Files
memby/admin-ui/dist/assets/index-Db7bWHnD.js
T
2026-08-22 08:26:10 +12:00

12 lines
253 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import{r as g,a as On,u as ws,L as Z,b as ks,m as vs,N as xn,O as Pn,c as We,B as _n,R as Un,d as W,e as As}from"./router-D9WH5XEU.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function t(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(a){if(a.ep)return;a.ep=!0;const l=t(a);fetch(a.href,l)}})();var jn={exports:{}},cs={};/**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Wn=g,Bn=Symbol.for("react.element"),Vn=Symbol.for("react.fragment"),Hn=Object.prototype.hasOwnProperty,zn=Wn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Kn={key:!0,ref:!0,__self:!0,__source:!0};function gn(s,n,t){var r,a={},l=null,i=null;t!==void 0&&(l=""+t),n.key!==void 0&&(l=""+n.key),n.ref!==void 0&&(i=n.ref);for(r in n)Hn.call(n,r)&&!Kn.hasOwnProperty(r)&&(a[r]=n[r]);if(s&&s.defaultProps)for(r in n=s.defaultProps,n)a[r]===void 0&&(a[r]=n[r]);return{$$typeof:Bn,type:s,key:l,ref:i,props:a,_owner:zn.current}}cs.Fragment=Vn;cs.jsx=gn;cs.jsxs=gn;jn.exports=cs;var e=jn.exports,vn,Es=On;vn=Es.createRoot,Es.hydrateRoot;const bn={overview:"M4 13h6V4H4zm0 7h6v-4H4zm10 0h6v-9h-6zm0-16v4h6V4z",library:"M3 5h18v14H3zM7 5v14M17 5v14M3 9.5h4M3 14.5h4M17 9.5h4M17 14.5h4",people:"M15 19v-1.2a3.3 3.3 0 0 0-3.3-3.3H6.8A3.3 3.3 0 0 0 3.5 17.8V19M9.2 11a3.2 3.2 0 1 0 0-6.4 3.2 3.2 0 0 0 0 6.4ZM17 10.6a3 3 0 0 0-1.4-5.7M20.5 19v-1.2a3.3 3.3 0 0 0-2.4-3.2",person:"M18 20v-1.5a4 4 0 0 0-4-4h-4a4 4 0 0 0-4 4V20M12 10.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Z",tv:"M4 5h16v10H4zM9 19h6M12 15v4M8 2.5 12 5l4-2.5",sliders:"M4 7h10M18 7h2M4 17h2m4 0h10M14 4v6M6 14v6",clock:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18ZM12 7.2V12l3 1.8",pulse:"M3 12h3.5L9 19l5-14 2.5 7H21",chart:"M4 19V9m5 10V5m5 14v-7m5 7V3",chip:"M8 8h8v8H8zM4.5 4.5h15v15h-15zM9 2v2.5M15 2v2.5M9 19.5V22M15 19.5V22M2 9h2.5M2 15h2.5M19.5 9H22M19.5 15H22",database:"M12 8.2c4.4 0 8-1.2 8-2.6S16.4 3 12 3 4 4.2 4 5.6s3.6 2.6 8 2.6ZM4 5.6v12.8C4 19.8 7.6 21 12 21s8-1.2 8-2.6V5.6M4 12c0 1.4 3.6 2.6 8 2.6s8-1.2 8-2.6",download:"M12 3.5v10m0 0 4-4m-4 4-4-4M4.5 18h15",upload:"M12 16V4m0 0L8 8m4-4 4 4M5 13v6h14v-6",sync:"M3.5 12a8.5 8.5 0 0 1 14.6-6M20.5 12a8.5 8.5 0 0 1-14.6 6M18 2.5V6h-3.5M6 21.5V18h3.5",search:"M10.5 17a6.5 6.5 0 1 1 0-13 6.5 6.5 0 0 1 0 13Zm4.6-1.9L20 20",star:"m12 3.2 2.6 5.4 5.9.8-4.3 4.1 1 5.9-5.2-2.8-5.2 2.8 1-5.9L3.5 9.4l5.9-.8L12 3.2Z",sparkle:"m10 3 1.5 4.3L16 8.8l-4.5 1.5L10 14.6 8.5 10.3 4 8.8l4.5-1.5L10 3ZM17.5 14l.9 2.4 2.6.9-2.6.9-.9 2.4-.9-2.4-2.6-.9 2.6-.9.9-2.4Z",bell:"M6.2 9.5a5.8 5.8 0 1 1 11.6 0c0 4.6 2.2 5.9 2.2 5.9H4s2.2-1.3 2.2-5.9M10 19.5a2 2 0 0 0 4 0",shield:"m12 3 7.5 3v5.4c0 5-3.2 8.2-7.5 9.6-4.3-1.4-7.5-4.6-7.5-9.6V6L12 3Zm-2.6 8.7 1.9 1.9 3.6-3.6",wrench:"m14.5 6.5 3-3 3 3-3 3M9 15l-5.5 5.5M13 4a5 5 0 0 0 6.5 6.5L10 20l-6-6 9.5-9.5Z",play:"M8 5.2v13.6L19 12 8 5.2ZM4 5v14",list:"M4 7h16M4 12h16M4 17h10",inbox:"M4 7h16v13H4zM8 4h8v3M8 12h8M8 16h5",send:"M21 3 10.5 13.5M21 3l-6.8 18-3.7-7.5L3 10z",history:"M3.5 12a8.5 8.5 0 1 0 2.8-6.3M3.5 4v4h4M12 7.5V12l3 1.8",check:"m5 12.5 4.5 4.5L19 7.5",alert:"M12 8.5v5m0 3.2h.01M10.3 4.4 2.7 17.5a2 2 0 0 0 1.7 3h15.2a2 2 0 0 0 1.7-3L13.7 4.4a2 2 0 0 0-3.4 0Z",power:"M12 3v9M7.5 6.2a7.5 7.5 0 1 0 9 0",key:"M14.5 3a6.5 6.5 0 1 0 3.4 12L19 14h2v-2h2V9.5l-2.5-2.5A6.5 6.5 0 0 0 14.5 3Zm-2.6 4.6a1.6 1.6 0 1 1-2.3 2.3 1.6 1.6 0 0 1 2.3-2.3Z",captions:"M4 5.5h16v13H4zM7 15h5m3 0h2M7 11h3m2 0h5",journey:"M4 6h5v5h6v7h5M7 3 4 6l3 3m10 6 3 3-3 3",plug:"M9 3v6M15 3v6M6.5 9h11v3.5a5.5 5.5 0 0 1-11 0zM12 18v3",calendar:"M4 6h16v15H4zM8 3v5M16 3v5M4 11h16",trash:"M4 7h16M9 7V4.5h6V7M6.5 7l1 13h9l1-13M10 11v5M14 11v5",plus:"M12 5v14M5 12h14",close:"M6 6l12 12M18 6 6 18",caret:"m6 9 6 6 6-6",external:"M14 4h6v6M20 4l-9 9M18 14v5.5H4.5V6H10",refresh:"M3.5 12a8.5 8.5 0 0 1 14.6-6M20.5 12a8.5 8.5 0 0 1-14.6 6M18 2.5V6h-3.5M6 21.5V18h3.5",filter:"M3.5 5.5h17l-6.5 7.5V20l-4-2v-5L3.5 5.5Z",menu:"M4 7h16M4 12h16M4 17h16",globe:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18ZM3.5 9h17M3.5 15h17M12 3a14 14 0 0 1 0 18 14 14 0 0 1 0-18Z",logout:"M15 17l5-5-5-5M20 12H9M12 4H5v16h7"};function se({name:s,className:n}){const t=bn[s];return t?e.jsx("svg",{className:n??"ico",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",preserveAspectRatio:"xMidYMid meet","aria-hidden":"true",children:e.jsx("path",{d:t})}):null}function Qe({name:s,tone:n}){return bn[s]?e.jsx("span",{className:"glyph","data-tone":n,children:e.jsx(se,{name:s})}):null}const Oe=[{id:"everyday",label:"Everyday",defaultCollapsed:!1,items:[{id:"overview",path:"/admin",label:"Overview",title:"Overview",intro:"What the gateway is doing right now.",icon:"overview"},{id:"activity",path:"/admin/activity",label:"Activity",title:"Activity",intro:"Every administrative event, newest first.",icon:"bell",badge:"notifications"},{id:"accounts",path:"/admin/accounts",label:"Users",title:"Users",intro:"Who uses Memby, and the devices they are signed in on.",icon:"people"},{id:"requests",path:"/admin/requests",label:"Media requests",title:"Media requests",intro:"Who can ask for something the library does not have.",icon:"inbox"},{id:"notifications",path:"/admin/notifications",label:"Notifications",title:"Notifications",intro:"Everything Memby sent: who it went to, over which channel, and whether it worked.",icon:"send"},{id:"media-reports",path:"/admin/media-reports",label:"Media reports",title:"Media reports",intro:"Problems viewers reported with a film or episode.",icon:"alert"},{id:"updates",path:"/admin/updates",label:"App updates",title:"App updates",intro:"Publish an optional or a required client update.",icon:"upload"},{id:"logs",path:"/admin/logs",label:"Logs",title:"Logs",intro:"Structured gateway events as they happen.",icon:"list"}]},{id:"people",label:"Devices & access",defaultCollapsed:!0,items:[{id:"account",path:"/admin/accounts/:userId",label:"User",title:"User",intro:"Devices, recommendation setup and synced settings for one person.",icon:"person",hidden:!0},{id:"settings-history",path:"/admin/accounts/:userId/settings",label:"Settings history",title:"Settings history",intro:"Every change to one person's synced settings, and which devices took it.",icon:"sliders",hidden:!0},{id:"clients",path:"/admin/clients",label:"Devices",title:"Devices",intro:"Which sets have reported in, what they are running and what their build understands.",icon:"tv"},{id:"logins",path:"/admin/logins",label:"Sign-ins",title:"Sign-in history",intro:"Every connection attempt: who, which television, from where, and whether it got in.",icon:"key"},{id:"device",path:"/admin/devices/:deviceId",label:"Device",title:"Device",intro:"One television: how often it connects, at what times, and from which addresses.",icon:"tv",hidden:!0}]},{id:"content",label:"Content & discovery",defaultCollapsed:!0,items:[{id:"library",path:"/admin/library",label:"Library",title:"Library",intro:"Import and inspect the catalogue Memby ranks.",icon:"library"},{id:"hero",path:"/admin/hero",label:"Home hero",title:"Home hero",intro:"Choose films or television shows for the launcher spotlight while recent releases fill the remaining places.",icon:"star"},{id:"metadata-hero",path:"/admin/metadata-hero",label:"Metadata hero",title:"Metadata hero",intro:"Order the focused-title information shown above browse rows on every television.",icon:"tv"},{id:"recommendations",path:"/admin/recommendations",label:"For You",title:"For You",intro:"The prepared pools personalised rows are drawn from.",icon:"sparkle"},{id:"inspector",path:"/admin/inspector",label:"Score inspector",title:"Score inspector",intro:"Re-run the ranker for one person and read every component.",icon:"search"}]},{id:"experience",label:"Viewing experience",defaultCollapsed:!0,items:[{id:"features",path:"/admin/features",label:"Features",title:"Features",intro:"Roll out, stop and recover optional behaviour with no app release.",icon:"sliders"},{id:"playback",path:"/admin/playback",label:"Playback",title:"Playback",intro:"Presentation policy sent with every playback launch.",icon:"play"},{id:"subtitles",path:"/admin/subtitles",label:"Subtitles",title:"Subtitles",intro:"Which providers a viewer may fetch a missing subtitle from.",icon:"captions"},{id:"credits",path:"/admin/credits",label:"Credits detection",title:"Credits detection",intro:"Control predictive scanning and review every completed credits scan.",icon:"clock"}]},{id:"operations",label:"Operations",defaultCollapsed:!0,items:[{id:"tasks",path:"/admin/tasks",label:"Scheduled tasks",title:"Scheduled tasks",intro:"What the gateway does in the background, when it last ran and whether it worked.",icon:"clock"},{id:"task",path:"/admin/tasks/:taskId",label:"Task",title:"Task",intro:"One scheduled task: its cadence, its switch and its own run history.",icon:"clock",hidden:!0},{id:"imports",path:"/admin/imports",label:"Imports",title:"Imports",intro:"Catalogue synchronisation history.",icon:"database"},{id:"runtime",path:"/admin/runtime",label:"Runtime",title:"Runtime",intro:"Goroutines, memory and the background workers inside the gateway process.",icon:"chip"},{id:"maintenance",path:"/admin/maintenance",label:"Maintenance",title:"Maintenance",intro:"Take Memby offline now or schedule daily quiet time.",icon:"wrench"},{id:"gateway-settings",path:"/admin/settings",label:"Gateway settings",title:"Gateway settings",intro:"Timezone, logging and the other server-level settings for this gateway.",icon:"sliders",hidden:!0}]},{id:"integrations",label:"Integrations",defaultCollapsed:!0,items:[{id:"integrations",path:"/admin/integrations",label:"Overview",title:"Integrations",intro:"Every external service Memby depends on: configured, working, and what it last did.",icon:"plug"},{id:"integration",path:"/admin/integrations/:integrationId",label:"Integration",title:"Integration",intro:"One external service: its switch, its settings, its jobs and its run history.",icon:"plug",hidden:!0},{id:"webhooks",path:"/admin/integrations/webhooks",label:"Event webhooks",title:"Event webhooks",intro:"Send administrative events to Discord and, in time, elsewhere.",icon:"send"}]},{id:"insights",label:"Insights",defaultCollapsed:!0,items:[{id:"views",path:"/admin/views",label:"Views",title:"App views",intro:"Home-screen visits, viewers and the times Memby is used.",icon:"overview"},{id:"searches",path:"/admin/searches",label:"Searches",title:"Searches",intro:"What viewers have been looking for, and what was searched just now.",icon:"search"},{id:"journeys",path:"/admin/journeys",label:"Journeys",title:"User journeys",intro:"How viewers move through Memby, use features and complete flows.",icon:"journey"},{id:"engagement",path:"/admin/engagement",label:"Row engagement",title:"Row engagement",intro:"Impressions, focus, dwell and selections per launcher row.",icon:"chart"}]}],Gn=Oe.flatMap(s=>s.items),Zn=Oe.flatMap(s=>s.items.filter(n=>!n.path.includes(":")).map(n=>({...n,group:s.label??""})));class Is extends Error{constructor(n,t){super(n),this.status=t,this.name="ApiError"}}const Yn=5*60*1e3;let fn=Date.now();for(const s of["pointerdown","pointermove","keydown","wheel","scroll"])window.addEventListener(s,()=>{fn=Date.now()},{passive:!0});const Jn=()=>Date.now()-fn<Yn,Ls="memby-admin-relogin";function Qn(){try{if(Date.now()-Number(sessionStorage.getItem(Ls)??0)<3e4)return!1;sessionStorage.setItem(Ls,String(Date.now()))}catch{}return window.location.reload(),!0}async function Xe(s,n={}){const t=await fetch(s,{...n,headers:{"Content-Type":"application/json",...Jn()?{"X-Memby-Admin-Active":"1"}:{},...n.headers??{}}});if(t.status===401)throw new Is(Qn()?"Your sign-in has expired. Signing in again…":"Your sign-in has expired. Reload this page to sign in again.",401);if(!t.ok){const r=await t.json().catch(()=>({}));throw new Is(r.error??`Request failed (${t.status})`,t.status)}if(t.status!==204)return await t.json()}function Be(s){const n=new URLSearchParams;for(const[r,a]of Object.entries(s))a==null||a===""||a===!1||n.set(r,String(a));const t=n.toString();return t?`?${t}`:""}const D={get:s=>Xe(s),post:(s,n)=>Xe(s,{method:"POST",body:n===void 0?void 0:JSON.stringify(n)}),put:(s,n)=>Xe(s,{method:"PUT",body:n===void 0?void 0:JSON.stringify(n)}),del:s=>Xe(s,{method:"DELETE"})},Xn=3e4,yn=g.createContext(null);function et({children:s}){var m;const[n,t]=g.useState(),[r,a]=g.useState(!1),[l,i]=g.useState(""),[h,c]=g.useState(""),[o,u]=g.useState(!0),p=g.useRef(0),d=g.useCallback(async()=>{const j=++p.current;try{const y=await D.get("/admin/api/status");if(j!==p.current)return;t(y),a(!0),c("")}catch(y){if(j!==p.current)return;a(!1),c(y instanceof Error?y.message:String(y))}finally{j===p.current&&(i(new Date().toISOString()),u(!1))}},[]),x=g.useCallback(async j=>{var y;await D.post("/admin/api/maintenance",{enabled:j,message:((y=n==null?void 0:n.maintenance)==null?void 0:y.message)??""}),await d()},[d,(m=n==null?void 0:n.maintenance)==null?void 0:m.message]);g.useEffect(()=>{d();let j;const y=()=>{window.clearInterval(j),j=document.hidden?void 0:window.setInterval(()=>void d(),Xn)},v=()=>{y(),document.hidden||d()};return y(),document.addEventListener("visibilitychange",v),()=>{window.clearInterval(j),document.removeEventListener("visibilitychange",v)}},[d]);const f=g.useMemo(()=>{var j;return{status:n,version:(n==null?void 0:n.serverVersion)??"",currentUser:((j=n==null?void 0:n.currentUser)==null?void 0:j.trim())||"Administrator",online:r,checkedAt:l,error:h,loading:o,reload:d,setMaintenance:x}},[n,r,l,h,o,d,x]);return e.jsx(yn.Provider,{value:f,children:s})}function je(){const s=g.useContext(yn);if(!s)throw new Error("useGateway used outside GatewayProvider");return s}function st(s,n){const t=s.label.toLowerCase(),r=s.group.toLowerCase();return t.startsWith(n)?4:t.includes(n)?3:r.includes(n)?2:`${s.title} ${s.intro}`.toLowerCase().includes(n)?1:0}function nt(){const s=ws(),{status:n}=je(),[t,r]=g.useState(!1),[a,l]=g.useState(""),[i,h]=g.useState(0),c=g.useRef(null),o=g.useRef(null),u=g.useMemo(()=>{const d=a.trim().toLowerCase();return[...Zn,...((n==null?void 0:n.requestUsers)??[]).map(f=>({id:`user-${f.id}`,path:`/admin/accounts/${encodeURIComponent(f.id)}`,label:f.username||"Unnamed user",title:`User: ${f.username||"Unnamed user"}`,intro:"Open this users devices and settings.",group:"Users",icon:"people"})),...((n==null?void 0:n.clients)??[]).map(f=>({id:`device-${f.deviceId}`,path:`/admin/devices/${encodeURIComponent(f.deviceId)}`,label:f.deviceName||"Unnamed device",title:`Device: ${f.deviceName||"Unnamed device"}`,intro:`${f.username||"Unknown user"} · ${f.version||"unknown version"}`,group:"Devices",icon:"tv"}))].map((f,m)=>({item:f,rank:d?st(f,d):1,index:m})).filter(f=>f.rank>0).sort((f,m)=>m.rank-f.rank||f.index-m.index).map(({item:f,rank:m})=>({item:f,rank:m}))},[a,n]);g.useEffect(()=>h(0),[a]),g.useEffect(()=>{const d=x=>{var f;(f=c.current)!=null&&f.contains(x.target)||r(!1)};return document.addEventListener("pointerdown",d),()=>document.removeEventListener("pointerdown",d)},[]),g.useEffect(()=>{const d=x=>{var m,j;if(x.key!=="S"||!x.shiftKey||x.ctrlKey||x.metaKey||x.altKey)return;const f=document.activeElement;f&&(f.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(f.tagName))||(x.preventDefault(),(m=o.current)==null||m.focus(),(j=o.current)==null||j.select())};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[]);const p=d=>{var x;r(!1),l(""),(x=o.current)==null||x.blur(),s(d)};return e.jsxs("div",{className:"omni",ref:c,"data-open":t||void 0,children:[e.jsxs("div",{className:"omni-input",children:[e.jsx(se,{name:"search"}),e.jsx("input",{ref:o,type:"search",value:a,placeholder:"Search","aria-label":"Search","aria-expanded":t,onFocus:()=>r(!0),onChange:d=>{l(d.target.value),r(!0)},onKeyDown:d=>{var x;if(d.key==="Escape")l(""),r(!1),(x=o.current)==null||x.blur();else if(d.key==="ArrowDown")d.preventDefault(),h(f=>Math.min(f+1,u.length-1));else if(d.key==="ArrowUp")d.preventDefault(),h(f=>Math.max(f-1,0));else if(d.key==="Enter"){const f=u[i];if(!f)return;d.preventDefault(),p(f.item.path)}}}),e.jsx("span",{className:"omni-key",children:"⇧S"})]}),t?e.jsx("div",{className:"omni-panel",role:"listbox",children:u.length===0?e.jsx("p",{className:"empty",children:"No pages, users or devices match that search."}):u.map((d,x)=>e.jsxs("a",{className:x===i?"omni-item on":"omni-item",href:d.item.path,role:"option","aria-selected":x===i,onPointerEnter:()=>h(x),onClick:f=>{f.preventDefault(),p(d.item.path)},children:[d.item.icon?e.jsx(se,{name:d.item.icon}):null,e.jsxs("span",{children:[e.jsx("b",{children:d.item.label}),e.jsx("small",{children:d.item.intro})]}),e.jsx("span",{className:"omni-group",children:d.item.group})]},d.item.id))}):null]})}const w=s=>(s??0).toLocaleString(),F=s=>s?new Date(s).toLocaleString():"—";function ye(s){if(!s)return"0s";if(s<1e3)return`${Math.round(s)}ms`;const n=Math.round(s/1e3);if(n<60)return`${n}s`;const t=Math.floor(n/60);return t<60?`${t}m ${n%60}s`:`${Math.floor(t/60)}h ${t%60}m`}function _e(s){const n=Math.round(Math.max(0,s??0)/6e4);if(n<=0)return"none";if(n<60)return`${n} min`;const t=Math.floor(n/60),r=n%60;return r===0?t===1?"1 hour":`${t} hours`:`${t}h ${r}m`}function Ne(s){if(!s||s<=0)return"on request only";if(s<60)return`every ${s}s`;const n=Math.round(s/60);if(n<60)return`every ${n} min`;const t=Math.round(n/60);return t<48?t===1?"hourly":`every ${t} hours`:`every ${Math.round(t/24)} days`}function he(s){const n=["B","KB","MB","GB"];let t=Number(s??0),r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${r===0?t:t.toFixed(1)} ${n[r]}`}const wn=s=>String(s??"?").trim().split(/\s+/).slice(0,2).map(n=>n[0]??"").join("").toUpperCase(),is=s=>`${Math.round((s??0)*100)}%`;function be(s){if(!s)return"—";const n=Date.now()-new Date(s).getTime();if(n<0)return"just now";const t=Math.floor(n/1e3);if(t<45)return"just now";const r=Math.floor(t/60);if(r<60)return`${r} min ago`;const a=Math.floor(r/60);if(a<24)return`${a}h ago`;const l=Math.floor(a/24);return l<30?`${l}d ago`:new Date(s).toLocaleDateString()}function ds(s){if(!s)return"—";const n=new Date(s).getTime()-Date.now();if(!Number.isFinite(n))return"—";if(n<=0)return"due now";const t=Math.round(n/1e3);if(t<60)return`in ${t}s`;const r=Math.round(t/60);if(r<60)return`in ${r} min`;const a=Math.round(r/60);return a<24?`in ${a}h`:`in ${Math.round(a/24)}d`}const kn=15*60*1e3,tt=3*60*60*1e3,Ze=s=>!!s&&Date.now()-new Date(s).getTime()<kn;function Ns(s){const n=s?new Date(s).getTime():0;if(!n)return{tone:"bad",label:"never seen"};const t=Date.now()-n;return t<kn?{tone:"ok",label:"active now"}:t<tt?{tone:"idle",label:"seen recently"}:{tone:"bad",label:"not seen lately"}}const Nn=g.createContext(null),qs=50,at=3e4;function it({children:s}){const[n,t]=g.useState([]),[r,a]=g.useState(0),[l,i]=g.useState([]),[h,c]=g.useState(!1),[o,u]=g.useState(""),p=g.useRef(0),d=g.useCallback(async()=>{var y;try{const v=await D.get(`/admin/api/notifications?limit=${qs}`);t(v.events),a(v.unread),i(v.types),p.current=Math.max(p.current,((y=v.events[0])==null?void 0:y.id)??0),u("")}catch(v){u(v instanceof Error?v.message:String(v))}},[]),x=g.useCallback(y=>{p.current=Math.max(p.current,y.id),t(v=>v.some(b=>b.id===y.id)?v:[y,...v].sort((b,A)=>A.id-b.id).slice(0,qs)),y.readAt||a(v=>v+1),i(v=>v.some(b=>b.type===y.type)?v.map(b=>b.type===y.type?{...b,count:b.count+1}:b):[...v,{type:y.type,count:1}])},[]);g.useEffect(()=>{d()},[d]),g.useEffect(()=>{let y=null,v,b=!1;return(()=>{b||(y=new EventSource(`/admin/api/notifications/stream?after=${p.current}`),y.addEventListener("open",()=>{c(!0),window.clearInterval(v),v=void 0}),y.addEventListener("admin",k=>{try{x(JSON.parse(k.data))}catch{}}),y.addEventListener("error",()=>{c(!1),v===void 0&&(v=window.setInterval(()=>void d(),at))}))})(),()=>{b=!0,y==null||y.close(),window.clearInterval(v)}},[x,d]);const f=g.useCallback(async y=>{const v=y.filter(b=>b>0);if(v.length!==0){t(b=>b.map(A=>v.includes(A.id)&&!A.readAt?{...A,readAt:new Date().toISOString()}:A));try{const b=await D.post("/admin/api/notifications/read",{ids:v});a(b.unread)}catch{d()}}},[d]),m=g.useCallback(async()=>{a(0),t(y=>y.map(v=>v.readAt?v:{...v,readAt:new Date().toISOString()}));try{const y=await D.post("/admin/api/notifications/read",{all:!0});a(y.unread)}catch{d()}},[d]),j=g.useMemo(()=>({events:n,unread:r,types:l,connected:h,error:o,markRead:f,markAllRead:m,reload:d}),[n,r,l,h,o,f,m,d]);return e.jsx(Nn.Provider,{value:j,children:s})}function Ss(){const s=g.useContext(Nn);if(!s)throw new Error("useNotifications used outside NotificationProvider");return s}function Sn(s){return s.severity==="error"?"bad":s.severity==="warning"?"warn":"info"}function Mn(s){return s.startsWith("auth.")?"key":s.startsWith("device.")?"tv":s.startsWith("admin.")?"shield":s.startsWith("task.")?"clock":s.startsWith("integration.")?"plug":s.startsWith("library.")?"library":s.startsWith("emby.")?"globe":s.startsWith("server.")?"power":"bell"}function Ds(s){return{"auth.login":"Signed in","auth.login_failed":"Sign-in refused","auth.logout":"Signed out","device.registered":"New device","device.removed":"Device removed","device.renamed":"Device renamed","admin.sign_in":"Admin sign-in","server.started":"Server started","server.maintenance":"Maintenance","task.completed":"Task finished","task.failed":"Task failed","integration.failed":"Integration failed","integration.test":"Integration test","library.sync":"Library sync","emby.unreachable":"Emby unreachable","emby.recovered":"Emby recovered"}[s]??s.replace(/[._]/g," ")}const Fs=99;function rt(){const{events:s,unread:n,connected:t,markRead:r,markAllRead:a}=Ss(),[l,i]=g.useState(!1),h=g.useRef(null);return g.useEffect(()=>{const c=u=>{var p;(p=h.current)!=null&&p.contains(u.target)||i(!1)},o=u=>{u.key==="Escape"&&i(!1)};return document.addEventListener("pointerdown",c),document.addEventListener("keydown",o),()=>{document.removeEventListener("pointerdown",c),document.removeEventListener("keydown",o)}},[]),g.useEffect(()=>{if(!l)return;const c=s.filter(o=>!o.readAt).map(o=>o.id);c.length>0&&r(c)},[l]),e.jsxs("div",{className:"bell",ref:h,"data-open":l||void 0,children:[e.jsxs("button",{type:"button",className:"bell-button","aria-label":n>0?`Activity, ${n} unread`:"Activity","aria-expanded":l,onClick:()=>i(c=>!c),children:[e.jsx(se,{name:"bell"}),n>0?e.jsx("span",{className:"bell-badge",children:n>Fs?`${Fs}+`:n}):null]}),l?e.jsxs("div",{className:"bell-panel",children:[e.jsxs("div",{className:"bell-head",children:[e.jsx("b",{children:"Activity"}),e.jsxs("div",{className:"row tight",children:[t?null:e.jsx("span",{className:"tag","data-tone":"warn",children:"reconnecting"}),n>0?e.jsx("button",{type:"button","data-variant":"quiet","data-size":"sm",onClick:()=>void a(),children:"Mark all read"}):null]})]}),e.jsx("div",{className:"bell-list",children:s.length===0?e.jsx("p",{className:"empty",children:"Nothing has happened yet."}):s.slice(0,20).map(c=>{const o=e.jsxs(e.Fragment,{children:[e.jsx(Qe,{name:Mn(c.type),tone:Sn(c)}),e.jsxs("span",{className:"bell-body",children:[e.jsx("b",{children:c.title||c.type}),c.summary?e.jsx("p",{children:c.summary}):null,e.jsx("time",{dateTime:c.occurredAt,children:be(c.occurredAt)})]})]});return c.link?e.jsx(Z,{className:"bell-item","data-unread":!c.readAt||void 0,to:c.link,onClick:()=>i(!1),children:o},c.id):e.jsx("div",{className:"bell-item","data-unread":!c.readAt||void 0,children:o},c.id)})}),e.jsx("div",{className:"bell-foot",children:e.jsx(Z,{to:"/admin/activity",onClick:()=>i(!1),children:"All activity"})})]}):null]})}function J(s,n={}){const{pollMs:t,enabled:r=!0}=n,[a,l]=g.useState(),[i,h]=g.useState(""),[c,o]=g.useState(r),[u,p]=g.useState(!1),d=g.useRef(0),x=g.useRef(!1),f=g.useCallback(async()=>{if(!r)return;const m=++d.current;x.current&&p(!0);try{const j=await D.get(s);if(m!==d.current)return;l(j),h(""),x.current=!0}catch(j){if(m!==d.current)return;h(j instanceof Error?j.message:String(j))}finally{m===d.current&&(o(!1),p(!1))}},[s,r]);return g.useEffect(()=>(x.current=!1,o(!0),f(),()=>{d.current+=1}),[f]),g.useEffect(()=>{if(!t||!r)return;let m;const j=()=>{window.clearInterval(m),m=document.hidden?void 0:window.setInterval(()=>void f(),t)},y=()=>{j(),document.hidden||f()};return j(),document.addEventListener("visibilitychange",y),()=>{window.clearInterval(m),document.removeEventListener("visibilitychange",y)}},[t,r,f]),{data:a,error:i,loading:c,refreshing:u,reload:f,set:l}}function ne(){const[s,n]=g.useState(null),t=g.useRef(!0);g.useEffect(()=>()=>{t.current=!1},[]);const r=g.useCallback(async(a,l)=>{n(a);try{return await l(),!0}finally{t.current&&n(null)}},[]);return{busy:s,run:r}}const Os="Memby";function lt(s){g.useEffect(()=>{const n=s.trim();document.title=n?`${n} | ${Os}`:Os},[s])}function U({title:s,intro:n,actions:t,crumbs:r,icon:a}){var h;const l=ks(),i=a??((h=Gn.find(c=>vs({path:c.path,end:!0},l.pathname)))==null?void 0:h.icon);return lt(s),e.jsxs("header",{className:"page-head",children:[r?e.jsx("nav",{className:"crumbs",children:r}):null,e.jsxs("div",{className:"page-head-row",children:[e.jsxs("div",{className:"page-head-title",children:[i?e.jsx("span",{className:"page-head-icon","aria-hidden":"true",children:e.jsx(se,{name:i})}):null,e.jsxs("div",{className:"page-head-text",children:[e.jsx("h1",{children:s}),n?e.jsx("p",{children:n}):null]})]}),t?e.jsx("div",{className:"page-head-actions",children:t}):null]})]})}function C({title:s,intro:n,icon:t,tone:r,actions:a,footer:l,children:i}){return e.jsxs("section",{className:"card",children:[s?e.jsxs("div",{className:"card-head",children:[t?e.jsx(Qe,{name:t,tone:r}):null,e.jsxs("div",{className:"card-head-text",children:[e.jsx("h2",{children:s}),n?e.jsx("p",{children:n}):null]}),a?e.jsx("div",{className:"card-head-actions",children:a}):null]}):null,i,l?e.jsx("div",{className:"card-foot",children:l}):null]})}function xe({cols:s,children:n}){return e.jsx("div",{className:"grid","data-cols":s,children:n})}function ae({tiles:s}){return e.jsx("div",{className:"tiles",children:s.map(n=>e.jsxs("div",{className:"tile",children:[n.icon?e.jsx(Qe,{name:n.icon,tone:n.tone}):null,e.jsx("b",{className:n.small?"small":void 0,children:n.value}),e.jsx("span",{children:n.label})]},n.label))})}function N({children:s,tone:n}){return e.jsx("span",{className:"tag","data-tone":n,children:s})}function ce({children:s,tone:n}){return e.jsx("span",{className:"chip","data-tone":n,children:s})}function ee({children:s}){return e.jsx("p",{className:"empty",children:s})}function Y({columns:s,children:n}){return e.jsx("tr",{children:e.jsx("td",{colSpan:s,className:"muted",children:e.jsx("p",{className:"empty",children:n})})})}function pe({children:s,tone:n}){return e.jsx("p",{className:"note","data-tone":n,children:s})}function $({children:s,onClick:n,variant:t,size:r,disabled:a,busy:l,icon:i,type:h="button",title:c}){return e.jsxs("button",{type:h,className:"","data-variant":t,"data-size":r,disabled:a||l,onClick:n,title:c,children:[l?e.jsx("span",{className:"spinner"}):i?e.jsx(se,{name:i}):null,s]})}function q({label:s,hint:n,children:t,grow:r}){return e.jsxs("label",{className:r?"field grow":"field",children:[e.jsx("span",{children:s}),t,n?e.jsx("small",{children:n}):null]})}function G({label:s,hint:n,checked:t,onChange:r,disabled:a}){return e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:t,disabled:a,onChange:l=>r(l.target.checked)}),e.jsx("span",{className:"switch"}),e.jsxs("span",{className:"check-body",children:[e.jsx("b",{children:s}),n?e.jsx("p",{children:n}):null]})]})}function Ye({value:s,options:n,onChange:t}){return e.jsx("div",{className:"segments",role:"group",children:n.map(r=>e.jsx("button",{type:"button","aria-pressed":r.value===s,onClick:()=>t(r.value),children:r.label},String(r.value)))})}function K({children:s}){return e.jsx("div",{className:"table-wrap",children:s})}function hs({data:s,labelOf:n,valueOf:t,toneOf:r,title:a}){if(s.length===0)return e.jsx(ee,{children:"Nothing in this window."});const l=s.map(h=>t(h)),i=Math.max(1,...l);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"bars",children:s.map((h,c)=>{const o=t(h);return e.jsx("div",{className:"bar","data-tone":r==null?void 0:r(h),"data-empty":o===0||void 0,style:{height:`${Math.max(2,o/i*100)}%`},title:a?a(h):`${n(h,c)}: ${o}`},c)})}),e.jsxs("div",{className:"bars-axis",children:[e.jsx("span",{children:n(s[0],0)}),e.jsx("span",{children:n(s[s.length-1],s.length-1)})]})]})}function Cn({value:s,total:n,tone:t}){const r=n>0?Math.min(1,s/n):0;return e.jsx("div",{className:"meter","data-tone":t,children:e.jsx("div",{style:{width:`${r*100}%`}})})}function _({message:s,onDismiss:n}){return s?e.jsxs("div",{className:"banner",role:"alert",children:[e.jsx(se,{name:"alert"}),e.jsx("span",{children:s}),n?e.jsx("button",{type:"button",onClick:n,"aria-label":"Dismiss",children:e.jsx(se,{name:"close"})}):null]}):null}function V({rows:s=3}){return e.jsxs("div",{className:"loading-page","aria-busy":"true","aria-label":"Loading",children:[e.jsxs("div",{className:"loading-heading",children:[e.jsx("span",{className:"skeleton"}),e.jsx("span",{className:"skeleton"})]}),e.jsx("div",{className:"loading-tiles",children:Array.from({length:4},(n,t)=>e.jsx("span",{className:"skeleton"},t))}),Array.from({length:s},(n,t)=>e.jsxs("section",{className:"loading-card",children:[e.jsx("span",{className:"skeleton"}),e.jsx("span",{className:"skeleton"}),e.jsx("span",{className:"skeleton"})]},t))]})}function ke({title:s,body:n,confirmLabel:t="Confirm",destructive:r,busy:a,onConfirm:l,onCancel:i}){const h=g.useId(),c=g.useRef(null);return g.useEffect(()=>{var u;(u=c.current)==null||u.focus();const o=p=>{p.key==="Escape"&&i()};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[i]),e.jsx("div",{className:"scrim",onPointerDown:o=>o.target===o.currentTarget&&i(),children:e.jsxs("div",{className:"dialog",role:"dialog","aria-modal":"true","aria-labelledby":h,ref:c,tabIndex:-1,children:[e.jsx("h2",{id:h,children:s}),e.jsx("p",{children:n}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx($,{onClick:i,variant:"quiet",children:"Cancel"}),e.jsx($,{onClick:l,variant:r?"danger":"primary",busy:a,children:t})]})]})})}function Ue({rows:s}){return e.jsx("div",{className:"kv",children:s.map(n=>e.jsxs("div",{className:"kv-row",children:[e.jsx("span",{children:n.label}),e.jsx("span",{children:n.value})]},n.label))})}function xs({children:s,aside:n}){return e.jsxs("h4",{className:"subhead",children:[e.jsx("span",{children:s}),n?e.jsx("small",{children:n}):null]})}function Ms({tiles:s}){return e.jsx("div",{className:"tiles plain",children:s.map(n=>e.jsxs("div",{className:"tile",children:[e.jsx("b",{className:n.small?"small":void 0,children:n.value}),e.jsx("span",{children:n.label})]},n.label))})}function ot({open:s,onNavigate:n}){const{unread:t}=Ss(),r=ks(),[a,l]=g.useState(()=>{try{return JSON.parse(localStorage.getItem("memby-admin-nav")??"{}")}catch{return{}}}),i=c=>{try{localStorage.setItem("memby-admin-nav",JSON.stringify(c))}catch{}};g.useEffect(()=>{const c=Oe.find(o=>o.items.some(u=>vs({path:u.path,end:!0},r.pathname)));c&&l(o=>{const u={...o};return Oe.forEach(p=>{p.collapsible!==!1&&(u[p.id]=p.id!==c.id)}),i(u),u})},[r.pathname]);const h=(c,o=!1)=>{l(u=>{const p={...u},d=!(u[c]??o);return Oe.forEach(x=>{x.collapsible!==!1&&(p[x.id]=x.id===c?d:!0)}),i(p),p})};return e.jsx("nav",{className:"rail",id:"rail","data-open":s||void 0,"aria-label":"Console sections",children:Oe.map(c=>{const o=c.items.filter(x=>!x.hidden);if(o.length===0)return null;const u=o.some(x=>vs({path:x.path,end:!0},r.pathname)),p=c.collapsible!==!1,d=u||!p||!(a[c.id]??c.defaultCollapsed??!1);return e.jsxs("div",{className:"rail-group",children:[c.label&&p?e.jsxs("button",{type:"button",className:"rail-head","aria-expanded":d,onClick:()=>h(c.id,c.defaultCollapsed),children:[c.label,e.jsx(se,{name:"caret",className:"ico caret"})]}):c.label?e.jsx("div",{className:"rail-head rail-head-static",children:c.label}):null,d?o.map(x=>e.jsx(xn,{to:x.path,end:x.path==="/admin",onClick:n,className:({isActive:f})=>f?"on":"","aria-current":void 0,children:({isActive:f})=>e.jsxs("span",{style:{display:"contents"},ref:m=>{const j=m==null?void 0:m.parentElement;j&&(f?j.setAttribute("aria-current","page"):j.removeAttribute("aria-current"))},children:[x.icon?e.jsx(se,{name:x.icon}):null,x.label,x.badge==="notifications"&&t>0?e.jsx("span",{className:"rail-badge",children:t>99?"99+":t}):null]})},x.id)):null]},c.id)})})}function ct(){var k,I,E;const{version:s,currentUser:n,online:t,loading:r,status:a,setMaintenance:l}=je(),[i,h]=g.useState(!1),[c,o]=g.useState(!1),[u,p]=g.useState(!1),[d,x]=g.useState(!1),f=ks(),m=!!((k=a==null?void 0:a.maintenance)!=null&&k.enabled),j=!!((I=a==null?void 0:a.quietTime)!=null&&I.active),y=g.useRef(null),v=((E=Array.from(n.trim())[0])==null?void 0:E.toLocaleUpperCase("en-NZ"))||"A",b=a&&t&&!m&&!j?"ok":a||!r?"bad":"checking",A=async()=>{if(!(u||!a)){p(!0);try{await l(!m)}finally{p(!1)}}};return g.useEffect(()=>h(!1),[f.pathname]),g.useEffect(()=>{if(!c)return;const R=X=>{var le;(le=y.current)!=null&&le.contains(X.target)||o(!1)},L=X=>{X.key==="Escape"&&o(!1)};return document.addEventListener("mousedown",R),window.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",R),window.removeEventListener("keydown",L)}},[c]),g.useEffect(()=>{if(!i)return;const R=document.body.style.overflow;document.body.style.overflow="hidden";const L=X=>{X.key==="Escape"&&h(!1)};return window.addEventListener("keydown",L),()=>{document.body.style.overflow=R,window.removeEventListener("keydown",L)}},[i]),e.jsxs(e.Fragment,{children:[e.jsx("a",{className:"skip",href:"#main",children:"Skip to content"}),e.jsxs("header",{className:"topbar",children:[e.jsxs("a",{className:"topbar-brand",href:"/admin",children:[e.jsx("span",{className:"brand-mark","aria-hidden":"true",children:"M"}),e.jsx("span",{className:"brand-word",children:"Memby Gateway"})]}),e.jsx("button",{type:"button",className:"rail-toggle","aria-label":"Sections","aria-expanded":i,"aria-controls":"rail",onClick:()=>h(R=>!R),children:e.jsx(se,{name:"menu"})}),e.jsx("div",{className:"topbar-spacer"}),e.jsxs("div",{className:"topbar-tools",children:[e.jsx(nt,{}),e.jsxs("span",{className:"topbar-version",children:["gateway ",s||"unknown"]}),e.jsx("button",{type:"button",className:"topbar-status","data-tone":b,"aria-pressed":m,disabled:!a||!t||u||j,title:a?j?"Memby quiet time is active":m?"Bring Memby back online":t?"Take Memby offline":"Memby is not responding":"Checking Memby status","aria-label":j?"Memby quiet time is active":m?"Memby is offline. Bring it online":a&&t?"Memby is online. Take it offline":r?"Checking Memby status":"Memby is not responding",onClick:()=>m?void A():x(!0),children:e.jsx("span",{className:"dot","aria-hidden":"true"})}),e.jsx(rt,{}),e.jsxs("div",{className:"account-menu","data-open":c||void 0,ref:y,children:[e.jsxs("button",{type:"button",className:"account-trigger","aria-haspopup":"menu","aria-expanded":c,"aria-label":`Signed in as ${n}`,onClick:()=>o(R=>!R),children:[e.jsx("span",{className:"account-avatar","aria-hidden":"true",children:v}),e.jsx("span",{className:"account-name",children:n}),e.jsx(se,{name:"caret",className:"ico account-caret"})]}),c?e.jsxs("div",{className:"account-panel",role:"menu",children:[e.jsxs("div",{className:"account-identity",children:[e.jsx("span",{className:"account-avatar account-avatar-large","aria-hidden":"true",children:v}),e.jsxs("span",{children:[e.jsx("small",{children:"Signed in as"}),e.jsx("b",{children:n})]})]}),e.jsxs(xn,{to:"/admin/settings",role:"menuitem",onClick:()=>o(!1),children:[e.jsx(se,{name:"sliders"}),"Gateway settings"]}),e.jsx("form",{method:"post",action:"/admin/logout",children:e.jsxs("button",{type:"submit",role:"menuitem",children:[e.jsx(se,{name:"logout"}),"Log out"]})})]}):null]})]})]}),i?e.jsx("button",{type:"button",className:"rail-scrim","aria-label":"Close sections",onClick:()=>h(!1)}):null,e.jsx(ot,{open:i,onNavigate:()=>h(!1)}),e.jsx("main",{className:"page",id:"main",children:e.jsx(Pn,{})}),d?e.jsx(ke,{title:"Take Memby offline?",body:"Every television will stop working immediately. Viewers will see the maintenance message configured on the Maintenance page, while this console remains available.",confirmLabel:"Go offline",destructive:!0,busy:u,onConfirm:()=>{x(!1),A()},onCancel:()=>x(!1)}):null]})}const $n=g.createContext(null),dt=5e3;function ht({children:s}){const[n,t]=g.useState([]),r=g.useRef(1),a=g.useCallback(c=>{t(o=>o.filter(u=>u.id!==c))},[]),l=g.useCallback((c,o="ok")=>{const u=r.current++;t(p=>[...p,{id:u,message:c,tone:o}]),window.setTimeout(()=>a(u),dt)},[a]),i=g.useCallback(async(c,o)=>{try{const u=await c();return o&&l(o,"ok"),u}catch(u){l(u instanceof Error?u.message:String(u),"bad");return}},[l]),h=g.useMemo(()=>({show:l,wrap:i}),[l,i]);return e.jsxs($n.Provider,{value:h,children:[s,e.jsx("div",{className:"toasts",role:"status","aria-live":"polite",children:n.map(c=>e.jsxs("div",{className:"toast","data-tone":c.tone,children:[e.jsx(se,{name:c.tone==="bad"?"alert":"check"}),e.jsx("span",{children:c.message}),e.jsx("button",{type:"button",onClick:()=>a(c.id),"aria-label":"Dismiss",children:e.jsx(se,{name:"close"})})]},c.id))})]})}function ie(){const s=g.useContext($n);if(!s)throw new Error("useToast used outside ToastProvider");return s}const Ps={ok:"ok",watch:"warn",bad:"bad"},ut={ok:"Healthy",watch:"Worth watching",bad:"Needs attention"};function Tn({health:s,compact:n}){const t=s.notes??[];return e.jsxs("div",{className:"verdict","data-tone":Ps[s.level]??"ok",children:[e.jsxs("div",{className:"verdict-head",children:[e.jsx(se,{name:s.level==="ok"?"check":"alert"}),e.jsx("b",{children:ut[s.level]??"Unknown"}),e.jsx("span",{children:s.summary})]}),n||t.length===0?null:e.jsx("ul",{className:"verdict-notes",children:t.map((r,a)=>e.jsxs("li",{children:[e.jsx(N,{tone:Ps[r.level]??"note",children:r.area}),e.jsx("span",{children:r.message})]},`${r.area}-${a}`))})]})}function rs(s,n){switch(s.direction){case"rising":return`rising ${n(Math.abs(s.perHour))} an hour`;case"falling":return`falling ${n(Math.abs(s.perHour))} an hour`;case"steady":return"steady";default:return"gathering history"}}function Rn(s){if(!s||s<60)return`${Math.max(0,Math.round(s))}s`;const n=Math.floor(s/60);if(n<60)return`${n} min`;const t=Math.floor(n/60);return t<48?`${t}h ${n%60}m`:`${Math.floor(t/24)} days`}function mt(){var y,v,b,A,k,I;const{status:s,error:n,loading:t}=je(),r=J("/admin/api/runtime",{pollMs:3e4}),a=J("/admin/api/views",{pollMs:6e4});if(t||!s)return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Overview",intro:"What the gateway is doing right now."}),e.jsx(_,{message:n}),e.jsx(V,{})]});const l=s.features??{features:[],revision:0,safeMode:!1},i=l.features??[],h=s.clients??[],c=h.filter(E=>Ze(E.lastSeen)).length,o=s.updatePolicy??{},u=!!o.minimumVersion&&o.minimumVersion===o.latestVersion,p=s.playbackPolicy,d=s.mdblist,x=s.forYou,f=(s.runs??[]).slice(0,5),m=r.data,j=m?m.memory.memoryLimit>0&&m.memory.memoryLimit<Number.MAX_SAFE_INTEGER:!1;return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Overview",intro:"What the gateway is doing right now."}),e.jsx(_,{message:n}),e.jsx(ae,{tiles:[{label:"items in the library",value:w(s.library.total),icon:"library",tone:"data"},{label:"people signed in",value:w((s.requestUsers??[]).length),icon:"people",tone:"note"},{label:`devices · ${c} active now`,value:w(h.length),icon:"tv",tone:"info"},{label:`visits today · ${((y=a.data)==null?void 0:y.lastWeek.visits)??0} this time last week`,value:w((v=a.data)==null?void 0:v.today.visits),icon:"overview",tone:"data"},{label:`viewers today · ${((b=a.data)==null?void 0:b.lastWeek.viewers)??0} this time last week`,value:w((A=a.data)==null?void 0:A.today.viewers),icon:"people",tone:"note"},{label:"optional features on",value:`${i.filter(E=>E.enabled).length} / ${i.length}`,icon:"sliders",tone:"ok"},{label:"last import",value:F(s.library.lastSynced),small:!0,icon:"clock"}]}),e.jsxs(xe,{cols:"2",children:[e.jsx(C,{title:"What televisions are being told",intro:"The answers the gateway is giving every set right now.",icon:"tv",tone:"info",children:e.jsx(Ue,{rows:[{label:"Availability",value:(k=s.maintenance)!=null&&k.enabled?e.jsx(N,{tone:"bad",children:"offline for maintenance"}):(I=s.quietTime)!=null&&I.active?e.jsx(N,{tone:"warn",children:"quiet time active"}):e.jsx(N,{tone:"ok",children:"online"})},{label:"Feature control plane",value:l.safeMode?e.jsx(N,{tone:"warn",children:"safe mode · optional features off"}):e.jsxs(N,{tone:"ok",children:["revision r",w(l.revision)]})},{label:"App update prompt",value:o.enabled?e.jsxs(N,{tone:u?"warn":"ok",children:[u?"required · ":"optional · ",o.latestVersion]}):e.jsx(N,{children:"off"})},{label:"Catalogue import",value:s.syncRunning?e.jsx(N,{tone:"warn",children:"running"}):e.jsxs(N,{children:["every ",s.syncEvery]})},{label:"Playback preroll",value:(p==null?void 0:p.prerollEnabled)===!1?e.jsx(N,{children:"off"}):e.jsxs(N,{tone:"ok",children:[((p==null?void 0:p.prerollDurationMs)??6500)/1e3,"s"]})}]})}),e.jsx(C,{title:"Services",intro:"The services this gateway leans on, and whether they answered.",icon:"wrench",tone:"note",actions:e.jsx(Z,{to:"/admin/integrations",children:"Integrations"}),children:e.jsx(Ue,{rows:[{label:"Movies (Radarr)",value:s.radarrReady?e.jsx(N,{tone:"ok",children:"ready"}):e.jsx(N,{children:"not configured"})},{label:"Series (Sonarr)",value:s.sonarrReady?e.jsx(N,{tone:"ok",children:"ready"}):e.jsx(N,{children:"not configured"})},{label:"MDBList ratings",value:d!=null&&d.enabled?e.jsxs(N,{tone:"ok",children:[w(d.cachedTitles)," titles stored"]}):e.jsx(N,{children:d!=null&&d.apiKeyConfigured?"off · key saved":"off · no key"})},{label:"For You pools",value:s.forYouRunning?e.jsx(N,{tone:"warn",children:"rebuilding"}):e.jsxs(N,{children:[w((x==null?void 0:x.candidates)??0)," ranked candidates"]})},{label:"Recommendation profiles",value:e.jsx("span",{className:"mono",children:w((x==null?void 0:x.profiles)??0)})}]})})]}),e.jsxs(xe,{cols:"2",children:[e.jsx(C,{title:"Latest imports",intro:"The last few catalogue synchronisations.",icon:"sync",tone:"data",actions:e.jsx(Z,{to:"/admin/imports",children:"All imports"}),children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Started"}),e.jsx("th",{children:"Kind"}),e.jsx("th",{children:"Status"}),e.jsx("th",{className:"num",children:"Written"})]})}),e.jsx("tbody",{children:f.length===0?e.jsx(Y,{columns:4,children:"No imports have run yet."}):f.map(E=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:F(E.startedAt)}),e.jsx("td",{children:E.kind}),e.jsx("td",{children:e.jsx(N,{tone:E.status==="success"?"ok":E.status==="running"?"warn":"bad",children:E.status})}),e.jsx("td",{className:"num",children:w(E.itemsUpserted)})]},E.id||E.startedAt))})]})})}),e.jsx(C,{title:"Process",intro:"The container the gateway is served from.",icon:"chip",tone:"info",actions:e.jsx(Z,{to:"/admin/runtime",children:e.jsx($,{size:"sm",variant:"quiet",icon:"external",children:"Runtime details"})}),children:m?e.jsxs(e.Fragment,{children:[e.jsx(Tn,{health:m.health,compact:!0}),e.jsx(Ms,{tiles:[{label:`heap used · ${rs(m.heapTrend,he)}`,value:he(m.memory.heapInuse)},{label:"of the process limit",value:j?`${(m.memory.heapShare*100).toFixed(1)}%`:"no limit"},{label:`goroutines · ${rs(m.goroutineTrend,E=>w(Math.round(E)))}`,value:w(m.goroutines)},{label:"running for",value:Rn(m.uptimeSeconds)}]}),e.jsxs("p",{className:"hint",children:["Heap in use is what the gateway is holding;"," ",he(m.memory.sys)," is reserved from the operating system on its behalf, which is always larger and is not a leak.",j?` The limit is ${he(m.memory.memoryLimit)}${m.memory.configuredLimit?" (GOMEMLIMIT)":""}.`:" No memory limit is set."]})]}):e.jsx("p",{className:"hint",children:"Reading process statistics…"})})]})]})}const pt=[{value:1,label:"Today"},{value:7,label:"7 days"},{value:30,label:"30 days"}];function xt(){const{unread:s,connected:n,markAllRead:t,reload:r}=Ss(),[a,l]=g.useState(7),[i,h]=g.useState(""),[c,o]=g.useState(""),[u,p]=g.useState(!1),[d,x]=g.useState(0),f=100,m=g.useMemo(()=>`/admin/api/notifications${Be({days:a,type:i,severity:c,unread:u,limit:f,offset:d*f})}`,[a,i,c,u,d]),{data:j,error:y,loading:v,reload:b}=J(m),A=async()=>{await t(),await b()};return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Activity",intro:"Every administrative event the gateway has published: sign-ins, devices, scheduled tasks, integrations and the server itself. The same feed the bell and every integration read from.",actions:s>0?e.jsx($,{onClick:()=>void A(),icon:"check",children:"Mark all read"}):void 0}),e.jsx(_,{message:y}),e.jsx(ae,{tiles:[{label:"Events in window",value:w((j==null?void 0:j.total)??0),icon:"bell",tone:"info"},{label:"Unread",value:w(s),icon:"alert",tone:s>0?"warn":void 0},{label:"Kinds seen",value:w((j==null?void 0:j.types.length)??0),icon:"list",tone:"note"},{label:"Live feed",value:n?"connected":"reconnecting",small:!0,icon:"pulse",tone:n?"ok":"warn"}]}),e.jsxs("div",{className:"filters",children:[e.jsx(q,{label:"Window",children:e.jsx(Ye,{value:a,options:pt.map(k=>({value:k.value,label:k.label})),onChange:k=>{l(k),x(0)}})}),e.jsx(q,{label:"Kind",children:e.jsxs("select",{value:i,onChange:k=>{h(k.target.value),x(0)},children:[e.jsx("option",{value:"",children:"Everything"}),((j==null?void 0:j.types)??[]).map(k=>e.jsxs("option",{value:k.type,children:[Ds(k.type)," (",k.count,")"]},k.type))]})}),e.jsx(q,{label:"Severity",children:e.jsxs("select",{value:c,onChange:k=>{o(k.target.value),x(0)},children:[e.jsx("option",{value:"",children:"Any"}),e.jsx("option",{value:"info",children:"Information"}),e.jsx("option",{value:"warning",children:"Warning"}),e.jsx("option",{value:"error",children:"Error"})]})}),e.jsx(q,{label:"Read state",children:e.jsxs("select",{value:u?"unread":"",onChange:k=>{p(k.target.value==="unread"),x(0)},children:[e.jsx("option",{value:"",children:"All"}),e.jsx("option",{value:"unread",children:"Unread only"})]})}),e.jsx("div",{className:"filter-actions",children:e.jsx($,{variant:"quiet",size:"sm",icon:"refresh",onClick:()=>{b(),r()},children:"Refresh"})})]}),v?e.jsx(V,{}):e.jsx(C,{title:"Events",icon:"bell",tone:"info",footer:((j==null?void 0:j.total)??0)>f?e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",disabled:d===0,onClick:()=>x(d-1),children:"Newer"}),e.jsx($,{size:"sm",disabled:(d+1)*f>=((j==null?void 0:j.total)??0),onClick:()=>x(d+1),children:"Older"})]}):void 0,children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"When"}),e.jsx("th",{children:"Kind"}),e.jsx("th",{children:"What happened"}),e.jsx("th",{children:"Who"}),e.jsx("th",{children:"What"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:((j==null?void 0:j.events.length)??0)===0?e.jsx(Y,{columns:6,children:"Nothing has happened in this window."}):j==null?void 0:j.events.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:F(k.occurredAt),children:be(k.occurredAt)}),e.jsx("td",{className:"nowrap",children:e.jsxs("span",{className:"row tight",children:[e.jsx(Qe,{name:Mn(k.type),tone:Sn(k)}),Ds(k.type)]})}),e.jsxs("td",{children:[e.jsx("b",{children:k.title}),k.summary?e.jsx("div",{className:"muted",children:k.summary}):null]}),e.jsx("td",{className:"muted nowrap",children:k.actor||"—"}),e.jsx("td",{className:"muted nowrap",children:k.target||"—"}),e.jsxs("td",{className:"nowrap",children:[k.readAt?null:e.jsx(N,{tone:"ok",children:"new"}),k.link?e.jsx(Z,{className:"table-row-link",to:k.link,children:"Open"}):null]})]},k.id))})]})})})]})}function _s(s){const n=s?new Date(s).getTime():0;return Number.isFinite(n)?n:0}function Us(){return e.jsx("span",{className:"muted",title:"No Tracearr sessions matched to this person",children:"—"})}function jt(){const{data:s,error:n,loading:t}=J("/admin/api/accounts",{pollMs:6e4}),r=(s==null?void 0:s.accounts)??[],a=r.flatMap(u=>u.devices??[]),l=r.filter(u=>{var p;return(p=u.recommendations)==null?void 0:p.completed}).length,i=r.filter(u=>{var p,d;return((p=u.recommendations)==null?void 0:p.prompted)&&!((d=u.recommendations)!=null&&d.completed)}).length,h=r.filter(u=>{var p;return(p=u.watchTime)==null?void 0:p.matched}),c=h.reduce((u,p)=>{var d;return u+(((d=p.watchTime)==null?void 0:d.weekMs)??0)},0),o=[...r].sort((u,p)=>_s(p.lastSeen)-_s(u.lastSeen));return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Users",intro:"Who uses Memby, and which devices they are signed in to."}),e.jsx(_,{message:n}),t?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"Memby users",value:w(r.length),icon:"people",tone:"note"},{label:"signed-in devices",value:w(a.length),icon:"tv",tone:"info"},{label:"active in the last 15 mins",value:w(a.filter(u=>Ze(u.lastSeen)).length),icon:"pulse",tone:"ok"},{label:"recommendation setups completed",value:w(l),icon:"check",tone:"ok"},{label:"setup prompts queued",value:w(i),icon:"sparkle",tone:"note"},...h.length?[{label:"watch time this week",value:_e(c),icon:"pulse",tone:"data"}]:[]]}),e.jsx(C,{title:"Users",icon:"people",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"User"}),e.jsx("th",{children:"Short name"}),e.jsx("th",{className:"num",children:"Devices"}),e.jsx("th",{className:"num",children:"This week"}),e.jsx("th",{className:"num",children:"This month"}),e.jsx("th",{children:"Recommendations"}),e.jsx("th",{children:"Last seen"})]})}),e.jsx("tbody",{children:o.length===0?e.jsx(Y,{columns:7,children:"No one has signed in to Memby yet. Emby-only accounts are intentionally not listed here."}):o.map(u=>{var j,y;const p=u.devices??[],d=p.filter(v=>Ze(v.lastSeen)).length,x=(j=u.recommendations)!=null&&j.completed?{label:"personalised",tone:"ok"}:(y=u.recommendations)!=null&&y.prompted?{label:"prompt queued",tone:"warn"}:{label:"not invited",tone:void 0},f=Ns(u.lastSeen),m=u.watchTime;return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"row tight",children:[e.jsx("span",{className:"dot-state","data-tone":f.tone,title:f.label}),e.jsx("span",{className:"avatar",children:u.initials||wn(u.username)}),e.jsx(Z,{className:"table-row-link",to:`/admin/accounts/${encodeURIComponent(u.id)}`,children:u.username||"Unnamed user"})]})}),e.jsx("td",{children:u.shortName||e.jsx("span",{className:"muted",title:"Memby greets them by their account name",children:"account name"})}),e.jsxs("td",{className:"num",children:[w(p.length),d?e.jsxs("span",{className:"table-sub",children:[w(d)," active now"]}):null]}),e.jsx("td",{className:"num",children:m!=null&&m.matched?_e(m.weekMs):e.jsx(Us,{})}),e.jsx("td",{className:"num muted",children:m!=null&&m.matched?_e(m.monthMs):e.jsx(Us,{})}),e.jsx("td",{children:e.jsx(N,{tone:x.tone,children:x.label})}),e.jsx("td",{className:"nowrap muted",title:F(u.lastSeen),children:be(u.lastSeen)})]},u.id)})})]})})})]})]})}function js(s){const n=String(s??"").replace("#","");return n.length!==8?`#${n}`:`#${n.slice(2)}${n.slice(0,2)}`}function gt(){var z,oe,we,Te,Re,ge;const{userId:s=""}=We(),n=ws(),{wrap:t}=ie(),{busy:r,run:a}=ne(),l=`/admin/api/accounts/${encodeURIComponent(s)}`,{data:i,error:h,loading:c,reload:o}=J("/admin/api/accounts",{pollMs:3e4}),[u,p]=g.useState(null),[d,x]=g.useState(null),[f,m]=g.useState(null),[j,y]=g.useState(null),[v,b]=g.useState(null),[A,k]=g.useState(null),I=J(`${l}/viewers`),E=((i==null?void 0:i.accounts)??[]).find(T=>T.id===s),R=(((z=I.data)==null?void 0:z.viewers)??[]).filter(T=>T.kind!=="main"),L=!!((oe=I.data)!=null&&oe.enabled)&&R.length<(((we=I.data)==null?void 0:we.maxShadowViewers)??0),X=(i==null?void 0:i.catalogue)??[],le=(i==null?void 0:i.themes)??[];g.useEffect(()=>{var T;u===null&&E&&p({...((T=E.settings)==null?void 0:T.preferences)??{}})},[E,u]),g.useEffect(()=>{f===null&&E&&m({...E.notifications})},[E,f]),g.useEffect(()=>{if(d!==null||!E)return;const T=E.themes??[];x(T.length===0?le.map(P=>P.id):T)},[E,d,le]);const ue=g.useMemo(()=>{const T=[];for(const P of X){let de=T.find(me=>me.name===P.area);de||T.push(de={name:P.area,definitions:[]}),de.definitions.push(P)}return T},[X]),te=(T,P,de,me)=>a(T,async()=>{const Ie=await t(P,de);y(null),Ie!==void 0&&(me==null||me()),await o()});if(c)return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"User",crumbs:e.jsx(Z,{to:"/admin/accounts",children:"← All users"})}),e.jsx(V,{})]});if(!E)return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"User",crumbs:e.jsx(Z,{to:"/admin/accounts",children:"← All users"})}),e.jsx(_,{message:h}),e.jsx(C,{children:e.jsx(ee,{children:"This user is no longer signed in to Memby."})})]});const H=E.devices??[],re=H.filter(T=>Ze(T.lastSeen)).length,S=E.settings??{},O=E.recommendations??{};return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:E.username||"Unnamed user",intro:`Memby user · ${E.shortName?`greeted as ${E.shortName} · `:""}${w(H.length)} device${H.length===1?"":"s"} · last seen ${F(E.lastSeen)}`,crumbs:e.jsx(Z,{to:"/admin/accounts",children:"← All users"}),actions:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"avatar",children:E.initials||wn(E.username)}),re?e.jsxs(N,{tone:"ok",children:[re," active now"]}):e.jsx(N,{children:"idle"}),e.jsx(ce,{children:E.id})]})}),e.jsx(_,{message:h}),e.jsxs(xe,{cols:"wide",children:[e.jsx(C,{title:"Devices",intro:"Every build a set has been seen running is listed under it. Signing one out revokes its Memby session, drops that history and removes it from Emby's own device list. Its Emby account is not changed.",icon:"tv",tone:"info",children:H.length===0?e.jsx(ee,{children:"No devices are signed in to this user."}):e.jsx("div",{className:"list",children:H.map(T=>{const P=Ns(T.lastSeen);return e.jsxs("div",{className:"list-item",children:[e.jsxs("div",{className:"list-body",children:[e.jsxs("b",{children:[e.jsx("span",{className:"dot-state","data-tone":P.tone,title:P.label})," ",e.jsx(Z,{className:"table-row-link",to:`/admin/devices/${encodeURIComponent(T.id)}`,children:T.name||"Memby TV"})]}),e.jsxs("p",{children:[T.version?`Memby ${T.version}`:"Legacy Memby client"," · ",P.label," · last seen ",F(T.lastSeen)," · signed in ",F(T.signedInAt)]}),(T.versions??[]).length>0?e.jsx("div",{className:"chips",children:(T.versions??[]).map(de=>e.jsxs(ce,{tone:de.version===T.version?"ok":void 0,children:[de.version,de.version===T.version?" · now":""]},de.version))}):null]}),e.jsxs("div",{className:"list-actions",children:[e.jsx($,{size:"sm",disabled:!T.id,onClick:()=>b({id:T.id,name:T.name}),children:"Rename"}),e.jsx($,{size:"sm",variant:"danger",disabled:!T.id,onClick:()=>y({kind:"remove-device",deviceId:T.id,name:T.name}),children:"Sign out"})]})]},T.id||T.name)})})}),e.jsxs(C,{title:"Viewers",intro:"Several people under one Emby account, each with their own Continue Watching, watched history and favourites. Only the account itself is synced with Emby; a shadow viewer's watching is kept by Memby and never reported.",icon:"people",tone:"note",actions:I.data&&!I.data.enabled?e.jsx(N,{tone:"warn",children:"switched off"}):e.jsxs(N,{tone:"ok",children:[w(R.length)," beside the account"]}),footer:L?e.jsx($,{variant:"primary",onClick:()=>k({id:null,name:""}),children:"Add viewer"}):e.jsx($,{disabled:!0,children:I.data?`${w(I.data.maxShadowViewers)} is the limit`:"Add viewer"}),children:[I.data&&!I.data.enabled?e.jsx(_,{message:"Viewers are switched off for this server, so every television watches as the account. Nothing here is deleted — turn the feature on under Features to bring these people back."}):null,I.loading?e.jsx(V,{}):(((Te=I.data)==null?void 0:Te.viewers)??[]).length===0?e.jsx(ee,{children:"Nobody is set up yet, so this account has one viewer: itself."}):e.jsx("div",{className:"list",children:(((Re=I.data)==null?void 0:Re.viewers)??[]).map(T=>e.jsxs("div",{className:"list-item",children:[e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:T.name}),e.jsxs("p",{children:[T.kind==="main"?"The account itself — named by Emby, and the only one whose watching Emby hears about":"Watches privately; nothing reaches Emby",T.createdAt&&T.kind!=="main"?` · added ${F(T.createdAt)}`:""]})]}),e.jsx("div",{className:"list-actions",children:T.kind==="main"?e.jsx(N,{tone:"info",children:"synced with Emby"}):e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",onClick:()=>k({id:T.id,name:T.name}),children:"Rename"}),e.jsx($,{size:"sm",variant:"danger",onClick:()=>y({kind:"remove-viewer",viewer:T}),children:"Remove"})]})})]},T.id))})]}),e.jsxs(C,{title:"Recommendation setup",intro:"The prompt appears the next time this person opens Memby on any of their televisions.",icon:"sparkle",tone:"note",footer:O.completed?e.jsx($,{busy:r==="reset-rec",onClick:()=>y({kind:"reset-recommendations"}),children:"Clear stored choices"}):O.prompted?e.jsx($,{onClick:()=>y({kind:"cancel-prompt"}),children:"Cancel prompt"}):e.jsx($,{variant:"primary",busy:r==="prompt",onClick:()=>void te("prompt",()=>D.put(`${l}/recommendations/prompt`),"Setup prompt queued."),children:"Send setup prompt"}),children:[e.jsx("div",{className:"row tight",children:O.completed?e.jsx(N,{tone:"ok",children:"completed"}):O.prompted?e.jsx(N,{tone:"warn",children:"prompt queued"}):e.jsx(N,{children:"not invited"})}),e.jsx(vt,{prompt:O})]})]}),(ge=E.watchTime)!=null&&ge.matched?e.jsx(C,{title:"Watch time",intro:"From Tracearr, for this person across every client — not only Memby. The week runs from Monday and the month from the first, both in the server's own timezone.",icon:"pulse",tone:"data",actions:E.watchTime.tracearrUsername?e.jsx(ce,{children:E.watchTime.tracearrUsername}):null,children:e.jsx(ae,{tiles:[{label:`this week · ${w(E.watchTime.weekSessions)} session${E.watchTime.weekSessions===1?"":"s"}`,value:_e(E.watchTime.weekMs),icon:"pulse",tone:"data"},{label:`this month · ${w(E.watchTime.monthSessions)} session${E.watchTime.monthSessions===1?"":"s"}`,value:_e(E.watchTime.monthMs),icon:"calendar",tone:"info"},{label:"since Tracearr started recording",value:_e(E.watchTime.totalMs),icon:"clock",tone:"note"},{label:"last watched",value:F(E.watchTime.lastWatchedAt),icon:"history",tone:void 0,small:!0}]})}):null,e.jsx(C,{title:"Notifications",intro:"Choose what this person sees across every television. Changes apply through the gateway within a few seconds and do not require an app release.",icon:"bell",tone:"note",actions:f!=null&&f.enabled?e.jsx(N,{tone:"ok",children:"enabled"}):e.jsx(N,{children:"muted"}),footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:r==="notifications",onClick:()=>void te("notifications",()=>D.put(`${l}/notifications`,f),"Notification settings saved.",()=>m(null)),children:"Save notifications"}),e.jsx($,{onClick:()=>{m(null),o()},children:"Discard changes"})]}),children:f?e.jsxs("div",{className:"checks columns",children:[e.jsx(G,{label:"All notifications",hint:"The master switch. Turning this off hides every optional notification below.",checked:f.enabled,onChange:T=>m(P=>P&&{...P,enabled:T})}),e.jsx(G,{label:"My Shows return dates",hint:"Remind this person when a followed show is about to return.",checked:f.showReturnAlerts,disabled:!f.enabled,onChange:T=>m(P=>P&&{...P,showReturnAlerts:T})}),e.jsx(G,{label:"Sonarr television alerts",hint:"New episodes, additions and cancellation news supplied by Sonarr.",checked:f.sonarrAlerts,disabled:!f.enabled,onChange:T=>m(P=>P&&{...P,sonarrAlerts:T})}),e.jsx(G,{label:"Radarr film alerts",hint:"Notify this person when Radarr imports a new film.",checked:f.radarrAlerts,disabled:!f.enabled,onChange:T=>m(P=>P&&{...P,radarrAlerts:T})}),e.jsx(G,{label:"Optional app updates",hint:"Offer new app versions to this person. Mandatory compatibility updates are always enforced.",checked:f.updateAlerts,disabled:!f.enabled,onChange:T=>m(P=>P&&{...P,updateAlerts:T})}),e.jsx(G,{label:"Library activity",hint:"Show alerts after the Memby library catalogue is refreshed.",checked:f.libraryAlerts,disabled:!f.enabled,onChange:T=>m(P=>P&&{...P,libraryAlerts:T})}),e.jsx(G,{label:"Weekly watch-time summary",hint:"Send this person their week-to-date and month-to-date viewing on Sunday evening, and a summary of the month just gone once it ends. Needs Tracearr.",checked:f.watchTimeDigest,disabled:!f.enabled,onChange:T=>m(P=>P&&{...P,watchTimeDigest:T})}),e.jsx(G,{label:"Service status",hint:"Memby deployment and Emby outage or recovery notices. Maintenance mode itself still applies.",checked:f.systemAlerts,disabled:!f.enabled,onChange:T=>m(P=>P&&{...P,systemAlerts:T})})]}):null}),e.jsx(C,{title:"Settings",intro:"These live on the server and follow the person, so a change here reaches every television they use — usually within a few seconds, and on the next launch for a set that is switched off.",icon:"sliders",tone:"ok",actions:S.saved?e.jsxs(N,{tone:S.source==="admin"?"warn":"ok",children:["r",w(S.revision)," · ",S.source||"device"," · ",F(S.updatedAt)]}):e.jsx(N,{children:"defaults · never synced"}),footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:r==="push",onClick:()=>void te("push",()=>D.put(`${l}/preferences`,{preferences:u??{}}),"Pushed to their televisions.",()=>p(null)),children:"Push to their televisions"}),e.jsx($,{onClick:()=>{p(null),o()},children:"Discard changes"}),e.jsx($,{onClick:()=>y({kind:"reset-preferences"}),children:"Restore defaults"}),e.jsx(Z,{className:"crumb",to:`/admin/accounts/${encodeURIComponent(s)}/settings`,children:"History and rollback →"})]}),children:ue.map(T=>e.jsxs("div",{className:"group",children:[e.jsx("p",{className:"group-label",children:T.name}),T.definitions.map(P=>e.jsx(bt,{definition:P,value:u==null?void 0:u[P.key],onChange:de=>p(me=>({...me??{},[P.key]:de}))},P.key))]},T.name))}),e.jsx(C,{title:"Colour schemes",intro:"Which palettes this person may choose between in Settings → Appearance. Tick everything to leave them unrestricted. Their current choice is an ordinary setting above; withdrawing it here puts them back on Midnight.",icon:"sparkle",tone:"note",actions:(E.themes??[]).length===0?e.jsx(N,{children:"all schemes"}):e.jsxs(N,{tone:"note",children:[w((E.themes??[]).length)," of ",w(le.length)]}),footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:r==="themes",onClick:()=>(d??[]).length===0?y({kind:"no-themes"}):void te("themes",()=>D.put(`${l}/themes`,{themes:d??[]}),"Colour schemes saved.",()=>x(null)),children:"Save colour schemes"}),e.jsx($,{onClick:()=>x(le.map(T=>T.id)),children:"Allow all"}),e.jsxs("span",{className:"hint",children:["Seasonal themes are not listed. They apply to every television in the house for their dates and nobody can decline one — the only switch is ",e.jsx("em",{children:"Seasonal themes"})," on the features page."]})]}),children:e.jsx("div",{className:"checks columns",children:le.map(T=>{var P,de,me;return e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:(d??[]).includes(T.id),onChange:Ie=>x(Ve=>Ie.target.checked?[...Ve??[],T.id]:(Ve??[]).filter(M=>M!==T.id))}),e.jsx("span",{className:"switch"}),e.jsx("span",{className:"swatch",style:{"--swatch-surface":js((P=T.palette)==null?void 0:P.surface),"--swatch-accent":js((de=T.palette)==null?void 0:de.accent),"--swatch-hairline":js((me=T.palette)==null?void 0:me.hairline)},children:e.jsx("i",{})}),e.jsxs("span",{className:"check-body",children:[e.jsx("b",{children:T.name}),e.jsx("p",{children:T.description})]})]},T.id)})})}),e.jsx(C,{title:"Remove Memby access",intro:"Signs every one of this person's Memby devices out. Their Emby account, viewing history and library permissions are untouched.",icon:"alert",tone:"bad",children:e.jsx($,{variant:"danger",onClick:()=>y({kind:"remove-account"}),children:"Remove Memby access"})}),v?e.jsx(ft,{initial:v.name,busy:r==="rename",onCancel:()=>b(null),onConfirm:T=>void te("rename",()=>D.put(`${l}/devices/${encodeURIComponent(v.id)}`,{deviceName:T}),"Device renamed.",()=>b(null))}):null,A?e.jsx(yt,{initial:A.name,renaming:A.id!==null,busy:r==="viewer-name",onCancel:()=>k(null),onConfirm:T=>void te("viewer-name",()=>A.id?D.put(`${l}/viewers/${encodeURIComponent(A.id)}`,{name:T}):D.post(`${l}/viewers`,{name:T}),A.id?"Viewer renamed.":"Viewer added.",()=>{k(null),I.reload()})}):null,j?e.jsx(wt,{pending:j,busy:r,username:E.username,onCancel:()=>y(null),onConfirm:()=>{switch(j.kind){case"remove-device":return void te("remove-device",()=>D.del(`${l}/devices/${encodeURIComponent(j.deviceId)}`),"Device signed out.");case"remove-viewer":return void te("remove-viewer",()=>D.del(`${l}/viewers/${encodeURIComponent(j.viewer.id)}`),"Viewer removed.",()=>void I.reload());case"remove-account":return void te("remove-account",()=>D.del(`${l}/sessions`),"Memby access removed.",()=>n("/admin/accounts"));case"reset-recommendations":case"cancel-prompt":return void te("reset-rec",()=>D.del(`${l}/recommendations`),"Recommendation choices cleared.");case"reset-preferences":return void te("reset-prefs",()=>D.del(`${l}/preferences`),"Defaults restored.",()=>p(null));case"no-themes":return void te("themes",()=>D.put(`${l}/themes`,{themes:[]}),"Colour schemes saved.",()=>x(null))}}}):null]})}function vt({prompt:s}){const n=s.ratings??[],t=[["Genres",s.genres],["Studios",s.studios],["Actors",s.actors],["Actresses",s.actresses],["Directors",s.directors],["Types",s.contentTypes]],r=[...n.map(a=>e.jsxs(ce,{tone:"warn",children:[a.title," · ",w(a.rating)," ★"]},`r:${a.title}`)),...t.flatMap(([a,l])=>(l??[]).map(i=>e.jsxs(ce,{children:[a,": ",i]},`${a}:${i}`)))];return r.length===0?e.jsx(ee,{children:"No recommendation selections have been saved."}):e.jsx("div",{className:"chips",children:r})}function bt({definition:s,value:n,onChange:t}){if(s.kind==="toggle")return e.jsx(G,{label:s.name,hint:s.description,checked:!!n,onChange:t});if(s.kind==="choice"||s.kind==="number"){const a=s.unit??"",l=s.kind==="number"?(s.numbers??[]).map(i=>({value:String(i),label:i===0?"No limit":a?`${i} ${a}`:String(i)})):s.options??[];return e.jsx(q,{label:s.name,hint:s.description,children:e.jsx("select",{value:String(n??""),onChange:i=>t(s.kind==="number"?Number(i.target.value):i.target.value),children:l.map(i=>e.jsx("option",{value:i.value,children:i.label},i.value))})})}if(s.kind==="multi"){const a=Array.isArray(n)?n:[],l=[...a,...(s.options??[]).map(i=>i.value).filter(i=>!a.includes(i))];return e.jsxs("div",{className:"field",children:[e.jsx("span",{children:s.name}),e.jsx("small",{children:s.description}),e.jsx("div",{className:"checks",children:l.map(i=>{const h=(s.options??[]).find(c=>c.value===i);return h?e.jsx(G,{label:h.label,checked:a.includes(i),onChange:c=>t(c?[...a,i]:a.filter(o=>o!==i))},i):null})})]})}if(s.kind==="text")return e.jsx(q,{label:s.name,hint:s.description,children:e.jsx("input",{type:"text",value:String(n??""),maxLength:s.maxLength,placeholder:s.placeholder,onChange:a=>t(s.uppercase?a.target.value.toLocaleUpperCase("en-NZ"):a.target.value)})});const r=Array.isArray(n)?n:[];return e.jsx(q,{label:s.name,hint:s.description,children:e.jsx("textarea",{spellCheck:!1,placeholder:"One row id per line",value:r.join(`
`),onChange:a=>t(a.target.value.split(`
`).map(l=>l.trim()).filter(Boolean))})})}function ft({initial:s,busy:n,onConfirm:t,onCancel:r}){const[a,l]=g.useState(s||"Memby TV");return e.jsx("div",{className:"scrim",onPointerDown:i=>i.target===i.currentTarget&&r(),children:e.jsxs("div",{className:"dialog",role:"dialog","aria-modal":"true",children:[e.jsx("h2",{children:"Name this device"}),e.jsx("p",{children:"The name a viewer sees in Settings → Devices, and what the console calls it."}),e.jsx(q,{label:"Device name",children:e.jsx("input",{type:"text",value:a,autoFocus:!0,maxLength:80,onChange:i=>l(i.target.value)})}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx($,{variant:"quiet",onClick:r,children:"Cancel"}),e.jsx($,{variant:"primary",busy:n,disabled:!a.trim(),onClick:()=>t(a.trim()),children:"Rename"})]})]})})}function yt({initial:s,renaming:n,busy:t,onConfirm:r,onCancel:a}){const[l,i]=g.useState(s);return e.jsx("div",{className:"scrim",onPointerDown:h=>h.target===h.currentTarget&&a(),children:e.jsxs("div",{className:"dialog",role:"dialog","aria-modal":"true",children:[e.jsx("h2",{children:n?"Rename this viewer":"Add a viewer"}),e.jsx("p",{children:"The name shown on the televisions “Whos watching?” screen. Everything they watch is kept by Memby and never reported to Emby."}),e.jsx(q,{label:"Name",children:e.jsx("input",{type:"text",value:l,autoFocus:!0,maxLength:40,onChange:h=>i(h.target.value)})}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx($,{variant:"quiet",onClick:a,children:"Cancel"}),e.jsx($,{variant:"primary",busy:t,disabled:!l.trim(),onClick:()=>r(l.trim()),children:n?"Rename":"Add viewer"})]})]})})}function wt({pending:s,busy:n,username:t,onConfirm:r,onCancel:a}){const i={"remove-device":{title:"Sign this device out of Memby?",body:"Its Emby account will not be changed. The set can sign in again at any time.",label:"Sign out",destructive:!0},"remove-account":{title:`Remove Memby access for ${t||"this user"}?`,body:"Every Memby device will be signed out. Their Emby account, viewing history and library permissions are untouched.",label:"Remove access",destructive:!0},"reset-recommendations":{title:"Clear this person's stored recommendation choices?",body:"Viewing history remains intact; only the explicit setup answers are removed.",label:"Clear",destructive:!0},"cancel-prompt":{title:"Cancel this person's queued recommendation prompt?",body:"They will not be invited to set up recommendations on their next launch.",label:"Cancel prompt",destructive:!1},"reset-preferences":{title:"Restore the Memby defaults for this person?",body:"Their televisions will pick the change up the next time they check in.",label:"Restore defaults",destructive:!0},"remove-viewer":{title:"Remove this viewer?",body:"What they were part-way through, what they had watched and their favourites are deleted, on every television in the house. The Emby account is untouched.",label:"Remove viewer",destructive:!0},"no-themes":{title:"Allow this person no colour schemes?",body:"They will be left on Midnight with nothing to choose between.",label:"Save anyway",destructive:!0}}[s.kind];return e.jsx(ke,{title:i.title,body:i.body,confirmLabel:i.label,destructive:i.destructive,busy:!!n,onConfirm:r,onCancel:a})}function kt(s,n){if(s.kind==="toggle")return n?"On":"Off";if(s.kind==="choice"){const r=(s.options??[]).find(a=>a.value===n);return r?r.label:String(n??"")}if(s.kind==="number")return Number(n)===0&&s.unit?"No limit":s.unit?`${n} ${s.unit}`:String(n??"");const t=Array.isArray(n)?n:[];return t.length===0?"None":t.map(r=>{var a;return((a=(s.options??[]).find(l=>l.value===r))==null?void 0:a.label)??r}).join(", ")}function Nt(){const{userId:s=""}=We(),{wrap:n}=ie(),{busy:t,run:r}=ne(),a=`/admin/api/accounts/${encodeURIComponent(s)}`,{data:l,error:i,loading:h,reload:c}=J(`${a}/preferences/history`,{pollMs:3e4}),[o,u]=g.useState(new Set),[p,d]=g.useState(null),x=(l==null?void 0:l.username)||"this account",f=(l==null?void 0:l.devices)??[],m=(l==null?void 0:l.revisions)??[],j=(l==null?void 0:l.catalogue)??[],y=b=>u(A=>{const k=new Set(A);return k.has(b)?k.delete(b):k.add(b),k}),v=b=>r("restore",async()=>{await n(()=>D.post(`${a}/preferences/revisions/${b}/restore`),`Restored r${b}.`),d(null),await c()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Settings history",intro:`Every change to ${x}'s synced settings, and which of their televisions has taken it.`,crumbs:e.jsxs(Z,{to:`/admin/accounts/${encodeURIComponent(s)}`,children:["← ",x]})}),e.jsx(_,{message:i}),h?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(C,{title:"Where each device has got to",intro:"A set takes a change by fetching it, which it does within a few seconds of being told — so anything still behind is switched off, mid-film, or cannot reach the gateway.",icon:"tv",tone:"info",actions:l!=null&&l.saved?e.jsxs(N,{tone:l.currentSource==="admin"?"warn":"ok",children:["now on r",w(l.currentRevision)," · ",l.currentSource||"device"]}):e.jsx(N,{children:"defaults · never synced"}),children:f.length===0?e.jsx(ee,{children:"No television has been signed in to this account."}):e.jsx("div",{className:"list",children:f.map(b=>{const A=b.never?void 0:b.behind?"bad":"ok";return e.jsxs("div",{className:"list-item",children:[e.jsxs("div",{className:"list-body",children:[e.jsxs("b",{children:[e.jsx("span",{className:"dot-state","data-tone":A})," ",b.name||"Memby TV"," ",b.signedOut?e.jsx(N,{children:"signed out"}):null]}),e.jsxs("p",{children:[b.never?"Has not fetched these settings yet":`Holding r${w(b.revision)} · taken ${F(b.ackedAt)}`,b.clientVersion?` · Memby ${b.clientVersion}`:"",b.signedOut?"":` · last seen ${F(b.lastSeen)}`]})]}),e.jsx("div",{className:"list-actions",children:b.never?e.jsx(N,{children:"never taken one"}):b.behind?e.jsxs(N,{tone:"bad",children:[w(b.behind)," behind"]}):e.jsx(N,{tone:"ok",children:"up to date"})})]},b.deviceId||b.name)})})}),e.jsx(C,{title:"Change history",intro:"Restoring puts an earlier version back as a new change, so the televisions notice it and the version it replaced stays here to return to.",icon:"history",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"When"}),e.jsx("th",{className:"num",children:"Rev"}),e.jsx("th",{children:"Changed by"}),e.jsx("th",{children:"What changed"}),e.jsx("th",{className:"num",children:"Taken by"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:m.length===0?e.jsx(Y,{columns:6,children:"Nothing has been changed on this account yet."}):m.flatMap(b=>{const A=o.has(b.revision),k=b.acks??[],I=b.changes??[],E=[e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:F(b.createdAt)}),e.jsxs("td",{className:"num nowrap",children:["r",w(b.revision)," ",b.current?e.jsx(N,{tone:"ok",children:"current"}):null]}),e.jsxs("td",{className:"nowrap",children:[e.jsx(N,{tone:b.source==="admin"?"warn":"ok",children:b.author}),b.restoredFrom?e.jsxs("span",{className:"muted",children:[" restored r",w(b.restoredFrom)]}):null]}),e.jsx("td",{className:"muted",children:b.initial?e.jsx("span",{className:"muted",children:"First recorded settings"}):I.length===0?e.jsx("span",{className:"muted",children:"No visible change"}):e.jsx("div",{className:"chips",children:I.map((R,L)=>e.jsxs(ce,{children:[R.name,": ",R.before," → ",R.after]},`${R.name}:${L}`))})}),e.jsx("td",{className:"num",children:k.length===0?e.jsx("span",{className:"muted",children:"—"}):e.jsx("span",{title:k.map(R=>R.deviceName||R.deviceId).join(", "),children:w(k.length)})}),e.jsx("td",{className:"num nowrap",children:e.jsxs("span",{className:"list-actions",children:[e.jsx($,{size:"sm",onClick:()=>y(b.revision),children:A?"Hide":"Show"}),b.current?null:e.jsx($,{size:"sm",onClick:()=>d(b.revision),children:"Restore"})]})})]},b.revision)];return A&&E.push(e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"muted",children:e.jsx("div",{className:"chips",children:j.map(R=>{var L;return e.jsxs(ce,{children:[R.name,":"," ",kt(R,(L=b.preferences)==null?void 0:L[R.key])]},R.key)})})})},`${b.revision}:detail`)),E})})]})})})]}),p!==null?e.jsx(ke,{title:`Restore revision ${p}?`,body:"It goes out as a new change, so every one of their televisions will pick it up — and the current version stays in this history to return to.",confirmLabel:"Restore",busy:t==="restore",onConfirm:()=>void v(p),onCancel:()=>d(null)}):null]})}function St({client:s}){const n=s.versions??[];return n.length===0?e.jsx("span",{className:"muted",children:"—"}):e.jsx("span",{className:"versions",children:n.map(t=>e.jsx(ce,{tone:t.version===s.version?"ok":void 0,children:t.version},t.version))})}function Mt(){const{status:s,error:n,loading:t}=je(),r=(s==null?void 0:s.clients)??[],a=r.filter(i=>(i.capabilities??[]).includes("server_features_v1")),l=new Set(r.map(i=>i.version).filter(Boolean));return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Devices",intro:"Which sets have reported in, what they are running and what their build understands."}),e.jsx(_,{message:n}),t?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"devices known",value:w(r.length),icon:"tv",tone:"info"},{label:"active in the last quarter hour",value:w(r.filter(i=>Ze(i.lastSeen)).length),icon:"pulse",tone:"ok"},{label:"reporting their capabilities",value:w(a.length),icon:"sliders",tone:"ok"},{label:"app builds in service",value:w(l.size),icon:"download",tone:"note"}]}),e.jsx(C,{title:"Devices",intro:"Every request carries what that build understands. A feature is only presented to a device that declares its contract, which is what lets an older set keep working while a new one gets the new behaviour. Status is whether the set is reporting that list at all; a build old enough to say nothing is served the fallback.",icon:"tv",tone:"info",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Device"}),e.jsx("th",{children:"Person"}),e.jsx("th",{children:"App"}),e.jsx("th",{children:"Builds seen"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Last seen"})]})}),e.jsx("tbody",{children:r.length===0?e.jsx(Y,{columns:6,children:"No devices have signed in yet."}):r.map(i=>{const h=(i.capabilities??[]).includes("server_features_v1"),c=Ns(i.lastSeen);return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"row tight",children:[e.jsx("span",{className:"dot-state","data-tone":c.tone,title:c.label}),e.jsx(Z,{className:"table-row-link",to:`/admin/devices/${encodeURIComponent(i.deviceId)}`,children:i.deviceName||"Memby TV"})]})}),e.jsx("td",{className:"muted",children:i.username}),e.jsx("td",{className:"mono",children:i.version||"legacy"}),e.jsx("td",{children:e.jsx(St,{client:i})}),e.jsx("td",{children:e.jsx(N,{tone:h?"ok":"warn",children:h?"reported":"missing"})}),e.jsx("td",{className:"nowrap muted",children:F(i.lastSeen)})]},`${i.deviceId}:${i.username}`)})})]})})})]})]})}const Ws={user:"",q:"",ip:"",outcome:"",from:"",to:""},Ct=[{value:1,label:"Today"},{value:7,label:"7 days"},{value:30,label:"30 days"},{value:0,label:"All"}];function $t(){var b,A,k,I,E,R;const[s,n]=g.useState("log"),[t,r]=g.useState(7),[a,l]=g.useState(Ws),[i,h]=g.useState(0),c=100,o=g.useMemo(()=>Be({...a,days:a.from?void 0:t||void 0,limit:c,offset:i*c}),[a,t,i]),u=J(`/admin/api/logins${o}`,{enabled:s==="log"}),p=J(`/admin/api/logins/devices${o}`,{enabled:s==="devices"}),d=((b=u.data)==null?void 0:b.users)??((A=p.data)==null?void 0:A.users)??[],x=((k=u.data)==null?void 0:k.totals)??((I=p.data)==null?void 0:I.totals),f=((E=u.data)==null?void 0:E.retentionDays)??((R=p.data)==null?void 0:R.retentionDays)??90,m=s==="log"?u.loading:p.loading,j=s==="log"?u.error:p.error,y=L=>{l(X=>({...X,...L})),h(0)},v=Object.entries(a).some(([,L])=>L!=="")||!!a.from;return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Sign-in history",intro:"Every connection attempt, kept as history rather than as the latest state of a device. A television that has since been removed still appears here, because it still connected.",actions:e.jsx(Ye,{value:s,options:[{value:"log",label:"Log"},{value:"devices",label:"By device"}],onChange:n})}),e.jsx(_,{message:j}),x?e.jsx(ae,{tiles:[{label:"Successful sign-ins",value:w(x.logins),icon:"key",tone:"ok"},{label:"Refused",value:w(x.failures),icon:"shield",tone:x.failures>0?"warn":void 0},{label:"Televisions",value:w(x.devices),icon:"tv",tone:"info"},{label:"People",value:w(x.users),icon:"people",tone:"note"},{label:"Addresses",value:w(x.addresses),icon:"globe",tone:"data"},{label:"History kept",value:`${f} days`,small:!0,icon:"clock"}]}):null,e.jsxs("div",{className:"filters",children:[e.jsx(q,{label:"Window",children:e.jsx(Ye,{value:a.from?-1:t,options:Ct.map(L=>({value:L.value,label:L.label})),onChange:L=>{r(L),y({from:"",to:""})}})}),e.jsx(q,{label:"Person",children:e.jsxs("select",{value:a.user,onChange:L=>y({user:L.target.value}),children:[e.jsx("option",{value:"",children:"Anyone"}),d.map(L=>e.jsx("option",{value:L.id,children:L.username||L.id},L.id))]})}),e.jsx(q,{label:"Outcome",children:e.jsxs("select",{value:a.outcome,onChange:L=>y({outcome:L.target.value}),children:[e.jsx("option",{value:"",children:"Both"}),e.jsx("option",{value:"success",children:"Got in"}),e.jsx("option",{value:"failure",children:"Refused"})]})}),e.jsx(q,{label:"Address",children:e.jsx("input",{type:"text",value:a.ip,placeholder:"10.0.0.4",onChange:L=>y({ip:L.target.value})})}),e.jsx(q,{label:"From",children:e.jsx("input",{type:"date",value:a.from,onChange:L=>y({from:L.target.value})})}),e.jsx(q,{label:"To",children:e.jsx("input",{type:"date",value:a.to,onChange:L=>y({to:L.target.value})})}),e.jsx(q,{label:"Search",grow:!0,children:e.jsx("input",{type:"search",value:a.q,placeholder:"Name, device or address",onChange:L=>y({q:L.target.value})})}),e.jsx("div",{className:"filter-actions",children:v?e.jsx($,{variant:"quiet",size:"sm",onClick:()=>{l(Ws),h(0)},children:"Clear"}):null})]}),m?e.jsx(V,{}):s==="log"?e.jsx(Tt,{data:u.data,page:i,limit:c,onPage:h}):e.jsx(Rt,{data:p.data})]})}function Tt({data:s,page:n,limit:t,onPage:r}){if(!s)return null;const a=s.events.length,l=s.total===0?0:n*t+1;return e.jsxs(e.Fragment,{children:[e.jsxs(xe,{cols:"wide",children:[e.jsx(C,{title:"Attempts per day",intro:"Grouped in the server's own timezone, so an evening sign-in stays on the day it happened.",icon:"chart",tone:"info",children:e.jsx(hs,{data:s.days,labelOf:i=>i.day,valueOf:i=>i.logins+i.failures,toneOf:i=>i.failures>i.logins?"bad":void 0,title:i=>`${i.day}: ${i.logins} in, ${i.failures} refused, ${i.devices} televisions`})}),e.jsx(C,{title:"Where from",icon:"globe",tone:"data",children:s.addresses.length===0?e.jsx(ee,{children:"No addresses in this window."}):e.jsx("div",{className:"list",children:s.addresses.slice(0,8).map(i=>e.jsxs("div",{className:"list-item",children:[e.jsxs("div",{className:"list-body",children:[e.jsx("b",{className:"mono",children:i.ipAddress}),e.jsxs("p",{children:[w(i.logins)," in",i.failures>0?` · ${w(i.failures)} refused`:""]})]}),i.failures>0&&i.logins===0?e.jsx(N,{tone:"bad",children:"only refused"}):null]},i.ipAddress))})})]}),e.jsx(C,{title:"Attempts",intro:"Uncollapsed and newest first: this is what to read when somebody says a television will not sign in.",icon:"key",tone:"ok",actions:e.jsx("span",{className:"filter-summary",children:s.total===0?"nothing matches":`${w(l)}${w(l+a-1)} of ${w(s.total)}`}),footer:s.total>t?e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",disabled:n===0,onClick:()=>r(n-1),children:"Newer"}),e.jsx($,{size:"sm",disabled:(n+1)*t>=s.total,onClick:()=>r(n+1),children:"Older"})]}):void 0,children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"When"}),e.jsx("th",{children:"Person"}),e.jsx("th",{children:"Television"}),e.jsx("th",{className:"nowrap",children:"Address"}),e.jsx("th",{children:"Build"}),e.jsx("th",{children:"Outcome"})]})}),e.jsx("tbody",{children:s.events.length===0?e.jsx(Y,{columns:6,children:"No sign-in attempts match these filters."}):s.events.map(i=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:F(i.occurredAt)}),e.jsx("td",{children:i.username||e.jsx("span",{className:"quiet",children:"unknown"})}),e.jsx("td",{children:i.deviceId?e.jsx(Z,{className:"table-row-link",to:`/admin/devices/${encodeURIComponent(i.deviceId)}`,children:i.deviceName||i.deviceId}):e.jsx("span",{className:"quiet",children:"—"})}),e.jsx("td",{className:"mono nowrap",children:i.ipAddress||"—"}),e.jsx("td",{className:"mono",children:i.clientVersion||"—"}),e.jsx("td",{className:"nowrap",children:i.success?i.newDevice?e.jsx(N,{tone:"info",children:"first sign-in"}):e.jsx(N,{tone:"ok",children:"got in"}):e.jsx(N,{tone:"bad",children:i.failureReason||"refused"})})]},i.id))})]})})})]})}function Rt({data:s}){return s?e.jsx(C,{title:"Televisions",intro:"Grouped from the history, not from the session list — a set whose session has expired still connected, and this is the record of it.",icon:"tv",tone:"info",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Television"}),e.jsx("th",{children:"Person"}),e.jsx("th",{className:"num",children:"Today"}),e.jsx("th",{className:"num",children:"Sign-ins"}),e.jsx("th",{className:"num",children:"Refused"}),e.jsx("th",{className:"num",children:"Addresses"}),e.jsx("th",{className:"nowrap",children:"Last address"}),e.jsx("th",{className:"nowrap",children:"Last sign-in"}),e.jsx("th",{children:"Build"})]})}),e.jsx("tbody",{children:s.devices.length===0?e.jsx(Y,{columns:9,children:"No television has connected in this window."}):s.devices.map(n=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx(Z,{className:"table-row-link",to:`/admin/devices/${encodeURIComponent(n.deviceId)}`,children:n.deviceName||n.deviceId})}),e.jsx("td",{className:"muted",children:n.username||"—"}),e.jsx("td",{className:"num",children:n.loginsToday>0?w(n.loginsToday):"—"}),e.jsx("td",{className:"num",children:w(n.logins)}),e.jsx("td",{className:"num",children:n.failures>0?e.jsx("span",{className:"mono",children:w(n.failures)}):"—"}),e.jsx("td",{className:"num",children:w(n.distinctIps)}),e.jsx("td",{className:"mono nowrap",children:n.lastIp||"—"}),e.jsx("td",{className:"nowrap muted",children:n.lastLogin?F(n.lastLogin):"—"}),e.jsx("td",{className:"mono",children:n.clientVersion||"—"})]},n.deviceId))})]})})}):null}const At=[{value:1,label:"Today"},{value:7,label:"7 days"},{value:30,label:"30 days"},{value:0,label:"All"}];function Et(){const{deviceId:s=""}=We(),[n,t]=g.useState(7),r=g.useMemo(()=>`/admin/api/logins/devices/${encodeURIComponent(s)}${Be({days:n||void 0,limit:200})}`,[s,n]),{data:a,error:l,loading:i}=J(r,{enabled:!!s}),h=a==null?void 0:a.summary,c=(h==null?void 0:h.deviceName)||s;return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:c,intro:"One television's whole relationship with the gateway.",crumbs:e.jsxs(e.Fragment,{children:[e.jsx(Z,{to:"/admin/clients",children:"Devices"}),e.jsx("span",{children:"/"}),e.jsx(Z,{to:"/admin/logins",children:"Sign-ins"}),e.jsx("span",{children:"/"}),e.jsx("span",{children:c})]}),actions:e.jsx(Ye,{value:n,options:At.map(o=>({value:o.value,label:o.label})),onChange:t})}),e.jsx(_,{message:l}),i?e.jsx(V,{}):a?e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"Sign-ins today",value:w((h==null?void 0:h.loginsToday)??0),icon:"clock",tone:"ok"},{label:"Sign-ins in total",value:w((h==null?void 0:h.logins)??0),icon:"key",tone:"info"},{label:"Refused",value:w((h==null?void 0:h.failures)??0),icon:"shield",tone:((h==null?void 0:h.failures)??0)>0?"warn":void 0},{label:"Addresses seen",value:w((h==null?void 0:h.distinctIps)??0),icon:"globe",tone:"data"},{label:"First seen",value:h!=null&&h.firstLogin?F(h.firstLogin):"—",small:!0,icon:"history"},{label:"Last seen",value:h!=null&&h.lastLogin?F(h.lastLogin):"—",small:!0,icon:"pulse",tone:"note"}]}),e.jsxs(xe,{cols:"wide",children:[e.jsx(C,{title:"Connections per day",icon:"chart",tone:"info",children:e.jsx(hs,{data:a.days,labelOf:o=>o.day,valueOf:o=>o.logins+o.failures,toneOf:o=>o.failures>o.logins?"bad":void 0,title:o=>`${o.day}: ${o.logins} in${o.failures?`, ${o.failures} refused`:""}`})}),e.jsxs("div",{className:"stack",children:[e.jsx(C,{title:"Identity",icon:"tv",tone:"info",children:e.jsxs("div",{className:"list",children:[e.jsx("div",{className:"list-item",children:e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:"Person"}),e.jsx("p",{children:(h==null?void 0:h.username)||"unknown"})]})}),e.jsx("div",{className:"list-item",children:e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:"Device id"}),e.jsx("p",{className:"mono",children:a.deviceId})]})}),e.jsx("div",{className:"list-item",children:e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:"Running"}),e.jsx("p",{className:"mono",children:(h==null?void 0:h.clientVersion)||"unknown"})]})})]})}),e.jsx(C,{title:"Builds",intro:"Kept per television rather than per session, so it survives a sign-out.",icon:"upload",tone:"note",children:a.versions.length===0?e.jsx(ee,{children:"No build history for this television."}):e.jsx("div",{className:"list",children:a.versions.map(o=>e.jsx("div",{className:"list-item",children:e.jsxs("div",{className:"list-body",children:[e.jsx("b",{className:"mono",children:o.version}),e.jsxs("p",{children:[F(o.firstSeen)," → ",F(o.lastSeen)]})]})},o.version))})})]})]}),e.jsx(C,{title:"Addresses",icon:"globe",tone:"data",children:a.addresses.length===0?e.jsx(ee,{children:"No addresses recorded in this window."}):e.jsx("div",{className:"chips",children:a.addresses.map(o=>e.jsxs(ce,{tone:o.failures>0?"warn":"data",children:[o.ipAddress," · ",w(o.logins),o.failures>0?` (+${w(o.failures)} refused)`:""]},o.ipAddress))})}),e.jsx(C,{title:"Every attempt",icon:"key",tone:"ok",actions:e.jsxs("span",{className:"filter-summary",children:[w(a.total)," in this window"]}),children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"When"}),e.jsx("th",{children:"Person"}),e.jsx("th",{className:"nowrap",children:"Address"}),e.jsx("th",{children:"Build"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Outcome"})]})}),e.jsx("tbody",{children:a.events.length===0?e.jsx(Y,{columns:6,children:"This television has not connected in the selected window."}):a.events.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:F(o.occurredAt)}),e.jsx("td",{children:o.username||e.jsx("span",{className:"quiet",children:"unknown"})}),e.jsx("td",{className:"mono nowrap",children:o.ipAddress||"—"}),e.jsx("td",{className:"mono",children:o.clientVersion||"—"}),e.jsx("td",{className:"muted",children:o.method}),e.jsx("td",{className:"nowrap",children:o.success?o.newDevice?e.jsx(N,{tone:"info",children:"first sign-in"}):e.jsx(N,{tone:"ok",children:"got in"}):e.jsx(N,{tone:"bad",children:o.failureReason||"refused"})})]},o.id))})]})})})]}):null]})}function It(){const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a}=ie(),{busy:l,run:i}=ne(),[h,c]=g.useState(!1),o=(s==null?void 0:s.library.byType)??{},u=!!(s!=null&&s.syncRunning),p=d=>i(d,async()=>{await a(()=>D.post("/admin/api/sync",{kind:d}),d==="full"?"Full re-import started.":"Import started."),c(!1),await r()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Library",intro:"Import and inspect the catalogue Memby ranks."}),e.jsx(_,{message:n}),t||!s?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"items",value:w(s.library.total),icon:"library",tone:"data"},...Object.keys(o).sort().map(d=>({label:d,value:w(o[d]),icon:"list"})),{label:"last import",value:F(s.library.lastSynced),small:!0,icon:"clock"}]}),e.jsx(C,{title:"Import the catalogue",intro:"Emby's catalogue is copied here so search and the recommendation candidate pool can be answered from one indexed table. Watched, favourite and resume state is deliberately not stored — that is per person and still comes from Emby live.",icon:"library",tone:"data",footer:e.jsx("span",{className:"hint",children:u?"Import running…":`An incremental import runs automatically every ${s.syncEvery}.`}),children:e.jsxs("div",{className:"row",children:[e.jsx($,{variant:"primary",icon:"sync",disabled:u,busy:l==="incremental",onClick:()=>void p("incremental"),children:"Sync new items"}),e.jsx($,{icon:"database",disabled:u,onClick:()=>c(!0),children:"Full re-import"})]})})]}),h?e.jsx(ke,{title:"Re-import the entire library?",body:"A full pass mark-and-sweeps the catalogue and can take several minutes on a large library. Televisions keep reading the current table throughout.",confirmLabel:"Re-import",busy:l==="full",onConfirm:()=>void p("full"),onCancel:()=>c(!1)}):null]})}function Lt(){var p;const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a}=ie(),{busy:l,run:i}=ne(),h=(s==null?void 0:s.requestUsers)??[],c=((p=s==null?void 0:s.requestPolicy)==null?void 0:p.allowedUserIds)??[],o=g.useMemo(()=>new Map(((s==null?void 0:s.requestUsage)??[]).map(d=>[d.userId,d])),[s==null?void 0:s.requestUsage]),u=d=>i(`access-${d}`,async()=>{const x=c.includes(d)?c.filter(f=>f!==d):[...c,d];await a(()=>D.post("/admin/api/request-policy",{allowedUserIds:x}),x.includes(d)?"Request access granted.":"Request access removed."),await r()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Media requests",intro:"Who can ask for something the library does not have."}),e.jsx(_,{message:n}),t?e.jsx(V,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx(C,{title:"Where a request goes",intro:"Movies follow Radarrs policy. Series follow the dedicated Sonarr request policy: monitored as normal, with backlog searching only when an operator enables it under Integrations.",icon:"inbox",tone:"info",actions:e.jsxs(e.Fragment,{children:[e.jsxs(N,{tone:s!=null&&s.radarrReady?"ok":"bad",children:["Movies ",s!=null&&s.radarrReady?"ready":"not configured"]}),e.jsxs(N,{tone:s!=null&&s.sonarrReady?"ok":"bad",children:["Series ",s!=null&&s.sonarrReady?"ready":"not configured"]})]}),children:!(s!=null&&s.radarrReady)&&!(s!=null&&s.sonarrReady)?e.jsx(ee,{children:"Neither Radarr nor Sonarr is configured, so a request would have nowhere to go. The button stays hidden on every television until one of them is."}):null}),e.jsx(C,{title:"Request access and activity",intro:"One button grants or removes access. A recorded request has already been sent to Radarr or Sonarr; Memby does not duplicate their download state.",icon:"people",tone:"note",children:h.length===0?e.jsx(ee,{children:"No one has signed in yet."}):e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"User"}),e.jsx("th",{children:"Last seen"}),e.jsx("th",{className:"num",children:"Sent to services"}),e.jsx("th",{children:"Last request"}),e.jsx("th",{children:"Access"})]})}),e.jsx("tbody",{children:h.map(d=>{const x=o.get(d.id),f=c.includes(d.id);return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("b",{children:d.username})}),e.jsx("td",{className:"muted nowrap",children:F(d.lastSeen)}),e.jsx("td",{className:"num",children:(x==null?void 0:x.requests)??0}),e.jsx("td",{className:"muted nowrap",children:x!=null&&x.lastRequest?F(x.lastRequest):"—"}),e.jsx("td",{children:e.jsx($,{size:"sm",variant:f?"quiet":"primary",busy:l===`access-${d.id}`,onClick:()=>void u(d.id),children:f?"Remove access":"Give access"})})]},d.id)})})]})})})]})]})}function qt(){const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a}=ie(),{busy:l,run:i}=ne(),[h,c]=g.useState(!1),o=s==null?void 0:s.forYou,u=!!(s!=null&&s.forYouRunning),p=(d,x,f)=>i(x,async()=>{await a(()=>D.post("/admin/api/for-you",{action:d}),f),c(!1),await r()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"For You",intro:"The prepared pools personalised rows are drawn from."}),e.jsx(_,{message:n}),t?e.jsx(V,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"Tracearr sessions",value:w((o==null?void 0:o.tracearrSessions)??0),icon:"play",tone:"info"},{label:"user profiles",value:w((o==null?void 0:o.profiles)??0),icon:"people",tone:"note"},{label:"ranked candidates",value:w((o==null?void 0:o.candidates)??0),icon:"sparkle",tone:"note"},{label:"last full import",value:F(o==null?void 0:o.lastFullImport),small:!0,icon:"clock"}]}),e.jsx(C,{title:"Pool maintenance",intro:"Prepared pools refresh in the background; these are the manual versions of the same work. A rebuild is safe at any time — televisions read the last finished pool until a new one lands.",icon:"sparkle",tone:"note",footer:e.jsx("span",{className:"hint",children:u?"For You maintenance running…":"Prepared pools normally refresh in the background."}),children:e.jsxs("div",{className:"row",children:[e.jsx($,{variant:"primary",icon:"download",disabled:u,busy:l==="import",onClick:()=>void p("incremental-import","import","Import started."),children:"Import recent sessions"}),e.jsx($,{icon:"database",disabled:u,onClick:()=>c(!0),children:"Full Tracearr backfill"}),e.jsx($,{icon:"sync",disabled:u,busy:l==="rebuild",onClick:()=>void p("rebuild-all","rebuild","Rebuild started."),children:"Rebuild all pools"})]})}),e.jsx(C,{title:"Reading a person's scores",intro:"The inspector re-runs the shared weighted scorer over one person's prepared pool, after Emby permission and parental-control filtering, and shows every component and evidence reason behind the order.",icon:"search",tone:"info",actions:e.jsx(Z,{to:"/admin/inspector",children:"Open the inspector"}),children:e.jsx(e.Fragment,{})})]}),h?e.jsx(ke,{title:"Backfill all Tracearr history?",body:"Every session is re-read and every active user's pool is rebuilt. It is safe at any time — televisions keep reading the last finished pool — but on a long history it takes a while.",confirmLabel:"Backfill",busy:l==="full",onConfirm:()=>void p("full-import","full","Backfill started."),onCancel:()=>c(!1)}):null]})}const Dt=[["Genre","genres"],["Studio","studios"],["Actor","actors"],["Director","directors"],["Franchise","franchises"],["Runtime","runtimeRanges"],["Age rating","ageRatings"],["Community rating","communityRatings"],["Release period","releasePeriods"],["Content type","contentTypes"]];function Ft(s){return s?Dt.flatMap(([n,t])=>Object.entries(s[t]??{}).map(([r,a])=>({dimension:n,name:r,weight:a.weight??0,evidence:a.evidence??0}))).sort((n,t)=>Math.abs(t.weight)-Math.abs(n.weight)):[]}const Bs=s=>`${s>=0?"+":""}${s.toFixed(3)}`;function Ot(){const{status:s}=je(),{wrap:n}=ie(),{busy:t,run:r}=ne(),[a,l]=g.useState(""),[i,h]=g.useState("default"),[c,o]=g.useState("0"),[u,p]=g.useState(""),[d,x]=g.useState(null),[f,m]=g.useState("Choose a person to inspect their recommendations."),[j,y]=g.useState(""),v=(s==null?void 0:s.requestUsers)??[],b=()=>r("run",async()=>{if(!a){y("Choose a person to pressure-test.");return}y(""),m("Running the permission check and the scorer…");const R=new URLSearchParams({userId:a,context:i,minutes:c||"0",limit:"100"});u&&R.set("at",new Date(u).toISOString());const L=await n(()=>D.get(`/admin/api/recommendations?${R.toString()}`));L?(x(L),m(`Scored at ${new Date().toLocaleTimeString()}.`)):m("Pressure test failed.")}),A=Ft((d==null?void 0:d.profile)??null).slice(0,24),k=(d==null?void 0:d.actions)??[],I=(d==null?void 0:d.items)??[],E=(d==null?void 0:d.profileMeta)??{};return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Score inspector",intro:"Re-run the ranker for one person and read every component."}),e.jsx(_,{message:j}),e.jsx(C,{title:"Run a pressure test",intro:"Nothing is changed by running this. It scores the person's prepared pool as the launcher would, in the context you choose.",icon:"search",tone:"info",footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:t==="run",onClick:()=>void b(),children:"Run pressure test"}),e.jsx("span",{className:"hint",children:f})]}),children:e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Person",children:e.jsxs("select",{value:a,onChange:R=>l(R.target.value),children:[e.jsx("option",{value:"",children:"Choose a person…"}),v.map(R=>e.jsx("option",{value:R.id,children:R.username},R.id))]})}),e.jsx(q,{label:"Context",children:e.jsxs("select",{value:i,onChange:R=>h(R.target.value),children:[e.jsx("option",{value:"default",children:"Default"}),e.jsx("option",{value:"bedtime",children:"One episode before bed"}),e.jsx("option",{value:"hidden",children:"Hidden library"}),e.jsx("option",{value:"new-releases",children:"Recent new releases"})]})}),e.jsx(q,{label:"Available minutes",children:e.jsx("input",{type:"number",min:0,max:360,value:c,onChange:R=>o(R.target.value)})}),e.jsx(q,{label:"Evaluate at",children:e.jsx("input",{type:"datetime-local",value:u,onChange:R=>p(R.target.value)})})]})}),d?e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"prepared pool",value:w(d.poolCandidates),icon:"database",tone:"data"},{label:"permission eligible",value:w(d.permissionEligible),icon:"shield",tone:"ok"},{label:"ranked result",value:w(I.length),icon:"sparkle",tone:"note"},{label:"source events",value:w(E.sourceEvents??0),icon:"pulse",tone:"info"},{label:"algorithm",value:E.algorithmVersion||"—",small:!0,icon:"chip"},{label:"pool built",value:F(E.poolBuiltAt),small:!0,icon:"clock"}]}),e.jsxs(C,{title:"Profile evidence",intro:"The strongest learned affinities, and every explicit action this person has taken.",icon:"sparkle",tone:"note",children:[A.length===0?e.jsx(ee,{children:"No repeated affinity evidence yet; cold-start priors apply."}):e.jsx("div",{className:"chips",children:A.map(R=>e.jsxs(ce,{tone:R.weight<0?"bad":void 0,children:[R.dimension,": ",R.name," ",Bs(R.weight)," · n=",w(R.evidence)]},`${R.dimension}:${R.name}`))}),k.length===0?e.jsx(ee,{children:"No explicit recommendation actions."}):e.jsx("div",{className:"chips",children:k.map((R,L)=>e.jsxs(ce,{tone:"ok",children:[R.action,": ",R.title||R.itemId]},`${R.action}:${L}`))})]}),I.length===0?e.jsx(C,{children:e.jsx(ee,{children:"No candidates survived this context, the explicit exclusions and the permission filter."})}):e.jsx(xe,{children:I.map((R,L)=>{const X=R.explanation??{},le=Object.entries(X.components??{}).sort((H,re)=>Math.abs(re[1])-Math.abs(H[1])),ue=R.exposure??{},te=[R.type,R.year,R.runtimeMinutes?`${R.runtimeMinutes} min`:null,...R.genres??[]].filter(Boolean).join(" · ");return e.jsxs(C,{title:`#${L+1} · ${R.title}`,intro:te,actions:e.jsx(ce,{tone:"ok",children:Number(X.total??0).toFixed(3)}),children:[e.jsxs("p",{className:"hint",children:[R.preparedReason||"No legacy prepared explanation",R.compatibilityLabel?` · ${R.compatibilityLabel}`:""]}),e.jsxs("div",{className:"chips",children:[(X.reasonCodes??[]).map(H=>e.jsx(ce,{tone:"ok",children:H},H)),le.map(([H,re])=>e.jsxs(ce,{tone:re<0?"bad":void 0,children:[H,"=",Bs(re)]},H))]}),e.jsxs("details",{children:[e.jsx("summary",{className:"muted",children:"Pool, row and exposure detail"}),e.jsxs("p",{className:"hint",children:["Base rank ",w(R.baseRank??0)," · base ",Number(R.baseScore??0).toFixed(3)," · affinity ",Number(R.affinityScore??0).toFixed(3)," · compatibility"," ",Number(R.compatibilityScore??0).toFixed(3)," · impressions"," ",w(ue.impressions??0)," · focuses ",w(ue.focuses??0)," · selects"," ",w(ue.selects??0)]}),e.jsx("div",{className:"chips",children:(R.eligibleRows??[]).map(H=>e.jsx(ce,{tone:"ok",children:H},H))}),R.preparedEvidenceTitle?e.jsxs("p",{className:"hint",children:["Prepared evidence: ",R.preparedEvidenceTitle]}):null]})]},`${L}:${R.title}`)})})]}):null]})}const Pt=4,Ee=[{id:"home",label:"Home",type:"films and television shows"},{id:"movies",label:"Movies",type:"films"},{id:"tv_shows",label:"TV Shows",type:"television shows"}],He=()=>({pinnedItems:[],primeSubtitle:""}),bs=[{value:1,short:"Mon",label:"Monday"},{value:2,short:"Tue",label:"Tuesday"},{value:3,short:"Wed",label:"Wednesday"},{value:4,short:"Thu",label:"Thursday"},{value:5,short:"Fri",label:"Friday"},{value:6,short:"Sat",label:"Saturday"},{value:0,short:"Sun",label:"Sunday"}];function Vs(s){const n=s.getTimezoneOffset()*6e4;return new Date(s.getTime()-n).toISOString().slice(0,16)}function Hs(s){return!!(s&&Number.isFinite(new Date(s).getTime())&&new Date(s).getFullYear()>=2e3)}function _t(s){return s.frequency??"once"}function Ut(s){if(s.frequency==="daily")return`Every day · ${s.startTime}${s.endTime}`;if(s.frequency==="weekly"){const n=bs.filter(r=>(s.weekdays??[]).includes(r.value));return`${(n.length===7?"Every day":n.map(r=>r.short).join(", "))||"No days selected"} · ${s.startTime}${s.endTime}`}return`${s.startAt?new Date(s.startAt).toLocaleString():"Start missing"}${s.endAt?new Date(s.endAt).toLocaleString():"End missing"}`}function zs(s,n){const t=new Date;t.setMinutes(Math.ceil(t.getMinutes()/30)*30,0,0);const r=new Date(t.getTime()+2*60*60*1e3),a=n==="home"||n==="movies"&&s.type==="Movie"||n==="tv_shows"&&s.type==="Series";return{id:crypto.randomUUID(),itemId:s.id,startAt:t.toISOString(),endAt:r.toISOString(),priority:0,enabled:!0,placements:[a?n:"home"]}}function Wt(){var te,H,re;const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a,show:l}=ie(),{busy:i,run:h}=ne(),[c,o]=g.useState("home"),[u,p]=g.useState({home:He(),movies:He(),tv_shows:He()}),[d,x]=g.useState(!1),[f,m]=g.useState(""),[j,y]=g.useState(null),[v,b]=g.useState([]),[A,k]=g.useState(null),I=s==null?void 0:s.heroPolicy;g.useEffect(()=>{var S,O,z;d||!I||(p({home:((S=I.placements)==null?void 0:S.home)??{pinnedItems:I.pinnedItems??[],primeSubtitle:I.primeSubtitle??""},movies:((O=I.placements)==null?void 0:O.movies)??He(),tv_shows:((z=I.placements)==null?void 0:z.tv_shows)??He()}),b(I.schedules??[]))},[I,d]);const E=()=>h("search",async()=>{const S=f.trim();if(!S)return;const O=await a(()=>D.get(`/admin/api/hero/search?q=${encodeURIComponent(S)}`));O&&y(O.items??[])}),R=u[c],L=R.pinnedItems??[],X=S=>{p(O=>({...O,[c]:{...O[c],...S}})),x(!0)},le=S=>{if(!L.some(O=>O.id===S.id)){if(L.length>=Pt){l("Remove a pinned title before adding another.","bad");return}X({pinnedItems:[...L,S]})}},ue=()=>h("save",async()=>{await a(()=>D.post("/admin/api/hero-policy",{placements:Object.fromEntries(Object.entries(u).map(([S,O])=>[S,{pinnedItemIds:(O.pinnedItems??[]).map(z=>z.id),primeSubtitle:O.primeSubtitle.trim()}])),schedules:v}),"Hero saved."),x(!1),await r()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Featured content",intro:"Manage an independent, backend-resolved hero for Home, Movies and TV Shows."}),e.jsx(_,{message:n}),t?e.jsx(V,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{children:Ee.map(S=>{var Re;const O=u[S.id],z=v.filter(ge=>ge.enabled&&(ge.placements??["home"]).includes(S.id)).sort((ge,T)=>T.priority-ge.priority)[0],oe=(O.pinnedItems??[]).length?"Manual":z?"Schedule ready":"Automatic",we=(Re=I==null?void 0:I.items)==null?void 0:Re.find(ge=>ge.id===(z==null?void 0:z.itemId)),Te=(O.pinnedItems??[]).map(ge=>ge.name).join(", ")||(we==null?void 0:we.name)||(z==null?void 0:z.itemId)||"Resolved for each viewer";return e.jsx(C,{title:S.label,intro:`${oe} · ${Te}`,tone:S.id===c?"info":void 0,children:e.jsxs($,{size:"sm",variant:"quiet",onClick:()=>o(S.id),children:["Manage ",S.label]})},S.id)})}),e.jsx("div",{className:"tabs",role:"tablist","aria-label":"Hero placement",children:Ee.map(S=>e.jsx($,{variant:c===S.id?"primary":"quiet",onClick:()=>o(S.id),children:S.label},S.id))}),e.jsxs(C,{title:`${(te=Ee.find(S=>S.id===c))==null?void 0:te.label} hero`,intro:`Pinned ${(H=Ee.find(S=>S.id===c))==null?void 0:H.type} lead this section only. Empty places use this placements automatic selection.`,icon:"star",tone:"note",footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:i==="save",onClick:()=>void ue(),children:"Save hero"}),e.jsx($,{onClick:()=>{X({pinnedItems:[]})},children:"Clear pins"}),d?e.jsx("span",{className:"hint",children:"Unsaved changes."}):null]}),children:[L.length===0?e.jsx(ee,{children:"No titles are pinned. The hero is entirely release-aware and automatic."}):e.jsx("div",{className:"hero-pins",children:L.map((S,O)=>e.jsxs("div",{className:"hero-pin",children:[e.jsx("span",{className:"hero-pin-order",children:O+1}),e.jsxs("span",{children:[e.jsx("b",{children:S.name}),e.jsxs("small",{children:[S.type,S.year?` · ${S.year}`:""]})]}),e.jsx($,{size:"sm",icon:"clock",onClick:()=>k(zs(S,c)),children:"Schedule"}),e.jsx($,{variant:"quiet",size:"sm",icon:"close",title:`Remove ${S.name}`,onClick:()=>X({pinnedItems:L.filter(z=>z.id!==S.id)})})]},S.id))}),e.jsx(q,{label:"Prime-card subtitle",hint:"Optional wording under the large first card. Leave blank to use Memby's natural release or rating reason.",children:e.jsx("input",{type:"text",maxLength:160,value:R.primeSubtitle,placeholder:"Leave blank for the automatic reason",onChange:S=>{X({primeSubtitle:S.target.value})}})})]}),e.jsx(C,{title:"Hero schedule",intro:"The gateway applies these rules in server time. Manual pins win first; otherwise the highest-priority active schedule wins, followed by Membys automatic hero.",icon:"clock",tone:"info",actions:e.jsx(N,{tone:"info",children:(I==null?void 0:I.timeZone)||"server local time"}),footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:i==="save",onClick:()=>void ue(),children:"Save schedule"}),e.jsx("span",{className:"hint",children:"Daily and weekly rules repeat until you switch them off."})]}),children:v.length===0?e.jsx(ee,{children:"No scheduled heroes yet. Use Schedule beside a pinned or searched title."}):e.jsx("div",{className:"hero-schedule-list",children:[...v].sort((S,O)=>Number(O.enabled)-Number(S.enabled)||O.priority-S.priority).map(S=>{const O=[...(I==null?void 0:I.items)??[],...L,...j??[]].find(z=>z.id===S.itemId);return e.jsxs("article",{className:"hero-schedule","data-enabled":S.enabled||void 0,children:[e.jsxs("div",{className:"hero-schedule-time",children:[e.jsx("b",{children:S.frequency==="weekly"?"Weekly":S.frequency==="daily"?"Daily":"Once"}),e.jsx("span",{children:S.frequency?S.startTime:S.startAt?new Date(S.startAt).toLocaleDateString():"—"})]}),e.jsxs("div",{className:"hero-schedule-main",children:[e.jsxs("div",{className:"hero-schedule-title",children:[e.jsx("h3",{children:(O==null?void 0:O.name)??S.itemId}),e.jsx(N,{tone:S.enabled?"ok":void 0,children:S.enabled?"enabled":"paused"})]}),e.jsx("p",{children:Ut(S)}),e.jsxs("div",{className:"chips",children:[(S.placements??["home"]).map(z=>{var oe;return e.jsx("span",{className:"chip",children:(oe=Ee.find(we=>we.id===z))==null?void 0:oe.label},z)}),S.priority!==0?e.jsxs("span",{className:"chip",children:["Priority ",S.priority]}):null]})]}),e.jsxs("div",{className:"hero-schedule-actions",children:[e.jsx($,{size:"sm",onClick:()=>k({...S}),children:"Edit"}),e.jsx($,{size:"sm",variant:"quiet",onClick:()=>{b(z=>z.map(oe=>oe.id===S.id?{...oe,enabled:!oe.enabled}:oe)),x(!0)},children:S.enabled?"Pause":"Enable"}),e.jsx($,{size:"sm",variant:"quiet",onClick:()=>{b(z=>z.filter(oe=>oe.id!==S.id)),x(!0)},children:"Remove"})]})]},S.id)})})}),e.jsxs(C,{title:"Find a title",intro:`Search the imported Emby catalogue. Add a result to the selected ${(re=Ee.find(S=>S.id===c))==null?void 0:re.label} placement; switch tabs to show it in more than one section.`,icon:"search",tone:"info",children:[e.jsxs("div",{className:"field-row",children:[e.jsx(q,{label:"Title",grow:!0,children:e.jsx("input",{type:"search",value:f,placeholder:"Search films and television shows",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&E()}})}),e.jsx($,{busy:i==="search",icon:"search",onClick:()=>void E(),children:"Search"})]}),j===null?null:j.length===0?e.jsx(ee,{children:"No playable films or series matched that search."}):e.jsx(xe,{children:j.map(S=>e.jsx(C,{title:S.name,intro:`${S.type||"Title"} · ${S.year||"Year unknown"}`,children:e.jsxs("div",{className:"row",children:[e.jsx($,{size:"sm",icon:"plus",disabled:L.some(O=>O.id===S.id)||c==="movies"&&S.type!=="Movie"||c==="tv_shows"&&S.type!=="Series",onClick:()=>le(S),children:L.some(O=>O.id===S.id)?"Pinned":"Add to hero"}),e.jsx($,{size:"sm",icon:"clock",onClick:()=>k(zs(S,c)),children:"Schedule"})]})},S.id))})]})]}),A?e.jsx(Bt,{schedule:A,item:[...(I==null?void 0:I.items)??[],...L,...j??[]].find(S=>S.id===A.itemId),timeZone:(I==null?void 0:I.timeZone)||"server local time",isNew:!v.some(S=>S.id===A.id),onCancel:()=>k(null),onSave:S=>{b(O=>O.some(z=>z.id===S.id)?O.map(z=>z.id===S.id?S:z):[...O,S]),k(null),x(!0)}}):null]})}function Bt({schedule:s,item:n,timeZone:t,isNew:r,onSave:a,onCancel:l}){const[i,h]=g.useState({...s,weekdays:[...s.weekdays??[]]}),c=_t(i),o=m=>{const j=new Date,y=new Date(j.getTime()+2*60*60*1e3);h(v=>{var b;return m==="once"?{...v,frequency:void 0,startAt:Hs(v.startAt)?v.startAt:j.toISOString(),endAt:Hs(v.endAt)?v.endAt:y.toISOString()}:{...v,frequency:m,startTime:v.startTime||"18:00",endTime:v.endTime||"22:00",weekdays:m==="weekly"?(b=v.weekdays)!=null&&b.length?v.weekdays:[1,2,3,4,5]:[]}})},u=i.placements??["home"],p=m=>m==="home"||m==="movies"&&(n==null?void 0:n.type)==="Movie"||m==="tv_shows"&&(n==null?void 0:n.type)==="Series",d=!!(i.startAt&&i.endAt&&new Date(i.endAt)>new Date(i.startAt)),x=!!(i.startTime&&i.endTime&&i.startTime!==i.endTime&&(c!=="weekly"||(i.weekdays??[]).length>0)),f=c==="once"?d:x;return e.jsx("div",{className:"scrim",onPointerDown:m=>m.target===m.currentTarget&&l(),children:e.jsxs("div",{className:"dialog hero-schedule-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"hero-schedule-title",children:[e.jsxs("div",{className:"hero-schedule-dialog-head",children:[e.jsx("span",{className:"hero-schedule-kicker",children:"Hero schedule"}),e.jsx("h2",{id:"hero-schedule-title",children:(n==null?void 0:n.name)??i.itemId}),e.jsxs("p",{children:["Choose exactly when this title can lead the selected sections. Times use ",t,"."]})]}),e.jsx("div",{className:"schedule-frequency",role:"group","aria-label":"Schedule frequency",children:["once","daily","weekly"].map(m=>e.jsxs("button",{type:"button","aria-pressed":c===m,onClick:()=>o(m),children:[e.jsx("b",{children:m==="once"?"One time":m==="daily"?"Every day":"Weekly"}),e.jsx("span",{children:m==="once"?"A date range":m==="daily"?"Same time daily":"Choose days"})]},m))}),c==="once"?e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Starts",children:e.jsx("input",{type:"datetime-local",value:i.startAt?Vs(new Date(i.startAt)):"",onChange:m=>h(j=>({...j,startAt:m.target.value?new Date(m.target.value).toISOString():void 0}))})}),e.jsx(q,{label:"Ends",children:e.jsx("input",{type:"datetime-local",value:i.endAt?Vs(new Date(i.endAt)):"",onChange:m=>h(j=>({...j,endAt:m.target.value?new Date(m.target.value).toISOString():void 0}))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Starts each time",children:e.jsx("input",{type:"time",value:i.startTime??"",onChange:m=>h(j=>({...j,startTime:m.target.value}))})}),e.jsx(q,{label:"Ends each time",hint:"An earlier end time continues into the following day.",children:e.jsx("input",{type:"time",value:i.endTime??"",onChange:m=>h(j=>({...j,endTime:m.target.value}))})})]}),c==="weekly"?e.jsxs("div",{className:"schedule-days",children:[e.jsxs("div",{className:"schedule-days-head",children:[e.jsx("b",{children:"Days"}),e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>h(m=>({...m,weekdays:[1,2,3,4,5]})),children:"Weekdays"}),e.jsx("button",{type:"button",onClick:()=>h(m=>({...m,weekdays:[6,0]})),children:"Weekend"}),e.jsx("button",{type:"button",onClick:()=>h(m=>({...m,weekdays:bs.map(j=>j.value)})),children:"Every day"})]})]}),e.jsx("div",{className:"schedule-day-grid",children:bs.map(m=>{const j=(i.weekdays??[]).includes(m.value);return e.jsx("button",{type:"button","aria-pressed":j,title:m.label,onClick:()=>h(y=>({...y,weekdays:j?(y.weekdays??[]).filter(v=>v!==m.value):[...y.weekdays??[],m.value]})),children:m.short},m.value)})})]}):null]}),e.jsxs("div",{className:"schedule-options",children:[e.jsxs("div",{children:[e.jsx("span",{className:"schedule-option-label",children:"Show in"}),e.jsx("div",{className:"schedule-placement-grid",children:Ee.map(m=>e.jsx(G,{label:m.label,checked:u.includes(m.id),disabled:!p(m.id),onChange:j=>h(y=>{const v=y.placements??["home"],b=j?[...v,m.id]:v.filter(A=>A!==m.id);return{...y,placements:b.length?[...new Set(b)]:v}})},m.id))})]}),e.jsx(q,{label:"Priority",hint:"Higher rules win when schedules overlap.",children:e.jsx("input",{type:"number",min:-1e3,max:1e3,step:10,value:i.priority,onChange:m=>h(j=>({...j,priority:Number(m.target.value)}))})})]}),e.jsx(G,{label:"Schedule enabled",hint:"Pause it without losing its days and times.",checked:i.enabled,onChange:m=>h(j=>({...j,enabled:m}))}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx($,{variant:"quiet",onClick:l,children:"Cancel"}),e.jsx($,{variant:"primary",disabled:!f,onClick:()=>a(i),children:r?"Add rule":"Save rule"})]})]})})}const Ks=["title","ratings","facts","summary"];function Vt(){var p;const s=J("/admin/api/metadata-hero"),{busy:n,run:t}=ne(),{wrap:r}=ie(),[a,l]=g.useState(null);g.useEffect(()=>{a===null&&s.data&&l(s.data.settings.contentOrder)},[a,s.data]);const i=a??Ks,h=((p=s.data)==null?void 0:p.options)??[],c=[...i,...h.map(d=>d.value).filter(d=>!i.includes(d))],o=(d,x)=>{const f=i.indexOf(d),m=f+x;if(f<0||m<0||m>=i.length)return;const j=[...i],y=j[f];j[f]=j[m],j[m]=y,l(j)},u=()=>t("save",async()=>{const d=await r(()=>D.post("/admin/api/metadata-hero",{contentOrder:i}),"Metadata hero saved for every television.");d&&(s.set(d),l(d.settings.contentOrder))});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Metadata hero",intro:"Choose which content appears beside focused browse cards, and the order every television uses."}),e.jsx(_,{message:s.error}),s.loading?e.jsx(V,{rows:2}):e.jsxs("div",{className:"metadata-hero-layout",children:[e.jsx(C,{title:"Content order",intro:"Enabled blocks are drawn from top to bottom. Changes apply to the whole household.",icon:"sliders",footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:n==="save",onClick:()=>void u(),children:"Save metadata hero"}),e.jsx($,{onClick:()=>l(Ks),children:"Restore default order"})]}),children:e.jsx("div",{className:"metadata-hero-order",children:c.map(d=>{const x=h.find(j=>j.value===d);if(!x)return null;const f=i.indexOf(d),m=f>=0;return e.jsxs("div",{className:"metadata-hero-order-row","data-enabled":m||void 0,children:[e.jsx("span",{className:"metadata-hero-order-number",children:m?f+1:"—"}),e.jsx(G,{label:x.label,hint:x.description,checked:m,disabled:m&&i.length===1,onChange:j=>l(j?[...i,d]:i.filter(y=>y!==d))}),e.jsxs("div",{className:"metadata-hero-order-actions",children:[e.jsx($,{size:"sm",variant:"quiet",disabled:!m||f===0,title:`Move ${x.label} up`,onClick:()=>o(d,-1),children:"↑"}),e.jsx($,{size:"sm",variant:"quiet",disabled:!m||f===i.length-1,title:`Move ${x.label} down`,onClick:()=>o(d,1),children:"↓"})]})]},d)})})}),e.jsx(C,{title:"Television preview",intro:"A representative focused film at launcher scale and in the current order.",icon:"tv",children:e.jsxs("div",{className:"metadata-hero-preview","aria-label":"Metadata hero preview",children:[e.jsx("div",{className:"metadata-hero-preview-copy",children:i.map(d=>d==="title"?e.jsx("div",{className:"metadata-preview-title",children:"THE SOUTHERN LIGHT"},d):d==="ratings"?e.jsxs("div",{className:"metadata-preview-ratings",children:[e.jsx("b",{children:"IMDb 8.2"}),e.jsx("b",{children:"TMDb 81%"})]},d):d==="facts"?e.jsxs("div",{className:"metadata-preview-facts",children:[e.jsx("span",{children:"2026    1h 54m    M    Drama, Mystery"}),e.jsx("b",{children:"4K"}),e.jsx("b",{children:"5.1"})]},d):d==="recommendation_reason"?e.jsx("div",{className:"metadata-preview-reason",children:"Because you watched Harbour Lights"},d):d==="time_remaining"?e.jsxs("div",{className:"metadata-preview-progress",children:[e.jsx("span",{children:e.jsx("i",{})}),e.jsx("b",{children:"47 MINUTES REMAINING"})]},d):d==="summary"?e.jsx("p",{className:"metadata-preview-summary",children:"A quiet coastal town follows an unexpected signal across the winter sky."},d):null)}),e.jsx("div",{className:"metadata-hero-preview-art","aria-hidden":"true"})]})})]})]})}function Ht(){const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a}=ie(),{busy:l,run:i}=ne(),[h,c]=g.useState(null),o=s==null?void 0:s.features,u=(o==null?void 0:o.features)??[],p=(s==null?void 0:s.clients)??[],d=(o==null?void 0:o.revision)??0,x=(y,v,b,A)=>i(v,async()=>{await a(()=>D.post("/admin/api/features",{action:y,expectedRevision:d,overrides:A??{}}),b),c(null),await r()}),f=p.filter(y=>(y.capabilities??[]).includes("server_features_v1")).length,m=!!(o!=null&&o.safeMode),j=(y,v)=>({...Object.fromEntries(u.filter(b=>b.source==="override").map(b=>[b.key,b.enabled])),[y]:v});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Features",intro:"Roll out, stop and recover optional behaviour with no app release."}),e.jsx(_,{message:n}),t||!o?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(C,{title:"Control plane",intro:"Every optional feature has a safe default, an explicit override and a remote recovery path. Safe mode turns all of them off at once; sign-in, browsing and playback are never optional.",icon:"sliders",tone:"ok",actions:e.jsx($,{variant:m?void 0:"danger",busy:l==="safe",onClick:()=>m?void x("leave-safe-mode","safe","Safe mode ended."):c({action:"safe-mode",title:"Enable safe mode?",body:"Every optional feature is disabled immediately on every television. Core sign-in, browsing and playback remain available.",label:"Enable safe mode"}),children:m?"Leave safe mode":"Enable safe mode"}),children:e.jsx(Ms,{tiles:[{label:"features active",value:`${u.filter(y=>y.enabled).length} / ${u.length}`},{label:"explicit overrides",value:w(u.filter(y=>y.source==="override").length)},{label:"televisions reporting the control plane",value:`${f} / ${p.length}`},{label:"published revision",value:`r${w(d)}`}]})}),e.jsx(xe,{cols:"2",children:u.length===0?e.jsx(C,{title:"Nothing registered",icon:"sliders",children:e.jsx(ee,{children:"No server features are registered."})}):u.map(y=>e.jsxs(C,{title:y.name,intro:y.description,actions:e.jsx(N,{tone:y.enabled?"ok":void 0,children:y.enabled?"active":"off"}),footer:e.jsxs("span",{className:"hint",children:["↳ ",y.recovery]}),children:[e.jsx(G,{label:y.enabled?"On":"Off",hint:"Changing this applies the feature policy to every compatible television.",checked:y.enabled,disabled:l===y.key,onChange:v=>c({action:"feature",key:y.key,enabled:v,title:`${v?"Turn on":"Turn off"} ${y.name}?`,body:`${v?"Enable":"Disable"} this feature for every compatible television. ${y.recovery}`,label:v?"Turn on":"Turn off"})}),e.jsxs("div",{className:"chips",children:[e.jsx(ce,{children:y.key}),e.jsxs(ce,{children:["protocol ",w(y.minimumProtocol),"+"]}),e.jsx(ce,{tone:y.compatible?"ok":"warn",children:y.compatible?"server compatible":"compatibility blocked"}),e.jsx(ce,{tone:"note",children:y.area})]})]},y.key))}),e.jsx(C,{children:e.jsxs("div",{className:"row",children:[e.jsx($,{disabled:!o.canRollback,onClick:()=>c({action:"rollback",title:"Roll back one revision?",body:"The previous published feature revision is restored on every television.",label:"Roll back"}),children:"Roll back one revision"}),e.jsx($,{onClick:()=>c({action:"reset",title:"Clear every override?",body:"All features return to their safe software defaults.",label:"Clear overrides"}),children:"Clear all overrides"}),e.jsx("span",{className:"spacer"}),m?e.jsx(N,{tone:"warn",children:"safe mode · optional features off"}):e.jsxs(N,{tone:"ok",children:["live · revision r",w(d)]})]})})]}),h?e.jsx(ke,{title:h.title,body:h.body,confirmLabel:h.label,destructive:h.action!=="rollback",busy:l===h.action,onConfirm:()=>void x(h.action==="feature"?"save":h.action,h.action==="feature"?h.key??"feature":h.action,`${h.label} done.`,h.action==="feature"&&h.key?j(h.key,!!h.enabled):void 0),onCancel:()=>c(null)}):null]})}function zt(){const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a,show:l}=ie(),{busy:i,run:h}=ne(),[c,o]=g.useState(!0),[u,p]=g.useState("6.5"),[d,x]=g.useState(!1);g.useEffect(()=>{var m,j;d||!s||(o(((m=s.playbackPolicy)==null?void 0:m.prerollEnabled)!==!1),p(String((((j=s.playbackPolicy)==null?void 0:j.prerollDurationMs)??6500)/1e3)))},[s,d]);const f=()=>h("save",async()=>{const m=Number(u);if(!Number.isFinite(m)||m<1||m>30){l("The preroll duration must be between 1 and 30 seconds.","bad");return}await a(()=>D.post("/admin/api/playback-policy",{prerollEnabled:c,prerollDurationMs:Math.round(m*1e3)}),"Playback policy saved."),x(!1),await r()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Playback",intro:"Presentation policy sent with every playback launch."}),e.jsx(_,{message:n}),t?e.jsx(V,{rows:1}):e.jsxs(C,{title:"Upcoming-show preroll",intro:"Sent with every playback launch. A change applies to the next title opened on every gateway-connected television; no app release is required.",icon:"play",tone:"info",actions:c?e.jsxs(N,{tone:"ok",children:["on · ",u,"s"]}):e.jsx(N,{children:"off"}),footer:e.jsx($,{variant:"primary",busy:i==="save",onClick:()=>void f(),children:"Save playback policy"}),children:[e.jsx(G,{label:"Show the preroll before a title starts",checked:c,onChange:m=>{o(m),x(!0)}}),e.jsx("div",{className:"fields",children:e.jsx(q,{label:"Duration",hint:"Between 1 and 30 seconds. The stream is already playing behind it.",children:e.jsx("input",{type:"number",min:1,max:30,step:.5,value:u,onChange:m=>{p(m.target.value),x(!0)}})})})]})]})}function Kt(){const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a}=ie(),{busy:l,run:i}=ne(),[h,c]=g.useState(null),[o,u]=g.useState(null),[p,d]=g.useState(!1),x=s==null?void 0:s.subtitles,f=x==null?void 0:x.stored;g.useEffect(()=>{h||!x||c({bazarr:x.bazarrEnabled,openSubtitles:x.openSubtitlesEnabled,key:"",clearKey:!1,username:x.openSubtitlesUsername??"",password:"",clearLogin:!1})},[x,h]);const m=b=>c(A=>A&&{...A,...b}),j=()=>i("save",async()=>{h&&(await a(()=>D.post("/admin/api/subtitle-settings",{bazarrEnabled:h.bazarr,openSubtitlesEnabled:h.openSubtitles,openSubtitlesApiKey:h.key.trim(),clearOpenSubtitlesApiKey:h.clearKey,openSubtitlesUsername:h.username.trim(),openSubtitlesPassword:h.password,clearOpenSubtitlesLogin:h.clearLogin}),"Subtitle settings saved."),c(null),await r())}),y=()=>i("test",async()=>{u(null);const b=await a(()=>D.post("/admin/api/subtitle-test"));u((b==null?void 0:b.results)??[])}),v=()=>i("clear",async()=>{await a(()=>D.post("/admin/api/subtitle-settings",{action:"clear-stored"}),"Stored subtitles deleted."),d(!1),await r()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Subtitles",intro:"Which providers a viewer may fetch a missing subtitle from."}),e.jsx(_,{message:n}),t||!x||!h?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"offered on televisions",value:x.available?"yes":"no",small:!0,icon:"captions",tone:x.available?"ok":void 0},{label:"providers on",value:w((x.bazarrEnabled&&x.bazarrConfigured?1:0)+(x.openSubtitlesEnabled?1:0)),icon:"list",tone:"note"},{label:"subtitles held",value:w((f==null?void 0:f.count)??0),icon:"database",tone:"data"},{label:"last fetched",value:F(f==null?void 0:f.latest),small:!0,icon:"clock"}]}),e.jsxs(xe,{cols:"2",children:[e.jsx(C,{title:"Bazarr",intro:"Bazarr writes the subtitle file beside the media file, so Emby finds it and the track behaves like one that was always there. Its address is deployment configuration; this switch only decides whether viewers may use it.",icon:"wrench",tone:"data",actions:x.bazarrConfigured?h.bazarr?e.jsx(N,{tone:"ok",children:"on"}):e.jsx(N,{children:"off"}):e.jsx(N,{children:"not configured"}),footer:e.jsx("span",{className:"hint",children:x.bazarrConfigured?`Configured at ${x.bazarrUrl}`:"Set MEMBY_BAZARR_URL and MEMBY_BAZARR_API_KEY to use Bazarr."}),children:e.jsx(G,{label:"Offer Bazarr in the player",hint:"Off leaves every subtitle it has already written in place.",checked:h.bazarr,disabled:!x.bazarrConfigured,onChange:b=>m({bazarr:b})})}),e.jsxs(C,{title:"OpenSubtitles",intro:"OpenSubtitles hands back a file rather than writing one, so Memby keeps what it fetches and serves it to the television itself. Titles are matched on their IMDb or TMDb id, which is exact — there is no guessing at a name.",icon:"captions",tone:"note",actions:x.openSubtitlesEnabled?e.jsx(N,{tone:x.openSubtitlesAccount?"ok":"warn",children:x.openSubtitlesAccount?"on · signed in":"on · anonymous"}):e.jsx(N,{children:x.openSubtitlesKeyConfigured?"off · key saved":"off · no key"}),children:[e.jsx(G,{label:"Offer OpenSubtitles in the player",hint:"Needs an API key. It cannot be switched on without one.",checked:h.openSubtitles,onChange:b=>m({openSubtitles:b})}),e.jsx(q,{label:"API key",hint:"From your consumer at opensubtitles.com. Leave blank to keep the saved key.",children:e.jsx("input",{type:"password",autoComplete:"new-password",value:h.key,placeholder:x.openSubtitlesKeyConfigured?"Saved key (leave blank to keep)":"Paste an API key",onChange:b=>m({key:b.target.value})})}),e.jsx(G,{label:"Remove the saved key",checked:h.clearKey,onChange:b=>m({clearKey:b})}),e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Account username",hint:"Optional, and the difference between a working feature and one that stops after a few files: without an account, downloads come out of the small anonymous allowance.",children:e.jsx("input",{type:"text",autoComplete:"off",value:h.username,placeholder:"Not signed in",onChange:b=>m({username:b.target.value})})}),e.jsx(q,{label:"Account password",hint:"Leave blank to keep the saved one.",children:e.jsx("input",{type:"password",autoComplete:"new-password",value:h.password,onChange:b=>m({password:b.target.value})})})]}),e.jsx(G,{label:"Sign out and forget the account",checked:h.clearLogin,onChange:b=>m({clearLogin:b})})]})]}),e.jsxs(C,{children:[e.jsxs("div",{className:"row",children:[e.jsx($,{variant:"primary",busy:l==="save",onClick:()=>void j(),children:"Save subtitle settings"}),e.jsx($,{busy:l==="test",icon:"pulse",onClick:()=>void y(),children:"Test the providers"}),e.jsx("span",{className:"hint",children:x.featureEnabled?"A change applies to the next title opened; no app release is required.":"Downloading subtitles is switched off on the Features page, so nothing here is offered."})]}),o===null?null:o.length===0?e.jsx(ee,{children:"No provider is switched on, so there was nothing to ask."}):e.jsx("div",{className:"list",children:o.map(b=>e.jsxs("div",{className:"list-item",children:[e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:b.provider}),e.jsx("p",{children:b.message})]}),e.jsx("div",{className:"list-actions",children:e.jsx(N,{tone:b.ok?"ok":"bad",children:b.ok?"reachable":"not reachable"})})]},b.provider))})]}),e.jsx(C,{title:"Subtitles Memby is holding",intro:"Only files fetched from a provider that cannot write beside the media file are kept here; they are served to televisions as ordinary tracks on every later playback. Emptying this is safe — each one can be fetched again, at the cost of the download allowance that fetched it.",icon:"database",tone:"data",actions:f!=null&&f.count?e.jsxs(N,{tone:"data",children:[w(f.count)," files · ",he(f.bytes)]}):e.jsx(N,{children:"nothing held"}),footer:e.jsx($,{variant:"danger",disabled:!(f!=null&&f.count),onClick:()=>d(!0),children:"Delete every stored subtitle"}),children:e.jsx(e.Fragment,{})})]}),p?e.jsx(ke,{title:"Delete every stored subtitle?",body:"Each one can be fetched again, at the cost of the download allowance that fetched it. Subtitles Bazarr wrote beside the media are untouched — those belong to Emby.",confirmLabel:"Delete",destructive:!0,busy:l==="clear",onConfirm:()=>void v(),onCancel:()=>d(!1)}):null]})}function Gt(){const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a}=ie(),{busy:l,run:i}=ne(),[h,c]=g.useState(null),[o,u]=g.useState(!1),p=s==null?void 0:s.updatePolicy;g.useEffect(()=>{h||!p||c({version:p.latestVersion??"",url:p.downloadUrl??"",notes:p.notes??"",retireBelow:p.retireBelowVersion??"",required:!!p.minimumVersion&&p.minimumVersion===p.latestVersion,destructive:!!p.retireBelowVersion&&p.retireBelowVersion===p.latestVersion})},[p,h]);const d=j=>i(j?"save":"off",async()=>{h&&(await a(()=>D.post("/admin/api/update-policy",{enabled:j,latestVersion:h.version.trim(),downloadUrl:h.url.trim(),notes:h.notes.trim(),required:h.required,destructive:h.destructive,retireBelowVersion:h.retireBelow.trim()}),j?"Update policy saved.":"Update prompts turned off."),u(!1),c(null),await r())}),x=!!(p!=null&&p.minimumVersion)&&(p==null?void 0:p.minimumVersion)===(p==null?void 0:p.latestVersion),f=!!(p!=null&&p.retireBelowVersion)&&(p==null?void 0:p.retireBelowVersion)===(p==null?void 0:p.latestVersion),m=j=>c(y=>y&&{...y,...j});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"App updates",intro:"Publish an optional or a required client update."}),e.jsx(_,{message:n}),t||!h?e.jsx(V,{rows:1}):e.jsxs(C,{title:"Update policy",intro:"Televisions check on every launch. An optional update is a prompt the viewer can dismiss; a required one covers the home screen until they update, so it needs a download URL that actually works.",icon:"download",tone:"info",actions:p!=null&&p.enabled?e.jsxs(N,{tone:x?"warn":"ok",children:[f?"sign-out · ":x?"required · ":"optional · ",p.latestVersion]}):e.jsx(N,{children:"off"}),footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:l==="save",onClick:()=>h.required?u(!0):void d(!0),children:"Save policy"}),e.jsx($,{busy:l==="off",onClick:()=>void d(!1),children:"Turn prompts off"})]}),children:[e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Latest version",children:e.jsx("input",{type:"text",value:h.version,placeholder:"0.2.63",onChange:j=>m({version:j.target.value})})}),e.jsx(q,{label:"APK URL",children:e.jsx("input",{type:"text",value:h.url,placeholder:"https://nas/memby/memby-0.2.63.apk",onChange:j=>m({url:j.target.value})})})]}),e.jsx(q,{label:"What's new",hint:"Shown on the television above the update button.",children:e.jsx("input",{type:"text",value:h.notes,placeholder:"One line the viewer reads",onChange:j=>m({notes:j.target.value})})}),e.jsx(q,{label:"Sign out builds below",hint:"The destructive compatibility floor. Leave blank to keep every supported viewer signed in.",children:e.jsx("input",{type:"text",value:h.retireBelow,placeholder:"0.2.44",onChange:j=>m({retireBelow:j.target.value})})}),e.jsx(G,{label:"Require this update",hint:"Blocks the home screen on every television below this version.",checked:h.required,onChange:j=>m({required:j})}),e.jsx(G,{label:"Set the destructive floor to this update",hint:"Deletes sessions on every older television when it next uses Memby, then shows the required update screen.",checked:h.destructive,onChange:j=>m(j?{destructive:!0,required:!0,retireBelow:h.version.trim()}:{destructive:!1,retireBelow:h.retireBelow.trim()===h.version.trim()?"":h.retireBelow})})]}),o&&h?e.jsx(ke,{title:h.destructive?"Sign every older television out?":"Require this update?",body:h.destructive?"This deletes sessions on every older television and forces viewers to sign in again after updating.":"Required updates block the home screen on every television below this version until they update.",confirmLabel:"Publish",destructive:h.destructive,busy:l==="save",onConfirm:()=>void d(!0),onCancel:()=>u(!1)}):null]})}const Zt=[{value:60,label:"Every minute"},{value:300,label:"Every 5 minutes"},{value:600,label:"Every 10 minutes"},{value:900,label:"Every 15 minutes"},{value:1800,label:"Every 30 minutes"},{value:3600,label:"Hourly"},{value:10800,label:"Every 3 hours"},{value:21600,label:"Every 6 hours"},{value:43200,label:"Every 12 hours"},{value:86400,label:"Daily"},{value:604800,label:"Weekly"}];function Yt(s){const n=[...Zt];for(const t of[s.defaultIntervalSeconds,s.intervalSeconds])t>0&&!n.some(r=>r.value===t)&&n.push({value:t,label:Ne(t).replace(/^every /,"Every ")});return n.sort((t,r)=>t.value-r.value)}const Ke=s=>s.defaultIntervalSeconds>0&&s.intervalSeconds!==s.defaultIntervalSeconds;function us(s){return s==="failed"?"bad":s==="running"?"info":s==="skipped"?"warn":"ok"}function ls(s){if(s.running)return{state:"running",label:"Running",tone:"info",title:"Running right now"};if(!s.enabled)return{state:"disabled",label:"Disabled",tone:"warn",title:"Switched off — it will not run on its schedule"};const n=s.lastRun;return n?n.status==="failed"?{state:"failed",label:"Failed",tone:"bad",title:n.error||"The last run failed"}:n.status==="skipped"?{state:"skipped",label:"Skipped",tone:"warn",title:n.detail||"The last run declined to do anything"}:{state:"successful",label:"Successful",tone:"ok",title:"The last run finished cleanly"}:{state:"never",label:"Never run",tone:void 0,title:"This task has not run since the gateway started recording"}}function Jt(s){if(s.state==="running"||s.state==="successful")return"ok";if(s.state==="failed")return"bad";if(s.state==="disabled"||s.state==="skipped")return"warn"}const Gs={failed:0,running:1,skipped:2,disabled:3,never:4,successful:5};function Qt(s,n){const t=Gs[ls(s).state]-Gs[ls(n).state];if(t!==0)return t;if(!!s.group!=!!n.group)return s.group?-1:1;const r=s.group.localeCompare(n.group);return r!==0?r:s.name.localeCompare(n.name)}const Xt=2e4,ea=3e3;function sa(){const{wrap:s}=ie(),{busy:n,run:t}=ne(),[r,a]=g.useState(!1),{data:l,error:i,loading:h,reload:c}=J("/admin/api/tasks?limit=60",{pollMs:r?ea:Xt}),o=(l==null?void 0:l.tasks)??[],u=o.some(j=>j.running);u!==r&&a(u);const p=j=>t(j.id,async()=>{await s(()=>D.post(`/admin/api/tasks/${encodeURIComponent(j.id)}/run`),`${j.name} started.`),await c()}),d=o.filter(j=>{var y;return((y=j.lastRun)==null?void 0:y.status)==="failed"}).length,x=o.filter(Ke).length,f=o.filter(j=>!j.enabled).length,m=[...o].sort(Qt);return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Scheduled tasks",intro:"The gateway's background work: what it does, when it last ran, how long it took and whether it worked. Every one of these can be started by hand."}),e.jsx(_,{message:i}),h?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"Tasks",value:w(o.length),icon:"clock",tone:"info"},{label:"Running now",value:w(o.filter(j=>j.running).length),icon:"pulse",tone:u?"ok":void 0},{label:"Last run failed",value:w(d),icon:"alert",tone:d>0?"bad":void 0},{label:"Switched off",value:w(f),icon:"power",tone:f>0?"warn":void 0},{label:"Retimed",value:w(x),icon:"clock",tone:x>0?"note":void 0}]}),d>0?e.jsx(pe,{tone:"bad",children:"A failed task publishes an administrative event, so the failure is in the activity feed and wherever your integrations send it — you did not have to be looking at this page."}):null,e.jsx(C,{title:"Tasks",intro:"Anything wrong sorts to the top. Open a task to change its schedule, switch it off, or read its own run history.",icon:"clock",tone:"info",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Task"}),e.jsx("th",{children:"Service"}),e.jsx("th",{children:"Schedule"}),e.jsx("th",{children:"Last run"}),e.jsx("th",{className:"num",children:"Took"}),e.jsx("th",{children:"Next run"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:m.length===0?e.jsx(Y,{columns:8,children:"This gateway has no scheduled tasks registered."}):m.map(j=>{const y=ls(j),v=j.lastRun,b=`/admin/tasks/${encodeURIComponent(j.id)}`;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx(Z,{className:"table-row-link",to:b,children:j.name}),e.jsx("span",{className:"table-sub",children:j.description})]}),e.jsx("td",{className:"muted nowrap",children:j.group||"Other"}),e.jsxs("td",{className:"nowrap",children:[Ne(j.intervalSeconds),Ke(j)?e.jsxs("span",{className:"table-sub",children:["default ",Ne(j.defaultIntervalSeconds)]}):null]}),e.jsxs("td",{className:"nowrap muted",title:v?F(v.startedAt):void 0,children:[v?be(v.startedAt):"never",v!=null&&v.error?e.jsx("span",{className:"table-sub",children:v.error}):null]}),e.jsx("td",{className:"num muted",children:v?ye(v.durationMs):"—"}),e.jsx("td",{className:"nowrap muted",children:j.enabled?j.running?"now":ds(j.nextRun):"—"}),e.jsx("td",{className:"nowrap",children:e.jsxs("span",{className:"row tight",children:[e.jsx("span",{className:"dot-state","data-tone":Jt(y)}),e.jsx(N,{tone:y.tone,children:e.jsx("span",{title:y.title,children:y.label})})]})}),e.jsx("td",{className:"nowrap",children:e.jsxs("span",{className:"row tight",children:[e.jsx($,{size:"sm",icon:"play",busy:n===j.id,disabled:j.running,title:`Run ${j.name} now`,onClick:()=>void p(j)}),e.jsx(Z,{className:"table-row-link",to:b,children:"Details"})]})})]},j.id)})})]})})}),e.jsx(C,{title:"Recent runs",intro:"Every task together and in order, which is what shows two jobs interfering with each other.",icon:"history",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"Started"}),e.jsx("th",{children:"Task"}),e.jsx("th",{children:"Trigger"}),e.jsx("th",{children:"Result"}),e.jsx("th",{className:"num",children:"Took"}),e.jsx("th",{children:"Detail"})]})}),e.jsx("tbody",{children:((l==null?void 0:l.runs.length)??0)===0?e.jsx(Y,{columns:6,children:"No task has run yet."}):l==null?void 0:l.runs.map(j=>{var y;return e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:F(j.startedAt),children:be(j.startedAt)}),e.jsx("td",{children:e.jsx(Z,{className:"table-row-link",to:`/admin/tasks/${encodeURIComponent(j.taskId)}`,children:((y=o.find(v=>v.id===j.taskId))==null?void 0:y.name)??j.taskId})}),e.jsx("td",{className:"muted",children:j.trigger}),e.jsx("td",{children:e.jsx(N,{tone:us(j.status),children:j.status})}),e.jsx("td",{className:"num muted",children:ye(j.durationMs)}),e.jsx("td",{className:"muted",children:j.error||j.detail||"—"})]},j.id)})})]})})})]})]})}const na=2e4,ta=3e3,aa=100;function ia(s){const n=s.filter(l=>l.status!=="running"),t=n.filter(l=>l.status==="failed").length,r=n.filter(l=>l.durationMs>0),a=r.length?r.reduce((l,i)=>l+i.durationMs,0)/r.length:0;return{runs:n.length,failed:t,averageMs:a,timed:r.length}}function ra(){var y;const{taskId:s=""}=We(),{wrap:n}=ie(),{busy:t,run:r}=ne(),[a,l]=g.useState(!1),{data:i,error:h,loading:c,reload:o}=J(`/admin/api/tasks?task=${encodeURIComponent(s)}&limit=${aa}`,{pollMs:a?ta:na,enabled:!!s}),u=i==null?void 0:i.tasks.find(v=>v.id===s),p=!!(u!=null&&u.running);p!==a&&l(p);const d=(i==null?void 0:i.runs)??[],x=u?ls(u):void 0,f=ia(d),m=(v,b,A)=>r(v,async()=>{await n(()=>D.put(`/admin/api/tasks/${encodeURIComponent(s)}`,A),b),await o()}),j=v=>r("run",async()=>{await n(()=>D.post(`/admin/api/tasks/${encodeURIComponent(s)}/run`),`${v.name} started.`),await o()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:(u==null?void 0:u.name)||s,intro:u==null?void 0:u.description,icon:"clock",crumbs:e.jsxs(e.Fragment,{children:[e.jsx(Z,{to:"/admin/tasks",children:"Scheduled tasks"}),e.jsx("span",{children:"/"}),e.jsx("span",{children:(u==null?void 0:u.name)||s})]}),actions:u?e.jsx($,{variant:"primary",icon:"play",busy:t==="run",disabled:u.running,onClick:()=>void j(u),children:u.running?"Running":"Run now"}):void 0}),e.jsx(_,{message:h}),c?e.jsx(V,{}):u?e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"Status",value:(x==null?void 0:x.label)??"—",small:!0,icon:"pulse",tone:x==null?void 0:x.tone},{label:"Service",value:u.group||"Other",small:!0,icon:"chip",tone:"info"},{label:"Runs every",value:Ne(u.intervalSeconds),small:!0,icon:"clock",tone:Ke(u)?"note":void 0},{label:"Next run",value:u.enabled?u.running?"now":ds(u.nextRun):"not scheduled",small:!0,icon:"history",tone:u.enabled?void 0:"warn"},{label:`Failed of the last ${w(f.runs)}`,value:w(f.failed),icon:"alert",tone:f.failed>0?"bad":void 0},{label:`Average of ${w(f.timed)} timed runs`,value:f.timed?ye(Math.round(f.averageMs)):"—",small:!0,icon:"chart",tone:"data"}]}),(y=u.lastRun)!=null&&y.error?e.jsxs(pe,{tone:"bad",children:["The last run failed: ",u.lastRun.error]}):null,e.jsxs(C,{title:"Schedule",intro:"How often the gateway runs this on its own, and whether it runs it at all.",icon:"sliders",tone:"info",children:[e.jsxs("div",{className:"row",children:[e.jsx(q,{label:"How often it runs",children:e.jsx("select",{"aria-label":`How often ${u.name} runs`,value:u.intervalSeconds,disabled:t==="interval"||u.running,onChange:v=>void m("interval",`${u.name} now runs ${Ne(Number(v.target.value))}.`,{intervalSeconds:Number(v.target.value)}),children:Yt(u).map(v=>e.jsxs("option",{value:v.value,children:[v.label,v.value===u.defaultIntervalSeconds?" (default)":""]},v.value))})}),Ke(u)?e.jsxs($,{icon:"refresh",busy:t==="interval",disabled:u.running,onClick:()=>void m("interval",`${u.name} back to its default cadence.`,{intervalSeconds:0}),children:["Back to ",Ne(u.defaultIntervalSeconds)]}):null]}),e.jsx(G,{label:"Run this on its schedule",hint:"Switched off, the gateway leaves it alone. You can still start it by hand.",checked:u.enabled,disabled:t==="enabled",onChange:v=>void m("enabled",v?`${u.name} switched on.`:`${u.name} switched off.`,{enabled:v})}),Ke(u)?e.jsxs(pe,{tone:"note",children:["This task is retimed: its code asks for ",Ne(u.defaultIntervalSeconds)," and it is set to ",Ne(u.intervalSeconds),"."]}):null]}),e.jsx(C,{title:"Run history",intro:"This task alone, newest first — which is what separates a job that fails occasionally from one that has stopped working.",icon:"history",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"Started"}),e.jsx("th",{children:"Trigger"}),e.jsx("th",{children:"Result"}),e.jsx("th",{className:"num",children:"Took"}),e.jsx("th",{children:"Detail"})]})}),e.jsx("tbody",{children:d.length===0?e.jsx(Y,{columns:5,children:"This task has not run yet."}):d.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:F(v.startedAt),children:be(v.startedAt)}),e.jsx("td",{className:"muted",children:v.trigger}),e.jsx("td",{children:e.jsx(N,{tone:us(v.status),children:v.status})}),e.jsx("td",{className:"num muted",children:ye(v.durationMs)}),e.jsx("td",{className:"muted",children:v.error||v.detail||"—"})]},v.id))})]})})})]}):e.jsx(C,{title:"No such task",icon:"alert",tone:"bad",children:e.jsxs(ee,{children:["This gateway has no task called ",e.jsx("code",{children:s}),". It may have been renamed or removed."," ",e.jsx(Z,{to:"/admin/tasks",children:"Back to scheduled tasks"}),"."]})})]})}function Pe(s){switch(s){case"error":return"bad";case"healthy":return"ok";case"running":return"info";case"disabled":return"warn";default:return}}function An(s){return Pe(s)}const Zs={error:0,running:1,idle:2,healthy:3,disabled:4,unconfigured:5};function la(s,n){const t=Zs[s.status]-Zs[n.status];return t!==0?t:s.name.localeCompare(n.name)}const oa=s=>!!(s&&(s.processed||s.changed||s.skipped||s.failed));function Je(s){if(!oa(s)||!s)return"";const n=[];return s.processed&&n.push(`${s.processed.toLocaleString()} checked`),s.changed&&n.push(`${s.changed.toLocaleString()} changed`),s.skipped&&n.push(`${s.skipped.toLocaleString()} skipped`),s.failed&&n.push(`${s.failed.toLocaleString()} failed`),n.join(" · ")}function Cs(s){if(s.status==="running")return"Running…";if(s.error)return s.error;if(s.detail)return s.detail;const n=Je(s.counts);return n||"No changes"}function ca(s){return s.powers.length?`Switching ${s.name} off also stops: ${s.powers.join("; ")}.`:""}const da=2e4,ha=3e3;function ua(){const[s,n]=g.useState(!1),{data:t,error:r,loading:a}=J("/admin/api/integrations/services?limit=40",{pollMs:s?ha:da}),l=((t==null?void 0:t.services)??[]).some(d=>d.running);l!==s&&n(l);const i=[...(t==null?void 0:t.services)??[]].sort(la),h=(t==null?void 0:t.runs)??[],c=i.filter(d=>d.status==="error"),o=i.filter(d=>d.running),u=i.filter(d=>d.configured&&!d.enabled),p=i.filter(d=>!d.configured);return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Integrations",intro:"The services Memby depends on: whether each one is configured, whether it is working, what it is doing right now and what it last managed to do."}),e.jsx(_,{message:r}),a?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"Integrations",value:w(i.length),icon:"plug",tone:"info"},{label:"Not working",value:w(c.length),icon:"alert",tone:c.length>0?"bad":void 0},{label:"Running now",value:w(o.length),icon:"pulse",tone:o.length>0?"ok":void 0},{label:"Switched off",value:w(u.length),icon:"power",tone:u.length>0?"warn":void 0},{label:"Not configured",value:w(p.length),icon:"sliders",tone:p.length>0?"note":void 0}]}),c.length>0?e.jsxs(pe,{tone:"bad",children:[c.map(d=>d.name).join(", ")," ",c.length===1?"is not answering":"are not answering",". A failed run also publishes an administrative event, so it is in the activity feed and wherever your webhooks send it — you did not have to be looking at this page."]}):null,e.jsx(C,{title:"Services",intro:"Anything wrong sorts to the top. Open a service to switch it off, read its settings, or see everything it has done.",icon:"plug",tone:"info",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Integration"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Last run"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Next run"}),e.jsx("th",{children:"Enabled"})]})}),e.jsx("tbody",{children:i.length===0?e.jsx(Y,{columns:6,children:"This gateway has no integrations."}):i.map(d=>e.jsx(ma,{service:d},d.id))})]})})}),e.jsx(C,{title:"Recent activity",intro:"Every integration's work together and in order, which is what shows two of them getting in each other's way. This is what Memby attempted and what came of it — the Logs page is where the technical detail behind a failure lives.",icon:"history",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"Started"}),e.jsx("th",{children:"Integration"}),e.jsx("th",{children:"Task"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Outcome"}),e.jsx("th",{className:"num",children:"Took"})]})}),e.jsx("tbody",{children:h.length===0?e.jsx(Y,{columns:6,children:"No integration has run yet."}):h.map(d=>{const x=i.find(m=>m.id===d.integrationId),f=x==null?void 0:x.tasks.find(m=>m.id===d.taskId);return e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:F(d.startedAt),children:be(d.startedAt)}),e.jsx("td",{className:"nowrap",children:e.jsx(Z,{className:"table-row-link",to:`/admin/integrations/${encodeURIComponent(d.integrationId??"")}`,children:(x==null?void 0:x.name)??d.integrationId})}),e.jsx("td",{className:"muted",children:(f==null?void 0:f.name)??d.taskId}),e.jsx("td",{children:e.jsx(N,{tone:us(d.status),children:d.status})}),e.jsxs("td",{className:"muted",children:[Cs(d),d.error&&Je(d.counts)?e.jsx("span",{className:"table-sub",children:Je(d.counts)}):null]}),e.jsx("td",{className:"num muted",children:ye(d.durationMs)})]},d.id)})})]})})})]})]})}function ma({service:s}){const n=`/admin/integrations/${encodeURIComponent(s.id)}`;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx(Z,{className:"table-row-link",to:n,children:s.name}),e.jsx("span",{className:"table-sub",children:s.address||s.summary})]}),e.jsx("td",{className:"nowrap",children:e.jsxs("span",{className:"row tight",children:[e.jsx("span",{className:"dot-state","data-tone":An(s.status)}),e.jsx(N,{tone:Pe(s.status),children:e.jsx("span",{title:s.detail||s.statusLabel,children:s.statusLabel})})]})}),e.jsx("td",{className:"nowrap muted",title:s.lastRun?F(s.lastRun.startedAt):void 0,children:s.lastRun?be(s.lastRun.startedAt):"never"}),e.jsx("td",{className:"muted",children:s.lastRun?Cs(s.lastRun):s.detail||"—"}),e.jsx("td",{className:"nowrap muted",children:s.configured?s.enabled?s.running?"now":ds(s.nextRun):"off":"—"}),e.jsx("td",{className:"nowrap",children:s.configured?s.enabled?e.jsx(N,{tone:"ok",children:"On"}):e.jsx(N,{tone:"warn",children:"Off"}):e.jsx(N,{children:"not configured"})})]})}const pa={imdb:"IMDb",tomatoes:"Rotten Tomatoes",audience:"Rotten Tomatoes Audience",metacritic:"Metacritic",letterboxd:"Letterboxd",rogerebert:"Roger Ebert",tmdb:"TMDb",trakt:"Trakt",mal:"MyAnimeList",anilist:"AniList",anidb:"AniDB",kitsu:"Kitsu",score:"MDBList Score",score_average:"MDBList Average"};function xa(){const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a}=ie(),{busy:l,run:i}=ne(),[h,c]=g.useState(!1),[o,u]=g.useState(""),[p,d]=g.useState(!1),[x,f]=g.useState([]),[m,j]=g.useState(!1),y=s==null?void 0:s.mdblist;g.useEffect(()=>{m||!y||(c(y.enabled),f(y.sources??[]))},[y,m]);const v=()=>i("save",async()=>{await a(()=>D.post("/admin/api/mdblist-settings",{enabled:h,apiKey:o.trim(),clearApiKey:p,sources:x}),"Ratings settings saved."),u(""),d(!1),j(!1),await r()}),b=(y==null?void 0:y.cachedTitles)??0;return e.jsxs(e.Fragment,{children:[e.jsx(_,{message:n}),t||!y?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsxs(xe,{cols:"2",children:[e.jsxs(C,{title:"MDBList connection",intro:"The key stays on this server and a failure never blocks a television. Every rating fetched is stored here permanently and re-checked about once a month, so browsing the library costs nothing after the first look at a title.",icon:"star",tone:"note",actions:h?e.jsxs(N,{tone:"ok",children:["on · ",x.length," sources"]}):e.jsx(N,{children:y.apiKeyConfigured?"off · key saved":"off · no key"}),children:[e.jsx(G,{label:"Show external ratings on televisions",hint:"Off leaves the stored ratings in place.",checked:h,onChange:A=>{c(A),j(!0)}}),e.jsx(q,{label:"API key",hint:"Leave blank to keep the key that is already saved.",children:e.jsx("input",{type:"password",autoComplete:"new-password",value:o,placeholder:y.apiKeyConfigured?"Saved key (leave blank to keep)":"Paste an API key",onChange:A=>u(A.target.value)})}),e.jsx(G,{label:"Remove the saved key",checked:p,onChange:d})]}),e.jsx(C,{title:"Sources shown on televisions",intro:"A title with none of these has no ratings strip at all, which is the honest answer — nothing stands in for a score that was never fetched.",icon:"list",tone:"data",children:(y.availableSources??[]).length===0?e.jsx(ee,{children:"No rating sources are available."}):e.jsx("div",{className:"checks columns",children:(y.availableSources??[]).map(A=>e.jsx(G,{label:pa[A]??A,checked:x.includes(A),onChange:k=>{j(!0),f(I=>k?[...I,A]:I.filter(E=>E!==A))}},A))})})]}),e.jsx(C,{children:e.jsxs("div",{className:"row",children:[e.jsx($,{variant:"primary",busy:l==="save",onClick:()=>void v(),children:"Save ratings settings"}),e.jsx("span",{className:"hint",children:b?"Ratings are fetched as televisions browse, never on the request path.":"No ratings stored yet. They are saved as televisions browse the library."})]})})]})]})}const ja={id:"",name:"Discord",url:"",enabled:!0,events:[]};function ga(){const{wrap:s,show:n}=ie(),{busy:t,run:r}=ne(),{data:a,error:l,loading:i,reload:h}=J("/admin/api/integrations",{pollMs:6e4}),[c,o]=g.useState(null),[u,p]=g.useState(null),d=(a==null?void 0:a.catalogue)??[],x=(a==null?void 0:a.integrations)??[],f=v=>o({id:v.id,name:v.name,url:"",enabled:v.enabled,events:v.events??[]}),m=()=>r("save",async()=>{if(!c)return;await s(()=>D.post("/admin/api/integrations",c),c.id?"Integration saved.":"Integration added.")&&(o(null),await h())}),j=v=>r("remove",async()=>{await s(()=>D.del(`/admin/api/integrations/${encodeURIComponent(v.id)}`),`${v.name} removed.`),p(null),await h()}),y=v=>r(`test:${v.id}`,async()=>{const b=await s(()=>D.post(`/admin/api/integrations/${encodeURIComponent(v.id)}/test`));b&&n(b.message,b.ok?"ok":"bad"),await h()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Event webhooks",intro:"Send administrative events to somewhere you already look. Events pass through the gateway's own event layer, so nothing about authentication or scheduled tasks knows Discord exists — and a second kind of destination is a change here rather than everywhere.",actions:e.jsx($,{variant:"primary",icon:"plus",onClick:()=>o(ja),children:"Add a webhook"})}),e.jsx(_,{message:l}),((a==null?void 0:a.dropped)??0)>0?e.jsxs(pe,{tone:"warn",children:[w((a==null?void 0:a.dropped)??0)," events could not be queued for delivery. The queue is deliberately lossy — a slow endpoint must never hold up a television signing in — but a number growing here means a destination is not keeping up."]}):null,i?e.jsx(V,{}):x.length===0&&!c?e.jsx(C,{title:"Nothing configured",icon:"plug",tone:"note",children:e.jsx(ee,{children:"No destinations yet. A Discord webhook takes about a minute: in Discord, open a channel's settings → Integrations → Webhooks → New Webhook, copy its URL, and paste it here."})}):x.map(v=>e.jsx(fa,{integration:v,catalogue:d,busy:t,onEdit:()=>f(v),onTest:()=>void y(v),onRemove:()=>p(v)},v.id)),c?e.jsx(ya,{draft:c,catalogue:d,busy:t==="save",onChange:o,onSave:()=>void m(),onCancel:()=>o(null)}):null,u?e.jsx(ke,{title:`Remove ${u.name}?`,body:"The webhook address and its delivery history go with it. Events already published stay in the activity feed.",confirmLabel:"Remove",destructive:!0,busy:t==="remove",onConfirm:()=>void j(u),onCancel:()=>p(null)}):null]})}function va(){const{wrap:s}=ie(),{busy:n,run:t}=ne(),{data:r,error:a,loading:l,reload:i}=J("/admin/api/sonarr-request-policy"),[h,c]=g.useState(0),[o,u]=g.useState(!1);g.useEffect(()=>{r&&(c(r.qualityProfileId),u(r.searchImmediately))},[r]);const p=()=>t("sonarr-request-policy",async()=>{await s(()=>D.post("/admin/api/sonarr-request-policy",{qualityProfileId:h,searchImmediately:o}),"Sonarr TV request policy saved."),await i()}),d=r==null?void 0:r.profiles.find(x=>x.id===h);return e.jsxs(C,{title:"Sonarr TV requests",intro:"The policy Memby uses when a viewer requests a television series. The series remains monitored; searching its existing episodes is an explicit choice.",icon:"tv",tone:r!=null&&r.configured?"ok":"warn",actions:r!=null&&r.configured?e.jsx(N,{tone:"ok",children:"configured"}):e.jsx(N,{tone:"warn",children:"needs attention"}),footer:e.jsx($,{variant:"primary",busy:n==="sonarr-request-policy",disabled:l||h<=0,onClick:()=>void p(),children:"Save Sonarr policy"}),children:[e.jsx(_,{message:a??(r==null?void 0:r.error)??""}),l?e.jsx(V,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fields",children:e.jsx(q,{label:"Request quality profile",hint:"Memby stores this Sonarr profile ID. 720p is the recommended safe default; Memby will never fall back to Any.",children:e.jsxs("select",{value:h,onChange:x=>c(Number(x.target.value)),disabled:!(r!=null&&r.profiles.length),children:[e.jsx("option",{value:0,children:"Choose a quality profile…"}),r==null?void 0:r.profiles.map(x=>e.jsxs("option",{value:x.id,children:[x.name,x.recommended?" — recommended (720p)":""]},x.id))]})})}),e.jsx(G,{label:"Search for episodes immediately after request",hint:"Off adds and monitors the series without searching its backlog. Enable only when requests should start an immediate episode search.",checked:o,onChange:u}),d?e.jsxs(pe,{tone:"info",children:["Requested series will use ",e.jsx("b",{children:d.name})," (profile ID ",d.id,"), be monitored using Membys existing all-episodes strategy, and ",o?"start an immediate search.":"not start an immediate search."]}):null]})]})}function ba(){const{wrap:s}=ie(),{busy:n,run:t}=ne(),{data:r,error:a,loading:l,reload:i}=J("/admin/api/radarr-request-policy"),[h,c]=g.useState(0),[o,u]=g.useState(!1);g.useEffect(()=>{r&&(c(r.qualityProfileId),u(r.searchImmediately))},[r]);const p=()=>t("radarr-request-policy",async()=>{await s(()=>D.post("/admin/api/radarr-request-policy",{qualityProfileId:h,searchImmediately:o}),"Radarr movie request policy saved."),await i()}),d=r==null?void 0:r.profiles.find(x=>x.id===h);return e.jsxs(C,{title:"Radarr movie requests",intro:"The policy Memby uses when a viewer requests a film. The film remains monitored; an immediate Radarr search is an explicit choice.",icon:"tv",tone:r!=null&&r.configured?"ok":"warn",actions:r!=null&&r.configured?e.jsx(N,{tone:"ok",children:"configured"}):e.jsx(N,{tone:"warn",children:"needs attention"}),footer:e.jsx($,{variant:"primary",busy:n==="radarr-request-policy",disabled:l||h<=0,onClick:()=>void p(),children:"Save Radarr policy"}),children:[e.jsx(_,{message:a??(r==null?void 0:r.error)??""}),l?e.jsx(V,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fields",children:e.jsx(q,{label:"Request quality profile",hint:"Memby stores this Radarr profile ID. 720p is the recommended safe default; Memby will never fall back to Any.",children:e.jsxs("select",{value:h,onChange:x=>c(Number(x.target.value)),disabled:!(r!=null&&r.profiles.length),children:[e.jsx("option",{value:0,children:"Choose a quality profile…"}),r==null?void 0:r.profiles.map(x=>e.jsxs("option",{value:x.id,children:[x.name,x.recommended?" — recommended (720p)":""]},x.id))]})})}),e.jsx(G,{label:"Search for the film immediately after request",hint:"Off adds and monitors the film without asking Radarr to search. Enable only when requests should start an immediate search.",checked:o,onChange:u}),d?e.jsxs(pe,{tone:"info",children:["Requested films will use ",e.jsx("b",{children:d.name})," (profile ID ",d.id,"), remain monitored, and ",o?"start an immediate search.":"not start an immediate search."]}):null]})]})}function fa({integration:s,catalogue:n,busy:t,onEdit:r,onTest:a,onRemove:l}){const i=s.health,h=!i.lastFailure||i.lastSuccess&&i.lastSuccess>i.lastFailure,c=s.events??[];return e.jsxs(C,{title:s.name,intro:s.hint?`Discord webhook ${s.hint}`:"Discord webhook",icon:"plug",tone:s.enabled?"ok":"warn",actions:e.jsxs(e.Fragment,{children:[s.enabled?e.jsx(N,{tone:"ok",children:"on"}):e.jsx(N,{tone:"warn",children:"off"}),i.deliveries>0?e.jsx(N,{tone:h?"ok":"bad",children:h?"delivering":"failing"}):e.jsx(N,{children:"never used"}),e.jsx($,{size:"sm",icon:"pulse",busy:t===`test:${s.id}`,onClick:a,children:"Test"}),e.jsx($,{size:"sm",onClick:r,children:"Edit"}),e.jsx($,{size:"sm",variant:"danger",icon:"trash",onClick:l,title:"Remove"})]}),children:[e.jsxs("div",{className:"list",children:[e.jsx("div",{className:"list-item",children:e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:"Events sent"}),e.jsx("p",{children:c.length===0?"None selected — this destination is configured but will never post anything.":c.map(o=>{var u;return((u=n.find(p=>p.type===o))==null?void 0:u.label)??o}).join(", ")})]})}),e.jsxs("div",{className:"list-item",children:[e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:"Last delivered"}),e.jsx("p",{children:i.lastSuccess?F(i.lastSuccess):"never"})]}),e.jsx("div",{className:"list-actions",children:i.deliveries>0?e.jsxs("span",{className:"quiet",children:[w(i.deliveries)," attempts, ",w(i.failures)," failed"]}):null})]}),i.lastFailure?e.jsx("div",{className:"list-item",children:e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:"Last failure"}),e.jsxs("p",{children:[F(i.lastFailure),i.lastError?` — ${i.lastError}`:""]})]})}):null]}),s.deliveries.length>0?e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"Attempted"}),e.jsx("th",{children:"Event"}),e.jsx("th",{children:"Result"}),e.jsx("th",{className:"num",children:"Took"})]})}),e.jsx("tbody",{children:s.deliveries.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:F(o.attemptedAt),children:be(o.attemptedAt)}),e.jsx("td",{className:"muted",children:o.eventType}),e.jsx("td",{children:o.success?e.jsx(N,{tone:"ok",children:o.statusCode||"ok"}):e.jsx(N,{tone:"bad",children:o.error||o.statusCode||"failed"})}),e.jsx("td",{className:"num muted",children:ye(o.durationMs)})]},o.id))})]})}):e.jsx(K,{children:e.jsx("table",{children:e.jsx("tbody",{children:e.jsx(Y,{columns:4,children:"Nothing has been delivered through this webhook yet."})})})})]})}function ya({draft:s,catalogue:n,busy:t,onChange:r,onSave:a,onCancel:l}){const i=[...new Set(n.map(c=>c.group))],h=(c,o)=>r({...s,events:o?[...s.events,c]:s.events.filter(u=>u!==c)});return e.jsxs(C,{title:s.id?`Edit ${s.name}`:"New Discord webhook",icon:"plug",tone:"info",footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:t,onClick:a,children:s.id?"Save":"Add"}),e.jsx($,{variant:"quiet",onClick:l,children:"Cancel"}),e.jsx("span",{className:"spacer"}),s.events.length===0?e.jsx("span",{className:"quiet",children:"Nothing selected — this destination would never post."}):e.jsxs("span",{className:"quiet",children:[s.events.length," events selected"]})]}),children:[e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Name",hint:"What this destination is called in the console.",children:e.jsx("input",{type:"text",value:s.name,onChange:c=>r({...s,name:c.target.value})})}),e.jsx(q,{label:"Webhook address",hint:s.id?"Leave blank to keep the address already saved — it is a credential and is never sent back to this page.":"Discord → channel settings → Integrations → Webhooks → New Webhook → Copy Webhook URL.",children:e.jsx("input",{type:"url",value:s.url,placeholder:s.id?"unchanged":"https://discord.com/api/webhooks/…",onChange:c=>r({...s,url:c.target.value})})})]}),e.jsx(G,{label:"Enabled",hint:"Off keeps the configuration and stops the posts.",checked:s.enabled,onChange:c=>r({...s,enabled:c})}),i.map(c=>e.jsxs("div",{children:[e.jsx("div",{className:"card-head",style:void 0,children:e.jsx("div",{className:"card-head-text",children:e.jsx("h2",{children:c})})}),n.filter(o=>o.group===c).map(o=>e.jsx(G,{label:o.label,hint:o.description,checked:s.events.includes(o.type),onChange:u=>h(o.type,u)},o.type))]},c))]})}const wa=2e4,ka=3e3;function Na(){const{integrationId:s=""}=We(),{wrap:n,show:t}=ie(),{busy:r,run:a}=ne(),[l,i]=g.useState(!1),{data:h,error:c,loading:o,reload:u}=J(`/admin/api/integrations/services/${encodeURIComponent(s)}?limit=80`,{pollMs:l?ka:wa,enabled:!!s}),p=h==null?void 0:h.service,d=(h==null?void 0:h.runs)??[],x=!!(p!=null&&p.running);x!==l&&i(x);const f=v=>a("enabled",async()=>{await n(()=>D.post(`/admin/api/integrations/services/${encodeURIComponent(s)}/enabled`,{enabled:v}),`${(p==null?void 0:p.name)??"Integration"} ${v?"enabled":"disabled"}.`),await u()}),m=()=>a("test",async()=>{const v=await n(()=>D.post(`/admin/api/integrations/services/${encodeURIComponent(s)}/test`));v&&t(v.reachable?`${p==null?void 0:p.name} answered in ${ye(v.latencyMs)}.`:v.error||`${p==null?void 0:p.name} did not answer.`,v.reachable?"ok":"bad"),await u()}),j=(v,b)=>a(v,async()=>{await n(()=>D.post(`/admin/api/tasks/${encodeURIComponent(v)}/run`),`${b} started.`),await u()});if(o||!p)return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Integration",intro:"One external service and everything it has done."}),e.jsx(_,{message:c}),o?e.jsx(V,{}):e.jsx(pe,{tone:"warn",children:"No such integration."})]});const y=d.filter(v=>v.status==="failed").length;return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:p.name,intro:p.summary,actions:e.jsx(Z,{className:"table-row-link",to:"/admin/integrations",children:"All integrations"})}),e.jsx(_,{message:c}),e.jsx(ae,{tiles:[{label:"Status",value:p.statusLabel,small:!0,icon:"pulse",tone:Pe(p.status)},{label:"Runs recorded",value:w(p.runs),icon:"history",tone:"data"},{label:"Failed runs",value:w(p.failures),icon:"alert",tone:p.failures>0?"bad":void 0},{label:"Last worked",value:p.lastSuccessAt?be(p.lastSuccessAt):"never",small:!0,icon:"check",tone:p.lastSuccessAt?"ok":void 0}]}),e.jsxs(C,{title:"Connection",intro:"Address and credentials come from this gateway's environment; the switch is stored on the server and applies to the whole household.",icon:"plug",tone:Pe(p.status)??"info",actions:e.jsxs("span",{className:"row tight",children:[e.jsx("span",{className:"dot-state","data-tone":An(p.status)}),e.jsx(N,{tone:Pe(p.status),children:p.statusLabel})]}),footer:p.configured&&p.probed?e.jsx($,{icon:"sync",busy:r==="test",onClick:()=>void m(),children:"Test connection"}):void 0,children:[p.detail?e.jsx(pe,{tone:Pe(p.status),children:p.detail}):null,p.configured?e.jsxs(e.Fragment,{children:[e.jsx(G,{label:`${p.name} enabled`,hint:p.enabled?ca(p):`Memby is not calling ${p.name} or scheduling any of its work.`,checked:p.enabled,disabled:r==="enabled",onChange:v=>void f(v)}),e.jsx(Ue,{rows:[{label:"Address",value:p.address||"—"},...(p.facts??[]).map(v=>({label:v.label,value:v.tone?e.jsx(N,{tone:v.tone==="warn"?"warn":"ok",children:v.value}):v.value})),{label:"Last checked",value:p.probed?p.health?`${be(p.health.checkedAt)} · ${ye(p.health.latencyMs)}`:"not yet":"Not probed — see below"}]}),p.probed?null:e.jsxs(pe,{children:[p.name," is not probed for reachability: its allowance is bought by the day, and spending a request of it to draw a status would compete with the televisions for the thing being reported on. Its health comes from the run history below."]})]}):e.jsxs(pe,{tone:"warn",children:["This gateway has no address or credential for ",p.name,". Set them in the deployment's environment and restart the container; there is nothing to switch until then."]})]}),p.powers.length>0?e.jsx(C,{title:"What depends on this",intro:"Switching the service off stops all of it. Nothing below fails quietly — it stops being offered.",icon:"journey",tone:"note",children:e.jsx("div",{className:"list",children:p.powers.map(v=>e.jsxs("div",{className:"list-item",children:[e.jsx(Qe,{name:"check",tone:"ok"}),e.jsx("span",{className:"list-body",children:v})]},v))})}):null,e.jsx(Ma,{id:p.id}),e.jsx(C,{title:"Scheduled work",intro:"The background jobs belonging to this service. Cadence and the per-job switch live on each job's own page; this is where you start one by hand.",icon:"clock",tone:"info",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Task"}),e.jsx("th",{children:"Schedule"}),e.jsx("th",{children:"Last run"}),e.jsx("th",{children:"Next run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:p.tasks.length===0?e.jsx(Y,{columns:5,children:"This service has no scheduled work: Memby calls it when a television asks for something rather than on a timer."}):p.tasks.map(v=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx(Z,{className:"table-row-link",to:`/admin/tasks/${encodeURIComponent(v.id)}`,children:v.name}),e.jsx("span",{className:"table-sub",children:v.description})]}),e.jsx("td",{className:"nowrap muted",children:Ne(v.intervalSeconds)}),e.jsx("td",{className:"nowrap muted",title:v.lastRun?F(v.lastRun.startedAt):void 0,children:v.lastRun?be(v.lastRun.startedAt):"never"}),e.jsx("td",{className:"nowrap muted",children:!v.enabled||!p.enabled?"off":v.running?"now":ds(v.nextRun)}),e.jsx("td",{className:"nowrap",children:e.jsx($,{size:"sm",icon:"play",busy:r===v.id,disabled:v.running,title:`Run ${v.name} now`,onClick:()=>void j(v.id,v.name)})})]},v.id))})]})})}),e.jsx(C,{title:"Run history",intro:"What Memby attempted on this service's behalf and what came of it. This is not the application log — a failure here gives the reason, and Logs is where the technical detail behind it lives.",icon:"history",tone:"note",actions:y>0?e.jsx(Z,{className:"table-row-link",to:`/admin/logs?q=${encodeURIComponent(p.id)}`,children:"Open the logs"}):void 0,children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"Started"}),e.jsx("th",{children:"Task"}),e.jsx("th",{children:"Trigger"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Outcome"}),e.jsx("th",{className:"num",children:"Checked"}),e.jsx("th",{className:"num",children:"Changed"}),e.jsx("th",{className:"num",children:"Skipped"}),e.jsx("th",{className:"num",children:"Failed"}),e.jsx("th",{className:"num",children:"Took"})]})}),e.jsx("tbody",{children:d.length===0?e.jsxs(Y,{columns:10,children:["Nothing has run for ",p.name," yet."]}):d.map(v=>e.jsx(Sa,{run:v,service:p},v.id))})]})})})]})}function Sa({run:s,service:n}){var a,l,i,h;const t=n.tasks.find(c=>c.id===s.taskId),r=c=>c?w(c):"—";return e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:F(s.startedAt),children:be(s.startedAt)}),e.jsx("td",{className:"muted",children:(t==null?void 0:t.name)??s.taskId}),e.jsx("td",{className:"muted",children:s.trigger}),e.jsx("td",{children:e.jsx(N,{tone:us(s.status),children:s.status})}),e.jsxs("td",{className:"muted",children:[Cs(s),s.error&&Je(s.counts)?e.jsx("span",{className:"table-sub",children:Je(s.counts)}):null]}),e.jsx("td",{className:"num muted",children:r(((a=s.counts)==null?void 0:a.processed)??0)}),e.jsx("td",{className:"num muted",children:r(((l=s.counts)==null?void 0:l.changed)??0)}),e.jsx("td",{className:"num muted",children:r(((i=s.counts)==null?void 0:i.skipped)??0)}),e.jsx("td",{className:"num muted",children:r(((h=s.counts)==null?void 0:h.failed)??0)}),e.jsx("td",{className:"num muted",children:ye(s.durationMs)})]})}function Ma({id:s}){switch(s){case"mdblist":return e.jsx(xa,{});case"sonarr":return e.jsx(va,{});case"radarr":return e.jsx(ba,{});default:return null}}function Ca(){var X,le,ue,te;const{status:s,error:n,loading:t,reload:r}=je(),{wrap:a}=ie(),{busy:l,run:i}=ne(),[h,c]=g.useState(""),[o,u]=g.useState(!1),[p,d]=g.useState(!1),[x,f]=g.useState(!1),[m,j]=g.useState("23:00"),[y,v]=g.useState("07:00"),[b,A]=g.useState(""),[k,I]=g.useState(!1),E=!!((X=s==null?void 0:s.maintenance)!=null&&X.enabled);g.useEffect(()=>{var H;!p&&s&&c(((H=s.maintenance)==null?void 0:H.message)??"")},[s,p]),g.useEffect(()=>{k||!(s!=null&&s.quietTime)||(f(s.quietTime.enabled),j(s.quietTime.startTime),v(s.quietTime.endTime),A(s.quietTime.message))},[s,k]);const R=H=>i(H?"on":"off",async()=>{await a(()=>D.post("/admin/api/maintenance",{enabled:H,message:h}),H?"Memby is offline for every television.":"Memby is back online."),u(!1),d(!1),await r()}),L=()=>i("quiet",async()=>{await a(()=>D.post("/admin/api/quiet-time",{enabled:x,startTime:m,endTime:y,message:b}),x?"Quiet time saved.":"Quiet time turned off."),I(!1),await r()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Maintenance",intro:"Take Memby offline now or schedule daily quiet time."}),e.jsx(_,{message:n}),t?e.jsx(V,{rows:1}):e.jsx(C,{title:"Gateway availability",intro:"Takes Memby offline for every television, independently of Emby. Sign-in and all content calls answer 503 with the message below, and the television shows it in place of the launcher rows. This console keeps working.",icon:"power",tone:E?"bad":"warn",actions:E?e.jsx(N,{tone:"bad",children:"offline"}):e.jsx(N,{tone:"ok",children:"online"}),footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"danger",disabled:E,onClick:()=>u(!0),children:"Go offline"}),e.jsx($,{disabled:!E,busy:l==="off",onClick:()=>void R(!1),children:"Bring back online"})]}),children:e.jsx(q,{label:"Message shown on the television",hint:"Say what is happening and when it will be back. It is the only thing the viewer is told.",children:e.jsx("input",{type:"text",value:h,placeholder:"Back shortly — upgrading the server",onChange:H=>{c(H.target.value),d(!0)}})})}),t?null:e.jsxs(C,{title:"Quiet time",intro:`Pause new television requests and server background work every day in ${((le=s==null?void 0:s.quietTime)==null?void 0:le.timeZone)??"the server timezone"}. Work already under way finishes safely. The admin console and health checks stay available so the schedule can always be changed.`,icon:"clock",tone:(ue=s==null?void 0:s.quietTime)!=null&&ue.active?"warn":"info",actions:(te=s==null?void 0:s.quietTime)!=null&&te.active?e.jsx(N,{tone:"warn",children:"active now"}):x?e.jsx(N,{tone:"ok",children:"scheduled"}):e.jsx(N,{children:"off"}),footer:e.jsx($,{variant:"primary",busy:l==="quiet",onClick:()=>void L(),children:"Save quiet time"}),children:[e.jsx(G,{label:"Pause server activity during quiet time",checked:x,onChange:H=>{f(H),I(!0)}}),e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Starts",hint:"Uses the server's 24-hour clock.",children:e.jsx("input",{type:"time",value:m,onChange:H=>{j(H.target.value),I(!0)}})}),e.jsx(q,{label:"Ends",hint:"May be on the following day, for example 23:00 to 07:00.",children:e.jsx("input",{type:"time",value:y,onChange:H=>{v(H.target.value),I(!0)}})})]}),e.jsx(q,{label:"Message shown on the television",hint:"Shown when a television contacts Memby during quiet time.",children:e.jsx("input",{type:"text",value:b,placeholder:"Quiet time — try again after 7 am",onChange:H=>{A(H.target.value),I(!0)}})})]}),o?e.jsx(ke,{title:"Take Memby offline?",body:"Every television will stop working immediately and show your message in place of the launcher. This console keeps working.",confirmLabel:"Go offline",destructive:!0,busy:l==="on",onConfirm:()=>void R(!0),onCancel:()=>u(!1)}):null]})}const Ys=s=>s==="Unattributed"?"warn":s==="Go runtime"?"note":"info";function $a(){const s=J("/admin/api/runtime",{pollMs:3e4}),[n,t]=g.useState(),[r,a]=g.useState(!1),[l,i]=g.useState(""),h=g.useCallback(async()=>{a(!0),i("");try{t(await D.get("/admin/api/runtime/goroutines"))}catch(f){i(f instanceof Error?f.message:String(f))}finally{a(!1)}},[]);if(s.loading||!s.data)return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Runtime",intro:"What the gateway process is doing."}),e.jsx(_,{message:s.error}),e.jsx(V,{})]});const c=s.data,o=c.memory,u=c.samples??[],p=c.workers??[],d=p.filter(f=>f.state==="running").length,x=o.memoryLimit>0&&o.memoryLimit<Number.MAX_SAFE_INTEGER;return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Runtime",intro:"What the gateway process is doing: the work it is holding open, the memory it is using, and how both have moved."}),e.jsx(_,{message:s.error}),e.jsx(Tn,{health:c.health}),e.jsx(ae,{tiles:[{label:`goroutines · ${rs(c.goroutineTrend,f=>w(Math.round(f)))}`,value:w(c.goroutines),icon:"pulse",tone:c.goroutineTrend.direction==="rising"?"warn":"info"},{label:"named workers running",value:w(d),icon:"clock",tone:"note"},{label:`heap in use · ${rs(c.heapTrend,he)}`,value:he(o.heapInuse),icon:"chip",tone:o.heapShare>=.75?"warn":"data"},{label:"running for",value:Rn(c.uptimeSeconds),icon:"history",tone:"data"}]}),e.jsxs(xe,{cols:"2",children:[e.jsxs(C,{title:"Memory",intro:"Three different figures that are routinely confused. Heap in use is what the gateway is actually holding. Reserved is what the Go runtime has taken from the operating system on its behalf — always larger, and not a leak. The limit is the one the container is stopped at.",icon:"chip",tone:"data",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(Cn,{value:o.heapInuse,total:o.memoryLimit,tone:o.heapShare>=.9?"bad":o.heapShare>=.75?"warn":"ok"}),e.jsxs("p",{className:"hint",children:["The heap is using ",(o.heapShare*100).toFixed(1),"% of the"," ",he(o.memoryLimit)," limit",o.configuredLimit?` set by GOMEMLIMIT=${o.configuredLimit}`:"","."]})]}):e.jsx(pe,{tone:"warn",children:"No memory limit is set, so the Go runtime will grow until the container is killed by the host. Set GOMEMLIMIT to give it a ceiling to collect against."}),e.jsx(Ue,{rows:[{label:"Heap currently used",value:he(o.heapInuse)},{label:"Heap allocated to live objects",value:he(o.heapAlloc)},{label:"Heap held but idle",value:he(o.heapIdle)},{label:"Returned to the operating system",value:he(o.heapReleased)},{label:"Goroutine stacks",value:he(o.stackInuse)},{label:"Runtime / system reserved",value:he(o.sys)},{label:"Configured process limit",value:x?he(o.memoryLimit):"none"},{label:"Next collection at",value:he(o.nextGc)}]})]}),e.jsxs(C,{title:"Collection",intro:"How often the garbage collector runs and how long it stops the gateway for. Everything the televisions ask for waits during a pause, so this is the figure that turns a memory problem into a slow one.",icon:"refresh",tone:"note",children:[e.jsx(Ms,{tiles:[{label:"collections",value:w(o.numGc)},{label:"collections an hour",value:o.gcPerHour>0?o.gcPerHour.toFixed(0):"—"},{label:"recent pause",value:`${o.pauseRecentMs.toFixed(1)} ms`},{label:"paused in total",value:`${(o.pauseTotalMs/1e3).toFixed(1)} s`}]}),e.jsx(Ue,{rows:[{label:"Processors available",value:w(c.gomaxprocs)},{label:"Operating-system threads",value:w(c.threads)},{label:"Processor use",value:c.process.cpuKnown?`${(c.process.cpuPercent??0).toFixed(1)}% of one processor · ${(c.process.cpuSeconds??0).toFixed(0)}s used in total`:"not available on this host"},{label:"Open connections",value:c.process.filesKnown?`${w(c.process.openSockets)} sockets of ${w(c.process.openFiles)} open files${c.process.fileLimit?` · limit ${w(c.process.fileLimit)}`:""}`:"not available on this host"},{label:"Go version",value:c.goVersion}]})]})]}),e.jsxs(xe,{cols:"2",children:[e.jsx(C,{title:"Goroutines over time",intro:"A single instantaneous count cannot show a leak. This can: a line that climbs and never comes back down is work the gateway is not letting go of.",icon:"chart",tone:"info",children:e.jsx(Js,{samples:u,valueOf:f=>f.goroutines,format:f=>w(f),everySeconds:c.sampleEverySeconds})}),e.jsx(C,{title:"Memory over time",intro:"Heap in use, sampled on the same tick. A saw-tooth that returns to roughly the same floor after each collection is healthy; a floor that keeps rising is not.",icon:"chart",tone:"data",children:e.jsx(Js,{samples:u,valueOf:f=>f.heapInuse,format:he,everySeconds:c.sampleEverySeconds})})]}),e.jsx(C,{title:"Background workers",intro:"Memby's own long-running work, named where it is started rather than guessed at from a stack. A worker that has finished is not necessarily a fault — several are one-shot startup jobs — but one that keeps being started again is failing at something.",icon:"clock",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Worker"}),e.jsx("th",{children:"Area"}),e.jsx("th",{children:"State"}),e.jsx("th",{children:"Since"}),e.jsx("th",{className:"num",children:"Starts"})]})}),e.jsx("tbody",{children:p.length===0?e.jsx(Y,{columns:5,children:"Nothing has registered. This gateway predates named workers."}):p.map(f=>e.jsx(Ta,{worker:f},f.name))})]})})}),e.jsxs(C,{title:"Goroutine breakdown",intro:"What those goroutines are actually doing, and which part of Memby they belong to. Collecting it means walking every stack, which stops the gateway for a few milliseconds — so it is taken when you ask rather than continuously.",icon:"search",tone:"info",children:[e.jsxs("div",{className:"row",children:[e.jsx($,{onClick:h,busy:r,icon:"refresh",variant:"primary",children:n?"Collect again":"Collect breakdown"}),e.jsx("a",{href:"/admin/api/runtime/goroutines?format=text",download:!0,children:e.jsx($,{icon:"download",variant:"quiet",children:"Download full stack dump"})})]}),e.jsx(_,{message:l}),n?e.jsx(Ra,{report:n}):e.jsx(ee,{children:"Nothing collected yet. The snapshot is a moment in time, so it is taken on request and stamped with when it was taken."})]})]})}function Ta({worker:s}){const n=s.state==="finished";return e.jsxs("tr",{children:[e.jsx("td",{children:s.name}),e.jsx("td",{children:e.jsx(N,{tone:"info",children:s.component})}),e.jsx("td",{children:e.jsx(N,{tone:n?"note":"ok",children:n?"finished":"running"})}),e.jsx("td",{children:F(n?s.stopped:s.started)}),e.jsx("td",{className:"num",children:s.starts>1?e.jsx(N,{tone:"warn",children:s.starts}):s.starts})]})}function Js({samples:s,valueOf:n,format:t,everySeconds:r}){if(s.length<2)return e.jsxs(ee,{children:["Not enough history yet. Readings are taken every"," ",r>=60?`${Math.round(r/60)} minutes`:`${r}s`,", and a trend needs about fifteen minutes of them."]});const a=l=>new Date(l.at).toLocaleTimeString();return e.jsx(hs,{data:s,labelOf:l=>a(l),valueOf:l=>n(l),title:l=>`${a(l)}: ${t(n(l))}`})}function Ra({report:s}){const n=s.categories??[],t=s.components??[],r=s.groups??[];return e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"hint",children:[w(s.total)," goroutines, collected ",F(s.at)," in"," ",s.collectedInMs.toFixed(1)," ms."]}),e.jsxs(xe,{cols:"2",children:[e.jsxs("div",{children:[e.jsx(xs,{children:"By what they are doing"}),e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"State"}),e.jsx("th",{className:"num",children:"Count"})]})}),e.jsx("tbody",{children:n.map(a=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("b",{children:a.label}),e.jsx("p",{className:"hint",children:a.description}),e.jsx("p",{className:"hint",children:(a.states??[]).map(l=>`${l.state} (${l.count})`).join(" · ")})]}),e.jsx("td",{className:"num",children:w(a.count)})]},a.category))})]})})]}),e.jsxs("div",{children:[e.jsx(xs,{children:"By which part of Memby"}),e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Area"}),e.jsx("th",{className:"num",children:"Count"}),e.jsx("th",{className:"num",children:"Oldest"})]})}),e.jsx("tbody",{children:t.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx(N,{tone:Ys(a.component),children:a.component})}),e.jsx("td",{className:"num",children:w(a.count)}),e.jsx("td",{className:"num",children:a.longestWaitMinutes>0?`${w(a.longestWaitMinutes)} min`:"—"})]},a.component))})]})})]})]}),e.jsx(xs,{aside:s.groupsTotal>r.length?`the ${r.length} largest of ${w(s.groupsTotal)}`:void 0,children:"Where they are waiting"}),e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"num",children:"Count"}),e.jsx("th",{children:"Area"}),e.jsx("th",{children:"State"}),e.jsx("th",{children:"Function"}),e.jsx("th",{className:"num",children:"Oldest"})]})}),e.jsx("tbody",{children:r.length===0?e.jsx(Y,{columns:5,children:"Nothing to group."}):r.map((a,l)=>e.jsxs("tr",{children:[e.jsx("td",{className:"num",children:w(a.count)}),e.jsx("td",{children:e.jsx(N,{tone:Ys(a.component),children:a.component})}),e.jsx("td",{children:a.state}),e.jsxs("td",{children:[e.jsx("span",{className:"mono",children:a.function}),e.jsx("p",{className:"hint",children:a.file})]}),e.jsx("td",{className:"num",children:a.longestWaitMinutes>0?`${w(a.longestWaitMinutes)} min`:"—"})]},`${a.component}-${a.function}-${a.state}-${l}`))})]})})]})}const Aa=-1;function qe(s){return s===0?"":s<0?"off":String(s)}function De(s,n){const t=s.trim().toLowerCase();if(t==="")return 0;if(n&&(t==="off"||t==="none"||t==="0"))return Aa;const r=Number.parseInt(t,10);return Number.isFinite(r)?r:0}function Fe(s,n){return s<=0?"off":`${s} ${n}${s===1?"":"s"}`}function gs(s){return{timezone:s.timezone??"",logLevel:s.logLevel??"",sessionIdleDays:qe(s.sessionIdleDays),sonarrAlertMinutes:qe(s.sonarrAlertMinutes),radarrAlertMinutes:qe(s.radarrAlertMinutes),embyHealthSeconds:qe(s.embyHealthSeconds),slowRequestMillis:qe(s.slowRequestMillis),librarySyncMinutes:qe(s.librarySyncMinutes)}}function Ea(){const{data:s,error:n,loading:t,reload:r}=J("/admin/api/gateway-settings"),{wrap:a}=ie(),{busy:l,run:i}=ne(),[h,c]=g.useState(null);g.useEffect(()=>{!h&&s&&c(gs(s.settings))},[s,h]);const o=(m,j)=>c(y=>y&&{...y,[m]:j}),u=()=>i("save",async()=>{if(!h)return;const m={timezone:h.timezone.trim(),logLevel:h.logLevel.trim(),sessionIdleDays:De(h.sessionIdleDays,!1),sonarrAlertMinutes:De(h.sonarrAlertMinutes,!0),radarrAlertMinutes:De(h.radarrAlertMinutes,!0),embyHealthSeconds:De(h.embyHealthSeconds,!0),slowRequestMillis:De(h.slowRequestMillis,!0),librarySyncMinutes:De(h.librarySyncMinutes,!0)},j=await a(()=>D.post("/admin/api/gateway-settings",m),"Gateway settings saved.");j&&c(gs(j.settings)),await r()}),p=()=>i("clear",async()=>{const m=await a(()=>D.post("/admin/api/gateway-settings",{timezone:"",logLevel:"",sessionIdleDays:0,sonarrAlertMinutes:0,radarrAlertMinutes:0,embyHealthSeconds:0,slowRequestMillis:0,librarySyncMinutes:0}),"Every setting is back to what this container was deployed with.");m&&c(gs(m.settings)),await r()}),d=s==null?void 0:s.deployed,x=s==null?void 0:s.effective,f=(s==null?void 0:s.logLevels)??[];return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Gateway settings",intro:"Server-level settings for this gateway, changeable without a redeployment."}),e.jsx(_,{message:n}),t||!h||!d||!x?e.jsx(V,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx(C,{title:"This gateway",intro:"What the process is running and what it currently believes.",icon:"chip",tone:"info",actions:e.jsx(N,{tone:"info",children:(s==null?void 0:s.version)??"unknown"}),children:e.jsx(Ue,{rows:[{label:"Server timezone",value:x.timezone||"not set"},{label:"Log level",value:x.logLevel},{label:"Sign-in expiry",value:Fe(x.sessionIdleDays,"day")},{label:"Emby health probe",value:Fe(x.embyHealthSeconds,"second")},{label:"Slow-request breakdown",value:Fe(x.slowRequestMillis,"millisecond")},{label:"Catalogue sweep",value:Fe(x.librarySyncMinutes,"minute")},{label:"Episode alert window",value:Fe(x.sonarrAlertMinutes,"minute")},{label:"Film alert window",value:Fe(x.radarrAlertMinutes,"minute")}]})}),e.jsxs(C,{title:"Overrides",intro:"Leave a field empty to use the value this container was deployed with, shown beneath it. Changes take effect immediately — nothing here needs a restart.",icon:"sliders",tone:"note",footer:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",busy:l==="save",onClick:()=>void u(),children:"Save settings"}),e.jsx($,{busy:l==="clear",onClick:()=>void p(),children:"Use deployed values"})]}),children:[e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Server timezone",hint:`Deployed: ${d.timezone||"not set"}. An IANA name, for example Pacific/Auckland. Decides what "today" means for the schedule rows, the home hero and the sign-in history.`,children:e.jsx("input",{type:"text",value:h.timezone,placeholder:d.timezone,onChange:m=>o("timezone",m.target.value)})}),e.jsx(q,{label:"Log level",hint:`Deployed: ${d.logLevel}. Applies to the running process at once, so debug can be turned on to watch something happen.`,children:e.jsxs("select",{value:h.logLevel,onChange:m=>o("logLevel",m.target.value),children:[e.jsxs("option",{value:"",children:["Deployed (",d.logLevel,")"]}),f.map(m=>e.jsx("option",{value:m,children:m},m))]})})]}),e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Sign a television out after (days)",hint:`Deployed: ${d.sessionIdleDays} days. A session row holds a live Emby token, so this is how long a set nobody uses keeps working credentials.`,children:e.jsx("input",{type:"text",inputMode:"numeric",value:h.sessionIdleDays,placeholder:String(d.sessionIdleDays),onChange:m=>o("sessionIdleDays",m.target.value)})}),e.jsx(q,{label:"Slow-request breakdown above (ms)",hint:`Deployed: ${d.slowRequestMillis||"off"}. A request slower than this logs where its time went — Emby, Postgres, Redis, row assembly. Lower it while chasing one slow screen; type off to stop annotating altogether.`,children:e.jsx("input",{type:"text",inputMode:"numeric",value:h.slowRequestMillis,placeholder:String(d.slowRequestMillis),onChange:m=>o("slowRequestMillis",m.target.value)})}),e.jsx(q,{label:"Emby health probe (seconds)",hint:`Deployed: ${d.embyHealthSeconds||"off"}. How often the gateway asks Emby whether it is answering. Type off to stop probing, which also removes the outage bar from every television.`,children:e.jsx("input",{type:"text",inputMode:"numeric",value:h.embyHealthSeconds,placeholder:String(d.embyHealthSeconds),onChange:m=>o("embyHealthSeconds",m.target.value)})})]}),e.jsx("div",{className:"fields",children:e.jsx(q,{label:"Catalogue sweep (minutes)",hint:`Deployed: ${d.librarySyncMinutes||"off"}. How often the gateway asks Emby what has changed. With the Sonarr and Radarr webhooks wired up a new file is in the catalogue within a minute of landing, and this is only reconciliation for media they do not manage — 360 is a sensible choice then. Without them it is the only way anything is found.`,children:e.jsx("input",{type:"text",inputMode:"numeric",value:h.librarySyncMinutes,placeholder:String(d.librarySyncMinutes),onChange:m=>o("librarySyncMinutes",m.target.value)})})}),e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Episode alert window (minutes)",hint:`Deployed: ${d.sonarrAlertMinutes||"off"}. How long a "just aired" notice stays on offer to a set that was switched off at the time. Type off to stop announcing them.`,children:e.jsx("input",{type:"text",inputMode:"numeric",value:h.sonarrAlertMinutes,placeholder:String(d.sonarrAlertMinutes),onChange:m=>o("sonarrAlertMinutes",m.target.value)})}),e.jsx(q,{label:"Film alert window (minutes)",hint:`Deployed: ${d.radarrAlertMinutes||"off"}. The same, for a film Radarr has just imported.`,children:e.jsx("input",{type:"text",inputMode:"numeric",value:h.radarrAlertMinutes,placeholder:String(d.radarrAlertMinutes),onChange:m=>o("radarrAlertMinutes",m.target.value)})})]}),e.jsxs(pe,{tone:"note",children:["These override the deployed configuration in the database, so they survive a restart — but a deployment rewrites ",e.jsx("code",{children:".env"}),", not this, and the two can then disagree. Anything meant to be permanent belongs in ",e.jsx("code",{children:".env.example"})," ","as well."]}),s!=null&&s.settings.updatedBy?e.jsxs(pe,{children:["Last changed by ",s.settings.updatedBy,s.settings.updatedAt?` on ${new Date(s.settings.updatedAt).toLocaleString("en-NZ")}`:"","."]}):null]})]})]})}const Ia={done:"ok",pending:"warn",failed:"bad"};function La(s){const n=s.payload??{};if(n.series){const t=n.episode&&n.episode>0?` S${String(n.season??0).padStart(2,"0")}E${String(n.episode).padStart(2,"0")}`:"";return`${n.series}${t}`}return n.title?n.year?`${n.title} (${n.year})`:n.title:s.key}function qa(){const{data:s,error:n,loading:t}=J("/admin/api/ingest",{pollMs:15e3});if(t)return e.jsx(V,{rows:1});const r=!!(s!=null&&s.sonarrConfigured||s!=null&&s.radarrConfigured),a=(s==null?void 0:s.recent)??[];return e.jsxs(e.Fragment,{children:[e.jsx(_,{message:n}),e.jsxs(C,{title:"Webhook activity",intro:"Sonarr and Radarr are what put files on disk, so they are what the catalogue learns from. A notification is recorded the moment it arrives and read into the catalogue once the file has settled — which is why an import appears here before it appears in Emby.",icon:"plug",tone:"info",children:[e.jsx(ae,{tiles:[{label:"Sonarr webhook",value:s!=null&&s.sonarrConfigured?"Configured":"Not configured",small:!0,tone:s!=null&&s.sonarrConfigured?"ok":"warn",icon:"tv"},{label:"Radarr webhook",value:s!=null&&s.radarrConfigured?"Configured":"Not configured",small:!0,tone:s!=null&&s.radarrConfigured?"ok":"warn",icon:"play"},{label:"Waiting",value:w((s==null?void 0:s.counts.pending)??0),icon:"clock",tone:"note"},{label:"Given up on",value:w((s==null?void 0:s.counts.failed)??0),icon:"alert",tone:"bad"},{label:"Settle delay",value:`${(s==null?void 0:s.settleSeconds)??0}s`,small:!0,icon:"history",tone:"data"}]}),r?null:e.jsxs("p",{className:"muted",children:["Neither hook has a token, so both answer 404 and nothing is recorded here. Set MEMBY_SONARR_WEBHOOK_TOKEN and MEMBY_RADARR_WEBHOOK_TOKEN, then point each *arr at"," ",e.jsx("code",{children:"/hooks/sonarr"})," and ",e.jsx("code",{children:"/hooks/radarr"}),". Until then the catalogue sweep below is the only way a new title is found."]}),e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"When"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"What"}),e.jsx("th",{children:"Why"}),e.jsx("th",{children:"State"}),e.jsx("th",{children:"Outcome"}),e.jsx("th",{className:"num",children:"Tries"}),e.jsx("th",{children:"Notes"})]})}),e.jsx("tbody",{children:a.length===0?e.jsx(Y,{columns:8,children:r?"Nothing has been imported, upgraded, renamed or deleted since this was switched on.":"No webhook is configured."}):a.map(l=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:F(l.updatedAt)}),e.jsx("td",{className:"muted",children:l.source||"—"}),e.jsx("td",{children:La(l)}),e.jsx("td",{className:"muted",children:l.reason}),e.jsx("td",{children:e.jsx(N,{tone:Ia[l.state]??"warn",children:l.state})}),e.jsx("td",{className:"muted",children:l.outcome||"—"}),e.jsx("td",{className:"num",children:l.attempts}),e.jsx("td",{className:"muted",children:l.lastError||""})]},l.key))})]})})]})]})}function Da(){const{status:s,error:n,loading:t}=je(),r=(s==null?void 0:s.runs)??[];return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Imports",intro:"What Sonarr and Radarr said changed, and the catalogue sweep that reconciles everything they do not manage."}),e.jsx(_,{message:n}),e.jsx(qa,{}),t?e.jsx(V,{rows:1}):e.jsx(C,{title:"Synchronisation history",intro:"A full import mark-and-sweeps the catalogue; an incremental one asks Emby for what changed, with a minute of overlap so nothing falls between two runs. With both webhooks wired up this is reconciliation — media dropped in by hand, a title edited in Emby, a notification that never arrived — rather than how new titles are found.",icon:"sync",tone:"data",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Started"}),e.jsx("th",{children:"Kind"}),e.jsx("th",{children:"Trigger"}),e.jsx("th",{children:"Status"}),e.jsx("th",{className:"num",children:"Seen"}),e.jsx("th",{className:"num",children:"Written"}),e.jsx("th",{className:"num",children:"Removed"}),e.jsx("th",{children:"Notes"})]})}),e.jsx("tbody",{children:r.length===0?e.jsx(Y,{columns:8,children:"Nothing has been imported yet."}):r.map(a=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:F(a.startedAt)}),e.jsx("td",{children:a.kind}),e.jsx("td",{className:"muted",children:a.trigger}),e.jsx("td",{children:e.jsx(N,{tone:a.status==="success"?"ok":a.status==="running"?"warn":"bad",children:a.status})}),e.jsx("td",{className:"num",children:w(a.itemsSeen)}),e.jsx("td",{className:"num",children:w(a.itemsUpserted)}),e.jsx("td",{className:"num",children:w(a.itemsRemoved)}),e.jsx("td",{className:"muted",children:a.error||""})]},a.id||a.startedAt))})]})})})]})}const Fa={gateway:"quiet",auth:"note",playback:"info",media:"info",emby:"data",library:"data",subtitles:"data",search:"note",tracearr:"idle",credits:"idle",integrations:"note",requests:"info",home:"quiet"},En=s=>Fa[s]??"quiet",Oa={admin:["gateway","Gateway","Admin"],installer:["gateway","Gateway","Installer"],api:["gateway","Gateway","API"],health:["gateway","Gateway","Health"],status:["gateway","Gateway","Status"],maintenance:["gateway","Gateway","Maintenance"],"quiet-time":["gateway","Gateway","Quiet time"],webhooks:["gateway","Gateway","Webhooks"],scheduler:["gateway","Gateway","Scheduler"],settings:["gateway","Gateway","Settings"],updates:["gateway","Gateway","Updates"],analytics:["gateway","Gateway","Analytics"],auth:["auth","Auth","Session"],devices:["auth","Auth","Devices"],playback:["playback","Playback","Session"],screensaver:["media","Media","Screensaver"],artwork:["media","Media","Artwork"],details:["media","Media","Details"],search:["search","Search","Query"],home:["home","Home","Rows"],"my-shows":["home","Home","My shows"],recommendations:["tracearr","Tracearr","Recommendations"],"for-you":["tracearr","Tracearr","For you"],library:["library","Library","Sync"],credits:["credits","Credits","Scanner"],ratings:["media","Media","Ratings"],integrations:["integrations","Integrations","Arr"],requests:["requests","Requests","Media"],"emby-health":["emby","Emby","Health"]},Pa=[[/^emby |emby (reachable|unreachable|health)/,["emby","Emby","API"]],[/subtitle/,["subtitles","Subtitles","Provider"]],[/^sonarr|sonarr /,["integrations","Integrations","Sonarr"]],[/^radarr|radarr /,["integrations","Integrations","Radarr"]],[/^tracearr/,["tracearr","Tracearr","Signals"]],[/^credits/,["credits","Credits","Scanner"]],[/^library sync/,["library","Library","Sync"]],[/^(signed in|signed out|sign-in rejected)/,["auth","Auth","Session"]],[/^device /,["auth","Auth","Devices"]],[/^(playback (requested|started|stopped|progress))/,["playback","Playback","Session"]],[/^(next episode resolved|trailer playback|trickplay)/,["playback","Playback","Player"]],[/^scheduled task/,["gateway","Gateway","Scheduler"]],[/^(update offered|update policy)/,["gateway","Gateway","Updates"]]];function _a(s,n){const t=n.toLowerCase();for(const[a,l]of Pa)if(a.test(t))return l;const r=Oa[s];return r||(s?["gateway","Gateway",ms(s.replace(/[-_]/g," "))]:["gateway","Gateway","Server"])}const Ua={h:36e5,m:6e4,s:1e3,ms:1,us:.001,µs:.001,ns:1e-6};function fs(s){if(typeof s=="number")return Number.isFinite(s)?s:null;if(typeof s!="string"||!s)return null;const n=s.matchAll(/([0-9]*\.?[0-9]+)(ns|µs|us|ms|h|m|s)/g);let t=0,r=!1;for(const a of n){const l=a[2]?Ua[a[2]]:void 0;l!==void 0&&(t+=Number(a[1])*l,r=!0)}return r?t:null}function $s(s){return s<1?"<1 ms":s<1e3?`${Math.round(s)} ms`:s<1e4?`${(s/1e3).toFixed(1)} s`:s<6e4?`${Math.round(s/1e3)} s`:`${Math.floor(s/6e4)}m ${Math.round(s%6e4/1e3)}s`}const Wa=s=>s>=3e3?"bad":s>=1e3?"warn":null,Ba={200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",412:"Precondition Failed",418:"Client Closed Request",426:"Upgrade Required",429:"Too Many Requests",499:"Client Closed Request",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};function Va(s){const n=Ba[s];return n||(s>=500?"Server Error":s>=400?"Client Error":s>=300?"Redirected":s>=200?"OK":"Response")}const Ha=s=>s>=500?"bad":s>=400?"warn":s>=300?"quiet":"ok",za={"/healthz":"Health probe","/readyz":"Readiness probe","/v1/status":"Status poll","/v1/home":"Home rows","/v1/features":"Features","/v1/preferences":"Preferences","/v1/theme":"Theme","/v1/magic":"Magic pick","/v1/calendar":"TV calendar","/v1/search":"Search","/v1/update":"Update check"},Ka=s=>/\d/.test(s)||s.length>24;function Qs(s){const n=za[s];if(n)return n;const t=s.split("/").filter(a=>a&&a!=="v1"&&a!=="api");t[0]==="admin"&&t.shift();const r=t.filter(a=>!Ka(a));return r.length===0?s:ms(r.join(" ").replace(/[-_.]/g," ").replace(/\s+/g," ").trim())}const ms=s=>s&&s.charAt(0).toUpperCase()+s.slice(1),es=s=>ms(s.replace(/_/g," ")),ve=s=>s==null?"":String(s),In=new Set(["","unknown","none","null","<nil>","0"]),Ce=s=>!In.has(ve(s).toLowerCase()),Ga=["title","series","name","query","item_title","file"],Za={directplay:"ok",direct:"ok",directstream:"ok",transcode:"warn",transcoding:"warn"};function Ya(s,n,t){if(t!==null)return{label:`${t} ${Va(t)}`,short:String(t),tone:Ha(t)};if(Ce(s.error))return{label:"Failed",short:"Failed",tone:n==="WARN"?"warn":"bad"};const r=ve(s.play_method).toLowerCase().replace(/[\s_-]/g,"");if(r&&!In.has(r)){const a=ms(ve(s.play_method).replace(/([a-z])([A-Z])/g,"$1 $2"));return{label:a,short:a,tone:Za[r]??"info"}}if(Ce(s.cache)){const a=/hit|true|yes/i.test(ve(s.cache));return{label:a?"Cached":"Cache miss",short:a?"Cached":"Miss",tone:a?"data":"quiet"}}return n==="ERROR"?{label:"Failed",short:"Failed",tone:"bad"}:n==="WARN"?{label:"Warning",short:"Warning",tone:"warn"}:null}function Ja(s){const n=[];Ce(s.user)&&n.push(ve(s.user)),Ce(s.device)&&n.push(ve(s.device));const t=fs(s.marker_ms);t!==null&&t>0&&n.push(`Start ${Xs(t)}`);const r=fs(s.position);return r!==null&&r>0&&n.push(`At ${Xs(r)}`),Ce(s.watched)&&n.push(`${ve(s.watched)} watched`),Ce(s.reason)&&n.push(ve(s.reason)),n.slice(0,3).join(" · ")}function Xs(s){const n=Math.round(s/1e3),t=Math.floor(n/3600),r=Math.floor(n%3600/60),a=n%60,l=i=>String(i).padStart(2,"0");return t>0?`${t}:${l(r)}:${l(a)}`:`${r}:${l(a)}`}const Ln=[{title:"Request",keys:["method","path","query_keys","status","cache","client","protocol","host"]},{title:"Context",keys:["user","user_id","device","device_id","item","title","series","type","play_method","play_session_id","media_source_id","position","resume","runtime","watched","subtitles","subtitle_track","subtitle_language","event_name"]},{title:"Where the time went",keys:["duration","breakdown","elsewhere"]},{title:"Diagnostics",keys:["error","stack","correlation","version","gateway_version"]}],Qa=new Set(Ln.flatMap(s=>s.keys)),Xa=s=>Qa.has(s),ei=new Intl.DateTimeFormat("en-NZ",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}),si=new Intl.DateTimeFormat("en-NZ",{weekday:"short",day:"numeric",month:"short"}),en=new WeakMap;function Ge(s){const n=en.get(s);if(n)return n;const t=ni(s);return en.set(s,t),t}function ni(s){const n=s.attributes??{},t=s.message??"",[r,a,l]=_a(ve(n.component),t),i=ve(n.path),h=i?ve(n.method).toUpperCase():"",c=Number(n.status),o=i&&Number.isFinite(c)&&c>0?c:null,u=t==="request"&&!!i,p=Ga.find(L=>Ce(n[L])),d=p?ve(n[p]):"";let x,f;u?(x=h||"HTTP",f=Qs(i)):i&&h?(x=h,f=d?`${es(t)} · ${d}`:`${es(t)}${Qs(i)}`):(x="",f=d?`${es(t)} · ${d}`:es(t));const m=fs(n.duration??n.duration_ms??n.negotiation_duration),j=Ce(n.error)?ve(n.error):"",y=Ja(n),v=new Date(s.occurredAt),b=ve(n.breakdown),A=j||(u?b:y),k=j?"error":A?"context":"",I=!j&&u?y:"",E=Object.entries(n);return{serviceKey:r,service:a,component:l,action:x,summary:f,context:y,detail:j,secondary:A,secondaryTone:k,trail:I,result:Ya(n,s.level,o),durationMs:m,method:h,status:o,eventKey:t,level:s.level,time:`${ei.format(v)}.${String(v.getMilliseconds()).padStart(3,"0")}`,day:si.format(v),dayKey:v.toDateString(),tall:!!A,haystack:[t,a,l,f,y,j,...E.flat().map(ve)].join(" ").toLowerCase(),fields:E,attributes:n}}const sn={TRACE:5,DEBUG:10,INFO:20,WARN:30,ERROR:40},ss={level:"INFO",service:"",component:"",event:"",method:"",status:"",slower:0,text:""};function ti(s,n){if(!s)return!0;if(n===null)return!1;if(s==="error")return n>=400;const t=Number(s[0]);return Math.floor(n/100)===t}function ai(s,n,t){if((sn[s.level]??0)<(sn[n.level]??20))return!1;const r=Ge(s);return!(n.service&&r.serviceKey!==n.service||n.component&&r.component!==n.component||n.event&&r.eventKey!==n.event||n.method&&r.method!==n.method||!ti(n.status,r.status)||n.slower>0&&(r.durationMs??0)<n.slower||t&&!r.haystack.includes(t))}function ii(s){const n=new Map,t=new Set,r=new Set,a=new Set;for(const l of s){const i=Ge(l);n.set(i.serviceKey,i.service),t.add(i.component),r.add(i.eventKey),i.method&&a.add(i.method)}return{services:[...n].map(([l,i])=>({key:l,label:i})).sort((l,i)=>l.label.localeCompare(i.label)),components:[...t].sort((l,i)=>l.localeCompare(i)),events:[...r].sort((l,i)=>l.localeCompare(i)),methods:[...a].sort((l,i)=>l.localeCompare(i))}}function ri(s,n){var r;const t=[];if(s.service){const a=((r=n.find(l=>l.key===s.service))==null?void 0:r.label)??s.service;t.push({key:"service",label:`Service: ${a}`})}return s.component&&t.push({key:"component",label:`Component: ${s.component}`}),s.event&&t.push({key:"event",label:`Event: ${s.event}`}),s.method&&t.push({key:"method",label:`Method: ${s.method}`}),s.status&&t.push({key:"status",label:`Status: ${s.status==="error"?"≥400":s.status}`}),s.slower>0&&t.push({key:"slower",label:`Duration: >${$s(s.slower)}`}),s.text&&t.push({key:"text",label:`Search: ${s.text}`}),t}const ns=2e4,li=5e3,nn=7,oi=16,ci=15,di=2,hi=1,ys=nn+oi+nn+hi,tn=ys+di+ci,an=26,ui=31,rn=10,mi=[{value:"TRACE",label:"Everything"},{value:"DEBUG",label:"Debug+"},{value:"INFO",label:"Info+"},{value:"WARN",label:"Warnings+"},{value:"ERROR",label:"Errors only"}],pi=[{value:"",label:"Any result"},{value:"2xx",label:"Success (2xx)"},{value:"3xx",label:"Redirect (3xx)"},{value:"4xx",label:"Client error (4xx)"},{value:"5xx",label:"Server error (5xx)"},{value:"error",label:"Failed (≥400)"}],xi=[{value:0,label:"Any duration"},{value:100,label:"Slower than 100 ms"},{value:500,label:"Slower than 500 ms"},{value:1e3,label:"Slower than 1 s"},{value:3e3,label:"Slower than 3 s"}],ln=s=>s.replace(/_/g," ");function ts({onPick:s,className:n,title:t,children:r,...a}){return e.jsx("button",{type:"button",className:`logfacet ${n}`,title:t,onClick:s,...a,children:r})}const ji=g.memo(function({event:n,view:t,top:r,height:a,selected:l,onInspect:i,onFilter:h}){const c=t.durationMs!==null?Wa(t.durationMs):null;return e.jsxs("div",{className:"logrow","data-level":t.level,"data-selected":l||void 0,style:{transform:`translateY(${r}px)`,height:`${a}px`},children:[e.jsx("time",{className:"logrow-time",title:n.occurredAt,children:t.time}),e.jsx(ts,{className:"logrow-level","data-level":t.level,title:`Show ${t.level} and above`,onPick:()=>h({level:t.level}),children:t.level}),e.jsxs("span",{className:"logrow-place",children:[e.jsx(ts,{className:"logrow-service","data-tone":En(t.serviceKey),title:`Filter to ${t.service}`,onPick:()=>h({service:t.serviceKey,component:""}),children:t.service}),e.jsx("span",{className:"logrow-sep","aria-hidden":"true",children:""}),e.jsx(ts,{className:"logrow-component",title:`Filter to ${t.component}`,onPick:()=>h({component:t.component}),children:t.component})]}),e.jsxs("button",{type:"button",className:"logrow-summary",title:[t.summary,t.trail,t.secondary].filter(Boolean).join(" — "),onClick:()=>i(n.sequence),children:[e.jsxs("span",{className:"logrow-line",children:[t.action?e.jsx("b",{className:"logrow-action","data-method":t.method||void 0,children:t.action}):null,e.jsx("span",{className:"logrow-text",children:t.summary}),t.trail?e.jsx("span",{className:"logrow-trail",children:t.trail}):null]}),t.secondary?e.jsx("span",{className:"logrow-second","data-tone":t.secondaryTone,children:t.secondaryTone==="error"?`↳ ${t.secondary}`:t.secondary}):null]}),e.jsx("span",{className:"logrow-result",children:t.result?e.jsx(ts,{className:"logrow-verdict","data-tone":t.result.tone,title:t.status!==null?`Filter to ${t.status}`:`Filter to ${t.eventKey}`,onPick:()=>t.status!==null?h({status:`${Math.floor(t.status/100)}xx`}):h({event:t.eventKey}),children:t.result.label}):null}),e.jsx("span",{className:"logrow-duration","data-tone":c??void 0,children:t.durationMs!==null?$s(t.durationMs):""})]})});function gi({event:s,view:n,onClose:t}){const[r,a]=g.useState(!1),l=n.fields.filter(([c])=>!Xa(c)&&c!=="component"),i=async()=>{try{await navigator.clipboard.writeText(JSON.stringify(s,null,2)),a(!0),window.setTimeout(()=>a(!1),1600)}catch{a(!1)}},h=Ln.map(c=>({title:c.title,rows:c.keys.map(o=>[o,n.attributes[o]]).filter(([,o])=>o!=null&&String(o)!=="")})).filter(c=>c.rows.length>0);return e.jsxs("section",{className:"logdrawer","aria-label":`Log record ${s.sequence}`,children:[e.jsxs("header",{className:"logdrawer-head",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"logdrawer-place",children:[e.jsx("span",{className:"logrow-service","data-tone":En(n.serviceKey),children:n.service}),e.jsx("span",{className:"logrow-sep","aria-hidden":"true",children:""}),n.component]}),e.jsx("b",{children:n.summary}),n.detail?e.jsx("p",{className:"logdrawer-error",children:n.detail}):null]}),e.jsxs("div",{className:"logdrawer-actions",children:[e.jsx($,{size:"sm",variant:"quiet",onClick:i,icon:"download",children:r?"Copied":"Copy JSON"}),e.jsx($,{size:"sm",variant:"quiet",onClick:t,icon:"close",children:"Close"})]})]}),e.jsxs("div",{className:"logdrawer-grid",children:[e.jsxs("div",{className:"logdrawer-section",children:[e.jsx("h4",{children:"Overview"}),e.jsxs("dl",{children:[e.jsx("dt",{children:"Time"}),e.jsxs("dd",{children:[n.day," ",n.time]}),e.jsx("dt",{children:"Level"}),e.jsx("dd",{children:n.level}),e.jsx("dt",{children:"Service"}),e.jsxs("dd",{children:[n.service," ",n.component]}),e.jsx("dt",{children:"Event"}),e.jsx("dd",{children:n.eventKey}),n.result?e.jsxs(e.Fragment,{children:[e.jsx("dt",{children:"Result"}),e.jsx("dd",{children:n.result.label})]}):null,n.durationMs!==null?e.jsxs(e.Fragment,{children:[e.jsx("dt",{children:"Duration"}),e.jsx("dd",{children:$s(n.durationMs)})]}):null,e.jsx("dt",{children:"Record"}),e.jsxs("dd",{children:["#",s.sequence]})]})]}),h.map(c=>e.jsxs("div",{className:"logdrawer-section",children:[e.jsx("h4",{children:c.title}),e.jsx("dl",{children:c.rows.map(([o,u])=>e.jsxs(g.Fragment,{children:[e.jsx("dt",{children:ln(o)}),e.jsx("dd",{children:String(u)})]},o))})]},c.title)),l.length?e.jsxs("div",{className:"logdrawer-section",children:[e.jsx("h4",{children:"Details"}),e.jsx("dl",{children:l.map(([c,o])=>e.jsxs(g.Fragment,{children:[e.jsx("dt",{children:ln(c)}),e.jsx("dd",{children:String(o)})]},c))})]}):null]}),e.jsxs("details",{className:"logdrawer-raw",children:[e.jsx("summary",{children:"Raw event"}),e.jsx("pre",{children:JSON.stringify(s,null,2)})]})]})}function vi(){var Ve;const[s,n]=g.useState([]),[t,r]=g.useState(0),[a,l]=g.useState(!1),[i,h]=g.useState(0),[c,o]=g.useState(()=>{const M=new URLSearchParams(window.location.search).get("q")??"";return M?{...ss,text:M}:ss}),[u,p]=g.useState(""),[d,x]=g.useState({top:0,height:600}),[f,m]=g.useState(!0),[j,y]=g.useState(null),v=g.useDeferredValue(c.text.trim().toLowerCase()),b=g.useRef(0),A=g.useRef(!1),k=g.useRef(0),I=g.useRef(null),E=g.useRef(!0),R=g.useRef(void 0),L=g.useRef([]),X=g.useRef(a);g.useEffect(()=>{X.current=a},[a]);const le=g.useCallback(M=>{n(B=>{const Q=B.concat(M);return Q.length>ns?Q.slice(Q.length-ns):Q})},[]),ue=g.useCallback(async()=>{if(A.current||document.hidden)return;A.current=!0;const M=k.current,B=[];let Q=0;try{let fe=0,Me;do Me=await D.get(`/admin/api/events?after=${b.current}&limit=1000`),b.current=Me.next||b.current,Q+=Me.dropped||0,B.push(...Me.events??[]),fe+=1;while(Me.hasMore&&fe<20);p("")}catch(fe){p(fe instanceof Error?fe.message:String(fe))}finally{B.length>0&&M===k.current&&(X.current?(L.current=L.current.concat(B),L.current.length>ns&&(L.current=L.current.slice(L.current.length-ns)),h(L.current.length)):le(B)),Q>0&&M===k.current&&r(fe=>fe+Q),A.current=!1}},[le]);g.useEffect(()=>{let M;const B=()=>{window.clearInterval(M),M=document.hidden?void 0:window.setInterval(()=>void ue(),li)},Q=()=>{B(),document.hidden||ue()};return ue(),B(),document.addEventListener("visibilitychange",Q),()=>{window.clearInterval(M),document.removeEventListener("visibilitychange",Q)}},[ue]);const te=g.useCallback(()=>{X.current=!0,l(!0)},[]),H=g.useCallback(()=>{X.current=!1;const M=L.current;L.current=[],h(0),l(!1),M.length&&le(M)},[le]),re=g.useCallback(M=>{o(B=>({...B,...M}))},[]),S=g.useMemo(()=>s.filter(M=>ai(M,c,v)),[s,c,v]),O=g.useMemo(()=>{const M=new Float64Array(S.length+1),B=new Uint8Array(S.length),Q=new Uint8Array(S.length);let fe=0,Me="";for(let Le=0;Le<S.length;Le+=1){const Ts=S[Le];if(!Ts)continue;const ps=Ge(Ts);ps.dayKey!==Me&&(Q[Le]=1,Me=ps.dayKey,fe+=an);const Rs=ps.tall?tn:ys;M[Le]=fe,B[Le]=Rs,fe+=Rs}return M[S.length]=fe,{tops:M,heights:B,divider:Q,total:fe}},[S]),z=Math.max(0,d.top-ui),oe=g.useMemo(()=>{let M=0,B=S.length;for(;M<B;){const Q=M+B>>1;(O.tops[Q]??0)+(O.heights[Q]??0)<=z?M=Q+1:B=Q}return Math.max(0,M-rn)},[O,z,S.length]),we=g.useMemo(()=>{const M=z+d.height;let B=oe;for(;B<S.length&&(O.tops[B]??0)<M;)B+=1;return Math.min(S.length,B+rn)},[O,z,d.height,oe,S.length]),Te=g.useMemo(()=>{const M=[];for(let B=oe;B<we;B+=1){const Q=S[B];Q&&M.push({event:Q,view:Ge(Q),index:B})}return M},[S,oe,we]),Re=((Ve=S.at(-1))==null?void 0:Ve.sequence)??0,ge=g.useMemo(()=>s.find(M=>M.sequence===j),[s,j]),T=g.useCallback(()=>{const M=I.current;M&&(E.current=!0,M.scrollTop=M.scrollHeight,m(!0),x({top:M.scrollTop,height:M.clientHeight}))},[]);g.useLayoutEffect(()=>{const M=I.current;!M||!E.current||(M.scrollTop=M.scrollHeight,x({top:M.scrollTop,height:M.clientHeight}))},[Re,O.total]),g.useEffect(()=>()=>window.cancelAnimationFrame(R.current??0),[]);const P=()=>{const M=I.current;if(!M)return;const B=M.scrollHeight-M.scrollTop-M.clientHeight<tn;E.current=B,m(B),window.cancelAnimationFrame(R.current??0),R.current=window.requestAnimationFrame(()=>{x({top:M.scrollTop,height:M.clientHeight})})},de=()=>{const M=new Blob([JSON.stringify(S,null,2)],{type:"application/json"}),B=document.createElement("a");B.href=URL.createObjectURL(M),B.download=`memby-events-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,B.click(),window.setTimeout(()=>URL.revokeObjectURL(B.href),1e3)},me=g.useMemo(()=>ii(s),[s]),Ie=ri(c,me.services);return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Server logs",intro:"Structured gateway events as they happen."}),e.jsx(_,{message:u}),e.jsxs(C,{children:[e.jsxs("div",{className:"logbar",children:[e.jsxs("div",{className:"logbar-filters",children:[e.jsxs("select",{"aria-label":"Service",value:c.service,onChange:M=>re({service:M.target.value,component:""}),children:[e.jsx("option",{value:"",children:"All services"}),me.services.map(M=>e.jsx("option",{value:M.key,children:M.label},M.key))]}),e.jsxs("select",{"aria-label":"Component",value:c.component,onChange:M=>re({component:M.target.value}),children:[e.jsx("option",{value:"",children:"All components"}),me.components.map(M=>e.jsx("option",{value:M,children:M},M))]}),e.jsx("select",{"aria-label":"Level",value:c.level,onChange:M=>re({level:M.target.value}),children:mi.map(M=>e.jsx("option",{value:M.value,children:M.label},M.value))}),e.jsxs("select",{"aria-label":"Event",value:c.event,onChange:M=>re({event:M.target.value}),children:[e.jsx("option",{value:"",children:"All events"}),me.events.map(M=>e.jsx("option",{value:M,children:M},M))]}),e.jsx("select",{"aria-label":"Result",value:c.status,onChange:M=>re({status:M.target.value}),children:pi.map(M=>e.jsx("option",{value:M.value,children:M.label},M.value))}),e.jsxs("select",{"aria-label":"Method",value:c.method,onChange:M=>re({method:M.target.value}),children:[e.jsx("option",{value:"",children:"Any method"}),me.methods.map(M=>e.jsx("option",{value:M,children:M},M))]}),e.jsx("select",{"aria-label":"Duration",value:String(c.slower),onChange:M=>re({slower:Number(M.target.value)}),children:xi.map(M=>e.jsx("option",{value:String(M.value),children:M.label},M.value))}),e.jsxs("label",{className:"logsearch",children:[e.jsx(se,{name:"search"}),e.jsx("input",{type:"search",value:c.text,"aria-label":"Search logs",placeholder:"Search person, title, service, component, path, request ID…",onChange:M=>re({text:M.target.value})})]})]}),e.jsxs("div",{className:"logbar-actions",children:[e.jsx($,{size:"sm",variant:"quiet",onClick:()=>a?H():te(),icon:a?"play":"clock",children:a?i?`Resume (${w(i)})`:"Resume":"Pause"}),e.jsx($,{size:"sm",variant:"quiet",onClick:()=>{k.current+=1,L.current=[],h(0),n([]),r(0),y(null)},children:"Clear view"}),e.jsx($,{size:"sm",variant:"quiet",onClick:de,icon:"download",title:"Export the rows matching the current filters, as delivered by the gateway",children:"Export JSON"})]})]}),Ie.length?e.jsxs("div",{className:"logchips",children:[Ie.map(M=>e.jsxs("button",{type:"button",className:"logchip",onClick:()=>re({[M.key]:ss[M.key]}),children:[M.label,e.jsx(se,{name:"close"})]},M.key)),e.jsx("button",{type:"button",className:"logchip logchip-clear",onClick:()=>o(ss),children:"Clear all"})]}):null,e.jsxs("div",{className:"logshell",children:[e.jsxs("div",{className:"logview",ref:I,onScroll:P,role:"log","aria-label":"Server events",children:[e.jsxs("div",{className:"loghead","aria-hidden":"true",children:[e.jsx("span",{children:"Time"}),e.jsx("span",{children:"Level"}),e.jsx("span",{children:"Service"}),e.jsx("span",{children:"Event"}),e.jsx("span",{children:"Result"}),e.jsx("span",{children:"Duration"})]}),S.length===0?e.jsx("p",{className:"empty",children:s.length===0?"Waiting for server events…":"No events match these filters."}):e.jsx("div",{className:"logbody",style:{height:`${O.total}px`},children:Te.map(({event:M,view:B,index:Q})=>e.jsxs(g.Fragment,{children:[O.divider[Q]?e.jsx("div",{className:"logday",style:{transform:`translateY(${(O.tops[Q]??0)-an}px)`},children:e.jsx("span",{children:B.day})}):null,e.jsx(ji,{event:M,view:B,top:O.tops[Q]??0,height:O.heights[Q]??ys,selected:M.sequence===j,onInspect:y,onFilter:re})]},M.sequence))})]}),!f&&S.length>0?e.jsxs("button",{type:"button",className:"logtail",onClick:T,children:[e.jsx(se,{name:"caret"}),"Jump to latest"]}):null]}),e.jsxs("p",{className:"hint",children:[w(s.length)," retained · ",w(S.length)," matching",S.length?` · ${w(Te.length)} rows mounted`:"",t?` · ${w(t)} overwritten before delivery`:"",a?` · paused${i?`, ${w(i)} held`:""}`:""]}),ge?e.jsx(gi,{event:ge,view:Ge(ge),onClose:()=>y(null)}):s.length?e.jsx(pe,{children:"Select a row to see the full record — request, context, diagnostics and raw event."}):null]})]})}const on=["home","movies","shows","favorites","search","recent_searches","genre_browse","for_you","for_you_time","recommendation","continue","latest","my_shows","details","playback","magic_movie","notifications","profiles","settings"];function Ae(s){const n=String(s||"—").replaceAll("_"," ");return n==="favorites"?"Favourites":n==="abandoned"?"Abandoned / interrupted":n}function bi(){const[s,n]=g.useState(30),[t,r]=g.useState(""),a=ws(),l=g.useMemo(()=>`/admin/api/journeys${Be({days:s,userId:t})}`,[s,t]),{data:i,error:h,loading:c}=J(l),o=i==null?void 0:i.stats,u=(i==null?void 0:i.users)??[],p=(i==null?void 0:i.actions)??[],d=(i==null?void 0:i.paths)??[],x=d[0],f=g.useMemo(()=>{const m=new Map(((i==null?void 0:i.features)??[]).map(y=>[y.feature,y])),j=new Map(on.map((y,v)=>[y,v]));return[...new Set([...on,...m.keys()])].map(y=>({name:y,stat:m.get(y)})).sort((y,v)=>{var A,k;const b=(((A=v.stat)==null?void 0:A.uses)??0)-(((k=y.stat)==null?void 0:k.uses)??0);return b||(j.get(y.name)??Number.MAX_SAFE_INTEGER)-(j.get(v.name)??Number.MAX_SAFE_INTEGER)})},[i==null?void 0:i.features]);return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"User journeys",intro:"How viewers move through Memby, use features and complete flows."}),e.jsx(_,{message:h}),e.jsx(C,{title:"Journey health",intro:"Server-derived foreground visits, completion and interruption. Search text, content titles and setting values are never stored.",icon:"people",tone:"info",actions:e.jsxs(e.Fragment,{children:[e.jsx(q,{label:"Window",children:e.jsxs("select",{value:s,onChange:m=>n(Number(m.target.value)),children:[e.jsx("option",{value:1,children:"24 hours"}),e.jsx("option",{value:7,children:"7 days"}),e.jsx("option",{value:30,children:"30 days"}),e.jsx("option",{value:90,children:"90 days"})]})}),e.jsx(q,{label:"User",children:e.jsxs("select",{value:t,onChange:m=>{const j=m.target.value;r(j),j&&a(`/admin/journeys/${encodeURIComponent(j)}`)},children:[e.jsx("option",{value:"",children:"All users"}),u.map(m=>e.jsx("option",{value:m.userId,children:m.username||m.userId},m.userId))]})})]}),children:c?e.jsx(V,{rows:1}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:"journeys",value:w(o==null?void 0:o.journeys),icon:"list",tone:"data"},{label:"viewers",value:w(o==null?void 0:o.viewers),icon:"people",tone:"info"},{label:"completion",value:is(o==null?void 0:o.completionRate),icon:"check",tone:"ok"},{label:"abandoned",value:w(o==null?void 0:o.abandoned),icon:"alert",tone:"note"},{label:"active now",value:w(o==null?void 0:o.active),icon:"pulse",tone:"info"},{label:"average steps",value:((o==null?void 0:o.averageSteps)??0).toFixed(1),icon:"chart"},{label:"average visit",value:ye(o==null?void 0:o.averageTimeMs),small:!0,icon:"clock"},{label:"history kept",value:`${(i==null?void 0:i.retentionDays)??90} days`,small:!0,icon:"clock"}]}),e.jsxs("div",{className:"summary-grid",children:[e.jsxs("div",{className:"summary",children:[e.jsxs("div",{className:"summary-head",children:[e.jsx("b",{children:"Visit completion"}),e.jsx("strong",{children:is(o==null?void 0:o.completionRate)})]}),e.jsx(Cn,{value:(o==null?void 0:o.completed)??0,total:(o==null?void 0:o.journeys)??0}),e.jsxs("p",{children:[w(o==null?void 0:o.completed)," completed · ",w(o==null?void 0:o.abandoned)," abandoned ·"," ",w(o==null?void 0:o.active)," active"]})]}),e.jsxs("div",{className:"summary",children:[e.jsx("div",{className:"summary-head",children:e.jsx("b",{children:"Most common route"})}),e.jsx("strong",{style:void 0,children:x?`${Ae(x.from)}${Ae(x.to)}`:"Not enough data"}),e.jsx("p",{children:x?`${w(x.count)} times in this window`:"Journeys will appear here as viewers move through Memby."})]})]})]})}),e.jsxs(xe,{cols:"2",children:[e.jsx(C,{title:"What people do",intro:"Actions show total use and how many separate visits included them.",icon:"chart",tone:"info",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Action"}),e.jsx("th",{className:"num",children:"Uses"}),e.jsx("th",{className:"num",children:"Visits"})]})}),e.jsx("tbody",{children:p.length===0?e.jsx(Y,{columns:3,children:"No significant actions in this window."}):p.map(m=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("b",{children:Ae(m.action)}),e.jsx("span",{className:"table-sub",children:Ae(m.category)})]}),e.jsx("td",{className:"num",children:w(m.events)}),e.jsx("td",{className:"num",children:w(m.journeys)})]},`${m.category}:${m.action}`))})]})})}),e.jsx(C,{title:"Where people go",intro:"The most common steps between screens, including where quiet visits ended.",icon:"list",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Route"}),e.jsx("th",{className:"num",children:"Times"})]})}),e.jsx("tbody",{children:d.length===0?e.jsx(Y,{columns:2,children:"No repeated paths in this window."}):d.map((m,j)=>e.jsxs("tr",{children:[e.jsxs("td",{children:[Ae(m.from)," ",e.jsx("span",{className:"route-arrow",children:"→"})," ",Ae(m.to)]}),e.jsx("td",{className:"num",children:w(m.count)})]},`${m.from}:${m.to}:${j}`))})]})})})]}),e.jsx(C,{title:"Feature use",intro:"Rare and unused features are shown against Memby's major feature catalogue.",icon:"pulse",tone:"data",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Feature"}),e.jsx("th",{className:"num",children:"Uses"}),e.jsx("th",{children:"Last used"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:f.map(({name:m,stat:j})=>{const y=(j==null?void 0:j.uses)??0;return e.jsxs("tr",{children:[e.jsx("td",{children:Ae(m)}),e.jsx("td",{className:"num",children:w(y)}),e.jsx("td",{className:"muted nowrap",children:j?F(j.lastUsedAt):"—"}),e.jsx("td",{children:y===0?e.jsx(N,{tone:"warn",children:"not used"}):y<3?e.jsx(N,{tone:"note",children:"rare"}):e.jsx(N,{tone:"ok",children:"used"})})]},m)})})]})})}),t?null:e.jsx(C,{title:"Inspect a viewer",intro:"Choose a person above to open their dedicated session and viewing-journey timeline.",icon:"journey",tone:"info",children:e.jsx("p",{className:"empty",children:"A viewing journey follows one intent through to playback, so two films watched in a single app session appear as two separate journeys."})})]})}const $e=s=>{const n=String(s||"—").replaceAll("_"," ");return n==="favorites"?"Favourites":n},qn=s=>$e((s==null?void 0:s.target)||(s==null?void 0:s.screen)||(s==null?void 0:s.source)||(s==null?void 0:s.feature)),fi=s=>{const n=s.find(t=>t.category==="playback"&&t.action==="request");return n!=null&&n.source?$e(n.source):qn(s[0])},cn=s=>s.itemName?`${$e(s.itemType)} · ${s.itemName}`:s.source&&s.target?`${$e(s.source)}${$e(s.target)}`:qn(s),yi=s=>({journey_start:"Opened Memby",home_open:"Opened Memby",journey_end:"Finished session",screen_view:"Viewed",select:"Selected",open:"Opened",close:"Closed",request:s.category==="playback"?"Asked to watch":"Requested",stop:"Left the player",start:s.category==="playback"?s.outcome==="failure"?"Playback failed":"Started watching":"Started",complete:s.category==="playback"?s.outcome==="completed"?"Finished watching":"Stopped watching":"Completed"})[s.action]??$e(s.action);function wi(s){var r;const n=[...s].reverse().find(a=>a.category==="playback"&&a.outcome);if((n==null?void 0:n.outcome)==="failure")return{label:"playback failed",tone:"warn"};if((n==null?void 0:n.outcome)==="completed")return{label:"watched",tone:"ok"};if((n==null?void 0:n.outcome)==="abandoned")return{label:"stopped part-way",tone:"note"};if((n==null?void 0:n.outcome)==="success")return{label:"watched",tone:"ok"};const t=(r=[...s].reverse().find(a=>a.outcome))==null?void 0:r.outcome;return t==="success"||t==="completed"?{label:$e(t),tone:"ok"}:t==="failure"||t==="cancelled"||t==="abandoned"?{label:$e(t),tone:"note"}:s.some(a=>a.action==="stop"&&a.category==="playback")?{label:"watched",tone:"ok"}:{label:"left before playback ended",tone:"warn"}}function ki(s){const n=s.reduce((t,r,a)=>(r.category==="playback"&&r.action==="request"&&t.push(a),t),[]);return n.length===0?[s]:n.map((t,r)=>s.slice(r===0?0:t,n[r+1]??s.length))}function Ni(){var c,o;const{userId:s=""}=We(),n=g.useMemo(()=>`/admin/api/journeys${Be({days:90,userId:s})}`,[s]),{data:t,error:r,loading:a}=J(n),l=((o=(c=t==null?void 0:t.users)==null?void 0:c.find(u=>u.userId===s))==null?void 0:o.username)||s,i=g.useMemo(()=>{const u=new Map;for(const p of(t==null?void 0:t.events)??[])u.set(p.journeyId,[...u.get(p.journeyId)??[],p]);return[...u.values()].map(p=>p.sort((d,x)=>d.sequence-x.sequence)).sort((p,d)=>{var x,f;return(((x=d[0])==null?void 0:x.occurredAt)??"").localeCompare(((f=p[0])==null?void 0:f.occurredAt)??"")})},[t==null?void 0:t.events]),h=i.flatMap(u=>ki(u).map((p,d)=>{var x;return{events:p,key:`${(x=u[0])==null?void 0:x.journeyId}:${d}`}}));return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:`${l}'s journeys`,intro:"Each app session is shown as the viewing journeys it contains: entry, selection, playback outcome.",icon:"journey",crumbs:e.jsx(Z,{className:"crumb",to:"/admin/journeys",children:"Journeys"})}),e.jsx(_,{message:r}),a?e.jsx(V,{}):e.jsx(C,{title:"Viewing journeys",intro:`${i.length} app session${i.length===1?"":"s"} · ${h.length} viewing journey${h.length===1?"":"s"} in the last 90 days.`,icon:"journey",tone:"info",children:e.jsx("div",{className:"visits",children:h.length===0?e.jsx("p",{className:"empty",children:"No journeys recorded for this viewer."}):h.map((u,p)=>{const d=u.events,x=d[0],f=[...d].reverse().find(j=>j.itemName||j.action==="select"||j.category==="playback"&&j.action==="request"),m=wi(d);return e.jsxs("article",{className:"visit",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("b",{children:F(x==null?void 0:x.occurredAt)}),e.jsxs("span",{children:["Journey ",p+1," · ",d.length," recorded steps"]})]}),e.jsx(N,{tone:m.tone,children:m.label})]}),e.jsxs("div",{className:"journey-answers",children:[e.jsxs("div",{className:"journey-answer","data-kind":"entry",children:[e.jsx(se,{name:"journey"}),e.jsx("span",{children:"Entered from"}),e.jsx("b",{children:fi(d)})]}),e.jsxs("div",{className:"journey-answer","data-kind":"selection",children:[e.jsx(se,{name:"play"}),e.jsx("span",{children:"Selected"}),e.jsx("b",{children:f?cn(f):"Nothing selected"})]}),e.jsxs("div",{className:"journey-answer","data-kind":"outcome",children:[e.jsx(se,{name:m.tone==="ok"?"check":"clock"}),e.jsx("span",{children:"Outcome"}),e.jsx("b",{children:m.label})]})]}),e.jsx("ol",{className:"journey-timeline",children:d.map(j=>e.jsxs("li",{children:[e.jsx("span",{className:"timeline-dot","data-action":j.action}),e.jsxs("div",{children:[e.jsx("b",{children:yi(j)}),e.jsx("span",{children:cn(j)})]}),e.jsx("time",{children:F(j.occurredAt)})]},`${j.journeyId}:${j.sequence}`))})]},u.key)})})})]})}function dn(s){const n=String(s||"—").replaceAll("_"," ");return n==="favorites"?"Favourites":n==="abandoned"?"Abandoned / interrupted":n}function Si(){const[s,n]=g.useState(30),{data:t,error:r,loading:a}=J(`/admin/api/analytics?days=${s}`),l=(t==null?void 0:t.rows)??[];return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Row engagement",intro:"Impressions, focus, dwell and selections per launcher row."}),e.jsx(_,{message:r}),e.jsx(C,{title:"Launcher rows",intro:"Impressions are rows drawn, focuses are rows the D-pad reached, and dwell is how long it stayed there. Open rate is what a row was worth.",icon:"chart",tone:"info",actions:e.jsx(q,{label:"Window",children:e.jsxs("select",{value:s,onChange:i=>n(Number(i.target.value)),children:[e.jsx("option",{value:1,children:"24 hours"}),e.jsx("option",{value:7,children:"7 days"}),e.jsx("option",{value:30,children:"30 days"}),e.jsx("option",{value:90,children:"90 days"})]})}),children:a?e.jsx(V,{rows:1}):e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Kind"}),e.jsx("th",{className:"num",children:"Dwell"}),e.jsx("th",{className:"num",children:"Impressions"}),e.jsx("th",{className:"num",children:"Focuses"}),e.jsx("th",{className:"num",children:"Opened"}),e.jsx("th",{className:"num",children:"Open rate"}),e.jsx("th",{className:"num",children:"Viewers"})]})}),e.jsx("tbody",{children:l.length===0?e.jsx(Y,{columns:8,children:"No events in this window."}):l.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:dn(i.rowId)}),e.jsx("td",{className:"muted",children:dn(i.rowKind)}),e.jsx("td",{className:"num",children:ye(i.dwellMs)}),e.jsx("td",{className:"num",children:w(i.impressions)}),e.jsx("td",{className:"num",children:w(i.focuses)}),e.jsx("td",{className:"num",children:w(i.selects)}),e.jsx("td",{className:"num",children:is(i.selectRate)}),e.jsx("td",{className:"num",children:w(i.viewers)})]},`${i.rowId}:${i.rowKind}`))})]})})})]})}function Mi(){const[s,n]=g.useState(7),{data:t,error:r,loading:a}=J(`/admin/api/searches?days=${s}`),l=(t==null?void 0:t.terms)??[],i=(t==null?void 0:t.recent)??[],h=t==null?void 0:t.totals;return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Searches",intro:"What viewers have been looking for, and what was searched just now."}),e.jsx(_,{message:r}),e.jsx(ae,{tiles:[{label:"searches",value:w((h==null?void 0:h.searches)??0),icon:"search",tone:"info"},{label:"distinct queries",value:w((h==null?void 0:h.queries)??0),icon:"list",tone:"data"},{label:"viewers searching",value:w((h==null?void 0:h.viewers)??0),icon:"people",tone:"note"},{label:"history kept",value:`${(t==null?void 0:t.retentionDays)??30} days`,small:!0,icon:"clock"}]}),a?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(C,{title:"What the house looks for",intro:"Queries the search tab ran, grouped without regard to case and labelled with the most recent spelling. Instant search asks from the second character, so a title typed slowly leaves its prefixes here too.",icon:"search",tone:"info",actions:e.jsx(q,{label:"Window",children:e.jsxs("select",{value:s,onChange:c=>n(Number(c.target.value)),children:[e.jsx("option",{value:1,children:"24 hours"}),e.jsx("option",{value:7,children:"7 days"}),e.jsx("option",{value:30,children:"30 days"})]})}),children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{className:"num",children:"Searches"}),e.jsx("th",{className:"num",children:"Viewers"}),e.jsx("th",{children:"Last searched"})]})}),e.jsx("tbody",{children:l.length===0?e.jsx(Y,{columns:4,children:"Nothing searched in this window."}):l.map(c=>e.jsxs("tr",{children:[e.jsx("td",{children:c.query}),e.jsx("td",{className:"num",children:w(c.searches)}),e.jsx("td",{className:"num",children:w(c.viewers)}),e.jsx("td",{className:"muted nowrap",children:F(c.lastAt)})]},c.query))})]})})}),e.jsx(C,{title:"As it happened",intro:"The log, newest first — the query exactly as it was typed, and who typed it. This is the one to read when somebody says search is not finding something.",icon:"history",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"When"}),e.jsx("th",{children:"Viewer"}),e.jsx("th",{children:"Query"})]})}),e.jsx("tbody",{children:i.length===0?e.jsx(Y,{columns:3,children:"No searches in this window."}):i.map((c,o)=>e.jsxs("tr",{children:[e.jsx("td",{className:"muted nowrap",children:F(c.occurredAt)}),e.jsx("td",{children:c.username||e.jsx(N,{tone:"warn",children:c.userId||"unknown"})}),e.jsx("td",{children:c.query})]},`${c.occurredAt}:${o}`))})]})})})]})]})}function hn(s,n){if(n===0)return s>0?"new this week":"no change";const t=Math.round((s-n)/n*100);return`${t>0?"+":""}${t}% vs last week`}function Ci(){const{data:s,error:n,loading:t}=J("/admin/api/views",{pollMs:6e4}),r=(s==null?void 0:s.daily)??[],a=(s==null?void 0:s.hourly)??[];return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Views",intro:"How often people reach Membys home screen. This measures app use, not playback streams."}),e.jsx(_,{message:n}),t?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{tiles:[{label:hn((s==null?void 0:s.today.visits)??0,(s==null?void 0:s.lastWeek.visits)??0),value:w(s==null?void 0:s.today.visits),icon:"overview",tone:"data"},{label:hn((s==null?void 0:s.today.viewers)??0,(s==null?void 0:s.lastWeek.viewers)??0),value:w(s==null?void 0:s.today.viewers),icon:"people",tone:"note"},{label:"busiest time today",value:(s==null?void 0:s.busiestHour)||"—",small:!0,icon:"clock",tone:"info"}]}),e.jsx(C,{title:"Visits by day",intro:"One visit is a signed-in home-screen opening. Viewers are distinct signed-in profiles.",icon:"chart",tone:"data",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Day"}),e.jsx("th",{className:"num",children:"Visits"}),e.jsx("th",{className:"num",children:"Viewers"})]})}),e.jsx("tbody",{children:r.length===0?e.jsx(Y,{columns:3,children:"No home-screen visits yet."}):r.map(l=>e.jsxs("tr",{children:[e.jsx("td",{children:l.label}),e.jsx("td",{className:"num",children:w(l.visits)}),e.jsx("td",{className:"num",children:w(l.viewers)})]},l.label))})]})})}),e.jsx(C,{title:"Today by hour",intro:"Local New Zealand time. Use this to see when viewers are opening Memby.",icon:"clock",tone:"info",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Hour"}),e.jsx("th",{className:"num",children:"Visits"}),e.jsx("th",{className:"num",children:"Viewers"})]})}),e.jsx("tbody",{children:a.length===0?e.jsx(Y,{columns:3,children:"No home-screen visits yet today."}):a.map(l=>e.jsxs("tr",{children:[e.jsx("td",{children:l.label}),e.jsx("td",{className:"num",children:w(l.visits)}),e.jsx("td",{className:"num",children:w(l.viewers)})]},l.label))})]})})})]})]})}const $i=s=>s.mediaType==="episode"?`${s.seriesTitle} S${String(s.seasonNumber).padStart(2,"0")}E${String(s.episodeNumber).padStart(2,"0")}`:s.title;function Ti(){var a;const s=J("/admin/api/media-reports",{pollMs:15e3}),{busy:n,run:t}=ne(),r=(l,i)=>t(`${l.id}-${i}`,async()=>{await D.post(`/admin/api/media-reports/${l.id}/status`,{status:i}),await s.reload()});return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Media reports",intro:"Viewer-reported problems and the individual replacement searches they asked Memby to start."}),s.loading?e.jsx(V,{rows:4}):e.jsx(C,{title:"Open and recent reports",intro:"A replacement always targets one film or one episode. Existing files stay in place while Radarr or Sonarr applies its normal import policy.",icon:"inbox",children:(a=s.data)!=null&&a.reports.length?e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Media"}),e.jsx("th",{children:"Report"}),e.jsx("th",{children:"Viewer"}),e.jsx("th",{children:"Replacement"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Reported"}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:s.data.reports.map(l=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("b",{children:$i(l)}),e.jsx("br",{}),e.jsx("span",{className:"muted",children:l.title})]}),e.jsxs("td",{children:[l.reason.replaceAll("_"," "),l.comment?e.jsxs(e.Fragment,{children:[e.jsx("br",{}),e.jsx("span",{className:"muted",children:l.comment})]}):null]}),e.jsxs("td",{children:[l.reportedByUsername,e.jsx("br",{}),e.jsx("span",{className:"muted",children:l.reportedByDevice||"Unknown device"})]}),e.jsx("td",{children:e.jsx(N,{tone:l.replacementRequested?"note":void 0,children:l.replacementRequested?l.replacementStatus||"Requested":"Not requested"})}),e.jsx("td",{children:e.jsx(N,{tone:l.status==="resolved"?"ok":l.status==="dismissed"?void 0:"warn",children:l.status})}),e.jsx("td",{className:"nowrap muted",children:F(l.createdAt)}),e.jsxs("td",{children:[e.jsx($,{size:"sm",variant:"quiet",busy:n===`${l.id}-acknowledged`,onClick:()=>void r(l,"acknowledged"),children:"Acknowledge"})," ",e.jsx($,{size:"sm",variant:"quiet",busy:n===`${l.id}-resolved`,onClick:()=>void r(l,"resolved"),children:"Resolve"})," ",e.jsx($,{size:"sm",variant:"quiet",busy:n===`${l.id}-dismissed`,onClick:()=>void r(l,"dismissed"),children:"Dismiss"})]})]},l.id))})]})}):e.jsx(ee,{children:"No media problems have been reported."})})]})}const un={user:"",kind:"",channel:"",status:"",source:"",q:"",from:"",to:""},Ri=[{value:1,label:"Today"},{value:7,label:"7 days"},{value:30,label:"30 days"},{value:90,label:"90 days"}],ze=100,Dn={sent:"ok",delivered:"ok",failed:"bad",pending:"warn",skipped:"idle"},Ai={"in-app":"note",broadcast:"info",webhook:"data"},os={"in-app":"In-app",broadcast:"Broadcast",webhook:"Webhook"};function Se(s){if(!s)return"—";const n=s.replace(/[-_.:]+/g," ").trim();return n.charAt(0).toUpperCase()+n.slice(1)}function as(s,n){return(s??[]).map(t=>e.jsxs("option",{value:t.value,children:[n(t.value)," (",t.count,")"]},t.value))}function Ei(){var y,v,b,A;const[s,n]=g.useState(7),[t,r]=g.useState(un),[a,l]=g.useState(0),[i,h]=g.useState(null),c=g.useMemo(()=>Be({...t,days:t.from?void 0:s,limit:ze,offset:a*ze}),[t,s,a]),o=J(`/admin/api/notification-log${c}`),u=o.data,p=k=>{r(I=>({...I,...k})),l(0),h(null)},d=Object.values(t).some(k=>k!==""),x=u==null?void 0:u.totals,f=(u==null?void 0:u.retentionDays)??90,m=(u==null?void 0:u.entries.length)??0,j=!u||u.total===0?0:a*ze+1;return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Notifications",intro:"Everything Memby sent — a viewer's own news, the bar every television draws, and each outbound webhook — with what became of it. Every feature reports through one notification service, so this is the whole trail rather than whichever half a feature remembered to log."}),e.jsx(_,{message:o.error}),x?e.jsx(ae,{tiles:[{label:"Sent",value:w(x.sent),icon:"send",tone:"ok"},{label:"Confirmed",value:w(x.delivered),icon:"check",tone:"ok"},{label:"Failed",value:w(x.failed),icon:"alert",tone:x.failed>0?"bad":void 0},{label:"Skipped",value:w(x.skipped),icon:"filter",tone:"idle"},{label:"People reached",value:w(x.users),icon:"people",tone:"note"},{label:"History kept",value:`${f} days`,small:!0,icon:"clock"}]}):null,e.jsxs("div",{className:"filters",children:[e.jsx(q,{label:"Window",children:e.jsx(Ye,{value:t.from?-1:s,options:Ri.map(k=>({value:k.value,label:k.label})),onChange:k=>{n(k),p({from:"",to:""})}})}),e.jsx(q,{label:"Person",children:e.jsxs("select",{value:t.user,onChange:k=>p({user:k.target.value}),children:[e.jsx("option",{value:"",children:"Anyone"}),((u==null?void 0:u.users)??[]).map(k=>e.jsx("option",{value:k.id,children:k.username||k.id},k.id))]})}),e.jsx(q,{label:"Type",children:e.jsxs("select",{value:t.kind,onChange:k=>p({kind:k.target.value}),children:[e.jsx("option",{value:"",children:"Any type"}),as((y=u==null?void 0:u.facets)==null?void 0:y.kinds,Se)]})}),e.jsx(q,{label:"Channel",children:e.jsxs("select",{value:t.channel,onChange:k=>p({channel:k.target.value}),children:[e.jsx("option",{value:"",children:"Any channel"}),as((v=u==null?void 0:u.facets)==null?void 0:v.channels,k=>os[k]??Se(k))]})}),e.jsx(q,{label:"Status",children:e.jsxs("select",{value:t.status,onChange:k=>p({status:k.target.value}),children:[e.jsx("option",{value:"",children:"Any status"}),as((b=u==null?void 0:u.facets)==null?void 0:b.statuses,Se)]})}),e.jsx(q,{label:"Source",children:e.jsxs("select",{value:t.source,onChange:k=>p({source:k.target.value}),children:[e.jsx("option",{value:"",children:"Any service"}),as((A=u==null?void 0:u.facets)==null?void 0:A.sources,Se)]})}),e.jsx(q,{label:"From",children:e.jsx("input",{type:"date",value:t.from,onChange:k=>p({from:k.target.value})})}),e.jsx(q,{label:"To",children:e.jsx("input",{type:"date",value:t.to,onChange:k=>p({to:k.target.value})})}),e.jsx(q,{label:"Search",grow:!0,children:e.jsx("input",{type:"search",value:t.q,placeholder:"Title, message, error or person",onChange:k=>p({q:k.target.value})})}),e.jsx("div",{className:"filter-actions",children:d?e.jsx($,{variant:"quiet",size:"sm",onClick:()=>{r(un),l(0),h(null)},children:"Clear"}):null})]}),o.loading&&!u?e.jsx(V,{}):null,u&&u.days.length>1?e.jsx(C,{title:"Notifications per day",intro:"Failures and deliberate skips are counted beside the deliveries, because a quiet week and a week nothing was allowed to send look identical otherwise.",icon:"chart",tone:"info",children:e.jsx(hs,{data:u.days,labelOf:k=>k.day,valueOf:k=>k.sent+k.delivered+k.failed+k.skipped,toneOf:k=>k.failed>0?"bad":void 0,title:k=>`${k.day}: ${k.sent+k.delivered} sent, ${k.failed} failed, ${k.skipped} skipped`})}):null,u?e.jsx(C,{title:"History",intro:"Newest first. A row says who, what and whether it worked on its own; open one for the whole message and the delivery response.",icon:"send",tone:"ok",actions:e.jsx("span",{className:"filter-summary",children:u.total===0?"nothing matches":`${w(j)}${w(j+m-1)} of ${w(u.total)}`}),footer:u.total>ze?e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",disabled:a===0,onClick:()=>l(a-1),children:"Newer"}),e.jsx($,{size:"sm",disabled:(a+1)*ze>=u.total,onClick:()=>l(a+1),children:"Older"})]}):void 0,children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nowrap",children:"When"}),e.jsx("th",{children:"Recipient"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Title"}),e.jsx("th",{children:"Channel"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Status"}),e.jsx("th",{"aria-label":"Details"})]})}),e.jsx("tbody",{children:u.entries.length===0?e.jsx(Y,{columns:8,children:"No notifications match these filters."}):u.entries.map(k=>e.jsxs(g.Fragment,{children:[e.jsx(Ii,{entry:k,open:i===k.id,onToggle:()=>h(i===k.id?null:k.id)}),i===k.id?e.jsx(Li,{entry:k}):null]},k.id))})]})})}):null]})}function Ii({entry:s,open:n,onToggle:t}){return e.jsxs("tr",{"data-selected":n||void 0,children:[e.jsx("td",{className:"nowrap muted",children:F(s.occurredAt)}),e.jsx("td",{children:s.userId?e.jsx(Z,{className:"table-row-link",to:`/admin/accounts/${encodeURIComponent(s.userId)}`,children:s.username||s.userId}):s.target?e.jsx("span",{className:"muted",children:s.target}):e.jsx("span",{className:"quiet",children:"Everyone"})}),e.jsx("td",{className:"mono",children:s.kind||"—"}),e.jsx("td",{children:s.title||e.jsx("span",{className:"quiet",children:"—"})}),e.jsx("td",{className:"nowrap",children:e.jsx(N,{tone:Ai[s.channel],children:os[s.channel]??s.channel})}),e.jsx("td",{className:"muted",children:Se(s.source)}),e.jsx("td",{className:"nowrap",children:e.jsx(N,{tone:Dn[s.status]??"idle",children:s.status})}),e.jsx("td",{className:"nowrap",children:e.jsx($,{size:"sm",variant:"quiet",onClick:t,icon:n?"close":"list",children:n?"Close":"Details"})})]})}function Li({entry:s}){const n=Object.entries(s.metadata??{}).filter(([,t])=>t!=null&&String(t)!=="");return e.jsx("tr",{className:"detail-row",children:e.jsx("td",{colSpan:8,children:e.jsxs("section",{className:"logdrawer","aria-label":`Notification ${s.id}`,children:[e.jsxs("header",{className:"logdrawer-head",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"logdrawer-place",children:[e.jsx("span",{children:os[s.channel]??s.channel}),e.jsx("span",{className:"logrow-sep","aria-hidden":"true",children:""}),Se(s.source)]}),e.jsx("b",{children:s.title||Se(s.kind)}),s.detail?e.jsx("p",{className:"logdrawer-error",children:s.detail}):null]}),e.jsx("div",{className:"logdrawer-actions",children:e.jsx(N,{tone:Dn[s.status]??"idle",children:s.status})})]}),e.jsxs("div",{className:"logdrawer-grid",children:[e.jsxs("div",{className:"logdrawer-section",children:[e.jsx("h4",{children:"Delivery"}),e.jsxs("dl",{children:[e.jsx("dt",{children:"Sent"}),e.jsx("dd",{children:F(s.occurredAt)}),s.eventAt?e.jsxs(e.Fragment,{children:[e.jsx("dt",{children:"Event"}),e.jsx("dd",{children:F(s.eventAt)})]}):null,e.jsx("dt",{children:"Channel"}),e.jsx("dd",{children:os[s.channel]??s.channel}),e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:s.kind||"—"}),e.jsx("dt",{children:"Service"}),e.jsx("dd",{children:Se(s.source)}),e.jsx("dt",{children:"Took"}),e.jsxs("dd",{children:[s.durationMs,"ms"]})]})]}),e.jsxs("div",{className:"logdrawer-section",children:[e.jsx("h4",{children:"Recipient"}),e.jsxs("dl",{children:[e.jsx("dt",{children:"Person"}),e.jsx("dd",{children:s.userId?s.username||s.userId:"the whole household"}),s.target?e.jsxs(e.Fragment,{children:[e.jsx("dt",{children:"Destination"}),e.jsx("dd",{children:s.target})]}):null,s.itemId?e.jsxs(e.Fragment,{children:[e.jsx("dt",{children:"Title id"}),e.jsx("dd",{children:s.itemId})]}):null,s.sourceKey?e.jsxs(e.Fragment,{children:[e.jsx("dt",{children:"Source key"}),e.jsx("dd",{children:s.sourceKey})]}):null]})]}),n.length?e.jsxs("div",{className:"logdrawer-section",children:[e.jsx("h4",{children:"Context"}),e.jsx("dl",{children:n.map(([t,r])=>e.jsxs(g.Fragment,{children:[e.jsx("dt",{children:Se(t)}),e.jsx("dd",{children:String(r)})]},t))})]}):null]}),s.body?e.jsxs("div",{className:"logdrawer-raw",children:[e.jsx("h4",{children:"Message"}),e.jsx("p",{className:"notification-body",children:s.body})]}):null]})})})}const qi=s=>s==="detected"?"ok":s==="failed"?"bad":s==="no_match"?"warn":"info",Di=s=>s==="no_match"?"no match":s,mn=s=>({"live-playback":"Live playback","tracearr-next":"Next episode","tracearr-binge-prefetch":"Binge look-ahead","multi-user-demand":"Multiple viewers"}[s]??s)||"Unknown",pn=(s,n)=>s>0&&n>0?`S${String(s).padStart(2,"0")}E${String(n).padStart(2,"0")}`:"Episode";function Fi(){var m,j,y,v;const s=J("/admin/api/credits?limit=150",{pollMs:15e3}),{wrap:n}=ie(),{busy:t,run:r}=ne(),[a,l]=g.useState(),[i,h]=g.useState(!1);g.useEffect(()=>{!i&&s.data&&l(s.data.settings)},[s.data,i]);const c=b=>{l(A=>A&&{...A,...b}),h(!0)},o=()=>{a&&r("save",async()=>{const b=await n(()=>D.put("/admin/api/credits",a),"Credits scanning settings saved.");b&&(s.set(b),l(b.settings),h(!1))})},u=((m=s.data)==null?void 0:m.history)??[],p=((j=s.data)==null?void 0:j.pending)??[],d=u.filter(b=>b.outcome==="detected").length,x=u.filter(b=>b.outcome==="no_match").length,f=u.filter(b=>b.outcome==="failed").length;return e.jsxs(e.Fragment,{children:[e.jsx(U,{title:"Credits detection",intro:"Control how far ahead Memby scans and see why each episode was selected, what the detector found, and when it may be tried again."}),e.jsx(_,{message:s.error}),s.loading||!a?e.jsx(V,{}):e.jsxs(e.Fragment,{children:[(y=s.data)!=null&&y.enabled?null:e.jsx(pe,{tone:"warn",children:"Credits detection is disabled in the gateway environment. These settings will be retained for the next time it is enabled."}),e.jsx(ae,{tiles:[{label:"Waiting candidates",value:w((v=s.data)==null?void 0:v.queueDepth),icon:"clock",tone:p.length?"info":void 0},{label:"Detected in this history",value:w(d),icon:"check",tone:"ok"},{label:"No match",value:w(x),icon:"search",tone:x?"warn":void 0},{label:"Failed",value:w(f),icon:"alert",tone:f?"bad":void 0}]}),e.jsxs(xe,{cols:"wide",children:[e.jsx(C,{title:"Candidate controls",intro:"The worker remains single-file and scans one episode at a time. These values control what is allowed to wait and how far prediction looks ahead.",icon:"sliders",tone:"note",footer:e.jsx($,{variant:"primary",icon:"check",busy:t==="save",disabled:!i,onClick:o,children:"Save settings"}),children:e.jsxs("div",{className:"fields",children:[e.jsx(q,{label:"Candidate limit",hint:"Maximum episodes waiting in the priority queue. Stronger candidates displace weaker ones when it is full.",children:e.jsx("input",{type:"number",min:1,max:100,value:a.candidateLimit,onChange:b=>c({candidateLimit:Number(b.target.value)})})}),e.jsx(q,{label:"Ordinary look-ahead",hint:"Episodes prepared ahead of a normally paced viewer.",children:e.jsx("input",{type:"number",min:1,max:10,value:a.prefetchEpisodes,onChange:b=>c({prefetchEpisodes:Number(b.target.value)})})}),e.jsx(q,{label:"Maximum look-ahead",hint:"Upper bound for fast binge viewing; must not be below the ordinary look-ahead.",children:e.jsx("input",{type:"number",min:a.prefetchEpisodes,max:20,value:a.maxPrefetch,onChange:b=>c({maxPrefetch:Number(b.target.value)})})}),e.jsx(q,{label:"Retry delay (hours)",hint:"After any speculative attempt, keep that episode out of refreshes for this long. Set 0 to allow every refresh.",children:e.jsx("input",{type:"number",min:0,max:720,value:a.retryHours,onChange:b=>c({retryHours:Number(b.target.value)})})})]})}),e.jsxs(C,{title:"How selection works",icon:"sparkle",tone:"data",children:[e.jsx("p",{className:"muted",children:"Recent viewing predicts the next few episodes. Priority favours a programme playing now, then the next episode, fast viewing, and episodes several people are approaching."}),e.jsx("p",{className:"muted",children:"A completed speculative attempt enters the retry delay even when no marker was found. Live playback can still raise an immediate candidate because somebody is waiting for it."})]})]}),e.jsx(C,{title:"Waiting candidates",intro:"The exact worker order after marker checks and retry cooldowns. A refresh may replace this list as viewing changes.",icon:"list",tone:"info",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Episode"}),e.jsx("th",{children:"Reason"}),e.jsx("th",{className:"num",children:"Priority"}),e.jsx("th",{className:"num",children:"Viewers"}),e.jsx("th",{children:"Demand seen"}),e.jsx("th",{children:"Item ID"})]})}),e.jsx("tbody",{children:p.length===0?e.jsx(Y,{columns:6,children:"No episodes are waiting to be scanned."}):p.map(b=>e.jsxs("tr",{children:[e.jsx("td",{children:pn(b.season,b.episode)}),e.jsx("td",{children:e.jsx(N,{tone:"info",children:mn(b.reason)})}),e.jsx("td",{className:"num",children:w(b.priority)}),e.jsx("td",{className:"num",children:w(b.userCount)}),e.jsx("td",{className:"nowrap muted",title:F(b.lastViewed),children:be(b.lastViewed)}),e.jsx("td",{className:"mono muted",children:b.itemId})]},b.itemId))})]})})}),e.jsx(C,{title:"Scan history",intro:"Completed worker attempts, newest first. Repeated item IDs make an ineffective retry delay visible immediately.",icon:"history",tone:"note",children:e.jsx(K,{children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Finished"}),e.jsx("th",{children:"Programme"}),e.jsx("th",{children:"Selected because"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Marker"}),e.jsx("th",{children:"Evidence"}),e.jsx("th",{className:"num",children:"Took"})]})}),e.jsx("tbody",{children:u.length===0?e.jsx(Y,{columns:7,children:"No credits scans have completed yet."}):u.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:F(b.finishedAt),children:be(b.finishedAt)}),e.jsxs("td",{children:[e.jsx("b",{children:b.seriesName||b.itemName||b.itemId}),e.jsxs("span",{className:"table-sub",children:[pn(b.season,b.episode),b.itemName&&b.seriesName?` · ${b.itemName}`:""]})]}),e.jsxs("td",{children:[e.jsx(N,{tone:"info",children:mn(b.reason)}),e.jsxs("span",{className:"table-sub",children:["priority ",b.priority]})]}),e.jsxs("td",{children:[e.jsx(N,{tone:qi(b.outcome),children:Di(b.outcome)}),b.error?e.jsx("span",{className:"table-sub",children:b.error}):null]}),e.jsx("td",{className:"nowrap",children:b.markerMs>0?ye(b.markerMs):"—"}),e.jsxs("td",{className:"muted",children:[b.method||"visual",b.confidence>0?` · ${is(b.confidence)}`:"",b.frames>0?` · ${b.frames} frames`:""]}),e.jsx("td",{className:"num muted",children:ye(b.durationMs)})]},b.id))})]})})})]})]})}function Oi(){return e.jsx(U,{title:"No such page",intro:"That address is not part of the console. Use the search in the bar above, or the sections on the left."})}function Pi(){return e.jsx(_n,{children:e.jsx(et,{children:e.jsx(it,{children:e.jsx(ht,{children:e.jsx(Un,{children:e.jsxs(W,{path:"/admin",element:e.jsx(ct,{}),children:[e.jsx(W,{index:!0,element:e.jsx(mt,{})}),e.jsx(W,{path:"activity",element:e.jsx(xt,{})}),e.jsx(W,{path:"accounts",element:e.jsx(jt,{})}),e.jsx(W,{path:"accounts/:userId",element:e.jsx(gt,{})}),e.jsx(W,{path:"accounts/:userId/settings",element:e.jsx(Nt,{})}),e.jsx(W,{path:"clients",element:e.jsx(Mt,{})}),e.jsx(W,{path:"logins",element:e.jsx($t,{})}),e.jsx(W,{path:"devices/:deviceId",element:e.jsx(Et,{})}),e.jsx(W,{path:"library",element:e.jsx(It,{})}),e.jsx(W,{path:"requests",element:e.jsx(Lt,{})}),e.jsx(W,{path:"recommendations",element:e.jsx(qt,{})}),e.jsx(W,{path:"inspector",element:e.jsx(Ot,{})}),e.jsx(W,{path:"hero",element:e.jsx(Wt,{})}),e.jsx(W,{path:"metadata-hero",element:e.jsx(Vt,{})}),e.jsx(W,{path:"features",element:e.jsx(Ht,{})}),e.jsx(W,{path:"playback",element:e.jsx(zt,{})}),e.jsx(W,{path:"subtitles",element:e.jsx(Kt,{})}),e.jsx(W,{path:"credits",element:e.jsx(Fi,{})}),e.jsx(W,{path:"updates",element:e.jsx(Gt,{})}),e.jsx(W,{path:"tasks",element:e.jsx(sa,{})}),e.jsx(W,{path:"tasks/:taskId",element:e.jsx(ra,{})}),e.jsx(W,{path:"integrations",element:e.jsx(ua,{})}),e.jsx(W,{path:"integrations/webhooks",element:e.jsx(ga,{})}),e.jsx(W,{path:"integrations/:integrationId",element:e.jsx(Na,{})}),e.jsx(W,{path:"maintenance",element:e.jsx(Ca,{})}),e.jsx(W,{path:"runtime",element:e.jsx($a,{})}),e.jsx(W,{path:"settings",element:e.jsx(Ea,{})}),e.jsx(W,{path:"imports",element:e.jsx(Da,{})}),e.jsx(W,{path:"logs",element:e.jsx(vi,{})}),e.jsx(W,{path:"journeys",element:e.jsx(bi,{})}),e.jsx(W,{path:"journeys/:userId",element:e.jsx(Ni,{})}),e.jsx(W,{path:"views",element:e.jsx(Ci,{})}),e.jsx(W,{path:"engagement",element:e.jsx(Si,{})}),e.jsx(W,{path:"searches",element:e.jsx(Mi,{})}),e.jsx(W,{path:"media-reports",element:e.jsx(Ti,{})}),e.jsx(W,{path:"notifications",element:e.jsx(Ei,{})}),e.jsx(W,{path:"overview",element:e.jsx(As,{to:"/admin",replace:!0})}),e.jsx(W,{path:"ratings",element:e.jsx(As,{to:"/admin/integrations/mdblist",replace:!0})}),e.jsx(W,{path:"*",element:e.jsx(Oi,{})})]})})})})})})}const Fn=document.getElementById("root");if(!Fn)throw new Error("the console has no root element to render into");vn(Fn).render(e.jsx(g.StrictMode,{children:e.jsx(Pi,{})}));