Files
memby/admin-ui/dist/assets/index-Ol_zP3CI.js
T
2026-08-14 13:32:14 +12:00

12 lines
156 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
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 p,a as ms,u as Re,L as Y,b as Ze,O as ps,N as xs,c as ke,B as js,R as vs,d as V,e as bs}from"./router-BwjLFE7Y.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))t(o);new MutationObserver(o=>{for(const c of o)if(c.type==="childList")for(const i of c.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&t(i)}).observe(document,{childList:!0,subtree:!0});function l(o){const c={};return o.integrity&&(c.integrity=o.integrity),o.referrerPolicy&&(c.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?c.credentials="include":o.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function t(o){if(o.ep)return;o.ep=!0;const c=l(o);fetch(o.href,c)}})();var Je={exports:{}},Ne={};/**
* @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 gs=p,fs=Symbol.for("react.element"),ys=Symbol.for("react.fragment"),ws=Object.prototype.hasOwnProperty,ks=gs.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Ns={key:!0,ref:!0,__self:!0,__source:!0};function Ye(s,n,l){var t,o={},c=null,i=null;l!==void 0&&(c=""+l),n.key!==void 0&&(c=""+n.key),n.ref!==void 0&&(i=n.ref);for(t in n)ws.call(n,t)&&!Ns.hasOwnProperty(t)&&(o[t]=n[t]);if(s&&s.defaultProps)for(t in n=s.defaultProps,n)o[t]===void 0&&(o[t]=n[t]);return{$$typeof:fs,type:s,key:c,ref:i,props:o,_owner:ks.current}}Ne.Fragment=ys;Ne.jsx=Ye;Ne.jsxs=Ye;Je.exports=Ne;var e=Je.exports,Xe,Ae=ms;Xe=Ae.createRoot,Ae.hydrateRoot;const Qe={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",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 ee({name:s,className:n}){const l=Qe[s];return l?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:l})}):null}function Se({name:s,tone:n}){return Qe[s]?e.jsx("span",{className:"glyph","data-tone":n,children:e.jsx(ee,{name:s})}):null}const Ee=[{id:"overview",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:"people",label:"People",items:[{id:"accounts",path:"/admin/accounts",label:"Users",title:"Memby users",intro:"Who uses Memby, and the devices they are signed in on.",icon:"people"},{id:"account",path:"/admin/accounts/:userId",label:"User",title:"User",intro:"Devices, recommendation setup and synced settings for one 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.",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.",hidden:!0}]},{id:"content",label:"Content",items:[{id:"library",path:"/admin/library",label:"Library",title:"Library",intro:"Import and inspect the catalogue Memby ranks.",icon:"library"},{id:"ratings",path:"/admin/ratings",label:"Movie ratings",title:"Movie ratings",intro:"Optional MDBList scores on films and shows.",icon:"star"},{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:"personalisation",label:"Personalisation",items:[{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:"Experience",items:[{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:"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:"updates",path:"/admin/updates",label:"App updates",title:"App updates",intro:"Publish an optional or a required client update.",icon:"upload"}]},{id:"operations",label:"Operations",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:"integrations",path:"/admin/integrations",label:"Integrations",title:"Integrations",intro:"Send administrative events to Discord and, in time, elsewhere.",icon:"plug"},{id:"maintenance",path:"/admin/maintenance",label:"Maintenance",title:"Maintenance",intro:"Take Memby offline for every television.",icon:"wrench"},{id:"imports",path:"/admin/imports",label:"Imports",title:"Imports",intro:"Catalogue synchronisation history.",icon:"database"},{id:"logs",path:"/admin/logs",label:"Server logs",title:"Server logs",intro:"Structured gateway events as they happen.",icon:"list"}]},{id:"reporting",label:"Reporting",items:[{id:"media-reports",path:"/admin/media-reports",label:"Media reports",title:"Media reports",intro:"Problems viewers reported with a film or episode.",icon:"inbox"},{id:"views",path:"/admin/views",label:"Views",title:"App views",intro:"Home-screen visits, viewers and the times Memby is used.",icon:"overview"},{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"},{id:"searches",path:"/admin/searches",label:"Searches",title:"Searches",intro:"What the household has been looking for, and what it searched just now.",icon:"search"}]}];Ee.flatMap(s=>s.items);const Ss=Ee.flatMap(s=>s.items.filter(n=>!n.hidden).map(n=>({...n,group:s.label??""})));class Te extends Error{constructor(n,l){super(n),this.status=l,this.name="ApiError"}}const Ms=5*60*1e3;let es=Date.now();for(const s of["pointerdown","pointermove","keydown","wheel","scroll"])window.addEventListener(s,()=>{es=Date.now()},{passive:!0});const Cs=()=>Date.now()-es<Ms,Le="memby-admin-relogin";function Rs(){try{if(Date.now()-Number(sessionStorage.getItem(Le)??0)<3e4)return!1;sessionStorage.setItem(Le,String(Date.now()))}catch{}return window.location.reload(),!0}async function ye(s,n={}){const l=await fetch(s,{...n,headers:{"Content-Type":"application/json",...Cs()?{"X-Memby-Admin-Active":"1"}:{},...n.headers??{}}});if(l.status===401)throw new Te(Rs()?"Your sign-in has expired. Signing in again…":"Your sign-in has expired. Reload this page to sign in again.",401);if(!l.ok){const t=await l.json().catch(()=>({}));throw new Te(t.error??`Request failed (${l.status})`,l.status)}if(l.status!==204)return await l.json()}function ge(s){const n=new URLSearchParams;for(const[t,o]of Object.entries(s))o==null||o===""||o===!1||n.set(t,String(o));const l=n.toString();return l?`?${l}`:""}const L={get:s=>ye(s),post:(s,n)=>ye(s,{method:"POST",body:n===void 0?void 0:JSON.stringify(n)}),put:(s,n)=>ye(s,{method:"PUT",body:n===void 0?void 0:JSON.stringify(n)}),del:s=>ye(s,{method:"DELETE"})},Es=3e4,ss=p.createContext(null);function $s({children:s}){var b;const[n,l]=p.useState(),[t,o]=p.useState(!0),[c,i]=p.useState(""),[r,d]=p.useState(""),[a,v]=p.useState(!0),x=p.useRef(0),h=p.useCallback(async()=>{const g=++x.current;try{const m=await L.get("/admin/api/status");if(g!==x.current)return;l(m),o(!0),d("")}catch(m){if(g!==x.current)return;o(!1),d(m instanceof Error?m.message:String(m))}finally{g===x.current&&(i(new Date().toISOString()),v(!1))}},[]),u=p.useCallback(async g=>{var m;await L.post("/admin/api/maintenance",{enabled:g,message:((m=n==null?void 0:n.maintenance)==null?void 0:m.message)??""}),await h()},[h,(b=n==null?void 0:n.maintenance)==null?void 0:b.message]);p.useEffect(()=>{h();let g;const m=()=>{window.clearInterval(g),g=document.hidden?void 0:window.setInterval(()=>void h(),Es)},y=()=>{m(),document.hidden||h()};return m(),document.addEventListener("visibilitychange",y),()=>{window.clearInterval(g),document.removeEventListener("visibilitychange",y)}},[h]);const f=p.useMemo(()=>({status:n,version:(n==null?void 0:n.serverVersion)??"",online:t,checkedAt:c,error:r,loading:a,reload:h,setMaintenance:u}),[n,t,c,r,a,h,u]);return e.jsx(ss.Provider,{value:f,children:s})}function se(){const s=p.useContext(ss);if(!s)throw new Error("useGateway used outside GatewayProvider");return s}function Is(s,n){const l=s.label.toLowerCase(),t=s.group.toLowerCase();return l.startsWith(n)?4:l.includes(n)?3:t.includes(n)?2:`${s.title} ${s.intro}`.toLowerCase().includes(n)?1:0}function As(){const s=Re(),{status:n}=se(),[l,t]=p.useState(!1),[o,c]=p.useState(""),[i,r]=p.useState(0),d=p.useRef(null),a=p.useRef(null),v=p.useMemo(()=>{const h=o.trim().toLowerCase();return[...Ss,...((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,b)=>({item:f,rank:h?Is(f,h):1,index:b})).filter(f=>f.rank>0).sort((f,b)=>b.rank-f.rank||f.index-b.index).map(({item:f,rank:b})=>({item:f,rank:b}))},[o]);p.useEffect(()=>r(0),[o]),p.useEffect(()=>{const h=u=>{var f;(f=d.current)!=null&&f.contains(u.target)||t(!1)};return document.addEventListener("pointerdown",h),()=>document.removeEventListener("pointerdown",h)},[]),p.useEffect(()=>{const h=u=>{var b,g;if(u.key!=="S"||!u.shiftKey||u.ctrlKey||u.metaKey||u.altKey)return;const f=document.activeElement;f&&(f.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(f.tagName))||(u.preventDefault(),(b=a.current)==null||b.focus(),(g=a.current)==null||g.select())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[]);const x=h=>{var u;t(!1),c(""),(u=a.current)==null||u.blur(),s(h)};return e.jsxs("div",{className:"omni",ref:d,"data-open":l||void 0,children:[e.jsxs("div",{className:"omni-input",children:[e.jsx(ee,{name:"search"}),e.jsx("input",{ref:a,type:"search",value:o,placeholder:"Search pages, users and devices…","aria-label":"Search pages, users and devices","aria-expanded":l,onFocus:()=>t(!0),onChange:h=>{c(h.target.value),t(!0)},onKeyDown:h=>{var u;if(h.key==="Escape")c(""),t(!1),(u=a.current)==null||u.blur();else if(h.key==="ArrowDown")h.preventDefault(),r(f=>Math.min(f+1,v.length-1));else if(h.key==="ArrowUp")h.preventDefault(),r(f=>Math.max(f-1,0));else if(h.key==="Enter"){const f=v[i];if(!f)return;h.preventDefault(),x(f.item.path)}}}),e.jsx("span",{className:"omni-key",children:"⇧S"})]}),l?e.jsx("div",{className:"omni-panel",role:"listbox",children:v.length===0?e.jsx("p",{className:"empty",children:"No pages, users or devices match that search."}):v.map((h,u)=>e.jsxs("a",{className:u===i?"omni-item on":"omni-item",href:h.item.path,role:"option","aria-selected":u===i,onPointerEnter:()=>r(u),onClick:f=>{f.preventDefault(),x(h.item.path)},children:[h.item.icon?e.jsx(ee,{name:h.item.icon}):null,e.jsxs("span",{children:[e.jsx("b",{children:h.item.label}),e.jsx("small",{children:h.item.intro})]}),e.jsx("span",{className:"omni-group",children:h.item.group})]},h.item.id))}):null]})}const w=s=>(s??0).toLocaleString(),P=s=>s?new Date(s).toLocaleString():"—",Ts=s=>s?new Date(s).toLocaleTimeString():"—";function ve(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 l=Math.floor(n/60);return l<60?`${l}m ${n%60}s`:`${Math.floor(l/60)}h ${l%60}m`}function Ls(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 l=Math.round(n/60);return l<48?l===1?"hourly":`every ${l} hours`:`every ${Math.round(l/24)} days`}function je(s){const n=["B","KB","MB","GB"];let l=Number(s??0),t=0;for(;l>=1024&&t<n.length-1;)l/=1024,t+=1;return`${t===0?l:l.toFixed(1)} ${n[t]}`}const ns=s=>String(s??"?").trim().split(/\s+/).slice(0,2).map(n=>n[0]??"").join("").toUpperCase(),Ce=s=>`${Math.round((s??0)*100)}%`;function ue(s){if(!s)return"—";const n=Date.now()-new Date(s).getTime();if(n<0)return"just now";const l=Math.floor(n/1e3);if(l<45)return"just now";const t=Math.floor(l/60);if(t<60)return`${t} min ago`;const o=Math.floor(t/60);if(o<24)return`${o}h ago`;const c=Math.floor(o/24);return c<30?`${c}d ago`:new Date(s).toLocaleDateString()}const ts=15*60*1e3,Ds=3*60*60*1e3,be=s=>!!s&&Date.now()-new Date(s).getTime()<ts;function $e(s){const n=s?new Date(s).getTime():0;if(!n)return{tone:"bad",label:"never seen"};const l=Date.now()-n;return l<ts?{tone:"ok",label:"active now"}:l<Ds?{tone:"warn",label:"seen recently"}:{tone:"bad",label:"not seen lately"}}const is=p.createContext(null),De=50,qs=3e4;function Ps({children:s}){const[n,l]=p.useState([]),[t,o]=p.useState(0),[c,i]=p.useState([]),[r,d]=p.useState(!1),[a,v]=p.useState(""),x=p.useRef(0),h=p.useCallback(async()=>{var m;try{const y=await L.get(`/admin/api/notifications?limit=${De}`);l(y.events),o(y.unread),i(y.types),x.current=Math.max(x.current,((m=y.events[0])==null?void 0:m.id)??0),v("")}catch(y){v(y instanceof Error?y.message:String(y))}},[]),u=p.useCallback(m=>{x.current=Math.max(x.current,m.id),l(y=>y.some(j=>j.id===m.id)?y:[m,...y].sort((j,R)=>R.id-j.id).slice(0,De)),m.readAt||o(y=>y+1),i(y=>y.some(j=>j.type===m.type)?y.map(j=>j.type===m.type?{...j,count:j.count+1}:j):[...y,{type:m.type,count:1}])},[]);p.useEffect(()=>{h()},[h]),p.useEffect(()=>{let m=null,y,j=!1;return(()=>{j||(m=new EventSource(`/admin/api/notifications/stream?after=${x.current}`),m.addEventListener("open",()=>{d(!0),window.clearInterval(y),y=void 0}),m.addEventListener("admin",k=>{try{u(JSON.parse(k.data))}catch{}}),m.addEventListener("error",()=>{d(!1),y===void 0&&(y=window.setInterval(()=>void h(),qs))}))})(),()=>{j=!0,m==null||m.close(),window.clearInterval(y)}},[u,h]);const f=p.useCallback(async m=>{const y=m.filter(j=>j>0);if(y.length!==0){l(j=>j.map(R=>y.includes(R.id)&&!R.readAt?{...R,readAt:new Date().toISOString()}:R));try{const j=await L.post("/admin/api/notifications/read",{ids:y});o(j.unread)}catch{h()}}},[h]),b=p.useCallback(async()=>{o(0),l(m=>m.map(y=>y.readAt?y:{...y,readAt:new Date().toISOString()}));try{const m=await L.post("/admin/api/notifications/read",{all:!0});o(m.unread)}catch{h()}},[h]),g=p.useMemo(()=>({events:n,unread:t,types:c,connected:r,error:a,markRead:f,markAllRead:b,reload:h}),[n,t,c,r,a,f,b,h]);return e.jsx(is.Provider,{value:g,children:s})}function Ie(){const s=p.useContext(is);if(!s)throw new Error("useNotifications used outside NotificationProvider");return s}function as(s){return s.severity==="error"?"bad":s.severity==="warning"?"warn":"info"}function rs(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 qe(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 Pe=99;function Fs(){const{events:s,unread:n,connected:l,markRead:t,markAllRead:o}=Ie(),[c,i]=p.useState(!1),r=p.useRef(null);return p.useEffect(()=>{const d=v=>{var x;(x=r.current)!=null&&x.contains(v.target)||i(!1)},a=v=>{v.key==="Escape"&&i(!1)};return document.addEventListener("pointerdown",d),document.addEventListener("keydown",a),()=>{document.removeEventListener("pointerdown",d),document.removeEventListener("keydown",a)}},[]),p.useEffect(()=>{if(!c)return;const d=s.filter(a=>!a.readAt).map(a=>a.id);d.length>0&&t(d)},[c]),e.jsxs("div",{className:"bell",ref:r,"data-open":c||void 0,children:[e.jsxs("button",{type:"button",className:"bell-button","aria-label":n>0?`Activity, ${n} unread`:"Activity","aria-expanded":c,onClick:()=>i(d=>!d),children:[e.jsx(ee,{name:"bell"}),n>0?e.jsx("span",{className:"bell-badge",children:n>Pe?`${Pe}+`:n}):null]}),c?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:[l?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 o(),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(d=>{const a=e.jsxs(e.Fragment,{children:[e.jsx(Se,{name:rs(d.type),tone:as(d)}),e.jsxs("span",{className:"bell-body",children:[e.jsx("b",{children:d.title||d.type}),d.summary?e.jsx("p",{children:d.summary}):null,e.jsx("time",{dateTime:d.occurredAt,children:ue(d.occurredAt)})]})]});return d.link?e.jsx(Y,{className:"bell-item","data-unread":!d.readAt||void 0,to:d.link,onClick:()=>i(!1),children:a},d.id):e.jsx("div",{className:"bell-item","data-unread":!d.readAt||void 0,children:a},d.id)})}),e.jsx("div",{className:"bell-foot",children:e.jsx(Y,{to:"/admin/activity",onClick:()=>i(!1),children:"All activity"})})]}):null]})}function O({title:s,intro:n,actions:l,crumbs:t}){return e.jsxs("header",{className:"page-head",children:[t?e.jsx("nav",{className:"crumbs",children:t}):null,e.jsxs("div",{className:"page-head-row",children:[e.jsxs("div",{children:[e.jsx("h1",{children:s}),n?e.jsx("p",{children:n}):null]}),l?e.jsx("div",{className:"page-head-actions",children:l}):null]})]})}function C({title:s,intro:n,icon:l,tone:t,actions:o,footer:c,children:i}){return e.jsxs("section",{className:"card",children:[s?e.jsxs("div",{className:"card-head",children:[l?e.jsx(Se,{name:l,tone:t}):null,e.jsxs("div",{className:"card-head-text",children:[e.jsx("h2",{children:s}),n?e.jsx("p",{children:n}):null]}),o?e.jsx("div",{className:"card-head-actions",children:o}):null]}):null,i,c?e.jsx("div",{className:"card-foot",children:c}):null]})}function re({cols:s,children:n}){return e.jsx("div",{className:"grid","data-cols":s,children:n})}function ne({tiles:s}){return e.jsx("div",{className:"tiles",children:s.map(n=>e.jsxs("div",{className:"tile",children:[n.icon?e.jsx(Se,{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 J({children:s,tone:n}){return e.jsx("span",{className:"chip","data-tone":n,children:s})}function W({children:s}){return e.jsx("p",{className:"empty",children:s})}function Q({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 fe({children:s,tone:n}){return e.jsx("p",{className:"note","data-tone":n,children:s})}function E({children:s,onClick:n,variant:l,size:t,disabled:o,busy:c,icon:i,type:r="button",title:d}){return e.jsxs("button",{type:r,className:"","data-variant":l,"data-size":t,disabled:o||c,onClick:n,title:d,children:[c?e.jsx("span",{className:"spinner"}):i?e.jsx(ee,{name:i}):null,s]})}function D({label:s,hint:n,children:l,grow:t}){return e.jsxs("label",{className:t?"field grow":"field",children:[e.jsx("span",{children:s}),l,n?e.jsx("small",{children:n}):null]})}function H({label:s,hint:n,checked:l,onChange:t,disabled:o}){return e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:l,disabled:o,onChange:c=>t(c.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 we({value:s,options:n,onChange:l}){return e.jsx("div",{className:"segments",role:"group",children:n.map(t=>e.jsx("button",{type:"button","aria-pressed":t.value===s,onClick:()=>l(t.value),children:t.label},String(t.value)))})}function z({children:s}){return e.jsx("div",{className:"table-wrap",children:s})}function ls({data:s,labelOf:n,valueOf:l,toneOf:t,title:o}){if(s.length===0)return e.jsx(W,{children:"Nothing in this window."});const c=s.map(r=>l(r)),i=Math.max(1,...c);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"bars",children:s.map((r,d)=>{const a=l(r);return e.jsx("div",{className:"bar","data-tone":t==null?void 0:t(r),"data-empty":a===0||void 0,style:{height:`${Math.max(2,a/i*100)}%`},title:o?o(r):`${n(r,d)}: ${a}`},d)})}),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 Os({value:s,total:n,tone:l}){const t=n>0?Math.min(1,s/n):0;return e.jsx("div",{className:"meter","data-tone":l,children:e.jsx("div",{style:{width:`${t*100}%`}})})}function U({message:s,onDismiss:n}){return s?e.jsxs("div",{className:"banner",role:"alert",children:[e.jsx(ee,{name:"alert"}),e.jsx("span",{children:s}),n?e.jsx("button",{type:"button",onClick:n,"aria-label":"Dismiss",children:e.jsx(ee,{name:"close"})}):null]}):null}function B({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,l)=>e.jsx("span",{className:"skeleton"},l))}),Array.from({length:s},(n,l)=>e.jsxs("section",{className:"loading-card",children:[e.jsx("span",{className:"skeleton"}),e.jsx("span",{className:"skeleton"}),e.jsx("span",{className:"skeleton"})]},l))]})}function oe({title:s,body:n,confirmLabel:l="Confirm",destructive:t,busy:o,onConfirm:c,onCancel:i}){const r=p.useId(),d=p.useRef(null);return p.useEffect(()=>{var v;(v=d.current)==null||v.focus();const a=x=>{x.key==="Escape"&&i()};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[i]),e.jsx("div",{className:"scrim",onPointerDown:a=>a.target===a.currentTarget&&i(),children:e.jsxs("div",{className:"dialog",role:"dialog","aria-modal":"true","aria-labelledby":r,ref:d,tabIndex:-1,children:[e.jsx("h2",{id:r,children:s}),e.jsx("p",{children:n}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx(E,{onClick:i,variant:"quiet",children:"Cancel"}),e.jsx(E,{onClick:c,variant:t?"danger":"primary",busy:o,children:l})]})]})})}function Fe({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 os({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 Us({open:s,onNavigate:n}){const{unread:l}=Ie(),t=Ze(),[o,c]=p.useState(()=>{try{return JSON.parse(localStorage.getItem("memby-admin-nav")??"{}")}catch{return{}}}),i=r=>{c(d=>{const a={...d,[r]:!d[r]};try{localStorage.setItem("memby-admin-nav",JSON.stringify(a))}catch{}return a})};return e.jsx("nav",{className:"rail",id:"rail","data-open":s||void 0,"aria-label":"Console sections",children:Ee.map(r=>{const d=r.items.filter(x=>!x.hidden);if(d.length===0)return null;const v=d.some(x=>t.pathname===x.path)||!o[r.id];return e.jsxs("div",{className:"rail-group",children:[r.label?e.jsxs("button",{type:"button",className:"rail-head","aria-expanded":v,onClick:()=>i(r.id),children:[r.label,e.jsx(ee,{name:"caret",className:"ico caret"})]}):null,v?d.map(x=>e.jsx(xs,{to:x.path,end:x.path==="/admin",onClick:n,className:({isActive:h})=>h?"on":"","aria-current":void 0,children:({isActive:h})=>e.jsxs("span",{style:{display:"contents"},ref:u=>{const f=u==null?void 0:u.parentElement;f&&(h?f.setAttribute("aria-current","page"):f.removeAttribute("aria-current"))},children:[x.icon?e.jsx(ee,{name:x.icon}):null,x.label,x.badge==="notifications"&&l>0?e.jsx("span",{className:"rail-badge",children:l>99?"99+":l}):null]})},x.id)):null]},r.id)})})}function Vs(){var f;const{version:s,online:n,checkedAt:l,status:t,setMaintenance:o}=se(),[c,i]=p.useState(!1),[r,d]=p.useState(!1),[a,v]=p.useState(!1),x=Ze(),h=!!((f=t==null?void 0:t.maintenance)!=null&&f.enabled),u=async()=>{if(!(r||!t)){d(!0);try{await o(!h)}finally{d(!1)}}};return p.useEffect(()=>i(!1),[x.pathname]),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":c,"aria-controls":"rail",onClick:()=>i(b=>!b),children:e.jsx(ee,{name:"menu"})}),e.jsx("div",{className:"topbar-spacer"}),e.jsxs("div",{className:"topbar-tools",children:[e.jsx(As,{}),e.jsxs("span",{className:"topbar-version",children:["gateway ",s||"unknown"]}),e.jsxs("button",{type:"button",className:"topbar-status","data-tone":n&&!h?"ok":"bad","aria-pressed":h,disabled:!t||r,title:h?"Bring Memby back online":"Take Memby offline",onClick:()=>h?void u():v(!0),children:[e.jsx("span",{className:"dot"}),e.jsx("b",{children:h?"offline":n?"online":"not responding"}),e.jsx("span",{children:h?"click to bring back online":l?`updated ${Ts(l)}`:""})]}),e.jsx(Fs,{}),e.jsx("form",{method:"post",action:"/admin/logout",children:e.jsx("button",{type:"submit","data-variant":"quiet","data-size":"sm",title:"Sign out",children:e.jsx(ee,{name:"logout"})})})]})]}),e.jsx(Us,{open:c,onNavigate:()=>i(!1)}),e.jsx("main",{className:"page",id:"main",children:e.jsx(ps,{})}),a?e.jsx(oe,{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:r,onConfirm:()=>{v(!1),u()},onCancel:()=>v(!1)}):null]})}const cs=p.createContext(null),Bs=5e3;function _s({children:s}){const[n,l]=p.useState([]),t=p.useRef(1),o=p.useCallback(d=>{l(a=>a.filter(v=>v.id!==d))},[]),c=p.useCallback((d,a="ok")=>{const v=t.current++;l(x=>[...x,{id:v,message:d,tone:a}]),window.setTimeout(()=>o(v),Bs)},[o]),i=p.useCallback(async(d,a)=>{try{const v=await d();return a&&c(a,"ok"),v}catch(v){c(v instanceof Error?v.message:String(v),"bad");return}},[c]),r=p.useMemo(()=>({show:c,wrap:i}),[c,i]);return e.jsxs(cs.Provider,{value:r,children:[s,e.jsx("div",{className:"toasts",role:"status","aria-live":"polite",children:n.map(d=>e.jsxs("div",{className:"toast","data-tone":d.tone,children:[e.jsx(ee,{name:d.tone==="bad"?"alert":"check"}),e.jsx("span",{children:d.message}),e.jsx("button",{type:"button",onClick:()=>o(d.id),"aria-label":"Dismiss",children:e.jsx(ee,{name:"close"})})]},d.id))})]})}function X(){const s=p.useContext(cs);if(!s)throw new Error("useToast used outside ToastProvider");return s}function G(s,n={}){const{pollMs:l,enabled:t=!0}=n,[o,c]=p.useState(),[i,r]=p.useState(""),[d,a]=p.useState(t),[v,x]=p.useState(!1),h=p.useRef(0),u=p.useRef(!1),f=p.useCallback(async()=>{if(!t)return;const b=++h.current;u.current&&x(!0);try{const g=await L.get(s);if(b!==h.current)return;c(g),r(""),u.current=!0}catch(g){if(b!==h.current)return;r(g instanceof Error?g.message:String(g))}finally{b===h.current&&(a(!1),x(!1))}},[s,t]);return p.useEffect(()=>(u.current=!1,a(!0),f(),()=>{h.current+=1}),[f]),p.useEffect(()=>{if(!l||!t)return;let b;const g=()=>{window.clearInterval(b),b=document.hidden?void 0:window.setInterval(()=>void f(),l)},m=()=>{g(),document.hidden||f()};return g(),document.addEventListener("visibilitychange",m),()=>{window.clearInterval(b),document.removeEventListener("visibilitychange",m)}},[l,t,f]),{data:o,error:i,loading:d,refreshing:v,reload:f,set:c}}function Z(){const[s,n]=p.useState(null),l=p.useRef(!0);p.useEffect(()=>()=>{l.current=!1},[]);const t=p.useCallback(async(o,c)=>{n(o);try{return await c(),!0}finally{l.current&&n(null)}},[]);return{busy:s,run:t}}function Ws(){var g,m,y,j,R;const{status:s,error:n,loading:l}=se(),t=G("/admin/api/runtime",{pollMs:3e4}),o=G("/admin/api/views",{pollMs:6e4});if(l||!s)return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Overview",intro:"What the gateway is doing right now."}),e.jsx(U,{message:n}),e.jsx(B,{})]});const c=s.features??{features:[],revision:0,safeMode:!1},i=c.features??[],r=s.clients??[],d=r.filter(k=>be(k.lastSeen)).length,a=s.updatePolicy??{},v=!!a.minimumVersion&&a.minimumVersion===a.latestVersion,x=s.playbackPolicy,h=s.mdblist,u=s.forYou,f=(s.runs??[]).slice(0,5),b=t.data;return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Overview",intro:"What the gateway is doing right now."}),e.jsx(U,{message:n}),e.jsx(ne,{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 · ${d} active now`,value:w(r.length),icon:"tv",tone:"info"},{label:`visits today · ${((g=o.data)==null?void 0:g.lastWeek.visits)??0} this time last week`,value:w((m=o.data)==null?void 0:m.today.visits),icon:"overview",tone:"data"},{label:`viewers today · ${((y=o.data)==null?void 0:y.lastWeek.viewers)??0} this time last week`,value:w((j=o.data)==null?void 0:j.today.viewers),icon:"people",tone:"note"},{label:"optional features on",value:`${i.filter(k=>k.enabled).length} / ${i.length}`,icon:"sliders",tone:"ok"},{label:"last import",value:P(s.library.lastSynced),small:!0,icon:"clock"}]}),e.jsxs(re,{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(Fe,{rows:[{label:"Availability",value:(R=s.maintenance)!=null&&R.enabled?e.jsx(N,{tone:"bad",children:"offline for maintenance"}):e.jsx(N,{tone:"ok",children:"online"})},{label:"Feature control plane",value:c.safeMode?e.jsx(N,{tone:"warn",children:"safe mode · optional features off"}):e.jsxs(N,{tone:"ok",children:["revision r",w(c.revision)]})},{label:"App update prompt",value:a.enabled?e.jsxs(N,{tone:v?"warn":"ok",children:[v?"required · ":"optional · ",a.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:(x==null?void 0:x.prerollEnabled)===!1?e.jsx(N,{children:"off"}):e.jsxs(N,{tone:"ok",children:[((x==null?void 0:x.prerollDurationMs)??6500)/1e3,"s"]})}]})}),e.jsx(C,{title:"Services",intro:"The services this gateway leans on, and whether they answered.",icon:"wrench",tone:"note",children:e.jsx(Fe,{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:h!=null&&h.enabled?e.jsxs(N,{tone:"ok",children:[w(h.cachedTitles)," titles stored"]}):e.jsx(N,{children:h!=null&&h.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((u==null?void 0:u.candidates)??0)," ranked candidates"]})},{label:"Recommendation profiles",value:e.jsx("span",{className:"mono",children:w((u==null?void 0:u.profiles)??0)})}]})})]}),e.jsxs(re,{cols:"2",children:[e.jsx(C,{title:"Latest imports",intro:"The last few catalogue synchronisations.",icon:"sync",tone:"data",actions:e.jsx(Y,{to:"/admin/imports",children:"All imports"}),children:e.jsx(z,{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(Q,{columns:4,children:"No imports have run yet."}):f.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:P(k.startedAt)}),e.jsx("td",{children:k.kind}),e.jsx("td",{children:e.jsx(N,{tone:k.status==="success"?"ok":k.status==="running"?"warn":"bad",children:k.status})}),e.jsx("td",{className:"num",children:w(k.itemsUpserted)})]},k.id||k.startedAt))})]})})}),e.jsx(C,{title:"Process",intro:"The container the gateway is served from.",icon:"chip",tone:"info",children:b?e.jsxs(e.Fragment,{children:[e.jsx(os,{tiles:[{label:"goroutines",value:w(b.goroutines)},{label:"heap in use",value:je(b.heapInuse)},{label:"reserved",value:je(b.sys)},{label:"collections",value:w(b.numGc)}]}),e.jsxs("p",{className:"hint",children:["Next collection at ",je(b.nextGc)," · memory limit"," ",b.memoryLimit>0&&b.memoryLimit<Number.MAX_SAFE_INTEGER?`${je(b.memoryLimit)}${b.configuredLimit?" (GOMEMLIMIT)":""}`:"no limit set"," ","· ",b.gomaxprocs," processors available."]})]}):e.jsx("p",{className:"hint",children:"Reading process statistics…"})})]})]})}const zs=[{value:1,label:"Today"},{value:7,label:"7 days"},{value:30,label:"30 days"}];function Ks(){const{unread:s,connected:n,markAllRead:l,reload:t}=Ie(),[o,c]=p.useState(7),[i,r]=p.useState(""),[d,a]=p.useState(""),[v,x]=p.useState(!1),[h,u]=p.useState(0),f=100,b=p.useMemo(()=>`/admin/api/notifications${ge({days:o,type:i,severity:d,unread:v,limit:f,offset:h*f})}`,[o,i,d,v,h]),{data:g,error:m,loading:y,reload:j}=G(b),R=async()=>{await l(),await j()};return e.jsxs(e.Fragment,{children:[e.jsx(O,{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(E,{onClick:()=>void R(),icon:"check",children:"Mark all read"}):void 0}),e.jsx(U,{message:m}),e.jsx(ne,{tiles:[{label:"Events in window",value:w((g==null?void 0:g.total)??0),icon:"bell",tone:"info"},{label:"Unread",value:w(s),icon:"alert",tone:s>0?"warn":void 0},{label:"Kinds seen",value:w((g==null?void 0:g.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(D,{label:"Window",children:e.jsx(we,{value:o,options:zs.map(k=>({value:k.value,label:k.label})),onChange:k=>{c(k),u(0)}})}),e.jsx(D,{label:"Kind",children:e.jsxs("select",{value:i,onChange:k=>{r(k.target.value),u(0)},children:[e.jsx("option",{value:"",children:"Everything"}),((g==null?void 0:g.types)??[]).map(k=>e.jsxs("option",{value:k.type,children:[qe(k.type)," (",k.count,")"]},k.type))]})}),e.jsx(D,{label:"Severity",children:e.jsxs("select",{value:d,onChange:k=>{a(k.target.value),u(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(D,{label:"Read state",children:e.jsxs("select",{value:v?"unread":"",onChange:k=>{x(k.target.value==="unread"),u(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(E,{variant:"quiet",size:"sm",icon:"refresh",onClick:()=>{j(),t()},children:"Refresh"})})]}),y?e.jsx(B,{}):e.jsx(C,{title:"Events",icon:"bell",tone:"info",footer:((g==null?void 0:g.total)??0)>f?e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",disabled:h===0,onClick:()=>u(h-1),children:"Newer"}),e.jsx(E,{size:"sm",disabled:(h+1)*f>=((g==null?void 0:g.total)??0),onClick:()=>u(h+1),children:"Older"})]}):void 0,children:e.jsx(z,{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:((g==null?void 0:g.events.length)??0)===0?e.jsx(Q,{columns:6,children:"Nothing has happened in this window."}):g==null?void 0:g.events.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:P(k.occurredAt),children:ue(k.occurredAt)}),e.jsx("td",{className:"nowrap",children:e.jsxs("span",{className:"row tight",children:[e.jsx(Se,{name:rs(k.type),tone:as(k)}),qe(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(Y,{className:"table-row-link",to:k.link,children:"Open"}):null]})]},k.id))})]})})})]})}function Hs(){const{data:s,error:n,loading:l}=G("/admin/api/accounts",{pollMs:6e4}),t=(s==null?void 0:s.accounts)??[],o=t.flatMap(r=>r.devices??[]),c=t.filter(r=>{var d;return(d=r.recommendations)==null?void 0:d.completed}).length,i=t.filter(r=>{var d,a;return((d=r.recommendations)==null?void 0:d.prompted)&&!((a=r.recommendations)!=null&&a.completed)}).length;return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Memby users",intro:"Who uses Memby, and the devices they are signed in on."}),e.jsx(U,{message:n}),e.jsx(fe,{tone:"info",children:"This is the Memby user list, not the Emby user directory. A person appears here only after signing in to the Memby app. Removing access signs their Memby devices out and does not delete or change their Emby account."}),l?e.jsx(B,{}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"Memby users",value:w(t.length),icon:"people",tone:"note"},{label:"signed-in devices",value:w(o.length),icon:"tv",tone:"info"},{label:"active in the last quarter hour",value:w(o.filter(r=>be(r.lastSeen)).length),icon:"pulse",tone:"ok"},{label:"recommendation setups completed",value:w(c),icon:"check",tone:"ok"},{label:"setup prompts queued",value:w(i),icon:"sparkle",tone:"note"}]}),e.jsx("section",{className:"card flush",children:t.length===0?e.jsx(W,{children:"No one has signed in to Memby yet. Emby-only accounts are intentionally not listed here."}):t.map(r=>{var h,u;const d=r.devices??[],a=d.filter(f=>be(f.lastSeen)).length,v=(h=r.recommendations)!=null&&h.completed?{label:"personalised",tone:"ok"}:(u=r.recommendations)!=null&&u.prompted?{label:"prompt queued",tone:"warn"}:{label:"not invited",tone:void 0},x=$e(r.lastSeen);return e.jsxs(Y,{className:"list-row",to:`/admin/accounts/${encodeURIComponent(r.id)}`,children:[e.jsxs("span",{className:"list-main",children:[e.jsx("span",{className:"avatar",children:ns(r.username)}),e.jsxs("span",{children:[e.jsxs("span",{className:"list-title",children:[r.username||"Unnamed user",e.jsx("span",{className:"dot-state","data-tone":x.tone,title:x.label})]}),e.jsxs("span",{className:"list-meta",children:[w(d.length)," device",d.length===1?"":"s",a?` · ${a} active now`:""," · last seen ",P(r.lastSeen)]})]})]}),e.jsxs("span",{className:"list-actions",children:[e.jsx(N,{tone:v.tone,children:v.label}),e.jsx("span",{className:"crumb",children:"Manage"})]})]},r.id)})})]})]})}function Me(s){const n=String(s??"").replace("#","");return n.length!==8?`#${n}`:`#${n.slice(2)}${n.slice(0,2)}`}function Gs(){const{userId:s=""}=ke(),n=Re(),{wrap:l}=X(),{busy:t,run:o}=Z(),c=`/admin/api/accounts/${encodeURIComponent(s)}`,{data:i,error:r,loading:d,reload:a}=G("/admin/api/accounts",{pollMs:3e4}),[v,x]=p.useState(null),[h,u]=p.useState(null),[f,b]=p.useState(null),[g,m]=p.useState(null),y=((i==null?void 0:i.accounts)??[]).find($=>$.id===s),j=(i==null?void 0:i.catalogue)??[],R=(i==null?void 0:i.themes)??[];p.useEffect(()=>{var $;v===null&&y&&x({...(($=y.settings)==null?void 0:$.preferences)??{}})},[y,v]),p.useEffect(()=>{if(h!==null||!y)return;const $=y.themes??[];u($.length===0?R.map(_=>_.id):$)},[y,h,R]);const k=p.useMemo(()=>{const $=[];for(const _ of j){let K=$.find(S=>S.name===_.area);K||$.push(K={name:_.area,definitions:[]}),K.definitions.push(_)}return $},[j]),A=($,_,K,S)=>o($,async()=>{const q=await l(_,K);b(null),q!==void 0&&(S==null||S()),await a()});if(d)return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"User",crumbs:e.jsx(Y,{to:"/admin/accounts",children:"← All users"})}),e.jsx(B,{})]});if(!y)return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"User",crumbs:e.jsx(Y,{to:"/admin/accounts",children:"← All users"})}),e.jsx(U,{message:r}),e.jsx(C,{children:e.jsx(W,{children:"This user is no longer signed in to Memby."})})]});const T=y.devices??[],M=T.filter($=>be($.lastSeen)).length,I=y.settings??{},te=y.recommendations??{};return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:y.username||"Unnamed user",intro:`Memby user · ${w(T.length)} device${T.length===1?"":"s"} · last seen ${P(y.lastSeen)}`,crumbs:e.jsx(Y,{to:"/admin/accounts",children:"← All users"}),actions:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"avatar",children:ns(y.username)}),M?e.jsxs(N,{tone:"ok",children:[M," active now"]}):e.jsx(N,{children:"idle"}),e.jsx(J,{children:y.id})]})}),e.jsx(U,{message:r}),e.jsxs(re,{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:T.length===0?e.jsx(W,{children:"No devices are signed in to this user."}):e.jsx("div",{className:"list",children:T.map($=>{const _=$e($.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":_.tone,title:_.label})," ",e.jsx(Y,{className:"table-row-link",to:`/admin/devices/${encodeURIComponent($.id)}`,children:$.name||"Memby TV"})]}),e.jsxs("p",{children:[$.version?`Memby ${$.version}`:"Legacy Memby client"," · ",_.label," · last seen ",P($.lastSeen)," · signed in ",P($.signedInAt)]}),($.versions??[]).length>0?e.jsx("div",{className:"chips",children:($.versions??[]).map(K=>e.jsxs(J,{tone:K.version===$.version?"ok":void 0,children:[K.version,K.version===$.version?" · now":""]},K.version))}):null]}),e.jsxs("div",{className:"list-actions",children:[e.jsx(E,{size:"sm",disabled:!$.id,onClick:()=>m({id:$.id,name:$.name}),children:"Rename"}),e.jsx(E,{size:"sm",variant:"danger",disabled:!$.id,onClick:()=>b({kind:"remove-device",deviceId:$.id,name:$.name}),children:"Sign out"})]})]},$.id||$.name)})})}),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:te.completed?e.jsx(E,{busy:t==="reset-rec",onClick:()=>b({kind:"reset-recommendations"}),children:"Clear stored choices"}):te.prompted?e.jsx(E,{onClick:()=>b({kind:"cancel-prompt"}),children:"Cancel prompt"}):e.jsx(E,{variant:"primary",busy:t==="prompt",onClick:()=>void A("prompt",()=>L.put(`${c}/recommendations/prompt`),"Setup prompt queued."),children:"Send setup prompt"}),children:[e.jsx("div",{className:"row tight",children:te.completed?e.jsx(N,{tone:"ok",children:"completed"}):te.prompted?e.jsx(N,{tone:"warn",children:"prompt queued"}):e.jsx(N,{children:"not invited"})}),e.jsx(Zs,{prompt:te})]})]}),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:I.saved?e.jsxs(N,{tone:I.source==="admin"?"warn":"ok",children:["r",w(I.revision)," · ",I.source||"device"," · ",P(I.updatedAt)]}):e.jsx(N,{children:"defaults · never synced"}),footer:e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"primary",busy:t==="push",onClick:()=>void A("push",()=>L.put(`${c}/preferences`,{preferences:v??{}}),"Pushed to their televisions.",()=>x(null)),children:"Push to their televisions"}),e.jsx(E,{onClick:()=>{x(null),a()},children:"Discard changes"}),e.jsx(E,{onClick:()=>b({kind:"reset-preferences"}),children:"Restore defaults"}),e.jsx(Y,{className:"crumb",to:`/admin/accounts/${encodeURIComponent(s)}/settings`,children:"History and rollback →"})]}),children:k.map($=>e.jsxs("div",{className:"group",children:[e.jsx("p",{className:"group-label",children:$.name}),$.definitions.map(_=>e.jsx(Js,{definition:_,value:v==null?void 0:v[_.key],onChange:K=>x(S=>({...S??{},[_.key]:K}))},_.key))]},$.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:(y.themes??[]).length===0?e.jsx(N,{children:"all schemes"}):e.jsxs(N,{tone:"note",children:[w((y.themes??[]).length)," of ",w(R.length)]}),footer:e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"primary",busy:t==="themes",onClick:()=>(h??[]).length===0?b({kind:"no-themes"}):void A("themes",()=>L.put(`${c}/themes`,{themes:h??[]}),"Colour schemes saved.",()=>u(null)),children:"Save colour schemes"}),e.jsx(E,{onClick:()=>u(R.map($=>$.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:R.map($=>{var _,K,S;return e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:(h??[]).includes($.id),onChange:q=>u(F=>q.target.checked?[...F??[],$.id]:(F??[]).filter(ie=>ie!==$.id))}),e.jsx("span",{className:"switch"}),e.jsx("span",{className:"swatch",style:{"--swatch-surface":Me((_=$.palette)==null?void 0:_.surface),"--swatch-accent":Me((K=$.palette)==null?void 0:K.accent),"--swatch-hairline":Me((S=$.palette)==null?void 0:S.hairline)},children:e.jsx("i",{})}),e.jsxs("span",{className:"check-body",children:[e.jsx("b",{children:$.name}),e.jsx("p",{children:$.description})]})]},$.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(E,{variant:"danger",onClick:()=>b({kind:"remove-account"}),children:"Remove Memby access"})}),g?e.jsx(Ys,{initial:g.name,busy:t==="rename",onCancel:()=>m(null),onConfirm:$=>void A("rename",()=>L.put(`${c}/devices/${encodeURIComponent(g.id)}`,{deviceName:$}),"Device renamed.",()=>m(null))}):null,f?e.jsx(Xs,{pending:f,busy:t,username:y.username,onCancel:()=>b(null),onConfirm:()=>{switch(f.kind){case"remove-device":return void A("remove-device",()=>L.del(`${c}/devices/${encodeURIComponent(f.deviceId)}`),"Device signed out.");case"remove-account":return void A("remove-account",()=>L.del(`${c}/sessions`),"Memby access removed.",()=>n("/admin/accounts"));case"reset-recommendations":case"cancel-prompt":return void A("reset-rec",()=>L.del(`${c}/recommendations`),"Recommendation choices cleared.");case"reset-preferences":return void A("reset-prefs",()=>L.del(`${c}/preferences`),"Defaults restored.",()=>x(null));case"no-themes":return void A("themes",()=>L.put(`${c}/themes`,{themes:[]}),"Colour schemes saved.",()=>u(null))}}}):null]})}function Zs({prompt:s}){const n=s.ratings??[],l=[["Genres",s.genres],["Studios",s.studios],["Actors",s.actors],["Actresses",s.actresses],["Directors",s.directors],["Types",s.contentTypes]],t=[...n.map(o=>e.jsxs(J,{tone:"warn",children:[o.title," · ",w(o.rating)," ★"]},`r:${o.title}`)),...l.flatMap(([o,c])=>(c??[]).map(i=>e.jsxs(J,{children:[o,": ",i]},`${o}:${i}`)))];return t.length===0?e.jsx(W,{children:"No recommendation selections have been saved."}):e.jsx("div",{className:"chips",children:t})}function Js({definition:s,value:n,onChange:l}){if(s.kind==="toggle")return e.jsx(H,{label:s.name,hint:s.description,checked:!!n,onChange:l});if(s.kind==="choice"||s.kind==="number"){const o=s.unit??"",c=s.kind==="number"?(s.numbers??[]).map(i=>({value:String(i),label:i===0?"No limit":o?`${i} ${o}`:String(i)})):s.options??[];return e.jsx(D,{label:s.name,hint:s.description,children:e.jsx("select",{value:String(n??""),onChange:i=>l(s.kind==="number"?Number(i.target.value):i.target.value),children:c.map(i=>e.jsx("option",{value:i.value,children:i.label},i.value))})})}if(s.kind==="multi"){const o=Array.isArray(n)?n:[],c=[...o,...(s.options??[]).map(i=>i.value).filter(i=>!o.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:c.map(i=>{const r=(s.options??[]).find(d=>d.value===i);return r?e.jsx(H,{label:r.label,checked:o.includes(i),onChange:d=>l(d?[...o,i]:o.filter(a=>a!==i))},i):null})})]})}const t=Array.isArray(n)?n:[];return e.jsx(D,{label:s.name,hint:s.description,children:e.jsx("textarea",{spellCheck:!1,placeholder:"One row id per line",value:t.join(`
`),onChange:o=>l(o.target.value.split(`
`).map(c=>c.trim()).filter(Boolean))})})}function Ys({initial:s,busy:n,onConfirm:l,onCancel:t}){const[o,c]=p.useState(s||"Memby TV");return e.jsx("div",{className:"scrim",onPointerDown:i=>i.target===i.currentTarget&&t(),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(D,{label:"Device name",children:e.jsx("input",{type:"text",value:o,autoFocus:!0,maxLength:80,onChange:i=>c(i.target.value)})}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx(E,{variant:"quiet",onClick:t,children:"Cancel"}),e.jsx(E,{variant:"primary",busy:n,disabled:!o.trim(),onClick:()=>l(o.trim()),children:"Rename"})]})]})})}function Xs({pending:s,busy:n,username:l,onConfirm:t,onCancel:o}){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 ${l||"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},"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(oe,{title:i.title,body:i.body,confirmLabel:i.label,destructive:i.destructive,busy:!!n,onConfirm:t,onCancel:o})}function Qs(s,n){if(s.kind==="toggle")return n?"On":"Off";if(s.kind==="choice"){const t=(s.options??[]).find(o=>o.value===n);return t?t.label:String(n??"")}if(s.kind==="number")return Number(n)===0&&s.unit?"No limit":s.unit?`${n} ${s.unit}`:String(n??"");const l=Array.isArray(n)?n:[];return l.length===0?"None":l.map(t=>{var o;return((o=(s.options??[]).find(c=>c.value===t))==null?void 0:o.label)??t}).join(", ")}function en(){const{userId:s=""}=ke(),{wrap:n}=X(),{busy:l,run:t}=Z(),o=`/admin/api/accounts/${encodeURIComponent(s)}`,{data:c,error:i,loading:r,reload:d}=G(`${o}/preferences/history`,{pollMs:3e4}),[a,v]=p.useState(new Set),[x,h]=p.useState(null),u=(c==null?void 0:c.username)||"this account",f=(c==null?void 0:c.devices)??[],b=(c==null?void 0:c.revisions)??[],g=(c==null?void 0:c.catalogue)??[],m=j=>v(R=>{const k=new Set(R);return k.has(j)?k.delete(j):k.add(j),k}),y=j=>t("restore",async()=>{await n(()=>L.post(`${o}/preferences/revisions/${j}/restore`),`Restored r${j}.`),h(null),await d()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Settings history",intro:`Every change to ${u}'s synced settings, and which of their televisions has taken it.`,crumbs:e.jsxs(Y,{to:`/admin/accounts/${encodeURIComponent(s)}`,children:["← ",u]})}),e.jsx(U,{message:i}),r?e.jsx(B,{}):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:c!=null&&c.saved?e.jsxs(N,{tone:c.currentSource==="admin"?"warn":"ok",children:["now on r",w(c.currentRevision)," · ",c.currentSource||"device"]}):e.jsx(N,{children:"defaults · never synced"}),children:f.length===0?e.jsx(W,{children:"No television has been signed in to this account."}):e.jsx("div",{className:"list",children:f.map(j=>{const R=j.never?void 0:j.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":R})," ",j.name||"Memby TV"," ",j.signedOut?e.jsx(N,{children:"signed out"}):null]}),e.jsxs("p",{children:[j.never?"Has not fetched these settings yet":`Holding r${w(j.revision)} · taken ${P(j.ackedAt)}`,j.clientVersion?` · Memby ${j.clientVersion}`:"",j.signedOut?"":` · last seen ${P(j.lastSeen)}`]})]}),e.jsx("div",{className:"list-actions",children:j.never?e.jsx(N,{children:"never taken one"}):j.behind?e.jsxs(N,{tone:"bad",children:[w(j.behind)," behind"]}):e.jsx(N,{tone:"ok",children:"up to date"})})]},j.deviceId||j.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(z,{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:b.length===0?e.jsx(Q,{columns:6,children:"Nothing has been changed on this account yet."}):b.flatMap(j=>{const R=a.has(j.revision),k=j.acks??[],A=j.changes??[],T=[e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:P(j.createdAt)}),e.jsxs("td",{className:"num nowrap",children:["r",w(j.revision)," ",j.current?e.jsx(N,{tone:"ok",children:"current"}):null]}),e.jsxs("td",{className:"nowrap",children:[e.jsx(N,{tone:j.source==="admin"?"warn":"ok",children:j.author}),j.restoredFrom?e.jsxs("span",{className:"muted",children:[" restored r",w(j.restoredFrom)]}):null]}),e.jsx("td",{className:"muted",children:j.initial?e.jsx("span",{className:"muted",children:"First recorded settings"}):A.length===0?e.jsx("span",{className:"muted",children:"No visible change"}):e.jsx("div",{className:"chips",children:A.map((M,I)=>e.jsxs(J,{children:[M.name,": ",M.before," → ",M.after]},`${M.name}:${I}`))})}),e.jsx("td",{className:"num",children:k.length===0?e.jsx("span",{className:"muted",children:"—"}):e.jsx("span",{title:k.map(M=>M.deviceName||M.deviceId).join(", "),children:w(k.length)})}),e.jsx("td",{className:"num nowrap",children:e.jsxs("span",{className:"list-actions",children:[e.jsx(E,{size:"sm",onClick:()=>m(j.revision),children:R?"Hide":"Show"}),j.current?null:e.jsx(E,{size:"sm",onClick:()=>h(j.revision),children:"Restore"})]})})]},j.revision)];return R&&T.push(e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"muted",children:e.jsx("div",{className:"chips",children:g.map(M=>{var I;return e.jsxs(J,{children:[M.name,":"," ",Qs(M,(I=j.preferences)==null?void 0:I[M.key])]},M.key)})})})},`${j.revision}:detail`)),T})})]})})})]}),x!==null?e.jsx(oe,{title:`Restore revision ${x}?`,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:l==="restore",onConfirm:()=>void y(x),onCancel:()=>h(null)}):null]})}function sn({client:s}){const n=s.versions??[];return n.length===0?e.jsx("span",{className:"muted",children:"—"}):e.jsx("span",{className:"versions",children:n.map(l=>e.jsx(J,{tone:l.version===s.version?"ok":void 0,children:l.version},l.version))})}function nn(){const{status:s,error:n,loading:l}=se(),t=(s==null?void 0:s.clients)??[],o=t.filter(i=>(i.capabilities??[]).includes("server_features_v1")),c=new Set(t.map(i=>i.version).filter(Boolean));return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Devices",intro:"Which sets have reported in, what they are running and what their build understands."}),e.jsx(U,{message:n}),l?e.jsx(B,{}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"devices known",value:w(t.length),icon:"tv",tone:"info"},{label:"active in the last quarter hour",value:w(t.filter(i=>be(i.lastSeen)).length),icon:"pulse",tone:"ok"},{label:"reporting their capabilities",value:w(o.length),icon:"sliders",tone:"ok"},{label:"app builds in service",value:w(c.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(z,{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:t.length===0?e.jsx(Q,{columns:6,children:"No devices have signed in yet."}):t.map(i=>{const r=(i.capabilities??[]).includes("server_features_v1"),d=$e(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":d.tone,title:d.label}),e.jsx(Y,{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(sn,{client:i})}),e.jsx("td",{children:e.jsx(N,{tone:r?"ok":"warn",children:r?"reported":"missing"})}),e.jsx("td",{className:"nowrap muted",children:P(i.lastSeen)})]},`${i.deviceId}:${i.username}`)})})]})})})]})]})}const Oe={user:"",q:"",ip:"",outcome:"",from:"",to:""},tn=[{value:1,label:"Today"},{value:7,label:"7 days"},{value:30,label:"30 days"},{value:0,label:"All"}];function an(){var j,R,k,A,T,M;const[s,n]=p.useState("log"),[l,t]=p.useState(7),[o,c]=p.useState(Oe),[i,r]=p.useState(0),d=100,a=p.useMemo(()=>ge({...o,days:o.from?void 0:l||void 0,limit:d,offset:i*d}),[o,l,i]),v=G(`/admin/api/logins${a}`,{enabled:s==="log"}),x=G(`/admin/api/logins/devices${a}`,{enabled:s==="devices"}),h=((j=v.data)==null?void 0:j.users)??((R=x.data)==null?void 0:R.users)??[],u=((k=v.data)==null?void 0:k.totals)??((A=x.data)==null?void 0:A.totals),f=((T=v.data)==null?void 0:T.retentionDays)??((M=x.data)==null?void 0:M.retentionDays)??90,b=s==="log"?v.loading:x.loading,g=s==="log"?v.error:x.error,m=I=>{c(te=>({...te,...I})),r(0)},y=Object.entries(o).some(([,I])=>I!=="")||!!o.from;return e.jsxs(e.Fragment,{children:[e.jsx(O,{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(we,{value:s,options:[{value:"log",label:"Log"},{value:"devices",label:"By device"}],onChange:n})}),e.jsx(U,{message:g}),u?e.jsx(ne,{tiles:[{label:"Successful sign-ins",value:w(u.logins),icon:"key",tone:"ok"},{label:"Refused",value:w(u.failures),icon:"shield",tone:u.failures>0?"warn":void 0},{label:"Televisions",value:w(u.devices),icon:"tv",tone:"info"},{label:"People",value:w(u.users),icon:"people",tone:"note"},{label:"Addresses",value:w(u.addresses),icon:"globe",tone:"data"},{label:"History kept",value:`${f} days`,small:!0,icon:"clock"}]}):null,e.jsxs("div",{className:"filters",children:[e.jsx(D,{label:"Window",children:e.jsx(we,{value:o.from?-1:l,options:tn.map(I=>({value:I.value,label:I.label})),onChange:I=>{t(I),m({from:"",to:""})}})}),e.jsx(D,{label:"Person",children:e.jsxs("select",{value:o.user,onChange:I=>m({user:I.target.value}),children:[e.jsx("option",{value:"",children:"Anyone"}),h.map(I=>e.jsx("option",{value:I.id,children:I.username||I.id},I.id))]})}),e.jsx(D,{label:"Outcome",children:e.jsxs("select",{value:o.outcome,onChange:I=>m({outcome:I.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(D,{label:"Address",children:e.jsx("input",{type:"text",value:o.ip,placeholder:"10.0.0.4",onChange:I=>m({ip:I.target.value})})}),e.jsx(D,{label:"From",children:e.jsx("input",{type:"date",value:o.from,onChange:I=>m({from:I.target.value})})}),e.jsx(D,{label:"To",children:e.jsx("input",{type:"date",value:o.to,onChange:I=>m({to:I.target.value})})}),e.jsx(D,{label:"Search",grow:!0,children:e.jsx("input",{type:"search",value:o.q,placeholder:"Name, device or address",onChange:I=>m({q:I.target.value})})}),e.jsx("div",{className:"filter-actions",children:y?e.jsx(E,{variant:"quiet",size:"sm",onClick:()=>{c(Oe),r(0)},children:"Clear"}):null})]}),b?e.jsx(B,{}):s==="log"?e.jsx(rn,{data:v.data,page:i,limit:d,onPage:r}):e.jsx(ln,{data:x.data})]})}function rn({data:s,page:n,limit:l,onPage:t}){if(!s)return null;const o=s.events.length,c=s.total===0?0:n*l+1;return e.jsxs(e.Fragment,{children:[e.jsxs(re,{cols:"wide",children:[e.jsx(C,{title:"Attempts per day",intro:"Grouped in the household's own timezone, so an evening sign-in stays on the day it happened.",icon:"chart",tone:"info",children:e.jsx(ls,{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(W,{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(c)}${w(c+o-1)} of ${w(s.total)}`}),footer:s.total>l?e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",disabled:n===0,onClick:()=>t(n-1),children:"Newer"}),e.jsx(E,{size:"sm",disabled:(n+1)*l>=s.total,onClick:()=>t(n+1),children:"Older"})]}):void 0,children:e.jsx(z,{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(Q,{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:P(i.occurredAt)}),e.jsx("td",{children:i.username||e.jsx("span",{className:"quiet",children:"unknown"})}),e.jsx("td",{children:i.deviceId?e.jsx(Y,{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 ln({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(z,{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(Q,{columns:9,children:"No television has connected in this window."}):s.devices.map(n=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx(Y,{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?P(n.lastLogin):"—"}),e.jsx("td",{className:"mono",children:n.clientVersion||"—"})]},n.deviceId))})]})})}):null}const on=[{value:1,label:"Today"},{value:7,label:"7 days"},{value:30,label:"30 days"},{value:0,label:"All"}];function cn(){const{deviceId:s=""}=ke(),[n,l]=p.useState(7),t=p.useMemo(()=>`/admin/api/logins/devices/${encodeURIComponent(s)}${ge({days:n||void 0,limit:200})}`,[s,n]),{data:o,error:c,loading:i}=G(t,{enabled:!!s}),r=o==null?void 0:o.summary,d=(r==null?void 0:r.deviceName)||s;return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:d,intro:"One television's whole relationship with the gateway.",crumbs:e.jsxs(e.Fragment,{children:[e.jsx(Y,{to:"/admin/clients",children:"Devices"}),e.jsx("span",{children:"/"}),e.jsx(Y,{to:"/admin/logins",children:"Sign-ins"}),e.jsx("span",{children:"/"}),e.jsx("span",{children:d})]}),actions:e.jsx(we,{value:n,options:on.map(a=>({value:a.value,label:a.label})),onChange:l})}),e.jsx(U,{message:c}),i?e.jsx(B,{}):o?e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"Sign-ins today",value:w((r==null?void 0:r.loginsToday)??0),icon:"clock",tone:"ok"},{label:"Sign-ins in total",value:w((r==null?void 0:r.logins)??0),icon:"key",tone:"info"},{label:"Refused",value:w((r==null?void 0:r.failures)??0),icon:"shield",tone:((r==null?void 0:r.failures)??0)>0?"warn":void 0},{label:"Addresses seen",value:w((r==null?void 0:r.distinctIps)??0),icon:"globe",tone:"data"},{label:"First seen",value:r!=null&&r.firstLogin?P(r.firstLogin):"—",small:!0,icon:"history"},{label:"Last seen",value:r!=null&&r.lastLogin?P(r.lastLogin):"—",small:!0,icon:"pulse",tone:"note"}]}),e.jsxs(re,{cols:"wide",children:[e.jsx(C,{title:"Connections per day",icon:"chart",tone:"info",children:e.jsx(ls,{data:o.days,labelOf:a=>a.day,valueOf:a=>a.logins+a.failures,toneOf:a=>a.failures>a.logins?"bad":void 0,title:a=>`${a.day}: ${a.logins} in${a.failures?`, ${a.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:(r==null?void 0:r.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:o.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:(r==null?void 0:r.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:o.versions.length===0?e.jsx(W,{children:"No build history for this television."}):e.jsx("div",{className:"list",children:o.versions.map(a=>e.jsx("div",{className:"list-item",children:e.jsxs("div",{className:"list-body",children:[e.jsx("b",{className:"mono",children:a.version}),e.jsxs("p",{children:[P(a.firstSeen)," → ",P(a.lastSeen)]})]})},a.version))})})]})]}),e.jsx(C,{title:"Addresses",icon:"globe",tone:"data",children:o.addresses.length===0?e.jsx(W,{children:"No addresses recorded in this window."}):e.jsx("div",{className:"chips",children:o.addresses.map(a=>e.jsxs(J,{tone:a.failures>0?"warn":"data",children:[a.ipAddress," · ",w(a.logins),a.failures>0?` (+${w(a.failures)} refused)`:""]},a.ipAddress))})}),e.jsx(C,{title:"Every attempt",icon:"key",tone:"ok",actions:e.jsxs("span",{className:"filter-summary",children:[w(o.total)," in this window"]}),children:e.jsx(z,{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:o.events.length===0?e.jsx(Q,{columns:6,children:"This television has not connected in the selected window."}):o.events.map(a=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:P(a.occurredAt)}),e.jsx("td",{children:a.username||e.jsx("span",{className:"quiet",children:"unknown"})}),e.jsx("td",{className:"mono nowrap",children:a.ipAddress||"—"}),e.jsx("td",{className:"mono",children:a.clientVersion||"—"}),e.jsx("td",{className:"muted",children:a.method}),e.jsx("td",{className:"nowrap",children:a.success?a.newDevice?e.jsx(N,{tone:"info",children:"first sign-in"}):e.jsx(N,{tone:"ok",children:"got in"}):e.jsx(N,{tone:"bad",children:a.failureReason||"refused"})})]},a.id))})]})})})]}):null]})}function dn(){const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o}=X(),{busy:c,run:i}=Z(),[r,d]=p.useState(!1),a=(s==null?void 0:s.library.byType)??{},v=!!(s!=null&&s.syncRunning),x=h=>i(h,async()=>{await o(()=>L.post("/admin/api/sync",{kind:h}),h==="full"?"Full re-import started.":"Import started."),d(!1),await t()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Library",intro:"Import and inspect the catalogue Memby ranks."}),e.jsx(U,{message:n}),l||!s?e.jsx(B,{}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"items",value:w(s.library.total),icon:"library",tone:"data"},...Object.keys(a).sort().map(h=>({label:h,value:w(a[h]),icon:"list"})),{label:"last import",value:P(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:v?"Import running…":`An incremental import runs automatically every ${s.syncEvery}.`}),children:e.jsxs("div",{className:"row",children:[e.jsx(E,{variant:"primary",icon:"sync",disabled:v,busy:c==="incremental",onClick:()=>void x("incremental"),children:"Sync new items"}),e.jsx(E,{icon:"database",disabled:v,onClick:()=>d(!0),children:"Full re-import"})]})})]}),r?e.jsx(oe,{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:c==="full",onConfirm:()=>void x("full"),onCancel:()=>d(!1)}):null]})}const hn={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 un(){const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o}=X(),{busy:c,run:i}=Z(),[r,d]=p.useState(!1),[a,v]=p.useState(""),[x,h]=p.useState(!1),[u,f]=p.useState([]),[b,g]=p.useState(!1),m=s==null?void 0:s.mdblist;p.useEffect(()=>{b||!m||(d(m.enabled),f(m.sources??[]))},[m,b]);const y=()=>i("save",async()=>{await o(()=>L.post("/admin/api/mdblist-settings",{enabled:r,apiKey:a.trim(),clearApiKey:x,sources:u}),"Ratings settings saved."),v(""),h(!1),g(!1),await t()}),j=(m==null?void 0:m.cachedTitles)??0;return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Movie ratings",intro:"Optional MDBList scores on films and shows."}),e.jsx(U,{message:n}),l||!m?e.jsx(B,{}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"titles stored",value:w(j),icon:"database",tone:"data"},{label:"due to be re-checked",value:w(m.staleTitles),icon:"sync",tone:"warn"},{label:"sources shown",value:w((m.sources??[]).length),icon:"star",tone:"note"},{label:"API key",value:m.apiKeyConfigured?"saved":"not set",small:!0,icon:"key",tone:m.apiKeyConfigured?"ok":void 0}]}),e.jsxs(re,{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:r?e.jsxs(N,{tone:"ok",children:["on · ",u.length," sources"]}):e.jsx(N,{children:m.apiKeyConfigured?"off · key saved":"off · no key"}),children:[e.jsx(H,{label:"Show external ratings on televisions",hint:"Off leaves the stored ratings in place.",checked:r,onChange:R=>{d(R),g(!0)}}),e.jsx(D,{label:"API key",hint:"Leave blank to keep the key that is already saved.",children:e.jsx("input",{type:"password",autoComplete:"new-password",value:a,placeholder:m.apiKeyConfigured?"Saved key (leave blank to keep)":"Paste an API key",onChange:R=>v(R.target.value)})}),e.jsx(H,{label:"Remove the saved key",checked:x,onChange:h})]}),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:(m.availableSources??[]).length===0?e.jsx(W,{children:"No rating sources are available."}):e.jsx("div",{className:"checks columns",children:(m.availableSources??[]).map(R=>e.jsx(H,{label:hn[R]??R,checked:u.includes(R),onChange:k=>{g(!0),f(A=>k?[...A,R]:A.filter(T=>T!==R))}},R))})})]}),e.jsx(C,{children:e.jsxs("div",{className:"row",children:[e.jsx(E,{variant:"primary",busy:c==="save",onClick:()=>void y(),children:"Save ratings settings"}),e.jsx("span",{className:"hint",children:j?"Ratings are fetched as televisions browse, never on the request path.":"No ratings stored yet. They are saved as televisions browse the library."})]})})]})]})}function mn(){var x;const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o}=X(),{busy:c,run:i}=Z(),r=(s==null?void 0:s.requestUsers)??[],d=((x=s==null?void 0:s.requestPolicy)==null?void 0:x.allowedUserIds)??[],a=p.useMemo(()=>new Map(((s==null?void 0:s.requestUsage)??[]).map(h=>[h.userId,h])),[s==null?void 0:s.requestUsage]),v=h=>i(`access-${h}`,async()=>{const u=d.includes(h)?d.filter(f=>f!==h):[...d,h];await o(()=>L.post("/admin/api/request-policy",{allowedUserIds:u}),u.includes(h)?"Request access granted.":"Request access removed."),await t()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Media requests",intro:"Who can ask for something the library does not have."}),e.jsx(U,{message:n}),l?e.jsx(B,{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(W,{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:r.length===0?e.jsx(W,{children:"No one has signed in yet."}):e.jsx(z,{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:r.map(h=>{const u=a.get(h.id),f=d.includes(h.id);return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("b",{children:h.username})}),e.jsx("td",{className:"muted nowrap",children:P(h.lastSeen)}),e.jsx("td",{className:"num",children:(u==null?void 0:u.requests)??0}),e.jsx("td",{className:"muted nowrap",children:u!=null&&u.lastRequest?P(u.lastRequest):"—"}),e.jsx("td",{children:e.jsx(E,{size:"sm",variant:f?"quiet":"primary",busy:c===`access-${h.id}`,onClick:()=>void v(h.id),children:f?"Remove access":"Give access"})})]},h.id)})})]})})})]})]})}function pn(){const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o}=X(),{busy:c,run:i}=Z(),[r,d]=p.useState(!1),a=s==null?void 0:s.forYou,v=!!(s!=null&&s.forYouRunning),x=(h,u,f)=>i(u,async()=>{await o(()=>L.post("/admin/api/for-you",{action:h}),f),d(!1),await t()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"For You",intro:"The prepared pools personalised rows are drawn from."}),e.jsx(U,{message:n}),l?e.jsx(B,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"Tracearr sessions",value:w((a==null?void 0:a.tracearrSessions)??0),icon:"play",tone:"info"},{label:"user profiles",value:w((a==null?void 0:a.profiles)??0),icon:"people",tone:"note"},{label:"ranked candidates",value:w((a==null?void 0:a.candidates)??0),icon:"sparkle",tone:"note"},{label:"last full import",value:P(a==null?void 0:a.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:v?"For You maintenance running…":"Prepared pools normally refresh in the background."}),children:e.jsxs("div",{className:"row",children:[e.jsx(E,{variant:"primary",icon:"download",disabled:v,busy:c==="import",onClick:()=>void x("incremental-import","import","Import started."),children:"Import recent sessions"}),e.jsx(E,{icon:"database",disabled:v,onClick:()=>d(!0),children:"Full Tracearr backfill"}),e.jsx(E,{icon:"sync",disabled:v,busy:c==="rebuild",onClick:()=>void x("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(Y,{to:"/admin/inspector",children:"Open the inspector"}),children:e.jsx(e.Fragment,{})})]}),r?e.jsx(oe,{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:c==="full",onConfirm:()=>void x("full-import","full","Backfill started."),onCancel:()=>d(!1)}):null]})}const xn=[["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 jn(s){return s?xn.flatMap(([n,l])=>Object.entries(s[l]??{}).map(([t,o])=>({dimension:n,name:t,weight:o.weight??0,evidence:o.evidence??0}))).sort((n,l)=>Math.abs(l.weight)-Math.abs(n.weight)):[]}const Ue=s=>`${s>=0?"+":""}${s.toFixed(3)}`;function vn(){const{status:s}=se(),{wrap:n}=X(),{busy:l,run:t}=Z(),[o,c]=p.useState(""),[i,r]=p.useState("default"),[d,a]=p.useState("0"),[v,x]=p.useState(""),[h,u]=p.useState(null),[f,b]=p.useState("Choose a person to inspect their recommendations."),[g,m]=p.useState(""),y=(s==null?void 0:s.requestUsers)??[],j=()=>t("run",async()=>{if(!o){m("Choose a person to pressure-test.");return}m(""),b("Running the permission check and the scorer…");const M=new URLSearchParams({userId:o,context:i,minutes:d||"0",limit:"100"});v&&M.set("at",new Date(v).toISOString());const I=await n(()=>L.get(`/admin/api/recommendations?${M.toString()}`));I?(u(I),b(`Scored at ${new Date().toLocaleTimeString()}.`)):b("Pressure test failed.")}),R=jn((h==null?void 0:h.profile)??null).slice(0,24),k=(h==null?void 0:h.actions)??[],A=(h==null?void 0:h.items)??[],T=(h==null?void 0:h.profileMeta)??{};return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Score inspector",intro:"Re-run the ranker for one person and read every component."}),e.jsx(U,{message:g}),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(E,{variant:"primary",busy:l==="run",onClick:()=>void j(),children:"Run pressure test"}),e.jsx("span",{className:"hint",children:f})]}),children:e.jsxs("div",{className:"fields",children:[e.jsx(D,{label:"Person",children:e.jsxs("select",{value:o,onChange:M=>c(M.target.value),children:[e.jsx("option",{value:"",children:"Choose a person…"}),y.map(M=>e.jsx("option",{value:M.id,children:M.username},M.id))]})}),e.jsx(D,{label:"Context",children:e.jsxs("select",{value:i,onChange:M=>r(M.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(D,{label:"Available minutes",children:e.jsx("input",{type:"number",min:0,max:360,value:d,onChange:M=>a(M.target.value)})}),e.jsx(D,{label:"Evaluate at",children:e.jsx("input",{type:"datetime-local",value:v,onChange:M=>x(M.target.value)})})]})}),h?e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"prepared pool",value:w(h.poolCandidates),icon:"database",tone:"data"},{label:"permission eligible",value:w(h.permissionEligible),icon:"shield",tone:"ok"},{label:"ranked result",value:w(A.length),icon:"sparkle",tone:"note"},{label:"source events",value:w(T.sourceEvents??0),icon:"pulse",tone:"info"},{label:"algorithm",value:T.algorithmVersion||"—",small:!0,icon:"chip"},{label:"pool built",value:P(T.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:[R.length===0?e.jsx(W,{children:"No repeated affinity evidence yet; cold-start priors apply."}):e.jsx("div",{className:"chips",children:R.map(M=>e.jsxs(J,{tone:M.weight<0?"bad":void 0,children:[M.dimension,": ",M.name," ",Ue(M.weight)," · n=",w(M.evidence)]},`${M.dimension}:${M.name}`))}),k.length===0?e.jsx(W,{children:"No explicit recommendation actions."}):e.jsx("div",{className:"chips",children:k.map((M,I)=>e.jsxs(J,{tone:"ok",children:[M.action,": ",M.title||M.itemId]},`${M.action}:${I}`))})]}),A.length===0?e.jsx(C,{children:e.jsx(W,{children:"No candidates survived this context, the explicit exclusions and the permission filter."})}):e.jsx(re,{children:A.map((M,I)=>{const te=M.explanation??{},$=Object.entries(te.components??{}).sort((S,q)=>Math.abs(q[1])-Math.abs(S[1])),_=M.exposure??{},K=[M.type,M.year,M.runtimeMinutes?`${M.runtimeMinutes} min`:null,...M.genres??[]].filter(Boolean).join(" · ");return e.jsxs(C,{title:`#${I+1} · ${M.title}`,intro:K,actions:e.jsx(J,{tone:"ok",children:Number(te.total??0).toFixed(3)}),children:[e.jsxs("p",{className:"hint",children:[M.preparedReason||"No legacy prepared explanation",M.compatibilityLabel?` · ${M.compatibilityLabel}`:""]}),e.jsxs("div",{className:"chips",children:[(te.reasonCodes??[]).map(S=>e.jsx(J,{tone:"ok",children:S},S)),$.map(([S,q])=>e.jsxs(J,{tone:q<0?"bad":void 0,children:[S,"=",Ue(q)]},S))]}),e.jsxs("details",{children:[e.jsx("summary",{className:"muted",children:"Pool, row and exposure detail"}),e.jsxs("p",{className:"hint",children:["Base rank ",w(M.baseRank??0)," · base ",Number(M.baseScore??0).toFixed(3)," · affinity ",Number(M.affinityScore??0).toFixed(3)," · compatibility"," ",Number(M.compatibilityScore??0).toFixed(3)," · impressions"," ",w(_.impressions??0)," · focuses ",w(_.focuses??0)," · selects"," ",w(_.selects??0)]}),e.jsx("div",{className:"chips",children:(M.eligibleRows??[]).map(S=>e.jsx(J,{tone:"ok",children:S},S))}),M.preparedEvidenceTitle?e.jsxs("p",{className:"hint",children:["Prepared evidence: ",M.preparedEvidenceTitle]}):null]})]},`${I}:${M.title}`)})})]}):null]})}const bn=4,ce=[{id:"home",label:"Home",type:"films and television shows"},{id:"movies",label:"Movies",type:"films"},{id:"tv_shows",label:"TV Shows",type:"television shows"}],xe=()=>({pinnedItems:[],primeSubtitle:""});function gn(){var $,_,K;const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o,show:c}=X(),{busy:i,run:r}=Z(),[d,a]=p.useState("home"),[v,x]=p.useState({home:xe(),movies:xe(),tv_shows:xe()}),[h,u]=p.useState(!1),[f,b]=p.useState(""),[g,m]=p.useState(null),[y,j]=p.useState([]),R=s==null?void 0:s.heroPolicy;p.useEffect(()=>{var S,q,F;h||!R||(x({home:((S=R.placements)==null?void 0:S.home)??{pinnedItems:R.pinnedItems??[],primeSubtitle:R.primeSubtitle??""},movies:((q=R.placements)==null?void 0:q.movies)??xe(),tv_shows:((F=R.placements)==null?void 0:F.tv_shows)??xe()}),j(R.schedules??[]))},[R,h]);const k=()=>r("search",async()=>{const S=f.trim();if(!S)return;const q=await o(()=>L.get(`/admin/api/hero/search?q=${encodeURIComponent(S)}`));q&&m(q.items??[])}),A=v[d],T=A.pinnedItems??[],M=S=>{x(q=>({...q,[d]:{...q[d],...S}})),u(!0)},I=S=>{if(!T.some(q=>q.id===S.id)){if(T.length>=bn){c("Remove a pinned title before adding another.","bad");return}M({pinnedItems:[...T,S]})}},te=()=>r("save",async()=>{await o(()=>L.post("/admin/api/hero-policy",{placements:Object.fromEntries(Object.entries(v).map(([S,q])=>[S,{pinnedItemIds:(q.pinnedItems??[]).map(F=>F.id),primeSubtitle:q.primeSubtitle.trim()}])),schedules:y}),"Hero saved."),u(!1),await t()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Featured content",intro:"Manage an independent, backend-resolved hero for Home, Movies and TV Shows."}),e.jsx(U,{message:n}),l?e.jsx(B,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx(re,{children:ce.map(S=>{var pe;const q=v[S.id],F=y.filter(ae=>ae.enabled&&(ae.placements??["home"]).includes(S.id)&&new Date(ae.startAt)<=new Date&&new Date(ae.endAt)>new Date).sort((ae,us)=>us.priority-ae.priority)[0],ie=(q.pinnedItems??[]).length?"Manual":F?"Scheduled":"Automatic",le=(pe=R==null?void 0:R.items)==null?void 0:pe.find(ae=>ae.id===(F==null?void 0:F.itemId)),me=(q.pinnedItems??[]).map(ae=>ae.name).join(", ")||(le==null?void 0:le.name)||(F==null?void 0:F.itemId)||"Resolved for each viewer";return e.jsx(C,{title:S.label,intro:`${ie} · ${me}`,tone:S.id===d?"info":void 0,children:e.jsxs(E,{size:"sm",variant:"quiet",onClick:()=>a(S.id),children:["Manage ",S.label]})},S.id)})}),e.jsx("div",{className:"tabs",role:"tablist","aria-label":"Hero placement",children:ce.map(S=>e.jsx(E,{variant:d===S.id?"primary":"quiet",onClick:()=>a(S.id),children:S.label},S.id))}),e.jsxs(C,{title:`${($=ce.find(S=>S.id===d))==null?void 0:$.label} hero`,intro:`Pinned ${(_=ce.find(S=>S.id===d))==null?void 0:_.type} lead this section only. Empty places use this placements automatic selection.`,icon:"star",tone:"note",footer:e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"primary",busy:i==="save",onClick:()=>void te(),children:"Save hero"}),e.jsx(E,{onClick:()=>{M({pinnedItems:[]})},children:"Clear pins"}),h?e.jsx("span",{className:"hint",children:"Unsaved changes."}):null]}),children:[T.length===0?e.jsx(W,{children:"No titles are pinned. The hero is entirely release-aware and automatic."}):e.jsx("div",{className:"chips",children:T.map((S,q)=>e.jsxs(E,{variant:"quiet",size:"sm",icon:"close",onClick:()=>{M({pinnedItems:T.filter(F=>F.id!==S.id)})},children:[q+1,". ",S.name,S.year?` (${S.year})`:""]},S.id))}),e.jsx(D,{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:A.primeSubtitle,placeholder:"Leave blank for the automatic reason",onChange:S=>{M({primeSubtitle:S.target.value})}})})]}),e.jsxs(C,{title:"Scheduled heroes",intro:"Schedules are resolved by the gateway: manual pins still win, then the highest-priority eligible schedule, then Membys automatic hero.",icon:"clock",tone:"info",children:[y.length===0?e.jsx(W,{children:"No scheduled heroes yet."}):e.jsx("div",{className:"stack",children:y.map(S=>{const q=[...(R==null?void 0:R.items)??[],...T,...g??[]].find(F=>F.id===S.itemId);return e.jsxs("div",{className:"row",children:[e.jsx("b",{children:(q==null?void 0:q.name)??S.itemId}),e.jsxs("span",{className:"muted",children:[new Date(S.startAt).toLocaleString()," → ",new Date(S.endAt).toLocaleString()," · priority ",S.priority," · ",(S.placements??["home"]).map(F=>{var ie;return(ie=ce.find(le=>le.id===F))==null?void 0:ie.label}).join(", ")]}),e.jsx("div",{className:"chips",children:ce.map(F=>e.jsx(E,{size:"sm",variant:(S.placements??["home"]).includes(F.id)?"primary":"quiet",onClick:()=>{j(ie=>ie.map(le=>{if(le.id!==S.id)return le;const me=le.placements??["home"],pe=me.includes(F.id)?me.filter(ae=>ae!==F.id):[...me,F.id];return{...le,placements:pe.length?pe:[F.id]}})),u(!0)},children:F.label},F.id))}),e.jsx(E,{size:"sm",variant:"quiet",onClick:()=>{j(F=>F.filter(ie=>ie.id!==S.id)),u(!0)},children:"Remove"})]},S.id)})}),T.length>0?e.jsx(E,{size:"sm",icon:"plus",onClick:()=>{const S=T[0];if(!S)return;const q=new Date,F=new Date(q.getTime()+2*60*60*1e3);j(ie=>[...ie,{id:crypto.randomUUID(),itemId:S.id,startAt:q.toISOString(),endAt:F.toISOString(),priority:0,enabled:!0,placements:[d]}]),u(!0)},children:"Schedule first pinned title for two hours"}):e.jsx("p",{className:"hint",children:"Pin or search for a title first, then add it to a schedule."})]}),e.jsxs(C,{title:"Find a title",intro:`Search the imported Emby catalogue. Add a result to the selected ${(K=ce.find(S=>S.id===d))==null?void 0:K.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(D,{label:"Title",grow:!0,children:e.jsx("input",{type:"search",value:f,placeholder:"Search films and television shows",onChange:S=>b(S.target.value),onKeyDown:S=>{S.key==="Enter"&&k()}})}),e.jsx(E,{busy:i==="search",icon:"search",onClick:()=>void k(),children:"Search"})]}),g===null?null:g.length===0?e.jsx(W,{children:"No playable films or series matched that search."}):e.jsx(re,{children:g.map(S=>e.jsx(C,{title:S.name,intro:`${S.type||"Title"} · ${S.year||"Year unknown"}`,children:e.jsx(E,{size:"sm",icon:"plus",disabled:T.some(q=>q.id===S.id)||d==="movies"&&S.type!=="Movie"||d==="tv_shows"&&S.type!=="Series",onClick:()=>I(S),children:T.some(q=>q.id===S.id)?"Pinned":"Add to hero"})},S.id))})]})]})]})}function fn(){const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o}=X(),{busy:c,run:i}=Z(),[r,d]=p.useState(null),a=s==null?void 0:s.features,v=(a==null?void 0:a.features)??[],x=(s==null?void 0:s.clients)??[],h=(a==null?void 0:a.revision)??0,u=(m,y,j,R)=>i(y,async()=>{await o(()=>L.post("/admin/api/features",{action:m,expectedRevision:h,overrides:R??{}}),j),d(null),await t()}),f=x.filter(m=>(m.capabilities??[]).includes("server_features_v1")).length,b=!!(a!=null&&a.safeMode),g=(m,y)=>({...Object.fromEntries(v.filter(j=>j.source==="override").map(j=>[j.key,j.enabled])),[m]:y});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Features",intro:"Roll out, stop and recover optional behaviour with no app release."}),e.jsx(U,{message:n}),l||!a?e.jsx(B,{}):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(E,{variant:b?void 0:"danger",busy:c==="safe",onClick:()=>b?void u("leave-safe-mode","safe","Safe mode ended."):d({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:b?"Leave safe mode":"Enable safe mode"}),children:e.jsx(os,{tiles:[{label:"features active",value:`${v.filter(m=>m.enabled).length} / ${v.length}`},{label:"explicit overrides",value:w(v.filter(m=>m.source==="override").length)},{label:"televisions reporting the control plane",value:`${f} / ${x.length}`},{label:"published revision",value:`r${w(h)}`}]})}),e.jsx(re,{cols:"2",children:v.length===0?e.jsx(C,{title:"Nothing registered",icon:"sliders",children:e.jsx(W,{children:"No server features are registered."})}):v.map(m=>e.jsxs(C,{title:m.name,intro:m.description,actions:e.jsx(N,{tone:m.enabled?"ok":void 0,children:m.enabled?"active":"off"}),footer:e.jsxs("span",{className:"hint",children:["↳ ",m.recovery]}),children:[e.jsx(H,{label:m.enabled?"On":"Off",hint:"Changing this applies the feature policy to every compatible television.",checked:m.enabled,disabled:c===m.key,onChange:y=>d({action:"feature",key:m.key,enabled:y,title:`${y?"Turn on":"Turn off"} ${m.name}?`,body:`${y?"Enable":"Disable"} this feature for every compatible television. ${m.recovery}`,label:y?"Turn on":"Turn off"})}),e.jsxs("div",{className:"chips",children:[e.jsx(J,{children:m.key}),e.jsxs(J,{children:["protocol ",w(m.minimumProtocol),"+"]}),e.jsx(J,{tone:m.compatible?"ok":"warn",children:m.compatible?"server compatible":"compatibility blocked"}),e.jsx(J,{tone:"note",children:m.area})]})]},m.key))}),e.jsx(C,{children:e.jsxs("div",{className:"row",children:[e.jsx(E,{disabled:!a.canRollback,onClick:()=>d({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(E,{onClick:()=>d({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"}),b?e.jsx(N,{tone:"warn",children:"safe mode · optional features off"}):e.jsxs(N,{tone:"ok",children:["live · revision r",w(h)]})]})})]}),r?e.jsx(oe,{title:r.title,body:r.body,confirmLabel:r.label,destructive:r.action!=="rollback",busy:c===r.action,onConfirm:()=>void u(r.action==="feature"?"save":r.action,r.action==="feature"?r.key??"feature":r.action,`${r.label} done.`,r.action==="feature"&&r.key?g(r.key,!!r.enabled):void 0),onCancel:()=>d(null)}):null]})}function yn(){const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o,show:c}=X(),{busy:i,run:r}=Z(),[d,a]=p.useState(!0),[v,x]=p.useState("6.5"),[h,u]=p.useState(!1);p.useEffect(()=>{var b,g;h||!s||(a(((b=s.playbackPolicy)==null?void 0:b.prerollEnabled)!==!1),x(String((((g=s.playbackPolicy)==null?void 0:g.prerollDurationMs)??6500)/1e3)))},[s,h]);const f=()=>r("save",async()=>{const b=Number(v);if(!Number.isFinite(b)||b<1||b>30){c("The preroll duration must be between 1 and 30 seconds.","bad");return}await o(()=>L.post("/admin/api/playback-policy",{prerollEnabled:d,prerollDurationMs:Math.round(b*1e3)}),"Playback policy saved."),u(!1),await t()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Playback",intro:"Presentation policy sent with every playback launch."}),e.jsx(U,{message:n}),l?e.jsx(B,{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:d?e.jsxs(N,{tone:"ok",children:["on · ",v,"s"]}):e.jsx(N,{children:"off"}),footer:e.jsx(E,{variant:"primary",busy:i==="save",onClick:()=>void f(),children:"Save playback policy"}),children:[e.jsx(H,{label:"Show the preroll before a title starts",checked:d,onChange:b=>{a(b),u(!0)}}),e.jsx("div",{className:"fields",children:e.jsx(D,{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:v,onChange:b=>{x(b.target.value),u(!0)}})})})]})]})}function wn(){const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o}=X(),{busy:c,run:i}=Z(),[r,d]=p.useState(null),[a,v]=p.useState(null),[x,h]=p.useState(!1),u=s==null?void 0:s.subtitles,f=u==null?void 0:u.stored;p.useEffect(()=>{r||!u||d({bazarr:u.bazarrEnabled,openSubtitles:u.openSubtitlesEnabled,key:"",clearKey:!1,username:u.openSubtitlesUsername??"",password:"",clearLogin:!1})},[u,r]);const b=j=>d(R=>R&&{...R,...j}),g=()=>i("save",async()=>{r&&(await o(()=>L.post("/admin/api/subtitle-settings",{bazarrEnabled:r.bazarr,openSubtitlesEnabled:r.openSubtitles,openSubtitlesApiKey:r.key.trim(),clearOpenSubtitlesApiKey:r.clearKey,openSubtitlesUsername:r.username.trim(),openSubtitlesPassword:r.password,clearOpenSubtitlesLogin:r.clearLogin}),"Subtitle settings saved."),d(null),await t())}),m=()=>i("test",async()=>{v(null);const j=await o(()=>L.post("/admin/api/subtitle-test"));v((j==null?void 0:j.results)??[])}),y=()=>i("clear",async()=>{await o(()=>L.post("/admin/api/subtitle-settings",{action:"clear-stored"}),"Stored subtitles deleted."),h(!1),await t()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Subtitles",intro:"Which providers a viewer may fetch a missing subtitle from."}),e.jsx(U,{message:n}),l||!u||!r?e.jsx(B,{}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"offered on televisions",value:u.available?"yes":"no",small:!0,icon:"captions",tone:u.available?"ok":void 0},{label:"providers on",value:w((u.bazarrEnabled&&u.bazarrConfigured?1:0)+(u.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:P(f==null?void 0:f.latest),small:!0,icon:"clock"}]}),e.jsxs(re,{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:u.bazarrConfigured?r.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:u.bazarrConfigured?`Configured at ${u.bazarrUrl}`:"Set MEMBY_BAZARR_URL and MEMBY_BAZARR_API_KEY to use Bazarr."}),children:e.jsx(H,{label:"Offer Bazarr in the player",hint:"Off leaves every subtitle it has already written in place.",checked:r.bazarr,disabled:!u.bazarrConfigured,onChange:j=>b({bazarr:j})})}),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:u.openSubtitlesEnabled?e.jsx(N,{tone:u.openSubtitlesAccount?"ok":"warn",children:u.openSubtitlesAccount?"on · signed in":"on · anonymous"}):e.jsx(N,{children:u.openSubtitlesKeyConfigured?"off · key saved":"off · no key"}),children:[e.jsx(H,{label:"Offer OpenSubtitles in the player",hint:"Needs an API key. It cannot be switched on without one.",checked:r.openSubtitles,onChange:j=>b({openSubtitles:j})}),e.jsx(D,{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:r.key,placeholder:u.openSubtitlesKeyConfigured?"Saved key (leave blank to keep)":"Paste an API key",onChange:j=>b({key:j.target.value})})}),e.jsx(H,{label:"Remove the saved key",checked:r.clearKey,onChange:j=>b({clearKey:j})}),e.jsxs("div",{className:"fields",children:[e.jsx(D,{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:r.username,placeholder:"Not signed in",onChange:j=>b({username:j.target.value})})}),e.jsx(D,{label:"Account password",hint:"Leave blank to keep the saved one.",children:e.jsx("input",{type:"password",autoComplete:"new-password",value:r.password,onChange:j=>b({password:j.target.value})})})]}),e.jsx(H,{label:"Sign out and forget the account",checked:r.clearLogin,onChange:j=>b({clearLogin:j})})]})]}),e.jsxs(C,{children:[e.jsxs("div",{className:"row",children:[e.jsx(E,{variant:"primary",busy:c==="save",onClick:()=>void g(),children:"Save subtitle settings"}),e.jsx(E,{busy:c==="test",icon:"pulse",onClick:()=>void m(),children:"Test the providers"}),e.jsx("span",{className:"hint",children:u.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."})]}),a===null?null:a.length===0?e.jsx(W,{children:"No provider is switched on, so there was nothing to ask."}):e.jsx("div",{className:"list",children:a.map(j=>e.jsxs("div",{className:"list-item",children:[e.jsxs("div",{className:"list-body",children:[e.jsx("b",{children:j.provider}),e.jsx("p",{children:j.message})]}),e.jsx("div",{className:"list-actions",children:e.jsx(N,{tone:j.ok?"ok":"bad",children:j.ok?"reachable":"not reachable"})})]},j.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 · ",je(f.bytes)]}):e.jsx(N,{children:"nothing held"}),footer:e.jsx(E,{variant:"danger",disabled:!(f!=null&&f.count),onClick:()=>h(!0),children:"Delete every stored subtitle"}),children:e.jsx(e.Fragment,{})})]}),x?e.jsx(oe,{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:c==="clear",onConfirm:()=>void y(),onCancel:()=>h(!1)}):null]})}function kn(){const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o}=X(),{busy:c,run:i}=Z(),[r,d]=p.useState(null),[a,v]=p.useState(!1),x=s==null?void 0:s.updatePolicy;p.useEffect(()=>{r||!x||d({version:x.latestVersion??"",url:x.downloadUrl??"",notes:x.notes??"",retireBelow:x.retireBelowVersion??"",required:!!x.minimumVersion&&x.minimumVersion===x.latestVersion,destructive:!!x.retireBelowVersion&&x.retireBelowVersion===x.latestVersion})},[x,r]);const h=g=>i(g?"save":"off",async()=>{r&&(await o(()=>L.post("/admin/api/update-policy",{enabled:g,latestVersion:r.version.trim(),downloadUrl:r.url.trim(),notes:r.notes.trim(),required:r.required,destructive:r.destructive,retireBelowVersion:r.retireBelow.trim()}),g?"Update policy saved.":"Update prompts turned off."),v(!1),d(null),await t())}),u=!!(x!=null&&x.minimumVersion)&&(x==null?void 0:x.minimumVersion)===(x==null?void 0:x.latestVersion),f=!!(x!=null&&x.retireBelowVersion)&&(x==null?void 0:x.retireBelowVersion)===(x==null?void 0:x.latestVersion),b=g=>d(m=>m&&{...m,...g});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"App updates",intro:"Publish an optional or a required client update."}),e.jsx(U,{message:n}),l||!r?e.jsx(B,{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:x!=null&&x.enabled?e.jsxs(N,{tone:u?"warn":"ok",children:[f?"sign-out · ":u?"required · ":"optional · ",x.latestVersion]}):e.jsx(N,{children:"off"}),footer:e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"primary",busy:c==="save",onClick:()=>r.required?v(!0):void h(!0),children:"Save policy"}),e.jsx(E,{busy:c==="off",onClick:()=>void h(!1),children:"Turn prompts off"})]}),children:[e.jsxs("div",{className:"fields",children:[e.jsx(D,{label:"Latest version",children:e.jsx("input",{type:"text",value:r.version,placeholder:"0.2.63",onChange:g=>b({version:g.target.value})})}),e.jsx(D,{label:"APK URL",children:e.jsx("input",{type:"text",value:r.url,placeholder:"https://nas/memby/memby-0.2.63.apk",onChange:g=>b({url:g.target.value})})})]}),e.jsx(D,{label:"What's new",hint:"Shown on the television above the update button.",children:e.jsx("input",{type:"text",value:r.notes,placeholder:"One line the viewer reads",onChange:g=>b({notes:g.target.value})})}),e.jsx(D,{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:r.retireBelow,placeholder:"0.2.44",onChange:g=>b({retireBelow:g.target.value})})}),e.jsx(H,{label:"Require this update",hint:"Blocks the home screen on every television below this version.",checked:r.required,onChange:g=>b({required:g})}),e.jsx(H,{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:r.destructive,onChange:g=>b(g?{destructive:!0,required:!0,retireBelow:r.version.trim()}:{destructive:!1,retireBelow:r.retireBelow.trim()===r.version.trim()?"":r.retireBelow})})]}),a&&r?e.jsx(oe,{title:r.destructive?"Sign every older television out?":"Require this update?",body:r.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:r.destructive,busy:c==="save",onConfirm:()=>void h(!0),onCancel:()=>v(!1)}):null]})}const Nn=2e4,Sn=3e3;function Ve(s){return s==="failed"?"bad":s==="running"?"info":s==="skipped"?"warn":"ok"}function Mn(){const{wrap:s}=X(),{busy:n,run:l}=Z(),[t,o]=p.useState(!1),{data:c,error:i,loading:r,reload:d}=G("/admin/api/tasks?limit=60",{pollMs:t?Sn:Nn}),a=(c==null?void 0:c.tasks)??[],v=a.some(m=>m.running);v!==t&&o(v);const x=m=>l(m.id,async()=>{await s(()=>L.post(`/admin/api/tasks/${encodeURIComponent(m.id)}/run`),`${m.name} started.`),await d()}),h=(m,y)=>l(`${m.id}:enabled`,async()=>{await s(()=>L.put(`/admin/api/tasks/${encodeURIComponent(m.id)}`,{enabled:y}),y?`${m.name} switched on.`:`${m.name} switched off.`),await d()}),u=a.filter(m=>{var y;return((y=m.lastRun)==null?void 0:y.status)==="failed"}).length,f=a.filter(m=>!m.enabled).length,b=(c==null?void 0:c.groups)??[],g=a.filter(m=>!m.group);return e.jsxs(e.Fragment,{children:[e.jsx(O,{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(U,{message:i}),r?e.jsx(B,{}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"Tasks",value:w(a.length),icon:"clock",tone:"info"},{label:"Running now",value:w(a.filter(m=>m.running).length),icon:"pulse",tone:v?"ok":void 0},{label:"Last run failed",value:w(u),icon:"alert",tone:u>0?"bad":void 0},{label:"Switched off",value:w(f),icon:"power",tone:f>0?"warn":void 0}]}),u>0?e.jsx(fe,{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,[...b,...g.length>0?[""]:[]].map(m=>{const y=a.filter(j=>j.group===m);return y.length===0?null:e.jsx(C,{title:m||"Other",icon:m==="System"?"chip":m==="Analytics"?"chart":"wrench",tone:m==="System"?"info":m==="Analytics"?"data":"note",children:e.jsx("div",{className:"list",children:y.map(j=>{var R;return e.jsxs("div",{className:"list-item",children:[e.jsxs("div",{className:"list-body",children:[e.jsxs("b",{children:[j.name," ",j.running?e.jsx(N,{tone:"info",children:"running"}):null,j.enabled?null:e.jsx(N,{tone:"warn",children:"off"})]}),e.jsx("p",{children:j.description}),e.jsxs("p",{className:"quiet",children:[Ls(j.intervalSeconds),j.enabled&&j.nextRun?` · next ${ue(j.nextRun).replace(" ago","")}`:"",j.lastRun?e.jsxs(e.Fragment,{children:[" · last ",e.jsx("span",{title:P(j.lastRun.startedAt),children:ue(j.lastRun.startedAt)}),` in ${ve(j.lastRun.durationMs)}`,j.lastRun.detail?` — ${j.lastRun.detail}`:""]}):" · never run"]}),(R=j.lastRun)!=null&&R.error?e.jsx("p",{className:"mono",style:void 0,children:e.jsx(N,{tone:"bad",children:j.lastRun.error})}):null]}),e.jsxs("div",{className:"list-actions",children:[j.lastRun?e.jsx(N,{tone:Ve(j.lastRun.status),children:j.lastRun.status}):e.jsx(N,{children:"never run"}),e.jsx(H,{label:"",checked:j.enabled,disabled:n===`${j.id}:enabled`,onChange:k=>void h(j,k)}),e.jsx(E,{size:"sm",icon:"play",busy:n===j.id,disabled:j.running,onClick:()=>void x(j),children:"Run now"})]})]},j.id)})})},m||"other")}),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(z,{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:((c==null?void 0:c.runs.length)??0)===0?e.jsx(Q,{columns:6,children:"No task has run yet."}):c==null?void 0:c.runs.map(m=>{var y;return e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:P(m.startedAt),children:ue(m.startedAt)}),e.jsx("td",{children:((y=a.find(j=>j.id===m.taskId))==null?void 0:y.name)??m.taskId}),e.jsx("td",{className:"muted",children:m.trigger}),e.jsx("td",{children:e.jsx(N,{tone:Ve(m.status),children:m.status})}),e.jsx("td",{className:"num muted",children:ve(m.durationMs)}),e.jsx("td",{className:"muted",children:m.error||m.detail||"—"})]},m.id)})})]})})})]})]})}const Cn={id:"",name:"Discord",url:"",enabled:!0,events:[]};function Rn(){const{wrap:s,show:n}=X(),{busy:l,run:t}=Z(),{data:o,error:c,loading:i,reload:r}=G("/admin/api/integrations",{pollMs:6e4}),[d,a]=p.useState(null),[v,x]=p.useState(null),h=(o==null?void 0:o.catalogue)??[],u=(o==null?void 0:o.integrations)??[],f=y=>a({id:y.id,name:y.name,url:"",enabled:y.enabled,events:y.events??[]}),b=()=>t("save",async()=>{if(!d)return;await s(()=>L.post("/admin/api/integrations",d),d.id?"Integration saved.":"Integration added.")&&(a(null),await r())}),g=y=>t("remove",async()=>{await s(()=>L.del(`/admin/api/integrations/${encodeURIComponent(y.id)}`),`${y.name} removed.`),x(null),await r()}),m=y=>t(`test:${y.id}`,async()=>{const j=await s(()=>L.post(`/admin/api/integrations/${encodeURIComponent(y.id)}/test`));j&&n(j.message,j.ok?"ok":"bad"),await r()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Integrations",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(E,{variant:"primary",icon:"plus",onClick:()=>a(Cn),children:"Add a webhook"})}),e.jsx(U,{message:c}),e.jsx(En,{}),e.jsx($n,{}),e.jsx(In,{}),((o==null?void 0:o.dropped)??0)>0?e.jsxs(fe,{tone:"warn",children:[w((o==null?void 0:o.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(B,{}):u.length===0&&!d?e.jsx(C,{title:"Nothing configured",icon:"plug",tone:"note",children:e.jsx(W,{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."})}):u.map(y=>e.jsx(An,{integration:y,catalogue:h,busy:l,onEdit:()=>f(y),onTest:()=>void m(y),onRemove:()=>x(y)},y.id)),d?e.jsx(Tn,{draft:d,catalogue:h,busy:l==="save",onChange:a,onSave:()=>void b(),onCancel:()=>a(null)}):null,v?e.jsx(oe,{title:`Remove ${v.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:l==="remove",onConfirm:()=>void g(v),onCancel:()=>x(null)}):null]})}function En(){const{wrap:s}=X(),{busy:n,run:l}=Z(),{data:t,error:o,loading:c,reload:i}=G("/admin/api/arr-integrations"),r=d=>l("arr-integrations",async()=>{t&&(await s(()=>L.post("/admin/api/arr-integrations",{sonarrEnabled:d.sonarrEnabled??t.sonarrEnabled,radarrEnabled:d.radarrEnabled??t.radarrEnabled}),"Integration settings saved."),await i())});return e.jsxs(C,{title:"Sonarr and Radarr",intro:"Turn either service off without removing its address, API key or request policy. Disabled services are not offered for Memby requests.",icon:"plug",tone:"info",children:[e.jsx(U,{message:o??""}),c?e.jsx(B,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx(H,{label:"Sonarr enabled",hint:t!=null&&t.sonarrConfigured?"Off stops Memby sending or looking up TV requests through Sonarr.":"Sonarr is not configured.",checked:!!(t!=null&&t.sonarrEnabled),disabled:!(t!=null&&t.sonarrConfigured)||n==="arr-integrations",onChange:d=>void r({sonarrEnabled:d})}),e.jsx(H,{label:"Radarr enabled",hint:t!=null&&t.radarrConfigured?"Off stops Memby sending or looking up film requests through Radarr.":"Radarr is not configured.",checked:!!(t!=null&&t.radarrEnabled),disabled:!(t!=null&&t.radarrConfigured)||n==="arr-integrations",onChange:d=>void r({radarrEnabled:d})})]})]})}function $n(){const{wrap:s}=X(),{busy:n,run:l}=Z(),{data:t,error:o,loading:c,reload:i}=G("/admin/api/sonarr-request-policy"),[r,d]=p.useState(0),[a,v]=p.useState(!1);p.useEffect(()=>{t&&(d(t.qualityProfileId),v(t.searchImmediately))},[t]);const x=()=>l("sonarr-request-policy",async()=>{await s(()=>L.post("/admin/api/sonarr-request-policy",{qualityProfileId:r,searchImmediately:a}),"Sonarr TV request policy saved."),await i()}),h=t==null?void 0:t.profiles.find(u=>u.id===r);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:t!=null&&t.configured?"ok":"warn",actions:t!=null&&t.configured?e.jsx(N,{tone:"ok",children:"configured"}):e.jsx(N,{tone:"warn",children:"needs attention"}),footer:e.jsx(E,{variant:"primary",busy:n==="sonarr-request-policy",disabled:c||r<=0,onClick:()=>void x(),children:"Save Sonarr policy"}),children:[e.jsx(U,{message:o??(t==null?void 0:t.error)??""}),c?e.jsx(B,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fields",children:e.jsx(D,{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:r,onChange:u=>d(Number(u.target.value)),disabled:!(t!=null&&t.profiles.length),children:[e.jsx("option",{value:0,children:"Choose a quality profile…"}),t==null?void 0:t.profiles.map(u=>e.jsxs("option",{value:u.id,children:[u.name,u.recommended?" — recommended (720p)":""]},u.id))]})})}),e.jsx(H,{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:a,onChange:v}),h?e.jsxs(fe,{tone:"info",children:["Requested series will use ",e.jsx("b",{children:h.name})," (profile ID ",h.id,"), be monitored using Membys existing all-episodes strategy, and ",a?"start an immediate search.":"not start an immediate search."]}):null]})]})}function In(){const{wrap:s}=X(),{busy:n,run:l}=Z(),{data:t,error:o,loading:c,reload:i}=G("/admin/api/radarr-request-policy"),[r,d]=p.useState(0),[a,v]=p.useState(!1);p.useEffect(()=>{t&&(d(t.qualityProfileId),v(t.searchImmediately))},[t]);const x=()=>l("radarr-request-policy",async()=>{await s(()=>L.post("/admin/api/radarr-request-policy",{qualityProfileId:r,searchImmediately:a}),"Radarr movie request policy saved."),await i()}),h=t==null?void 0:t.profiles.find(u=>u.id===r);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:t!=null&&t.configured?"ok":"warn",actions:t!=null&&t.configured?e.jsx(N,{tone:"ok",children:"configured"}):e.jsx(N,{tone:"warn",children:"needs attention"}),footer:e.jsx(E,{variant:"primary",busy:n==="radarr-request-policy",disabled:c||r<=0,onClick:()=>void x(),children:"Save Radarr policy"}),children:[e.jsx(U,{message:o??(t==null?void 0:t.error)??""}),c?e.jsx(B,{rows:2}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fields",children:e.jsx(D,{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:r,onChange:u=>d(Number(u.target.value)),disabled:!(t!=null&&t.profiles.length),children:[e.jsx("option",{value:0,children:"Choose a quality profile…"}),t==null?void 0:t.profiles.map(u=>e.jsxs("option",{value:u.id,children:[u.name,u.recommended?" — recommended (720p)":""]},u.id))]})})}),e.jsx(H,{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:a,onChange:v}),h?e.jsxs(fe,{tone:"info",children:["Requested films will use ",e.jsx("b",{children:h.name})," (profile ID ",h.id,"), remain monitored, and ",a?"start an immediate search.":"not start an immediate search."]}):null]})]})}function An({integration:s,catalogue:n,busy:l,onEdit:t,onTest:o,onRemove:c}){const i=s.health,r=!i.lastFailure||i.lastSuccess&&i.lastSuccess>i.lastFailure,d=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:r?"ok":"bad",children:r?"delivering":"failing"}):e.jsx(N,{children:"never used"}),e.jsx(E,{size:"sm",icon:"pulse",busy:l===`test:${s.id}`,onClick:o,children:"Test"}),e.jsx(E,{size:"sm",onClick:t,children:"Edit"}),e.jsx(E,{size:"sm",variant:"danger",icon:"trash",onClick:c,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:d.length===0?"None selected — this destination is configured but will never post anything.":d.map(a=>{var v;return((v=n.find(x=>x.type===a))==null?void 0:v.label)??a}).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?P(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:[P(i.lastFailure),i.lastError?` — ${i.lastError}`:""]})]})}):null]}),s.deliveries.length>0?e.jsx(z,{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(a=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",title:P(a.attemptedAt),children:ue(a.attemptedAt)}),e.jsx("td",{className:"muted",children:a.eventType}),e.jsx("td",{children:a.success?e.jsx(N,{tone:"ok",children:a.statusCode||"ok"}):e.jsx(N,{tone:"bad",children:a.error||a.statusCode||"failed"})}),e.jsx("td",{className:"num muted",children:ve(a.durationMs)})]},a.id))})]})}):e.jsx(z,{children:e.jsx("table",{children:e.jsx("tbody",{children:e.jsx(Q,{columns:4,children:"Nothing has been delivered through this webhook yet."})})})})]})}function Tn({draft:s,catalogue:n,busy:l,onChange:t,onSave:o,onCancel:c}){const i=[...new Set(n.map(d=>d.group))],r=(d,a)=>t({...s,events:a?[...s.events,d]:s.events.filter(v=>v!==d)});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(E,{variant:"primary",busy:l,onClick:o,children:s.id?"Save":"Add"}),e.jsx(E,{variant:"quiet",onClick:c,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(D,{label:"Name",hint:"What this destination is called in the console.",children:e.jsx("input",{type:"text",value:s.name,onChange:d=>t({...s,name:d.target.value})})}),e.jsx(D,{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:d=>t({...s,url:d.target.value})})})]}),e.jsx(H,{label:"Enabled",hint:"Off keeps the configuration and stops the posts.",checked:s.enabled,onChange:d=>t({...s,enabled:d})}),i.map(d=>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:d})})}),n.filter(a=>a.group===d).map(a=>e.jsx(H,{label:a.label,hint:a.description,checked:s.events.includes(a.type),onChange:v=>r(a.type,v)},a.type))]},d))]})}function Ln(){var b;const{status:s,error:n,loading:l,reload:t}=se(),{wrap:o}=X(),{busy:c,run:i}=Z(),[r,d]=p.useState(""),[a,v]=p.useState(!1),[x,h]=p.useState(!1),u=!!((b=s==null?void 0:s.maintenance)!=null&&b.enabled);p.useEffect(()=>{var g;!x&&s&&d(((g=s.maintenance)==null?void 0:g.message)??"")},[s,x]);const f=g=>i(g?"on":"off",async()=>{await o(()=>L.post("/admin/api/maintenance",{enabled:g,message:r}),g?"Memby is offline for every television.":"Memby is back online."),v(!1),h(!1),await t()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Maintenance",intro:"Take Memby offline for every television."}),e.jsx(U,{message:n}),l?e.jsx(B,{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:u?"bad":"warn",actions:u?e.jsx(N,{tone:"bad",children:"offline"}):e.jsx(N,{tone:"ok",children:"online"}),footer:e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"danger",disabled:u,onClick:()=>v(!0),children:"Go offline"}),e.jsx(E,{disabled:!u,busy:c==="off",onClick:()=>void f(!1),children:"Bring back online"})]}),children:e.jsx(D,{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:r,placeholder:"Back shortly — upgrading the server",onChange:g=>{d(g.target.value),h(!0)}})})}),a?e.jsx(oe,{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:c==="on",onConfirm:()=>void f(!0),onCancel:()=>v(!1)}):null]})}function Dn(){const{status:s,error:n,loading:l}=se(),t=(s==null?void 0:s.runs)??[];return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Imports",intro:"Catalogue synchronisation history."}),e.jsx(U,{message:n}),l?e.jsx(B,{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.",icon:"sync",tone:"data",children:e.jsx(z,{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:t.length===0?e.jsx(Q,{columns:8,children:"Nothing has been imported yet."}):t.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"nowrap muted",children:P(o.startedAt)}),e.jsx("td",{children:o.kind}),e.jsx("td",{className:"muted",children:o.trigger}),e.jsx("td",{children:e.jsx(N,{tone:o.status==="success"?"ok":o.status==="running"?"warn":"bad",children:o.status})}),e.jsx("td",{className:"num",children:w(o.itemsSeen)}),e.jsx("td",{className:"num",children:w(o.itemsUpserted)}),e.jsx("td",{className:"num",children:w(o.itemsRemoved)}),e.jsx("td",{className:"muted",children:o.error||""})]},o.id||o.startedAt))})]})})})]})}const Be={DEBUG:10,INFO:20,WARN:30,ERROR:40},_e=2e4,qn=5e3,Pn=["component","user","device","client","protocol","method","path","status","duration","version","gateway_version"];function We(s){const n=l=>{const t=Pn.indexOf(l);return t>=0?t:l==="error"?1e3:100};return Object.entries(s).sort((l,t)=>n(l[0])-n(t[0]))}const Fn=s=>s.replace(/_/g," "),On=s=>[s.message,...Object.entries(s.attributes??{}).flat()].join(" ").toLowerCase();function Un(){const[s,n]=p.useState([]),[l,t]=p.useState(0),[o,c]=p.useState(!1),[i,r]=p.useState("INFO"),[d,a]=p.useState(""),[v,x]=p.useState(""),h=p.useRef(0),u=p.useRef(!1),f=p.useRef(null),b=p.useRef(!0),g=p.useCallback(async()=>{if(!(o||u.current)){u.current=!0;try{let k=0,A;do{A=await L.get(`/admin/api/events?after=${h.current}&limit=1000`),h.current=A.next||h.current,A.dropped&&t(M=>M+A.dropped);const T=A.events??[];T.length>0&&n(M=>{const I=[...M,...T];return I.length>_e?I.slice(I.length-_e):I}),k+=1}while(A.hasMore&&k<20);x("")}catch(k){x(k instanceof Error?k.message:String(k))}finally{u.current=!1}}},[o]);p.useEffect(()=>{if(g(),o)return;const k=window.setInterval(()=>void g(),qn);return()=>window.clearInterval(k)},[g,o]);const m=p.useMemo(()=>{const k=Be[i]??20,A=d.trim().toLowerCase();return s.filter(T=>(Be[T.level]??0)>=k&&(!A||On(T).includes(A)))},[s,i,d]),y=m.slice(-2500);p.useLayoutEffect(()=>{const k=f.current;k&&b.current&&(k.scrollTop=k.scrollHeight)},[y.length]);const j=()=>{const k=f.current;k&&(b.current=k.scrollHeight-k.scrollTop-k.clientHeight<50)},R=()=>{const k=new Blob([JSON.stringify(s,null,2)],{type:"application/json"}),A=document.createElement("a");A.href=URL.createObjectURL(k),A.download=`memby-events-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,A.click(),window.setTimeout(()=>URL.revokeObjectURL(A.href),1e3)};return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Server logs",intro:"Structured gateway events as they happen."}),e.jsx(U,{message:v}),e.jsxs(C,{children:[e.jsxs("div",{className:"filters",children:[e.jsx(D,{label:"Level",children:e.jsxs("select",{value:i,onChange:k=>r(k.target.value),children:[e.jsx("option",{value:"DEBUG",children:"Debug and above"}),e.jsx("option",{value:"INFO",children:"Info and above"}),e.jsx("option",{value:"WARN",children:"Warnings and errors"}),e.jsx("option",{value:"ERROR",children:"Errors only"})]})}),e.jsx(D,{label:"Filter",grow:!0,children:e.jsx("input",{type:"search",value:d,placeholder:"Person, television, title, component, path…",onChange:k=>a(k.target.value)})}),e.jsxs("div",{className:"filter-actions",children:[e.jsx(E,{onClick:()=>c(k=>!k),icon:o?"play":"clock",children:o?"Resume":"Pause"}),e.jsx(E,{onClick:()=>{n([]),t(0)},children:"Clear view"}),e.jsx(E,{onClick:R,icon:"download",children:"Export JSON"})]})]}),e.jsxs("div",{className:"logview",ref:f,onScroll:j,role:"log","aria-live":"polite",children:[e.jsxs("div",{className:"loghead","aria-hidden":"true",children:[e.jsx("span",{children:"Time"}),e.jsx("span",{children:"Level"}),e.jsx("span",{children:"Event"}),e.jsx("span",{children:"Details"})]}),y.length===0?e.jsx("p",{className:"empty",children:s.length===0?"Waiting for server events…":"No events match this filter."}):y.map((k,A)=>e.jsxs("div",{className:"logline","data-level":k.level,children:[e.jsxs("time",{title:`Log record ${k.sequence}`,children:[P(k.occurredAt),e.jsxs("small",{children:["#",k.sequence]})]}),e.jsx("span",{className:"lvl",children:k.level}),e.jsx("span",{className:"msg",children:k.message}),e.jsx("span",{className:"attrs",children:e.jsxs("details",{className:"logdetails",children:[e.jsx("summary",{children:We(k.attributes??{}).map(([T,M])=>e.jsxs("span",{children:[e.jsxs("b",{children:[T,"="]}),String(M)," "]},T))}),e.jsxs("dl",{children:[e.jsx("dt",{children:"Log record"}),e.jsx("dd",{children:k.sequence}),We(k.attributes??{}).map(([T,M])=>e.jsxs(p.Fragment,{children:[e.jsx("dt",{children:Fn(T)}),e.jsx("dd",{children:String(M)})]},T))]})]})})]},`${k.occurredAt}:${A}`))]}),e.jsxs("p",{className:"hint",children:[w(s.length)," retained · ",w(m.length)," matching",y.length<m.length?` · showing the latest ${w(y.length)}`:"",l?` · ${w(l)} overwritten before delivery`:"",o?" · paused":""]})]})]})}const ze=["home","movies","shows","favorites","search","recent_searches","genre_browse","for_you","for_you_time","recommendation","continue","latest","my_shows","details","playback","notifications","profiles","settings"];function de(s){const n=String(s||"—").replaceAll("_"," ");return n==="favorites"?"Favourites":n==="abandoned"?"Abandoned / interrupted":n}function Vn(){const[s,n]=p.useState(30),[l,t]=p.useState(""),o=Re(),c=p.useMemo(()=>`/admin/api/journeys${ge({days:s,userId:l})}`,[s,l]),{data:i,error:r,loading:d}=G(c),a=i==null?void 0:i.stats,v=(i==null?void 0:i.users)??[],x=(i==null?void 0:i.actions)??[],h=(i==null?void 0:i.paths)??[],u=h[0],f=p.useMemo(()=>{const b=new Map(((i==null?void 0:i.features)??[]).map(m=>[m.feature,m])),g=new Map(ze.map((m,y)=>[m,y]));return[...new Set([...ze,...b.keys()])].map(m=>({name:m,stat:b.get(m)})).sort((m,y)=>{var R,k;const j=(((R=y.stat)==null?void 0:R.uses)??0)-(((k=m.stat)==null?void 0:k.uses)??0);return j||(g.get(m.name)??Number.MAX_SAFE_INTEGER)-(g.get(y.name)??Number.MAX_SAFE_INTEGER)})},[i==null?void 0:i.features]);return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"User journeys",intro:"How viewers move through Memby, use features and complete flows."}),e.jsx(U,{message:r}),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(D,{label:"Window",children:e.jsxs("select",{value:s,onChange:b=>n(Number(b.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(D,{label:"User",children:e.jsxs("select",{value:l,onChange:b=>{const g=b.target.value;t(g),g&&o(`/admin/journeys/${encodeURIComponent(g)}`)},children:[e.jsx("option",{value:"",children:"All users"}),v.map(b=>e.jsx("option",{value:b.userId,children:b.username||b.userId},b.userId))]})})]}),children:d?e.jsx(B,{rows:1}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:"journeys",value:w(a==null?void 0:a.journeys),icon:"list",tone:"data"},{label:"viewers",value:w(a==null?void 0:a.viewers),icon:"people",tone:"info"},{label:"completion",value:Ce(a==null?void 0:a.completionRate),icon:"check",tone:"ok"},{label:"abandoned",value:w(a==null?void 0:a.abandoned),icon:"alert",tone:"note"},{label:"active now",value:w(a==null?void 0:a.active),icon:"pulse",tone:"info"},{label:"average steps",value:((a==null?void 0:a.averageSteps)??0).toFixed(1),icon:"chart"},{label:"average visit",value:ve(a==null?void 0:a.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:Ce(a==null?void 0:a.completionRate)})]}),e.jsx(Os,{value:(a==null?void 0:a.completed)??0,total:(a==null?void 0:a.journeys)??0}),e.jsxs("p",{children:[w(a==null?void 0:a.completed)," completed · ",w(a==null?void 0:a.abandoned)," abandoned ·"," ",w(a==null?void 0:a.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:u?`${de(u.from)}${de(u.to)}`:"Not enough data"}),e.jsx("p",{children:u?`${w(u.count)} times in this window`:"Journeys will appear here as viewers move through Memby."})]})]})]})}),e.jsxs(re,{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(z,{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:x.length===0?e.jsx(Q,{columns:3,children:"No significant actions in this window."}):x.map(b=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("b",{children:de(b.action)}),e.jsx("span",{className:"table-sub",children:de(b.category)})]}),e.jsx("td",{className:"num",children:w(b.events)}),e.jsx("td",{className:"num",children:w(b.journeys)})]},`${b.category}:${b.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(z,{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:h.length===0?e.jsx(Q,{columns:2,children:"No repeated paths in this window."}):h.map((b,g)=>e.jsxs("tr",{children:[e.jsxs("td",{children:[de(b.from)," ",e.jsx("span",{className:"route-arrow",children:"→"})," ",de(b.to)]}),e.jsx("td",{className:"num",children:w(b.count)})]},`${b.from}:${b.to}:${g}`))})]})})})]}),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(z,{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:b,stat:g})=>{const m=(g==null?void 0:g.uses)??0;return e.jsxs("tr",{children:[e.jsx("td",{children:de(b)}),e.jsx("td",{className:"num",children:w(m)}),e.jsx("td",{className:"muted nowrap",children:g?P(g.lastUsedAt):"—"}),e.jsx("td",{children:m===0?e.jsx(N,{tone:"warn",children:"not used"}):m<3?e.jsx(N,{tone:"note",children:"rare"}):e.jsx(N,{tone:"ok",children:"used"})})]},b)})})]})})}),l?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 he=s=>{const n=String(s||"—").replaceAll("_"," ");return n==="favorites"?"Favourites":n},ds=s=>he((s==null?void 0:s.target)||(s==null?void 0:s.screen)||(s==null?void 0:s.source)||(s==null?void 0:s.feature)),Ke=s=>s.itemName?`${he(s.itemType)} · ${s.itemName}`:s.source&&s.target?`${he(s.source)}${he(s.target)}`:ds(s),Bn=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"?"Started watching":"Requested",stop:"Stopped watching",start:"Started",complete:"Completed"})[s.action]??he(s.action);function _n(s){var l;const n=(l=[...s].reverse().find(t=>t.outcome))==null?void 0:l.outcome;return n==="success"||n==="completed"?{label:he(n),tone:"ok"}:n==="failure"||n==="cancelled"||n==="abandoned"?{label:he(n),tone:"note"}:s.some(t=>t.action==="stop"&&t.category==="playback")?{label:"watched",tone:"ok"}:{label:"left before playback ended",tone:"warn"}}function Wn(s){const n=s.reduce((l,t,o)=>(t.category==="playback"&&t.action==="request"&&l.push(o),l),[]);return n.length===0?[s]:n.map((l,t)=>s.slice(t===0?0:l,n[t+1]??s.length))}function zn(){var d,a;const{userId:s=""}=ke(),n=p.useMemo(()=>`/admin/api/journeys${ge({days:90,userId:s})}`,[s]),{data:l,error:t,loading:o}=G(n),c=((a=(d=l==null?void 0:l.users)==null?void 0:d.find(v=>v.userId===s))==null?void 0:a.username)||s,i=p.useMemo(()=>{const v=new Map;for(const x of(l==null?void 0:l.events)??[])v.set(x.journeyId,[...v.get(x.journeyId)??[],x]);return[...v.values()].map(x=>x.sort((h,u)=>h.sequence-u.sequence)).sort((x,h)=>{var u,f;return(((u=h[0])==null?void 0:u.occurredAt)??"").localeCompare(((f=x[0])==null?void 0:f.occurredAt)??"")})},[l==null?void 0:l.events]),r=i.flatMap(v=>Wn(v).map((x,h)=>{var u;return{events:x,key:`${(u=v[0])==null?void 0:u.journeyId}:${h}`}}));return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:`${c}'s journeys`,intro:"Each app session is shown as the viewing journeys it contains: entry, selection, playback outcome.",crumbs:e.jsx(Y,{className:"crumb",to:"/admin/journeys",children:"Journeys"})}),e.jsx(U,{message:t}),o?e.jsx(B,{}):e.jsx(C,{title:"Viewing journeys",intro:`${i.length} app session${i.length===1?"":"s"} · ${r.length} viewing journey${r.length===1?"":"s"} in the last 90 days.`,icon:"journey",tone:"info",children:e.jsx("div",{className:"visits",children:r.length===0?e.jsx("p",{className:"empty",children:"No journeys recorded for this viewer."}):r.map((v,x)=>{const h=v.events,u=h[0],f=[...h].reverse().find(g=>g.itemName||g.action==="select"||g.category==="playback"&&g.action==="request"),b=_n(h);return e.jsxs("article",{className:"visit",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("b",{children:P(u==null?void 0:u.occurredAt)}),e.jsxs("span",{children:["Journey ",x+1," · ",h.length," recorded steps"]})]}),e.jsx(N,{tone:b.tone,children:b.label})]}),e.jsxs("div",{className:"journey-answers",children:[e.jsxs("div",{className:"journey-answer","data-kind":"entry",children:[e.jsx(ee,{name:"journey"}),e.jsx("span",{children:"Entered from"}),e.jsx("b",{children:ds(u)})]}),e.jsxs("div",{className:"journey-answer","data-kind":"selection",children:[e.jsx(ee,{name:"play"}),e.jsx("span",{children:"Selected"}),e.jsx("b",{children:f?Ke(f):"Nothing selected"})]}),e.jsxs("div",{className:"journey-answer","data-kind":"outcome",children:[e.jsx(ee,{name:b.tone==="ok"?"check":"clock"}),e.jsx("span",{children:"Outcome"}),e.jsx("b",{children:b.label})]})]}),e.jsx("ol",{className:"journey-timeline",children:h.map(g=>e.jsxs("li",{children:[e.jsx("span",{className:"timeline-dot","data-action":g.action}),e.jsxs("div",{children:[e.jsx("b",{children:Bn(g)}),e.jsx("span",{children:Ke(g)})]}),e.jsx("time",{children:P(g.occurredAt)})]},`${g.journeyId}:${g.sequence}`))})]},v.key)})})})]})}function He(s){const n=String(s||"—").replaceAll("_"," ");return n==="favorites"?"Favourites":n==="abandoned"?"Abandoned / interrupted":n}function Kn(){const[s,n]=p.useState(30),{data:l,error:t,loading:o}=G(`/admin/api/analytics?days=${s}`),c=(l==null?void 0:l.rows)??[];return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Row engagement",intro:"Impressions, focus, dwell and selections per launcher row."}),e.jsx(U,{message:t}),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(D,{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:o?e.jsx(B,{rows:1}):e.jsx(z,{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:c.length===0?e.jsx(Q,{columns:8,children:"No events in this window."}):c.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:He(i.rowId)}),e.jsx("td",{className:"muted",children:He(i.rowKind)}),e.jsx("td",{className:"num",children:ve(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:Ce(i.selectRate)}),e.jsx("td",{className:"num",children:w(i.viewers)})]},`${i.rowId}:${i.rowKind}`))})]})})})]})}function Hn(){const[s,n]=p.useState(7),{data:l,error:t,loading:o}=G(`/admin/api/searches?days=${s}`),c=(l==null?void 0:l.terms)??[],i=(l==null?void 0:l.recent)??[],r=l==null?void 0:l.totals;return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Searches",intro:"What the household has been looking for, and what it searched just now."}),e.jsx(U,{message:t}),e.jsx(ne,{tiles:[{label:"searches",value:w((r==null?void 0:r.searches)??0),icon:"search",tone:"info"},{label:"distinct queries",value:w((r==null?void 0:r.queries)??0),icon:"list",tone:"data"},{label:"viewers searching",value:w((r==null?void 0:r.viewers)??0),icon:"people",tone:"note"},{label:"history kept",value:`${(l==null?void 0:l.retentionDays)??30} days`,small:!0,icon:"clock"}]}),o?e.jsx(B,{}):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(D,{label:"Window",children:e.jsxs("select",{value:s,onChange:d=>n(Number(d.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(z,{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:c.length===0?e.jsx(Q,{columns:4,children:"Nothing searched in this window."}):c.map(d=>e.jsxs("tr",{children:[e.jsx("td",{children:d.query}),e.jsx("td",{className:"num",children:w(d.searches)}),e.jsx("td",{className:"num",children:w(d.viewers)}),e.jsx("td",{className:"muted nowrap",children:P(d.lastAt)})]},d.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(z,{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(Q,{columns:3,children:"No searches in this window."}):i.map((d,a)=>e.jsxs("tr",{children:[e.jsx("td",{className:"muted nowrap",children:P(d.occurredAt)}),e.jsx("td",{children:d.username||e.jsx(N,{tone:"warn",children:d.userId||"unknown"})}),e.jsx("td",{children:d.query})]},`${d.occurredAt}:${a}`))})]})})})]})]})}function Ge(s,n){if(n===0)return s>0?"new this week":"no change";const l=Math.round((s-n)/n*100);return`${l>0?"+":""}${l}% vs last week`}function Gn(){const{data:s,error:n,loading:l}=G("/admin/api/views",{pollMs:6e4}),t=(s==null?void 0:s.daily)??[],o=(s==null?void 0:s.hourly)??[];return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Views",intro:"How often people reach Membys home screen. This measures app use, not playback streams."}),e.jsx(U,{message:n}),l?e.jsx(B,{}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{tiles:[{label:Ge((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:Ge((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 household profiles.",icon:"chart",tone:"data",children:e.jsx(z,{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:t.length===0?e.jsx(Q,{columns:3,children:"No home-screen visits yet."}):t.map(c=>e.jsxs("tr",{children:[e.jsx("td",{children:c.label}),e.jsx("td",{className:"num",children:w(c.visits)}),e.jsx("td",{className:"num",children:w(c.viewers)})]},c.label))})]})})}),e.jsx(C,{title:"Today by hour",intro:"Local New Zealand time. Use this to see when the household is opening Memby.",icon:"clock",tone:"info",children:e.jsx(z,{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:o.length===0?e.jsx(Q,{columns:3,children:"No home-screen visits yet today."}):o.map(c=>e.jsxs("tr",{children:[e.jsx("td",{children:c.label}),e.jsx("td",{className:"num",children:w(c.visits)}),e.jsx("td",{className:"num",children:w(c.viewers)})]},c.label))})]})})})]})]})}const Zn=s=>s.mediaType==="episode"?`${s.seriesTitle} S${String(s.seasonNumber).padStart(2,"0")}E${String(s.episodeNumber).padStart(2,"0")}`:s.title;function Jn(){var o;const s=G("/admin/api/media-reports",{pollMs:15e3}),{busy:n,run:l}=Z(),t=(c,i)=>l(`${c.id}-${i}`,async()=>{await L.post(`/admin/api/media-reports/${c.id}/status`,{status:i}),await s.reload()});return e.jsxs(e.Fragment,{children:[e.jsx(O,{title:"Media reports",intro:"Viewer-reported problems and the individual replacement searches they asked Memby to start."}),s.loading?e.jsx(B,{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:(o=s.data)!=null&&o.reports.length?e.jsx(z,{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(c=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("b",{children:Zn(c)}),e.jsx("br",{}),e.jsx("span",{className:"muted",children:c.title})]}),e.jsxs("td",{children:[c.reason.replaceAll("_"," "),c.comment?e.jsxs(e.Fragment,{children:[e.jsx("br",{}),e.jsx("span",{className:"muted",children:c.comment})]}):null]}),e.jsxs("td",{children:[c.reportedByUsername,e.jsx("br",{}),e.jsx("span",{className:"muted",children:c.reportedByDevice||"Unknown device"})]}),e.jsx("td",{children:e.jsx(N,{tone:c.replacementRequested?"note":void 0,children:c.replacementRequested?c.replacementStatus||"Requested":"Not requested"})}),e.jsx("td",{children:e.jsx(N,{tone:c.status==="resolved"?"ok":c.status==="dismissed"?void 0:"warn",children:c.status})}),e.jsx("td",{className:"nowrap muted",children:P(c.createdAt)}),e.jsxs("td",{children:[e.jsx(E,{size:"sm",variant:"quiet",busy:n===`${c.id}-acknowledged`,onClick:()=>void t(c,"acknowledged"),children:"Acknowledge"})," ",e.jsx(E,{size:"sm",variant:"quiet",busy:n===`${c.id}-resolved`,onClick:()=>void t(c,"resolved"),children:"Resolve"})," ",e.jsx(E,{size:"sm",variant:"quiet",busy:n===`${c.id}-dismissed`,onClick:()=>void t(c,"dismissed"),children:"Dismiss"})]})]},c.id))})]})}):e.jsx(W,{children:"No media problems have been reported."})})]})}function Yn(){return e.jsx(O,{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 Xn(){return e.jsx(js,{children:e.jsx($s,{children:e.jsx(Ps,{children:e.jsx(_s,{children:e.jsx(vs,{children:e.jsxs(V,{path:"/admin",element:e.jsx(Vs,{}),children:[e.jsx(V,{index:!0,element:e.jsx(Ws,{})}),e.jsx(V,{path:"activity",element:e.jsx(Ks,{})}),e.jsx(V,{path:"accounts",element:e.jsx(Hs,{})}),e.jsx(V,{path:"accounts/:userId",element:e.jsx(Gs,{})}),e.jsx(V,{path:"accounts/:userId/settings",element:e.jsx(en,{})}),e.jsx(V,{path:"clients",element:e.jsx(nn,{})}),e.jsx(V,{path:"logins",element:e.jsx(an,{})}),e.jsx(V,{path:"devices/:deviceId",element:e.jsx(cn,{})}),e.jsx(V,{path:"library",element:e.jsx(dn,{})}),e.jsx(V,{path:"ratings",element:e.jsx(un,{})}),e.jsx(V,{path:"requests",element:e.jsx(mn,{})}),e.jsx(V,{path:"recommendations",element:e.jsx(pn,{})}),e.jsx(V,{path:"inspector",element:e.jsx(vn,{})}),e.jsx(V,{path:"hero",element:e.jsx(gn,{})}),e.jsx(V,{path:"features",element:e.jsx(fn,{})}),e.jsx(V,{path:"playback",element:e.jsx(yn,{})}),e.jsx(V,{path:"subtitles",element:e.jsx(wn,{})}),e.jsx(V,{path:"updates",element:e.jsx(kn,{})}),e.jsx(V,{path:"tasks",element:e.jsx(Mn,{})}),e.jsx(V,{path:"integrations",element:e.jsx(Rn,{})}),e.jsx(V,{path:"maintenance",element:e.jsx(Ln,{})}),e.jsx(V,{path:"imports",element:e.jsx(Dn,{})}),e.jsx(V,{path:"logs",element:e.jsx(Un,{})}),e.jsx(V,{path:"journeys",element:e.jsx(Vn,{})}),e.jsx(V,{path:"journeys/:userId",element:e.jsx(zn,{})}),e.jsx(V,{path:"views",element:e.jsx(Gn,{})}),e.jsx(V,{path:"engagement",element:e.jsx(Kn,{})}),e.jsx(V,{path:"searches",element:e.jsx(Hn,{})}),e.jsx(V,{path:"media-reports",element:e.jsx(Jn,{})}),e.jsx(V,{path:"overview",element:e.jsx(bs,{to:"/admin",replace:!0})}),e.jsx(V,{path:"*",element:e.jsx(Yn,{})})]})})})})})})}const hs=document.getElementById("root");if(!hs)throw new Error("the console has no root element to render into");Xe(hs).render(e.jsx(p.StrictMode,{children:e.jsx(Xn,{})}));