1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DocumentViewer-EKTVEOm7.js","assets/react-vendor-3j0hp6R8.js","assets/PageOcrRepository-BRlV8zHW.js","assets/DocumentViewer-CNWdf4oM.js","assets/DocumentViewer-in3yE4ie.css","assets/useResearchWorkspaceRepository-BR20tnf5.js","assets/documentSubscriptionReturn-B3VpUFfM.js","assets/index-Bef4-SGX.js","assets/vendor-CQdPkgkm.js","assets/vendor-DghdE1Nh.css","assets/router-vendor-Dg-IODGf.js","assets/icons-vendor-Ct9oFFFD.js","assets/charts-vendor-DRVidz11.js","assets/guides-general-CJN1k0im.js","assets/guides-general-BHvy2NqP.css","assets/index-EqAwUDPb.css"])))=>i.map(i=>d[i]); 2import{r as e,j as t,R as a,c as n}from"./react-vendor-3j0hp6R8.js";import{u as s,a as r,b as i,L as l,N as o,c,d}from"./router-vendor-Dg-IODGf.js";import{C as u,U as h,a as m,L as p,X as g,b as f,S as b,P as x,c as v,F as j,d as y,W as k,e as w,B as N,f as S,g as C,h as R,M as E,i as I,G as _,N as T,j as A,k as O,l as D,m as P,n as L,o as $,p as M,q as U,D as F,r as z,s as q,t as B,u as W,H as V,v as H,w as K,A as G,x as J,I as Y,E as Q,y as X,z as Z,J as ee,T as te,K as ae,O as ne,Q as se,R as re,V as ie,Y as le,Z as oe,_ as ce,$ as de,a0 as ue,a1 as he,a2 as me,a3 as pe,a4 as ge,a5 as fe,a6 as be,a7 as xe,a8 as ve,a9 as je,aa as ye,ab as ke,ac as we,ad as Ne,ae as Se,af as Ce,ag as Re,ah as Ee,ai as Ie,aj as _e,ak as Te,al as Ae,am as Oe,an as De,ao as Pe,ap as
2Le,aq as $e,ar as Me,as as Ue,at as Fe,au as ze,av as qe,aw as Be,ax as We,ay as Ve,az as He,aA as Ke,aB as Ge,aC as Je,aD as Ye,aE as Qe,aF as Xe,aG as Ze,aH as et,aI as tt,aJ as at,aK as nt,aL as st,aM as rt,aN as it,aO as lt,aP as ot,aQ as ct,aR as dt,aS as ut,aT as ht,aU as mt,aV as pt,aW as gt,aX as ft,aY as bt,aZ as xt,a_ as vt,a$ as jt,b0 as yt,b1 as kt,b2 as wt,b3 as Nt,b4 as St,b5 as Ct,b6 as Rt,b7 as Et,b8 as It,b9 as _t,ba as Tt,bb as At,bc as Ot,bd as Dt,be as Pt,bf as Lt,bg as $t,bh as Mt,bi as Ut,bj as Ft,bk as zt,bl as qt,bm as Bt,bn as Wt,bo as Vt,bp as Ht,bq as Kt,br as Gt}from"./icons-vendor-Ct9oFFFD.js";import{a as Jt,P as Yt,H as Qt,s as Xt,b as Zt,u as ea,E as ta,c as aa,S as na,d as sa,e as ra,D as ia,f as la,g as oa,v as ca,h as da,i as ua,K as ha,T as ma,j as pa,k as ga,l as fa,C as ba,m as xa,n as va,o as ja,G as ya}from"./vendor-CQdPkgkm.js";import{R as ka,L as wa,C as Na,X as Sa,Y as Ca,T as Ra,a as Ea,b as Ia,A as _a,c as Ta,B as Aa,d as Oa,P as Da,e as Pa,f as La}from"./charts-vendor-DRVidz11.js";import{g as $a,a as Ma,b as Ua,R as Fa,c as za,d as qa}from"./guides-general-CJN1k0im.js";const Ba={},Wa=function(e,t,a){let n=Promise.resolve();if(t&&t.length>0){let e=function(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),s=a?.nonce||a?.getAttribute("nonce");n=e(t.map(e=>{if((e=function(e){return"/"+e}(e))in Ba)return;Ba[e]=!0;const t=e.endsWith(".css"),a=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${a}`))return;const n=document.createElement("link");return n.rel=t?"stylesheet":"modulepreload",t||(n.as="script"),n.crossOrigin="",n.href=e,s&&n.setAttribute("nonce",s),document.head.appendChild(n),t?new Promise((t,a)=>{n.addEventListener("load",t),n.addEventListener("error",()=>a(new Error(`Unable to preload CSS for ${e}`)))}):void 0}))}function s(e){const t=new Event("vite:preloadError",{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return n.then(t=>{for(const e of t||[])"rejected"===e.status&&s(e.reason);return e().catch(s)})},Va=Object.freeze({cofounder:6,admin:5,employee:4,staff:3,intern:2,editor:1.5,customer:1,guest:0});function Ha(e){const t=Array.isArray(e)?e:e?[e]:[];return[...new Set(t.filter(e=>Object.hasOwn(Va,e)))]}function Ka(e,t){return!!Object.hasOwn(Va,t)&&function(e){const t=Ha(e).map(e=>Va[e]);return t.length?Math.max(...t):-1}(e)>=Va[t]}function Ga(e,t){const a=Ha(e),n=Ha(t);return 0!==a.length&&0!==n.length&&n.some(e=>a.includes(e))}const Ja=Object.freeze(["editor","admin","cofounder"]),Ya=Object.freeze(["admin","cofounder"]),Qa=Object.freeze(["admin","cofounder"]),Xa=Qa;function Za(e){return Ga(e?.roles||[],Ya)}function en(e){return!0===e?.is_active||!0===e?.isActive}const tn=6e4;function an(e,t=6e4,a=Date.now()){const n=function(e){if(!e||"string"!=typeof e)return null;try{const t=e.split(".")[1];if(!t)return null;const a=t.replace(/-/g,"+").replace(/_/g,"/"),n=a.padEnd(4*Math.ceil(a.length/4),"="),s=JSON.parse(atob(n));return Number.isFinite(s.exp)?1e3*s.exp:null}catch(t){return null}}(e);if(!n)return{expiresAt:null,timeUntilExpiry:0,isFresh:!1};const s=n-a;return{expiresAt:n,timeUntilExpiry:s,isFresh:s>t}}const nn={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_FF_ADMIN_WIKIBASE_ENABLED:"true",VITE_INFRASTRUCTURE_HEALTH_ENABLED:"true",VITE_PUBLIC_DOCUMENT_INDEXING_ENABLED:"false",VITE_VERCEL_BRANCH_URL:"tokenworks-git-main-fabdulla1s-projects.vercel.app",VITE_VERCEL_DEPLOYMENT_ID:"dpl_9e4GitEDTmmRPvocKXHT4bKooidz",VITE_VERCEL_ENV:"production",VITE_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"Fabdulla1",VITE_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Fabdulla1",VITE_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #59 from TokenWorks-LLC/feature/dashboard-guidance-upgrade-flow",VITE_VERCEL_GIT_COMMIT_REF:"main",VITE_VERCEL_GIT_COMMIT_SHA:"c60957eb648d9cfcbbfd0659895305b720d5fa60",VITE_VERCEL_GIT_PREVIOUS_SHA:"",VITE_VERCEL_GIT_PROVIDER:"github",VITE_VERCEL_GIT_PULL_REQUEST_ID:"",VITE_VERCEL_GIT_REPO_ID:"1050620961",VITE_VERCEL_GIT_REPO_OWNER:"TokenWorks-LLC",VITE_VERCEL_GIT_REPO_SLUG:"TokenWorks-Site",VITE_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"f29ca3a5618ce8fe/script.js","viewEndpoint":"f29ca3a5618ce8fe/view","eventEndpoint":"f29ca3a5618ce8fe/event","sessionEndpoint":"f29ca3a5618ce8fe/session"}
2,"speedInsights":{"scriptSrc":"a480724e475b6b00/script.js","endpoint":"a480724e475b6b00/vitals"}}',VITE_VERCEL_PROJECT_ID:"prj_nE5Xtyi5l6HKtIvRTMo5FJuiUmiS",VITE_VERCEL_PROJECT_PRODUCTION_URL:"www.tokenworks.ai",VITE_VERCEL_TARGET_ENV:"production",VITE_VERCEL_URL:"tokenworks-fi0qnhgoh-fabdulla1s-projects.vercel.app"};function sn(e=""){return"string"!=typeof e?"":e.trim().replace(/\/+$/,"")}function rn(e,t=function(e=nn){return e?.DEV?"":sn(e?.VITE_API_URL||"")}()){return`${sn(t)}${function(e){if("string"!=typeof e||0===e.trim().length)return"/";const t=e.trim();return t.startsWith("/")?t:`/${t}`}(e)}`}function ln(e){return"string"==typeof e?`${e}::`:`${e?.resourceId||e?.id||""}:${e?.objectId||""}:${e?.folderId||""}`}function on(e){return"string"==typeof e?e:e?.resourceId||e?.id||""}function cn(e){const t=String(e?.packTitle||e?.title||"Untitled Resource").trim(),a=String(e?.targetLabel||"").trim(),n=a&&t.endsWith(` / ${a}`)?t.slice(0,-(a.length+3)):t||"Untitled Resource",s=a?`${n} / ${a}`:n;return{title:n,targetLabel:a,label:e?.targetUnavailable?`${s} (unavailable)`:s}}const dn="employeeMessageDraft:v1:",un=Object.freeze({body:"",resources:Object.freeze([]),pending:null}),hn={},mn=new WeakMap;let pn=0;function gn(){const e="undefined"==typeof window?hn:window;return mn.has(e)||mn.set(e,{snapshots:new Map,fallbackStorage:new Map,listeners:new Map,activeSendTokens:new Set,sendOutcomes:new Map}),mn.get(e)}function fn(e,t){return e&&t?`${dn}${encodeURIComponent(e)}:${encodeURIComponent(t)}`:null}function bn(e){if(!Array.isArray(e))return[];const t=new Set;return e.reduce((e,a)=>{const n=function(e){if(!e||"object"!=typeof e)return null;const t=String(e.resourceId||e.id||"").trim();return t?{id:t,resourceId:t,objectId:e.objectId?String(e.objectId):null,folderId:e.folderId?String(e.folderId):null,targetKind:["resource","object","folder"].includes(e.targetKind)?e.targetKind:"resource",title:String(e.title||"Workspace Resource")}:null}(a);if(!n)return e;const s=ln(n);return t.has(s)||(t.add(s),e.push(n)),e},[])}function xn(e){return e&&"object"==typeof e?{body:"string"==typeof e.body?e.body:"",resources:bn(e.resources),pending:(t=e.pending,t&&"object"==typeof t&&"string"==typeof t.token?{token:t.token,body:"string"==typeof t.body?t.body:"",resources:bn(t.resources)}:null)}:un;var t}function vn(e,t){const a=new Set(t.map(ln));return[...e.filter(e=>!a.has(ln(e))),...t]}function jn(e,t){return t?e?`${e}\n${t}`:t:e}function yn(e,t,a){const n=!t.body&&!t.resources.length&&!t.pending;if(n?a.fallbackStorage.delete(e):a.fallbackStorage.set(e,t),"undefined"!=typeof window)try{n?window.sessionStorage.removeItem(e):window.sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function kn(e,t){t.listeners.get(e)?.forEach(e=>e())}function wn(e,t,a){const n=xn(t);return a.snapshots.set(e,n),yn(e,n,a),kn(e,a),n}function Nn(e,t){if(!e)return un;if(t.snapshots.has(e))return t.snapshots.get(e);let a=xn(function(e,t){if(t.fallbackStorage.has(e))return t.fallbackStorage.get(e);if("undefined"==typeof window)return null;try{const a=window.sessionStorage.getItem(e);if(!a)return null;const n=JSON.parse(a);return t.fallbackStorage.set(e,n),n}catch{try{window.sessionStorage.removeItem(e)}catch{}return null}}(e,t));return a.pending&&!t.activeSendTokens.has(a.pending.token)&&(a=xn({body:jn(a.pending.body,a.body),resources:vn(a.pending.resources,a.resources),pending:null}),yn(e,a,t)),t.snapshots.set(e,a),a}function Sn(e,t,a){const n=fn(e,t);if(!n)return()=>{};const s=gn(),r=s.listeners.get(n)||new Set;return r.add(a),s.listeners.set(n,r),()=>{r.delete(a),r.size||s.listeners.delete(n)}}function Cn(t,a){const n=e.useCallback(e=>Sn(t,a,e),[a,t]),s=e.useCallback(()=>function(e,t){return Nn(fn(e,t),gn())}(t,a),[a,t]);return e.useSyncExternalStore(n,s,()=>un)}function Rn(t,a){const n=e.useCallback(e=>Sn(t,a,e),[a,t]),s=e.useCallback(()=>function(e,t){const a=fn(e,t);return a&&gn().sendOutcomes.get(a)||null}(t,a),[a,t]);return e.useSyncExternalStore(n,s,()=>null)}function En(e,t,a){const n=fn(e,t);if(!n)return un;const s=gn(),r=Nn(n,s);return wn(n,"function"==typeof a?a(r):{...r,...a},s)}const In=["documentLibrary:response:","documentView:"],_n=new Set(["documentLibrary:snapshot:v1"]);function Tn(){if(function(){const e=gn();if(e.activeSendTokens.clear(),e.snapshots.clear(),e.fallbackStorage.clear(),e.sendOutcomes.clear(),"undefined"!=typeof window)try{const e=[];for(let t=0;t<window.sessionStorage.length;t+=1){const a=window.sessionStorage.key(t);a?.startsWith(dn)&&e.push(a)}
2e.forEach(e=>window.sessionStorage.removeItem(e))}catch{}e.listeners.forEach(e=>e.forEach(e=>e()))}(),"undefined"!=typeof window)try{const e=[];for(let t=0;t<window.sessionStorage.length;t+=1){const a=window.sessionStorage.key(t);a&&(_n.has(a)||In.some(e=>a.startsWith(e))||a.startsWith("documentLibrary:snapshot:"))&&e.push(a)}e.forEach(e=>window.sessionStorage.removeItem(e))}catch{}}const An=new Set(["consent_updated","page_view","nav_click","cookie_settings_opened"]),On=new Set(["home","customer_dashboard","document_library","document_viewer","workspace","admin","account","other"]),Dn=new Set(["banner","footer","settings","unknown"]);function Pn(e,t=120){return String(e||"").slice(0,t)}function Ln(e,t){const a=t&&"object"==typeof t&&!Array.isArray(t)?t:{};if("page_view"===e||"nav_click"===e){const e=Pn(a.route,40).trim();return{route:On.has(e)?e:"other"}}if("cookie_settings_opened"===e){const e=Pn(a.source,40).trim();return{source:Dn.has(e)?e:"unknown"}}return{}}async function $n({eventType:e,metadata:t={},consentState:a=null,force:n=!1}={}){if("undefined"==typeof window)return!1;const s=String(e||"").trim().toLowerCase();if(!An.has(s))return!1;const r=function(e){return e&&"object"==typeof e?{analytics:Boolean(e.analytics),personalization:Boolean(e.personalization),marketing:Boolean(e.marketing)}:null}(a);if(!n&&r&&!r.analytics)return!1;const i={event_type:s,metadata:Ln(s,t),consent_state:r};try{return await fetch("/api/analytics/cookie-events",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0,credentials:"same-origin"}),!0}catch{return!1}}const Mn="tw_consent",Un=()=>{try{const e=localStorage.getItem(Mn);if(!e)return null;const t=JSON.parse(e);return Date.now()-t.ts>31104e6||1!==t.v?(localStorage.removeItem(Mn),null):t}catch(e){return localStorage.removeItem(Mn),null}},Fn=(e,t={})=>{const a="string"==typeof t?.source?t.source:"unknown",n={v:1,essential:!0,analytics:Boolean(e.analytics),personalization:Boolean(e.personalization),marketing:Boolean(e.marketing),ts:Date.now()};try{return localStorage.setItem(Mn,JSON.stringify(n)),window.dispatchEvent(new CustomEvent("consentChange",{detail:n})),$n({eventType:"consent_updated",metadata:{source:a,consent_version:1,dnt_enabled:"1"===navigator.doNotTrack||"yes"===navigator.doNotTrack||"1"===navigator.msDoNotTrack||"1"===window.doNotTrack},consentState:n,force:!0}),n}catch(s){return null}},zn=e.createContext(null),qn="initializing",Bn="authenticated",Wn="refreshing",Vn="session_expired",Hn="logged_out";function Kn(e,t=null){const a=t?.code||"REQUEST_FAILED",n=401===e||"INVALID_CSRF"===a||"NO_REFRESH_TOKEN"===a||"INVALID_REFRESH_TOKEN"===a,s=new Error(n?"Your session has expired. Please sign in again.":t?.message||"Request failed");return s.status=e,s.code=n?"SESSION_EXPIRED":a,s.details=t,s.retryable=e>=500||429===e,s.safeMessage=s.message,s}function Gn(){const e=new Error("Auth session changed during request");return e.name="AbortError",e.code="AUTH_SESSION_STALE",e.safeMessage="",e}function Jn({children:a}){const[n,s]=e.useState(null),[r,i]=e.useState(null),[l,o]=e.useState(!0),[c,d]=e.useState(null),[u,h]=e.useState(qn),[m,p]=e.useState(null),[g,f]=e.useState(0),b=e.useRef(null),x=e.useRef(null),v=e.useRef(null),j=e.useRef(qn),y=e.useRef(0),k=e.useRef(!1),w=e.useRef(null),N=e.useRef(null);e.useEffect(()=>{b.current=r},[r]),e.useEffect(()=>{x.current=n},[n]),e.useEffect(()=>{j.current=u},[u]),e.useEffect(()=>{y.current=g},[g]);const S=e.useCallback(()=>{const e=y.current+1;y.current=e,f(e)},[]),C=e.useCallback((e="session_expired")=>{k.current&&j.current===Vn||(k.current=!0,Tn(),N.current=null,j.current=Vn,i(null),s(null),h(Vn),p(e),S())},[S]),R=e.useCallback((e=Hn)=>{k.current=e===Vn,Tn(),N.current=null,j.current=e,i(null),s(null),h(e),e!==Vn&&p(null),S()},[S]),E=e.useCallback(async()=>(v.current||(v.current=(async()=>{try{h(e=>e===qn?qn:Wn);const t=await function(e){const t="undefined"==typeof navigator?null:navigator.locks;return t?.request?t.request("tokenworks-auth-refresh-rotation",e):e()}(()=>{const e=Jt.get("x-csrf-token");return e?fetch(rn("/api/auth/refresh"),{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":e},credentials:"include"}):null});if(!t)return C("missing_csrf"),null;let a=null;try{a=await t.json()}catch(e){a=null}if(!t.ok){if(401===t.status||403===t.status)return C(a?.error?.code||"refresh_rejected"),null;throw Kn(t.status,a?.error)}const n=a?.data?.accessToken||null,r=a?.data?.user||null;if(!n)throw Kn(502,{code:"REFRESH_RESPONSE_INVALID",message:"Token refresh response was invali
2d"});if(i(n),r){const e=String(r.id||"");N.current&&N.current!==e&&Tn(),N.current=e,s(r)}return j.current=Bn,h(Bn),p(null),k.current=!1,d(null),{accessToken:n,user:r}}catch(t){if("SESSION_EXPIRED"===t?.code)return C(t.details?.code||"session_expired"),null;throw h(e=>e===Wn?Bn:e),t}finally{v.current=null}})()),v.current),[C]),I=e.useCallback(async({minimumValidityMs:e=6e4,trigger:t="request"}={})=>{if(j.current===Vn){const e=Kn(401,{code:"SESSION_EXPIRED"});throw e.trigger=t,e}const a=b.current,n=an(a,e);if(n.isFresh)return{accessToken:a,user:x.current,expiresAt:n.expiresAt,refreshed:!1};const s=await E();if(s?.accessToken)return{...s,refreshed:!0};const r=Kn(401,{code:"SESSION_EXPIRED"});throw r.trigger=t,r},[E]),_=e.useCallback(async(e,t={})=>{const a=!0===t._retry,n=!0===t._cacheBypass,s=!0===t._skipFreshSession,r=t._responseType||"json",i=y.current;let l=t._accessToken||null;if(!a&&!s){l=(await I({minimumValidityMs:t._minimumValidityMs??tn,trigger:t._freshnessTrigger||`request:${e}`})).accessToken}const o={"Content-Type":"application/json",...t.headers};Object.keys(o).forEach(e=>{"x-analytics-consent"===e.toLowerCase()&&delete o[e]}),!0===Un()?.analytics&&(o["X-Analytics-Consent"]="granted");const c=l||t._accessToken||b.current;c&&(o.Authorization=`Bearer ${c}`);const d=Jt.get("x-csrf-token");let u;d&&(o["X-CSRF-Token"]=d);try{u=await fetch(rn(e),{...t,_retry:void 0,_accessToken:void 0,_cacheBypass:void 0,_skipFreshSession:void 0,_minimumValidityMs:void 0,_freshnessTrigger:void 0,_responseType:void 0,headers:n?{...o,"Cache-Control":"no-store",Pragma:"no-cache"}:o,cache:n?"no-store":t.cache,credentials:"include"})}catch(p){if(i!==y.current)throw Gn();throw p}if(i!==y.current)throw Gn();let h=null;if(u.ok&&"blob"===r){const e=u.headers.get("content-disposition")||"",t=/filename="?([^";]+)"?/i.exec(e);h={ok:!0,data:{blob:await u.blob(),filename:t?.[1]||null,contentType:u.headers.get("content-type")||"application/octet-stream"}}}else try{h=await u.json()}catch(g){h=null}if(u.ok)return h;if(!n&&304===u.status)return _(e,{...t,_cacheBypass:!0});if(!a&&401===u.status){const a=await E();if(a)return _(e,{...t,_retry:!0,_accessToken:a.accessToken})}if(402===u.status)return{ok:!1,error:h?.error||{code:"SUBSCRIPTION_REQUIRED",message:"Active subscription required"}};const m=Kn(u.status,h?.error||null);throw"SESSION_EXPIRED"===m.code&&C(h?.error?.code||"session_expired"),m},[I,C,E]),T=e.useCallback(async(e,t={})=>{const a=!0===t._skipFreshSession,n=y.current;let s=t._accessToken||null;if(!a){s=(await I({minimumValidityMs:t._minimumValidityMs??tn,trigger:t._freshnessTrigger||`raw-request:${e}`})).accessToken}const r=async a=>{const n={...t.headers};a&&(n.Authorization=`Bearer ${a}`);const s=Jt.get("x-csrf-token");return s&&(n["X-CSRF-Token"]=s),fetch(rn(e),{...t,_retry:void 0,_accessToken:void 0,_skipFreshSession:void 0,_minimumValidityMs:void 0,_freshnessTrigger:void 0,headers:n,credentials:"include"})};let i;try{i=await r(s||t._accessToken||b.current)}catch(c){if(n!==y.current)throw Gn();throw c}if(n!==y.current)throw Gn();if(i.ok)return i;if(401===i.status&&!t._retry){const e=await E();if(e){if(i=await r(e.accessToken),n!==y.current)throw Gn();if(i.ok)return i}}const l=await async function(e){try{const t=await e.json();return t?.error||null}catch(t){return null}}(i),o=Kn(i.status,l);throw"SESSION_EXPIRED"===o.code&&C(l?.code||"session_expired"),o},[I,C,E]),A=e.useCallback(async()=>{try{const e=await _("/api/auth/me"),t=String(e.data.user?.id||"");return N.current&&N.current!==t&&Tn(),N.current=t,s(e.data.user),d(null),e.data.user}catch(e){throw"SESSION_EXPIRED"===e.code?C("session_expired"):s(null),e}},[_,C]);e.useEffect(()=>{!async function(){let e=null;try{const t=await E();e=t,t&&!t.user&&await A()}catch(t){}finally{j.current===qn&&h(e?.accessToken?Bn:Hn),o(!1)}}()},[]),e.useEffect(()=>{if(r)try{const{expiresAt:e,timeUntilExpiry:t}=an(r,0);if(!e)return;const a=Math.max(0,t-6e4),n=setTimeout(async()=>{try{await E()||C("scheduled_refresh_failed")}catch(e){}},a);return()=>clearTimeout(n)}catch(e){}},[r,C,E]),e.useEffect(()=>{if("undefined"==typeof window)return;const e=e=>{j.current!==Vn&&b.current&&(w.current&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{w.current=null,I({minimumValidityMs:tn,trigger:e}).catch(e=>{})},250))},t=()=>{"visible"===document.visibilityState&&e("visibilitychange")},a=()=>e("focus"),n=t=>e(t?.persisted?"pageshow:bfcache":"pageshow");return document.addEventListener("visibilitychange",t),window.addEventListener("focus",a),window.addEventListener("pageshow",n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("focus",a),window.removeEventListener("pageshow",n),w.current&&(window.clearTimeout(w.current),w.current=null)}},[I]);const O=e.useCallback(async(e,t,a,n)=>{try{d(null);const r=await fetch(rn("/api/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:e,password:t,antiBotToken:a,botMeta:n})}),l=await r.json();if(!r.ok){let t=l.error?.message||"Login failed";throw"INVALID_EMAIL"===l.error?.code&&e&&!e.includes(".")&&(t=`Invalid email address. Did you mean ${e}.ai or ${e}.com?`),new Error(t)}return Tn(),N.current=String(l.data.user?.id||""),i(l.data.accessToken),s(l.data.user),j.current=Bn,h(Bn),p(null),k.current=!1,S(),l.data.user}catch(r){throw d(r.message),r}},[S]),D=e.useCallback(async(e,t,a)=>{try{d(null);const n=await fetch(rn("/api/auth/signup"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:e,password:t,name:a})}),r=await n.json();if(!n.ok)throw new Error(r.error?.message||"Signup failed");return Tn(),N.current=String(r.data.user?.id||""),i(r.data.accessToken),s(r.data.user),j.current=Bn,h(Bn),p(null),k.current=!1,S(),r.data.user}catch(n){throw d(n.message),n}},[S]),P=e.useCallback(async()=>{try{const e=Jt.get("x-csrf-token");await fetch(rn("/api/auth/logout"),{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":e||""},credentials:"include"})}catch(e){}finally{R(),d(null)}},[R]),L={user:n,accessToken:r,loading:l,error:c,authStatus:u,sessionExpiredReason:m,authGeneration:g,makeAuthRequest:_,makeAuthenticatedFetch:T,login:O,signup:D,logout:P,refresh:E,ensureFreshSession:I,fetchMe:A,isAuthenticated:!!n,hasRole:e=>Ga(n?.roles||[],e),hasMinimumRole:e=>Ka(n?.roles||[],e),canEditResearchData:()=>function(e){return Ga(e?.roles||[],Ja)}(n),canAccessInternalResearchTools:()=>Za(n),canAccessCommunityPreview:()=>function(e){return Boolean(en(e)&&Ga(e?.roles||[],Qa))}(n),canAccessCommunityMessagingPreview:()=>function(e){return Boolean(en(e)&&Ga(e?.roles||[],Xa))}(n)};return t.jsx(zn.Provider,{value:L,children:a})}function Yn({required:t=!0}={}){const a=e.useContext(zn);if(!a&&t)throw new Error("useAuth must be used within an AuthProvider");return a}const Qn=new Set(["page_view","nav_click","cookie_settings_opened"]),Xn=(e="analytics")=>{const t=Un();return!!t&&Boolean(t[e])},Zn=(e="")=>"/"===e?"home":e.startsWith("/admin")?"admin":e.includes("/documents/")&&e.includes("/view")?"document_viewer":e.startsWith("/documents")||e.includes("tab=documents")?"document_library":e.startsWith("/workspace")||e.startsWith("/employee")?"workspace":e.startsWith("/dashboard")?"customer_dashboard":e.startsWith("/account")||e.startsWith("/settings")?"account":"other",es=(e,t={})=>{const a=String(e||"").trim().toLowerCase();if(!Qn.has(a))return;if(!Xn("analytics"))return;const n=((e,t={})=>
2{if("page_view"===e||"nav_click"===e){const e=t.path||("undefined"!=typeof window?window.location.pathname:"");return{route:Zn(e)}}if("cookie_settings_opened"===e)return{source:["banner","footer","settings"].includes(t.source)?t.source:"unknown"};return{}})(a,t);"undefined"!=typeof window&&window.gtag&&window.gtag("event",a,n),$n({eventType:a,metadata:n,consentState:{analytics:!0}})};function ts({item:a,onNavigate:n,isActive:s,exitBlocked:r=!1,exitBlockDescriptionId:i=null}){const[l,o]=e.useState(!1),[c,d]=e.useState(0),u=e.useRef(null),h=e.useRef(null),m=e.useRef(null),p=e.useRef(null),g=e.useId(),f=e.useCallback(()=>Array.from(h.current?.querySelectorAll('[role="menuitem"]')||[]),[]),b=e.useCallback(e=>{const t=f();if(0===t.length)return;const a=(e+t.length)%t.length;d(a),t[a]?.focus()},[f]),x=e=>{l?b(e):(p.current=e,d(e),o(!0))};return e.useEffect(()=>{if(!l||null===p.current)return;const e=p.current;p.current=null,b(e)},[b,l]),e.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]),t.jsxs("div",{className:"nav-dropdown",onMouseEnter:()=>{u.current&&clearTimeout(u.current),o(!0)},onMouseLeave:()=>{u.current=setTimeout(()=>{o(!1)},150)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||o(!1)},children:[t.jsxs("button",{ref:m,className:"nav-link "+(s?"active":""),onClick:()=>{a.dropdown&&a.dropdown.length>0?l?o(!1):x(0):(es("nav_click",{label:a.name}),n(a.path))},onKeyDown:e=>{"Escape"===e.key?(e.preventDefault(),o(!1)):"ArrowDown"===e.key?(e.preventDefault(),x(0)):"ArrowUp"===e.key&&(e.preventDefault(),x(a.dropdown.length-1))},"aria-expanded":l,"aria-haspopup":"menu","aria-controls":g,children:[a.name,a.hasDropdown&&t.jsx("svg",{className:"dropdown-arrow "+(l?"open":""),width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",children:t.jsx("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),a.hasDropdown&&a.dropdown&&t.jsx("div",{id:g,ref:h,className:"dropdown-menu "+(l?"open":""),role:"menu","aria-hidden":!l,onKeyDown:e=>{const t=f(),a=t.indexOf(document.activeElement);if("Escape"===e.key)return e.preventDefault(),e.stopPropagation(),o(!1),void m.current?.focus();let n=null;"ArrowDown"===e.key?n=a<0?0:a+1:"ArrowUp"===e.key?n=a<0?t.length-1:a-1:"Home"===e.key?n=0:"End"===e.key&&(n=t.length-1),null!==n&&(e.preventDefault(),b(n))},children:a.dropdown.map((e,a)=>t.jsx("button",{className:"dropdown-item"+(r?" route-exit-blocked":""),onClick:()=>(e=>{es("nav_click",{label:e.name});const t=n(e.path);o(!1),!1===t&&m.current?.focus()})(e),role:"menuitem",tabIndex:l&&a===c?0:-1,"aria-disabled":r||void 0,"aria-describedby":i||void 0,children:t.jsxs("div",{className:"dropdown-item-content",children:[t.jsx("span",{className:"dropdown-item-name",children:e.name}),e.description&&t.jsx("span",{className:"dropdown-item-description",children:e.description})]})},e.path))})]})}const as=a.createContext({routeLocation:null,registerRouteExitGuard:()=>()=>{},requestRouteExit:()=>!0,exitBlocked:!1,exitBlockDescriptionId:null});function ns(){const e=globalThis.history?.state?.idx;return Number.isInteger(e)?e:null}function ss(e){return!!e&&Boolean(e.blockExit||(e.isPending?e.isPending():!1===e.confirmable))}function rs(e){return!e?.isDirty||e.isDirty()}function is(e){(e?.isPending||e?.isDirty||!1===e?.confirmable)&&e.onBlocked?.()}function ls({children:e}){const n=s(),l=r(),o=i(),[c,d]=a.useState(null),u=a.useRef(n),h=a.useRef(ns()),m=a.useRef([n.key]),p=a.useRef({active:!1,inFlight:!1,expectedIndex:null,expectedKey:null,fallback:!1}),[g,f]=a.useState(!1),b=a.useRef(null),x=a.useCallback(e=>{const t={...e,token:Symbol(e.id||"route-exit-guard")};return d(t),()=>{d(e=>e?.token===t.token?null:e)}},[]),v=a.useCallback((e=null)=>{const t=function(e){if(!e)return null;try{const t=new URL(e,globalThis.location?.href||"http://localhost/");return{pathname:t.pathname,search:t.search,hash:t.hash}}catch{return null}}(e);return!(c&&(!t||!1!==c.shouldBlockLocation?.(t,n)))||(ss(c)?(c.onBlocked?.(),!1):!rs(c)||(window.confirm(c.message||"Discard your unsaved changes?")?(b.current={id:Symbol("accepted-route-exit"),destination:t,guard:c},!0):(is(c),!1)))},[c,n]);a.useEffect(()=>{if(!c)return;const e=e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const t=e.target.closest?.("a[href]");if(!t||"_blank"===t.target||t.hasAttribute("download"))return;if((t.getAttribute("href")||"").startsWith("#"))return;let a;try{a=new URL(t.href,window.location.href)}catch{return}a.origin===window.location.origin&&(v(`${a.pathname}${a.search}${a.hash}`)||(e.preventDefault(),e.stopPropagation()))};return globalThis.document.addEventListener("click",e,!0),()=>globalThis.document.removeEventListener("click",e,!0)},[c,v]);const j=u.current,y=!1!==c?.shouldBlockLocation?.(n,j),k=Boolean((c&&y||g)&&"POP"===l&&n.key!==j.key)?j:n;a.useEffect(()=>{const e=u.current,t=p.current,a=ns(),s=()=>{t.active=!1,t.inFlight=!1,t.expectedIndex=null,t.expectedKey=null,t.fallback=!1,f(!1)};if(n.key===e.key)return s(),void(h.current=a);const r=m.current,i=r.indexOf(e.key),g=r.indexOf(n.key);if(t.inFlight&&t.fallback&&n.pathname===e.pathname&&n.search===e.search&&n.hash===e.hash)return u.current=n,h.current=a,void s();if("POP"===l&&t.inFlight){if(!(null!==t.expectedIndex&&a===t.expectedIndex||null!==t.expectedKey&&n.key===t.expectedKey))return void c?.onBlocked?.();t.inFlight=!1,t.expectedIndex=null,t.expectedKey=null}if("POP"===l&&(c&&y||t.active)){if(!t.active&&c&&y){const e=ss(c);if(!e){if(!rs(c))return u.current=n,h.current=a,s(),void d(e=>e?.token===c.token?null:e);if(window.confirm(c.message||"Discard your unsaved changes?"))return u.current=n,h.current=a,s(),b.current=null,d(e=>e?.token===c.token?null:e),void c.onAccept?.()}e?c.onBlocked?.():is(c)}return void(()=>
2{if(t.inFlight)return;t.active=!0,f(!0);const n=null===h.current||null===a?0:h.current-a,s=i>=0&&g>=0?i-g:0;if(n){const e=Math.sign(n);t.inFlight=!0,t.expectedIndex=a+e,t.expectedKey=null,t.fallback=!1,globalThis.history.go(e)}else if(s){const e=Math.sign(s);t.inFlight=!0,t.expectedIndex=null,t.expectedKey=r[g+e]||null,t.fallback=!1,o(e)}else t.inFlight=!0,t.expectedIndex=null,t.expectedKey=null,t.fallback=!0,o({pathname:e.pathname,search:e.search,hash:e.hash},{replace:!1})})()}if("PUSH"===l){const e=i>=0?r.slice(0,i+1):[];m.current=[...e,n.key]}else"REPLACE"===l&&i>=0?m.current=r.map((e,t)=>t===i?n.key:e):g<0&&(m.current=[...r,n.key]);u.current=n,h.current=a,s();const x=b.current;var v,j;!x||x.destination&&(v=n,j=x.destination,!Boolean(v&&j&&v.pathname===j.pathname&&v.search===j.search&&v.hash===j.hash))||(b.current=null,d(e=>e?.token===x.guard.token?null:e),x.guard.onAccept?.())},[c,o,l,n,y]);const w=ss(c),N=w&&c.blockedDescriptionId||null,S=a.useMemo(()=>({routeLocation:k,registerRouteExitGuard:x,requestRouteExit:v,exitBlocked:w,exitBlockDescriptionId:N}),[N,w,x,v,k]);return t.jsx(as.Provider,{value:S,children:e})}function os(){return a.useContext(as)}function cs(){const{user:a,logout:n}=Yn(),s=i(),{requestRouteExit:r,exitBlocked:l,exitBlockDescriptionId:o}=os(),[c,d]=e.useState(!1),g=e.useRef(null),f=e.useRef(null);e.useEffect(()=>{function e(e){g.current&&!g.current.contains(e.target)&&d(!1)}function t(e){"Escape"===e.key&&(e.preventDefault(),d(!1),window.setTimeout(()=>f.current?.focus(),0))}if(c)return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)}},[c]);const b=e=>{r(e)&&(d(!1),s(e))};if(!a)return null;return t.jsxs("div",{className:"profile-menu",ref:g,children:[t.jsxs("button",{ref:f,className:"profile-trigger",onClick:()=>d(!c),"aria-label":"Account menu","aria-expanded":c,"aria-haspopup":"true",children:[a.pictureUrl?t.jsx("img",{src:a.pictureUrl,alt:"",className:"profile-avatar"}):t.jsx("div",{className:"profile-avatar profile-avatar-placeholder","aria-hidden":"true",children:(x=a.name||a.email,x?x.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2):"U")}),t.jsx("span",{className:"profile-name",children:a.name||"Account"}),t.jsx(u,{className:"profile-chevron "+(c?"open":""),size:16,"aria-hidden":"true"})]}),c&&t.jsxs("div",{className:"profile-dropdown",children:[t.jsxs("div",{className:"profile-dropdown-header",children:[t.jsx("p",{className:"profile-dropdown-name",children:a.name||"User"}),t.jsx("p",{className:"profile-dropdown-email",children:a.email})]}),t.jsx("div",{className:"profile-dropdown-divider"}),t.jsxs("button",{className:"profile-dropdown-item"+(l?" route-exit-blocked":""),onClick:()=>b("/dashboard?tab=settings"),"aria-disabled":l||void 0,"aria-describedby":o||void 0,children:[t.jsx(h,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:"Profile Settings"})]}),t.jsxs("button",{className:"profile-dropdown-item"+(l?" route-exit-blocked":""),onClick:()=>b("/dashboard?tab=settings§ion=subscription"),"aria-disabled":l||void 0,"aria-describedby":o||void 0,children:[t.jsx(m,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:"Billing & Subscription"})]}),t.jsx("div",{className:"profile-dropdown-divider"}),t.jsxs("button",{className:"profile-dropdown-item profile-dropdown-logout"+(l?" route-exit-blocked":""),onClick:async()=>{if(r("/login")){d(!1);try{await n(),s("/login")}catch(e){s("/login")}}},"aria-disabled":l||void 0,"aria-describedby":o||void 0,children:[t.jsx(p,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:"Logout"})]})]})]});var x}function ds({children:e,variant:a="primary",size:n="medium",onClick:s,disabled:r=!1,ariaLabel:i,type:l="button",className:o="",...c}){const d=`btn btn-${a} btn-${n} ${o}`.trim();return t.jsx("button",{type:l,className:d,onClick:s,disabled:r,"aria-label":i,...c,children:e})}ds.propTypes={children:Yt.node.isRequired,variant:Yt.oneOf(["primary","secondary","tertiary","danger","ghost","icon"]),size:Yt.oneOf(["small","medium","large"]),onClick:Yt.func,disabled:Yt.bool,ariaLabel:Yt.string,type:Yt.oneOf(["button","submit","reset"]),className:Yt.string};const us=[{name:"Home",path:"/",isActive:e=>"/"===e},{name:"Resources",path:"/resources",hasDropdown:!0,isActive:e=>"/resources"===e||e.startsWith("/research")||e.startsWith("/guides")||e.startsWith("/resources/tools")||"/tools"===e,dropdown:[{name:"Resources overview",path:"/resources",description:"Learning paths, guides, datasets, and contextual utilities"},{name:"Research",path:"/research",description:"Publications, projects, and research f
2indings"},{name:"Guides",path:"/guides",description:"Research workflows, playbooks, and tutorials"},{name:"Guide utilities",path:"/resources/tools",description:"Compatibility links to utilities now placed inside guides"}]},{name:"Hub",path:"/hub",hasDropdown:!0,isActive:e=>"/about"===e||e.startsWith("/careers"),dropdown:[{name:"About",path:"/about",description:"Mission, team, and research focus"},{name:"Careers",path:"/careers",description:"Join our research team"}]},{name:"Contact",path:"/contact",isActive:e=>"/contact"===e}],hs=["a[href]","button:not([disabled])","textarea:not([disabled])","input:not([disabled])","select:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),ms=[];let ps=0,gs="",fs=[];function bs(e){return Array.from(e?.querySelectorAll(hs)||[]).filter(e=>!e.inert&&"true"!==e.getAttribute("aria-hidden"))}function xs(){if("undefined"==typeof document)return null;let e=document.getElementById("tokenworks-overlay-root");return e||(e=document.createElement("div"),e.id="tokenworks-overlay-root",document.body.appendChild(e)),e}function vs(){const e=ms.at(-1);ms.forEach(t=>{const a=t.panelRef.current;if(!a)return;const n=t===e;a.inert=!n,a.setAttribute("aria-modal",n?"true":"false"),n?a.removeAttribute("aria-hidden"):a.setAttribute("aria-hidden","true")})}function js(e,t=null){const a=e?.panelRef.current;if(!a)return;const n=t?.isConnected&&a.contains(t)&&t||e.initialFocusRef?.current||bs(a)[0]||a;n?.focus?.()}function ys({isOpen:t,panelRef:a,initialFocusRef:n=null,returnFocusRef:s=null,onRequestClose:r}){const i=e.useRef(r),l=e.useRef(null);return i.current=r,e.useEffect(()=>{if(!t||"undefined"==typeof document)return;const e={panelRef:a,initialFocusRef:n,returnFocusRef:s,previousFocus:s?.current||document.activeElement};l.current=e,ms.push(e),function(){if(0===ps){gs=document.body.style.overflow,document.body.style.overflow="hidden";const e=xs();fs=Array.from(document.body.children).filter(t=>t!==e&&"SCRIPT"!==t.tagName).map(e=>({element:e,wasInert:Boolean(e.inert)})),fs.forEach(({element:e})=>{e.inert=!0})}ps+=1}(),vs(),js(e);const r=t=>{if(ms.at(-1)!==e)return;if("Escape"===t.key)return t.preventDefault(),t.stopPropagation(),void i.current?.("escape");if("Tab"!==t.key)return;const s=bs(a.current);if(!s.length)return t.preventDefault(),void a.current?.focus?.();const r=s[0],l=s.at(-1),o=document.activeElement;!t.shiftKey||o!==r&&o!==n?.current&&a.current?.contains(o)?t.shiftKey||o!==l&&a.current?.contains(o)||(t.preventDefault(),r.focus()):(t.preventDefault(),l.focus())};return document.addEventListener("keydown",r),()=>{document.removeEventListener("keydown",r);const t=ms.lastIndexOf(e);t>=0&&ms.splice(t,1),l.current=null,vs(),ps=Math.max(0,ps-1),0===ps&&(document.body.style.overflow=gs,fs.forEach(({element:e,wasInert:t})=>{e.isConnected&&(e.inert=t)}),fs=[]);const a=ms.at(-1),n=e.returnFocusRef?.current;a?js(a,n||e.previousFocus):n?.isConnected?n.focus?.():e.previousFocus?.isConnected&&e.previousFocus.focus?.()}},[n,t,a,s]),(e="programmatic")=>{const t=l.current;t&&ms.at(-1)===t&&i.current?.(e)}}const ks="mobile-site-nav-exit-block-description";function ws(){const{user:a,hasMinimumRole:r}=Yn(),o=i(),c=s(),{requestRouteExit:d,exitBlocked:u,exitBlockDescriptionId:h}=os(),[m,p]=e.useState(!1),[f,b]=e.useState(new Set),x=e.useRef(null),v=e.useRef(null),j=ys({isOpen:m,panelRef:x,initialFocusRef:v,onRequestClose:()=>p(!1)}),y=e=>m&&u?(d(e),j("blocked-navigation"),!1):!!d(e)&&(o(e),window.scrollTo(0,0),p(!1),!0),k=e=>{e.hasDropdown?(e=>{const t=new Set(f);t.has(e)?t.delete(e):t.add(e),b(t)})(e.path):(es("nav_click",{label:e.name}),y(e.path))};return e.useEffect(()=>{p(!1),b(new Set)},[c.pathname]),t.jsxs("header",{className:"header",children:[t.jsxs("nav",{className:"nav",children:[t.jsxs(l,{to:"/",className:"logo","aria-disabled":u||void 0,"aria-describedby":h||void 0,children:[t.jsx("img",{src:"/tokenworks_logo.png",alt:"TokenWorks LLC",className:"logo-icon"}),t.jsx("span",{className:"logo-text",children:"TokenWorks"})]}),t.jsxs("div",{className:"nav-right desktop-nav",children:[t.jsx("ul",{className:"nav-links",children:us.map(e=>t.jsx("li",{children:e.hasDropdown?t.jsx(ts,{item:e,onNavigate:y,isActive:e.isActive(c.pathname),exitBlocked:u,exitBlockDescriptionId:h}):t.jsx("button",{type:"button",onClick:()=>y(e.path),className:"nav-link "+(e.isActive(c.pathname)?"active":""),"aria-disabled":u||void 0,"aria-describedby":h||void 0,children:e.name})},e.path))}),t.jsx("div",{className:"header-cta-section",children:a?t.jsxs("div",{className:"header-user-section",children:[t.jsx(ds,{variant:"secondary",size:"medium",onClick:()=>
2y("/dashboard"),className:"dashboard-btn","aria-disabled":u||void 0,"aria-describedby":h||void 0,children:"Dashboard"}),r?.("intern")?t.jsx(ds,{variant:"secondary",size:"medium",onClick:()=>y("/dashboard/employee"),className:"dashboard-btn","aria-disabled":u||void 0,"aria-describedby":h||void 0,children:"Workspace"}):null,t.jsx(cs,{})]}):t.jsxs("div",{className:"auth-cta-group",children:[t.jsx(ds,{variant:"secondary",size:"medium",onClick:()=>y("/login"),className:"login-btn","aria-disabled":u||void 0,"aria-describedby":h||void 0,children:"Log in"}),t.jsx(ds,{variant:"primary",size:"medium",onClick:()=>y("/signup"),className:"signup-btn","aria-disabled":u||void 0,"aria-describedby":h||void 0,children:"Sign up"})]})})]}),t.jsxs("div",{className:"mobile-nav",children:[a?t.jsx(cs,{}):t.jsxs("div",{className:"mobile-auth-actions",children:[t.jsx(ds,{variant:"secondary",size:"small",onClick:()=>y("/login"),className:"mobile-auth-btn","aria-disabled":u||void 0,"aria-describedby":h||void 0,children:"Log in"}),t.jsx(ds,{variant:"primary",size:"small",onClick:()=>y("/signup"),className:"mobile-auth-btn","aria-disabled":u||void 0,"aria-describedby":h||void 0,children:"Sign up"})]}),t.jsx("button",{type:"button",className:"mobile-menu-button",onClick:()=>{p(!m)},"aria-label":"Toggle mobile menu","aria-expanded":m,"aria-controls":"mobile-site-nav",children:t.jsxs("span",{className:"hamburger "+(m?"open":""),children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})})]})]}),m&&"undefined"!=typeof document?n.createPortal(t.jsxs("div",{id:"mobile-site-nav",ref:x,className:"mobile-menu-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-site-nav-title","aria-describedby":u?ks:void 0,tabIndex:-1,children:[t.jsxs("div",{className:"mobile-menu-dialog-header",children:[t.jsx("h2",{id:"mobile-site-nav-title",children:"Site navigation"}),t.jsx("button",{ref:v,type:"button",className:"mobile-menu-close",onClick:()=>j("close-button"),"aria-label":"Close mobile menu",children:t.jsx(g,{size:22,"aria-hidden":"true"})})]}),u?t.jsx("p",{id:ks,className:"mobile-menu-exit-block-description",role:"status",children:"Page text is saving. Navigation is temporarily unavailable. Close this menu and choose a destination again after saving finishes."}):null,t.jsxs("ul",{className:"mobile-nav-links",children:[us.map((e,a)=>{const n=f.has(e.path),s=`mobile-site-nav-submenu-${a}`;return t.jsxs("li",{className:"mobile-nav-item",children:[t.jsxs("button",{type:"button",onClick:()=>k(e),className:"mobile-nav-link "+(e.isActive(c.pathname)?"active":""),"aria-expanded":e.hasDropdown?n:void 0,"aria-controls":e.hasDropdown?s:void 0,"aria-disabled":u&&!e.hasDropdown||void 0,"aria-describedby":u&&!e.hasDropdown?ks:void 0,children:[t.jsx("span",{children:e.name}),e.hasDropdown&&t.jsx("svg",{className:"mobile-dropdown-arrow "+(n?"open":""),width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",children:t.jsx("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e.hasDropdown&&e.dropdown&&t.jsx("ul",{id:s,className:"mobile-dropdown-items",hidden:!n,children:e.dropdown.map(e=>t.jsx("li",{children:t.jsxs("button",{type:"button",onClick:()=>(e=>{es("nav_click",{label:e.name}),y(e.path)})(e),className:"mobile-dropdown-item","aria-disabled":u||void 0,"aria-describedby":u?ks:void 0,children:[t.jsx("span",{className:"mobile-dropdown-item-name",children:e.name}),e.description&&t.jsx("span",{className:"mobile-dropdown-item-description",children:e.description})]})},e.path))})]},e.path)}),t.jsx("li",{className:"mobile-cta",children:a?t.jsxs("div",{className:"mobile-auth-cta-group",children:[t.jsx(ds,{variant:"secondary",size:"medium",onClick:()=>y("/dashboard"),className:"mobile-dashboard-btn","aria-disabled":u||void 0,"aria-describedby":u?ks:void 0,children:"Dashboard"}),r?.("intern")?t.jsx(ds,{variant:"secondary",size:"medium",onClick:()=>y("/dashboard/employee"),className:"mobile-dashboard-btn","aria-disabled":u||void 0,"aria-describedby":u?ks:void 0,children:"Worksp
2ace"}):null]}):t.jsxs("div",{className:"mobile-auth-cta-group",children:[t.jsx(ds,{variant:"secondary",size:"medium",onClick:()=>y("/login"),className:"mobile-login-btn","aria-disabled":u||void 0,"aria-describedby":u?ks:void 0,children:"Log in"}),t.jsx(ds,{variant:"primary",size:"medium",onClick:()=>y("/signup"),className:"mobile-signup-btn","aria-disabled":u||void 0,"aria-describedby":u?ks:void 0,children:"Sign up"})]})})]})]}),xs()):null]})}function Ns({onOpenCookieSettings:e}){const a=(new Date).getFullYear();return t.jsx("footer",{className:"footer",children:t.jsxs("div",{className:"container",children:[t.jsxs("div",{className:"footer-content",children:[t.jsxs("div",{className:"footer-section",children:[t.jsxs("div",{className:"footer-logo",children:[t.jsx("img",{src:"/tokenworks_logo.png",alt:"TokenWorks LLC",className:"footer-logo-icon"}),"TokenWorks LLC"]}),t.jsx("p",{className:"footer-description",children:"Research hub for language, cultural heritage, digital scholarship, and knowledge systems."}),t.jsxs("div",{className:"footer-contact",children:[t.jsx("p",{children:"[email protected]"}),t.jsx("p",{children:"St. Augustine, Florida, USA"})]})]}),t.jsxs("div",{className:"footer-section",children:[t.jsx("h3",{children:"Research"}),t.jsxs("ul",{className:"footer-links",children:[t.jsx("li",{children:t.jsx(l,{to:"/research",className:"footer-link",children:"Research & Publications"})}),t.jsx("li",{children:t.jsx(l,{to:"/contact",className:"footer-link",children:"Research Collaboration"})}),t.jsx("li",{children:t.jsx(l,{to:"/guides/wikibase",className:"footer-link",children:"Knowledge Systems"})}),t.jsx("li",{children:t.jsx(l,{to:"/resources",className:"footer-link",children:"Resources"})})]})]}),t.jsxs("div",{className:"footer-section",children:[t.jsx("h3",{children:"Learn"}),t.jsxs("ul",{className:"footer-links",children:[t.jsx("li",{children:t.jsx(l,{to:"/guides",className:"footer-link",children:"Guides"})}),t.jsx("li",{children:t.jsx(l,{to:"/guides/wikibase/docker-install",className:"footer-link",children:"Wikibase Setup"})})]})]}),t.jsxs("div",{className:"footer-section",children:[t.jsx("h3",{children:"About"}),t.jsxs("ul",{className:"footer-links",children:[t.jsx("li",{children:t.jsx(l,{to:"/about",className:"footer-link",children:"About"})}),t.jsx("li",{children:t.jsx(l,{to:"/careers",className:"footer-link",children:"Careers"})}),t.jsx("li",{children:t.jsx(l,{to:"/contact",className:"footer-link",children:"Contact"})}),t.jsx("li",{children:t.jsx(l,{to:"/privacy",className:"footer-link",children:"Privacy Policy"})}),t.jsx("li",{children:t.jsx(l,{to:"/security",className:"footer-link",children:"Security"})}),t.jsx("li",{children:t.jsx("button",{className:"footer-link cookie-sett
2ings-link",onClick:e,type:"button",children:"Cookie settings"})})]})]})]}),t.jsxs("div",{className:"footer-bottom",children:[t.jsxs("p",{className:"footer-copyright",children:["(c) ",a," TokenWorks LLC. All rights reserved."]}),t.jsxs("div",{className:"footer-social",children:[t.jsx("p",{className:"footer-tagline",children:"Research hub for language, cultural heritage, and knowledge systems."}),t.jsx("a",{className:"footer-social-link",href:"https://www.linkedin.com/company/tokenworks-llc",target:"_blank",rel:"noopener noreferrer","aria-label":"TokenWorks on LinkedIn",children:"LinkedIn"})]})]})]})})}function Ss({isOpen:a,onClose:s,title:r,children:i,size:l="medium",showCloseButton:o=!0,closeLabel:c="Close modal",closeOnBackdrop:d=!0,initialFocusRef:u=null,className:h=""}){const m=e.useRef(null),p=e.useId(),g=ys({isOpen:a,panelRef:m,initialFocusRef:u,onRequestClose:s});if(!a)return null;if("undefined"==typeof document)return null;const f=t.jsx("div",{className:"modal-backdrop",onClick:e=>{d&&e.target===e.currentTarget&&g("backdrop")},children:t.jsxs("div",{ref:m,className:`modal modal-${l} ${h}`,role:"dialog","aria-modal":"true","aria-labelledby":r?p:void 0,tabIndex:-1,children:[(r||o)&&t.jsxs("div",{className:"modal-header",children:[r&&t.jsx("h2",{className:"modal-title",id:p,children:r}),o&&t.jsx("button",{type:"button",className:"modal-close",onClick:()=>g("close-button"),"aria-label":c,children:"Ã"})]}),t.jsx("div",{className:"modal-content",children:i})]})});return n.createPortal(f,xs())}function Cs({isOpen:a,onClose:n,onSave:s}){const[r,i]=e.useState({essential:!0,analytics:!1,personalization:!1,marketing:!1}),l=e.useRef(null);e.useEffect(()=>{if(a){const e=Un();i(e?{essential:!0,analytics:e.analytics||!1,personalization:e.personalization||!1,marketing:e.marketing||!1}:{essential:!0,analytics:!1,personalization:!1,marketing:!1})}},[a]);const o=(e,t)=>{i(a=>({...a,[e]:t}))};return t.jsxs(Ss,{isOpen:a,onClose:n,title:"Cookie Preferences",closeLabel:"Close cookie preferences",initialFocusRef:l,className:"cookie-modal",children:[t.jsxs("div",{className:"cookie-modal-body",children:[t.jsx("p",{className:"cookie-modal-lead",children:"Select which categories you want to allow. Essential cookies are always on because the site won't work without them."}),t.jsxs("div",{className:"cookie-categories",children:[t.jsxs("div",{className:"cookie-category",children:[t.jsx("div",{className:"cookie-category-header",children:t.jsxs("label",{className:"cookie-toggle",children:[t.jsx("input",{type:"checkbox",checked:r.essential,disabled:!0,"aria-describedby":"essential-desc"}),t.jsx("span",{className:"toggle-slider disabled"}),t.jsx("span",{className:"category-name",children:"Essential"})]})}),t.jsx("p",{id:"essential-desc",className:"category-description",children:"Required for core functionality (security, basic preferences)."})]}),t.jsxs("div",{className:"cookie-category",children:[t.jsx("div",{className:"cookie-category-header",children:t.jsxs("label",{className:"cookie-toggle",children:[t.jsx("input",{ref:l,type:"checkbox",checked:r.analytics,onChange:e=>o("analytics",e.target.checked),"aria-describedby":"analytics-desc"}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"category-name",children:"Analytics"})]})}),t.jsx("p",{id:"analytics-desc",className:"category-description",children:"Helps us understand site usage to improve performance."})]}),t.jsxs("div",{className:"cookie-category",children:[t.jsx("div",{className:"cookie-category-header",children:t.jsxs("label",{className:"cookie-toggle",children:[t.jsx("input",{type:"checkbox",checked:r.personalization,onChange:e=>o("personalization",e.target.checked),"aria-describedby":"personalization-desc"}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"category-name",children:"Personalization"})]})}),t.jsx("p",{id:"personalization-desc",className:"category-description",children:"Saves your preferences to tailor content."})]}),t.jsxs("div",{className:"cookie-category",children:[t.jsx("div",{className:"cookie-category-header",children:t.jsxs("label",{className:"cookie-toggle",children:[t.jsx("input",{type:"checkbox",checked:r.marketing,onChange:e=>o("marketing",e.target.checked),"aria-describedby":"marketing-desc"}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"category-name",children:"Marketing"})]})}),t.jsx("p",{id:"marketing-desc",className:"category-description",children:"Used to measure campaigns and show relevant content."})]})]})]}),t.jsxs("div",{className:"cookie-modal-footer",children:[t.jsx("button",{className:"cookie-reset-link",onClick:()=>{i({essential:!0,analytics:!1,personalization:!1,marketing:!1})},type:"button",children:"Reset to defaults"}),t.jsxs("div",{className:"cookie-modal-actions",children:[t.jsx("button",{className:"btn-secondary",onClick:n,type:"button",children:"Cancel"}),t.jsx("button",{className:"btn-primary",onClick:()=>{s(r),n()},type:"button",children:"Save choices"})]})]})]})}function Rs({hideSettingsTrigger:a=!1,mobileSettingsTargetId:s=null}){const[r,i]=e.useState(!1),[l,o]=e.useState(!1),[c,d]=e.useState(!1),[u,h]=e.useState(!1),[m,p]=e.useState(null);e.useEffect(()=>{null===Un()?i(!0):d(!0)},[]),e.useEffect(()=>{if(!s)return void p(null);p(null);const e=()=>{const e=document.getElementById(s);p(t=>t===e?t:e)};e();const t=new MutationObserver(e);return t.observe(document.body,{childList:!0,subtree:!0}),()=>t.disconnect()},[s]);const g=e=>()=>{u||(h(!0),setTimeout(()=>h(!1),1e3),e())},b=g(()=>{((e="accept_all")=>
2{Fn({analytics:!0,personalization:!0,marketing:!0},{source:e})})("banner_accept_all"),i(!1),d(!0)}),x=g(()=>{((e="reject_non_essential")=>{Fn({analytics:!1,personalization:!1,marketing:!1},{source:e})})("banner_reject_non_essential"),i(!1),d(!0)}),v=e=>{Fn(e,{source:"banner_customize"}),i(!1),d(!0)},j=()=>{o(!0)};return r?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"cookie-banner-container",role:"dialog","aria-live":"polite","aria-labelledby":"cookie-banner-title",children:t.jsxs("div",{className:"cookie-banner",children:[t.jsxs("div",{className:"cookie-banner-content",children:[t.jsxs("div",{className:"cookie-banner-text",children:[t.jsx("h3",{id:"cookie-banner-title",children:"We use cookies"}),t.jsx("p",{children:"We use cookies to improve your experience, analyze traffic, and personalize content. Choose what to accept."})]}),t.jsxs("div",{className:"cookie-banner-actions",children:[t.jsxs("div",{className:"cookie-banner-buttons",children:[t.jsx("button",{className:"btn-primary",onClick:b,disabled:u,type:"button",children:"Accept all"}),t.jsx("button",{className:"btn-secondary",onClick:x,disabled:u,type:"button",children:"Reject non-essential"}),t.jsx("button",{className:"btn-text",onClick:()=>{o(!0)},type:"button",children:"Customize settings"})]}),t.jsxs("p",{className:"cookie-policy-link",children:["For more information, read our"," ",t.jsx("a",{href:"/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"privacy-link",children:"Privacy Policy"})]})]})]}),c&&t.jsx("button",{className:"cookie-banner-dismiss",onClick:()=>{c&&i(!1)},"aria-label":"Dismiss cookie banner",children:"Ã"})]})}),t.jsx(Cs,{isOpen:l,onClose:()=>o(!1),onSave:v})]}):t.jsxs(t.Fragment,{children:[c&&!a&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"cookie-settings-trigger"+(s?" cookie-settings-trigger--mobile-relocated":""),onClick:j,"aria-label":"Open cookie settings",title:"Cookie settings",children:t.jsx(f,{size:20,"aria-hidden":"true"})}),s&&m?n.createPortal(t.jsx("button",{className:"cookie-settings-trigger cookie-settings-trigger--mobile-inline",onClick:j,"aria-label":"Open cookie settings",title:"Cookie settings",children:t.jsx(f,{size:20,"aria-hidden":"true"})}),m):null]}),t.jsx(Cs,{isOpen:l,onClose:()=>o(!1),onSave:v})]})}function Es(e,t){return String(e||"").slice(0,t)}class Is extends a.Component{constructor(e){super(e),this.state={hasError:!1,error:null,isChunkError:!1},this.chunkReloadTimer=null}static getDerivedStateFromError(e){const t=e?.message?.includes("Failed to fetch dynamically imported module")||e?.message?.includes("Error loading chunk")||e?.message?.includes("Loading chunk")||e?.message?.includes("Expected a JavaScript module");return{hasError:!0,error:e,isChunkError:t}}componentDidCatch(e,t){this.errorInfo=t,this.state.isChunkError&&(this.clearChunkReloadTimer(),this.chunkReloadTimer=setTimeout(()=>{window.location.reload()},1e3))}componentDidUpdate(e){this.props.resetKey!==e.resetKey&&this.state.hasError&&(this.clearChunkReloadTimer(),this.errorInfo=null,this.setState({hasError:!1,error:null,isChunkError:!1}))}componentWillUnmount(){this.clearChunkReloadTimer()}clearChunkReloadTimer(){null!=this.chunkReloadTimer&&(clearTimeout(this.chunkReloadTimer),this.chunkReloadTimer=null)}render(){return this.state.hasError?this.state.isChunkError?t.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"50vh",padding:"2rem",textAlign:"center"},children:[t.jsx("h2",{children:"Loading updated version..."}),t.jsx("p",{children:"Please wait, the page will reload automatically."}),t.jsx("div",{style:{marginTop:"1rem",width:"40px",height:"40px",border:"4px solid #f3f3f3",borderTop:"4px solid #007bff",borderRadius:"50%",animation:"spin 1s linear infinite"}})]}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"50vh",padding:"2rem",textAlign:"center"},children:[t.jsx("h2",{children:"Something went wrong"}),t.jsx("p",{children:"Please try refreshing the page or click the button below to reload."}),t.jsxs("div",{style:{display:"flex",gap:"1rem",marginTop:"1.5rem"},children:[t.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"0.5rem 1rem",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Refresh Page"}),t.jsx("button",{onClick:()=>{try{const a=(e=this.state.error,t=this.errorInfo,{message:Es(e?.message,1e3),stack:Es(e?.stack,3e3),componentStack:Es(t?.componentStack,3e3),pagePath:`${window.location.pathname}${window.location.search}`,capturedAt:(new Date).toISOString()});sessionStorage.setItem("feedback_error_context",JSON.stringify(a)),window.location.assign("/dashboard?tab=feedback")}catch{window.location.assign("/dashboard?tab=feedback")}var e,t},style:{padding:"0.5rem 1rem",backgroundColor:"#e53e3e",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Report this error"})]})]}):this.props.children}}function _s({message:e="Loading...",minHeight:a="50vh",color:n="var(--text-muted)",className:s="",style:r={}}){return t.jsx("div",{className:s,style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:a,fontSize:"1.1rem",color:n,...r},children:e})}const Ts=({children:a,fallback:n,resetKey:s})=>{const r=t.jsx(_s,{color:"#666"});return t.jsx(Is,{resetKey:s,children:t.jsx(e.Suspense,{fallback:n||r,children:a})})},As=e.createContext(null);function Os({children:a}){const[n,s]=e.useState([]),r=e.useCallback(e=>{s(t=>t.filter(t=>t.id!==e))},[]),i=e.useCallback(e=>{if(!e?.message)return;const t=`${Date.now()}-${Math.random().toString(16).slice(2)}`,a={id:t,type:e.type||"info",message:e.message,description:e.description||"",duration:Number.isFinite(e.duration)?e.duration:4e3};s(e=>[...e,a]),a.duration>0&&window.setTimeout(()=>r(t),a.duration)},[r]),l=e.useMemo(()=>i,[i]);return t.jsxs(As.Provider,{value:l,children:[t.jsx("div",{className:"toast-stack",role:"status","aria-live":"polite",children:n.map(e=>t.jsxs("div",{className:`toast toast-${e.type}`,children:[t.jsxs("div",{className:"toast-body",children:[t.jsx("div",{className:"toast-message",children:e.message}),e.description&&t.jsx("div",{className:"toast-description",children:e.description})]}),t.jsx("button",{className:"toast-close",onClick:()=>r(e.id),"aria-label":"Dismiss",children:"Ã"})]},e.id))}),a]})}function Ds(){const t=e.useContext(As);if(!t)throw new Error("useToast must be used within ToastProvider");return t}const Ps=e.createContext(null);function Ls({children:a}){const[n,s]=e.useState(null),r=e.useCallback(e=>
2new Promise(t=>{s({title:e?.title||"Please confirm",message:e?.message||"Are you sure? This action cannot be undone.",confirmLabel:e?.confirmLabel||"Confirm",cancelLabel:e?.cancelLabel||"Cancel",confirmVariant:e?.confirmVariant||"primary",surface:"workspace"===e?.surface?"workspace":"legacy",resolve:t})}),[]),i=e=>{n?.resolve&&n.resolve(e),s(null)},l=e.useMemo(()=>r,[r]);return t.jsxs(Ps.Provider,{value:l,children:[a,t.jsxs(Ss,{isOpen:Boolean(n),onClose:()=>i(!1),title:n?.title,showCloseButton:!1,className:"confirm-modal"+("workspace"===n?.surface?" confirm-modal--workspace":""),children:[t.jsx("div",{className:"confirm-message",children:"string"==typeof n?.message?t.jsx("p",{children:n.message}):n?.message}),t.jsxs("div",{className:"confirm-actions",children:[t.jsx(ds,{variant:"secondary",onClick:()=>i(!1),children:n?.cancelLabel}),t.jsx(ds,{variant:n?.confirmVariant,onClick:()=>i(!0),children:n?.confirmLabel})]})]})]})}function $s(){const t=e.useContext(Ps);if(!t)throw new Error("useConfirm must be used within ConfirmProvider");return t}const Ms=[{word:"Ø§ÙØ¹Ø±Ø¨ÙØ©",lang:"ar",meaning:"Arabic"},{word:"×¢×ר×ת",lang:"he",meaning:"Hebrew"},{word:"ÜܪܡÜÜ",lang:"syr",meaning:"Aramaic"},{word:"á ááá",lang:"am",meaning:"Amharic"},{word:"Ù
Ø¹Ø±ÙØ©",lang:"ar",meaning:"knowledge"},{word:"×עת",lang:"he",meaning:"knowledge"},{word:"tokenization",lang:"en",meaning:"text processing"},{word:"morphology",lang:"en",meaning:"word structure"},{word:"Ø«ÙØ§ÙØ©",lang:"ar",meaning:"culture"},{word:"תר××ת",lang:"he",meaning:"culture"},{word:"semantics",lang:"en",meaning:"meaning study"},{word:"ontology",lang:"en",meaning:"knowledge structure"}],Us=()=>t.jsxs("div",{className:"soft-constellations",children:[t.jsx("div",{className:"constellation-background"}),t.jsx("div",{className:"floating-words",children:Ms.map((e,a)=>t.jsx("div",{className:`floating-word lang-${e.lang} word-${a}`,title:`${e.word} (${e.meaning})`,children:e.word},a))})]});function Fs(e){return e?`${e} | TokenWorks`:"TokenWorks | Research Hub for Language and Cultural Heritage"}function zs({title:e,description:a,canonicalPath:n,robots:s="index,follow"}){const r=a||"TokenWorks is a research hub for language, cultural heritage, digital scholarship, knowledge systems, and low-resource language research.",i=n?`https://www.tokenworks.ai${n}`:null;return t.jsxs(Qt,{children:[t.jsx("title",{children:Fs(e)}),t.jsx("meta",{name:"description",content:r}),t.jsx("meta",{name:"robots",content:s}),t.jsx("meta",{property:"og:title",content:Fs(e)}),t.jsx("meta",{property:"og:description",content:r}),i?t.jsx("link",{rel:"canonical",href:i}):null]})}function qs({eyebrow:e,title:a,description:n,align:s="center",className:r="",actions:i=null}){return t.jsxs("header",{className:`public-section-header public-section-header-${s} ${r}`.trim(),children:[e?t.jsx("p",{className:"public-section-eyebrow",children:e}):null,t.jsx("h2",{children:a}),n?t.jsx("p",{className:"public-section-description",children:n}):null,i?t.jsx("div",{className:"public-section-actions",children:i}):null]})}function Bs({items:e}){return t.jsx("div",{className:"trust-signal-grid",role:"list",children:e.map(e=>t.jsxs("article",{className:"trust-signal-card",role:"listitem",children:[t.jsx("div",{className:"trust-signal-icon","aria-hidden":"true",children:e.icon}),t.jsx("h3",{children:e.title}),t.jsx("p",{children:e.description})]},e.title))})}function Ws({kicker:e,title:a,subtitle:n,meta:s,buttons:r=[],tabs:i,align:l="center"}){const o=Array.isArray(s)?s.filter(Boolean):s?[s]:[];return t.jsx("section",{className:"section-hero",children:t.jsx("div",{className:"hero-gradient",children:t.jsxs("div",{className:`container hero-content hero-content-${l}`,children:[e&&t.jsx("p",{className:"hero-kicker",children:e}),t.jsx("h1",{className:"hero-title",children:a}),n&&t.jsx("p",{className:"hero-subtitle",children:n}),o.length>0&&t.jsx("ul",{className:"hero-meta-row","aria-label":"Page metadata",children:o.map((e,a)=>t.jsx("li",{children:e},`${e}-${a}`))}),r.length>0&&t.jsx("div",{className:"hero-actions",children:r.map((e,a)=>{const n=`btn btn-${e.variant||"primary"} hero-action-btn`;return e.href?t.jsx("a",{className:n,href:e.href,target:e.external?"_blank":void 0,rel:e.external?"noopener noreferrer":void 0,children:e.text},`${e.text}-${a}`):t.jsx("button",{type:"button",className:n,onClick:e.onClick,children:e.text},`${e.text}-${a}`)})}),i&&t.jsx("div",{className:"hero-tabs",children:i})]})})})}
2function Vs({title:e,subtitle:a,error:n,errorId:s,success:r,successId:i,children:l,footer:o}){return t.jsx("div",{className:"auth-page",children:t.jsx("div",{className:"auth-container",children:t.jsxs("div",{className:"auth-card",children:[e?t.jsx("h1",{children:e}):null,a?t.jsx("p",{className:"auth-subtitle",children:a}):null,n?t.jsx("div",{id:s,className:"auth-error",role:"alert",children:n}):null,r?t.jsx("div",{id:i,className:"auth-success",role:"status",children:r}):null,l,o?t.jsx("div",{className:"auth-footer",children:o}):null]})})})}function Hs({label:e,htmlFor:a,className:n="form-group",helperText:s=null,helperId:r,helperClassName:i,afterField:l=null,children:o}){return t.jsxs("div",{className:n,children:[e?t.jsx("label",{htmlFor:a,children:e}):null,o,l,s?t.jsx("small",{id:r,className:i,children:s}):null]})}function Ks({children:e,variant:a="primary",className:n="",...s}){const r=`auth-button auth-button-${a} ${n}`.trim();return t.jsx("button",{className:r,...s,children:e})}const Gs=e=>[".zip",".tar.gz",".py",".js",".json",".csv",".txt",".ttl",".rdf",".owl",".xml",".xlsx",".xls",".pdf",".doc",".docx",".sql",".sh",".bat",".cypher",".yml",".yaml",".ps1"].some(t=>e.toLowerCase().endsWith(t));function Js({children:e,icon:a,title:n,meta:s,body:r,primary:i,secondary:l,className:o=""}){const c=null!=e,d=Boolean(a||n||s||r||i||l);return t.jsx("div",{className:`card${i||l?" card--actionable":""} ${o}`,children:c?e:d?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"card-header",children:[a&&t.jsx("div",{className:"card-icon","aria-hidden":"true",children:a}),t.jsxs("div",{className:"card-title-section",children:[t.jsx("h3",{className:"card-title",children:n}),s&&t.jsx("div",{className:"card-meta",children:s})]})]}),r&&t.jsx("p",{className:"card-body",children:r}),(i||l)&&t.jsxs("div",{className:"card-actions",children:[i&&t.jsx("a",{href:i.href,className:"card-action card-action--primary","aria-label":i.label,children:i.label}),l&&t.jsx("a",{href:l.href,className:"card-action card-action--secondary "+(1===l.label.length?"card-action--icon":""),"aria-label":l.title||l.label,title:l.title||l.label,onClick:e=>{l&&l.href&&!l.external&&Gs(l.href)&&(e.preventDefault(),(async(e,t=null)=>{try{if(e.startsWith("http://")||e.startsWith("https://")){const a=document.createElement("a");return a.href=e,a.download=t||e.split("/").pop(),a.target="_blank",a.rel="noopener noreferrer",document.body.appendChild(a),a.click(),void document.body.removeChild(a)}const a=await fetch(e);if(!a.ok)throw new Error(`Failed to download file: ${a.status} ${a.statusText}`);const n=await a.blob(),s=window.URL.createObjectURL(n),r=document.createElement("a");r.href=s,r.download=t||e.split("/").pop(),document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>window.URL.revokeObjectURL(s),100)}catch(a){window.open(e,"_blank","noopener,noreferrer")}})(l.href))},download:!(l.external||!Gs(l.href))||void 0,target:l.external?"_blank":void 0,rel:l.external?"noopener noreferrer":void 0,children:l.label})]})]}):null})}function Ys({children:e,roles:a=null,minimumRole:n=null}){const{user:r,loading:i,authStatus:c,sessionExpiredReason:d,hasRole:u,hasMinimumRole:h}=Yn(),m=s();if(i||"initializing"===c)return t.jsx(_s,{minHeight:"60vh"});if(!r||"session_expired"===c||"logged_out"===c)return t.jsx(o,{to:"/login",state:{from:m,reason:"session_expired"===c?"session_expired":d},replace:!0});const p=a&&!u(a),g=n&&!h(n);return p||g?t.jsx("div",{className:"route-denied",children:t.jsxs(Js,{className:"route-denied-card",children:[t.jsx("h2",{className:"route-denied-title",children:"Access denied"}),t.jsx("p",{className:"route-denied-message",children:"You do not have permission to view this page. If you think you should, ask your TokenWorks administrator to review your access."}),t.jsxs("div",{className:"route-denied-actions",children:[t.jsx(ds,{onClick:()=>window.history.back(),children:"Go back"}),t.jsx(l,{className:"btn btn-secondary btn-medium",to:"/dashboard",children:"Go to your dashboard"})]})]})}):e}const Qs=Object.freeze(["Extracted document text and research tools","Bookmarks, personal folders, and eligible uploads"]);function Xs({onSubscriptionChange:a,documentAccessContext:n,embedded:s=!1}
2={}){const{isAuthenticated:r,makeAuthRequest:i}=Yn(),[l,o]=e.useState([]),[c,d]=e.useState(null),[u,h]=e.useState("USD"),[m,p]=e.useState(!0),[g,f]=e.useState(null),[v,j]=e.useState(null),[y,k]=e.useState(null),[w,N]=e.useState(!1),[S,C]=e.useState(!1),[R,E]=e.useState(!1),I=e.useCallback(async()=>{p(!0),j(null),k(null);const[e,t]=await Promise.allSettled([i("/api/stripe/plans"),i("/api/stripe/subscription-status")]);if("fulfilled"===e.status&&e.value?.ok){const t=e.value;t.data?.unavailable?(o([]),j("Subscription plans are temporarily unavailable.")):o(Array.isArray(t.data?.plans)?t.data.plans:[]),h(t.data?.displayCurrency||"USD")}else{const t="rejected"===e.status?e.reason?.message:e.value?.error?.message;j(t||"Subscription plans could not be loaded.")}if("fulfilled"===t.status&&t.value?.ok)d(t.value.data?.subscription||null),N(!0);else{const e="rejected"===t.status?t.reason?.message:t.value?.error?.message;k(e||"Subscription status could not be loaded.")}p(!1)},[i]);e.useEffect(()=>{r&&I()},[r,I]);if(!r)return t.jsx("div",{className:"subscription-manager",children:t.jsx(Js,{children:t.jsx("p",{children:"Please log in to manage your subscription."})})});if(m&&!w)return t.jsx("div",{className:"subscription-manager",children:t.jsx("div",{className:"loading",children:"Loading subscription data..."})});const _=c&&["active","trialing"].includes(c.status),T=er(c?.plan?.interval||c?.interval),A=c?.plan?.audience||c?.audience,O=function(e){const t=new Map(e.map(e=>[e.id,ar(e)])),a=new Map;for(const n of e){const e="student"===n.audience?"student":"regular",s=`audience-${e}`;a.has(s)||a.set(s,{key:s,audience:e,label:"student"===e?"Student":"Regular",benefits:Qs,variants:[]});const r=t.get(n.id)||er(n.interval||n.billingInterval);a.get(s).variants.push({plan:n,billingCycle:r})}return Array.from(a.values()).map(e=>({...e,variants:e.variants.sort((e,t)=>{const a=tr(e.billingCycle)-tr(t.billingCycle);return 0!==a?a:Number(e.plan.price?.cents||0)-Number(t.plan.price?.cents||0)})})).sort((e,t)=>{if(e.audience!==t.audience)return"regular"===e.audience?-1:1;return Math.min(...e.variants.map(e=>Number(e.plan.price?.cents||0)))-Math.min(...t.variants.map(e=>Number(e.plan.price?.cents||0)))}).map(e=>({...e,variants:e.variants.map(e=>{let t="Billed monthly with full research library access.";return"annual"===e.billingCycle&&(t="student_annual"===e.plan.planKey?"Billed annually - equivalent to $5/month.":"Billed annually."),{...e,billingNote:t}}),description:"student"===e.audience?"Student pricing is honor-system based.":"Standard research library membership pricing."}))}(l),D=s?"h2":"h1",P=s?"h3":"h2",L=s?"h4":"h3";return t.jsxs("div",{className:"subscription-manager"+(s?" subscription-manager--embedded":""),children:[t.jsx(D,{className:"subscription-manager-title",children:s?"Choose a plan to continue":"Subscription Management"}),g&&t.jsx("div",{className:"error-banner",children:g}),y?t.jsxs("div",{className:"error-banner",role:"alert",children:[t.jsx("strong",{children:"Subscription status unavailable."})," ",y," ",t.jsx(ds,{variant:"secondary",onClick:I,disabled:m,children:"Retry"})]}):null,v?t.jsxs("div",{className:"error-banner",role:"alert",children:[t.jsx("strong",{children:"Plan catalog unavailable."})," ",v]}):null,w&&c&&t.jsxs("section",{className:"current-subscription",children:[t.jsx(P,{children:"Current Plan"}),t.jsx(Js,{children:t.jsxs("div",{className:"sm-card sm-current-plan",children:[t.jsxs("div",{className:"sm-card-header",children:[t.jsx("div",{className:"sm-card-icon","aria-hidden":"true",children:t.jsx(b,{size:20})}),t.jsxs("div",{className:"sm-card-title-section",children:[t.jsx(L,{className:"sm-card-title",children:c.plan?.name||c.plan_name||"Subscribed"}),t.jsx("div",{className:"sm-card-meta",children:nr(c)})]})]}),sr(c)&&t.jsx("p",{className:"sm-status-message",children:sr(c)}),t.jsxs("div",{className:"sm-card-actions",children:[t.jsx(ds,{variant:"primary",onClick:async()=>{try{C(!0),f(null);const e=await i("/api/stripe/portal",{method:"POST"});if(!e?.ok)throw new Error(e?.error?.message||"Failed to open billing portal");window.location.href=e.data.portalUrl}catch(e){f(e.message),C(!1)}},disabled:S,children:"Manage Billing"}),_&&c.cancel_at_period_end&&t.jsx(ds,{variant:"primary",onClick:async()=>{try{C(!0),f(null);const e=await i("/api/stripe/reactivate",{method:"POST"});if(!e?.ok)throw new Error(e?.error?.message||"Failed to reactivate subscription");await I(),"function"==typeof a&&a()}catch(e){f(e.message)}finally{C(!1)}},disabled:S,children:"Resume Subscription"}),_&&!c.cancel_at_period_end&&t.jsx(ds,{variant:"danger",onClick:()=>{E(!0)},disabled:S,children:"Cancel Subscription"})]})]})})]}),w&&!v&&(!_||l.length>0)&&t.jsxs("section",{className:"available-plans","data-currency":u,children:[t.jsx(P,{children:_?"Change Plan":"Available plans"}),"EUR"===u&&t.jsx("p",{className:"sm-currency-note",children:"Prices shown in approximate EUR. Checkout is processed in USD."}),O.map(e=>t.jsxs("div",{className:"plan-type-group",children:[t.jsxs("div",{className:"plan-type-header",children:[t.jsx("h3",{children:e.label}),t.jsx("p",{children:e.description})]}),t.jsx("ul",{className:"feature-list sm-shared-benefits",children:e.benefits.map(e=>t.jsx("li",{children:e},e))}),t.jsx("div",{className:"plans-grid plans-grid--type",children:e.variants.map(({plan:s,billingCycle:r,billingNote:l})=>{const o=(d=s.id,!!(u=c)&&(u.plan_id===d||u.plan?.id===d));var d,u;const h=function({isCurrent:e,hasActiveSubscription:t,billingCycle:a,currentBilling
2Cycle:n,audience:s,currentAudience:r}){if(e)return"Current Plan";if(!t)return"Subscribe";if(n&&a!==n)return"annual"===a?"Switch to Annual":"Switch to Monthly";if(r&&s!==r)return"student"===s?"Switch to Student":"Switch to Regular";return"Switch Plan"}({isCurrent:o,hasActiveSubscription:_,billingCycle:r,currentBillingCycle:T,audience:e.audience,currentAudience:A});return t.jsx(Js,{children:t.jsxs("div",{className:"sm-card sm-plan-card",children:[t.jsxs("div",{className:"sm-card-header",children:[t.jsx("div",{className:"sm-card-icon","aria-hidden":"true",children:s.isPopular?t.jsx(b,{size:20}):t.jsx(x,{size:20})}),t.jsxs("div",{className:"sm-card-title-section",children:[t.jsx(L,{className:"sm-card-title",children:s.name}),t.jsxs("div",{className:"sm-card-meta",children:[s.price.isApproximate?"~":"",s.price.formatted," /",Zs(r)]}),t.jsx("span",{className:"sm-cycle-chip",children:(m=r,"annual"===m?"Annual billing":"Monthly billing")})]})]}),t.jsxs("div",{className:"sm-card-body",children:[s.description&&t.jsx("p",{children:s.description}),t.jsx("p",{className:"sm-plan-note",children:l})]}),t.jsx("div",{className:"sm-card-actions",children:t.jsx(ds,{variant:"primary",onClick:()=>_&&!o?(async e=>{try{C(!0),f(null);const t=await i("/api/stripe/change-plan",{method:"POST",body:JSON.stringify({planKey:e.planKey})});if(!t?.ok)throw new Error(t?.error?.message||"Plan change failed");await I(),"function"==typeof a&&a()}catch(t){f(t.message)}finally{C(!1)}})(s):(async e=>{try{C(!0),f(null);const t=await i("/api/stripe/checkout",{method:"POST",body:JSON.stringify({planKey:e.planKey,...n?{documentAccess:{reason:n.reason,capability:n.capability,...n.documentId?{documentId:n.documentId}:{}}}:{}})});if(!t?.ok)throw new Error(t?.error?.message||"Checkout failed");window.location.href=t.data.checkoutUrl}catch(t){f(t.message),C(!1)}})(s),disabled:S||o,children:h})})]})},s.id);var m})})]},e.key)),0===O.length&&t.jsx(Js,{children:t.jsx("p",{children:"No plans are currently available. Please check back shortly."})})]}),t.jsxs(Ss,{isOpen:R,onClose:()=>{S||E(!1)},title:"Cancel Subscription?",size:"small",children:[t.jsx("p",{children:"Are you sure you want to cancel your subscription? You will keep access until the end of the current billing period."}),t.jsxs("div",{className:"sm-modal-actions",children:[t.jsx(ds,{variant:"secondary",onClick:()=>E(!1),disabled:S,children:"Keep Subscription"}),t.jsx(ds,{variant:"danger",onClick:async()=>{try{C(!0),f(null);const e=await i("/api/stripe/cancel",{method:"POST"});if(!e?.ok)throw new Error(e?.error?.message||"Failed to cancel subscription");E(!1),await I(),"function"==typeof a&&a()}catch(e){f(e.message)}finally{C(!1)}},disabled:S,children:S?"Canceling...":"Yes, Cancel"})]})]})]})}function Zs(e){const t=String(e||"").toLowerCase();return"year"===t||"annual"===t||"annually"===t?" year":"month"===t||"monthly"===t?" month":t?` ${t}`:""}function er(e){const t=String(e||"").toLowerCase();return"year"===t?"annual":"monthly"}function tr(e){return"monthly"===e?1:"annual"===e?2:3}function ar(e){return er(e?.interval||e?.billingInterval)}function nr(e){if(!e.current_period_end)return"";const t=new Date(e.current_period_end),a=new Date,n=Math.max(0,Math.ceil((t-a)/864e5));return e.cancel_at_period_end?`Ends ${t.toLocaleDateString()} (${n} days)`:`Renews ${t.toLocaleDateString()} (${n} days)`}function sr(e){if(!e)return null;if(e.cancel_at_period_end&&e.current_period_end){return`Your subscription will end on ${new Date(e.current_period_end).toLocaleDateString()}. You can resume it anytime before then.`}switch(e.status){case"past_due":return"Your last payment failed. Update your payment method via Manage Billing to restore access.";case"unpaid":return"Your subscription is unpaid. Access has been suspended until payment is resolved.";case"incomplete":return"Your subscription requires payment confirmation. Please complete checkout.";case"incomplete_expired":return"Your initial payment was not completed in time. Please subscribe again.";case"canceled":return"Your subscription has been canceled.";default:return null}}const rr=Date.parse("2026-10-05T00:00:00Z"),ir=Object.freeze({overview:{id:"welcome",title:"Your research starts here",text:"Find documents, read available original PDFs, and manage your account here.",topic:"getting-started"},documents:{id:"documents",title:"Find your next document",text:"Search the library, then open a re
2cord to review its information and available PDF.",topic:"find-documents"},viewer:{id:"viewer",title:"Read at your own pace",text:"Use the page and zoom controls to explore the original PDF. Extracted text and personal library tools depend on your access.",topic:"read-pdfs"},uploads:{id:"uploads",title:"Submit a PDF for review",text:"Choose your PDFs, add optional details, and follow their review status here.",topic:"upload-pdfs"},subscription:{id:"subscription",title:"Choose your billing option",text:"Regular and Student offer the same functionality. Choose Monthly or Annual; current prices appear below.",topic:"account-billing"},text:{id:"text",title:"Explore extracted text",text:"A research plan adds extracted text and split PDF/text reading. Your available original PDF stays readable.",topic:"read-pdfs",promotional:!0}});const lr=new Map,or=new Map,cr=e=>`dashboardGuidance:v1:${e}`;function dr(e){const t=lr.get(e)||{disabled:!1,optedIn:!1,dismissed:[],snoozeUntil:0};if(!e)return t;try{const a=JSON.parse(window.localStorage.getItem(cr(e))||"null");return a&&"object"==typeof a?{disabled:!0===a.disabled,optedIn:!0===a.optedIn,dismissed:Array.isArray(a.dismissed)?a.dismissed.filter(e=>"string"==typeof e):[],snoozeUntil:Number(a.snoozeUntil)||0}:t}catch{return t}}function ur(e,t){if(e){lr.set(e,t);try{window.localStorage.setItem(cr(e),JSON.stringify(t))}catch{}window.dispatchEvent(new Event("tokenworks-guidance-preferences"))}}function hr(e){if(!or.has(e)){let t;try{t=JSON.parse(window.sessionStorage.getItem(`${cr(e)}:session`)||"null")}catch{}or.set(e,{automatic:Number(t?.automatic)||0,promotional:Number(t?.promotional)||0})}return or.get(e)}function mr(){const e=document.activeElement;return Boolean(document.querySelector('[aria-modal="true"], [data-guidance-blocker], .cookie-consent, .consent-banner, .cookie-banner-container, [role="alert"]')||e?.matches('input, textarea, select, [contenteditable="true"]')||window.getSelection()?.toString())}function pr(){const{user:a}=Yn(),n=i(),[s,r]=e.useState(()=>
2dr(a?.id));return e.useEffect(()=>{const e=()=>r(dr(a?.id));return e(),window.addEventListener("tokenworks-guidance-preferences",e),()=>window.removeEventListener("tokenworks-guidance-preferences",e)},[a?.id]),a?.id?t.jsxs("section",{className:"guidance-controls","aria-label":"Dashboard tips",children:[t.jsxs("div",{children:[t.jsx("h2",{children:"Dashboard tips"}),t.jsx("p",{children:"Optional pointers as you explore. Preferences apply to this browser."})]}),t.jsxs("div",{className:"guidance-actions",children:[t.jsx("button",{type:"button",onClick:()=>{ur(a?.id,{...s,disabled:!1,optedIn:!0,dismissed:[]}),n("/dashboard?tab=overview",{state:{guidanceTour:!0,guidanceTourAccountId:a.id}})},children:"Show tips again"}),t.jsx("button",{type:"button",onClick:()=>ur(a?.id,{...s,disabled:!s.disabled,optedIn:!0}),children:s.disabled?"Turn on tips":"Turn off tips"})]})]}):null}function gr({surface:a,ready:n=!0,lockedText:r=!1,onUpgrade:o,blocked:c=!1}){const{user:d}=Yn(),u=s(),h=new URLSearchParams(u.search).has("checkout"),[m,p]=e.useState(null),f=i(),[b,x]=e.useState(null),[v,j]=e.useState(null),y=v?.accountId===d?.id?v?.step??null:null,k=e.useCallback(e=>{j(null!==e&&d?.id?{accountId:d.id,step:e}:null)},[d?.id]),w=e.useRef(d?.id);e.useEffect(()=>{w.current=d?.id,p(null),j(null),x(null),N.current=null},[d?.id]);const N=e.useRef(null),S=e.useRef(null),C=e.useCallback(()=>{if(m){const e=dr(d?.id);ur(d?.id,{...e,dismissed:m.promotional?e.dismissed:[...new Set([...e.dismissed,m.id])],...m.promotional?{snoozeUntil:Date.now()+6048e5}:{}})}p(null),k(null)},[m,d?.id,k]);return e.useEffect(()=>{if(null!==y)return;if(p(null),!d?.id||!n||c||h)return;const e=`${d.id}:${u.key}:${a}`,t=dr(d.id),s="viewer"===a&&r&&t.dismissed.includes("viewer")?ir.text:ir[a];if(!s)return;const i=window.setTimeout(()=>{const t=dr(d.id),n=hr(d.id);if(s.promotional&&(t.snoozeUntil>Date.now()||n.promotional>=1))return;if(t.disabled||t.dismissed.includes(s.id)||!t.optedIn&&!function(e,t=Date.now()){const a=Date.parse(e);return Number.isFinite(a)&&a>=rr&&a<=t&&t-a<12096e5}(d.createdAt)||n.automatic>=2||N.current===e||mr())return;const r=document.querySelector(`[data-guidance-target="${a}"]`);r&&r.getClientRects().length&&(N.current=e,function(e,t=!1){const a=hr(e);a.automatic+=1,t&&(a.promotional+=1);try{window.sessionStorage.setItem(`${cr(e)}:session`,JSON.stringify(a))}catch{}}(d.id,s.promotional),p(s))},2500);return()=>window.clearTimeout(i)},[d?.id,d?.createdAt,u.key,a,n,c,r,y,h]),e.useEffect(()=>{const e=e=>{e.detail?.accountId===d?.id&&r&&n&&!c&&!mr()&&(e.preventDefault(),p(ir.text),k(null))};return window.addEventListener("tokenworks-guidance-locked-text",e),()=>window.removeEventListener("tokenworks-guidance-locked-text",e)},[d?.id,r,n,c,k]),e.useEffect(()=>{if(!m)return;const e=e=>{"Escape"!==e.key||document.querySelector('[aria-modal="true"]')||C()},t=()=>{if(mr()&&!S.current?.contains(document.activeElement))return void x(null);const e=document.querySelector(`[data-guidance-target="${a}"]`),t=e?.getBoundingClientRect();if(!t||!e.getClientRects().length||window.innerWidth<768)return void x(null);const n=Math.min(340,window.innerWidth-32),s=S.current?.getBoundingClientRect().height||240,r=t.bottom+12;r+s>window.innerHeight-16||t.top<0?x(null):x({left:Math.max(16,Math.min(t.left,window.innerWidth-n-16)),top:r})};t();const n=()=>{!S.current?.contains(document.activeElement)&&mr()&&p(null)};document.addEventListener("focusin",n),document.addEventListener("selectionchange",n),window.addEventListener("keydown",e),window.addEventListener("resize",t),window.addEventListener("scroll",t,!0);const s=new MutationObserver(()=>{document.querySelector('[aria-modal="true"], [data-guidance-blocker], [role="alert"]')&&p(null)});return s.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["aria-modal"]}),()=>{document.removeEventListener("focusin",n),document.removeEventListener("selectionchange",n),window.removeEventListener("keydown",e),window.removeEventListener("resize",t),window.removeEventListener("scroll",t,!0),s.disconnect()}},[m,a,d?.id,C]),e.useEffect(()=>{const e=d?.id&&u.state?.guidanceTourAccountId===d.id&&!dr(d.id).disabled,t=u.state?.guidanceTourStep;e&&Number.isInteger(t)&&t>=0&&t<=2?k(t):e&&u.state?.guidanceTour?k(0):k(null)},[u.key,u.state,d?.id,k]),e.useEffect(()=>{null!==y&&p(ir[["overview","documents","subscription"][y]])},[y]),e.useEffect(()=>{const e=()=>{dr(d?.id).disabled&&(p(null),k(null))};return window.addEventListener("tokenworks-guidance-preferences",e),()=>window.removeEventListener("tokenworks-guidance-preferences",e)},[d?.id,k]),d?.id&&w.current===d.id&&m&&!c&&n&&!h?t.jsxs("aside",{ref:S,className:"dashboard-guidance"+(b?" dashboard-guidance--anchored":""),style:b||void 0,"aria-label":m.title,children:[t.jsx("button",{className:"guidance-close",type:"button","aria-label":"Dismiss tip",onClick:C,children:t.jsx(g,{size:18,"aria-hidden":"true"})}),t.jsx("h2",{children:m.title}),t.jsx("p",{children:m.text}),t.jsxs("div",{className:"guidance-actions",children:[m.promotional?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>{p(null),o?.()},children:"View plans"}),t.jsx("button",{type:"button",onClick:C,children:"Not now"})]}):null!==y?t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:()=>
2{if(2===y)return void C();const e=y+1;k(e),f(1===e?"/dashboard?tab=documents":"/dashboard?tab=settings§ion=subscription",{state:{guidanceTourStep:e,guidanceTourAccountId:d.id}})},children:[" ",2===y?"Finish tour":"Next tip"]}),t.jsx("button",{type:"button",onClick:C,children:"Skip tour"})]}):"welcome"===m.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>{const e=dr(d?.id);ur(d?.id,{...e,optedIn:!0,dismissed:[...new Set([...e.dismissed,"welcome"])]}),k(0)},children:"Show me around"}),t.jsx("button",{type:"button",onClick:C,children:"Skip"})]}):t.jsx("button",{type:"button",onClick:C,children:"Got it"}),t.jsx(l,{to:`/dashboard?tab=help&topic=${m.topic}`,onClick:()=>{p(null),k(null)},children:"Learn more"})]})]}):null}function fr({isOpen:a,onClose:s,title:r="Menu",side:i="left",closeLabel:l="Close",panelId:o,classNames:c={},children:d}){const u=e.useRef(null),h=e.useRef(null),m=e.useId(),p=ys({isOpen:a,panelRef:u,initialFocusRef:h,onRequestClose:s});if(!a||"undefined"==typeof document)return null;const f=c.overlay||`side-drawer-overlay side-drawer-overlay--${i}`,b=c.panel||`side-drawer side-drawer--${i}`,x=t.jsx("div",{className:f,onClick:e=>{e.target===e.currentTarget&&p("backdrop")},children:t.jsxs("div",{id:o,ref:u,className:b,role:"dialog","aria-modal":"true","aria-labelledby":m,tabIndex:-1,children:[t.jsxs("div",{className:c.header||"side-drawer-header",children:[t.jsx("h2",{id:m,ref:h,tabIndex:-1,children:r}),t.jsx("button",{type:"button",className:c.closeButton||"side-drawer-close",onClick:()=>p("close-button"),"aria-label":l,children:t.jsx(g,{size:20,"aria-hidden":"true"})})]}),t.jsx("div",{className:c.body||"side-drawer-body",children:d})]})});return n.createPortal(x,xs())}const br=Object.freeze(["overview","documents","uploads","feedback","help","settings"]),xr="overview",vr=new Set(br),jr="/dashboard",yr=Object.freeze(["/research-feed","/researchers","/following","/research-workspaces","/research-notifications","/community/messages"]);function kr(e,t){return e===t||e.startsWith(`${t}/`)}function wr(e,t){const a=t?.pathname||"",n=t?.search||"";return e.tab?a===jr&&function(e){const t=new URLSearchParams(e||"").get("tab");return t&&vr.has(t)?t:xr}(n)===e.tab:e.matchPaths?e.matchPaths.some(e=>kr(a,e)):kr(a,e.path)}function Nr({isInternal:e=!1,canUseCommunityPreview:t=!1,isAdmin:a=!1}={}){return[{id:"workspace",label:null,items:[{id:"overview",label:"Overview",icon:v,tab:"overview",visible:!0},{id:"documents",label:"Documents",icon:j,tab:"documents",visible:!0},{id:"uploads",label:"Uploads",icon:y,tab:"uploads",visible:!0},{id:"tools",label:"Tools",icon:k,path:"/studio",visible:!0},{id:"settings",label:"Settings",icon:w,tab:"settings",visible:!0}]},{id:"internal",label:"Internal",items:[{id:"employee-workspace",label:"Workspace",icon:N,path:"/dashboard/employee",visible:e},{id:"community",label:"Community",icon:S,path:"/research-feed",matchPaths:yr,visible:t},{id:"admin",label:"Admin Panel",icon:C,path:"/admin",visible:a}]},{id:"support",label:null,placement:"footer",items:[{id:"help",label:"Help",icon:R,tab:"help",visible:!0},{id:"feedback",label:"Feedback",icon:E,tab:"feedback",visible:!0}]}].map(e=>({...e,items:e.items.filter(e=>e.visible).map(e=>{return{...e,to:e.tab?(t=e.tab,t===xr?jr:`${jr}?tab=${t}`):e.path};var t})})).filter(e=>e.items.length>0)}function Sr({location:a,capabilities:n,onNavigate:s=null,collapsed:r=!1,ariaLabel:i="Primary application navigation"}){const o=`dashboard-nav-${e.useId().replaceAll(":","")}`,c=Nr(n),d=c.filter(e=>"footer"!==e.placement),u=c.filter(e=>"footer"===e.placement),h=e=>{const n=`${o}-${e.id}`;return t.jsxs("div",{className:`sidebar-nav-group sidebar-nav-group--${e.id}`,children:[e.label?t.jsx("h2",{className:"sidebar-nav-group-label",id:n,children:e.label}):null,t.jsx("ul",{className:"sidebar-nav-list","aria-labelledby":e.label?n:void 0,children:e.items.map(e=>{const n=e.icon,r=wr(e,a);return t.jsx("li",{children:t.jsxs(l,{to:e.to,className:"sidebar-nav-item "+(r?"active":""),"aria-current":r?"page":void 0,onClick:s||void 0,children:[t.jsx("span",{className:"sidebar-nav-icon","aria-hidden":"true",children:t.jsx(n,{size:18})}),t.jsx("span",{className:"sidebar-nav-label",children:e.label})]})},e.id)})})]},e.id)};return t.jsxs("nav",{className:"sidebar-nav"+(r?" sidebar-nav--collapsed":""),"aria-label":i,children:[t.jsx("div",{className:"sidebar-nav-body",children:d.map(h)}),u.length?t.jsx("div",{className:"sidebar-nav-footer",children:u.map(h)}):null]})}const Cr="/api/employee/notifications",Rr="tokenworks:employee-conversation-read",Er="tokenworks:employee-workspace-update-read";function Ir(e){return"undefined"==typeof window||"function"!=typeof e?()=>{}:(window.addEventListener(Rr,e),()=>window.removeEventListener(Rr,e))}function _r(e){const t="number"==typeof e?e:e&&"object"==typeof e?e.unreadCount??e.unread:null;return Number.isSafeInteger(t)&&t>=0?t:null}function Tr(){return Object.assign(new Error("Notification state could not be reconciled after mark-read."),{code:"NOTIFICATION_RECONCILIATION_FAILED",safeMessage:"Notifications were marked read, but the latest notification state could not be refreshed."})}function Ar(){const{makeAuthRequest:t,hasMinimumRole:a}=Yn(),[n,s]=e.useState([]),[r,i]=e.useState(0),[l,o]=e.useState(!1),[c,d]=e.useState(null),[u,h]=e.useState(!1),[m,p]=e.useState(!1),[g,f]=e.useState(!1),[b,x]=e.useState(!1),v=a?.("intern"),j=e.useRef(null),y=e.useRef(null),k=e.useRef(null),w=e.useRef(null),N=e.useRef(!1),S=e.useRef(null),C=e.useRef(0),R=e.useRef(0),E=e.useRef(0),I=e.useRef(0),_=e.useRef(0),T=e.useRef(0),A=e.useRef(0),O=e.useRef(!1),D=e.useRef(!1),P=e.useRef(!0);e.useEffect(()=>(P.current=!0,()=>{P.current=!1,w.current=null,N.current=!1}),[]);const L=e.useCallback(e=>{if("EMPLOYEE_WORKSPACE_SCHEMA_NOT_READY"===e?.code)return h(!0),O.current=!0,void i(0);d(e)},[]),$=e.useCallback(async()=>
2{if(!v)return null;if(k.current){const e=await k.current;return null===e?null:{unread:e}}if(N.current)return S.current?.()??null;if(j.current)return j.current;const e=++E.current;return C.current=e,j.current=(async()=>{d(null);try{const a=await t("/api/employee/notifications/count"),n=a?.data||{};return!P.current||e<I.current?null:(I.current=e,e>=T.current&&(T.current=e,i(Number(n.unread)||0)),h(!1),O.current=!1,n)}catch(a){return!P.current||e<I.current||(I.current=e,L(a)),null}finally{A.current=Date.now(),C.current===e&&(j.current=null)}})(),j.current},[L,t,v]),M=e.useCallback(async()=>{if(!v)return null;if(y.current)return y.current;const e=++E.current;return R.current=e,y.current=(async()=>{const a=N.current;o(!0),a||d(null);try{const n=await t(Cr),r=n?.data||{},l=_r(r);return!P.current||e<_.current?null:Array.isArray(r.notifications)&&null!==l?(_.current=e,s(r.notifications),e>=T.current&&(T.current=e,i(l)),h(!1),O.current=!1,d(null),N.current&&(N.current=!1,x(!1)),p(!0),D.current=!0,l):(_.current=e,a?d(Tr()):L(Object.assign(new Error("Notification list response was invalid."),{code:"NOTIFICATION_LIST_INVALID",safeMessage:"Notifications could not be loaded."})),null)}catch(n){return!P.current||e<_.current||(_.current=e,a?d(Tr()):L(n)),null}finally{A.current=Date.now(),P.current&&R.current===e&&o(!1),R.current===e&&(y.current=null)}})(),y.current},[L,t,v]);S.current=M;const U=e.useCallback(async()=>v?D.current?M():$():null,[M,$,v]),F=e.useCallback(async()=>{if(!v)return null;N.current=!0,x(!0);const e=++E.current;R.current=e,I.current=e,_.current=e,T.current=e;const a=(async()=>{o(!0),d(null);try{const a=await t(Cr),n=a?.data||{},r=_r(n);return!P.current||e<_.current?null:Array.isArray(n.notifications)&&null!==r?(_.current=e,s(n.notifications),e>=T.current&&(T.current=e,i(r)),h(!1),O.current=!1,d(null),N.current=!1,x(!1),p(!0),D.current=!0,r):(d(Tr()),null)}catch{return!P.current||e<_.current||(_.current=e,d(Tr())),null}finally{A.current=Date.now(),P.current&&R.current===e&&o(!1),R.current===e&&(y.current=null),k.current===a&&(k.current=null)}})();return y.current=a,k.current=a,a},[t,v]),z=e.useCallback(()=>{v&&!O.current&&("undefined"!=typeof document&&"hidden"===document.visibilityState||Date.now()-A.current<5e3||$())},[$,v]),q=e.useCallback(async(e=[],a=!1,n=null)=>{if(!v||!P.current||w.current)return null;const s={};w.current=s,P.current&&f(!0),d(null);try{return await t("/api/employee/notifications/read",{method:"POST",body:JSON.stringify({notificationIds:e,all:a})}),P.current&&w.current===s?(n?.(),await F()):null}catch(r){return P.current&&w.current===s?"EMPLOYEE_WORKSPACE_SCHEMA_NOT_READY"===r.code?(h(!0),O.current=!0,null):(d(r),null):null}finally{w.current===s&&(w.current=null,P.current&&f(!1))}},[t,F,v]),B=e.useCallback((e=null)=>q([],!0,e),[q]);return e.useEffect(()=>{$()},[$]),e.useEffect(()=>{if(!v||"undefined"==typeof window)return;const e=()=>z(),t=()=>{"visible"===document.visibilityState&&z()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",t);const a=setInterval(z,6e4);return()=>{window.removeEventListener("focus",e),document.removeEventListener("visibilitychange",t),clearInterval(a)}},[z,v]),e.useEffect(()=>{if(!v)return;let e=!0;const t=()=>{const t=D.current||Boolean(y.current),a=y.current||j.current,n=++E.current;I.current=n,_.current=n,T.current=n,(async()=>{a&&await a,e&&P.current&&(R.current>n?y.current&&await y.current:t?await M():await $())})()},a=Ir(t);return window.addEventListener(Er,t),()=>{e=!1,a(),window.removeEventListener(Er,t)}},[M,$,v]),e.useEffect(()=>{if(v)return;const e=++E.current;I.current=e,_.current=e,T.current=e,C.current=0,R.current=0,j.current=null,y.current=null,k.current=null,w.current=null,N.current=!1,s([]),i(0),o(!1),f(!1),x(!1),d(null),h(!1),p(!1),D.current=!1,O.current=!1},[v]),{visible:v,notifications:n,unread:r,loading:l,error:c,unavailable:u,listLoaded:m,mutationPending:g,recoveryPending:b,loadList:M,refreshCount:$,refresh:U,markRead:q,markAllRead:B}}function Or(e,t=Date.now()){const a="number"==typeof e?e:Date.parse(e);if(!e||!Number.isFinite(a))return null;const n=Math.max(0,Math.floor((t-a)/1e3));return n<60?"Just now":n<3600?`${Math.floor(n/60)}m ago`:n<86400?`${Math.floor(n/3600)}h ago`:n<604800?`${Math.floor(n/86400)}d ago`:new Date(a).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Dr(e){return e>99?"99+":String(e)}const Pr=Object.freeze({conversation:"messages",workspace_conversation:"messages",workspace_message:"messages",task:"tasks",workspace_task:"tasks",project:"projects",workspace_project:"projects",team:"teams",resource:"resources",workspace_resource:"resources",person:"people",personnel_profile:"people",person_note:"notes",onboarding_assignment:"onboarding",workspace_update:"updates"});function Lr(e){return e?function(e,t,a={}){const n=Pr[e];
2if(!n||!t)return null;const s=a&&"object"==typeof a?a:{};switch(n){case"messages":return{tab:n,conversationId:s.conversationId||t};case"tasks":return{tab:n,projectId:s.projectId||null,taskId:s.taskId||t};case"projects":return{tab:n,projectId:s.projectId||t};case"updates":return{tab:n,updateId:s.updateId||t,projectId:s.projectId||null};case"teams":return{tab:n,teamId:s.teamId||t};case"resources":return{tab:n,resourceId:s.resourceId||t};case"notes":return{tab:n,noteMode:"shared",noteId:s.noteId||t};case"people":return{tab:n,personId:s.personId||t};case"onboarding":return{tab:n,assignmentId:s.assignmentId||t};default:return null}}(e.entityType,e.entityId,e.metadata):null}function $r(e={}){const t=new URLSearchParams;return Object.entries(e).forEach(([e,a])=>{null!=a&&""!==a&&t.set(e,String(a))}),t.has("tab")||t.set("tab","home"),`/dashboard/employee?${t.toString()}`}const Mr=Object.freeze([Object.freeze({id:"home",label:"Home",icon:v,title:"Workspace Home",description:"Your current work and recent activity.",width:"standard"}),Object.freeze({id:"updates",label:"Updates",icon:T,title:"Workspace Updates",description:"Announcements, project news, and shared research context.",unavailableLabel:"Workspace Updates are not available yet",width:"standard"}),Object.freeze({id:"projects",label:"Projects",icon:A,title:"Projects",description:"Projects, boards, resources, and progress.",width:"wide"}),Object.freeze({id:"tasks",label:"My Tasks",icon:O,title:"My Tasks",description:"Tasks assigned to you across projects.",width:"wide"}),Object.freeze({id:"messages",label:"Messages",icon:D,title:"Messages",description:"Direct, project, and team conversations.",width:"conversation"}),Object.freeze({id:"notes",label:"Notes",icon:P,title:"Notes",description:"Meeting notes shared with you and notes you write for yourself.",unavailableLabel:"Notes are not available yet",width:"standard"}),Object.freeze({id:"teams",label:"Teams",icon:L,title:"Teams",description:"Your teams, members, resources, and activity.",width:"standard"}),Object.freeze({id:"people",label:"People",icon:$,title:"People",description:"Internal personnel directory.",width:"standard"}),Object.freeze({id:"resources",label:"Resources",icon:M,title:"Resources",description:"Files and workspace resources available to you.",width:"standard"}),Object.freeze({id:"jupyter",label:"Jupyter",icon:U,title:"Jupyter",description:"Your private notebook workspace and server status.",width:"wide"}),Object.freeze({id:"wikibase",label:"Wikibase",icon:F,title:"Wikibase",description:"Open the private knowledge base or use governed data tools.",unavailableLabel:"Wikibase is not available",width:"wide"})]),Ur=Object.freeze({id:"onboarding",label:"Onboarding",icon:_,title:"Internal onboarding",description:"Learn the TokenWorks workspace, systems, and safe working practices.",unavailableLabel:"Onboarding is not available yet",width:"standard"}),Fr=Object.freeze({id:"settings",label:"Settings",icon:I,title:"Settings",description:"Manage your Workspace profile and how you appear to people.",width:"standard"}),zr=Object.freeze(Mr.map(e=>e.id)),qr=Object.freeze([Ur.id,Fr.id,...zr]),Br="/dashboard/employee";function Wr(e){return[Ur,Fr,...Mr].find(t=>t.id===e)||Mr[0]}function Vr(e){return`${Br}?tab=${e}`}const Hr="/research-notifications";function Kr({mobile:e,children:t}){return e&&"undefined"!=typeof document?n.createPortal(t,document.body):t}function Gr({researchUnreadCount:a=0,canUseCommunityNotifications:n=!1,onNavigate:s=null}){const{visible:r,notifications:i,unread:o,loading:c,error:d,unavailable:u,listLoaded:h,loadList:m,markRead:p,markAllRead:f}=Ar(),[b,x]=e.useState(!1),[v,j]=e.useState(!1),[y,k]=e.useState(()=>"undefined"!=typeof window&&Boolean(window.matchMedia?.("(max-width: 640px)").matches)),w=e.useRef(null),N=e.useRef(null),C=e.useRef(null),R=e.useRef(new Map),E=e.useId(),I=e.useId(),_=n&&Number(a)||0,T=r?o:0,A=T+_,O=Boolean(r||n),D=e.useCallback((e=!0)=>{j(!1),x(!1),e&&w.current?.focus?.()},[]);if(e.useEffect(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(max-width: 640px)"),t=()=>k(e.matches);return t(),e.addEventListener?.("change",t),()=>e.removeEventListener?.("change",t)},[]),e.useEffect(()=>{b&&N.current?.focus?.({preventScroll:!0})},[b]),e.useEffect(()=>{if(!b||!v||c)return;const e=d?C.current:N.current?.querySelector(".dashboard-notification-item")||N.current;e?.focus?.({preventScroll:!0}),j(!1)},[d,c,i,b,v]),e.useEffect(()=>{if(!O||!b||!y||"undefined"==typeof document)return;const e=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=e}},[y,b,O]),e.useEffect(()=>{b&&r&&m()},[m,b,r]),e.useEffect(()=>{if(!b||"undefined"==typeof document)return;const e=e=>{if("Escape"===e.key)return e.stopPropagation(),void D();if("Tab"!==e.key||!y)return;const t=Array.from(N.current?.querySelectorAll('a[href], button:not([disabled]), [tabindex]:not
2([tabindex="-1"])')||[]);if(!t.length)return;const a=t[0],n=t[t.length-1];!e.shiftKey||document.activeElement!==a&&document.activeElement!==N.current?e.shiftKey||document.activeElement!==n||(e.preventDefault(),a.focus()):(e.preventDefault(),n.focus())},t=e=>{N.current?.contains(e.target)||w.current?.contains(e.target)||D()};return document.addEventListener("keydown",e),document.addEventListener("mousedown",t),()=>{document.removeEventListener("keydown",e),document.removeEventListener("mousedown",t)}},[D,y,b]),!O)return null;const P=()=>{j(!0),m()},L=A?`, ${A} unread`:"",$=Boolean(h||i.length),M=r&&!u&&$,U=c&&!$,F=c&&$,q=d&&!$,B=d&&$;return t.jsxs("div",{className:"dashboard-notifications",children:[t.jsxs("button",{ref:w,type:"button",className:"dashboard-notifications-trigger","aria-label":`Notifications${L}`,"aria-expanded":b,"aria-haspopup":"dialog","aria-controls":E,onClick:()=>b?D():x(!0),children:[t.jsx(z,{size:18,"aria-hidden":"true"}),A?t.jsx("span",{className:"dashboard-notifications-badge","aria-hidden":"true",children:Dr(A)}):null]}),t.jsx("span",{className:"dashboard-visually-hidden","aria-live":"polite",children:A?`${A} unread notifications`:""}),b?t.jsx(Kr,{mobile:y,children:t.jsxs(t.Fragment,{children:[y?t.jsx("div",{className:"dashboard-notifications-scrim",onPointerDown:e=>{e.preventDefault(),e.stopPropagation(),D(),Promise.resolve().then(()=>w.current?.focus?.({preventScroll:!0}))},"aria-hidden":"true"}):null,t.jsxs("div",{className:"dashboard-notifications-panel",id:E,ref:N,role:"dialog","aria-modal":y?"true":"false","aria-labelledby":I,tabIndex:-1,children:[t.jsxs("div",{className:"dashboard-notifications-head",children:[t.jsx("h2",{id:I,children:"Notifications"}),t.jsxs("div",{className:"dashboard-notifications-head-actions",children:[r?t.jsx("button",{type:"button",className:"dashboard-notifications-action",onClick:()=>{f()},disabled:c||u||!T,children:"Mark all read"}):null,t.jsxs("button",{type:"button",className:"dashboard-notifications-action dashboard-notifications-close","aria-label":"Close notifications",onClick:()=>D(),children:[t.jsx(g,{size:16,"aria-hidden":"true"})," Close"]})]})]}),n?t.jsxs(l,{to:Hr,className:"dashboard-notifications-community",onClick:()=>D(!1),children:[t.jsx(S,{size:16,"aria-hidden":"true"}),t.jsx("span",{className:"dashboard-notifications-community-label",children:"Community"}),t.jsx("span",{className:"dashboard-notifications-community-meta",children:_?`${Dr(_)} unread`:"No unread updates"})]}):null,r?t.jsxs("div",{className:"dashboard-notifications-list",role:"region","aria-label":"Workspace notifications","aria-busy":c?"true":"false",children:[U?t.jsx("p",{role:"status","aria-live":"polite",className:"dashboard-notifications-state",children:"Loading notificationsâ¦"}):u?t.jsx("p",{role:"status",className:"dashboard-notifications-state",children:"Notifications will appear after workspace messaging is ready."}):q?t.jsxs("p",{role:"alert",className:"dashboard-notifications-state",children:[d.safeMessage||"Notifications could not be loaded."," ",t.jsx("button",{ref:C,type:"button",className:"dashboard-notifications-action",onClick:P,children:"Retry"})]}):null,F?t.jsx("p",{role:"status","aria-live":"polite",className:"dashboard-notifications-state",children:"Refreshing notificationsâ¦"}):null,B?t.jsxs("p",{role:"alert",className:"dashboard-notifications-state",children:[d.safeMessage||"Notifications could not be refreshed."," Showing the last loaded notifications."," ",t.jsx("button",{ref:C,type:"button",className:"dashboard-notifications-action",onClick:P,children:"Retry notifications"})]}):null,M?i.map(e=>{const a=null!==Lr(e),n=Or(e.createdAt);return t.jsxs("button",{ref:t=>{t?R.current.set(e.id,t):R.current.delete(e.id)},type:"button",className:"dashboard-notification-item"+(e.readAt?"":" is-unread"),onClick:()=>{(async e=>{const t=Lr(e);let a=!0;try{t&&s&&(a=!1!==await s(t))}catch{a=!1}if(!a){const t=R.current.get(e.id)||N.current;return void t?.focus?.({preventScroll:!0})}D(!1),await p([e.id])})(e)},children:[t.jsx("span",{className:"dashboard-notification-title",children:e.title}),t.jsx("span",{className:"dashboard-notification-summary",children:e.summary||e.notificationType}),t.jsxs("span",{className:"dashboard-notification-meta",children:[n?t.jsx("time",{dateTime:e.createdAt,children:n}):null,e.readAt?null:t.jsx("span",{className:"is-unread-tag",children:"Unread"}),a?null:t.jsx("span",{children:"No linked item"})]})]},e.id)}):null,!M||i.length||c||d?null:t.jsx("p",{className:"dashboard-notifications-state",children:"No notifications."})]}):null,n?t.jsx(l,{to:Hr,className:"dashboard-notifications-footer-link",onClick:()=>D(!1),children:"View all notifications"}):r?t.jsx(l,{to:Br,className:"dashboard-notifications-footer-link",onClick:()=>D(!1),children:"Open Workspace"}):null]})]})}):null]})}function Jr({contextLabel:e="Dashboard",sectionLabel:a,menuButtonRef:n,onOpenMenu:s,isMenuOpen:r=!1,canUseCommunityNotifications:i=!1,researchUnreadCount:l=0,onNotificationNavigate:o=null,menuControlsId:c="dashboard-navigation-drawer"}){return t.jsxs("header",{className:"dashboard-topbar",children:[t.jsx("button",{ref:n,type:"button",className:"mobile-menu-toggle",onClick:s,"aria-label":r?"Close application navigation":"Open application navigation","aria-controls":c,"aria-expanded":r,children:t.jsx(q,{size:22,"aria-hidden":"true"})}),t.jsxs("div",{className:"dashboard-topbar-context",children:[e?t.jsx("span",{className:"dashboard-topbar-eyebrow",children:e}):null,a?t.jsx("span",{className:"dashboard-topbar-section",children:a}):null]}),t.jsxs("div",{className:"topbar-actions",children:[t.jsx("span",{id:"dashboard-cookie-sett
2ings-slot",className:"dashboard-cookie-settings-slot"}),t.jsx(Gr,{canUseCommunityNotifications:i,researchUnreadCount:l,onNavigate:o})]})]})}const Yr="/api/research/notifications";class Qr extends Error{constructor(e,{code:t="RESEARCH_NOTIFICATION_REQUEST_FAILED",status:a=null}={}){super(e),this.name="ResearchNotificationRequestError",this.code=t,this.status=a}}class Xr{constructor({requestFn:e}={}){if("function"!=typeof e)throw new Error("ResearchNotificationRepository requires a requestFn");this.requestFn=e}async request(e,t={},a="Research notification request failed"){try{const n=await this.requestFn(e,t);if(!n?.ok)throw new Qr(n?.error?.message||a,{code:n?.error?.code,status:n?.error?.status});return n.data??n}catch(n){if(n instanceof Qr)throw n;if("AbortError"===n?.name)throw new Qr("Request cancelled",{code:"REQUEST_CANCELLED"});throw new Qr(n?.message||a,{code:n?.code,status:n?.status})}}list(e={}){return this.request(`${Yr}${function(e={}){const t=new URLSearchParams;for(const[n,s]of Object.entries(e))"signal"!==n&&null!=s&&String(s).trim()&&t.set(n,String(s));const a=t.toString();return a?`?${a}`:""}(e)}`,{method:"GET",signal:e.signal})}unreadCount({signal:e}={}){return this.request(`${Yr}/unread-count`,{method:"GET",signal:e})}setRead(e,t){return this.request(`${Yr}/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({read:Boolean(t)})})}markAllRead(){return this.request(`${Yr}/mark-all-read`,{method:"POST",body:JSON.stringify({})})}}function Zr(){const{makeAuthRequest:t}=Yn();return e.useMemo(()=>function(e){return new Xr({requestFn:e})}(t),[t])}const ei="research-notifications-changed";function ti(){"undefined"!=typeof window&&window.dispatchEvent(new Event(ei))}function ai(t){const a=Zr(),[n,s]=e.useState(0),[r,i]=e.useState(null),l=e.useCallback(async()=>{if(t)try{const e=await a.unreadCount();s(Number(e.unreadCount||0)),i(null)}catch(e){i(e)}},[t,a]);return e.useEffect(()=>{if(!t)return void s(0);l();const e=()=>{l()},a=()=>{"visible"===document.visibilityState&&l()};window.addEventListener("focus",e),window.addEventListener(ei,e),document.addEventListener("visibilitychange",a);const n=window.setInterval(()=>{"visible"===document.visibilityState&&l()},9e4);return()=>{window.removeEventListener("focus",e),window.removeEventListener(ei,e),document.removeEventListener("visibilitychange",a),window.clearInterval(n)}},[t,l]),{unreadCount:n,error:r,refresh:l}}function ni({pathname:e="",search:t=""}={}){if("/dashboard/employee"===e||e.startsWith("/dashboard/employee/"))return function(e){return{home:"workspace_home",projects:"workspace_projects",tasks:"workspace_tasks",messages:"workspace_messages",resources:"workspace_resources",tools:"workspace_tools"}[new URLSearchParams(e||"").get("tab")||"home"]||null}(t);if("/dashboard"===e){const e=new URLSearchParams(t||"").get("tab")||"overview";return"documents"===e?"document_library":"overview"===e?"customer_dashboard":null}return null}function si(t,a){const n=ni(a);e.useEffect(()=>{if(!n||"function"!=typeof t||!Xn("analytics"))return;const e=globalThis.crypto?.randomUUID?.()||null;if(!e)return;const a=`tw:analytics-surface:${n}`,s=Date.now();try{if(s-Number(sessionStorage.getItem(a)||0)<3e4)return;sessionStorage.setItem(a,String(s))}catch{}t("/api/analytics/events",{method:"POST",body:JSON.stringify({event_name:"surface_viewed",surface:n,entity_type:null,entity_id:null,idempotency_key:e})}).catch(()=>{})},[t,n])}function ri({children:a,variant:n="default",navigation:r=null,contextLabel:l=null,sectionLabel:o=null}){const{canAccessCommunityPreview:c,hasRole:d,hasMinimumRole:u,makeAuthRequest:h}=Yn(),m=s(),p=i(),[g,f]=e.useState(!1),[b,x]=e.useState(!1),v=e.useRef(null),j=e.useRef(null),y=e.useRef(null),k=Boolean(r);si(h,m);const w=d?.(["admin","cofounder"]),N=c?.(),S=u?.("intern"),{unreadCount:C}=ai(N),R={isInternal:S,canUseCommunityPreview:N,isAdmin:w},E=Nr(R).flatMap(e=>e.items).find(e=>wr(e,m)),I=({collapsed:e=!1,onNavigate:a=null,ariaLabel:n="Primary application navigation"}={})=>r?.render?r.render({collapsed:e,onNavigate:a}):t.jsx(Sr,{location:m,capabilities:R,collapsed:e,onNavigate:a,ariaLabel:n}),_=e.useCallback(()=>f(!1),[]),T=e.useCallback(e=>(p($r(e)),!0),[p]);return e.useLayoutEffect(()=>{const e=v.current,t=document.querySelector(".header");if(!e||!t)return;const a=()=>{e.style.setProperty("--dashboard-header-offset",`${t.getBoundingClientRect().height}px`)};a();const n="undefined"==typeof ResizeObserver?null:new ResizeObserver(a);return n?.observe(t),window.addEventListener("resize",a),()=>{n?.disconnect(),window.removeEventListener("resize",a)}},[]),e.useEffect(()=>{f(!1)},[m.pathname,m.search]),e.useEffect(()=>{if(!k||"function"!=typeof window.matchMedia)return;const e=window.matchMedia("(min-width: 1367px)"),t=e=>{e.matches&&f(!1)};return e.matches&&f(!1),e.addEventListener?.("change",t),()=>e.removeEventListener?.("change",t)},[k]),e.useEffect(()=>{j.current?.scrollTo?.({top:0,left:0})},[m.pathname,m.search]),t.jsxs("div",{ref:v,className:["dashboard-layout","research"===n?"dashboard-layout--research":"",k?"dashboard-layout--contextual":"",b&&!k?"dashboard-layout--collapsed":""].filter(
2Boolean).join(" "),children:[t.jsxs("aside",{id:"dashboard-sidebar",className:"dashboard-sidebar",children:[t.jsxs("div",{className:"dashboard-sidebar-head",children:[t.jsx("span",{className:"dashboard-sidebar-brand",children:r?.brand||"Dashboard"}),k?null:t.jsx("button",{type:"button",className:"dashboard-sidebar-collapse",onClick:()=>x(e=>!e),"aria-label":b?"Expand sidebar":"Collapse sidebar","aria-pressed":b,children:b?t.jsx(B,{size:18,"aria-hidden":"true"}):t.jsx(W,{size:18,"aria-hidden":"true"})})]}),I({collapsed:!k&&b})]}),t.jsxs("div",{className:"dashboard-main-column",children:[t.jsx(Jr,{contextLabel:l??r?.contextLabel??"Dashboard",sectionLabel:o??r?.sectionLabel??E?.label??null,menuButtonRef:y,onOpenMenu:()=>f(!0),isMenuOpen:g,canUseCommunityNotifications:N,researchUnreadCount:C,onNotificationNavigate:T}),t.jsx("main",{className:"dashboard-main",ref:j,children:t.jsx("div",{className:"dashboard-content",children:a})})]}),t.jsx(fr,{panelId:"dashboard-navigation-drawer",isOpen:g,onClose:_,title:r?.drawerTitle||"Dashboard",side:"left",closeLabel:"Close application navigation",children:I({onNavigate:_,ariaLabel:"Dashboard navigation"})})]})}const ii={default:"neutral",gray:"neutral",neutral:"neutral",primary:"info",blue:"info",info:"info",success:"success",green:"success",warning:"warning",orange:"warning",danger:"danger",red:"danger",purple:"info"};function li({children:e,variant:a="default",color:n,text:s,className:r=""}){const i=n||a,l=ii[i]||"neutral",o=s||e;return t.jsx("span",{className:`badge tw-badge tw-badge--${l} badge-${i} ${r}`,"data-tone":l,children:o})}const oi=e.forwardRef(function({value:e,onChange:a,onClear:n,placeholder:s="Search...",className:r="",...i},l){return t.jsxs("div",{className:`search-input-container ${r}`,children:[t.jsx("div",{className:"search-icon",children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M21 21L16.514 16.506M19 10.5C19 15.194 15.194 19 10.5 19C5.806 19 2 15.194 2 10.5C2 5.806 5.806 2 10.5 2C15.194 2 19 5.806 19 10.5Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),t.jsx("input",{ref:l,type:"text",value:e,onChange:e=>a(e.target.value),placeholder:s,className:"search-input",...i}),e&&t.jsx("button",{type:"button",onClick:()=>{a(""),n?.()},className:"clear-button","aria-label":"Clear search",children:t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M18 6L6 18M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})});const ci=/^(?:WQ|Q|P)[1-9][0-9]*$/i,di=/^(?:WQ|Q)[1-9][0-9]*\$(?:[a-f0-9-]{8,})$/i,ui=/^https?:\/\/[^\s]+\/(?:entity|wiki|special:entitydata)\/(?:WQ|Q|P)[1-9][0-9]*(?:\.json)?$/i,hi=/^https:\/\/wikibase\.tk-wiki-kg\.com\/wiki\/PageOCR:Q[1-9][0-9]*$/i;function mi(e,t=4e3){if(!["string","number","bigint"].includes(typeof e))return null;if("number"==typeof e&&!Number.isFinite(e))return null;const a=function(e,t=" "){return Array.from(String(e||""),e=>{const a=e.charCodeAt(0);return a<=31||127===a?t:e}).join("")}(e).replace(/\s+/g," ").trim();return!a||function(e){if("string"!=typeof e)return!1;const t=e.trim();return ci.test(t)||di.test(t)||ui.test(t)||hi.test(t)||/^PageOCR:/i.test(t)}(a)?null:a.slice(0,t)}function pi(e){const t=Array.isArray(e)?e:e?[e]:[];return Array.from(new Set(t.map(e=>mi(e,500)).filter(Boolean))).slice(0,50)}function gi({label:e,children:a,wide:n=!1}){return a?t.jsxs("div",{className:"document-metadata-field"+(n?" document-metadata-field--wide":""),children:[t.jsx("dt",{children:e}),t.jsx("dd",{dir:"auto",children:a})]}):null}function fi({values:e,separator:n=", "}){return e?.length?e.map((e,s)=>t.jsxs(a.Fragment,{children:[s>0?t.jsx("span",{"aria-hidden":"true",children:n}):null,t.jsx("span",{dir:"auto",children:e})]},`${e}-${s}`)):null}function bi({title:e,children:a}){return t.jsxs("section",{className:"document-metadata-section",children:[t.jsx("h3",{children:e}),t.jsx("dl",{className:"document-metadata-fields",children:a})]})}function xi({metadata:a,onClose:s}){const r=e.useRef(null),i=e.useRef(null),l=e.useId(),o=ys({isOpen:Boolean(a),panelRef:r,initialFocusRef:i,onRequestClose:s});if(!a||"undefined"==typeof document)return null;const c=Boolean(a.description||a.authors?.length||a.editors?.length||a.aliases?.length||a.subjects?.length),d=Boolean(a.publicationDate||a.language||a.documentType||a.volume||a.coveredPeriodStart||a.coveredPeriodEnd||a.collection||a.pageCount),u=Boolean(a.citation);return n.createPortal(t.jsx("div",{className:"document-metadata-drawer-overlay",onMouseDown:e=>{e.target===e.currentTarget&&o("backdrop")},children:t.jsxs("div",{ref:r,className:"document-metadata-drawer",role:"dialog","aria-modal":"true","aria-labelledby":l,tabIndex:-1,
2children:[t.jsxs("div",{className:"document-metadata-drawer-header",children:[t.jsxs("div",{children:[t.jsx("p",{children:"Document metadata"}),t.jsx("h2",{id:l,ref:i,tabIndex:-1,dir:"auto",children:a.title})]}),t.jsx("button",{type:"button",className:"document-metadata-drawer-close",onClick:()=>o("close-button"),"aria-label":"Close document metadata",children:t.jsx(g,{size:20,"aria-hidden":"true"})})]}),t.jsxs("div",{className:"document-metadata-drawer-content",children:[a.metadataNotice?t.jsx("p",{className:"document-metadata-state",role:"status",children:a.metadataNotice}):null,(h=a,h&&Boolean(h.description||h.authors?.length||h.editors?.length||h.aliases?.length||h.publicationDate||h.language||h.documentType||h.volume||h.coveredPeriodStart||h.coveredPeriodEnd||h.collection||h.subjects?.length||h.citation||h.pageCount)?t.jsxs("div",{className:"document-metadata-sections",children:[c?t.jsxs(bi,{title:"About this document",children:[t.jsx(gi,{label:"Description",wide:!0,children:a.description}),t.jsx(gi,{label:"Authors",children:t.jsx(fi,{values:a.authors})}),t.jsx(gi,{label:"Editors",children:t.jsx(fi,{values:a.editors})}),t.jsx(gi,{label:"Aliases",wide:!0,children:t.jsx(fi,{values:a.aliases,separator:" · "})}),t.jsx(gi,{label:"Subjects",wide:!0,children:t.jsx(fi,{values:a.subjects})})]}):null,d?t.jsxs(bi,{title:"Publication details",children:[t.jsx(gi,{label:"Publication date",children:a.publicationDate}),t.jsx(gi,{label:"Language",children:a.language}),t.jsx(gi,{label:"Document type",children:a.documentType}),t.jsx(gi,{label:"Volume",children:a.volume}),t.jsx(gi,{label:"Covered period",children:[a.coveredPeriodStart,a.coveredPeriodEnd].filter(Boolean).join(" â ")}),t.jsx(gi,{label:"Collection",children:a.collection}),t.jsx(gi,{label:"Page count",children:a.pageCount})]}):null,u?t.jsx(bi,{title:"Catalog record",children:t.jsx(gi,{label:"Citation",wide:!0,children:a.citation})}):null]}):t.jsx("p",{className:"document-metadata-empty",children:"Only the document title is available right now. More catalog details may be added later."}))]})]})}),xs());var h}const vi="drive-migration/";function ji(e){try{return decodeURIComponent(e)}catch{return e}}function yi(e,t){t&&!e.includes(t)&&e.push(t)}function ki(e){const t=String(e||"");return/\$002f/i.test(t)||/%24002f/i.test(t)}function wi(e){let t=String(e||"");for(let a=0;a<2;a+=1){const e=ji(t);if(e===t)break;t=e}return t.replace(/\$002f/gi,"/")}function Ni(e,t=1024){const a=Number.isInteger(t)&&t>0?t:1024,n=String(e||"").slice(0,a).replace(/[\x00-\x1f\x7f]/g,"");if(!n.includes(".."))return n;const s=[];for(const r of n.split("/"))if(".."!==r)s.push(r);else for(;s.length>0;){if(""!==s.pop())break}return s.join("/")}function Si(e){const t=String(e||""),a=t.lastIndexOf("/"),n=a>=0?t.slice(0,a+1):"",s=a>=0?t.slice(a+1):t;if(!s||/\.pdf$/i.test(s)||!/pdf$/i.test(s))return[];const r=[];return r.push(`${n}${s.replace(/(\.\d+)pdf$/i,"$1.pdf")}`),r.push(`${n}${s.replace(/(\.\d+)pdf$/i,"$1..pdf")}`),r.push(`${n}${s.replace(/pdf$/i,".pdf")}`),r.push(`${n}${s.replace(/pdf$/i,"..pdf")}`),r}function Ci(e){const t=String(e||"");if(!t.includes(".."))return[];const a=t.replace(/\.{2,}/g,"");return a&&a!==t?[a]:[]}function Ri(e,{libraryRootPrefix:t=vi,enforceLibraryPrefix:a=!1}={}){const n=[],s=Ni(e);if(!s)return n;const r=ki(s);yi(n,s),yi(n,s.replace(/^\/+/,""));const i=Ni(wi(s)).replace(/\/{2,}/g,"/"),l=i.replace(/^\/+/,"");r&&(yi(n,i),yi(n,l));for(const o of[...n])for(const e of Si(o))yi(n,e);for(const o of[...n])for(const e of Ci(o))yi(n,e);return a&&r&&l&&!l.startsWith(t)&&yi(n,`${t}${l}`),a?n.filter(e=>e.startsWith(t)):n}function Ei(e){const t=Ni(e);if(!ki(t))return!1;return wi(t).split("/").some(e=>"."===e||".."===e)}const Ii="documentLibrary:snapshot:v2:";function _i(e){return"vercel_blob"===e?"vercel_blob":"s3"}function Ti(e){if("undefined"==typeof window)return null;try{const t=window.sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Ai(e,t){if("undefined"!=typeof window)try{window.sessionStorage.setItem(e,JSON.stringify(t))}catch{return}}function Oi(e){if("undefined"!=typeof window)try{window.sessionStorage.removeItem(e)}catch{return}}function Di(e,t){return`documentLibrary:response:${e}:${JSON.stringify(t)}`}function Pi({userScope:e="anonymous",activeTab:t="all",currentPrefix:a="",limit:n=20,page:s=1,searchTerm:r="",selectedSuggestionId:i=null,shouldIncludeStructure:l=!0,sort:o="title_asc"}={}){const c=Number.isInteger(Number(s))&&Number(s)>0?Number(s):1,d=Number.isInteger(Number(n))&&Number(n)>0?Number(n):20;return Di(`browse:${e}`,{activeTab:t,currentPrefix:a,limit:d,offset:(c-1)*d,page:c,searchTerm:String(r||"").trim().toLowerCase(),selectedSuggestionId:i?String(i).trim():null,
2shouldIncludeStructure:l,sort:o})}function Li(e){const t=Ti(e);if(!t?.cachedAt)return null;const a=Date.now()-t.cachedAt;return a>9e5?(Oi(e),null):{data:t.data||null,freshness:a<=12e4?"fresh":"stale"}}function $i(e){return Li(e)?.data||null}function Mi(e,t){Ai(e,{cachedAt:Date.now(),data:t})}function Ui(e="anonymous"){const t=`${Ii}${e}`,a=Ti(t);return a?.cachedAt?Date.now()-a.cachedAt>18e5?(Oi(t),null):a:null}function Fi(e,t){const a=void 0===t?e:t;Ai(`${Ii}${void 0===t?"anonymous":e||"anonymous"}`,{cachedAt:Date.now(),...a})}function zi(e,{id:t,storageProvider:a,storageKey:n}){if(t){const a=e.filter(e=>e?.id&&String(e.id)===String(t));if(1===a.length)return a[0];if(a.length>1)return null}if(!n)return null;const s=_i(a),r=e.filter(e=>_i(e?.storageProvider)===s&&e?.storageKey&&e.storageKey===n);if(1===r.length)return r[0];if(r.length>1)return null;const i=e.filter(e=>!(_i(e?.storageProvider)!==s||!e?.storageKey||e.storageKey===n)&&(!e?.id&&function(e,t,{libraryRootPrefix:a=vi}={}){const n=Ni(e),s=Ni(t);if(!n||!s)return{equivalent:!1,matchType:null};if(n===s)return{equivalent:!0,matchType:"exact"};if(!n.startsWith(a)||!s.startsWith(a))return{equivalent:!1,matchType:null};if(Ei(n)||Ei(s))return{equivalent:!1,matchType:null};const r=Ri(n,{libraryRootPrefix:a,enforceLibraryPrefix:!0}),i=Ri(s,{libraryRootPrefix:a,enforceLibraryPrefix:!0});return r.includes(s)||i.includes(n)?{equivalent:!0,matchType:"compatible"}:{equivalent:!1,matchType:null}}(e.storageKey,n).equivalent));return 1===i.length?i[0]:null}function qi(e,t,a={}){if(!Array.isArray(e)||!t)return e;const n={id:t.id||a.id||null,storageProvider:t.storageProvider||a.storageProvider||null,storageKey:t.storageKey||a.storageKey||null};if(!n.id&&!n.storageKey)return e;const s=zi(e,n);return s?e.map(e=>e===s?function(e,t){if(!e)return e;if(!t)return e;const a=Object.prototype.hasOwnProperty.call(t,"bookmarks"),n=Object.prototype.hasOwnProperty.call(t,"isFavorite");return{...e,id:t.id??e.id??null,storageProvider:t.storageProvider??e.storageProvider,storageKey:t.storageKey??e.storageKey,filename:t.filename??e.filename,displayTitle:t.displayTitle??e.displayTitle??e.filename,pageCount:t.pageCount??e.pageCount??null,status:t.status??e.status,createdAt:t.createdAt??e.createdAt,viewCount:t.viewCount??e.viewCount??0,favoriteCount:t.favoriteCount??e.favoriteCount??0,isFavorite:n?t.isFavorite:e.isFavorite,bookmarks:a?t.bookmarks:e.bookmarks}}(e,t):e):e}function Bi(e){let t=e;if(null==t)return[];if("string"==typeof t&&(t=function(e){const t=e.trim();if(!t)return[];if(t.startsWith("[")&&t.endsWith("]"))return Wi(t);if(t.startsWith('"')&&t.endsWith('"')){const e=Wi(t);if("string"==typeof e){const t=e.trim();if(t.startsWith("[")&&t.endsWith("]"))return Wi(t)}}return[]}(t)),!Array.isArray(t))return[];const a=[],n=new Set;for(const s of t)!Number.isFinite(s)||!Number.isInteger(s)||s<=0||n.has(s)||(n.add(s),a.push(s));return a.sort((e,t)=>e-t)}function Wi(e){try{return JSON.parse(e)}catch{return[]}}const Vi=Object.freeze({DOCUMENT:"document",PAGE:"page"}),Hi=Object.freeze({ALL:"all",DOCUMENTS:"documents",PAGES:"pages"}),Ki=Object.freeze({document:"Title",title:"Title",display_name:"Title",displayName:"Title",name:"Title",alias:"Alias",aliases:"Alias",author:"Author",authors:"Author",identifier:"Identifier",identifiers:"Identifier",metadata:"Metadata",page_text:"Page text",text:"Page text",language:"Language",classification:"Classification",entity:"Entity",entities:"Entity",personal_name:"Personal name",personal_names:"Personal name",place:"Place",places:"Place",lemma:"Lemma",lemmas:"Lemma",annotation:"Annotation"}),Gi=Object.freeze({document_uuid:"Document ID",wikibase_qid:"Wikibase QID"}),Ji=Object.freeze({EMPTY_QUERY:"EMPTY_QUERY",NETWORK_ERROR:"NETWORK_ERROR",UNAUTHORIZED:"UNAUTHORIZED",SUBSCRIPTION_REQUIRED:"SUBSCRIPTION_REQUIRED",SERVER_ERROR:"SERVER_ERROR",INVALID_RESPONSE:"INVALID_RESPONSE",REQUEST_CANCELLED:"REQUEST_CANCELLED",UNKNOWN:"SEARCH_REQUEST_FAILED"}),Yi=20,Qi=new Set(Object.values(Hi));function Xi(e,t){if(!e)return null;if("function"==typeof e.get)return e.get(t);const a=e[t];return null==a?null:String(a)}function Zi(e){return String(e??"").slice(0,256)}function el(e){const t={},a=Zi(e?.query||"");a&&(t.q=a),e?.resultType&&e.resultType!==Hi.ALL&&(t.type=e.resultType);const n=e?.filters||{};return n.language&&(t.language=n.language),n.author&&(t.author=n.author),n.classification&&(t.classification=n.classification),n.hasPageText&&(t.hasText="1"),e?.cursor&&(t.cursor=e.cursor),t}function tl(e){if(null==e)return null;const t=String(e).trim();return t.length>0?t:null}function al(e,t=""){return tl(e)??t}function nl(e){const t=Number(e);return Number.isInteger(t)&&t>0?t:null}function sl(e){return Array.isArray(e)?e.map(e=>
2tl(e)).filter(Boolean):[]}function rl(e){return["lexical","hybrid","semantic"].includes(e)?e:"lexical"}function il(e){const t=String(e||"").replace(/[_-]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"Match"}function ll(e){const t=Array.isArray(e)?e:[],a=new Set,n=[];for(const s of t){const e=tl(s);e&&!a.has(e)&&(a.add(e),n.push({key:e,label:Ki[e]||il(e)}))}return n}function ol(e,t){if(!t.length)return!1;const a=e.map(e=>tl(e)?.toLowerCase()).filter(Boolean);return!!a.length&&t.some(e=>a.includes(e.value.toLowerCase()))}function cl(e){return(Array.isArray(e)?e:[]).map(e=>{const t=Number(e?.start),a=Number(e?.end);return Number.isInteger(t)&&Number.isInteger(a)?t<0||a<=t?null:{start:t,end:a}:null}).filter(Boolean)}function dl(e,t){const a=tl(e?.type??e?.resultType);return a===Vi.PAGE?function(e,{exactIdentifiers:t=[]}={}){const a=e||{},n=al(a.documentPageId??a.id),s=tl(a.pageWikibaseEntityId??a.pageQid),r=a.parentMetadata||{};return{resultType:Vi.PAGE,documentId:al(a.documentId),documentPageId:n,documentWikibaseEntityId:tl(a.documentWikibaseEntityId??a.documentQid),pageWikibaseEntityId:s,authors:sl(a.authors??r.authors),publicationDate:tl(a.publicationDate??r.publicationDate),language:tl(a.language??r.language),pageNumber:nl(a.pageNumber),documentDisplayName:al(a.documentDisplayName,"Untitled document"),snippet:al(a.snippet),matchRanges:cl(a.matchRanges),matchedFields:ll(a.matchedFields),isExactIdentifierMatch:ol([n,s],t),matchMode:rl(a.matchMode)}}(e,t):a===Vi.DOCUMENT?function(e,{exactIdentifiers:t=[]}={}){const a=e||{},n=al(a.documentId),s=tl(a.wikibaseEntityId??a.qid),r=al(a.displayName??a.title??a.name,"Untitled document");return{resultType:Vi.DOCUMENT,documentId:n,wikibaseEntityId:s,displayName:r,authors:sl(a.authors),publicationDate:tl(a.publicationDate??a.date),language:tl(a.language),matchedFields:ll(a.matchedFields),isExactIdentifierMatch:ol([n,s],t),matchMode:rl(a.matchMode)}}(e,t):null}function ul(e){const t=e||{},a=function(e){return(Array.isArray(e)?e:[]).map(e=>{const t=tl(e?.type),a=tl(e?.value);return t&&a?{type:t,value:a,label:Gi[t]||"Exact identifier"}:null}).filter(Boolean)}(t.exactIdentifiers),n=(Array.isArray(t.results)?t.results:[]).map(e=>dl(e,{exactIdentifiers:a})).filter(Boolean),s=tl(t.nextCursor);return{query:al(t.query),exactIdentifiers:a,results:n,nextCursor:s,hasMore:Boolean(s)}}const hl="/api/research/search";class ml extends Error{constructor(e,{code:t=Ji.UNKNOWN,status:a=null}={}){super(e),this.name="SearchRequestError",this.code=t,this.status=a}}class pl{constructor({requestFn:e}={}){if("function"!=typeof e)throw new Error("ResearchSearchRepository requires a requestFn");this.requestFn=e}async search(e,{limit:t=20,signal:a}={}){if(!String(e?.query||"").trim())throw new ml("Search query is empty",{code:Ji.EMPTY_QUERY});const n=function(e,{limit:t}={}){const a={...el(e)};Number.isInteger(t)&&t>0&&(a.limit=String(t));const n=new URLSearchParams(a).toString();return n?`${hl}?${n}`:hl}(e,{limit:t});let s;try{s=await this.requestFn(n,{method:"GET",signal:a})}catch(r){throw function(e){return"AbortError"===e?.name?new ml("Search request was cancelled",{code:Ji.REQUEST_CANCELLED}):"SESSION_EXPIRED"===e?.code||401===e?.status?new ml(e?.message||"Your session has expired.",{code:Ji.UNAUTHORIZED,status:e?.status??401}):"number"==typeof e?.status&&e.status>=500?new ml("The search service is temporarily unavailable.",{code:Ji.SERVER_ERROR,status:e.status}):e instanceof TypeError?new ml("Could not reach the search service.",{code:Ji.NETWORK_ERROR}):new ml(e?.message||"Search request failed",{code:e?.code||Ji.UNKNOWN,status:"number"==typeof e?.status?e.status:null})}(r)}if(!s?.ok)throw function(e){const t=e?.error,a=t?.code;return"SUBSCRIPTION_REQUIRED"===a?new ml(t.message||"An active subscription is required.",{code:Ji.SUBSCRIPTION_REQUIRED,status:402}):"SESSION_EXPIRED"===a?new ml(t.message||"Your session has expired.",{code:Ji.UNAUTHORIZED,status:401}):new ml(t?.message||"Search request failed",{code:a||Ji.UNKNOWN,status:null})}(s);return ul(s.data??s)}}function gl(){const{makeAuthRequest:t}=Yn();return e.useMemo(()=>function(e){return new pl({requestFn:e})}(t),[t])}const fl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function bl(e){const t=String(e||"").trim().toLowerCase();return function(e){return"string"==typeof e&&fl.test(e)}(t)?t:null}const xl="document_access",vl="legacy_document_access";function jl(e,{allowAdditionalKeys:t=[]}={}){if(!e||"object"!=typeof e)return null;const a=new Set(["reason","documentId","capability",...t]);if(Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&!a.has(t)).length>0)return null;const n=e.capability||"pdf_view";if(!["pdf_view","document_text"].includes(n))return null;const s=String(e.reason||"").trim();if(s===vl&&!e.documentId)return{reason:vl,documentId:null,capability:n,returnPath:null};const r=bl(e.documentId);return s===xl&&r?{reason:xl,documentId:r,capability:n,returnPath:`/documents/${r}/view`}:null}function yl(e,t="pdf_view"){const a=jl({reason:xl,documentId:e,capability:t});if(!a)return"/documents";return`/subscribe?${new URLSearchParams({reason:a.reason,documentId:a.documentId,..."pdf_view"!==a.capability?{capability:a.capability}:{}}).toString()}`}function kl(e="pdf_view"){return`/subscribe?${new URLSearchParams({reason:vl,..."document_text"===e?{capability:e}:{}})}`}const wl=new Set(["title_asc","title_desc","most_viewed","most_favorited","newest","oldest"]),Nl=new Set(["all","bookmarks","folders"]);function Sl(e){const t=String(e.get("view")||"all").toLowerCase();let a=Nl.has(t)?t:"all";const n=String(e.get("folder")||"").trim(),s=/^[a-zA-Z0-9_-]{1,128}$/.test(n)?n:"",r=[...String(e.get("prefix")||"")].filter(e=>{const t=e.charCodeAt(0);return t>=32&&127!==t}).join("").trim().slice(0,512),i=r?`${r.replace(/^\/+|\/+$/g,"")}/`:"";
2return{collectionTab:a,folder:s,prefix:s?"":i}}function Cl(e){const t=Number.parseInt(e.get("page")||"1",10),a=String(e.get("sort")||"title_asc").toLowerCase(),n="library"===a?"title_asc":a;return{q:e.get("q")||e.get("search")||"",page:Number.isInteger(t)&&t>0?t:1,sort:wl.has(n)?n:"title_asc",...Sl(e)}}function Rl(e,t){const a=new URLSearchParams(e);a.set("tab","documents");for(const l of["q","search","page","sort","author","genre","view","folder","prefix"])a.delete(l);const n=String(t.q||"").trim(),s=Number.parseInt(String(t.page||1),10),r=wl.has(t.sort)?t.sort:"title_asc";n&&a.set("q",n),s>1&&a.set("page",String(s)),"title_asc"!==r&&a.set("sort",r);const i=Sl(new URLSearchParams({view:t.collectionTab||"all",...t.folder?{folder:t.folder}:{},...t.prefix?{prefix:t.prefix}:{}}));return"all"!==i.collectionTab&&a.set("view",i.collectionTab),i.folder&&a.set("folder",i.folder),i.prefix&&a.set("prefix",i.prefix),a}const El=[{id:"all",label:"All Documents"},{id:"bookmarks",label:"Bookmarks"},{id:"folders",label:"My Folders"}];function Il(e){const t=String(e||"all").toLowerCase();return"favorites"===t||"saved"===t?"bookmarks":El.some(e=>e.id===t)?t:"all"}const _l=/(^|\/)users? uploads(\/|$)/i,Tl="drive-migration/",Al=/^[0-9][0-9 ._-]*$/;function Ol(e){if(!e)return null;if(e.isExactIdentifierMatch)return"Exact identifier match";if("semantic"===e.matchMode)return"Related metadata";if("hybrid"===e.matchMode)return"Matched metadata and related terms";const t=Array.isArray(e.matchedFields)?e.matchedFields.map(e=>e?.label).filter(Boolean):[];return t.length?`Matched ${t.slice(0,2).join(" and ").toLowerCase()}`:"Matched metadata"}function Dl(e){return"semantic"===e?.matchMode?"Related document text":"hybrid"===e?.matchMode?"Matched metadata and document text":"Matched in document text"}function Pl(e,a){if(!Array.isArray(a)||0===a.length)return null;const n=a.map(e=>String(e||"").trim()).filter(Boolean);if(0===n.length)return null;const s=n.slice(0,3),r=n.length-s.length;return t.jsxs("span",{dir:"auto","aria-label":`${e} ${n.join(", ")}`,children:[e," ",s.join(", "),r>0?t.jsxs("span",{className:"document-more-metadata",children:[" · ",r," more in Details"]}):null]})}function Ll(e){const t=String(e||"");try{return decodeURIComponent(t)}catch{return t}}function $l(e){return Ll(e).trim().replace(/\\+/g,"/").replace(/\/{2,}/g,"/").replace(/^\/+/,"").toLowerCase()}function Ml(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Ul(e,t){if(!Al.test(String(t||"").trim()))return!1;const a=e?.filename||function(e){const t=Ll(e).split("/").filter(Boolean);return t[t.length-1]||""}(e?.storageKey||"");return Ml(t)===Ml(String(a||"").replace(/\.pdf$/i,"").replace(/[_-]+/g," ").replace(/\./g,(e,t,a)=>{const n=a[t-1]||"",s=a[t+1]||"";return/\d/.test(n)&&/\d/.test(s)?e:" "}).replace(/\s+/g," ").trim())}function Fl(e,{title:t,isDuplicateTitle:a,formatDate:n}){if(!a&&!Ul(e,t))return null;const s=[],r=function(e){const t=String(e||"").trim();return t?t.slice(0,8):""}(e?.id);r?s.push(`ID ${r}`):e?.storageKey&&s.push("S3-only");const i=function(e){const t=Ll(e).trim().replace(/\\+/g,"/").replace(/\/{2,}/g,"/").replace(/^\/+/,"");if(!t)return null;if(!t.startsWith(Tl))return"Storage object";const a=t.slice(16);if(!a||!a.includes("/"))return Tl;const n=a.split("/").filter(Boolean)[0];return n?`${Tl}${n}/`:Tl}(e?.storageKey||"");i&&s.push(i);const l=e?.createdAt||e?.created_at;return l&&s.push(n(l)),s.length>0?s.join(" | "):null}function zl(e){return Array.isArray(e)?e.filter(e=>!function(e){const t=$l(e?.name||"").replace(/\/$/,""),a=$l(e?.prefix||"");return"user uploads"===t||"users uploads"===t||_l.test(a)}(e)):[]}function ql(e){return Array.isArray(e)?e.filter(e=>!function(e){const t=$l(e?.storageKey||"");if(t&&_l.test(t))return!0;const a=$l(e?.filename||"");return Boolean(a&&_l.test(a))}(e)).map(e=>({...e,storageProvider:["s3","vercel_blob"].includes(e?.storageProvider)?e.storageProvider:"s3",bookmarks:Bi(e?.bookmarks)})):[]}function Bl(e){return e&&"object"==typeof e?{...e,...Array.isArray(e.folders)?{folders:zl(e.folders)}:{},...Array.isArray(e.documents)?{documents:ql(e.documents)}:{}}:e}function Wl(e){return{...e,createdAt:e.metadataUpdatedAt||e.publishedAt||null,tags:Array.isArray(e.subjects)?e.subjects:[],publicMetadata:!0}}
2const Vl=({hasSubscription:n,userRoles:s=[],onOpenHelpTopic:r,initialSearchQuery:l="",onSearchQueryChange:o,initialPage:c=1,onPageChange:d,initialSort:h="title_asc",initialActiveTab:m,initialFolder:p,initialPrefix:f,onBrowseStateChange:x,publicMetadata:v=!1,publicDocumentId:y=null})=>{const{user:k,loading:w,makeAuthRequest:N}=Yn(),S=String(k?.id||"anonymous"),C=i(),E=gl(),I=s.includes("admin")||s.includes("cofounder"),_=I||!0===n,T=Boolean(l||Number(c)>1||"title_asc"!==h||null!=m||null!=p||null!=f),A=e.useRef(v?null:Ui(S)).current,O=T||A?.searchTerm||1!==Number(A?.pagination?.page||1)||"title_asc"!==(A?.sortOrder||"title_asc")?null:A,[D,P]=e.useState(()=>ql(O?.documents||[])),[L,$]=e.useState(()=>zl(O?.s3Folders||[])),[U,F]=e.useState(()=>O?.totalDocuments??null),[z,q]=e.useState(()=>f??O?.currentPrefix??""),[B,W]=e.useState(()=>!O),[ae,ne]=e.useState(()=>l||O?.searchTerm||""),[se,re]=e.useState(null),[ie,le]=e.useState(()=>function(e){const t=Number(e?.page),a=Number(e?.limit);return{page:Number.isInteger(t)&&t>0?t:1,limit:Number.isInteger(a)&&a>0?a:20}}({...O?.pagination,page:c})),[oe,ce]=e.useState(()=>Boolean(O?.s3HasMore)),[de,ue]=e.useState(null),[,he]=e.useState(!1),[me,pe]=e.useState(()=>Il(m||O?.activeTab)),[ge,fe]=e.useState(()=>O?.folders||[]),[be,xe]=e.useState(()=>(null!=p?p||"all":O?.activeFolder)||"all"),[ve,je]=e.useState(!1),[ye,ke]=e.useState(""),[we,Ne]=e.useState(new Set),[Se,Ce]=e.useState(null),Re=Ds(),[Ee,Ie]=e.useState(!1),[_e,Te]=e.useState([]),[Ae,Oe]=e.useState(!1),[De,Pe]=e.useState(-1),[Le,$e]=e.useState(!1),[Me,Ue]=e.useState([]),[Fe,ze]=e.useState("idle"),[qe,Be]=e.useState(""),[We,Ve]=e.useState(null),[He,Ke]=e.useState(""),[Ge,Je]=e.useState(!1),[Ye,Qe]=e.useState(!1),[Xe,Ze]=e.useState(null),[et,tt]=e.useState(""),[at,nt]=e.useState(!1),[st,rt]=e.useState(""),[it,lt]=e.useState(!1),[ot,ct]=e.useState(!1),[dt,ut]=e.useState(null),[ht,mt]=e.useState(!1),[pt,gt]=e.useState(null),[ft,bt]=e.useState(null),[xt,vt]=e.useState(h),[jt,yt]=e.useState(null),[kt,wt]=e.useState(!1),[Nt,St]=e.useState(0),[Ct,Rt]=e.useState(String(c)),[Et,It]=e.useState(""),[_t,Tt]=e.useState(!1),At=e.useRef(null),Ot=e.useRef(0),Dt=e.useRef(null),Pt=e.useRef(null),Lt=e.useRef(null),$t=e.useRef(0),Mt=e.useRef({}),Ut=e.useRef(null),Ft=e.useRef(null),zt=e.useRef(0),qt=e.useRef(null),Bt=e.useRef(0),Wt=e.useRef(!1),Vt=e.useRef(null),Ht=e.useRef(l),Kt=e.useRef(S),Gt=e.useRef(!1),Jt=e.useRef(null),Yt=e.useRef(null),Qt=e.useId(),Xt=e.useId(),Zt=e.useId(),ea=e.useId(),ta=e.useRef(null),aa=e.useRef(null);e.useEffect(()=>{Kt.current!==S&&(Kt.current=S,function(){if("undefined"!=typeof window)try{for(let e=window.sessionStorage.length-1;e>=0;e-=1){const t=window.sessionStorage.key(e);t?.startsWith("documentLibrary:")&&window.sessionStorage.removeItem(t)}}catch{return}}(),Ut.current?.abort(),Ft.current?.abort(),$t.current+=1,P([]),yt(null),F(null),ce(!1))},[S]),e.useEffect(()=>{Ht.current!==l&&(Ht.current=l,ne(l),re(null))},[l]),e.useEffect(()=>{const e=Number.isInteger(Number(c))&&Number(c)>0?Number(c):1;le(t=>t.page===e?t:{...t,page:e}),Rt(String(e))},[c]),e.useEffect(()=>{vt(h)},[h]),e.useEffect(()=>{null!=m&&pe(Il(m))},[m]),e.useEffect(()=>{null!=p&&xe(p||"all")},[p]),e.useEffect(()=>{null!=f&&q(f)},[f]);const na=e.useCallback(()=>{wt(!1),globalThis.requestAnimationFrame?.(()=>ta.current?.focus())},[]);e.useEffect(()=>{if(!kt)return;const e=document.body.style.overflow;document.body.style.overflow="hidden";const t=e=>{if("Escape"===e.key)return void na();if("Tab"!==e.key||!aa.current)return;const t=Array.from(aa.current.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')).filter(e=>!e.hasAttribute("hidden"));if(!t.length)return e.preventDefault(),void aa.current.focus();const a=t[0],n=t[t.length-1];!e.shiftKey||document.activeElement!==a&&document.activeElement!==aa.current?e.shiftKey||document.activeElement!==n&&document.activeElement!==aa.current||(e.preventDefault(),a.focus()):(e.preventDefault(),n.focus())};return document.addEventListener("keydown",t),globalThis.requestAnimationFrame?.(()=>{aa.current?.querySelector("button:not([disabled]), input:not([disabled]), select:not([disabled])")?.focus()}),()=>{document.body.style.overflow=e,document.removeEventListener("keydown",t)}},[na,kt]);const sa=e.useCallback(()=>{Wt.current||(Wt.current=!0,Wa(()=>import("./DocumentViewer-EKTVEOm7.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])).catch(()=>{}))},[]),ra=e.useCallback(e=>{const t=e||"getting-started";"function"!=typeof r?C(`/dashboard?tab=help&topic=${encodeURIComponent(t)}`):r(t)},[C,r]),ia=e.useMemo(()=>
2z?z.replace(/\/$/,"").split("/").filter(Boolean):[],[z]),la=e.useCallback(()=>{Fi(S,{activeTab:me,activeFolder:be,currentPrefix:z,searchTerm:ae,pagination:ie,documents:D,s3Folders:L,totalDocuments:U,s3HasMore:oe,folders:ge,sortOrder:xt})},[be,me,z,D,ge,ie,L,oe,ae,xt,U,S]),oa=e.useCallback(async()=>{if(v||!_)return;const e=function(e="anonymous"){return Di("folders",{userScope:e})}(S),t=$i(e);Array.isArray(t)&&fe(t);try{const t=await N("/api/documents/folders");if(t.ok){const a=t.data.folders||[];fe(a),Mi(e,a)}}catch(a){}},[_,N,v,S]);e.useEffect(()=>{null===n||_||(fe([]),pe("all"),xe("all"))},[_,n]);const ca=e.useCallback(async()=>{Ut.current&&Ut.current.abort();const e=new AbortController;Ut.current=e;const t=ie.page,a=ie.limit,n=ae.trim();W(!0),ue(null),he(!1),$([]);try{const s=y?`/api/public/documents/${encodeURIComponent(y)}`:(()=>{const e=new URLSearchParams({page:String(t),pageSize:String(a)});return n&&e.set("q",n),`/api/public/documents?${e}`})(),r=await fetch(rn(s),{signal:e.signal}),i=await r.json().catch(()=>null);if(!r.ok||!i?.ok)throw new Error(i?.error?.message||(y?"Document not found":"The document library is unavailable."));if(e.signal.aborted)return;if(y)P([Wl(i.data.document)]),F(null),ce(!1);else{const e=(i.data.documents||[]).map(Wl),a=i.data.pagination||{};P(e),F(a.total??e.length),yt(a),ce(t<Number(a.totalPages||t))}}catch(s){"AbortError"!==s.name&&(P([]),F(0),ce(!1),ue(s.message))}finally{e.signal.aborted||W(!1)}},[ie.limit,ie.page,y,ae]),da=e.useCallback(async({prefix:e,tab:t,limit:a,cacheKey:n})=>{const s=Date.now();if(s-(Mt.current[n]||0)<15e3)return;Mt.current[n]=s,qt.current?.abort();const r=new AbortController;qt.current=r;const i=++Bt.current;try{const s=new URLSearchParams({prefix:e,limit:String(a),offset:"0",tab:t,includeStructure:"true",structureOnly:"true",allowPrefixFallback:"true"}),l=await N(`/api/documents/browse?${s}`,{signal:r.signal});if(r.signal.aborted||i!==Bt.current||!l.ok)return void delete Mt.current[n];const o=Bl(l.data);Array.isArray(o.folders)&&$(o.folders),Mi(n,o)}catch(l){return delete Mt.current[n],void r.signal.aborted}},[N]),ua=e.useCallback(async()=>{qt.current?.abort(),Bt.current+=1,Ut.current&&Ut.current.abort();const e=new AbortController;Ut.current=e;
2const t=++$t.current,a=ie.page,n=ie.limit,s=ae.trim(),r="folders"===me?"all":me,i="all"===r&&!s&&1===a,l=i&&"all"===r&&""===z,o=i&&!l,c=(a-1)*n,d=Pi({userScope:S,activeTab:r,currentPrefix:z,limit:n,page:a,searchTerm:s,selectedSuggestionId:se,shouldIncludeStructure:o,sort:xt}),u=l?Pi({userScope:S,activeTab:r,currentPrefix:z,limit:n,page:a,searchTerm:s,shouldIncludeStructure:!0,sort:xt}):null,h=Li(d),m=Bl(h?.data),p=u?Bl($i(u)):null,g=Boolean(m?.documents);if(p&&(Array.isArray(p.folders)&&$(p.folders),null!=p.totalDocuments&&F(p.totalDocuments)),g){Array.isArray(m.folders)&&$(m.folders),P(ql(m.documents||[])),null!=m.totalDocuments&&F(m.totalDocuments),m.pagination&&yt(m.pagination);const e=m.pagination?.hasMore||!1;ce(e),ue(null),he(!1),W(!1)}else W(!0),ue(null),he(!1);if(g&&"fresh"===h?.freshness)l&&u&&!Array.isArray(p?.folders)&&da({prefix:z,tab:r,limit:n,cacheKey:u});else try{const i=new URLSearchParams({prefix:z,limit:n.toString(),offset:c.toString(),page:a.toString(),pageSize:n.toString(),tab:r,sort:xt});o||i.append("includeStructure","false"),l&&i.append("allowPrefixFallback","false"),s&&i.append("q",s),se&&i.append("documentId",se);const h=await N(`/api/documents/browse?${i}`,{signal:e.signal});if(e.signal.aborted||t!==$t.current)return;if(!h.ok){if("SUBSCRIPTION_REQUIRED"===h.error?.code)return void he(!0);throw new Error(h.error?.message||"Failed to fetch documents")}{const e=Bl(h.data);if(Array.isArray(e.folders)&&$(e.folders),P(ql(e.documents||[])),null!=e.totalDocuments&&F(e.totalDocuments),e.pagination){yt(e.pagination);const t=Number(e.pagination.page);Number.isInteger(t)&&t>0&&t!==a&&(le(e=>({...e,page:t})),Rt(String(t)),x?.({page:t},{replace:!0}))}const t=e.pagination?.hasMore||!1;if(ce(t),Mi(d,e),l&&u){Array.isArray(p?.folders)||da({prefix:z,tab:r,limit:n,cacheKey:u})}}}catch(f){if(e.signal.aborted||t!==$t.current)return;f.message?.toLowerCase().includes("subscription")?he(!0):g||(P([]),yt(null),F(0),ce(!1),ue(f.message))}finally{e.signal.aborted||t!==$t.current||g||W(!1)}},[N,z,ae,se,ie.page,ie.limit,me,da,x,xt,S]),ha=e.useCallback(async()=>{Ft.current?.abort();const e=new AbortController;Ft.current=e;
2const t=++zt.current,a=ie.page,n=ie.limit,s=ae.trim(),r=(a-1)*n,i="folders"===me?"all":me,l="folders"===me?"mine":null,o="all"!==be?be:null,c=Di("folder-list",{userScope:S,activeFolder:be,activeTab:me,folderScope:l,limit:n,offset:r,page:a,searchTerm:s.toLowerCase()}),d=$i(c),u=Boolean(d?.documents),h=Number(d?.pagination?.total),m=Number.isFinite(h)?Math.max(1,Math.ceil(Math.max(0,h)/n)):null;if(m&&a>m)return le(e=>({...e,page:m})),Rt(String(m)),void x?.({page:m},{replace:!0});u?($([]),P(ql(d.documents||[])),ce(d.pagination?.hasMore||!1),d.pagination&&yt(d.pagination),null!=d.pagination?.total&&F(d.pagination.total),ue(null),he(!1),W(!1)):(W(!0),ue(null),he(!1));try{const d=new URLSearchParams({limit:n.toString(),offset:r.toString(),tab:i,skip_count:"false"});l&&d.append("folder_scope",l),o&&d.append("folder_id",o),s&&d.append("q",s);const u=await N(`/api/documents/list?${d}`,{signal:e.signal});if(e.signal.aborted||t!==zt.current)return;if(!u.ok){if("SUBSCRIPTION_REQUIRED"===u.error?.code)return void he(!0);throw new Error(u.error?.message||"Failed to fetch documents")}{const e=Number(u.data.pagination?.total),t=Number.isFinite(e)?Math.max(1,Math.ceil(Math.max(0,e)/n)):null;if(t&&a>t)return le(e=>({...e,page:t})),Rt(String(t)),void x?.({page:t},{replace:!0});$([]),P(ql(u.data.documents||[])),ce(u.data.pagination?.hasMore||!1),yt(u.data.pagination||null),null!=u.data.pagination?.total&&F(u.data.pagination.total),Mi(c,u.data)}}catch(p){if(e.signal.aborted||t!==zt.current||"REQUEST_CANCELLED"===p.code)return;p.message?.toLowerCase().includes("subscription")?he(!0):u||(P([]),yt(null),F(0),ce(!1),ue(p.message))}finally{u||e.signal.aborted||t!==zt.current||W(!1)}},[N,be,ae,ie.page,ie.limit,me,x,S]);e.useEffect(()=>{oa()},[oa]),e.useEffect(()=>{if(!v&&null===n)return;Dt.current&&clearTimeout(Dt.current);const e=v?ca:"all"!==be||"folders"===me?ha:ua;return ae.trim()?Dt.current=setTimeout(e,400):e(),()=>{Dt.current&&clearTimeout(Dt.current),Ut.current&&Ut.current.abort(),Ft.current&&Ft.current.abort(),qt.current&&(qt.current.abort(),Bt.current+=1)}},[ae,se,me,be,z,ie.page,ie.limit,Nt,ua,ca,ha,n,v]),e.useEffect(()=>{const e=++Ot.current;At.current&&clearTimeout(At.current);const t=ae.trim(),a="folders"===me;return!t||t.length<2||a||y?(Te([]),Oe(!1),void $e(!1)):se?void 0:(At.current=setTimeout(async()=>{try{$e(!0);const a=new URLSearchParams({q:t,limit:"8"});if("all"!==me&&a.append("tab",me),z&&a.append("prefix",z),"all"!==be&&a.append("folder_id",be),v){const t=await fetch(rn(`/api/public/documents/suggest?${a}`)),n=await t.json().catch(()=>null);if(e!==Ot.current)return;t.ok&&n?.ok&&(Te((n.data?.suggestions||[]).map(e=>({documentId:e.id,label:e.displayTitle}))),Oe(!0))}else{const t=await N(`/api/documents/suggest?${a}`);if(e!==Ot.current)return;t.ok&&(Te(t.data.suggestions||[]),Oe(!0))}}catch(a){if(e!==Ot.current)return}finally{e===Ot.current&&$e(!1)}},250),()=>{At.current&&clearTimeout(At.current)})},[ae,me,z,be,se,N,y,v]),e.useEffect(()=>{Pt.current&&clearTimeout(Pt.current),Lt.current&&Lt.current.abort();const e=ae.trim();return!e||v||!I&&!0!==n||"all"!==me||"all"!==be||""!==z||1!==ie.page?(Ue([]),ze("idle"),void Be("")):(Pt.current=window.setTimeout(async()=>{const t=new AbortController;Lt.current=t,ze("loading"),Be("");try{const a=await E.search({query:e,resultType:"all",filters:{language:null,author:null,classification:null,hasPageText:!1},cursor:null},{limit:50,signal:t.signal});if(t.signal.aborted)return;Ue(a.results||[]),ze("ready")}catch(a){if(t.signal.aborted||"REQUEST_CANCELLED"===a.code)return;Ue([]),ze("unavailable"),Be("Document text matching is temporarily unavailable. Title and metadata results are still shown.")}},400),()=>{Pt.current&&clearTimeout(Pt.current),Lt.current&&Lt.current.abort()})},[be,me,z,E,n,I,ie.page,v,ae]),e.useEffect(()=>{v||la()},[la,v]);const ma=e=>{Ve(null),Ke(""),xe("all"),vt("title_asc"),q(e),le(e=>({...e,page:1})),x?.({sort:"title_asc",page:1,collectionTab:me,folder:"",prefix:e})},pa=e.useCallback(async(e,t)=>{if(!t||"none"===t)return!1;const a=e?.id?String(e.id):null,n=e?.storageKey?String(e.storageKey):null,
2s=e?.storageProvider?String(e.storageProvider):null;if(!a&&!n)return Re({type:"error",message:"This document cannot be added to folders yet"}),!1;try{const e={folderId:t,...a?{documentId:a}:{storageKey:n},...s?{storageProvider:s}:{}},r=await N("/api/documents/folders/items",{method:"POST",body:JSON.stringify(e)});if(!r.ok)return Re({type:"error",message:r.error?.message||"Failed to add document to folder"}),!1;const i=r.data?.documentId?String(r.data.documentId):a;return P(e=>e.map(e=>{const r=a&&String(e.id||"")===a,l=!a&&e.storageProvider===s&&n&&String(e.storageKey||"")===n;if(!r&&!l)return e;const o=Array.isArray(e.folderIds)?e.folderIds:[],c=Array.from(new Set([...o,t]));return{...e,id:e.id||i||null,folderIds:c}})),oa(),!0}catch(r){return Re({type:"error",message:"Failed to update folder assignment"}),!1}},[oa,N,Re]),ga=e.useCallback(e=>{Ve(t=>{const a=t===e?null:e;return a||Ke(""),a})},[]),fa=e.useCallback(()=>{Ve(null),Ke("")},[]);e.useEffect(()=>{if(!We)return;const e=Jt.current,t=Yt.current;globalThis.requestAnimationFrame?.(()=>{e?.querySelector("button:not(:disabled), input:not(:disabled)")?.focus()});const a=e=>{"Escape"===e.key&&(e.preventDefault(),fa(),globalThis.requestAnimationFrame?.(()=>t?.focus()))},n=a=>{e?.contains(a.target)||t?.contains(a.target)||(fa(),globalThis.requestAnimationFrame?.(()=>t?.focus()))};return document.addEventListener("keydown",a),document.addEventListener("pointerdown",n),()=>{document.removeEventListener("keydown",a),document.removeEventListener("pointerdown",n)}},[fa,We]);const ba=e.useCallback(e=>{const t=String(e?.filename||e?.displayTitle||""||"").replace(/\.pdf$/i,""),a=t.replace(/[._-]+/g," ").replace(/\s+/g," ").trim(),n=String(e?.displayTitle||"").replace(/\s+/g," ").trim();Ze(e||null),tt(t),nt(!n||n===a),rt(""),Qe(!0)},[]),xa=e.useCallback(()=>{it||(Qe(!1),Ze(null),tt(""),nt(!1),rt(""))},[it]),va=e.useCallback(async()=>{if(!Xe||it)return;const e=et.trim();if(e){lt(!0);try{const t={nextName:e,updateDisplayTitle:at};Xe.id&&(t.documentId=Xe.id),Xe.storageKey&&(t.storageKey=Xe.storageKey),Xe.storageProvider&&(t.storageProvider=Xe.storageProvider);const a=await N("/api/admin/documents/rename",{method:"PATCH",body:JSON.stringify(t)});if(!a?.ok)throw new Error(a?.error?.message||"Failed to rename document");const n=a.data?.documentId,s=a.data?.storageKey,r=a.data?.storageProvider,i=a.data?.filename,l=a.data?.title,o=a.data?.normalizedFilename||i,c=Xe.storageKey;P(e=>qi(e,{id:n||Xe.id||null,storageKey:s,storageProvider:r||Xe.storageProvider,filename:i,displayTitle:l},{id:Xe.id,storageProvider:Xe.storageProvider,storageKey:c})),fa(),Xe.id&&se===Xe.id&&re(null),Qe(!1),Ze(null),tt(""),nt(!1),rt(o||""),Re({type:"success",message:"PDF name updated successfully"})}catch(t){const a=e.toLowerCase().endsWith(".pdf")?e.replace(/\.pdf$/i,".pdf"):`${e}.pdf`;rt(a),Re({type:"error",message:t.message||"Failed to rename document"})}finally{lt(!1)}}else Re({type:"error",message:"Please enter a new PDF name"})},[fa,N,Re,at,it,Xe,et,se]),ja=e.useCallback(e=>{ut(e||null),ct(!0)},[]),ya=e.useCallback(()=>{ht||(ct(!1),ut(null))},[ht]),ka=e.useCallback(async()=>{if(dt&&!ht){mt(!0);try{const e={};if(dt.id){if(e.documentId=dt.id,!dt.storageKey||!dt.storageProvider)throw new Error("Document storage identity is missing");e.storageKey=dt.storageKey}else{if(!dt.storageKey)throw new Error("Document identifier is missing");e.storageKey=dt.storageKey}dt.storageProvider&&(e.storageProvider=dt.storageProvider);const t=await N("/api/admin/documents/delete",{method:"DELETE",body:JSON.stringify(e)});if(!t?.ok)throw new Error(t?.error?.message||"Failed to delete document");const a=t.data?.storageKey||dt.storageKey||null,n=t.data?.storageProvider||dt.storageProvider||null,s=Array.isArray(t.data?.deletedDocumentIds)?t.data.deletedDocumentIds.map(e=>String(e)):dt.id?[String(dt.id)]:[];P(e=>e.filter(e=>{const t=e?.id?String(e.id):null,r=!!t&&s.includes(t),i=n&&e?.storageProvider===n&&a&&String(e?.storageKey||"")===String(a);return!(r||i)})),fa(),Qe(!1),Ze(null),tt(""),ct(!1),ut(null);const r=t.data?.warning?.code||null;Re("DOCUMENT_STORAGE_DELETE_FAILED"===r?{type:"warning",message:"Document record was deleted, but storage cleanup needs retry."}:{type:"success",message:"PDF deleted successfully"})}catch(e){Re({type:"error",message:e.message||"Failed to delete document"})}finally{mt(!1)}}},[fa,ht,dt,N,Re]),wa=e.useCallback(async(e,t)=>{await pa({id:e?.id,storageProvider:e?.storageProvider,storageKey:e?.storageKey},String(t))&&(Re({type:"success",message:"Document added to folder"}),fa())},[fa,pa,Re]),Na=e.useCallback(async e=>{const t=He.trim();if(t&&!Ge){Je(!0);try{const a="all"!==be?be:null,n=await N("/api/documents/folders",{method:"POST",body:JSON.stringify({name:t,parentId:a})});if(!n.ok)return void Re({type:"error",message:n.error?.message||"Failed to create folder"});const s=n.data.folder;fe(e=>e.some(e=>e.id===s.id)?e:[...e,s]),Ne(e=>new Set(e).add(a||s.id));await pa({id:e?.id,storageProvider:e?.storageProvider,storageKey:e?.storageKey}
2,String(s.id))&&(Re({type:"success",message:"Folder created and document added"}),fa())}catch(a){Re({type:"error",message:"Failed to create folder and add document"})}finally{Je(!1)}}},[be,fa,pa,N,Re,He,Ge]),Sa=e.useCallback((e,t,a)=>{e.currentTarget.focus(),bt(function(e,{displayTitle:t}={}){const a=Number(e?.pageCount??e?.page_count),n=mi(e?.projectionCompleteness,64)?.toUpperCase(),s=mi(e?.projectionStatus,64)?.toUpperCase(),r=[n,s].some(e=>["CONFLICT","FAILED"].includes(e))?"Metadata is temporarily unavailable. The last safe values are shown when available.":"PARTIAL"===n?"This record is partial. Some unavailable or invalid fields were safely omitted.":["MISSING","UNAVAILABLE"].includes(s)?"Additional catalog metadata is not available yet.":null;return Object.freeze({title:mi(t,512)||mi(e?.displayTitle,512)||mi(e?.title,512)||mi(e?.displayName,512)||"Untitled document",description:mi(e?.description),authors:pi(e?.authors),editors:pi(e?.editors),aliases:pi(e?.aliases),publicationDate:mi(e?.publicationDate,128),language:mi(e?.language,128),documentType:mi(e?.documentType,256),volume:mi(e?.volume,256),coveredPeriodStart:mi(e?.coveredPeriodStart,128),coveredPeriodEnd:mi(e?.coveredPeriodEnd,128),collection:mi(e?.collection,512),subjects:pi(e?.subjects?.length?e.subjects:e?.tags),citation:mi(e?.citation),pageCount:Number.isInteger(a)&&a>0?a:null,metadataNotice:r})}(t,{displayTitle:a}))},[]),Ca=e.useCallback(()=>{bt(null)},[]),Ra=e.useCallback(e=>{const t=e&&"object"==typeof e,a=t?e.label:String(e);v&&t?(Gt.current=!1,C(`/documents/${e.documentId}`)):(ne(a),re(t?e.documentId:null),le(e=>({...e,page:1})),Rt("1"),x?.({q:a,page:1},{replace:!0})),Pe(-1),Oe(!1)},[C,x,v]),Ea=e.useCallback(e=>{Gt.current=!0,ne(e),re(null),Pe(-1),le(e=>({...e,page:1})),Rt("1"),o?.(e),x?.({q:e,page:1},{replace:!0})},[x,o]),Ia=e.useCallback(()=>{Ea(""),globalThis.requestAnimationFrame?.(()=>Vt.current?.focus())},[Ea]),_a=e=>{const t=Math.min(Ba,Math.max(1,Number(e)||1));le(e=>({...e,page:t})),Rt(String(t)),It(""),d?.(t),x?.({page:t})},Ta=e.useMemo(()=>{if(!ae.trim()||"idle"===Fe)return D;const e=new Map;for(const n of Me){const t=n.documentId;t&&(e.has(t)||e.set(t,{title:n.documentDisplayName||n.displayName||"Untitled document",documentMatch:null,pages:[]}),"document"===n.resultType&&(e.get(t).documentMatch={isExactIdentifierMatch:n.isExactIdentifierMatch,matchedFields:n.matchedFields,matchMode:n.matchMode}),"page"===n.resultType&&e.get(t).pages.length<3&&e.get(t).pages.push({id:n.documentPageId,pageNumber:n.pageNumber,snippet:n.snippet,matchMode:n.matchMode}))}const t=D.map(t=>({...t,documentMatch:e.get(t.id)?.documentMatch||null,pageMatches:e.get(t.id)?.pages||[]})),a=new Set(D.map(e=>e.id).filter(Boolean));for(const[n,s]of e)a.has(n)||t.push({id:n,displayTitle:s.title,filename:s.title,documentMatch:s.documentMatch,pageMatches:s.pages,enhancedOnly:!0});return t},[D,Me,Fe,ae]),Aa=e.useMemo(()=>Ta.reduce((e,t)=>e+(t.pageMatches?.length||0),0),[Ta]),Oa=e.useMemo(()=>{const e=new Map;return Ta.forEach(t=>{const a=Ml(t?.displayTitle||t?.filename);a&&e.set(a,(e.get(a)||0)+1)}),e},[Ta]),Da=e=>e?new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}):"Unknown",Pa=e.useMemo(()=>{const e=new Map;return ge.forEach(t=>{const a=t.parent_id||null;e.has(a)||e.set(a,[]),e.get(a).push(t)}),e.forEach(e=>e.sort((e,t)=>e.name.localeCompare(t.name))),e},[ge]),La=e.useMemo(()=>"all"===be?"All Documents":ge.find(e=>e.id===be)?.name||"Selected Folder",[be,ge]),$a="all"!==be,Ma="bookmarks"===me,Ua="folders"===me,Fa=Number(jt?.total??U??0),za=!1!==jt?.totalIsExact&&(null!=jt?.total||null!=U),qa=Boolean(jt?.hasNext??jt?.hasMore??oe),Ba=Math.max(1,Number(jt?.totalPages)||(za?Math.ceil(Fa/ie.limit):ie.page+(qa?1:0))||1),Va=function(e,t,a=2){const n=Math.max(1,Number(t)||1),s=Math.min(Math.max(1,Number(e)||1),n),r=new Set([1,n]);for(let o=Math.max(1,s-a);o<=Math.min(n,s+a);o+=1)r.add(o);const i=[...r].sort((e,t)=>e-t),l=[];for(let o=0;o<i.length;o+=1){const e=i[o];o>0&&e-i[o-1]>1&&l.push(`ellipsis-${i[o-1]}-${e}`),l.push(e)}return l}(ie.page,Ba),Ha=$a||z?"This folder is empty":Ma?"No bookmarks or favorites yet":Ua?"No foldered documents yet":"No documents found",Ka=ae?"Try adjusting your search terms":$a?"Save PDFs to this folder using the plus button on a document.":z?"There are no documents directly in this folder.":Ma?"Bookmark pages or favorite documents to keep them here.":Ua?"Create folders on the left, then use the plus button on any PDF to organize it.":"Upload your first document to get started",Ga=v?"Search public titles, authors, subjects, dates, and other catalog metadata.":!I&&!0!==n||"all"!==me||"all"!==be||z?"Search titles and metadata in the current library view.":"Search titles and metadata, with available document-text matches grouped by document.";e.useEffect(()=>
2{Ne(new Set(ge.map(e=>e.id)))},[ge]);const Ja=e.useCallback((e,t)=>{if(e===t)return!0;const a=[e];for(;a.length>0;){const e=a.pop(),n=Pa.get(e)||[];for(const s of n){if(s.id===t)return!0;a.push(s.id)}}return!1},[Pa]),Ya=(e,a=0)=>{const n=Pa.get(e.id)||[],s=we.has(e.id);return t.jsxs("div",{className:"folder-node",style:{"--folder-depth":a},children:[t.jsxs("div",{className:"folder-row "+(be===e.id?"active":""),children:[n.length>0?t.jsx("button",{type:"button",className:"folder-toggle",onClick:()=>{return t=e.id,void Ne(e=>{const a=new Set(e);return a.has(t)?a.delete(t):a.add(t),a});var t},"aria-label":s?"Collapse folder":"Expand folder",children:s?t.jsx(u,{size:14}):t.jsx(J,{size:14})}):t.jsx("span",{className:"folder-toggle placeholder"}),t.jsxs("button",{type:"button",className:"folder-item",onClick:()=>{Ve(null),Ke(""),xe(e.id),vt("title_asc"),q(""),le(e=>({...e,page:1})),x?.({sort:"title_asc",page:1,collectionTab:me,folder:e.id,prefix:""})},children:[t.jsx("span",{children:e.name}),t.jsx("span",{className:"folder-count",children:e.document_count||0})]}),t.jsx("button",{type:"button",className:"folder-delete",onClick:t=>{t.stopPropagation(),Ce(e),Ie(!0)},"aria-label":`Delete ${e.name}`,title:"Delete folder",children:t.jsx(te,{size:14})})]}),n.length>0&&s&&t.jsx("div",{className:"folder-children",children:n.map(e=>Ya(e,a+1))})]},e.id)};return v||null!==n?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`document-library${v?" document-library--public":""}${y?" document-library--detail":""}`,children:[!v&&t.jsx("h1",{className:"document-library-page-title",children:"Documents"}),v||!1!==n?null:t.jsxs("div",{className:"document-library-upgrade-note",role:"note",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"Eligible original library PDFs are available after sign-in."}),t.jsx("span",{children:"Upgrade for enhanced full-text search, extracted text, split PDF/text reading, bookmarks, and personal folders. Community availability depends on your account."})]}),t.jsx("button",{type:"button",onClick:()=>C("/subscribe"),children:"View paid features"})]}),t.jsxs("div",{className:"document-library-layout",children:[kt&&t.jsx("button",{type:"button",className:"mobile-folder-backdrop",onClick:na,"aria-label":"Close folder browser"}),t.jsx("div",{ref:aa,className:"document-library-sidebar"+(kt?" open":""),role:kt?"dialog":void 0,"aria-modal":kt?"true":void 0,"aria-labelledby":kt?ea:void 0,tabIndex:kt?-1:void 0,children:t.jsxs("div",{id:"document-folder-navigation",className:"document-folder-navigation"+(kt?" open":""),children:[t.jsxs("div",{className:"mobile-folder-panel-header",children:[t.jsx("strong",{id:ea,children:"Browse folders"}),t.jsx("button",{type:"button",className:"mobile-folder-close",onClick:na,"aria-label":"Close folder browser",children:t.jsx(g,{size:20,"aria-hidden":"true"})})]}),t.jsxs("div",{className:"folder-sidebar-header",children:[t.jsxs("div",{children:[t.jsx("p",{className:"folder-sidebar-title",children:"Research Library"}),t.jsx("p",{className:"folder-sidebar-subtitle",children:"Browse the collection"})]}),(!v||"function"==typeof r)&&t.jsx("button",{type:"button",className:"document-library-help-btn",onClick:()=>ra("find-documents"),"aria-label":"Help for browsing and searching documents",title:"Documents help",children:t.jsx(R,{size:14})})]}),t.jsxs("div",{className:"folder-tree folder-tree--library",children:[t.jsxs("button",{type:"button",className:"folder-item root "+("all"!==be||z?"":"active"),onClick:()=>{Ve(null),Ke(""),pe("all"),xe("all"),q(""),le(e=>({...e,page:1})),x?.({page:1,collectionTab:"all",folder:"",prefix:""})},children:[t.jsx(V,{size:14}),t.jsx("span",{children:"All Documents"}),null!=U&&U>0&&t.jsx("span",{className:"folder-count",children:U.toLocaleString()})]}),"all"===be&&z&&t.jsx("div",{className:"s3-sidebar-path",children:ia.map((e,a)=>{const n=ia.slice(0,a+1).join("/")+"/",s=n===z;return t.jsxs("button",{type:"button",className:"folder-item s3-path-item "+(s?"active":""),style:{"--folder-depth":a},onClick:()=>ma(n),children:[s?t.jsx(M,{size:14}):t.jsx(H,{size:14}),t.jsx("span",{children:decodeURIComponent(e)})]},n)})}),"all"===be&&L.length>0&&!ae&&t.jsxs("div",{className:"s3-sidebar-folders",children:[t.jsx("p",{className:"s3-sidebar-subheading",children:z?"
2Subfolders":"Folders"}),L.map(e=>t.jsxs("button",{type:"button",className:"folder-item s3-subfolder-item",style:{"--folder-depth":ia.length},onClick:()=>ma(e.prefix),children:[t.jsx(H,{size:14}),t.jsx("span",{children:e.name}),e.documentCount>0&&t.jsx("span",{className:"folder-count",children:e.documentCount.toLocaleString()})]},e.prefix))]})]}),!v&&_&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"folder-sidebar-divider"}),t.jsxs("div",{className:"folder-sidebar-header",children:[t.jsxs("div",{children:[t.jsx("p",{className:"folder-sidebar-title",children:"My Folders"}),t.jsx("p",{className:"folder-sidebar-subtitle",children:"Organize your workspace"})]}),t.jsxs("div",{className:"folder-sidebar-actions",children:[t.jsx("button",{type:"button",className:"document-library-help-btn",onClick:()=>ra("organize-documents"),"aria-label":"Help for folders workflow",title:"Folders help",children:t.jsx(R,{size:14})}),t.jsxs(ds,{variant:"secondary",size:"small",onClick:()=>je(!0),className:"folder-new-btn",children:[t.jsx(K,{size:16}),"New"]})]})]}),ve&&t.jsxs("div",{className:"folder-create-form",children:[t.jsx("input",{value:ye,onChange:e=>ke(e.target.value),placeholder:"Folder name"}),t.jsxs("p",{className:"folder-create-hint",children:["Creating in: ",La]}),t.jsxs("div",{className:"folder-create-actions",children:[t.jsx(ds,{variant:"primary",size:"small",onClick:async()=>{const e=ye.trim();if(e)try{const t="all"!==be?be:null,a=await N("/api/documents/folders",{method:"POST",body:JSON.stringify({name:e,parentId:t})});a.ok?(fe(e=>[...e,a.data.folder]),ke(""),je(!1),Ne(e=>new Set(e).add(t||a.data.folder.id))):Re({type:"error",message:a.error?.message||"Failed to create folder"})}catch(t){Re({type:"error",message:"Failed to create folder"})}},children:"Create"}),t.jsx(ds,{variant:"ghost",size:"small",onClick:()=>{je(!1),ke("")},children:"Cancel"})]})]}),t.jsx("div",{className:"folder-tree folder-tree--user",children:(Pa.get(null)||[]).map(e=>Ya(e,0))})]})]})}),t.jsxs("div",{className:"document-library-main",children:[t.jsx("div",{className:"document-library-header",children:y?t.jsxs("button",{type:"button",className:"breadcrumb-back",onClick:()=>C("/documents"),children:[t.jsx(G,{size:16}),"Back to library"]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"document-tab-actions",children:[t.jsx("div",{className:"document-tabs",role:"group","aria-label":"Document collections",children:(v||!_?El.slice(0,1):El).map(e=>t.jsx("button",{type:"button",className:"document-tab "+(me===e.id?"active":""),onClick:()=>(e=>{const t=Il(e),a="folders"===t?be:"all";Ve(null),Ke(""),pe(t),re(null),xe(a),vt("title_asc"),q(""),le(e=>({...e,page:1})),x?.({sort:"title_asc",page:1,collectionTab:t,folder:"all"===a?"":a,prefix:""})})(e.id),"aria-pressed":me===e.id,children:e.label},e.id))}),(!v||"function"==typeof r)&&t.jsx("button",{type:"button",className:"document-library-help-btn",onClick:()=>ra("find-documents"),"aria-label":"Help for document tabs and search",title:"Search and tabs help",children:t.jsx(R,{size:14})})]}),t.jsx("div",{className:"search-and-filters",children:t.jsxs("div",{className:"document-search-wrapper","data-guidance-target":"documents",children:[t.jsx("label",{className:"document-search-label",htmlFor:Xt,children:"Search the research library"}),t.jsx("p",{id:Zt,className:"document-search-description",children:Ga}),t.jsx(oi,{ref:Vt,id:Xt,value:ae,onChange:Ea,onClear:()=>globalThis.requestAnimationFrame?.(()=>Vt.current?.focus()),placeholder:"Title, author, subject, or keyword","aria-label":"Search documents","aria-describedby":Zt,"aria-busy":Le,name:"document-search",className:"document-search",maxLength:v?200:120,role:"combobox","aria-autocomplete":"list","aria-expanded":Ae&&_e.length>0,"aria-controls":Qt,"aria-activedescendant":De>=0?`${Qt}-option-${De}`:void 0,onKeyDown:e=>"Escape"===e.key?(Oe(!1),void Pe(-1)):_e.length?"ArrowDown"===e.key||"ArrowUp"===e.key?(e.preventDefault(),Oe(!0),void Pe(t=>"ArrowDown"===e.key?t>=_e.length-1?0:t+1:t<=0?_e.length-1:t-1)):void("Enter"===e.key&&De>=0&&(e.preventDefault(),Ra(_e[De]))):void 0,onFocus:()=>{Gt.current=!0,ae&&!se&&_e.length&&Oe(!0)},onBlur:()=>{Gt.current=!1,Ot.current+=1,setTimeout(()=>Oe(!1),150)}}),Ae&&_e.length>0&&t.jsx("div",{id:Qt,className:"search-suggestions",role:"listbox","aria-label":"Document search suggestions",children:_e.map((e,a)=>{const n=e&&"object"==typeof e,s=n?e.documentId:String(e),r=n?e.label:String(e);return t.jsxs("button",{type:"button",id:`${Qt}-option-${a}`,className:"suggestion-item"+(De===a?" suggestion-item--active":""),role:"option","aria-label":r,"aria-selected":De===a,tabIndex:-1,onMouseMove:()=>Pe(a),onMouseDown:e=>{e.preventDefault()},onClick:()=>Ra(e),children:[t.jsx("span",{className:"suggestion-item-label",dir:"auto",children:r}),t.jsx("span",{className:"suggestion-item-hint","aria-hidden":"true",children:v?"Open metadata":"Use suggestion"})]},s)})}),Le&&t.jsx("div",{className:"suggestion-loading",role:"status","aria-live":"polite",children:"Finding suggestionsâ¦"})]})})]})}),!v&&!y&&t.jsxs("button",{ref:ta,type:"button",className:"mobile-folder-disclosure","aria-expanded":kt,"aria-controls":"document-folder-navigation",onClick:()=>wt(!0),children:[t.jsx(H,{size:16,"aria-hidden":"true"}),_?"Browse and manage folders":"Browse library folders",t.jsx(J,{size:16,"aria-hidden":"true"})]}
2),!y&&t.jsxs("section",{className:"document-browse-controls","aria-label":"Document result controls",children:[t.jsx("div",{className:"document-results-summary",role:"status","aria-live":"polite",children:B&&0===D.length?t.jsx("span",{children:"Loading resultsâ¦"}):B?t.jsx("span",{children:"Updating resultsâ¦"}):t.jsxs("span",{children:[Fa.toLocaleString()," ",1===Fa?"result":"results"," · ","Page ",Math.min(ie.page,Ba)," of ",Ba]})}),!v&&t.jsxs("label",{className:"document-sort-control",children:[t.jsx("span",{children:"Sort"}),t.jsxs("select",{value:xt,onChange:e=>{return t=e.target.value,vt(t),le(e=>({...e,page:1})),Rt("1"),void x?.({sort:t,page:1});var t},"aria-label":"Sort documents",children:[t.jsx("option",{value:"title_asc",children:"Title AâZ"}),t.jsx("option",{value:"most_viewed",children:"Most viewed"}),t.jsx("option",{value:"most_favorited",children:"Most favorited"}),t.jsx("option",{value:"title_desc",children:"Title ZâA"}),t.jsx("option",{value:"newest",children:"Newest first"}),t.jsx("option",{value:"oldest",children:"Oldest first"})]})]})]}),ae.trim()&&"loading"===Fe?t.jsx("p",{className:"document-search-status",role:"status",children:"Searching document textâ¦"}):null,"unavailable"===Fe?t.jsx("p",{className:"document-search-status document-search-status--warning",role:"status",children:qe}):null,ae.trim()&&"ready"===Fe?t.jsxs("p",{className:"document-search-status",role:"status","aria-live":"polite",children:[Ta.length," ",1===Ta.length?"document matches":"documents match"," in title and metadata",Aa>0?`, with ${Aa} supporting ${1===Aa?"page match":"page matches"}.`:"."]}):null,de&&t.jsx("div",{role:"alert","aria-live":"assertive",children:t.jsxs(Js,{className:"error-card",children:[t.jsx("p",{className:"error-message",children:de}),t.jsx(ds,{variant:"secondary",size:"small",onClick:()=>St(e=>e+1),children:"Retry"})]})}),"all"===be&&z&&t.jsxs("div",{className:"s3-breadcrumbs",children:[t.jsxs("button",{type:"button",className:"breadcrumb-back",onClick:()=>{if(!z)return;Ve(null),Ke("");const e=z.replace(/\/$/,"").split("/").filter(Boolean);e.pop();const t=e.length>0?e.join("/")+"/":"";q(t),le(e=>({...e,page:1})),x?.({page:1,collectionTab:me,folder:"",prefix:t})},"aria-label":"Go back",children:[t.jsx(G,{size:16}),"Back"]}),t.jsxs("div",{className:"breadcrumb-trail",children:[t.jsxs("button",{type:"button",className:"breadcrumb-segment",onClick:()=>ma(""),children:[t.jsx(V,{size:14}),"Research Library"]}),ia.map((e,n)=>{const s=ia.slice(0,n+1).join("/")+"/",r=n===ia.length-1;return t.jsxs(a.Fragment,{children:[t.jsx(J,{size:14,className:"breadcrumb-separator"}),r?t.jsxs("span",{className:"breadcrumb-current",children:[t.jsx(M,{size:14}),decodeURIComponent(e)]}):t.jsxs("button",{type:"button",className:"breadcrumb-segment",onClick:()=>ma(s),children:[t.jsx(H,{size:14}),decodeURIComponent(e)]})]},s)})]})]}),t.jsx("div",{className:"document-library-results","aria-busy":B,children:B&&0===D.length?t.jsxs("div",{className:"loading-state",children:[t.jsx("div",{className:"spinner"}),t.jsx("p",{children:"Loading resultsâ¦"})]}):de||0!==Ta.length||0!==L.length?t.jsxs(t.Fragment,{children:[B&&t.jsxs("div",{className:"document-inline-progress",role:"status",children:[t.jsx("span",{className:"document-inline-progress-spinner","aria-hidden":"true"}),"Updating resultsâ¦"]}),"all"===be&&L.length>0&&!ae&&t.jsx("div",{className:"s3-folders-grid",children:L.map(e=>t.jsxs("button",{type:"button",className:"s3-folder-card",onClick:()=>ma(e.prefix),children:[t.jsx(M,{size:28,className:"s3-folder-icon"}),t.jsxs("div",{className:"s3-folder-info",children:[t.jsx("span",{className:"s3-folder-name",children:e.name}),e.documentCount>0&&t.jsxs("span",{className:"s3-folder-count",children:[e.documentCount.toLocaleString()," ",1===e.documentCount?"document":"documents"]})]}),t.jsx(J,{size:18,className:"s3-folder-chevron"})]},e.prefix))}),Ta.length>0&&t.jsx("div",{className:"documents-list",role:"list","aria-label":"Documents",children:Ta.map(e=>{const a=e.displayTitle||e.filename,n=e.createdAt||e.created_at,s=e.pageCount||e.page_count,r=(Oa.get(Ml(a))||0)>1,i=Fl(e,{title:a,isDuplicateTitle:r,formatDate:Da}),l=String(e.id||`${e.storageProvider||"unknown"}:${e.storageKey||e.filename||""}`),o=`document-folder-panel-${l.replace(/[^a-zA-Z0-9_-]/g,"-")}`,c=_&&Boolean(e.id||e.storageKey),d=c&&We===l,u=Bi(e.bookmarks),h=e.tags?.length?e.tags:e.subjects||[];return t.jsxs("div",{className:"document-row",role:"listitem",children:[t.jsxs("div",{className:"document-row-main",children:[t.jsxs("div",{className:"document-metadata-trigger",role:"button",tabIndex:0,"aria-haspopup":"dialog","aria-label":`View metadata for ${a}`,onClick:t=>Sa(t,e,a),onKeyDown:t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),Sa(t,e,a))},children:[t.jsx("span",{className:"document-file-icon","aria-hidden":"true",children:t.jsx(j,{size:20})}),t.jsxs("div",{className:"document-row-body",children:[t.jsxs("div",{className:"document-row-title-line",children:[t.jsx("h2",{className:"document-filename",title:a,dir:"auto",children:a}),h.length>0&&t.jsx("div",{className:"document-tags",children:h.slice(0,3).map(e=>t.jsx(li,{variant:"gray",className:"document-tag",children:e},e))}),t.jsxs("span",{className:"document-metadata-affordance","aria-hidden":"true",children:[t.jsx(Y,{size:13}),"Details"]}
2)]}),i&&t.jsx("div",{className:"document-title-context",title:i,dir:"auto",children:i}),e.description?t.jsx("div",{className:"document-title-context document-description-preview",title:e.description,"aria-label":e.description,dir:"auto",children:e.description}):null,e.documentMatch?t.jsx("div",{className:"document-match-context",children:Ol(e.documentMatch)}):null,t.jsxs("div",{className:"document-row-meta",children:[Pl("By",e.authors),Pl("Edited by",e.editors),e.publicationDate?t.jsxs("span",{children:["Published ",e.publicationDate]}):null,e.language?t.jsxs("span",{children:["Language ",e.language]}):null,e.documentType?t.jsx("span",{children:e.documentType}):null,e.collection?t.jsx("span",{children:e.collection}):null,y&&e.citation?t.jsxs("span",{children:["Citation ",e.citation]}):null,v||e.enhancedOnly?null:t.jsxs("span",{children:["Uploaded ",Da(n)]}),s&&t.jsxs("span",{children:[s," ",1===s?"page":"pages"]}),!v&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"document-stat",title:`Recorded opens: ${e.viewCount||0}`,"aria-label":`Recorded opens: ${e.viewCount||0}`,children:[t.jsx(Q,{size:14,"aria-hidden":"true"}),e.viewCount||0]}),t.jsxs("span",{className:"document-stat",title:`Users who favorited: ${e.favoriteCount||0}`,"aria-label":`Users who favorited: ${e.favoriteCount||0}`,children:[t.jsx(b,{size:14,"aria-hidden":"true"}),e.favoriteCount||0]})]}),"bookmarks"===me&&u.length>0&&t.jsxs("span",{className:"document-stat",title:`Your bookmarked pages: ${u.length}`,"aria-label":`Your bookmarked pages: ${u.length}`,children:[t.jsx(X,{size:14,"aria-hidden":"true"}),u.length]})]}),"bookmarks"===me&&u.length>0&&t.jsxs("div",{className:"document-bookmarks",children:[t.jsx("span",{children:"Bookmarked pages:"}),t.jsxs("span",{className:"document-bookmarks-list",children:[u.slice(0,6).join(", "),u.length>6?"...":""]})]})]})]}),e.pageMatches?.length>0?t.jsx("ul",{className:"document-page-matches","aria-label":`Matching pages in ${a}`,children:e.pageMatches.map((a,n)=>t.jsx("li",{children:t.jsxs("button",{type:"button",title:a.snippet||void 0,"aria-label":`Matched page ${a.pageNumber||"result"}`,onClick:()=>{const t=new URLSearchParams;a.pageNumber&&t.set("page",String(a.pageNumber)),t.set("highlight",ae.trim()),C(`/documents/${e.id}?${t.toString()}`)},children:[t.jsxs("span",{className:"document-page-match-kind",children:[Dl(a),t.jsx("span",{"aria-hidden":"true",children:" · "}),t.jsxs("span",{children:["Page ",a.pageNumber||"result"]})]}),a.snippet?t.jsx("span",{className:"document-page-match-snippet",dir:"auto",children:a.snippet}):null]})},a.id||`${a.pageNumber}-${n}`))}):null]}),t.jsxs("div",{className:"document-row-controls",children:[t.jsx(ds,{variant:"primary",size:"small",className:"document-view-action",onFocus:v?void 0:sa,onMouseEnter:v?void 0:sa,onClick:()=>{(async e=>{if(v&&e.id){const t=yl(e.id);if(!k)return void C(t);gt(e.id);try{const a=await N(`/api/documents/access?id=${encodeURIComponent(e.id)}`);C(a.ok&&a.data?.canAccess?`/documents/${e.id}/view`:t)}catch{C(t)}finally{gt(null)}return}if(la(),sa(),e.id){const t=new URLSearchParams;e.storageKey&&t.set("key",e.storageKey),e.storageProvider&&t.set("provider",e.storageProvider);const a=t.size?`?${t}`:"";C(`/documents/${e.id}/view${a}`)}else if(e.storageKey){const t=new URLSearchParams({key:e.storageKey});e.storageProvider&&t.set("provider",e.storageProvider),C(`/documents/view?${t}`)}})(e)},disabled:v&&(w||pt===e.id),children:"View"}),!v&&c&&t.jsxs("div",{className:"document-secondary-actions",role:"group","aria-label":`Actions for ${a}`,children:[t.jsxs("div",{className:"document-folder-panel-wrap",children:[t.jsx("button",{type:"button",className:"doc-action document-folder-trigger",onClick:e=>{Yt.current=e.currentTarget,ga(l)},"aria-label":"Add document to folder",title:"Add to folder","aria-expanded":d,"aria-haspopup":"dialog","aria-controls":o,children:t.jsx(Z,{size:16})}),d&&t.jsxs("div",{ref:Jt,id:o,className:"document-folder-panel",role:"dialog","aria-modal":"false","aria-labelledby":`${o}-title`,"aria-busy":Ge,children:[t.jsxs("div",{className:"document-folder-panel-header",children:[t.jsx("p",{className:"document-folder-panel-title",id:`${o}-title`,children:"Add to folder"}),t.jsx("button",{type:"button",className:"document-folder-panel-close",onClick:()=>{fa(),globalThis.requestAnimationFrame?.(()=>Yt.current?.focus())},children:"Close"})]}),ge.length>0?t.jsx("div",{className:"document-folder-panel-list",children:ge.map(a=>t.jsxs("button",{type:"button",className:"document-folder-panel-item",disabled:Ge,onClick:()=>{wa(e,a.id)},children:[t.jsx("span",{children:a.name}),t.jsx("span",{className:"folder-count",children:a.document_count||0})]},a.id))}):t.jsx("p",{className:"document-folder-panel-empty",children:"No folders yet. Create one below."}),t.jsxs("div",{className:"document-folder-panel-create",children:[t.jsx("input",{value:He,onCh
2ange:e=>Ke(e.target.value),placeholder:"New folder name","aria-label":"New folder name",maxLength:128,disabled:Ge,onKeyDown:t=>{"Enter"===t.key&&(t.preventDefault(),Na(e))}}),t.jsx(ds,{variant:"secondary",size:"small",disabled:Ge||!He.trim(),onClick:()=>{Na(e)},children:Ge?"Adding...":"Create + Add"})]})]})]}),I&&(e.id||e.storageKey)&&!e.enhancedOnly&&t.jsx("button",{type:"button",className:"doc-action doc-rename-action",onClick:()=>ba(e),"aria-label":"Rename PDF",title:"Rename PDF",children:t.jsx(ee,{size:16})}),I&&(e.id||e.storageKey)&&!e.enhancedOnly&&t.jsx("button",{type:"button",className:"doc-action doc-delete-action",onClick:()=>ja(e),"aria-label":"Delete PDF",title:"Delete PDF",children:t.jsx(te,{size:16})}),t.jsx("button",{type:"button",className:"doc-action "+(e.isFavorite?"active":""),onClick:()=>(async(e,t)=>{try{if(!e?.id&&!e?.storageKey)return;const a={...e.id?{documentId:e.id}:{storageKey:e.storageKey},...e.storageProvider?{storageProvider:e.storageProvider}:{},isFavorite:"favorite"===t?!e.isFavorite:e.isFavorite},n=await N("/api/documents/preferences",{method:"PATCH",body:JSON.stringify(a)});if(n.ok){const t=n.data?.documentId||e.id||null,a=n.data?.storageKey||e.storageKey||null,s=n.data?.storageProvider||e.storageProvider||null;P(r=>{const i=r.map(r=>{const i=e.id&&r.id===e.id||!e.id&&t&&r.id===t,l=s&&r.storageProvider===s&&a&&r.storageKey===a;if(!i&&!l)return r;const o=Boolean(r.isFavorite),c=Boolean(n.data.isFavorite),d=o===c?0:c?1:-1;return{...r,id:r.id||t||null,storageKey:r.storageKey||a||void 0,storageProvider:r.storageProvider||s||void 0,isFavorite:c,favoriteCount:Math.max(0,Number(r.favoriteCount||0)+d)}});return"bookmarks"!==me||n.data.isFavorite||0!==Bi(e.bookmarks).length?i:i.filter(t=>t.id!==e.id)})}}catch(a){}})(e,"favorite"),"aria-label":"Favorite document","aria-pressed":Boolean(e.isFavorite),children:t.jsx(b,{size:16})})]})]})]},e.id||`${e.storageProvider||"unknown"}:${e.storageKey}`)})})]}):t.jsxs(Js,{className:"empty-state",children:[t.jsx("svg",{width:"64",height:"64",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),t.jsx("h3",{children:Ha}),t.jsx("p",{children:Ka}),ae?t.jsx(ds,{variant:"secondary",size:"small",onClick:Ia,children:"Clear search"}):null]})}),!y&&Ba>1&&t.jsxs("nav",{className:"pagination","aria-label":"Documents pagination",children:[t.jsx("button",{type:"button",className:"pagination-nav-button pagination-desktop-only",disabled:1===ie.page,onClick:()=>_a(1),"aria-label":"Go to first page",children:"First"}),t.jsx("button",{type:"button",className:"pagination-nav-button",disabled:ie.page<=1,onClick:()=>_a(ie.page-1),children:"Previous"}),t.jsx("div",{className:"pagination-pages","aria-label":"Page numbers",children:Va.map(e=>"number"==typeof e?t.jsx("button",{type:"button",className:"pagination-page"+(e===ie.page?" active":""),onClick:()=>_a(e),"aria-current":e===ie.page?"page":void 0,"aria-label":`Page ${e}`,children:e},e):t.jsx("span",{className:"pagination-ellipsis","aria-hidden":"true",children:"â¦"},e))}),t.jsxs("span",{className:"pagination-mobile-status","aria-live":"polite",children:["Page ",ie.page," of ",Ba]}),t.jsx("button",{type:"button",className:"pagination-nav-button",disabled:ie.page>=Ba,onClick:()=>_a(ie.page+1),children:"Next"}),t.jsx("button",{type:"button",className:"pagination-nav-button",disabled:ie.page>=Ba,onClick:()=>_a(Ba),"aria-label":`Go to last page, page ${Ba}`,children:"Last"}),t.jsxs("div",{className:"pagination-jump-disclosure",children:[t.jsx("button",{type:"button",className:"pagination-jump-toggle","aria-expanded":_t,"aria-controls":"document-page-jump-form",onClick:()=>Tt(e=>!e),children:"Jump to page"}),t.jsxs("form",{id:"document-page-jump-form",className:"pagination-jump"+(_t?" open":""),onSubmit:e=>{e.preventDefault();const t=function(e,t){const a=String(e||"").trim();if(!/^\d+$/.test(a))return{page:null,error:"Enter a whole page number."};const n=Number.parseInt(a,10),s=Math.max(1,Number(t)||1);return n<1||n>s?{page:null,error:`Enter a page from 1 to ${s}.`}:{page:n,error:null}}(Ct,Ba);t.error?It(t.error):_a(t.page)},noValidate:!0,children:[t.jsxs("label",{htmlFor:"document-page-jump",children:["Page",t.jsx("input",{id:"document-page-jump",type:"text",inputMode:"numeric",pattern:"[0-9]*",value:Ct,onChange:e=>{Rt(e.target.value.replace(/[^0-9]/g,"")),It("")},"aria-invalid":Boolean(Et),"aria-describedby":Et?"document-page-jump-error":void 0}),t.jsxs("span",{children:["of ",Ba]})]}),t.jsx("button",{type:"submit",className:"pagination-go-button",children:"Go"}),Et&&t.jsx("span",{id:"document-page-jump-error",className:"pagination-jump-error",role:"alert",children:Et})]})]})]})]})]})]}),t.jsx(xi,{metadata:ft,onClose:Ca}),t.jsxs(Ss,{isOpen:Ee,onClose:()=>{Ie(!1),Ce(null)},title:"Delete folder",size:"small",children:[t.jsx("p",{className:"folder-delete-message",children:Se?`Delete the folder "${Se.name}"? Documents will remain in Bookmarks.`:"Delete this folder? Documents will remain in Bookmarks."}),t.jsxs("div",{className:"folder-delete-actions",children:[t.jsx(ds,{variant:"secondary",onClick:()=>{Ie(!1),Ce(null)},children:"Cancel"}),t.jsx(ds,{variant:"danger",onClick:()=>Se&&(async e=>{try{const t=await N("/api/documents/folders",{method:"DELETE",body:JSON.stringify({folderId:e.id})});if(t.ok){const t="all"!==be&&Ja(e.id,be);je(!1),ke(""),Ie(!1),Ce(null),xe(t=>"all"===t?t:Ja(e.id,t)?"all":t),t&&(le(e=>({...e,page:1})),x?.({page:1,folder:"",prefix:""})),oa()}else Re({type:"error",message:t.error?.message||"Failed to delete folder"})}catch(t){Re({type:"error",message:"Failed to delete folder"})}})(Se),children:"Delete Folder"})]})]}),t.jsx(Ss,{isOpen:Ye,onClose:xa,title:"Rename PDF",size:"small",children:t.jsxs("div",{className:"document-rename-modal",children:[t.jsx("p",{className:"document-rename-message",children:"Choose a new filename for this PDF. The display title can be kept separate."}),t.jsx("label",{htmlFor:"document-rename-input",className:"document-rename-label",children:"New filename"}),t.jsx("input",{id:"document-rename-input",type:"text",value:et,onChange:e=>tt(e.target.value),placeholder:"Enter a new PDF name",maxLength:240,disabled:it}),t.jsxs("label",{className:"document-rename-title-toggle",children:[t.jsx("input",{type:"checkbox",checked:at,onChange:e=>nt(e.target.checked),disabled:it}),t.jsx("span",{children:"Also update the display title"})]}),t.jsxs("p",{className:"document-rename-hint",children:["Final filename:"," ",st||(et.trim().toLowerCase().endsWith(".pdf")?et.trim().replace(/\.pdf$/i,".pdf"):`${et.trim()||"document"}.pdf`)]}),t.jsxs("div",{className:"document-rename-actions",children:[t.jsx(ds,{variant:"secondary",onClick:xa,disabled:it,children:"Cancel"}),t.jsx(ds,{variant:"primary",onClick:va,disabled:it||!et.trim(),children:it?"
2Saving...":"Save"})]})]})}),t.jsx(Ss,{isOpen:ot,onClose:ya,title:"Delete PDF",size:"small",children:t.jsxs("div",{className:"document-delete-modal",children:[t.jsx("p",{className:"document-delete-message",children:"This will permanently remove the PDF from storage and related database records. This action cannot be undone."}),dt&&t.jsx("p",{className:"document-delete-target",children:dt.displayTitle||dt.filename||dt.storageKey}),t.jsxs("div",{className:"document-delete-actions",children:[t.jsx(ds,{variant:"secondary",onClick:ya,disabled:ht,children:"Cancel"}),t.jsx(ds,{variant:"danger",onClick:ka,disabled:ht,children:ht?"Deleting...":"Delete PDF"})]})]})})]}):t.jsx("div",{className:"document-library",children:t.jsxs("div",{className:"loading-container",children:[t.jsx("div",{className:"spinner-large"}),t.jsx("p",{children:"Loading..."})]})})},Hl="/api/research/profiles",Kl="/api/research/follows",Gl="/api/research/feed",Jl="/api/research/discussions",Yl="/api/research/social";class Ql extends Error{constructor(e,{code:t="RESEARCH_SOCIAL_REQUEST_FAILED",status:a=null}={}){super(e),this.name="ResearchSocialRequestError",this.code=t,this.status=a}}function Xl(e={}){const t=new URLSearchParams;for(const[n,s]of Object.entries(e))"signal"!==n&&null!=s&&""!==String(s).trim()&&t.set(n,String(s));const a=t.toString();return a?`?${a}`:""}class Zl{constructor({requestFn:e}={}){if("function"!=typeof e)throw new Error("ResearchSocialRepository requires a requestFn");this.requestFn=e}async request(e,t={},a="Research social request failed"){let n;try{n=await this.requestFn(e,t)}catch(s){throw function(e){return"AbortError"===e?.name?new Ql("Request cancelled",{code:"REQUEST_CANCELLED",status:null}):new Ql(e?.message||"Research social request failed",{code:e?.code||"RESEARCH_SOCIAL_REQUEST_FAILED",status:"number"==typeof e?.status?e.status:null})}(s)}if(!n?.ok)throw function(e,t){const a=e?.error;return new Ql(a?.message||t,{code:a?.code||"RESEARCH_SOCIAL_REQUEST_FAILED",status:a?.status||null})}(n,a);return n.data??n}listProfiles(e={}){return this.request(`${Hl}${Xl(e)}`,{method:"GET",signal:e.signal},"Failed to load people")}getProfile(e,{signal:t}={}){return this.request(`${Hl}/${encodeURIComponent(e||"me")}`,{method:"GET",signal:t},"Failed to load profile")}updateProfile(e,t){return this.request(`${Hl}/me`,{method:"PATCH",body:JSON.stringify(t||{})},"Failed to update profile")}getContributions(e,t={}){return this.request(`${Hl}/${encodeURIComponent(e||"me")}/contributions${Xl(t)}`,{method:"GET",signal:t.signal},"Failed to load contributions")}getFollowState(e,t,{signal:a}={}){return this.request(`${Kl}${Xl({targetType:e,targetId:t})}`,{method:"GET",signal:a},"Failed to load follow state")}listFollows(e={}){return this.request(`${Kl}${Xl(e)}`,{method:"GET",signal:e.signal},"Failed to load follows")}followTarget(e,t){return this.request(Kl,{method:"POST",body:JSON.stringify({targetType:e,targetId:t})},"Failed to follow target")}unfollowTarget(e,t){return this.request(Kl,{method:"DELETE",body:JSON.stringify({targetType:e,targetId:t})},"Failed to unfollow target")}blockUser(e){return this.request(`${Yl}/blocks`,{method:"POST",body:JSON.stringify({userId:e})},"Failed to block researcher")}unblockUser(e){return this.request(`${Yl}/blocks/${encodeURIComponent(e)}`,{method:"DELETE"},"Failed to unblock researcher")}muteUser(e){return this.request(`${Yl}/mutes`,{method:"POST",body:JSON.stringify({userId:e})},"Failed to mute researcher")}unmuteUser(e){return this.request(`${Yl}/mutes/${encodeURIComponent(e)}`,{method:"DELETE"},"Failed to unmute researcher")}reportSocialTarget(e,t,a,n=""){const s=globalThis.crypto?.randomUUID?.()||`report-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.request(`${Yl}/reports`,{method:"POST",headers:{"Idempotency-Key":s},body:JSON.stringify({targetType:e,targetId:t,reason:a,details:n,idempotencyKey:s})},"Failed to submit report")}listActivityFeed(e={}){return this.request(`${Gl}${Xl(e)}`,{method:"GET",signal:e.signal},"Failed to load research activity feed")}getActivityDiagnostics({signal:e}={}){return this.request(`${Gl}${Xl({diagnostics:!0})}`,{method:"GET",signal:e},"Failed to load research activity diagnostics")}listDiscussions(e={}){return this.request(`${Jl}${Xl(e)}`,{method:"GET",signal:e.signal},"Failed to load discussions")}
2getDiscussion(e,{signal:t}={}){return this.request(`${Jl}/${encodeURIComponent(e)}`,{method:"GET",signal:t},"Failed to load discussion")}createDiscussion(e={}){return this.request(Jl,{method:"POST",body:JSON.stringify(e)},"Failed to create discussion")}replyToDiscussion(e,t={}){return this.request(`${Jl}/${encodeURIComponent(e)}/replies`,{method:"POST",body:JSON.stringify(t)},"Failed to reply to discussion")}updateDiscussionStatus(e,t,a={}){return this.request(`${Jl}/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({...a,status:t})},"Failed to update discussion")}editDiscussionMessage(e,t,a={}){return this.request(`${Jl}/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)},"Failed to edit discussion message")}}function eo(){const{makeAuthRequest:t}=Yn();return e.useMemo(()=>function(e){return new Zl({requestFn:e})}(t),[t])}const to=["researchInterests","languages","periods","regions","specialties"];function ao(e){return[...new Set(String(e||"").split(/[\n,]/).map(e=>e.trim()).filter(Boolean))]}function no(e={}){return{displayName:e.displayName||"",slug:e.profileSlug||e.slug||"",headline:e.headline||"",bio:e.bio||"",affiliation:e.affiliation||"",department:e.department||"",location:e.location||"",avatarUrl:e.avatarUrl||"",websiteUrl:e.websiteUrl||"",orcid:e.orcid||"",wikimediaUsername:e.wikimediaUsername||"",factgridUsername:e.factgridUsername||"",profileVisibility:e.profileVisibility||"private",showContributions:!1!==e.showContributions,showAffiliation:!1!==e.showAffiliation,showResearchInterests:!1!==e.showResearchInterests,showFollowers:!0===e.showFollowers,showFollowing:!0===e.showFollowing,...Object.fromEntries(to.map(t=>{return[t,(a=e[t],Array.isArray(a)?a.join("\n"):"")];var a}))}}function so({url:a,displayName:n}){const[s,r]=e.useState(""),i=Boolean(a)&&s!==a;return t.jsx("div",{className:"community-profile-avatar-preview",children:i?t.jsx("img",{src:a,alt:"Profile avatar preview",onError:()=>r(a)}):t.jsx("span",{"aria-label":"Avatar initials preview",children:(l=n,String(l||"TW").split(/\s+/).slice(0,2).map(e=>e[0]).join("").toUpperCase())})});var l}function ro({onDirtyChange:a}){const n=eo(),[s,r]=e.useState(null),[i,l]=e.useState(null),[o,c]=e.useState(null),[d,u]=e.useState("loading"),[h,m]=e.useState("");e.useEffect(()=>{const e=new AbortController;return n.getProfile("me",{signal:e.signal}).then(e=>{const t=e.profile,a=no(t);r(t),l(a),c(a),u("idle")}).catch(e=>{"REQUEST_CANCELLED"!==e.code&&(m(e.message||"Profile settings could not be loaded."),u("error"))}),()=>e.abort()},[n]);const p=e.useMemo(()=>Boolean(i&&o&&JSON.stringify(i)!==JSON.stringify(o)),[o,i]);e.useEffect(()=>(a?.(p),()=>a?.(!1)),[p,a]),e.useEffect(()=>{if(!p)return;const e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[p]);const g=(e,t)=>{l(a=>({...a,[e]:t})),"saved"===d&&u("idle"),m("")};return"loading"===d?t.jsx("div",{className:"community-profile-form-state",children:"Loading Profile settingsâ¦"}):i?t.jsxs("form",{className:"community-profile-form",onSubmit:async e=>{e.preventDefault();const t=function(e){if(e.avatarUrl)try{if("https:"!==new URL(e.avatarUrl).protocol)return"Avatar URL must use HTTPS."}catch{return"Avatar URL must be a valid HTTPS URL."}for(const t of to){const a=ao(e[t]);if(a.length>24)return`${t} supports at most 24 entries.`;if(a.some(e=>e.length>80))return`${t} entries must be 80 characters or fewer.`}return null}(i);if(t)return m(t),void u("error");u("saving"),m("");try{const e={...i,...Object.fromEntries(to.map(e=>[e,ao(i[e])]))},t=(await n.updateProfile("me",e)).profile,a=no(t);r(t),l(a),c(a),u("saved")}catch(a){m(a.message||"Profile changes could not be saved."),u("error")}},noValidate:!0,"aria-describedby":"profile-form-status",children:[t.jsxs("div",{className:"community-profile-form-heading",children:[t.jsxs("div",{children:[t.jsx("h2",{children:"Profile"}),t.jsx("p",{children:"Manage how you appear in Community. A profile is created only when you intentionally save these settings."})]}),t.jsx(so,{url:i.avatarUrl,displayName:i.displayName})]}),t.jsxs("section",{"aria-labelledby":"profile-identity-heading",children:[t.jsx("h3",{id:"profile-identity-heading",children:"Identity"}),t.jsxs("div",{className:"community-profile-form-grid",children:[[["displayName","Display name",120,"text"],["slug","Profile slug",60,"text"],["headline","Headline",180,"text"],["location","
2Location",120,"text"],["avatarUrl","Avatar URL",1e3,"url"]].map(([e,a,n,s])=>t.jsxs("label",{htmlFor:`community-profile-${e}`,children:[a,t.jsx("input",{id:`community-profile-${e}`,type:s,value:i[e],maxLength:n,onChange:t=>g(e,t.target.value)}),"avatarUrl"===e?t.jsx("small",{children:"HTTPS image URL only. Uploads are not supported."}):null]},e)),t.jsxs("label",{className:"community-profile-form-wide",htmlFor:"community-profile-bio",children:["Biography",t.jsx("textarea",{id:"community-profile-bio",value:i.bio,maxLength:2e3,rows:6,onChange:e=>g("bio",e.target.value)}),t.jsxs("small",{children:[i.bio.length,"/2000 characters"]})]})]})]}),t.jsxs("section",{"aria-labelledby":"profile-research-heading",children:[t.jsx("h3",{id:"profile-research-heading",children:"Affiliation and research"}),t.jsxs("div",{className:"community-profile-form-grid",children:[[["affiliation","Affiliation",180],["department","Department",180]].map(([e,a,n])=>t.jsxs("label",{htmlFor:`community-profile-${e}`,children:[a,t.jsx("input",{id:`community-profile-${e}`,value:i[e],maxLength:n,onChange:t=>g(e,t.target.value)})]},e)),to.map(e=>t.jsxs("label",{htmlFor:`community-profile-${e}`,children:[e.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()),t.jsx("textarea",{id:`community-profile-${e}`,value:i[e],rows:4,onChange:t=>g(e,t.target.value)}),t.jsx("small",{children:"One entry per line, up to 24."})]},e))]})]}),t.jsxs("section",{"aria-labelledby":"profile-links-heading",children:[t.jsx("h3",{id:"profile-links-heading",children:"Scholarly links"}),t.jsx("div",{className:"community-profile-form-grid",children:[["websiteUrl","Website URL",1e3,"url"],["orcid","ORCID",19,"text"],["wikimediaUsername","Wikimedia username",120,"text"],["factgridUsername","FactGrid username",120,"text"]].map(([e,a,n,s])=>t.jsxs("label",{htmlFor:`community-profile-${e}`,children:[a,t.jsx("input",{id:`community-profile-${e}`,type:s,value:i[e],maxLength:n,onChange:t=>g(e,t.target.value)})]},e))})]}),t.jsxs("section",{"aria-labelledby":"profile-privacy-heading",children:[t.jsx("h3",{id:"profile-privacy-heading",children:"Privacy"}),t.jsxs("div",{className:"community-profile-form-grid",children:[t.jsxs("label",{htmlFor:"community-profile-visibility",children:["Profile visibility",t.jsxs("select",{id:"community-profile-visibility",value:i.profileVisibility,onChange:e=>g("profileVisibility",e.target.value),children:[t.jsx("option",{value:"private",children:"Private â safe account identity only"}),t.jsx("option",{value:"internal",children:"Internal â current Community users"}),t.jsx("option",{value:"public",disabled:!0,children:"Public â unavailable during internal preview"})]}),t.jsx("small",{children:"These controls affect what other preview members see. They never make a profile anonymously public while Community remains in internal preview."})]}),t.jsxs("fieldset",{className:"community-profile-form-wide",children:[t.jsx("legend",{children:"Display controls"}),[["showContributions","Show contributions"],["showAffiliation","Show affiliation and department"],["showResearchInterests","Show research interests"],["showFollowers","Show followers and follower count"],["showFollowing","Show following and following count"]].map(([e,a])=>t.jsxs("label",{className:"community-profile-checkbox",children:[t.jsx("input",{type:"checkbox",checked:i[e],onChange:t=>g(e,t.target.checked)}),a]},e))]})]})]}),t.jsx("div",{id:"profile-form-status",className:h?"community-profile-form-error":"community-profile-form-status",role:h?"alert":"status","aria-live":"polite",children:h||("saved"===d?"Profile saved.":p?"You have unsaved changes.":s?.profileCompleted?"Profile is up to date.":"Your Community profile has not been completed yet.")}),t.jsxs("div",{className:"community-profile-form-actions",children:[t.jsxs(ds,{variant:"ghost",type:"button",disabled:!p||"saving"===d,onClick:()=>{l(o),m(""),u("idle")},children:[t.jsx(ae,{size:16}),"Discard changes"]}),t.jsxs(ds,{variant:"primary",type:"submit",disabled:!p||"saving"===d,children:[t.jsx(ne,{size:16}),"saving"===d?"Savingâ¦":"Save Profile"]})]})]}):t.jsx("div",{className:"community-profile-form-state community-profile-form-error",role:"alert",children:h||"Profile settings are unavailable."})}const io={IDLE:"idle",INITIAL_LOADING:"initial_loading",RECONCILING:"reconciling",REFRESHING:"refreshing",LOADED:"loaded",EMPTY:"empty",NO_CUSTOMER:"no_customer",ER
2ROR:"error"},lo=new Map,oo=Object.freeze(["profile","subscription","billing"]),co=Object.freeze(["subscription","billing"]);const uo=()=>{const{user:a,makeAuthRequest:n,canAccessCommunityPreview:s}=Yn(),r=Boolean(s?.()),[i,l]=c(),o=r?oo:co,d=i.get("section"),u=r?"profile":"subscription",h=o.includes(d)?d:u,[m,p]=e.useState(h),[g,f]=e.useState(!1);e.useEffect(()=>{o.includes(d)&&d!==m?p(d):o.includes(m)||p(u)},[m,u,d,o]);const b=e=>{if("profile"===m&&"profile"!==e&&g&&!window.confirm("Discard your unsaved Profile changes?"))return;p(e);const t=new URLSearchParams(i);t.set("tab","settings"),t.set("section",e),l(t,{replace:!0})},[x,v]=e.useState([]),[j,y]=e.useState(io.IDLE),[k,w]=e.useState(null),[N,S]=e.useState(null),[C,R]=e.useState(null),E=e.useRef(0),I=e.useRef(!1),[_,T]=e.useState(null);e.useEffect(()=>{"billing"!==m?("subscription"===m&&A(),E.current+=1):P()},[m]);const A=async()=>{try{const e=await n("/api/stripe/subscription-status");e.ok&&T(e.data)}catch(e){}},O=async({reconcile:e=!1}={})=>e?n("/api/stripe/billing-history/reconcile?limit=20",{method:"POST",_cacheBypass:!0}):n("/api/stripe/billing-history?limit=20",{_cacheBypass:!0}),D=e=>"failed"===e?.status?io.ERROR:"no_customer"===e?.status?io.NO_CUSTOMER:io.EMPTY,P=async()=>{if(I.current)return;const e=E.current+1;E.current=e,I.current=!0,y(io.INITIAL_LOADING),w(null),S(null);try{const t=await O();if(E.current!==e)return;if(!t.ok)throw new Error(t.error?.message||"Failed to load billing history");const n=t.data?.payments||[];if(v(n),R(t.data?.reconciliation||null),n.length>0)return void y(io.LOADED);y(io.RECONCILING);const s=await async function(e,t){const a=e||"current-user";return lo.has(a)||lo.set(a,t().finally(()=>{lo.delete(a)})),lo.get(a)}(a?.id,()=>O({reconcile:!0}));if(E.current!==e)return;if(!s.ok)throw new Error(s.error?.message||"Failed to reconcile billing history");const r=s.data?.payments||[],i=s.data?.reconciliation||null;v(r),R(i),0===r.length&&"failed"===i?.status&&w(i.message||"We could not check Stripe for recent invoices. Please try again."),y(r.length>0?io.LOADED:D(i))}catch(t){if("AbortError"===t?.name||"AUTH_SESSION_STALE"===t?.code)return;E.current===e&&(w(t.safeMessage||t.message||"Failed to load billing history"),y(io.ERROR))}finally{E.current===e&&(I.current=!1)}},L=async()=>{if(I.current)return;const e=E.current+1;E.current=e,I.current=!0;const t=x.length>0;y(t?io.REFRESHING:io.RECONCILING),w(null),S(null);try{const a=await O({reconcile:!0});if(E.current!==e)return;if(!a.ok)throw new Error(a.error?.message||"Failed to refresh billing history");const n=a.data?.payments||[],s=a.data?.reconciliation||null;if(v(n),R(s),"failed"===s?.status){const e=s.message||"We could not check Stripe for recent invoices. Your saved billing history is still shown.";if(t||n.length>0){const t=/saved billing history/i.test(e)?e:`${e} Your saved billing history is still shown.`;S(t),y(io.LOADED)}else w(e),y(io.ERROR);return}y(n.length>0?io.LOADED:D(s))}catch(a){if("AbortError"===a?.name||"AUTH_SESSION_STALE"===a?.code)return;const e=a.safeMessage||a.message||"Failed to refresh billing history";t?(S(`${e}. Your saved billing history is still shown.`),y(io.LOADED)):(w(e),y(io.ERROR))}finally{E.current===e&&(I.current=!1)}},$=(e,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100),M=e=>e?new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):"N/A",U=e=>{switch(e?.toLowerCase()){case"succeeded":case"paid":return"success";case"pending":case"processing":return"warning";case"failed":case"canceled":return"danger";default:return"default"}},F=[io.INITIAL_LOADING,io.RECONCILING,io.REFRESHING].includes(j),z=j===io.NO_CUSTOMER?"No Stripe customer is linked to this account yet.":"No billing history found";return t.jsxs("div",{className:"account-settings",children:[t.jsxs("div",{className:"settings-nav",children:[r?t.jsxs("button",{className:"settings-nav-item "+("profile"===m?"active":""),onClick:()=>b("profile"),children:[t.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Profile"]}):null,t.jsxs("button",{className:"settings-nav-item "+("subscription"===m?"active":""),onClick:()=>b("subscription"),children:[t.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3v-8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Subscription"]}),t.jsxs("button",{className:"settings-nav-item "+("billing"===m?"active":""),onClick:()=>b("billing"),children:[t.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Billing History"]})]}),t.jsxs("div",{className:"settings-content",children:[r&&"profile"===m&&t.jsx(Js,{className:"profile-section",children:t.jsx(ro,{onDirtyChange:f})}),"subscription"===m&&t.jsxs("div",{className:"subscription-section",children:[_?.comped_access&&t.jsx(Js,{children:t.jsx("div",{className:"subscription-detail
2s-card",children:t.jsxs("div",{className:"subscription-info-row",children:[t.jsx("span",{className:"subscription-info-label",children:"Complimentary Access"}),t.jsxs("span",{className:"subscription-info-value",children:["Until ",M(_.comped_access.ends_at),_.comped_access.reason&&` â ${_.comped_access.reason}`]})]})})}),t.jsx(Xs,{onSubscriptionChange:A})]}),"billing"===m&&t.jsxs(Js,{className:"billing-section",children:[t.jsxs("div",{className:"section-header",children:[t.jsx("h2",{children:"Billing History"}),t.jsx(ds,{variant:"secondary",size:"small",onClick:L,disabled:F,children:F?"Refreshing...":"Refresh"})]}),k&&t.jsx("div",{className:"alert alert-error",children:k}),N&&t.jsx("div",{className:"alert alert-warning",children:N}),j===io.INITIAL_LOADING?t.jsxs("div",{className:"loading-state",children:[t.jsx("div",{className:"spinner"}),t.jsx("p",{children:"Loading billing history..."})]}):0===x.length?t.jsx("div",{className:"empty-state",children:j===io.RECONCILING?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"spinner"}),t.jsx("p",{children:"Checking Stripe for recent invoices..."}),t.jsx("p",{className:"empty-state-hint",children:"We will check once, then show the latest confirmed result here."})]}):t.jsxs(t.Fragment,{children:[t.jsx("p",{children:z}),"failed"===C?.status&&t.jsx("p",{className:"empty-state-hint",children:"We could not check Stripe for recent invoices. Please try refresh again."}),j===io.ERROR&&t.jsx(ds,{variant:"secondary",size:"small",onClick:L,children:"Try again"})]})}):t.jsxs("div",{children:[j===io.REFRESHING&&t.jsx("p",{className:"billing-status-note",children:"Checking Stripe for recent invoices..."}),t.jsx("div",{className:"billing-table-wrapper",children:t.jsxs("table",{className:"billing-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Date"}),t.jsx("th",{children:"Amount"}),t.jsx("th",{children:"Status"}),t.jsx("th",{children:"Receipt"})]})}),t.jsx("tbody",{children:x.map(e=>t.jsxs("tr",{children:[t.jsx("td",{children:M(e.created_at)}),t.jsx("td",{children:$(e.amount,e.currency)}),t.jsx("td",{children:t.jsx(li,{variant:U(e.status),children:e.status})}),t.jsx("td",{children:e.receipt_url?t.jsx("a",{href:e.receipt_url,target:"_blank",rel:"noopener noreferrer",className:"receipt-link",children:"View Receipt"}):t.jsx("span",{className:"no-receipt",children:"N/A"})})]},e.id))})]})})]})]})]})]})},ho={},mo=[{id:"bug",label:"Bug Report",icon:re,description:"Something isn't working correctly"},{id:"feature",label:"Feature Request",icon:ie,description:"Suggest a new feature or improvement"},{id:"general",label:"General Feedback",icon:le,description:"Share your thoughts or experience"}];function po(){return window.crypto?.randomUUID?window.crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(Number(e)^window.crypto.getRandomValues(new Uint8Array(1))[0]&15>>Number(e)/4).toString(16))}function go(e){return{browserUserAgent:window.navigator?.userAgent||"",viewport:{width:window.innerWidth,height:window.innerHeight},appVersion:ho?.VITE_APP_VERSION||"",errorMessage:e?.message||e?.errorMessage||"",componentStack:e?.componentStack||e?.stack||""}}function fo({errorContext:a,onSuccess:n}){const{makeAuthRequest:s}=Yn(),r=Ds(),[i,l]=e.useState(a||null),[o,c]=e.useState(a?"bug":""),[d,u]=e.useState(""),[h,m]=e.useState(""),[p,f]=e.useState(!1),[b,x]=e.useState(!1),[v,j]=e.useState(()=>po()),[y,k]=e.useState([]),[w,N]=e.useState({total:0,limit:10,offset:0}),[S,C]=e.useState(!1),[R,E]=e.useState(null),I=e.useCallback(async({offset:e=0,append:t=!1}={})=>{C(!0),E(null);try{const a=new URLSearchParams({limit:String(10),offset:String(e)}),n=await s(`/api/feedback?${a}`);if(!n.ok)throw new Error(n.error?.message||"Failed to load feedback history");const r=n.data?.feedback||[];k(e=>t?[...e,...r]:r),N({total:n.data?.pagination?.total||0,limit:n.data?.pagination?.limit||10,offset:e})}catch(a){E(a.message||"Failed to load feedback history")}finally{C(!1)}},[s]);e.useEffect(()=>{if(!a){const t=sessionStorage.getItem("feedback_error_context");if(t){let a=!1;try{const e=JSON.parse(t),n=e?.capturedAt?Date.parse(e.capturedAt):Date.now();a=Date.now()-n<=18e5,a&&l(e)}catch(e){}sessionStorage.removeItem("feedback_error_context"),a&&c("bug")}}},[]),e.useEffect(()=>{I()},[I]);return t.jsxs("div",{className:"feedback-container",children:[t.jsxs("div",{className:"feedback-header",children:[t.jsx("h1",{children:"Feedback & Error Reporting"}),t.jsx("p",{className:"feedback-subtitle",children:"Help us improve by reporting issues or suggesting features"})]}),b&&t.jsxs(Js,{className:"feedback-success-card",children:[t.jsx(se,{size:40,className:"feedback-success-icon"}
2),t.jsx("h2",{children:"Thank you for your feedback!"}),t.jsx("p",{children:"Our team will review your submission."}),t.jsx(ds,{variant:"secondary",onClick:()=>{c(i?"bug":""),u(""),m(""),x(!1),l(null),j(po())},children:"Submit Another"})]}),t.jsxs("form",{className:"feedback-form",onSubmit:async e=>{if(e.preventDefault(),o&&d.trim()&&h.trim()){f(!0);try{const e=await s("/api/feedback",{method:"POST",body:JSON.stringify({category:o,title:d.trim(),description:h.trim(),error_context:i||null,clientContext:go(i),pagePath:i?.pagePath||`${window.location.pathname}${window.location.search}`,submissionKey:v})});e.ok?(x(!0),u(""),m(""),l(null),j(po()),I(),r({type:"success",message:"Feedback submitted â thank you!"}),n?.()):r({type:"error",message:e.error?.message||"Failed to submit feedback"})}catch{r({type:"error",message:"Something went wrong. Please try again."})}finally{f(!1)}}},children:[t.jsxs(Js,{className:"feedback-category-card",children:[t.jsx("h3",{children:"What type of feedback?"}),t.jsx("div",{className:"feedback-category-grid",children:mo.map(e=>t.jsxs("button",{type:"button",className:"feedback-category-option "+(o===e.id?"active":""),onClick:()=>c(e.id),children:[t.jsx(e.icon,{size:24}),t.jsx("span",{className:"feedback-category-label",children:e.label}),t.jsx("span",{className:"feedback-category-desc",children:e.description})]},e.id))})]}),o&&t.jsxs(Js,{className:"feedback-details-card",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"feedback-title",children:"Title"}),t.jsx("input",{id:"feedback-title",type:"text",value:d,onChange:e=>u(e.target.value),placeholder:"bug"===o?"Brief description of the issue":"Brief summary",className:"form-input",maxLength:200,required:!0}),t.jsxs("small",{className:"form-help",children:[d.length,"/",200]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"feedback-description",children:"Description"}),t.jsx("textarea",{id:"feedback-description",value:h,onChange:e=>m(e.target.value),placeholder:"bug"===o?"What happened? What did you expect? Steps to reproduce...":"feature"===o?"Describe the feature and how it would help you...":"Share your thoughts...",className:"form-input feedback-textarea",maxLength:5e3,rows:6,required:!0}),t.jsxs("small",{className:"form-help",children:[h.length,"/",5e3]})]}),i&&t.jsxs("div",{className:"feedback-error-context",children:[t.jsx(li,{variant:"danger",children:"Technical Context Attached"}),t.jsx("p",{children:"Technical error information will be included with your report to help us diagnose the issue."}),t.jsx("button",{type:"button",className:"feedback-remove-context",onClick:()=>l(null),"aria-label":"Remove technical context",title:"Remove technical context",children:t.jsx(g,{size:16})})]}),t.jsx("div",{className:"feedback-actions",children:t.jsx(ds,{type:"submit",variant:"primary",disabled:p||!d.trim()||!h.trim(),children:p?"Submitting...":t.jsxs(t.Fragment,{children:[t.jsx(oe,{size:16}),"Submit Feedback"]})})})]})]}),t.jsxs("section",{className:"feedback-history","aria-labelledby":"my-feedback-heading",children:[t.jsxs("div",{className:"feedback-history-header",children:[t.jsx("h2",{id:"my-feedback-heading",children:"My Feedback"}),t.jsxs(ds,{type:"button",variant:"ghost",size:"small",onClick:()=>I(),disabled:S,children:[t.jsx(ce,{size:15}),"Refresh"]})]}),R?t.jsxs(Js,{className:"feedback-history-card",children:[t.jsx("p",{className:"feedback-history-error",children:R}),t.jsx(ds,{type:"button",size:"small",onClick:()=>I(),children:"Retry"})]}):0===y.length?t.jsx(Js,{className:"feedback-history-card",children:t.jsx("p",{className:"feedback-history-empty",children:S?"Loading feedback...":"No feedback submitted yet."})}):t.jsx("div",{className:"feedback-history-list",children:y.map(e=>t.jsxs(Js,{className:"feedback-history-item",children:[t.jsxs("div",{className:"feedback-history-item-header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:e.title}),t.jsx("p",{children:new Date(e.created_at).toLocaleString()})]}),t.jsx(li,{variant:"resolved"===e.status?"success":"in_review"===e.status?"info":"dismissed"===e.status?"default":"warning",children:e.status.replace("_"," ")})]}),t.jsx("p",{className:"feedback-history-description",children:e.description}),e.related_document&&t.jsxs("p",{className:"feedback-history-meta",children:["Document: ",e.related_document.title||e.related_document.filename]}),e.admin_response&&t.jsxs("div",{className:"feedback-admin-response",children:[t.jsx("h4",{children:"Response"}),t.jsx("p",{children:e.admin_response})]})]},e.id))}),y.length<w.total&&t.jsx("div",{className:"feedback-history-actions",children:t.jsx(ds,{type:"button",variant:"secondary",size:"small",disabled:S,onClick:()=>I({offset:y.length,append:!0}
2),children:S?"Loading...":"Load More"})})]})]})}function bo({faqs:e,heading:a="Common questions"}){return Array.isArray(e)&&0!==e.length?t.jsxs("section",{className:"dashboard-help-faq","aria-labelledby":"dashboard-help-faq-heading",children:[t.jsx("h3",{id:"dashboard-help-faq-heading",children:a}),t.jsx("div",{className:"dashboard-help-faq-list",children:e.map(e=>t.jsxs("details",{id:`faq-${e.id}`,children:[t.jsx("summary",{children:e.question}),t.jsx("p",{children:e.answer})]},e.id))})]}):null}function xo({media:e}){return e?.src?t.jsxs("figure",{className:"dashboard-help-media",children:[t.jsx("img",{src:e.src,width:e.width,height:e.height,alt:e.alt||"",loading:"lazy"}),e.caption?t.jsx("figcaption",{children:e.caption}):null]}):null}function vo({link:e}){return t.jsxs(l,{className:"dashboard-help-action-link",to:e.to,children:[t.jsxs("span",{children:[t.jsx("strong",{children:e.label}),e.accessNote?t.jsx("small",{children:e.accessNote}):null]}),t.jsx(de,{size:17,"aria-hidden":"true"})]})}function jo({guide:e,guides:a,headingRef:n,onOpenTopic:s,onHelpHome:r}){const i=a.findIndex(t=>t.id===e.id),o=i>0?a[i-1]:null,c=i<a.length-1?a[i+1]:null,d=(e,t)=>{s&&(e.preventDefault(),s(t))};return t.jsxs("article",{className:"dashboard-help-article","aria-labelledby":"dashboard-help-article-title",children:[t.jsxs("button",{type:"button",className:"dashboard-help-home-link",onClick:r,children:[t.jsx(G,{size:16,"aria-hidden":"true"}),"Help home"]}),t.jsxs("header",{className:"dashboard-help-article-header",children:[t.jsx("p",{children:"Dashboard guide"}),t.jsx("h2",{id:"dashboard-help-article-title",ref:n,tabIndex:"-1",children:e.title}),t.jsx("p",{children:e.summary})]}),t.jsx("div",{className:"dashboard-help-article-sections",children:(e.sections||[]).map(e=>t.jsxs("section",{id:e.id,children:[t.jsx("h3",{children:e.heading}),(e.paragraphs||[]).map(e=>t.jsx("p",{children:e},e)),e.steps?.length?t.jsx("ol",{children:e.steps.map(e=>t.jsx("li",{children:e},e))}):null,e.items?.length?t.jsx("ul",{children:e.items.map(e=>t.jsx("li",{children:e},e))}):null,e.definitions?.length?t.jsx("dl",{className:"dashboard-help-definitions",children:e.definitions.map(e=>t.jsxs("div",{children:[t.jsx("dt",{children:e.term}),t.jsx("dd",{children:e.description})]},e.term))}):null,e.callout?t.jsxs("aside",{className:"dashboard-help-callout",role:"note",children:[t.jsx(Y,{size:18,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("h4",{children:e.callout.title}),t.jsx("p",{children:e.callout.body})]})]}):null,t.jsx(xo,{media:e.media})]},e.id))}),t.jsx(bo,{faqs:e.faqs,heading:"troubleshooting"===e.id?"Quick answers":"Questions about this topic"}),e.quickLinks?.length?t.jsxs("section",{className:"dashboard-help-actions","aria-labelledby":"dashboard-help-actions-heading",children:[t.jsx("h3",{id:"dashboard-help-actions-heading",children:"Take the next step"}),t.jsx("div",{className:"dashboard-help-action-list",children:e.quickLinks.map(a=>t.jsx(vo,{link:a},`${e.id}-${a.to}-${a.label}`))})]}):null,t.jsxs("nav",{className:"dashboard-help-pagination","aria-label":"Adjacent help topics",children:[o?t.jsxs(l,{to:`/dashboard?tab=help&topic=${encodeURIComponent(o.id)}`,onClick:e=>d(e,o.id),children:[t.jsx(G,{size:16,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("small",{children:"Previous"}),o.title]})]}):t.jsx("span",{}),c?t.jsxs(l,{className:"dashboard-help-pagination-next",to:`/dashboard?tab=help&topic=${encodeURIComponent(c.id)}`,onClick:e=>d(e,c.id),children:[t.jsxs("span",{children:[t.jsx("small",{children:"Next"}),c.title]}),t.jsx(de,{size:16,"aria-hidden":"true"})]}):null]})]})}const yo=[{title:"Find documents",description:"Search the library and understand document access.",topicId:"find-documents",icon:ue},{title:"Read a PDF",description:"Use the inline reader and save your place.",topicId:"read-pdfs",icon:he},{title:"Manage my account",description:"Review your profile, plan, and billing history.",topicId:"account-billing",icon:m},{title:"Report a problem",description:"Send useful feedback or find the right contact path.",topicId:"feedback-support",icon:le}];function ko({topicId:e,onOpenTopic:a,children:n,className:s}){return t.jsx(l,{to:`/dashboard?tab=help&topic=${encodeURIComponent(e)}`,className:s,onClick:t=>{a&&(t.preventDefault(),a(e))},children:n})}function wo({guides:e,onOpenTopic:a}){return t.jsxs("div",{className:"dashboard-help-landing",children:[t.jsxs("section",{"aria-labelledby":"dashboard-help-frequent-heading",children:[t.jsxs("div",{className:"dashboard-help-section-heading",children:[t.jsx("p",{className:"dashboard-help-section-kicker",children:"Frequent tasks"}),t.jsx("h2",{id:"dashboard-help-frequent-heading",children:"Start with what you need to do"})]}),t.jsx("div",{className:"dashboard-help-task-grid",children:yo.map(e=>{const n=e.icon;return t.jsxs(ko,{topicId:e.topicId,onOpenTopic:a,className:"dashboard-help-task",children:[t.jsx("span",{className:"dashboard-help-task-icon","aria-hidden":"true",children:t.jsx(n,{size:20})}),t.jsxs("span",{className:"dashboard-help-task-copy",children:[t.jsx("strong",{children:e.title}),t.jsx("span",{children:e.description})]}),t.jsx(de,{size:17,"aria-hidden":"true"})]},e.topicId)})})]}),t.jsxs("section",{className:"dashboard-help-browse","aria-labelledby":"dashboard-help-browse-heading",children:[t.jsxs("div",{className:"dashboard-help-section-heading",children:[t.jsx("p",{className:"dashboard-help-section-kicker",children:"Browse topics"}),t.jsx("h2",{id:"dashboard-help-browse-heading",children:"Learn your dashboard"})]}),t.jsx("div",{className:"dashboard-help-browse-list",children:e.map((e,n)=>t.jsxs(ko,{topicId:e.id,onOpenTopic:a,className:"dashboard-help-browse-link",children:[t.jsx("span",{className:"dashboard-help-browse-number","aria-hidden":"true",children:String(n+1).padStart(2,"0")}),t.jsxs("span",{children:[t.jsx("strong",{children:e.title}),t.jsx("span",{children:e.summary})]}),t.jsx(de,{size:17,"aria-hidden":"true"})]},e.id))})]}),t.jsxs("aside",{className:"dashboard-help-access-note","aria-labelledby":"dashboard-help-access-heading",children:[t.jsx("h2",{id:"dashboard-help-access-heading",children:"Help stays available"}),t.jsx("p",{children:"Help, account settings, feedback, and published document information are available to authenticated users. Protected PDFs, personal library tools, and uploads can require current document access."})]})]})}function No({guides:e,selectedTopicId:a,onOpenTopic:n}){return t.jsx("ul",{className:"dashboard-help-topic-list",children:e.map(e=>{const s=e.id===a;return t.jsx("li",{children:t.jsx(l,{to:`/dashboard?tab=help&topic=${encodeURIComponent(e.id)}`,className:"dashboard-help-topic-link"+(s?" is-current":""),"aria-current":s?"page":void 0,onClick:t=>{n&&(t.preventDefault(),n(e.id))},children:e.title})},e.id)})})}function So({guides:e,selectedTopicId:a,onOpenTopic:n}){return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:"dashboard-help-topic-nav","aria-label":"Help topics",children:[t.jsx("p",{children:"Help topics"}),t.jsx(No,{guides:e,selectedTopicId:a,onOpenTopic:n})]}),t.jsxs("details",{className:"dashboard-help-topic-disclosure",children:[t.jsxs("summary",{children:[t.jsx("span",{children:"Browse topics"}),t.jsx(u,{size:18,"aria-hidden":"true"})]}),t.jsx("nav",{"aria-label":"Help topics on mobile",children:t.jsx(No,{guides:e,selectedTopicId:a,onOpenTopic:n})})]})]})}const Co={guides:[]};function Ro(e){return String(e||"").trim().toLocaleLowerCase()}function Eo({query:e,topicResults:a,faqResults:n,onOpenTopic:s,onClear:r}){const i=a.length+n.length;return 0===i?t.jsxs("section",{className:"dashboard-help-no-results","aria-labelledby":"dashboard-help-no-results",children:[t.jsx(me,{size:30,"aria-hidden":"true"}),t.jsxs("h2",{id:"dashboard-help-no-results",children:["No Help results for â",e.trim(),"â"]}
2),t.jsx("p",{children:"Try fewer words, browse all topics, or tell us what you could not find."}),t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:r,children:"Clear search"}),t.jsx(l,{to:"/dashboard?tab=feedback",children:"Send Feedback"}),t.jsx(l,{to:"/contact",children:"Contact TokenWorks"})]})]}):t.jsxs("section",{className:"dashboard-help-search-results","aria-labelledby":"dashboard-help-results",children:[t.jsxs("div",{className:"dashboard-help-results-heading",children:[t.jsxs("div",{children:[t.jsx("p",{className:"dashboard-help-section-kicker",children:"Search results"}),t.jsxs("h2",{id:"dashboard-help-results",children:[i," result",1===i?"":"s"," for â",e.trim(),"â"]})]}),t.jsx("button",{type:"button",onClick:r,children:"Clear search"})]}),a.length?t.jsxs("div",{className:"dashboard-help-result-group",children:[t.jsx("h3",{children:"Topics"}),a.map(e=>t.jsxs(l,{to:`/dashboard?tab=help&topic=${encodeURIComponent(e.id)}`,onClick:t=>{t.preventDefault(),s(e.id)},children:[t.jsxs("span",{children:[t.jsx("strong",{children:e.title}),t.jsx("small",{children:e.summary})]}),t.jsx(de,{size:17,"aria-hidden":"true"})]},e.id))]}):null,n.length?t.jsxs("div",{className:"dashboard-help-result-group",children:[t.jsx("h3",{children:"Questions"}),n.map(({faq:e,guide:a})=>t.jsxs(l,{to:`/dashboard?tab=help&topic=${encodeURIComponent(a.id)}`,onClick:e=>{e.preventDefault(),s(a.id)},children:[t.jsxs("span",{children:[t.jsx("strong",{children:e.question}),t.jsx("small",{children:a.title})]}),t.jsx(de,{size:17,"aria-hidden":"true"})]},`${a.id}-${e.id}`))]}):null]})}function Io({initialTopic:a,onTopicChange:n}){const{makeAuthRequest:s}=Yn(),r=i(),[o,c]=e.useState(Co),[d,u]=e.useState(!0),[h,m]=e.useState(null),[p,g]=e.useState(0),[f,b]=e.useState(""),x=e.useRef(s);x.current=s;const v=e.useRef(null),j=e.useRef(null),y=e.useRef(!1);e.useEffect(()=>{let e=!1;return(async()=>{u(!0),m(null);try{const t=await x.current("/api/help/guides",{method:"GET",_cacheBypass:!0});if(e)return;if(!t?.ok)throw new Error("We could not load Help right now.");c({guides:Array.isArray(t.data?.guides)?t.data.guides:[]})}catch{e||m("We could not load Help right now. Please retry or contact TokenWorks.")}finally{e||u(!1)}})(),()=>{e=!0}},[p]);const k=o.guides,w=e.useMemo(()=>k.find(e=>e.id===a)||null,[k,a]),N=Boolean(a&&!d&&k.length>0&&!w),S=Ro(f),{topicResults:C,faqResults:E}=e.useMemo(()=>{if(!S)return{topicResults:[],faqResults:[]};const e=[],t=[];for(const a of k){[a.title,a.summary,...a.keywords||[]].join(" ").toLocaleLowerCase().includes(S)&&e.push(a);for(const e of a.faqs||[])Ro(e.question).includes(S)&&t.push({faq:e,guide:a})}return{topicResults:e,faqResults:t}},[k,S]),I=C.length+E.length;e.useEffect(()=>{w&&y.current&&(y.current=!1,v.current?.focus())},[w]);const _=e=>{e&&(y.current=!0,"function"==typeof n?n(e):r(`/dashboard?tab=help&topic=${encodeURIComponent(e)}`),w?.id===e&&v.current?.focus())},T=()=>{"function"==typeof n?n(null):r("/dashboard?tab=help"),window.requestAnimationFrame(()=>j.current?.focus())};return t.jsxs("div",{className:"dashboard-help-center",children:[t.jsx(pr,{}),t.jsxs("header",{className:"dashboard-help-header",children:[t.jsxs("div",{className:"dashboard-help-eyebrow",children:[t.jsx(R,{size:17,"aria-hidden":"true"}),t.jsx("span",{children:"Dashboard Help"})]}),t.jsx("h1",{ref:j,tabIndex:"-1",children:"How can we help?"}),t.jsx("p",{children:"Learn how to find documents, read PDFs, organize your research, manage your account, and get support from your TokenWorks dashboard."}),t.jsxs("div",{className:"dashboard-help-search",children:[t.jsx("label",{htmlFor:"dashboard-help-search-input",children:"Search Help"}),t.jsx(oi,{id:"dashboard-help-search-input",value:f,onChange:b,placeholder:"Search topics and common questions",autoComplete:"off","aria-describedby":"dashboard-help-search-hint dashboard-help-search-status"}),t.jsxs("div",{className:"dashboard-help-search-meta",children:[t.jsx("span",{id:"dashboard-help-search-hint",children:"Your search stays in this browser tab."}),t.jsx("span",{id:"dashboard-help-search-status",role:"status","aria-live":"polite",children:S?`${I} Help result${1===I?"":"s"}`:""})]})]})]}),d?t.jsxs("div",{className:"dashboard-help-state",role:"status","aria-live":"polite",children:[t.jsx("div",{className:"spinner-large","aria-hidden":"true"}),t.jsx("p",{children:"Loading Helpâ¦"})]}):h?t.jsxs("section",{className:"dashboard-help-state dashboard-help-error",role:"alert",children:[t.jsx("h2",{children:"Help is temporarily unavailable"}),t.jsx("p",{children:h}),t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>g(e=>e+1),children:"Retry"}),t.jsx(l,{to:"/dashboard?tab=feedback",children:"Send Feedback"}),t.jsx(l,{to:"/contact",children:"Contact TokenWorks"})]})]}):0===k.length?t.jsxs("section",{className:"dashboard-help-state",children:[t.jsx("h2",{children:"No Help topics are available"}),t.jsx("p",{children:"Please try again later or contact TokenWorks."}),t.jsx(l,{to:"/contact",children:"Contact TokenWorks"})]}):t.jsxs(t.Fragment,{children:[N?t.jsxs("aside",{className:"dashboard-help-unknown",role:"status",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"Topic not found"}),t.jsx("span",{children:"This link may be out of date. Search Help or browse the topics below."})]}),t.jsx("button",{type:"button",onClick:T,children:"Help home"})]}):null,w?t.jsxs("div",{className:"dashboard-help-reading-layout",children:[t.jsx(So,{guides:k,selectedTopicId:w.id,onOpenTopic:_}),t.jsx(jo,{guide:w,guides:k,headingRef:v,onOpenTopic:_,onHelpHome:T})]}):S?t.jsx(Eo,{query:f,topicResults:C,faqResults:E,onOpenTopic:_,onClear:()=>b("")}):t.jsx(wo,{guides:k,onOpenTopic:_}),t.jsxs("aside",{className:"dashboard-help-support","aria-labelledby":"dashboard-help-support-title",children:[t.jsxs("div",{children:[t.jsx("h2",{id:"dashboard-help-support-title",children:"Still need help?"}),t.jsx("p",{children:"Tell us what happened or contact TokenWorks for account and billing questions."})]}),t.jsxs("div",{children:[t.jsx(l,{to:"/dashboard?tab=feedback",children:"Send Feedback"}),t.jsx(l,{to:"/contact",children:"Contact TokenWorks"})]})]})]})]})}const _o="recentRead",To="tokenworks:recent-read-updated";function Ao(e){return e?`${_o}:${e}
2`:_o}function Oo(e,t,a){const n=Boolean(t&&a)?`?key=${encodeURIComponent(t)}&provider=${encodeURIComponent(a)}`:"";return e?`/documents/${e}/view${n}`:null}function Do(e){if(!e)return null;try{const t=JSON.parse(e),a=Number(t?.page),n=Number.isInteger(a)&&a>0?a:1,s=t?.documentId?String(t.documentId):null,r=t?.storageKey?String(t.storageKey):null,i=["s3","vercel_blob"].includes(t?.storageProvider)?t.storageProvider:null,l=(s?Oo(s,r,i):t?.resumePath)||(s?Oo(s,r,i):r?`/documents/view?key=${encodeURIComponent(r)}${i?`&provider=${encodeURIComponent(i)}`:""}`:null);return l?{documentId:s,storageKey:r,storageProvider:i,resumePath:l,title:t?.title?String(t.title):"Untitled document",page:n,updatedAt:t?.updatedAt?String(t.updatedAt):(new Date).toISOString()}:null}catch{return null}}function Po(e){if("undefined"==typeof window)return null;const t=Ao(e),a=Do(window.localStorage.getItem(t));if(a)return a;if(!e)return null;const n=Do(window.localStorage.getItem(_o));if(!n)return null;try{window.localStorage.setItem(t,JSON.str
2ingify(n))}catch{return n}return n}function Lo(e,t){if("undefined"==typeof window)return null;const a=Do(JSON.stringify(t));if(!a)return null;const n=Ao(e);try{window.localStorage.setItem(n,JSON.stringify(a))}catch{return null}if(!e)try{window.localStorage.setItem(_o,JSON.stringify(a))}catch{return a}return"function"==typeof window.CustomEvent&&window.dispatchEvent(new window.CustomEvent(To,{detail:a})),a}const $o=new Set(["pending_upload","pending_validation","pending_review","approving"]),Mo=new Set(["failed","rejected","duplicate_rejected"]),Uo=Object.freeze({documents:"Search, read, bookmark, and organize the library.",uploads:"Submit a PDF and follow its review status.",tools:"Open the research and processing tools available to you.",settings:"Manage your account, profile, and security settings.","employee-workspace":"Continue assigned work, messages, projects, and notes.",community:"Open research discussions, people, and shared workspaces.",admin:"Open privileged administration and operational controls."});function Fo({id:e,eyebrow:a,title:n,description:s}){return t.jsxs("div",{className:"dashboard-overview-section-heading",children:[a?t.jsx("p",{children:a}):null,t.jsx("h2",{id:e,children:n}),s?t.jsx("span",{children:s}):null]})}function zo({user:e,capabilities:a,subscriptionLoading:n,showSubscriptionBlocker:s,uploads:r=[],uploadsLoading:i=!1,uploadsError:o=null,recentRead:c,announcement:d,announcementError:u,announcementBu
2sy:h,pendingReactionEmojis:m=[],onReaction:p,internalSummary:g,internalSummaryLoading:f=!1,internalSummaryError:b=null,onOpenHelp:x}){const v=function(e=[]){return e.filter(e=>$o.has(e.status)||Mo.has(e.status))}(r),j=s||v.length>0,y=function(e){return e?e.resumePath?e.resumePath:e.documentId?Oo(e.documentId,e.storageKey,e.storageProvider):e.storageKey?`/documents/view?key=${encodeURIComponent(e.storageKey)}${e.storageProvider?`&provider=${encodeURIComponent(e.storageProvider)}`:""}`:null:null}(c),k=Nr(a).flatMap(e=>e.items).filter(e=>Uo[e.id]),w=g?.taskSummary,N=g?.messageSummary,S=[{label:"Assigned open",value:Number(w?.assignedOpen)||0,to:"/dashboard/employee?tab=tasks",icon:pe},{label:"Overdue",value:Number(w?.overdue)||0,to:"/dashboard/employee?tab=tasks",icon:ge},{label:"Unread conversations",value:Number(N?.unreadConversations)||0,to:"/dashboard/employee?tab=messages",icon:le}].filter(e=>e.value>0),C=Boolean(d?.message),E=!(a.isInternal||i||j||c||C);return t.jsxs("div",{className:"dashboard-overview",children:[t.jsxs("header",{className:"dashboard-overview-hero",children:[t.jsxs("div",{children:[t.jsx("p",{className:"dashboard-overview-eyebrow",children:"Overview"}),t.jsxs("h1",{children:["Welcome back, ",e?.name||"there"]}),t.jsx("span",{children:"Pick up where you left off or move straight to what needs you."})]}),t.jsxs("button",{type:"button",className:"dashboard-help-trigger",onClick:()=>x?.("getting-started"),children:[t.jsx(R,{size:16,"aria-hidden":"true"}),"Help"]})]}),j?t.jsxs("section",{className:"dashboard-overview-section","aria-labelledby":"dashboard-attention-title",children:[t.jsx(Fo,{id:"dashboard-attention-title",eyebrow:"Priority",title:"Needs attention",description:"Items that may block access or need a decision."}),t.jsxs("div",{className:"dashboard-attention-list",children:[s?t.jsxs(l,{className:"dashboard-attention-item is-warning",to:"/subscribe",children:[t.jsx(fe,{size:18,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:"Library access needs an active subscription"}),t.jsx("small",{children:"Review plans to restore protected document access."})]}),t.jsx(de,{size:17,"aria-hidden":"true"})]}):null,v.map(e=>{return t.jsxs(l,{className:"dashboard-attention-item"+(Mo.has(e.status)?" is-danger":""),to:"/dashboard?tab=uploads",children:[t.jsx(fe,{size:18,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:e.title||e.filename||"Document upload"}),t.jsx("small",{children:(a=e.status,Mo.has(a)?"Needs review":"pending_upload"===a?"Upload not finished":"pending_validation"===a?"Validation in progress":"approving"===a?"Publishing in progress":"Awaiting review")})]}),t.jsx(de,{size:17,"aria-hidden":"true"})]},e.id);var a})]})]}):null,E?t.jsxs("section",{className:"dashboard-overview-section","aria-labelledby":"dashboard-onboarding-title",children:[t.jsx(Fo,{id:"dashboard-onboarding-title",eyebrow:"Get started",title:"Start with the library",description:"Search, read, and bookmark documents â your activity will show up here."}),t.jsxs(Js,{className:"dashboard-continue-card",children:[t.jsx(he,{size:20,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("h3",{children:"Browse the library"}),t.jsx("p",{children:"Not sure where to start? The Help center covers uploads, reading, and bookmarks."}),t.jsxs("div",{className:"dashboard-onboarding-actions",children:[t.jsxs(l,{to:"/dashboard?tab=documents",children:["Browse documents ",t.jsx(de,{size:15,"aria-hidden":"true"})]}),t.jsx("button",{type:"button",onClick:()=>x?.("getting-started"),children:"Open Help"})]})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"dashboard-overview-primary-grid",children:[t.jsxs("section",{className:"dashboard-overview-section","aria-labelledby":"dashboard-continue-title",children:[t.jsx(Fo,{id:"dashboard-continue-title",eyebrow:"Continue",title:"Return to your reading",description:"Stored on this browser for a quick return."}),t.jsxs(Js,{className:"dashboard-continue-card",children:[t.jsx(he,{size:20,"aria-hidden":"true"}),c?t.jsxs("div",{children:[t.jsx("h3",{children:c.title}),t.jsxs("p",{children:["Resume from page ",c.page,"."]}),t.jsxs(l,{to:y||"/dashboard?tab=documents",children:["Resume reading ",t.jsx(de,{size:15,"aria-hidden":"true"})]})]}):t.jsxs("div",{children:[t.jsx("h3",{children:"Choose something to read"}),t.jsx("p",{children:"Your most recent reading position will appear here."}),t.jsxs(l,{to:"/dashboard?tab=documents",children:["Browse documents ",t.jsx(de,{size:15,"aria-hidden":"true"})]})]})]})]}),a.isInternal?t.jsxs("section",{className:"dashboard-overview-section","aria-labelledby":"dashboard-work-title",children:[t.jsx(Fo,{id:"dashboard-work-title",eyebrow:"Internal",title:"Workspace",description:"A concise view of your current work."}),t.jsxs(Js,{className:"dashboard-workspace-summary",children:[f?t.jsx("p",{role:"status",children:"Loading Worksp
2ace summaryâ¦"}):null,b?t.jsx("p",{role:"alert",children:"Workspace summary is unavailable right now."}):null,f||b||!g?null:S.length?t.jsx("div",{className:"dashboard-workspace-signals",children:S.map(e=>{const a=e.icon;return t.jsxs(l,{to:e.to,children:[t.jsx(a,{size:17,"aria-hidden":"true"}),t.jsx("strong",{children:e.value}),t.jsx("span",{children:e.label})]},e.label)})}):t.jsx("p",{className:"dashboard-workspace-caught-up",children:"No assigned work needs attention."}),t.jsxs(l,{className:"dashboard-workspace-open",to:"/dashboard/employee",children:["Open Workspace ",t.jsx(de,{size:15,"aria-hidden":"true"})]})]})]}):null]}),t.jsxs("section",{className:"dashboard-overview-section","aria-labelledby":"dashboard-news-title",children:[t.jsx(Fo,{id:"dashboard-news-title",eyebrow:"Updates",title:"Whatâs new"}),t.jsxs(Js,{className:"announcement-card",children:[u?t.jsx("p",{className:"announcement-error",role:"alert",children:u}):d?.message?t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"announcement-message",children:d.message}),d.updatedAt?t.jsxs("p",{className:"announcement-meta",children:["Updated ",new Date(d.updatedAt).toLocaleDateString()]}):null]}):t.jsx("p",{className:"announcement-empty",children:"No announcements right now."}),d?.allowedReactions?.length&&d.message?t.jsx("div",{className:"announcement-reactions","aria-busy":h?"true":"false",children:d.allowedReactions.map(e=>{const a=Number(d.reactions?.[e]||0),n=d.userReactions?.includes(e),s=m.includes(e);return t.jsxs("button",{type:"button",className:`reaction-button${n?" active":""}${s?" pending":""}`,onClick:()=>p?.(e),"aria-label":`${e} reaction, ${a} total${n?", selected":""}`,"aria-busy":s?"true":"false",children:[t.jsx("span",{children:e}),t.jsx("strong",{children:a})]},e)})}):null]})]})]}),t.jsxs("section",{className:"dashboard-overview-section","aria-labelledby":"dashboard-go-to-title",children:[t.jsx(Fo,{id:"dashboard-go-to-title",eyebrow:"Shortcuts",title:"Go to",description:"The same destinations available in your navigation."}),t.jsx("div",{className:"dashboard-destination-grid",children:k.map(e=>{const a=e.icon;return t.jsxs(l,{to:e.to,className:"dashboard-destination-card",children:[t.jsx(a,{size:19,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:e.label}),t.jsx("small",{children:Uo[e.id]})]}),t.jsx(de,{size:16,"aria-hidden":"true"})]},e.id)})})]}),i||n||o?t.jsx("p",{className:"dashboard-overview-load-state","aria-live":"polite",children:o?"Upload attention could not be checked.":"Checking account and upload activityâ¦"}):null]})}const qo=Object.freeze({active:"active",archived:"archived",blocked:"blocked",complete:"complete",completed:"complete",done:"complete",in_progress:"active",running:"active",enabled:"active",onboarding:"active",open:"active",paused:"paused",starting:"review",stopping:"review",ready:"complete",stopped:"neutral",disabled:"neutral",error:"blocked",planned:"neutral",review:"review",todo:"neutral"}),Bo=Object.freeze({low:"low",normal:"normal",medium:"normal",high:"high",urgent:"urgent"});function Wo(e){return String(e??"").trim().toLowerCase().replace(/[\s-]+/gu,"_")}function Vo(e,t="Not set"){const a=Wo(e);return a?a.split("_").filter(Boolean).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(" "):t}function Ho(e){if(!e)return null;const t=/^\d{4}-\d{2}-\d{2}$/u.test(String(e))?`${e}T23:59:59.999`:e,a=new Date(t);return Number.isNaN(a.getTime())?null:a}function Ko(e,t=new Date){const a=Ho(e);if(!a)return{key:"neutral",label:"No due date",date:null,known:!1};const n=a.getTime()-t.getTime(),s=n<0?"overdue":n<=6048e5?"soon":"future";return{key:s,label:"overdue"===s?"Overdue":"soon"===s?"Due soon":"Due",date:a,known:!0}}function Go(e){const t=Ho(e);return t?new Intl.DateTimeFormat("en",{month:"short",day:"numeric",year:"numeric"}).format(t):"No date"}function Jo(...e){return e.filter(Boolean).join(" ")}function Yo({title:a,headingRef:n=null,headingTabIndex:s,description:r=null,actions:i=null,boundary:l="flat",className:o="",children:c,...d}){const u=e.useId();return t.jsxs("section",{className:Jo("ws-section",`ws-section--${l}`,o),"aria-labelledby":a?u:void 0,...d,children:[a||i?t.jsxs("header",{className:"ws-section__header",children:[t.jsxs("div",{children:[a?t.jsx("h2",{ref:n,className:"ws-section-title",id:u,tabIndex:s,children:a}):null,r?t.jsx("p",{className:"ws-section__description",children:r}):null]}),i?t.jsx("div",{className:"ws-section__actions",children:i}):null]}):null,c]})}const Qo=a.forwardRef(function({as:e="article",interactive:t=!1,tone:n="neutral",boundary:s="divided",className:r="",children:i,...l},o){return a.createElement(e,{ref:o,className:Jo("ws-record",`ws-record--${s}`,t&&"ws-record--interactive","neutral"!==n&&`ws-record--${n}`,r),...l},i)});function Xo({as:e="div",boundary:t="flat",className:n="",children:s,...r}){return a.createElement(e,{className:Jo("ws-inset",`ws-inset--${t}`,n),...r},s)}function Zo({items:e=[],label:a="Status summary",className:n=""}){return t.jsx("dl",{className:Jo("ws-status-summary",n),role:"group","aria-label":a,children:e.map(e=>t.jsxs("div",{className:Jo(e.tone&&`ws-status-summary--${e.tone}`),children:[t.jsx("dt",{children:e.label}),t.jsx("dd",{children:e.value??"Unverified"})]},e.label))})}const ec=a.forwardRef(function({as:e="button",variant:a="secondary",size:n="standard",iconOnly:s=!1,className:r="",type:i="button",children:l,...o},c){return t.jsx(e,{ref:c,type:"button"===e?i:void 0,className:Jo("ws-button",`ws-button--${a}`,`ws-button--${n}`,s&&"ws-button--icon",r),...o,children:l})});function tc({value:e,label:a=null,className:n=""}){const s=function(e){const t=Wo(e);return{key:qo[t]||"neutral",label:Vo(e),raw:t,known:Boolean(qo[t])}}(e);return t.jsxs("span",{className:Jo("ws-chip",`ws-chip--${s.key}`,n),children:[t.jsx("span",{className:"ws-chip__dot","aria-hidden":"true"}),a||s.label]})}function ac({value:e,className:a=""}){const n=function(e){const t=Wo(e);return{key:Bo[t]||"normal",label:Vo(e,"Normal"),raw:t,known:Boolean(Bo[t])}}(e);return t.jsxs("span",{className:Jo("ws-chip",`ws-priority--${n.key}`,a),children:[t.jsx("span",{className:"ws-chip__marker","aria-hidden":"true",children:"urgent"===n.key?"!!":"high"===n.key?"!":"â¢"}),n.label]})}function nc({value:e,now:a,className:n="",prefix:s=!0}){const r=Ko(e,a),i="overdue"===r.key?be:ye;return t.jsxs("span",{className:Jo("ws-due-state",`ws-due-state--${r.key}`,n),children:[t.jsx(i,{size:15,"aria-hidden":"true"}),t.jsx("span",{children:r.known?`${s?`${r.label}: `:""}${Go(e)}`:r.label})]})}function sc({label:a="Filters",resultCount:n=null,resultLabel:s=null,activeFilterCount:r=0,onClear:i=null,mobileCollapsible:l=!1,className:o="",children:c}){const[d,u]=e.useState(!1),h=e.useId(),m=a?`${a.charAt(0).toLocaleLowerCase()}${a.slice(1)}`:"filters";return t.jsxs("section",{className:Jo("ws-filter-bar",l&&"ws-filter-bar--mobile-collapsible",o),role:"group","aria-label":a,children:[l?t.jsxs("button",{type:"button",className:"ws-filter-bar__mobile-toggle","aria-expanded":d,"aria-controls":h,"aria-label":`${d?"Hide":"Show"} ${m}`,onClick:()=>u(e=>!e),children:[t.jsxs("span",{children:[t.jsx(je,{size:18,"aria-hidden":"true"})," Filters"]}),t.jsx("small",{children:r?`${r} active`:d?"Hide controls":"Show controls"})]}):null,t.jsx("div",{id:h,className:Jo("ws-filter-bar__controls",d&&"is-mobile-open"),children:c}),t.jsxs("div",{className:"ws-filter-bar__summary","aria-live":"polite",children:[s||null!==n?t.jsx("span",{children:s||`${n} ${1===n?"result":"results"}`}):null,r>0?t.jsxs("span",{children:[r," active ",1===r?"filter":"filters"]}):null,i&&r>0?t.jsx(ec,{variant:"ghost",size:"compact",onClick:i,children:"Clear filters"}):null]})]})}function rc({label:a,required:n=!1,help:s=null,error:r=null,className:i="",children:l}){const o=e.useId(),c=e.isValidElement(l)&&l.props.id?l.props.id:o,d=s?`${c}-help`:void 0,u=r?`${c}
2-error`:void 0,h=[d,u].filter(Boolean).join(" ")||void 0,m=e.isValidElement(l)?e.cloneElement(l,{id:c,required:n||l.props.required,"aria-invalid":r?"true":l.props["aria-invalid"],"aria-describedby":h||l.props["aria-describedby"]}):l;return t.jsxs("div",{className:Jo("ws-form-field",r&&"ws-form-field--error",i),children:[t.jsxs("span",{className:"ws-form-field__label-row",children:[t.jsx("label",{className:"ws-label",htmlFor:c,children:a}),n?t.jsx("span",{className:"ws-form-field__required",children:"Required"}):null]}),m,s?t.jsx("p",{className:"ws-form-field__help",id:d,children:s}):null,r?t.jsxs("p",{className:"ws-form-field__error",id:u,children:[t.jsx(fe,{size:15,"aria-hidden":"true"}),r]}):null]})}function ic({legend:e,description:a=null,className:n="",disabled:s=!1,children:r}){return t.jsxs("fieldset",{className:Jo("ws-form-section",n),disabled:s,children:[t.jsx("legend",{children:e}),a?t.jsx("p",{className:"ws-form-section__description",children:a}):null,t.jsx("div",{className:"ws-form-section__body",children:r})]})}function lc({className:e="",children:a}){return t.jsx("div",{className:Jo("ws-form-actions",e),children:a})}const oc=a.forwardRef(function({type:e="status",children:a,className:n="",...s},r){if(!a)return null;const i="error"===e,l=i?fe:"warning"===e?be:pe;return t.jsxs("p",{ref:r,className:Jo("ws-inline-feedback",`ws-inline-feedback--${e}`,n),role:i?"alert":"status","aria-live":i?"assertive":"polite",...s,children:[t.jsx(l,{size:16,"aria-hidden":"true"}),a]})});function cc({isOpen:a,onClose:s,title:r,description:i=null,variant:l="sheet",closeLabel:o="Close",closeOnBackdrop:c=!0,returnFocusRef:d=null,footer:u=null,className:h="",initialFocusRef:m=null,busy:p=!1,children:f}){const b=e.useRef(null),x=e.useRef(null),v=e.useRef(!1),j=e.useId(),y=e.useId();a&&!v.current&&"undefined"!=typeof document&&(x.current=document.activeElement),e.useLayoutEffect(()=>{v.current=a},[a]);const k=ys({isOpen:a,panelRef:b,initialFocusRef:m,returnFocusRef:d||x,onRequestClose:s});return a&&"undefined"!=typeof document?n.createPortal(t.jsx("div",{className:"ws-overlay-backdrop",onMouseDown:e=>{c&&e.target===e.currentTarget&&k("backdrop")},children:t.jsxs("section",{ref:b,className:Jo("ws-overlay",`ws-overlay--${l}`,h),role:"dialog","aria-modal":"true","aria-labelledby":j,"aria-describedby":i?y:void 0,"aria-busy":p?"true":void 0,tabIndex:-1,children:[t.jsxs("header",{className:"ws-overlay__header",children:[t.jsxs("div",{children:[t.jsx("h2",{id:j,children:r}),i?t.jsx("p",{id:y,children:i}):null]}),t.jsx(ec,{variant:"ghost",iconOnly:!0,"aria-label":o,disabled:p,onClick:()=>k("close-button"),children:t.jsx(g,{size:20,"aria-hidden":"true"})})]}),t.jsx("div",{className:"ws-overlay__body",children:f}),u?t.jsx("footer",{className:"ws-overlay__footer",children:u}):null]})}),xs()):null}function dc({type:e="empty",title:a,description:n=null,action:s=null,className:r=""}){const i="error"===e,l=i?"assertive":["loading","success","unavailable","permission"].includes(e)?"polite":void 0,o="error"===e?fe:"success"===e?pe:"unavailable"===e?be:"permission"===e?xe:"no-results"===e?me:"empty"===e?ve:null;return t.jsxs("section",{className:Jo("ws-request-state",`ws-request-state--${e}`,r),role:i?"alert":l?"status":void 0,"aria-live":l,"aria-busy":"loading"===e?"true":void 0,children:["loading"===e?t.jsxs("span",{className:"ws-request-state__skeleton","aria-hidden":"true",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]}):o?t.jsx(o,{className:"ws-request-state__icon",size:20,"aria-hidden":"true"}):null,t.jsxs("div",{children:[t.jsx("h3",{children:a}),n?t.jsx("p",{children:n}):null,s?t.jsx("div",{className:"ws-request-state__action",children:s}):null]})]})}function uc({label:e,className:a="",children:n,scrollable:s=!1}){return t.jsx("div",{className:Jo("ws-responsive-list",s&&"ws-responsive-list--scrollable",a),role:"region","aria-label":e,tabIndex:s?0:void 0,children:n})}function hc({item:e}){return t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:e.title}),t.jsx("span",{children:e.summary}),t.jsxs("small",{children:[e.actor?.name||"Someone"," ·"," ",t.jsx("time",{dateTime:e.createdAt,children:new Date(e.createdAt).toLocaleStr
2ing()})]})]})}function mc({item:e,onNavigate:a,useLink:n=!1,linkScope:s=null}){const r=e?.urlState?.tab?e.urlState:null,i=r&&s?{...r,scope:s}:r;return r&&n?t.jsx(Qo,{as:l,to:$r(i),interactive:!0,className:"employee-activity-item",children:t.jsx(hc,{item:e})}):r&&a?t.jsx(Qo,{as:"button",type:"button",interactive:!0,className:"employee-activity-item",onClick:()=>a(r),children:t.jsx(hc,{item:e})}):t.jsx(Qo,{className:"employee-activity-item employee-activity-item--static",children:t.jsx(hc,{item:e})})}const pc=Object.freeze({home:"foundation",teams:"foundation",people:"foundation",settings:"foundation",notes:"notes",resources:"foundation",projects:"projects",tasks:"tasks",messages:"messaging",notifications:"messaging",updates:"updates",jupyter:"foundation",wikibase:"wikibase",onboarding:"onboarding"}),gc=Object.freeze(["EMPLOYEE_WORKSPACE_SCHEMA_NOT_READY","EMPLOYEE_WORKSPACE_DATABASE_UNAVAILABLE","DATABASE_TRANSACTION_UNAVAILABLE"]);function fc(e,t){const a=pc[t];if(!a)return!0;if(!e||"object"!=typeof e)return!0;const n=e[a];return void 0===n||Boolean(n)}function bc({loading:e=!1,error:a=null,unavailable:n=!1,isEmpty:s=!1,loadingLabel:r="Loadingâ¦",unavailableLabel:i="Not available yet",unavailableDescription:l="This part of the workspace is still being set up. It will appear here once it is ready.",errorLabel:o="Could not be loaded",permissionLimited:c=!1,permissionLabel:d="Access is limited",permissionDescription:u="Your current workspace role does not include this information.",permissionAction:h=null,emptyLabel:m="Nothing here yet",emptyDescription:p=null,emptyType:g="empty",emptyAction:f=null,onRetry:b=null,className:x="",children:v=null}){const j=n||function(e){return Boolean(e?.code&&gc.includes(e.code))}(a);if(e)return t.jsx(dc,{className:`workspace-request-state ${x}`.trim(),type:"loading",title:r,description:"Please wait while the latest workspace data is prepared."});if(j)return t.jsx(dc,{className:`workspace-request-state ${x}`.trim(),type:"unavailable",title:i,description:l});if(a){const e=a.safeMessage||"Something went wrong. Please try again.";return t.jsx(dc,{className:`workspace-request-state ${x}`.trim(),type:"error",title:o,description:e,action:b?t.jsx(ec,{variant:"secondary",onClick:b,children:"Retry"}):null})}return c?t.jsx(dc,{className:`workspace-request-state ${x}`.trim(),type:"permission",title:d,description:u,action:h}):s?t.jsx(dc,{className:`workspace-request-state ${x}`.trim(),type:g,title:m,description:p,action:f}):v}function xc({endpoint:a="/api/workspace/v1/activity?scope=mine",onNavigate:n,limit:s=10,initialVisibleCount:r=null,useLinks:i=!1}){const{makeAuthRequest:l}=Yn(),[o,c]=e.useState([]),[d,u]=e.useState(!1),[h,m]=e.useState(null),[p,g]=e.useState(null),f=e.useId(),b=e.useCallback(async()=>{u(!0),m(null);try{const e=new URLSearchParams({limit:String(s)}),t=await l(`${a}${a.includes("?")?"&":"?"}${e.toString()}`);c(t.data.activity||[])}catch(e){m(e)}finally{u(!1)}},[a,s,l]);e.useEffect(()=>{b()},[b]);const x=Number.isInteger(r)&&r>0?r:o.length,v=o.slice(0,x),j=o.slice(x),y=`${a}|${o.map(({id:e})=>e).join("|")}`,k=j.length>0&&p===y,w=`Show ${j.length} more activity ${1===j.length?"item":"items"}`,N=e=>t.jsx("li",{children:t.jsx(mc,{item:e,onNavigate:n,useLink:i})},e.id);return t.jsx(Yo,{className:"employee-activity-feed",title:"Recent activity",children:t.jsx(bc,{className:"employee-home-inline-request",loading:d&&!o.length,error:h,isEmpty:!o.length,loadingLabel:"Loading activityâ¦",errorLabel:"Activity could not be loaded",emptyLabel:"No recent activity.",onRetry:b,children:t.jsxs(t.Fragment,{children:[t.jsx("ol",{className:"employee-activity-list",children:v.map(N)}),j.length?t.jsxs(t.Fragment,{children:[t.jsx(ec,{variant:"ghost",className:"employee-home-disclosure employee-activity-disclosure","aria-expanded":k,"aria-controls":f,onClick:()=>g(k?null:y),children:k?"Show less":w}),t.jsx("ol",{id:f,className:"employee-activity-list employee-activity-list--additional",start:x+1,hidden:!k,children:j.map(N)})]}):null]})})})}function vc({progress:e,status:a,compact:n=!1}){const s=Number(e?.completedRequired||0),r=Number(e?.totalRequired||0),i=Number(e?.percent||0),l=["completed","waived"].includes(a),o=Math.max(0,Math.min(l?100:99,i)),c=`${s} of ${r} required items · ${o}%`;return t.jsxs("div",{className:"onboarding-progress"+(n?" onboarding-progress--compact":""),children:[t.jsxs("div",{className:"onboarding-progress-copy",children:[t.jsx("strong",{children:c}),n?null:t.jsx("span",{children:"Final completion includes the required quiz."})]}),t.jsxs("progress",{max:"100",value:o,"aria-label":`Onboarding progress: ${c}`,children:[o,"%"]})]})}function jc({onboarding:e,onNavigate:a}){const n=e?.enabled?e.activeAssignment:null;return n?t.jsxs(Qo,{className:"onboarding-home-card",boundary:"elevated",children:[t.jsxs("div",{children:[t.jsx("span",{className:"onboarding-eyebrow",children:"Continue internal onboarding"}),t.jsxs("h2",{children:[n.program.name," v",n.program.version]}),t.jsx(vc,{progress:n.progress,status:n.status,compact:!0})]}),t.jsx(ec,{variant:"primary",onClick:()=>a?.({tab:"onboarding",assignmentId:n.id}),children:"Continue onboarding"})]}):null}function yc(e,t,a){const[n,s=""]=e.split("#",2),r=n.includes("?")?"&":"?";return`${n}${r}limit=${t}&offset=${a}${s?`#${s}`:""}`}function kc(t,a={}){const{makeAuthRequest:n}=Yn(),s=e.useRef(a.initialData||null).current,r=a.collectionKey||null,i=a.pageSize||50,[l,o]=e.useState({endpoint:t,data:s,error:null}),[c,d]=e.useState(t||null),[u,h]=e.useState(!1),[m,p]=e.useState(null),[g,f]=e.useState(!1),[b,x]=e.useState({endpoint:null,generation:0,operation:null,status:"idle",requestToken:null,error:null}),v=e.useRef(0),j=e.useCallback(async({rejectOnError:e=!1,requestToken:a=null}={})=>
2{if(!t)return null;const l=++v.current;x({endpoint:t,generation:l,operation:"refresh",status:"pending",requestToken:a,error:null}),d(t),h(!1),p(null),f(!1),o(e=>e.endpoint===t?{...e,error:null}:e);try{const e=r?yc(t,i+1,0):t,s=await n(e);if(l!==v.current)return null;const c=r&&s.data?.[r]||[],d=r?{...s.data,[r]:c.slice(0,i)}:s.data;return f(Boolean(r&&c.length>i)),o({endpoint:t,data:d,error:null}),x({endpoint:t,generation:l,operation:"refresh",status:"success",requestToken:a,error:null}),d}catch(c){if(l!==v.current)return null;if(o({endpoint:t,data:s,error:c}),x({endpoint:t,generation:l,operation:"refresh",status:"error",requestToken:a,error:c}),e)throw c;return null}finally{l===v.current&&d(null)}},[r,t,s,n,i]),y=e.useCallback(async()=>{if(!t||!r||u||!g)return null;const e=l.endpoint===t&&l.data?.[r]||[],a=++v.current;x({endpoint:t,generation:a,operation:"loadMore",status:"pending",requestToken:null,error:null}),d(null),h(!0),p(null);try{const s=await n(yc(t,i+1,e.length));if(a!==v.current)return null;const l=s.data?.[r]||[],c=l.slice(0,i);return f(l.length>i),o(e=>e.endpoint===t?{...e,data:{...e.data,...s.data,[r]:[...e.data?.[r]||[],...c]}}:e),x({endpoint:t,generation:a,operation:"loadMore",status:"success",requestToken:null,error:null}),c}catch(s){return a===v.current&&(p(s),x({endpoint:t,generation:a,operation:"loadMore",status:"error",requestToken:null,error:s})),null}finally{a===v.current&&h(!1)}},[r,t,g,u,n,i,l]);e.useEffect(()=>{j()},[j]);const k=l.endpoint===t;return{data:k?l.data:s,loading:Boolean(t)&&(!k||c===t),error:k?l.error:null,refresh:j,hasMore:k&&g,loadMore:y,loadingMore:u,loadMoreError:m,requestLifecycle:b}}function wc(e,t="No due date"){if(!e)return t;const a=String(e),n=/^(\d{4})-(\d{2})-(\d{2})/.exec(a);return n?`${n[1]}-${n[2]}-${n[3]}`:a}function Nc(e){const t=Number(e||0);return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:t<1073741824?`${(t/1024/1024).toFixed(1)} MB`:`${(t/1024/1024/1024).toFixed(1)} GB`}function Sc(e,t="Unknown"){const a=String(e??"").trim().replace(/[_-]+/g," ").replace(/\s+/g," ");return a?`${a.charAt(0).toLocaleUpperCase()}${a.slice(1)}`:t}const Cc=Object.freeze({format:"tokenworks.update.prosemirror",version:1,document:{type:"doc",content:[{type:"paragraph"}]}});function Rc(e){try{const t=new URL(e);return"https:"===t.protocol&&!t.username&&!t.password}catch{return!1}}function Ec({node:e,path:a,headingOffset:n}){if(!e||"object"!=typeof e)return null;if("text"===e.type)return function(e,a){return(e.marks||[]).reduce((e,a,n)=>"bold"===a.type?t.jsx("strong",{children:e},n):"italic"===a.type?t.jsx("em",{children:e},n):"code"===a.type?t.jsx("code",{children:e},n):"link"===a.type&&Rc(a.attrs?.href)?t.jsx("a",{href:a.attrs.href,target:"_blank",rel:"noopener noreferrer",children:e},n):e,a)}(e,e.text);if("hardBreak"===e.type)return t.jsx("br",{});if("horizontalRule"===e.type)return t.jsx("hr",{});const s=(e.content||[]).map((e,s)=>t.jsx(Ec,{node:e,path:`${a}-${s}`,headingOffset:n},`${a}-${s}`));if("paragraph"===e.type)return t.jsx("p",{children:s});if("heading"===e.type&&[2,3].includes(e.attrs?.level)){const a=`h${Math.min(6,e.attrs.level+n)}`;return t.jsx(a,{children:s})}return"bulletList"===e.type?t.jsx("ul",{children:s}):"orderedList"===e.type?t.jsx("ol",{children:s}):"listItem"===e.type?t.jsx("li",{children:s}):"blockquote"===e.type?t.jsx("blockquote",{children:s}):"codeBlock"===e.type?t.jsx("pre",{children:s}):null}function Ic({document:e,className:a="",headingOffset:n=0}){const s=e?.document?.content;return Array.isArray(s)?t.jsx("div",{className:`workspace-update-prose ${a}`.trim(),children:s.map((e,a)=>t.jsx(Ec,{node:e,path:String(a),headingOffset:n},a))}):null}function _c({label:e,active:a,disabled:n,tabIndex:s,onFocus:r,onClick:i,expanded:l,controls:o,buttonRef:c,children:d}){return t.jsxs("button",{ref:c,type:"button","aria-label":e,"aria-pressed":void 0===a?void 0:a,"aria-expanded":l,"aria-controls":o,title:e,disabled:n,tabIndex:s,onFocus:r,onClick:i,children:[d,t.jsx("span",{className:"sr-only",children:e})]})}function Tc({value:n,onChange:s,disabled:r=!1}){const i=e.useRef(null),l=e.useRef(null),o=e.useRef(null),c=e.useId(),[d,u]=e.useState(0),[h,m]=e.useState(!1),[p,g]=e.useState("https://"),[f,b]=e.useState(""),x=e.useMemo(()=>[Xt.configure({heading:{levels:[2,3]},link:!1,strike:!1}),Zt.configure({openOnClick:!1,autolink:!1,protocols:["https"],HTMLAttributes:{rel:"noopener noreferrer",target:null},isAllowedUri:Rc})],[]),v=ea({extensions:x,content:n?.document||Cc.document,editable:!r,editorProps:{attributes:{class:"workspace-update-editor-document",role:"textbox","aria-label":"Update article content","aria-multiline":"true"},transformPastedHTML:e=>e.replace(/<(script|style|iframe)[^>]*>[\s\S]*?<\/\1>/giu,"")}
2,onUpdate:({editor:e})=>s?.({format:Cc.format,version:Cc.version,document:e.getJSON()})},[]);if(e.useEffect(()=>v?.setEditable(!r),[r,v]),e.useEffect(()=>{v&&n?.document&&JSON.stringify(v.getJSON())!==JSON.stringify(n.document)&&v.commands.setContent(n.document,{emitUpdate:!1})},[v,n]),e.useEffect(()=>{h&&o.current?.focus()},[h]),!v)return t.jsx("p",{role:"status",children:"Preparing the article editorâ¦"});const j=[{label:"Text style",controls:[["Bold",ke,()=>v.chain().focus().toggleBold().run(),v.isActive("bold")],["Italic",we,()=>v.chain().focus().toggleItalic().run(),v.isActive("italic")],["Heading 2",Ne,()=>v.chain().focus().toggleHeading({level:2}).run(),v.isActive("heading",{level:2})],["Heading 3",Se,()=>v.chain().focus().toggleHeading({level:3}).run(),v.isActive("heading",{level:3})]]},{label:"Structure",controls:[["Bulleted list",Ce,()=>v.chain().focus().toggleBulletList().run(),v.isActive("bulletList")],["Numbered list",Re,()=>v.chain().focus().toggleOrderedList().run(),v.isActive("orderedList")],["Block quote",Ee,()=>v.chain().focus().toggleBlockquote().run(),v.isActive("blockquote")],["Horizontal rule",Ie,()=>v.chain().focus().setHorizontalRule().run(),void 0]]},{label:"Code",controls:[["Inline code",_e,()=>v.chain().focus().toggleCode().run(),v.isActive("code")],["Code block",Te,()=>v.chain().focus().toggleCodeBlock().run(),v.isActive("codeBlock")]]},{label:"History",controls:[["Undo",ae,()=>v.chain().focus().undo().run(),void 0],["Redo",Ae,()=>v.chain().focus().redo().run(),void 0]]}],y=j.flatMap(e=>e.controls),k=()=>{m(!1),b(""),requestAnimationFrame(()=>l.current?.focus())};return t.jsxs("div",{className:"workspace-update-rich-editor",children:[t.jsxs("div",{ref:i,className:"workspace-update-editor-toolbar",role:"toolbar","aria-label":"Article formatting","aria-disabled":r||void 0,tabIndex:r?0:void 0,onKeyDown:e=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;e.preventDefault();const t=y.length+1,a="Home"===e.key?0:"End"===e.key?t-1:"ArrowRight"===e.key?(d+1)%t:(d-1+t)%t;u(a),i.current?.querySelectorAll("button")?.[a]?.focus()},children:[j.map(e=>t.jsx("span",{className:"workspace-update-editor-toolbar-group",role:"group","aria-label":e.label,children:e.controls.map(([e,n,s,i])=>{const l=y.findIndex(([t])=>t===e);return t.jsx(_c,{label:e,active:i,disabled:r||!v.can().chain().focus().run(),tabIndex:d===l?0:-1,onFocus:()=>u(l),onClick:s,children:a.createElement(n,{size:17,"aria-hidden":!0})},e)})},e.label)),t.jsx("span",{className:"workspace-update-editor-toolbar-group",role:"group","aria-label":"Links",children:t.jsx(_c,{label:"Add or edit link",active:v.isActive("link"),disabled:r,expanded:h,controls:c,buttonRef:l,tabIndex:d===y.length?0:-1,onFocus:()=>u(y.length),onClick:()=>{g(v.getAttributes("link").href||"https://"),m(!0)},children:t.jsx(Oe,{size:17,"aria-hidden":"true"})})})]}),h?t.jsxs("form",{id:c,className:"workspace-update-editor-link",onSubmit:e=>{e.preventDefault(),Rc(p)?(v.chain().focus().extendMarkRange("link").setLink({href:p}).run(),m(!1),b(""),requestAnimationFrame(()=>l.current?.focus())):b("Enter a complete HTTPS address without credentials.")},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),k())},children:[t.jsxs("label",{children:["Secure link",t.jsx("input",{ref:o,type:"url",inputMode:"url",maxLength:2048,value:p,"aria-invalid":Boolean(f),onChange:e=>{g(e.target.value),b("")}})]}),t.jsx("button",{type:"submit",children:"Apply"}),v.isActive("link")?t.jsx("button",{type:"button",onClick:()=>{v.chain().focus().unsetLink().run(),k()},children:"Remove link"}):null,t.jsx("button",{type:"button",onClick:k,children:"Cancel"}),f?t.jsx("p",{role:"alert",children:f}):null]}):null,t.jsx(ta,{editor:v})]})}const Ac=["general","company","project","research","operations","resource"];function Oc(e){return e?`${e.charAt(0).toUpperCase()}${e.slice(1).replaceAll("_"," ")}`:""}function Dc(e){return e?new Intl.DateTimeFormat(void 0,{dateStyle:"medium"}).format(new Date(e)):""}function Pc(e){return!(!e.updatedAt||!e.publishedAt)&&new Date(e.updatedAt).getTime()-new Date(e.publishedAt).getTime()>1e3}function Lc(e){try{const t=new URL(e);return"https:"!==t.protocol||t.username||t.password?null:t}catch{return null}}function $c({update:e,compact:a=!1}){return t.jsxs("div",{className:"workspace-update-meta"+(a?" is-compact":""),children:[e.isRead?null:t.jsx("span",{className:"workspace-update-unread",children:"Unread"}),e.isImportant?t.jsxs("span",{className:"workspace-update-important",children:[t.jsx(fe,{size:14,"aria-hidden":"true"})," Important"]}):null,e.isPinned?t.jsxs("span",{children:[t.jsx(Pe,{size:14,"aria-hidden":"true"})," Pinned"]}):null,e.category?t.jsx("span",{children:Oc(e.category)}
2):null,e.audienceContext?.label?t.jsx("span",{children:e.audienceContext.label}):null,e.publishedAt?t.jsx("time",{dateTime:e.publishedAt,children:Dc(e.publishedAt)}):null]})}function Mc({preview:e,onRefresh:a,onRemove:n,busy:s=!1,authoring:r=!1,ordinal:i=1,headingLevel:l=3}){const o=e.status||"failed",c=function(e){return[e?.canonicalUrl,e?.url].filter(Boolean).map(Lc).find(Boolean)}(e),d="ready"!==o||!c,{source:u,displayPath:h}=function(e,t){const a=t?.hostname.replace(/^www\./u,"")||"",n=e.siteName||(/(^|\.)x\.com$/iu.test(a)?"X":/(^|\.)twitter\.com$/iu.test(a)?"Twitter":a||"External link"),s=[...t?.pathname||""].map(e=>{const t=e.codePointAt(0);return t<32||127===t?"":e}).join("").replace(/\/{2,}/gu,"/"),r=s&&"/"!==s?s:"";return{source:n,displayPath:r.length>72?`${r.slice(0,69)}â¦`:r}}(e,c),m=h?`${u} link · ${h}`:`${u} link`,p=`h${l}`,g="pending"===o?c?"Rich preview details are still being prepared. The link remains available.":r?"No safe HTTPS destination is available. Replace or remove this link before publishing.":"No safe HTTPS destination is available for this saved link.":c?"Rich preview details are unavailable. The original safe link remains available.":r?"No safe HTTPS destination is available. Replace or remove this link before publishing.":"No safe HTTPS destination is available for this saved link.";return t.jsxs("article",{className:"workspace-update-link-preview"+(d?" has-error":""),"aria-busy":s,children:[t.jsxs("div",{children:[t.jsx("span",{children:u}),t.jsx(p,{children:e.title||m}),e.description?t.jsx("p",{children:e.description}):null,d?t.jsx("p",{children:g}):null]}),t.jsxs("div",{className:"workspace-update-link-actions",children:[c?t.jsxs("a",{href:c.href,target:"_blank",rel:"noopener noreferrer","aria-label":`Visit ${e.title||m}, link ${i}, in a new tab`,children:["Visit source ",t.jsx(Le,{size:15,"aria-hidden":"true"})]}):null,a?t.jsx("button",{type:"button",disabled:s,onClick:()=>a(e),children:"Refresh"}):null,n?t.jsx("button",{type:"button",className:"workspace-update-link-remove",disabled:s,onClick:()=>n(e),children:"Remove"}):null]})]})}function Uc({resource:e,onOpen:a,opening:n=!1}){const s="object"===e.targetKind?j:"folder"===e.targetKind?M:he,r=cn(e),i=r.targetLabel||Oc(e.targetKind)||"Workspace Resource",l=t.jsxs(t.Fragment,{children:[t.jsx(s,{size:19,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:r.title}),t.jsx("small",{children:i})]}),n?t.jsx("span",{className:"workspace-update-resource-pending",children:"Openingâ¦"}):null,!n&&a?t.jsx(Le,{size:16,"aria-hidden":"true"}):null]});return a?t.jsx("button",{type:"button",className:"workspace-update-resource",onClick:()=>a(e),disabled:n,"aria-label":`${n?"Opening":"Open"} ${r.label}`,children:l}):t.jsx("div",{className:"workspace-update-resource is-preview","aria-label":r.label,children:l})}function Fc({linkPreviews:e=[],resources:a=[],restrictedResourceCount:n=0,onOpenResource:s=null,authoring:r=!1,headingLevel:i=2,idPrefix:l="update",openingResourceKey:o=null,resourceOpenError:c=null}){const d=`h${i}`;return t.jsxs(t.Fragment,{children:[e.length?t.jsxs("section",{className:"workspace-update-related","aria-labelledby":`${l}-links-heading`,children:[t.jsx(d,{id:`${l}-links-heading`,children:"Related links"}),e.map((e,a)=>t.jsx(Mc,{preview:e,authoring:r,ordinal:a+1,headingLevel:i+1},e.id))]}):null,a.length||n?t.jsxs("section",{className:"workspace-update-related","aria-labelledby":`${l}-resources-heading`,children:[t.jsx(d,{id:`${l}-resources-heading`,children:"Workspace Resources"}),t.jsx("div",{className:"workspace-update-resources",children:a.map(e=>t.jsx(Uc,{resource:e,onOpen:s,opening:o===ln(e)},ln(e)))}),c?t.jsx("p",{className:"workspace-update-resource-error",role:"alert",children:c}):null,n?t.jsxs("p",{className:"workspace-update-restricted",role:"status",children:[n," attached Resource",1===n?" is":"s are"," unavailable with your current access."]}):null]}):null]})}function zc({update:e,onOpen:a,compact:n=!1}){return t.jsxs(Qo,{as:"article",boundary:"divided",className:`workspace-update-row${n?" is-compact":""}${e.isPinned?" is-pinned":""}`,children:[t.jsx($c,{update:e,compact:n}),t.jsx("h3",{children:t.jsx("button",{type:"button","data-update-id":e.id,onClick:()=>a(e.id),children:e.title})}),e.excerpt?t.jsx("p",{children:e.excerpt}):null,n||!e.resourceCount&&!e.linkPreviewCount?null:t.jsxs("span",{className:"workspace-update-attachment-summary",children:[Number(e.resourceCount||0)," Resource",1===e.resourceCount?"":"s"," ·"," ",Number(e.linkPreviewCount||0)," external link",1===e.linkPreviewCount?"":"s"]})]})}function qc({updateId:n,onBack:s,onOpenResource:r}){const{makeAuthRequest:i}=Yn(),[l,o]=e.useState({loading:!0,update:null,error:null}),c=a.useRef(null),d=a.useRef(null),u=a.useRef(null),h=a.useRef(null),m=a.useRef(0),p=a.useRef(null),g=a.useRef(0),f=a.useRef(n);f.current=n;const[b,x]=e.useState(!1),[v,j]=e.useState(!1),[y,k]=e.useState(0),[w,N]=e.useState(""),S=a.useRef(null),C=a.useRef(!1),[R,E]=e.useState({key:null,error:null}),I=e.useCallback(async()=>{const e=++m.current;o(e=>({...e,loading:!0,error:null}));try{const t=await i(`/api/workspace/v1/updates/${encodeURIComponent(n)}?scope=mine`);e===m.current&&(x(!1),o({loading:!1,update:t.data.update,error:null}))}catch(t){e===m.current&&o({loading:!1,update:null,error:t})}},[i,n]);if(e.useEffect(()=>{I()},[I]),e.useEffect(()=>(g.current+=1,p.current=null,d.current=null,C.current=!1,j(!1),N(""),E({key:null,error:null}),()=>{g.current+=1}),[n]),e.useEffect(()=>{const e=l.update?.id;if(!e||e!==n)return;if(d.current===e)return;const t=window.requestAnimationFrame(()=>{const t=c.current;t&&(d.current=e,t.focus({preventScroll:!0}),t.scrollIntoView?.({block:"start",behavior:"auto"}))});return()=>window.cancelAnimationFrame(t)},[l.update?.id,n]),e.useEffect(()=>{l.update&&u.current!==l.update.id&&h.current!==l.update.id&&(h.current=l.update.id,j(!0),N(""),i(`/api/workspace/v1/updates/${encodeURIComponent(l.update.id)}/read?scope=mine`,{method:"POST",body:JSON.stringify({})}).then(()=>{h.current===l.update.id&&(u.current=l.update.id,h.current=null,C.current&&(C.current=!1,c.current?.focus?.({preventScroll:!0})),j(!1),x(!1),N("Update marked read."),function(e){"undefined"==typeof window||"string"!=typeof e||!e.trim()||window.dispatchEvent(new CustomEvent(Er,{detail:{updateId:e}}))}(l.update.id),o(e=>e.update?.id===l.update.id?{...e,update:{...e.update,isRead:!0}}:e))}).catch(()=>{h.current===l.update.id&&(h.current=null,j(!1),x(!0),C.current&&(C.current=!1,window.requestAnimationFrame(()=>S.current?.focus?.())))}
2))},[i,y,l.update]),l.loading)return t.jsx(bc,{loading:!0,loadingLabel:"Loading Updateâ¦"});if(l.error){const e="WORKSPACE_UPDATE_NOT_FOUND"===l.error.code;return t.jsxs("div",{className:"workspace-update-detail-state",children:[t.jsx("h1",{className:"sr-only",children:"Workspace Update unavailable"}),t.jsxs(ec,{variant:"ghost",onClick:s,children:[t.jsx(G,{size:16,"aria-hidden":"true"})," Back to Updates"]}),t.jsx(bc,{error:l.error,errorLabel:e?"This Workspace Update is not available.":"Update could not load",onRetry:e?null:I})]})}const _=l.update;return t.jsxs("article",{ref:c,className:"workspace-update-article",tabIndex:-1,"aria-labelledby":"workspace-update-detail-title",children:[t.jsxs(ec,{variant:"ghost",onClick:s,children:[t.jsx(G,{size:16,"aria-hidden":"true"})," Back to Updates"]}),t.jsxs("header",{children:[t.jsx($c,{update:_}),t.jsx("h1",{id:"workspace-update-detail-title",children:_.title}),_.summary?t.jsx("p",{className:"workspace-update-article-summary",children:_.summary}):null,t.jsxs("p",{className:"workspace-update-byline",children:["By ",_.author?.name||"Former Workspace administrator",Pc(_)?t.jsxs(t.Fragment,{children:[" · Updated ",t.jsx("time",{dateTime:_.updatedAt,children:Dc(_.updatedAt)})]}):null]})]}),b?t.jsxs("p",{className:"workspace-update-read-error",role:"status",children:["Read status was not saved."," ",t.jsx("button",{ref:S,type:"button",disabled:v,"aria-busy":v?"true":void 0,onClick:()=>{C.current=!0,j(!0),k(e=>e+1)},children:v?"Retrying read statusâ¦":"Retry"})]}):null,t.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:w}),t.jsx(Ic,{document:_.bodyDocument}),t.jsx(Fc,{linkPreviews:_.linkPreviews,resources:_.resources,restrictedResourceCount:_.restrictedResourceCount,onOpenResource:async e=>{if(!r||p.current)return;const t=++g.current,a=n,s=()=>t===g.current&&f.current===a,i=ln(e);p.current=i,E({key:i,error:null});try{if(await r({...e,updateId:a},{isCurrent:s}),!s())return;E({key:null,error:null})}catch(l){if(!s())return;E({key:null,error:l?.safeMessage||l?.message||"This Resource could not be opened."})}finally{s()&&(p.current=null)}},openingResourceKey:R.key,resourceOpenError:R.error})]})}function Bc({updateId:n=null,projectId:s="",onOpenUpdate:r,onProjectFilterChange:i,onOpenResource:l}){const{makeAuthRequest:o}=Yn(),[c,d]=e.useState({search:"",submittedSearch:"",category:"",unread:!1}),[u,h]=e.useState([]),[m,p]=e.useState({loading:!0,items:[],cursor:null,error:null}),[g,f]=e.useState({loading:!1,error:null,cursor:null}),[b,x]=e.useState({loading:!0,error:null}),[v,j]=e.useState(""),y=a.useRef(null),k=a.useRef(null),w=a.useRef(null),N=a.useRef(0),S=a.useRef(0),C=a.useId(),R=e.useMemo(()=>{const e=new URLSearchParams({scope:"mine",limit:"12"});return c.submittedSearch&&e.set("q",c.submittedSearch),c.category&&e.set("category",c.category),c.unread&&e.set("unread","true"),s&&e.set("projectId",s),`/api/workspace/v1/updates?${e}`},[c.category,c.submittedSearch,c.unread,s]),E=e.useCallback(async({cursor:e=null,append:t=!1}={})=>{const a=++N.current;t?f({loading:!0,error:null,cursor:e}):(p(e=>({...e,loading:!0,error:null})),f({loading:!1,error:null,cursor:null}));try{const n=await o(e?`${R}&cursor=${encodeURIComponent(e)}`:R);if(a!==N.current)return null;const s=n.data||{};return p(e=>({loading:!1,items:t?[...e.items,...s.updates||[]]:s.updates||[],cursor:s.pagination?.nextCursor||null,error:null})),t&&f({loading:!1,error:null,cursor:null}),s}catch(n){return a===N.current&&(t?f({loading:!1,error:n,cursor:e}):p(e=>({...e,loading:!1,error:n}))),null}},[R,o]);e.useEffect(()=>{n||E()},[E,n]);const I=e.useCallback(async()=>{const e=++S.current;let t;x({loading:!0,error:null});try{const e=await o("/api/workspace/v1/projects?scope=mine&limit=100");t=e.data?.projects||[]}catch(a){return void(e===S.current&&x({loading:!1,error:a}))}if(s&&!t.some(e=>e.id===s))try{const e=await o(`/api/workspace/v1/projects/${encodeURIComponent(s)}?scope=mine`),a=e.data?.project;a?.id===s&&(t=[...t,a])}catch(a){return void(e===S.current&&(h(t),x({loading:!1,error:a})))}e===S.current&&(h(t),x({loading:!1,error:null}))},[o,s]);e.useEffect(()=>(I(),()=>{S.current+=1}),[I]),e.useEffect(()=>{if(n||!w.current)return;const e=y.current?.querySelector(`[data-update-id="${w.current}"]`);requestAnimationFrame(()=>e?.focus())},[n]);const _=e.useCallback(e=>{w.current=e,r(e)},[r]);if(n)return t.jsx(qc,{updateId:n,onBack:()=>r(null),onOpenResource:l});const T=!m.loading&&!m.error&&!m.items.length,A="EMPLOYEE_WORKSPACE_SCHEMA_NOT_READY"===m.error?.code,O=u.some(e=>e.id===s),D=b.loading?"Loading selected projectâ¦":"Selected project (details unavailable)";return t.jsxs("div",{className:"workspace-updates-feed",children:[t.jsxs("section",{className:"workspace-update-filter-section","aria-labelledby":"update-filters-heading",children:[t.jsx("h2",{id:"update-filters-heading",className:"sr-only",children:"Filter Workspace Updates"}),t.jsxs("form",{className:"workspace-update-filters","aria-label":"Filter Workspace Updates",onSubmit:e=>{e.preventDefault();const t=c.search.trim();1!==t.length?(j(""),d(e=>({...e,submittedSearch:t}))):j("Enter at least 2 characters to search Updates.")},children:[t.jsxs("label",{className:"workspace-update-search",children:[t.jsx("span",{children:"Search Updates"}),t.jsxs("span",{children:[t.jsx(ue,{size:17,"aria-hidden":"true"}),t.jsx("input",{type:"search",value:c.search,"aria-invalid":Boolean(v),"aria-describedby":v?"w
2orkspace-update-search-error":void 0,placeholder:"Search titles and articles",onChange:e=>d(t=>({...t,search:e.target.value}))})]})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Project"}),t.jsxs("select",{value:s,"aria-busy":b.loading?"true":"false","aria-describedby":C,onChange:e=>i(e.target.value),children:[t.jsx("option",{value:"",children:"All accessible projects"}),s&&!O?t.jsx("option",{value:s,children:D}):null,u.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Category"}),t.jsxs("select",{value:c.category,onChange:e=>d(t=>({...t,category:e.target.value})),children:[t.jsx("option",{value:"",children:"All categories"}),Ac.map(e=>t.jsx("option",{value:e,children:Oc(e)},e))]})]}),t.jsxs("div",{className:"workspace-update-filter-actions",children:[t.jsxs("label",{className:"workspace-update-unread-toggle",children:[t.jsx("input",{type:"checkbox",checked:c.unread,onChange:e=>d(t=>({...t,unread:e.target.checked}))}),t.jsx(De,{size:16,"aria-hidden":"true"})," Unread only"]}),t.jsx(ec,{variant:"primary",type:"submit",children:"Search"})]})]}),v?t.jsx("p",{id:"workspace-update-search-error",role:"alert",children:v}):null,t.jsx("div",{id:C,className:"workspace-update-project-options-state",children:b.loading?t.jsx("p",{role:"status",children:"Loading accessible projectsâ¦"}):b.error?t.jsxs(oc,{type:"error",children:[t.jsxs("span",{children:["Project choices could not be loaded.",s?" The selected project remains active.":""]}),t.jsx(ec,{variant:"ghost",size:"compact",onClick:()=>{I()},children:"Retry project choices"})]}):null})]}),t.jsxs(bc,{loading:m.loading&&!m.items.length,error:A?null:m.error,unavailable:A,loadingLabel:"Loading your Updatesâ¦",unavailableLabel:"Workspace Updates are temporarily unavailable.",errorLabel:"Workspace Updates could not be loaded",isEmpty:T,emptyLabel:c.unread?"You are caught upâthere are no unread Updates.":c.submittedSearch||c.category||s?"No Updates match these filters.":"No Workspace Updates have been published yet.",onRetry:()=>E(),children:[t.jsx("p",{className:"sr-only",role:"status",children:m.loading?"Updating results.":`${m.items.length} Updates shown.`}),t.jsx("div",{ref:y,className:"workspace-update-list",tabIndex:-1,children:m.items.map(e=>t.jsx(zc,{update:e,onOpen:_},e.id))}),!m.loading&&m.cursor||g.error?t.jsxs("div",{className:"workspace-update-load-more","aria-busy":g.loading?"true":"false",children:[g.error?t.jsx(oc,{type:"error",children:g.error.safeMessage||"More Updates could not be loaded."}):null,t.jsx(ec,{ref:k,variant:"secondary",disabled:g.loading,onClick:()=>{(async()=>{const e=g.error?g.cursor:m.cursor;if(!e)return;const t=new Set(m.items.map(e=>e.id)),a="undefined"!=typeof document&&document.activeElement===k.current,n=await E({cursor:e,append:!0});if(!a)return;const s=(n?.updates||[]).find(e=>!t.has(e.id));window.requestAnimationFrame(()=>{let e=k.current;n&&!n.pagination?.nextCursor&&s&&(e=Array.from(y.current?.querySelectorAll("[data-update-id]")||[]).find(e=>e.dataset.updateId===s.id)),e?.focus?.({preventScroll:!0})})})()},children:g.loading?"Loading moreâ¦":g.error?"Retry loading more Updates":"Load more Updates"})]}):null]})]})}function Wc({projectId:a,onOpenUpdate:n,onViewAll:s,request:r}){const[i,l]=e.useState({loading:!0,items:[],error:null}),o=e.useCallback(()=>{let e=!1;return l(e=>({...e,loading:!0,error:null})),Promise.resolve(r(`/api/workspace/v1/projects/${encodeURIComponent(a)}/updates?scope=mine&limit=3`)).then(t=>{e||l({loading:!1,items:t?.data?.updates||[],error:null})}).catch(t=>{e||l({loading:!1,items:[],error:t})}),()=>{e=!0}},[a,r]);return e.useEffect(()=>o(),[o]),t.jsx(Yo,{className:"workspace-project-updates",title:"Latest project Updates",actions:t.jsx(ec,{variant:"ghost",onClick:s,children:"View all for this project"}),children:t.jsx(bc,{loading:i.loading,error:i.error,loadingLabel:"Loading project Updatesâ¦",errorLabel:"Project Updates could not be loaded",isEmpty:!i.loading&&!i.error&&!i.items.length,emptyLabel:"No project Updates yet.",onRetry:o,children:i.items.map(e=>t.jsx(zc,{update:e,onOpen:n,compact:!0},e.id))})})}function Vc({title:e="Latest from TokenWorks",description:a="Relevant announcements, project news, and shared context.",boundary:n="flat",previewLimit:s=3}){const r=i(),o=Number.isInteger(s)&&s>0?s:3,{data:c,loading:d,error:u,refresh:h}=kc(`/api/workspace/v1/updates?scope=mine&limit=${o}`),m=(c?.updates||[]).slice(0,o),p="EMPLOYEE_WORKSPACE_SCHEMA_NOT_READY"===u?.code;return t.jsx(Yo,{className:"workspace-announcements-section",title:e,description:a,boundary:n,actions:t.jsx(l,{to:"/dashboard/employee?tab=updates",children:"View all Updates"}),children:t.jsx(bc,{className:"employee-home-inline-request",loading:d&&!c,error:p?null:u,unavailable:p,loadingLabel:"Loading Worksp
2ace Updatesâ¦",emptyLabel:"No Workspace Updates right now.",unavailableLabel:"Workspace Updates are temporarily unavailable.",errorLabel:"Workspace Updates could not be loaded",isEmpty:!d&&!u&&0===m.length,onRetry:h,children:t.jsx("div",{className:"workspace-announcement-list",children:m.map(e=>t.jsx(zc,{update:e,compact:!0,onOpen:e=>r(`/dashboard/employee?tab=updates&updateId=${encodeURIComponent(e)}`)},e.id))})})})}function Hc({profile:e,user:a}){const n=e?[Sc(e.personnelType),e.title,`Status: ${Sc(e.status,"Pending")}`].filter(Boolean).join(" · "):"Profile setup pending";return t.jsxs("div",{className:"employee-home-intro","aria-label":"Workspace identity",children:[t.jsxs("p",{className:"employee-home-greeting",children:["Welcome",a?.name?`, ${a.name}`:""]}),t.jsx("p",{className:"employee-home-context",children:n})]})}const Kc=Object.freeze([{key:"overdue",label:"Overdue tasks",tone:"danger",icon:be,target:{tab:"tasks"}},{key:"blocked",label:"Blocked tasks",tone:"danger",icon:be,target:{tab:"tasks"}},{key:"dueSoon",label:"Projects due soon",tone:"warning",icon:ge,target:{tab:"projects"}},{key:"unreadConversations",label:"Unread conversations",tone:"info",icon:$e,target:{tab:"messages"}}]),Gc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Jc(e){if("string"!=typeof e?.id)return null;const t=e.id.trim();return Gc.test(t)?t.toLowerCase():null}function Yc({taskSummary:n,projectSummary:s,messageSummary:r,notificationSummary:i,tasksAvailable:o,projectsAvailable:c,messagesAvailable:d,notificationsAvailable:u,onOpenNotifications:h}){const m=e.useId(),[p,g]=e.useState(null),f=(Array.isArray(r?.recent)?r.recent.map(e=>({conversation:e,conversationId:Jc(e)})).filter(({conversationId:e})=>Boolean(e)):[]).find(({conversation:e})=>Number(e.unreadCount)>0),b={unreadConversations:f?{tab:"messages",conversationId:f.conversationId}:{tab:"messages"}},x=(e,t)=>{if(!t||null==e||""===e)return null;const a=Number(e);return Number.isFinite(a)?a:null},v={overdue:x(n?.overdue,o),blocked:x(n?.blocked,o),dueSoon:x(s?.dueSoon,c),unreadConversations:x(r?.unreadConversations,d),unreadNotifications:x(i?.unread,u)},j=v.unreadNotifications,y=Number(j)>0,k=[...Kc.filter(({key:e})=>Number(v[e])>0),...y?[{key:"unreadNotifications",label:"Personal notifications",tone:"info",icon:z,isNotification:!0}]:[]],w=k.slice(0,2),N=k.slice(2),S=k.map(({key:e})=>e).join("|"),C=N.length>0&&p===S,R=`Show ${N.length} more ${1===N.length?"signal":"signals"}`,E=Object.values(v).some(e=>null===e),I=1===j?"1 unread notification. Open Notifications in the Workspace header.":`${j} unread notifications. Open Notifications in the Workspace header.`,_=h?{as:"button",type:"button",interactive:!0,"aria-label":`Open notifications, ${j} unread`,onClick:e=>h(e.currentTarget)}:{as:"aside",role:"note","aria-label":"Personal notification summary"},T=({key:e,label:n,tone:s,icon:r,target:i,isNotification:o})=>t.jsx("li",{children:o?t.jsxs(Qo,{..._,boundary:"flat",className:"employee-home-notification-note",children:[t.jsx("span",{className:"employee-home-attention-icon","aria-hidden":"true",children:t.jsx(r,{size:18})}),t.jsxs("span",{className:"employee-home-attention-copy",children:[t.jsxs("span",{className:"employee-home-notification-title",children:[t.jsx("strong",{children:n}),t.jsx(li,{variant:"info",children:j})]}),t.jsx("span",{children:I})]})]}):t.jsxs(Qo,{as:l,to:$r(b[e]||i),interactive:!0,tone:"info"===s?"active":s,boundary:"flat",className:`employee-home-attention-row is-${s}`,children:[t.jsx("span",{className:"employee-home-attention-icon","aria-hidden":"true",children:a.createElement(r,{size:18})}),t.jsx("strong",{className:"employee-home-attention-label",children:n}),t.jsx(li,{variant:"info"===s?"info":s,children:v[e]})]})},e);return t.jsx(Yo,{className:"employee-home-attention",title:"Needs attention",description:"The signals most likely to need a response.",children:k.length?t.jsxs(t.Fragment,{children:[t.jsx("ul",{className:"employee-home-attention-list",children:w.map(T)}),N.length?t.jsxs(t.Fragment,{children:[t.jsx(ec,{variant:"ghost",className:"employee-home-disclosure","aria-expanded":C,"aria-controls":m,onClick:()=>g(C?null:S),children:C?"Show less":R}),t.jsx("ul",{id:m,className:"employee-home-attention-list employee-home-attention-list--additional",hidden:!C,children:N.map(T)})]}):null,E?t.jsx("p",{className:"employee-home-availability-note",role:"status",children:"Some attention signals are temporarily unavailable."}):null]}):E?t.jsxs("p",{className:"employee-home-attention-state is-unavailable",role:"status",children:[t.jsx(be,{size:18,"aria-hidden":"true"}),"Attention signals are temporarily unavailable."]}):t.jsxs("p",{className:"employee-home-attention-state is-caught-up",children:[t.jsx(pe,{size:18,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:"Youâre caught up."})," No current work signals need your attention."]})]})})}function Qc({task:e}){const a=Ko(e?.dueDate),n=function(e){return"overdue"===Ko(e?.dueDate).key?"danger":e?.isBlocked?"warning":"neutral"}(e),s=e?.isBlocked?"Blocked":Sc(e?.column?.name,"Assigned");return t.jsxs(Qo,{as:l,to:$r({tab:"tasks",taskId:e.id,projectId:e.project?.id||e.projectId}),interactive:!0,tone:n,boundary:"flat",className:`employee-home-work-row employee-home-task-row is-${n}`,children:[t.jsxs("span",{className:"employee-home-row-copy",children:[t.jsx("h3",{children:e.title||"Untitled task"}),t.jsx("span",{className:"ws-meta",children:e.project?.name||"Project not specified"})]}),t.jsxs("span",{className:"employee-home-row-meta",children:[t.jsx(li,{variant:e?.isBlocked?"warning":"overdue"===a.key?"danger":"default",children:"overdue"===a.key?"Overdue":s}),e?.dueDate?t.jsx(nc,{value:e.dueDate}):null]})]})}function Xc({project:e}){return t.jsxs(Qo,{as:l,to:$r({tab:"projects",projectId:e.id}),interactive:!0,boundary:"flat",className:"employee-home-work-row employee-home-project-row",children:[t.jsxs("span",{className:"employee-home-row-copy",children:[t.jsx("strong",{children:e.name||"Untitled project"}),t.jsx("span",{className:"ws-meta",children:Sc(e.status,"Project")})]}),e.dueDate?t.jsx(nc,{value:e.dueDate}):null]})}function Zc({title:e,destination:a,label:n}){return t.jsxs("div",{className:"employee-home-work-group-header",children:[t.jsx("h3",{children:e}),t.jsx(ec,{as:l,to:a,variant:"ghost",size:"compact",children:n})]})}function ed({taskSummary:e,projectSummary:a,tasksAvailable:n,projectsAvailable:s}){const r=(e?.recent||[]).slice(0,2),i=(a?.recent||[]).slice(0,1),l=n&&s&&0===r.length&&0===i.length;return t.jsx(Yo,{className:"employee-home-work",title:"My work",description:"Resume assigned tasks and active project work.",children:l?t.jsx("p",{className:"employee-home-inline-state",children:"No assigned work to resume."}):t.jsxs("div",{className:"employee-home-work-groups",children:[t.jsxs("div",{className:"employee-home-work-group",children:[t.jsx(Zc,{title:"Tasks",destination:$r({tab:"tasks"}),label:"All tasks"}),n?r.length?t.jsx("ul",{className:"employee-home-task-list",children:r.map(e=>t.jsx("li",{children:t.jsx(Qc,{task:e})},e.id))}):t.jsx("p",{className:"employee-home-inline-state",children:"No assigned tasks to resume."}):t.jsx("p",{className:"employee-home-inline-state",role:"status",children:"Assigned tasks are temporarily unavailable."})]}),t.jsxs("div",{className:"employee-home-work-group employee-home-projects-group",children:[t.jsx(Zc,{title:"Active projects",destination:$r({tab:"projects"}),label:"All projects"}),s?i.length?t.jsx("ul",{className:"employee-home-project-list",children:i.map(e=>t.jsx("li",{children:t.jsx(Xc,{project:e})},e.id))}):t.jsx("p",{className:"employee-home-inline-state",children:"No active projects to preview."}):t.jsx("p",{className:"employee-home-inline-state",role:"status",children:"Projects are temporarily unavailable."})]})]})})}function td({user:e,availability:n,onboarding:s}){const r=e?.roles?.some(e=>["admin","cofounder"].includes(e)),i=s?.activeAssignment?null:(s?.assignments||[]).find(e=>"completed"===e.status),o=[i?{label:"Onboarding materials",icon:_,to:$r({tab:"onboarding",assignmentId:i.id})}:null,fc(n,"messages")?{label:"Messages",icon:D,to:$r({tab:"messages"})}:null,{label:"Teams",icon:L,to:$r({tab:"teams"})},fc(n,"resources")?{label:"Resources",icon:M,to:$r({tab:"resources"})}:null,r?{label:"Admin",icon:w,to:"/admin"}
2:null].filter(Boolean);return t.jsx(Yo,{className:"employee-home-context-links",title:"Workspace destinations",children:t.jsx("nav",{"aria-label":"Workspace destinations",children:t.jsx("ul",{children:o.map(({label:e,icon:n,to:s})=>t.jsx("li",{children:t.jsxs(Qo,{as:l,to:s,interactive:!0,boundary:"flat",className:"employee-home-context-link",children:[a.createElement(n,{size:17,"aria-hidden":!0}),t.jsx("strong",{children:e})]})},e))})})})}function ad({summary:e,user:a,onNavigateActivity:n,onOpenNotifications:s,onboarding:r}){const i=e?.profile,l=e?.projectSummary||{},o=e?.taskSummary||{},c=e?.messageSummary||{},d=e?.availability||null,u=fc(d,"projects"),h=fc(d,"tasks"),m=fc(d,"messages"),p=fc(d,"notifications"),g=n;return t.jsxs("div",{className:"employee-home employee-home--mine",children:[t.jsx(Hc,{profile:i,user:a}),t.jsx(Vc,{boundary:"record",previewLimit:1}),t.jsx(Yc,{taskSummary:o,projectSummary:l,messageSummary:c,notificationSummary:e?.notificationSummary,tasksAvailable:h,projectsAvailable:u,messagesAvailable:m,notificationsAvailable:p,onOpenNotifications:s}),t.jsx(jc,{onboarding:r,onNavigate:g}),t.jsx(ed,{taskSummary:o,projectSummary:l,tasksAvailable:h,projectsAvailable:u}),t.jsx(xc,{endpoint:"/api/workspace/v1/activity?scope=mine",limit:5,initialVisibleCount:2,useLinks:!0}),t.jsx(td,{user:a,availability:d,onboarding:r})]})}const nd=[{value:"",label:"All events"},{value:"task_created",label:"Task created"},{value:"task_moved",label:"Task moved"},{value:"task_updated",label:"Task updated"},{value:"team_memberships_replaced",label:"Team membership changed"},{value:"team_projects_replaced",label:"Team projects changed"},{value:"team_resources_replaced",label:"Team resources changed"},{value:"workspace_project_updated",label:"Project updated"},{value:"workspace_resource_updated",label:"Resource updated"}],sd=[{value:"name-asc",label:"Name AâZ",sort:"name",direction:"asc"},{value:"overdueTasks-desc",label:"Most overdue tasks",sort:"overdueTasks",direction:"desc"},{value:"blockedTasks-desc",label:"Most blocked tasks",sort:"blockedTasks",direction:"desc"},{value:"openTasks-desc",label:"Most open tasks",sort:"openTasks",direction:"desc"}],rd=Object.freeze({search:"",personnelType:"",department:"",order:"name-asc"}),id=Object.freeze({eventType:"",dateFrom:"",dateTo:""});function ld(e,t=!0){if(!t||null==e||""===e)return null;const a=Number(e);return Number.isFinite(a)?a:null}function od(e,t,a=!0){const n=e?.[t];return void 0===n?a:n&&"object"==typeof n?!1!==n.available:Boolean(n)}function cd(e){return $r({...e,scope:"all"})}function dd({overview:e,availability:a,stale:n=!1}){const s=od(a,"tasks"),r=od(a,"projects"),i=od(a,"onboarding",Boolean(e.onboarding)),o=[{key:"tasks",label:"Tasks",items:[{key:"blocked-tasks",label:"Blocked tasks",description:"Open work currently waiting on a blocker.",action:"Open Tasks",count:ld(e.tasks?.blocked,s),tone:"danger",target:{tab:"tasks"}},{key:"overdue-tasks",label:"Overdue tasks",description:"Open work past its due date.",action:"Open Tasks",count:ld(e.tasks?.overdue,s),tone:"danger",target:{tab:"tasks"}},{key:"unassigned-tasks",label:"Unassigned tasks",description:"Tasks without a current assignee.",action:"Open Tasks",count:ld(e.tasks?.unassigned,s),tone:"warning",target:{tab:"tasks"}}]},{key:"projects",label:"Projects",items:[{key:"overdue-projects",label:"Overdue projects",description:"Active projects past their due date.",action:"Open Projects",count:ld(e.projects?.overdue,r),tone:"danger",target:{tab:"projects"}}]},{key:"onboarding",label:"Onboarding",items:[{key:"onboarding-incomplete",label:"Onboarding incomplete",description:"Assignments that have not been completed.",action:"Review incomplete onboarding",count:ld(e.onboarding?.incomplete,i),tone:"warning",target:{tab:"people",peopleMode:"onboarding"}},{key:"onboarding-awaiting-quiz",label:"Awaiting quiz",description:"Assignments ready for the onboarding quiz.",action:"Review onboarding awaiting quiz",count:ld(e.onboarding?.awaitingQuiz,i),tone:"warning",target:{tab:"people",peopleMode:"onboarding",onboardingStatus:"awaiting_quiz"}}
2,{key:"onboarding-retake",label:"Retake required",description:"Assignments that require another quiz attempt.",action:"Review onboarding retakes",count:ld(e.onboarding?.retakeRequired,i),tone:"danger",target:{tab:"people",peopleMode:"onboarding",onboardingStatus:"retake_required"}}]}],c=o.map(e=>({...e,items:e.items.filter(e=>Number(e.count)>0)})).filter(e=>e.items.length),d=o.some(e=>e.items.some(e=>null===e.count)),u=o.filter(e=>e.items.every(e=>null!==e.count)).length;return t.jsxs(Yo,{className:"employee-workspace-attention",title:"Workspace attention",description:"Exceptions across tasks, projects, and onboarding.",children:[n?t.jsxs("p",{className:"employee-workspace-stale-marker",children:[t.jsx(be,{size:15,"aria-hidden":"true"})," Previously loaded data"]}):null,c.length?t.jsx("div",{className:"employee-workspace-attention-groups",children:c.map(e=>t.jsxs("section",{"aria-labelledby":`workspace-attention-${e.key}`,children:[t.jsx("h3",{id:`workspace-attention-${e.key}`,children:e.label}),t.jsx("ul",{children:e.items.map(e=>t.jsx("li",{children:t.jsxs(Qo,{as:l,to:cd(e.target),interactive:!0,boundary:"flat",tone:e.tone,className:`employee-workspace-attention-row is-${e.tone}`,children:[t.jsxs("span",{className:"employee-workspace-attention-copy",children:[t.jsx("strong",{children:e.label}),t.jsx("span",{children:e.description})]}),t.jsx("span",{className:"employee-workspace-attention-action",children:e.action}),t.jsxs("strong",{className:"employee-workspace-count",children:[e.count,t.jsxs("span",{className:"sr-only",children:[" ",e.label]})]})]})},e.key))})]},e.key))}):d?t.jsxs("p",{className:"employee-home-attention-state is-unavailable",role:"status",children:[t.jsx(be,{size:18,"aria-hidden":"true"}),0===u?"Workspace exception signals are temporarily unavailable.":"Some workspace exception signals are temporarily unavailable."]}):t.jsxs("p",{className:"employee-home-attention-state is-caught-up",children:[t.jsx(pe,{size:18,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:"No current workspace exceptions."})," Operational signals are quiet right now."]})]}),c.length&&d?t.jsx("p",{className:"employee-home-availability-note",role:"status",children:"Some workspace exception signals are temporarily unavailable."}):null]})}function ud({overview:e,availability:a,stale:n=!1}){const s=od(a,"projects"),r=od(a,"onboarding",Boolean(e.onboarding)),i=[{key:"people",label:"Active personnel",value:ld(e.personnel?.active),action:"Open People",target:{tab:"people"}},{key:"teams",label:"Active teams",value:ld(e.teams?.active),action:"Open Teams",target:{tab:"teams"}},{key:"projects",label:"Active projects",value:ld(e.projects?.active,s),action:"Open Projects",target:{tab:"projects"}},{key:"resources",label:"Ready resources",value:ld(e.resources?.ready),action:"Open Resources",target:{tab:"resources"}},{key:"onboarding-completed",label:"Onboarding completed this week",value:ld(e.onboarding?.completedThisWeek,r),action:"Review completed onboarding",target:{tab:"people",peopleMode:"onboarding",onboardingStatus:"completed"}}],o=i.filter(e=>Number(e.value)>0),c=i.some(e=>null===e.value);return t.jsxs(Yo,{className:"employee-workspace-snapshot",title:"Workspace snapshot",description:"Active people, teams, projects, resources, and recent onboarding.",children:[n?t.jsxs("p",{className:"employee-workspace-stale-marker",children:[t.jsx(be,{size:15,"aria-hidden":"true"})," Previously loaded data"]}):null,o.length?t.jsx("dl",{className:"employee-workspace-snapshot-list",children:o.map(e=>t.jsxs("div",{children:[t.jsx("dt",{children:e.label}),t.jsxs("dd",{children:[t.jsx("strong",{children:e.value}),t.jsx(l,{to:cd(e.target),children:e.action})]})]},e.key))}):c?t.jsx("p",{className:"employee-home-inline-state",role:"status",children:"Workspace context is temporarily unavailable."}):t.jsx("p",{className:"employee-home-inline-state",children:"No active workspace context to summarize."}),o.length&&c?t.jsx("p",{className:"employee-home-availability-note",role:"status",children:"Some workspace context is temporarily unavailable."}):null]})}function hd({workload:a,availability:n,capabilities:s,draftFilters:r,appliedFilters:i,onDraftChange:o,onApply:c,onClear:d,loading:u,error:h,onRetry:m}){const[p,g]=e.useState(!1),f=e.useId(),b=od(n,"projects")&&od(n,"tasks"),x=Object.entries(i).filter(([e,t])=>t!==rd[e]).length,v=x>0,j=Math.max(a.length-3,0);return e.useEffect(()=>{g(!1)}
2,[i]),t.jsxs(Yo,{className:"employee-workspace-workload",title:"Workload signals",description:"A short people preview for coordinating active assignments.",actions:t.jsx(ec,{as:l,to:cd({tab:"people"}),variant:"ghost",size:"compact",children:"Open People directory"}),children:[t.jsx(sc,{label:"Workload filters",mobileCollapsible:!0,activeFilterCount:x,resultLabel:b?`${a.length} ${1===a.length?"person":"people"} in this Home preview`:null,onClear:d,className:"employee-workspace-workload-filters",children:t.jsxs("form",{className:"employee-workspace-workload-filter-form",onSubmit:c,children:[t.jsxs("label",{children:[t.jsx("span",{children:"Search"}),t.jsx("input",{type:"search",value:r.search,onChange:e=>o("search",e.target.value),placeholder:"Name or title"})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Department"}),t.jsx("input",{value:r.department,onChange:e=>o("department",e.target.value),placeholder:"Full department name"})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Personnel type"}),t.jsx("select",{value:r.personnelType,onChange:e=>o("personnelType",e.target.value),children:["","employee","intern","student","researcher","contractor"].map(e=>t.jsx("option",{value:e,children:e?Sc(e):"All types"},e))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Order"}),t.jsx("select",{value:r.order,onChange:e=>o("order",e.target.value),children:sd.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))})]}),t.jsx(ec,{type:"submit",variant:"secondary",disabled:u,children:u?"Updating workloadâ¦":"Apply filters"})]})}),t.jsxs(bc,{loading:u,error:h,loadingLabel:"Updating workspace workloadâ¦",unavailable:!b,unavailableLabel:"Workload signals are temporarily unavailable",unavailableDescription:"Project and task data must both be available for this coordination preview.",permissionLimited:!1===s?.canViewWorkspaceWorkload,errorLabel:"Workspace workload could not be updated",isEmpty:!u&&!h&&b&&0===a.length,emptyType:v?"no-results":"empty",emptyLabel:v?"No people match these filters.":"No people in this preview.",emptyDescription:v?"Change or clear the applied filters to try again.":null,onRetry:m,children:[t.jsx("ol",{id:f,className:"employee-workspace-workload-list"+(p?" is-mobile-expanded":""),children:a.map(e=>{const a=e.name||"Unnamed person",n=[{key:"overdue",label:"overdue",value:ld(e.overdueTasks),tone:"danger"},{key:"blocked",label:"blocked",value:ld(e.blockedTasks),tone:"danger"},{key:"due-soon",label:"due soon",value:ld(e.dueSoon),tone:"warning"}],s=n.filter(e=>Number(e.value)>0),r=n.some(e=>null===e.value);return t.jsx("li",{children:t.jsxs(Qo,{boundary:"flat",className:"employee-workspace-workload-row",children:[t.jsxs("span",{className:"employee-workspace-person-copy",children:[t.jsx("strong",{children:a}),t.jsxs("span",{children:[Sc(e.personnelType,"Internal")," ·"," ",e.department||"No department"]})]}),s.length?t.jsxs("div",{className:"employee-workspace-workload-exception-summary",children:[t.jsx("ul",{className:"employee-workspace-workload-exceptions","aria-label":`Exceptions for ${a}`,children:s.map(e=>t.jsxs("li",{className:`is-${e.tone}`,children:[t.jsx("strong",{children:e.value})," ",e.label]},e.key))}),r?t.jsx("span",{className:"employee-workspace-workload-partial",role:"status",children:"Some exception counts unavailable"}):null]}):r?t.jsx("span",{className:"employee-workspace-workload-quiet",children:"Exception counts unavailable"}):t.jsx("span",{className:"employee-workspace-workload-quiet",children:"No current exceptions"}),t.jsxs("span",{className:"employee-workspace-workload-context",children:[ld(e.openTasks)??"Unavailable"," open tasks ·"," ",ld(e.projectCount)??"Unavailable"," projects ·"," ",ld(e.teamCount)??"Unavailable"," teams"]}),t.jsx(ec,{as:l,to:cd({tab:"people",personId:e.id}),variant:"ghost",size:"compact","aria-label":`View ${a} in People`,children:"View in People"})]})},e.id)})}),j?t.jsx(ec,{variant:"ghost",className:"employee-workspace-mobile-preview-toggle","aria-expanded":p,"aria-controls":f,onClick:()=>g(e=>!e),children:p?"Show fewer people":`Show ${j} more ${1===j?"person":"people"}`}):null]})]})}function md(){const[a,n]=e.useState(null),[s,r]=e.useState(rd),[i,l]=e.useState(rd),[o,c]=e.useState(id),[d,u]=e.useState(!1),h=e.useId(),m=e.useMemo(()=>{const e=new URLSearchParams({scope:"all",limit:"6"});return Object.entries(function(e){const t=sd.find(t=>t.value===e.order)||sd[0];return{search:e.search.trim(),personnelType:e.personnelType,department:e.department.trim(),sort:t.sort,direction:t.direction}}
2(i)).forEach(([t,a])=>{a&&e.set(t,a)}),`/api/workspace/v1/home?${e.toString()}`},[i]),p=e.useMemo(()=>{const e=new URLSearchParams({scope:"all",limit:"8"});return Object.entries(o).forEach(([t,a])=>{a&&e.set(t,a)}),`/api/workspace/v1/activity?${e.toString()}`},[o]),{data:g,loading:f,error:b,refresh:x}=kc(m),{data:v,loading:j,error:y,refresh:k}=kc(p);e.useEffect(()=>{g?.overview&&n(g)},[g]);const w=g?.overview?g:a,N=w?.overview,S=w?.workload||[],C=v?.activity||[],R=Object.values(o).filter(Boolean).length,E=Math.max(C.length-3,0),I=!g?.overview&&Boolean(a?.overview);e.useEffect(()=>{u(!1)},[p]);return t.jsxs("div",{className:"employee-home employee-workspace-overview",children:[N?t.jsxs(t.Fragment,{children:[I?t.jsxs("div",{className:"employee-workspace-retained-status"+(b?" is-error":""),role:b?"alert":"status",children:[t.jsx(be,{size:18,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:b?"Showing previously loaded workspace data.":"Refreshing workspace data."})," ",b?"The latest refresh failed.":"Previously loaded attention and snapshot remain visible."]}),b?t.jsx(ec,{variant:"secondary",size:"compact",onClick:x,children:"Retry workspace refresh"}):null]}):null,t.jsx(dd,{overview:N,availability:w?.availability,stale:I}),t.jsxs("div",{className:"employee-workspace-home-primary-grid",children:[t.jsx(hd,{workload:S,availability:w?.availability,capabilities:w?.capabilities,draftFilters:s,appliedFilters:i,onDraftChange:(e,t)=>
2r(a=>({...a,[e]:t})),onApply:e=>{e.preventDefault(),l({...s})},onClear:()=>{r(rd),l(rd)},loading:f,error:b,onRetry:x}),t.jsx(ud,{overview:N,availability:w?.availability,stale:I})]})]}):t.jsx(Yo,{className:"employee-workspace-operational-state",title:"Workspace operations",description:"Organization-wide attention, workload, and operating context.",children:t.jsx(bc,{className:"employee-workspace-home-request",loading:f&&!g,error:b,unavailable:!f&&!b,loadingLabel:"Loading workspace operationsâ¦",unavailableLabel:"Workspace operations are temporarily unavailable",errorLabel:"Workspace operations could not be loaded",onRetry:x})}),t.jsx(Vc,{title:"Updates for you",description:"Audience-filtered announcements and project news relevant to you."}),t.jsxs(Yo,{className:"employee-workspace-activity",title:"Recent workspace activity",description:"Operational events only; private conversation activity is excluded.",actions:t.jsx(ec,{variant:"ghost",size:"compact",onClick:k,disabled:j,children:j?"Refreshing activityâ¦":"Refresh activity"}),children:[t.jsxs(sc,{label:"Workspace activity filters",className:"employee-workspace-activity-filters",mobileCollapsible:!0,activeFilterCount:R,onClear:()=>c(id),children:[t.jsxs("label",{children:[t.jsx("span",{children:"Event"}),t.jsx("select",{value:o.eventType,onChange:e=>c(t=>({...t,eventType:e.target.value})),children:nd.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"From"}),t.jsx("input",{type:"date",value:o.dateFrom,max:o.dateTo||void 0,onChange:e=>c(t=>({...t,dateFrom:e.target.value}))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"To"}),t.jsx("input",{type:"date",value:o.dateTo,min:o.dateFrom||void 0,onChange:e=>c(t=>({...t,dateTo:e.target.value}))})]})]}),t.jsx(bc,{className:"employee-home-inline-request",loading:j&&!v,error:y,isEmpty:!j&&!y&&0===C.length,loadingLabel:"Loading workspace activityâ¦",errorLabel:"Workspace activity could not be loaded",emptyType:R?"no-results":"empty",emptyLabel:R?"No workspace activity matches these filters.":"No recent workspace activity.",emptyDescription:R?"Change or clear the activity filters to try again.":null,onRetry:k,children:t.jsxs(t.Fragment,{children:[t.jsx("ol",{id:h,className:"employee-workspace-activity-list"+(d?" is-mobile-expanded":""),children:C.map(e=>t.jsx("li",{children:t.jsx(mc,{item:e,useLink:!0,linkScope:"all"})},e.id))}),E?t.jsx(ec,{variant:"ghost",className:"employee-workspace-mobile-preview-toggle","aria-expanded":d,"aria-controls":h,onClick:()=>u(e=>!e),children:d?"Show fewer activity items":`Show ${E} more activity ${1===E?"item":"items"}`}):null]})})]})]})}const pd=["employee","intern","student","researcher","contractor"],gd=["invited","onboarding","active","paused","offboarded"];function fd(e){return{personnelType:e?.personnelType||"intern",status:e?.status||"active",title:e?.title||"",department:e?.department||"",timezone:e?.timezone||"",startDate:e?.startDate?String(e.startDate).slice(0,10):"",endDate:e?.endDate?String(e.endDate).slice(0,10):"",managerUserId:e?.manager?.id||"",mentorUserId:e?.mentor?.id||"",introduction:e?.introduction||e?.summary||"",linkedinUrl:e?.linkedinUrl||"",skills:(e?.skills||[]).join(", "),removeAvatar:!1}}function bd(e,t){return{personnelType:e.personnelType,status:e.status,title:e.title,department:e.department,timezone:e.timezone,startDate:e.startDate||null,endDate:e.endDate||null,managerUserId:e.managerUserId||null,mentorUserId:e.mentorUserId||null,introduction:e.introduction,linkedinUrl:e.linkedinUrl,skills:e.skills.split(",").map(e=>e.trim()).filter(Boolean),removeAvatar:Boolean(e.removeAvatar),expectedVersion:t}}function xd({person:e,people:n=[],onCancel:s,onSaved:r}){const{makeAuthRequest:i}=Yn(),[l,o]=a.useState(()=>fd(e)),[c,d]=a.useState(""),[u,h]=a.useState(""),[m,p]=a.useState(""),[f,b]=a.useState(null);a.useEffect(()=>{o(fd(e)),h(""),p(""),b(null)},[e]);const x=(e,t)=>{o(a=>({...a,[e]:t})),p("")},v=a.useMemo(()=>{const t=[e?.manager,e?.mentor].filter(Boolean);return function(e){const t=new Set;return e.filter(e=>!(!e?.id||t.has(e.id)||(t.add(e.id),0)))}([...n,...t]).filter(t=>
2t.id!==e?.id&&!1!==t.hasProfile&&"offboarded"!==t.status)},[n,e?.id,e?.manager,e?.mentor]),j=Boolean(c);return t.jsxs("form",{className:"employee-admin-profile-editor","aria-label":`Edit personnel profile for ${e?.name||"selected person"}`,onSubmit:async t=>{if(t.preventDefault(),e?.id&&!c){d("save"),h(""),p(""),b(null);try{const t=await i(`/api/workspace/v1/people/${e.id}?scope=all`,{method:"PATCH",body:JSON.stringify(bd(l,e.profileVersion))});o(fd(t.data.person)),p("Personnel profile saved."),r?.(t.data.person)}catch(a){b(a?.data?.error?.details?.currentPerson||null),h(function(e){return"PROFILE_VERSION_CONFLICT"===e?.data?.error?.code?"This profile changed in another session. Reload the latest version before saving.":e?.safeMessage||e?.data?.error?.message||e?.message||"Unable to save."}(a))}finally{d("")}}},noValidate:!0,children:[u?t.jsxs("div",{className:"employee-admin-profile-editor__feedback",children:[t.jsx(oc,{type:"error",children:u}),f?t.jsxs(ec,{type:"button",variant:"secondary",size:"compact",onClick:()=>{f&&r?.(f,{keepEditing:!0})},children:[t.jsx(Me,{size:15,"aria-hidden":"true"})," Reload latest"]}):null]}):null,m?t.jsx(oc,{type:"success",children:m}):null,t.jsxs(ic,{legend:"Operational profile",children:[t.jsx(rc,{label:"Personnel type",children:t.jsx("select",{value:l.personnelType,onChange:e=>x("personnelType",e.target.value),disabled:j,children:pd.map(e=>t.jsx("option",{value:e,children:Sc(e)},e))})}),t.jsx(rc,{label:"Workspace status",children:t.jsx("select",{value:l.status,onChange:e=>x("status",e.target.value),disabled:j,children:gd.map(e=>t.jsx("option",{value:e,children:Sc(e)},e))})}),t.jsx(rc,{label:"Title",children:t.jsx("input",{value:l.title,onChange:e=>x("title",e.target.value),disabled:j})}),t.jsx(rc,{label:"Department",children:t.jsx("input",{value:l.department,onChange:e=>x("department",e.target.value),disabled:j})}),t.jsx(rc,{label:"Timezone",children:t.jsx("input",{value:l.timezone,onChange:e=>x("timezone",e.target.value),disabled:j})}),t.jsx(rc,{label:"Start date",children:t.jsx("input",{type:"date",value:l.startDate,onChange:e=>x("startDate",e.target.value),disabled:j})}),t.jsx(rc,{label:"End date",children:t.jsx("input",{type:"date",value:l.endDate,onChange:e=>x("endDate",e.target.value),disabled:j})})]}),t.jsxs(ic,{legend:"Profile details",children:[t.jsx(rc,{label:"Manager",children:t.jsxs("select",{value:l.managerUserId,onChange:e=>x("managerUserId",e.target.value),disabled:j,children:[t.jsx("option",{value:"",children:"No manager"}),v.map(e=>t.jsx("option",{value:e.id,children:e.name||"Unnamed"},e.id))]})}),t.jsx(rc,{label:"Mentor",children:t.jsxs("select",{value:l.mentorUserId,onChange:e=>x("mentorUserId",e.target.value),disabled:j,children:[t.jsx("option",{value:"",children:"No mentor"}),v.map(e=>t.jsx("option",{value:e.id,children:e.name||"Unnamed"},e.id))]})}),t.jsx(rc,{label:"Introduction",className:"employee-admin-profile-editor__wide",children:t.jsx("textarea",{rows:5,value:l.introduction,onChange:e=>x("introduction",e.target.value),disabled:j})}),t.jsx(rc,{label:"LinkedIn profile",className:"employee-admin-profile-editor__wide",children:t.jsx("input",{type:"url",value:l.linkedinUrl,onChange:e=>x("linkedinUrl",e.target.value),placeholder:"https://www.linkedin.com/in/profile",disabled:j})}),t.jsx(rc,{label:"Skills",help:"Separate skills with commas.",className:"employee-admin-profile-editor__wide",children:t.jsx("input",{value:l.skills,onChange:e=>x("skills",e.target.value),disabled:j})}),e?.avatarUrl?t.jsxs("label",{className:"employee-admin-profile-editor__checkbox employee-admin-profile-editor__wide",children:[t.jsx("input",{type:"checkbox",checked:l.removeAvatar,onChange:e=>x("removeAvatar",e.target.checked),disabled:j}),"Remove the current avatar when saving"]}):null]}),t.jsxs(lc,{className:"employee-admin-profile-editor__actions",children:[t.jsxs(ec,{type:"submit",variant:"primary",disabled:j,children:[t.jsx(ne,{size:16,"aria-hidden":"true"}),"save"===c?"Saving...":"Save personnel profile"]}),t.jsxs(ec,{type:"button",variant:"secondary",disabled:j,onClick:s,children:[t.jsx(g,{size:16,"aria-hidden":"true"})," Cancel"]})]})]})}const vd=/(https?:\/\/[^\s<>"']+|www\.[^\s<>"']+)/gi,jd=/[.,!?;:)\]]+$/;function yd(e){const t=e.match(jd);return t?{urlText:e.slice(0,-t[0].length),trailing:t[0]}:{urlText:e,trailing:""}}function kd(e){return e.startsWith("www.")?`https://${e}`:e.startsWith("http://")||e.startsWith("https://")?e:null}function wd({text:e,className:a=""}){if(!e)return null;const n=String(e),s=[];let r=0;for(const i of n.matchAll(vd)){const e=i[0],a=i.index||0;a>r&&s.push(n.slice(r,a));const{urlText:l,trailing:o}=yd(e),c=kd(l);c?(s.push(t.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",children:l},`link-${a}`)),o&&s.push(o)):s.push(e),r=a+e.length}return r<n.length&&s.push(n.slice(r)),t.jsx("span",{className:`linkified-text ${a}`.trim(),children:s})}function Nd({title:e,children:a}){return t.jsxs("section",{className:"employee-person-detail__section",children:[t.jsx("h3",{children:e}),a]})}function Sd({person:a,expanded:n,onToggle:s,isOwn:r=!1,onEdit:i,onAdminEdit:l,adminEditing:o=!1,adminEditor:c=null,showOperationalStatus:d=!1}){const[h,m]=e.useState(!1),[p,g]=e.useState(!1),f=n??h,b=!1===a.hasProfile,x=a.name||"Unnamed",v=a.avatarUrl||a.pictureUrl,j=[a.title,a.department].filter(
2Boolean).join(" · ")||(b?"Personnel profile pending":Sc(a.personnelType)),y=(a.skills||[]).slice(0,3),k=Math.max((a.skills||[]).length-y.length,0),w=b||d||"active"!==a.status,N=r&&a.capabilities?.canEditOwnPersonnelProfile,S=!r&&!1!==a.hasProfile&&a.capabilities?.canEditPersonnelProfile&&l,C=a.status&&"active"!==a.status?a.status:"neutral";return t.jsxs(Qo,{className:"employee-person-card",tone:C,boundary:"divided","data-expanded":f||void 0,children:[t.jsxs("div",{className:"employee-person-summary",children:[t.jsxs("div",{className:"employee-person-identity",children:[v&&!p?t.jsx("img",{className:"employee-person-avatar",src:v,alt:"",loading:"lazy",onError:()=>g(!0)}):t.jsx("span",{className:"employee-person-avatar employee-person-avatar--initials","aria-hidden":"true",children:(R=x,(R||"Unnamed").split(/\s+/).slice(0,2).map(e=>e[0]).join("").toUpperCase())}),t.jsxs("span",{className:"employee-person-primary",children:[t.jsxs("span",{className:"employee-person-name-row",children:[t.jsx("strong",{className:"ws-record-title",title:a.name||void 0,children:x}),r?t.jsx("small",{className:"employee-person-you",children:"You"}):null]}),t.jsx("small",{className:"ws-meta",title:j,children:j})]}),w?t.jsx(tc,{value:a.status,label:b?"Profile pending":null}):null]}),t.jsxs("div",{className:"employee-person-context ws-meta",children:[t.jsx("span",{children:a.teams?.[0]?.name||"No team listed"}),t.jsx("span",{children:Sc(a.personnelType)})]}),t.jsx("div",{className:"employee-person-skill-preview","aria-label":"Highlighted skills",children:y.length?t.jsxs(t.Fragment,{children:[y.map(e=>t.jsx("span",{children:e},e)),k?t.jsxs("small",{children:["+",k]}):null]}):t.jsx("small",{children:"No skills listed"})}),t.jsxs(ec,{className:"employee-person-disclosure",variant:"ghost",onClick:()=>{const e=!f;m(e),s?.(e)},"aria-expanded":f,"aria-label":`${f?"Hide":"View"} profile for ${x}`,children:[f?"Hide profile":"View profile",t.jsx(u,{size:16,"aria-hidden":"true"})]})]}),f?t.jsxs(Xo,{boundary:"divided",className:"employee-person-detail",children:[t.jsxs("div",{className:"employee-person-detail__header",children:[t.jsx("p",{children:"Profile details"}),t.jsxs("div",{className:"employee-person-detail__actions",children:[N?t.jsxs(ec,{variant:"secondary",size:"compact",onClick:i,children:[t.jsx(ee,{size:15,"aria-hidden":"true"})," Edit profile"]}):null,S&&!o?t.jsxs(ec,{variant:"secondary",size:"compact",onClick:l,children:[t.jsx(ee,{size:15,"aria-hidden":"true"})," Edit personnel profile"]}):null]})]}),o?c:t.jsxs("div",{className:"employee-person-detail__grid",children:[t.jsx(Nd,{title:"About",children:a.introduction?t.jsx(wd,{text:a.introduction}):t.jsx("p",{className:"ws-meta",children:"No introduction added yet."})}),t.jsx(Nd,{title:"Skills",children:a.skills?.length?t.jsx("ul",{className:"employee-person-detail__skills",children:a.skills.map(e=>t.jsx("li",{children:e},e))}):t.jsx("p",{className:"ws-meta",children:"No skills listed."})}),t.jsx(Nd,{title:"Teams",children:t.jsx("p",{children:a.teams?.map(e=>e.name).join(", ")||"No teams listed."})}),t.jsx(Nd,{title:"Reporting & mentorship",children:t.jsxs("dl",{className:"employee-person-detail__relationships",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Manager"}),t.jsx("dd",{children:a.manager?.name||"Not assigned"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Mentor"}),t.jsx("dd",{children:a.mentor?.name||"Not assigned"})]})]})}),a.linkedinUrl?t.jsx(Nd,{title:"Links",children:t.jsxs("a",{href:a.linkedinUrl,target:"_blank",rel:"noopener noreferrer","aria-label":"LinkedIn profile (opens in a new tab)",children:["LinkedIn profile ",t.jsx(Ue,{size:14,"aria-hidden":"true"})]})}):null]})]}):null]});var R}const Cd=["","not_assigned","not_started","in_progress","awaiting_quiz","retake_required","completed","waived"],Rd=["","intern","staff","employee","admin","cofounder"],Ed=new Set(["assigned","in_progress","awaiting_quiz"]);function Id(e){const t=new Uint8Array(e);return globalThis.crypto?.getRandomValues?globalThis.crypto.getRandomValues(t):t.map(()=>Number.parseInt(Math.floor(256*Math.random()).toString(16).padStart(2,"0"),16))}function _d(){if(globalThis.crypto?.randomUUID)return`admin:${globalThis.crypto.randomUUID()}`;const e=Id(16);e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`admin:${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Td(e){return null==e?"â":Number(e)/100+"%"}function Ad({assignment:e,capabilities:a,onAction:n,submitting:s}){const r=Ed.has(e.status);return t.jsxs(Qo,{className:"onboarding-oversight-assignment",children:[t.jsx("div",{className:"employee-card-heading",children:t.jsxs("div",{children:[t.jsxs("h3",{children:[e.program.name," v",e.program.version]}),t.jsxs("p",{children:[Sc(e.status)," · assigned"," ",wc(e.assignedAt,"Unknown")]})]})}),t.jsxs("dl",{className:"onboarding-oversight-summary",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Started"}),t.jsx("dd",{children:wc(e.startedAt,"Not started")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Completed"}),t.jsx("dd",{children:wc(e.completedAt,"Not completed")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Attempts"}),t.jsx("dd",{children:e.attemptSummary.attemptCount})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Latest score"}),t.jsx("dd",{children:Td(e.attemptSummary.latestScoreBasisPoints)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Best score"}),t.jsx("dd",{children:Td(e.attemptSummary.bestScoreBasisPoints)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Passed"}),t.jsx("dd",{children:e.attemptSummary.passed?"Yes":"No"})]})]}),t.jsx("div",{className:"onboarding-oversight-modules",children:e.modules.map(i=>t.jsxs("section",{"aria-labelledby":`oversight-module-${i.id}`,children:[t.jsxs("h4",{id:`oversight-module-${i.id}`,children:[i.position,". ",i.title," â ",Sc(i.status)]}),t.jsx("ul",{children:i.items.map(i=>
2t.jsxs("li",{children:[t.jsxs("span",{children:["READ"===i.type&&i.required?"Required reading â ":"",i.title," â ",Sc(i.status),"TRY_IT"===i.type?" · TRY_IT · self-attested; learner code not collected":""]}),r&&"QUIZ"!==i.type&&"incomplete"===i.status&&a.canWaiveOnboardingItem?t.jsx(ec,{variant:"ghost",size:"compact",disabled:s,onClick:()=>n("item-waive",e,i),children:"Waive item"}):null]},i.id))})]},i.id))}),r?t.jsxs("div",{className:"onboarding-oversight-actions",children:[a.canWaiveOnboardingAssignment?t.jsx(ec,{variant:"secondary",disabled:s,onClick:()=>n("assignment-waive",e),children:"Waive assignment"}):null,a.canResetOnboarding?t.jsx(ec,{variant:"secondary",disabled:s,onClick:()=>n("reset",e),children:"Reset and reassign"}):null]}):null]})}function Od({personId:e,onClose:n,onChanged:s}){const{makeAuthRequest:r}=Yn(),i=$s(),[l,o]=a.useState(""),[c,d]=a.useState(null),[u,h]=a.useState(!1),m=a.useRef(null),p=e?`/api/workspace/v1/onboarding/people/${e}?scope=all`:null,{data:g,loading:f,error:b,refresh:x}=kc(p),v=async(t,a=null,n=null)=>{const c=l.trim();if(c.length<8)return void d("Enter a reason of at least 8 characters before taking this action.");if(["item-waive","assignment-waive","reset"].includes(t)&&!(await i({title:"reset"===t?"Reset onboarding assignment?":"Confirm onboarding waiver",message:"reset"===t?"The current assignment will become superseded and a fresh assignment will be created. Historical progress and attempts remain intact.":"This waiver is permanent audit evidence and will include the reason you entered.",confirmLabel:"reset"===t?"Reset and reassign":"Record waiver"})))return;const u={assign:`/api/workspace/v1/onboarding/people/${e}/assign?scope=all`,"item-waive":`/api/workspace/v1/onboarding/assignments/${a?.id}/items/${n?.id}/waive?scope=all`,"assignment-waive":`/api/workspace/v1/onboarding/assignments/${a?.id}/waive?scope=all`,reset:`/api/workspace/v1/onboarding/assignments/${a?.id}/reset?scope=all`},p=JSON.stringify({action:t,assignmentId:a?.id||null,itemId:n?.id||null,reason:c});m.current?.signature!==p&&(m.current={signature:p,key:_d()}),h(!0),d(null);try{await r(u[t],{method:"POST",headers:{"Idempotency-Key":m.current.key},body:JSON.stringify({reason:c})}),o(""),m.current=null,await x(),await(s?.())}catch(g){d(g.safeMessage||g.message||"The onboarding action failed.")}finally{h(!1)}},j=g?.assignments?.at(-1)||null;return t.jsxs("section",{className:"onboarding-oversight-detail","aria-labelledby":"onboarding-person-heading",children:[t.jsxs("div",{className:"employee-section-heading",children:[t.jsxs("div",{children:[t.jsx("h2",{id:"onboarding-person-heading",children:g?.person?.name||"Onboarding detail"}),g?.person?t.jsxs("p",{children:[(g.person.roles||[]).map(Sc).join(", ")||"No internal role",g.person.personnel?.type?` · ${Sc(g.person.personnel.type)} personnel`:""]}):null]}),t.jsx(ec,{variant:"ghost",onClick:n,children:"Back to onboarding list"})]}),t.jsx(bc,{loading:f&&!g,error:b,loadingLabel:"Loading onboarding detailâ¦",errorLabel:"Onboarding detail could not be loaded",onRetry:x,children:g?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"onboarding-oversight-reason",children:[t.jsx("span",{children:"Required reason for an assignment, waiver, or reset"}),t.jsx("textarea",{value:l,maxLength:1e3,rows:3,onChange:e=>o(e.target.value),placeholder:"Record the reviewed operational reason"})]}),c?t.jsx("p",{className:"employee-error",role:"alert",children:c}):null,!j&&g.capabilities.canAssignOnboarding?t.jsx(ec,{variant:"primary",disabled:u,onClick:()=>v("assign"),children:u?"Assigningâ¦":"Assign onboarding"}):null,t.jsx("div",{className:"employee-panel-grid",children:(g.assignments||[]).slice().reverse().map(e=>t.jsx(Ad,{assignment:e,capabilities:g.capabilities,onAction:v,submitting:u},e.id))})]}):null})]})}function Dd({selectedPersonId:e=null,onSelectedPersonChange:n,initialStatus:s=""}){const[r,i]=a.useState({search:"",program:"tokenworks-internal-onboarding",status:Cd.includes(s)?s:"",role:"",limit:25,offset:0});a.useEffect(()=>{i(e=>({...e,status:Cd.includes(s)?s:"",offset:0}))},[s]);const l=a.useMemo(()=>{const e=new URLSearchParams({scope:"all",program:r.program,limit:String(r.limit),offset:String(r.offset)});return r.search&&e.set("search",r.search),r.status&&e.set("status",r.status),r.role&&e.set("role",r.role),`/api/workspace/v1/onboarding/people?${e.toString()}`},[r]),{data:o,loading:c,error:d,refresh:u}=kc(l,{initialData:{people:[],programs:[],pagination:{total:0}}});if(e)return t.jsx(Od,{personId:e,onClose:()=>n?.(null),onChanged:u});const h=(e,t)=>i(a=>({...a,[e]:t,offset:0})),m=Boolean(r.search||r.status||r.role),p=Number(o?.pagination?.total||0);return t.jsxs("section",{className:"employee-panel","aria-labelledby":"onboarding-oversight-heading",children:[t.jsx("div",{className:"employee-section-heading",children:t.jsxs("div",{children:[t.jsx("h2",{id:"onboarding-oversight-heading",children:"Employee onboarding"}),t.jsx("p",{children:"Versioned progress and quiz summaries. Selected answers are not shown."})]})}),t.jsxs("div",{className:"employee-toolbar",role:"group","aria-label":"Onboarding filters",children:[t.jsxs("label",{children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{value:r.search,onChange:e=>h("search",e.target.value),placeholder:"Search people","aria-label":"Search onboarding people"})]}),t.jsxs("select",{value:r.program,onChange:e=>h("program",e.target.value),"aria-label":"Onboarding program",children:[(o?.programs||[]).map(e=>t.jsx("option",{value:e.key,children:e.name},e.key)),o?.programs?.length?null:t.jsx("option",{value:"tokenworks-internal-onboarding",children:"TokenWorks Internal Onboarding"})]}),t.jsx("select",{value:r.status,onChange:e=>h("status",e.target.value),"aria-label":"Onboarding status",children:Cd.map(e=>t.jsx("option",{value:e,children:e?Sc(e):"All statuses"},e))}),t.jsx("select",{value:r.role,onChange:e=>h("role",e.target.value),"aria-label":"Onboarding role",children:Rd.map(e=>t.jsx("option",{value:e,children:e?Sc(e):"All roles"},e))})]}
2),t.jsx(bc,{loading:c&&!o?.people?.length,error:d,isEmpty:!c&&!o?.people?.length,loadingLabel:"Loading onboarding oversightâ¦",errorLabel:"Onboarding oversight could not be loaded",emptyLabel:"No people match these onboarding filters.",emptyDescription:m?"Clear filters to return to everyone in this onboarding program.":"No one is currently assigned to this onboarding program.",emptyType:m?"no-results":"empty",emptyAction:m?t.jsx(ec,{variant:"ghost",onClick:()=>i(e=>({...e,search:"",status:"",role:"",offset:0})),children:"Clear filters"}):null,onRetry:u,children:t.jsx("div",{className:"employee-card-grid onboarding-oversight-list",children:(o?.people||[]).map(e=>t.jsxs(Qo,{className:"onboarding-oversight-person",children:[t.jsx("h3",{children:e.user.name||"Unnamed person"}),t.jsx("p",{children:(e.user.roles||[]).map(Sc).join(", ")||"No current role"}),t.jsx("p",{children:t.jsx("strong",{children:Sc(e.onboarding.displayStatus)})}),e.onboarding.assignment?t.jsxs("p",{children:[e.onboarding.assignment.progress.completedRequired," of"," ",e.onboarding.assignment.progress.totalRequired," required · best"," ",Td(e.onboarding.assignment.attempts.bestScoreBasisPoints)]}):null,t.jsx(ec,{variant:"primary",onClick:()=>n?.(e.user.id),children:"View detail"})]},e.user.id))})}),t.jsxs("div",{className:"onboarding-oversight-pagination","aria-label":"Onboarding pagination",children:[t.jsx(ec,{variant:"secondary",disabled:0===r.offset,onClick:()=>i(e=>
2({...e,offset:Math.max(0,e.offset-e.limit)})),children:"Previous"}),t.jsxs("span",{children:[p?`${r.offset+1}â${Math.min(r.offset+r.limit,p)}`:"0"," ","of ",p]}),t.jsx(ec,{variant:"secondary",disabled:r.offset+r.limit>=p,onClick:()=>i(e=>({...e,offset:e.offset+e.limit})),children:"Next"})]})]})}const Pd=["","employee","intern","student","researcher","contractor"],Ld=["","active","invited","paused","offboarded"];function $d({teams:a=[],selectedPersonId:n=null,onSelectedPersonChange:s,scope:r="mine",mode:i="profiles",onModeChange:l,onboardingStatus:o="",onEditOwnProfile:c}){const d=e.useId(),u=e.useRef(null),h="onboarding"===i?"onboarding":"profiles",m=[{id:"profiles",label:"Directory"},{id:"onboarding",label:"Onboarding"}],p=t.jsx(Md,{teams:a,selectedPersonId:n,onSelectedPersonChange:s,scope:r,onEditOwnProfile:c});return"all"!==r?p:t.jsxs("div",{className:"employee-panel-grid",children:[t.jsx("nav",{ref:u,className:"employee-subsection-tabs employee-people-tabs",role:"tablist","aria-label":"People workspace",onKeyDown:e=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;e.preventDefault();const t=m.findIndex(e=>e.id===h),a="Home"===e.key?0:"End"===e.key?m.length-1:"ArrowRight"===e.key?(t+1)%m.length:(t-1+m.length)%m.length;l?.(m[a].id),requestAnimationFrame(()=>u.current?.querySelectorAll('[role="tab"]')?.[a]?.focus())},children:m.map(e=>t.jsx("button",{type:"button",role:"tab",id:`${d}-${e.id}-tab`,"aria-selected":h===e.id,"aria-controls":`${d}-${e.id}-panel`,tabIndex:h===e.id?0:-1,onClick:()=>l?.(e.id),children:e.label},e.id))}),t.jsx("section",{role:"tabpanel",id:`${d}-${h}-panel`,"aria-labelledby":`${d}-${h}-tab`,tabIndex:0,children:"onboarding"===h?t.jsx(Dd,{selectedPersonId:n,onSelectedPersonChange:s,initialStatus:o}):p})]})}function Md({teams:a,selectedPersonId:n,onSelectedPersonChange:s,scope:r,onEditOwnProfile:i}){const{makeAuthRequest:o,user:c}=Yn(),[d,u]=e.useState(""),[h,m]=e.useState(""),[p,g]=e.useState(""),[f,b]=e.useState(""),[x,v]=e.useState(""),[j,y]=e.useState(null),[k,w]=e.useState(null),[N,S]=e.useState(null),C=e.useMemo(()=>{const e=new URLSearchParams;return h&&e.set("search",h),p&&e.set("personnelType",p),f&&e.set("teamId",f),"all"===r&&x&&e.set("status",x),e.set("scope",r),`/api/workspace/v1/people?${e.toString()}`},[h,r,p,f,x]);e.useEffect(()=>{const e=window.setTimeout(()=>m(d.trim()),250);return()=>window.clearTimeout(e)},[d]);const{data:R,loading:E,error:I,refresh:_,hasMore:T,loadMore:A,loadingMore:O,loadMoreError:D}=kc(C,{collectionKey:"people"});e.useEffect(()=>{if(!n)return y(null),w(null),void S(null);const e=(R?.people||[]).find(e=>e.id===n);if(e)return y(e),w(t=>t===e.id?t:null),void S(null);let t=!1;return async function(){try{const e=await o(`/api/workspace/v1/people/${n}?scope=${encodeURIComponent(r)}`);t||(y(e.data.person),w(t=>t===e.data.person?.id?t:null),S(null))}catch{t||(y(null),S("This profile is unavailable or you no longer have access."))}}(),()=>{t=!0}},[R?.people,o,r,n]);const P=(e,t)=>{!1!==s?.(t?e.id:null)&&(y(t?e:null),t||w(null),S(null))},L=[d,p,f,"all"===r&&x].filter(Boolean).length,$=()=>{u(""),g(""),b(""),v("")},M=(e,{keepEditing:t=!1}={})=>{y(e),w(t?e.id:null),_().catch(()=>{})};return t.jsxs("section",{className:"employee-panel employee-people-directory","aria-labelledby":"people-directory-title",children:[t.jsxs("header",{className:"employee-people-heading",children:[t.jsxs("div",{children:[t.jsx("p",{className:"ws-eyebrow",children:"all"===r?"All workspace":"My workspace"}),t.jsx("h2",{id:"people-directory-title",children:"Workspace directory"}),t.jsx("p",{children:"all"===r?"Find everyone across active, invited, paused, and offboarded records.":"Find teammates by name, role, team, or expertise."})]}),t.jsxs("div",{className:"employee-people-heading__actions",children:["all"===r?t.jsxs(ec,{as:l,to:"/admin?tab=people",variant:"secondary",children:[t.jsx(Fe,{size:16,"aria-hidden":"true"})," Manage personnel"]}):null,i?t.jsxs(ec,{variant:"secondary",onClick:i,children:[t.jsx(ze,{size:16,"aria-hidden":"true"})," Edit my profile"]}):null]})]}),t.jsxs(sc,{label:"People filters",resultCount:R?(R.people||[]).length:null,activeFilterCount:L,onClear:$,mobileCollapsible:!0,className:"employee-people-filters",children:[t.jsxs("label",{className:"employee-people-search",children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{value:d,onChange:e=>u(e.target.value),placeholder:"Search names, roles, or skills","aria-label":"Search people"})]}),t.jsx("select",{value:p,onChange:e=>g(e.target.value),"aria-label":"Personnel type",children:Pd.map(e=>t.jsx("option",{value:e,children:e?Sc(e):"All types"},e))}),t.jsxs("select",{value:f,onChange:e=>b(e.target.value),"aria-label":"Team",children:[t.jsx("option",{value:"",children:"All teams"}),a.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]}),"all"===r?t.jsx("select",{value:x,onChange:e=>v(e.target.value),"aria-label":"Status",children:Ld.map(e=>t.jsx("option",{value:e,children:e?Sc(e):"All statuses"},e))}):null]}),N?t.jsxs("div",{className:"employee-people-selection-error",children:[t.jsx(oc,{type:"error",children:N}),t.jsx(ec,{variant:"secondary",onClick:()=>{!1!==s?.(null)&&(y(null),w(null),S(null))},children:"Back to directory"})]}):null,j&&!(R?.people||[]).some(e=>e.id===j.id)?t.jsx(Sd,{person:j,isOwn:j.id===c?.id,onEdit:i,onAdminEdit:"all"===r?()=>w(j.id):void 0,adminEditing:k===j.id,adminEditor:k===j.id?t.jsx(xd,{person:j,people:R?.people||[],onCancel:()=>w(null),onSaved:M}
2):null,showOperationalStatus:"all"===r,expanded:!0,onToggle:e=>P(j,e)}):null,t.jsxs(bc,{loading:E,error:I,isEmpty:!E&&!(R?.people||[]).length,loadingLabel:"Loading the people directoryâ¦",errorLabel:"People could not be loaded",emptyLabel:L?"No people match these filters.":"No people to show yet.",emptyDescription:L?"Clear filters to return to the directory.":null,emptyType:L?"no-results":"empty",emptyAction:L?t.jsx(ec,{variant:"ghost",onClick:$,children:"Clear filters"}):null,onRetry:_,children:[t.jsx("div",{className:"employee-people-list","aria-label":"People directory results",children:(R?.people||[]).map(e=>(e=>{const a=j?.id===e.id?j:e,n=k===a.id;return t.jsx(Sd,{person:a,isOwn:a.id===c?.id,onEdit:i,onAdminEdit:"all"===r?()=>w(a.id):void 0,adminEditing:n,adminEditor:n?t.jsx(xd,{person:a,people:R?.people||[],onCancel:()=>w(null),onSaved:M}):null,showOperationalStatus:"all"===r,expanded:j?.id===a.id,onToggle:e=>P(a,e)},a.id)})(e))}),T?t.jsx("div",{className:"employee-pagination-actions",children:t.jsx(ec,{variant:"secondary",disabled:O,onClick:A,children:O?"Loadingâ¦":"Load more people"})}):null,D?t.jsx(oc,{type:"error",children:"More people could not be loaded. Try again."}):null]})]})}function Ud(e){return e?.code||e?.details?.code||e?.data?.error?.code||null}function Fd(e){return"PROFILE_VERSION_CONFLICT"===Ud(e)?"Your profile changed in another session. Reload the latest version before saving.":e?.safeMessage||e?.details?.message||e?.data?.error?.message||e?.message||"Your profile could not be updated."}function zd({onDone:e,onDirtyChange:n,onSaved:s}){const{makeAuthRequest:r}=Yn(),i=$s(),[l,o]=a.useState(null),[c,d]=a.useState(""),[u,h]=a.useState(""),[m,p]=a.useState([]),[f,b]=a.useState(""),[x,v]=a.useState(""),[j,y]=a.useState(!0),[k,w]=a.useState(""),[N,S]=a.useState(null),[C,R]=a.useState(""),[E,I]=a.useState({}),[_,T]=a.useState(""),[A,O]=a.useState(!1),[D,P]=a.useState(!1),L=a.useRef(null),$=a.useRef(null),M=a.useRef(null),U=a.useRef(null),F=a.useRef(null),z=a.useRef(null),q=a.useCallback(e=>{o(e),d(e.summary||""),h(e.linkedinUrl||""),p(e.skills||[]),b(""),I({}),P(!1)},[]),B=a.useCallback(()=>(z.current||(z.current=r("/api/workspace/v1/profile/me",{method:"POST",body:"{}"}).catch(e=>{throw z.current=null,e})),z.current),[r]),W=a.useCallback(async()=>{y(!0),R(""),T(""),O(!1);try{const e=await r("/api/workspace/v1/profile/me");q(e.data.profile)}catch(e){if("PERSONNEL_PROFILE_REQUIRED"===Ud(e))try{const e=await B();return void q(e.data.profile)}catch(t){R(Fd(t))}else R(Fd(e))}finally{y(!1)}},[q,B,r]);a.useEffect(()=>{W()},[W]);const V=Boolean(l&&(c!==(l.summary||"")||u!==(l.linkedinUrl||"")||JSON.stringify(m)!==JSON.stringify(l.skills||[])));a.useEffect(()=>{n?.(V)},[V,n]),a.useEffect(()=>()=>n?.(!1),[n]),a.useEffect(()=>{if(!V)return;const e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[V]);const H=a.useCallback(e=>{const t="summary"===e?$.current:"linkedinUrl"===e?M.current:"skills"===e?U.current:null,a=()=>(t||F.current)?.focus();"undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame(a):a()},[]),K=a.useCallback(e=>{const t=Ud(e),a=function(e){const t=e?.details?.details?.field||e?.data?.error?.details?.field;return"string"==typeof t?t:null}(e);O("PROFILE_VERSION_CONFLICT"===t),R(Fd(e)),a&&I(t=>({...t,[a]:Fd(e)})),H(a)},[H]),J=e=>{const t=String(e).split(/[\n,]+/).map(e=>e.trim().replace(/\s+/g," ")).filter(Boolean);if(!t.length)return;let a=m;const n=[];let s=!1;for(const r of t)if(Array.from(r).length>80)s=!0;else if(!a.some(e=>e.toLowerCase()===r.toLowerCase())){if(a.length>=24)return R("You can list up to 24 skills. Remove one before adding another."),v("Skill limit of 24 reached."),p(a),void b("");a=[...a,r],n.push(r)}s?R("Skills can be up to 80 characters."):n.length&&R(""),n.length&&(p(a),v(1===n.length?`Added ${n[0]}.`:`Added ${n.length} skills.`),T("")),b("")},Y=e=>{p(t=>t.filter(t=>t!==e)),v(`Removed ${e}.`),R(""),T("")};if(j)return t.jsxs("section",{className:"employee-profile-editor employee-profile-editor--loading",role:"status",children:[t.jsx("span",{className:"employee-profile-editor__skeleton employee-profile-editor__skeleton--title"}),t.jsx("span",{className:"employee-profile-editor__skeleton employee-profile-editor__skeleton--avatar"}),t.jsx("span",{children:"Loading your profileâ¦"})]});if(!l)return t.jsx("section",{className:"employee-profile-editor employee-profile-editor--unavailable",children:t.jsx(dc,{type:"error",title:"Your profile could not be loaded",description:C,action:t.jsx(ec,{variant:"secondary",onClick:W,children:"Try again"})})});const Q=l.avatarUrl,X=Boolean(k),ee=[l.title,l.department].filter(
2Boolean).join(" · ")||"Workspace member",ae=!(l.avatarUrl||l.summary||l.linkedinUrl||l.skills&&0!==l.skills.length);return t.jsxs("section",{className:"employee-profile-editor","aria-labelledby":"profile-editor-title",children:[t.jsxs("header",{className:"employee-profile-editor__heading",children:[t.jsxs("div",{children:[t.jsx("h2",{id:"profile-editor-title",children:"Profile"}),t.jsx("p",{children:ae?"Add a summary, skills, or LinkedIn link, then choose Save changes below. A photo is optional.":"Your photo, summary, skills, and LinkedIn link."})]}),e?t.jsxs(ec,{variant:"ghost",onClick:async()=>{V&&!(await i({title:"Discard profile changes?",message:"Your unsaved profile text and skills will be lost.",confirmLabel:"Discard changes",confirmVariant:"danger"}))||e?.()},children:[t.jsx(G,{size:16,"aria-hidden":"true"})," Back"]}):null]}),t.jsxs("div",{ref:F,tabIndex:-1,className:"employee-profile-editor__feedback-region",children:[C?t.jsxs("div",{className:"employee-profile-editor__feedback",children:[t.jsx(oc,{type:"error",children:C}),A?t.jsxs(ec,{variant:"secondary",size:"compact",onClick:W,children:[t.jsx(Me,{size:15,"aria-hidden":"true"})," Reload latest"]}):null]}):null,_?t.jsx(oc,{type:"success",children:_}):null]}),t.jsxs("div",{className:"employee-profile-editor__layout",children:[t.jsxs("aside",{className:"employee-profile-editor__identity","aria-label":"Profile photo and identity",children:[t.jsx("div",{className:"employee-profile-editor__avatar",children:Q&&!D?t.jsx("img",{src:Q,alt:"Your current profile photo",onError:()=>P(!0)}):t.jsx("span",{className:"employee-profile-editor__avatar-fallback","aria-hidden":"true",children:(ne=l.name,(ne||"Profile").split(/\s+/).slice(0,2).map(e=>e[0]).join("").toUpperCase())})}),t.jsxs("div",{className:"employee-profile-editor__identity-copy",children:[t.jsx("strong",{children:l.name||"Your profile"}),t.jsx("span",{children:ee}),l.status&&"active"!==l.status?t.jsxs("span",{children:["Workspace status: ",l.status]}):null]}),t.jsxs("div",{className:"employee-profile-editor__photo-actions",children:[t.jsxs(ec,{variant:"secondary",disabled:X,onClick:()=>L.current?.click(),children:[t.jsx(qe,{size:16,"aria-hidden":"true"}),"avatar-upload"===k?"Uploadingâ¦":"Change photo"]}),t.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png","aria-label":"Choose a new profile photo",hidden:!0,onChange:async e=>{const t=e.target.files?.[0];if(e.target.value="",t){if(!["image/jpeg","image/png"].includes(t.type)||t.size>5242880)return R("Choose a JPEG or PNG image no larger than 5 MB."),T(""),void window.requestAnimationFrame(()=>F.current?.focus());w("avatar-upload"),S(0),R(""),T(""),O(!1);try{const e=await async function(e){const t=await crypto.subtle.digest("SHA-256",await e.arrayBuffer());return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}(t),a=await r("/api/workspace/v1/profile/me/avatar/initiate",{method:"POST",body:JSON.stringify({filename:t.name,contentType:t.type,sizeBytes:t.size,sha256:e,expectedVersion:l.profileVersion})});await function(e,t,a,n){return new Promise((s,r)=>{const i=new XMLHttpRequest;i.open("PUT",e),Object.entries(t||{}).forEach(([e,t])=>i.setRequestHeader(e,t)),i.upload.addEventListener("progress",e=>{e.lengthComputable&&n(Math.round(e.loaded/e.total*100))}),i.addEventListener("load",()=>{i.status>=200&&i.status<300?s():r(new Error("The avatar upload could not be stored."))}),i.addEventListener("error",()=>r(new Error("The avatar upload was interrupted."))),i.send(a)})}(a.data.uploadUrl,a.data.uploadHeaders,t,S),S(100);const n=await r("/api/workspace/v1/profile/me/avatar/complete",{method:"POST",body:JSON.stringify({uploadId:a.data.uploadId,expectedVersion:l.profileVersion})});o(n.data.profile),P(!1),T("Profile photo updated."),s?.(n.data.profile)}catch(a){K(a)}finally{w(""),S(null)}}}}),Q?t.jsxs(ec,{variant:"ghost",disabled:X,onClick:async()=>{w("avatar-remove"),R(""),T(""),O(!1);try{const e=await r("/api/workspace/v1/profile/me/avatar",{method:"DELETE",body:JSON.stringify({expectedVersion:l.profileVersion})});o(e.data.profile),P(!1),T("Profile photo removed."),s?.(e.data.profile)}catch(e){K(e)}finally{w("")}},children:[t.jsx(te,{size:16,"aria-hidden":"true"}),"avatar-remove"===k?"Removingâ¦":"Remove"]}):null]}),t.jsx("small",{className:"ws-meta",children:"JPEG or PNG, up to 5 MB. Photo changes save immediately."}),null!==N?t.jsx("progress",{value:N,max:"100","aria-label":"Avatar upload progress"}):null,t.jsx("p",{className:"ws-meta employee-profile-editor__managed-note",children:"Your name, role, and organization details are managed by an administrator."})]}),t.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),V&&!k){w("save"),R(""),I({}),T(""),O(!1);try{const e=await r("/api/workspace/v1/profile/me",{method:"PATCH",body:JSON.stringify({summary:c,skills:m,linkedinUrl:u,expectedVersion:l.profileVersion})});q(e.data.profile),T("Profile changes saved. Your Workspace profile is up to date."),s?.(e.data.profile)}catch(t){K(t)}finally{w("")}}},className:"employee-profile-editor__form",children:[t.jsx(ic,{legend:"About",description:"A short introduction that teammates see on your Workspace profile.",children:t.jsx(rc,{label:"Summary",help:`${Array.from(c).length}/2000 characters`,error:E.summary||null,children:t.jsx("textarea",{ref:$,maxLength:2e3,rows:7,value:c,onChange:e=>{d(e.target.value),T(""),I(e=>({...e,summary:null}))},placeholder:"Share your focus, responsibilities, or current interests."})})}),t.jsxs(ic,{legend:"Skills",description:"Add up to 24 concise skills so peo
2ple can find the right expertise.",children:[t.jsx("label",{className:"ws-label",htmlFor:"profile-skill-input",children:"Add a skill"}),t.jsxs("div",{className:"employee-profile-editor__skill-input",children:[t.jsx("input",{id:"profile-skill-input",ref:U,maxLength:80,value:f,onChange:e=>b(e.target.value),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),J(f)):"Backspace"===e.key&&!f&&m.length&&(e.preventDefault(),Y(m[m.length-1]))},onPaste:e=>{const t=e.clipboardData?.getData("text")||"";/[\n,]/.test(t)&&(e.preventDefault(),J(t))},placeholder:"For example, React or research synthesis","aria-describedby":"profile-skill-hint"}),t.jsxs(ec,{type:"button",variant:"secondary",onClick:()=>J(f),children:[t.jsx(Z,{size:16,"aria-hidden":"true"})," Add"]})]}),t.jsx("p",{id:"profile-skill-hint",className:"ws-meta",children:"Press Enter to add. Backspace removes the last skill when the field is empty."}),m.length?t.jsx("ul",{className:"employee-profile-editor__skills","aria-label":"Selected skills",children:m.map(e=>t.jsxs("li",{children:[e,t.jsx("button",{type:"button",onClick:()=>Y(e),"aria-label":`Remove ${e}`,children:t.jsx(g,{size:14,"aria-hidden":"true"})})]},e))}):t.jsx("p",{className:"employee-profile-editor__empty-skills ws-meta",children:"No skills added yet."}),t.jsx("span",{className:"sr-only","aria-live":"polite",children:x})]}),t.jsx(ic,{legend:"Professional link",description:"This optional link is visible to people who can view your profile.",children:t.jsx(rc,{label:"LinkedIn profile",help:"Personal profile URL only, without tracking parameters. Example: https://www.linkedin.com/in/your-profile",error:E.linkedinUrl||null,children:t.jsx("input",{ref:M,type:"url",maxLength:500,placeholder:"https://www.linkedin.com/in/your-profile",value:u,onChange:e=>{h(e.target.value),T(""),I(e=>({...e,linkedinUrl:null}))}})})}),t.jsxs(lc,{className:"employee-profile-editor__actions",children:[t.jsx(ec,{type:"submit",disabled:X||!V,children:"save"===k?"Saving changesâ¦":"Save changes"}),t.jsx(ec,{type:"button",variant:"secondary",disabled:X||!V,onClick:async()=>{V&&!(await i({title:"Discard profile changes?",message:"Your unsaved profile text and skills will be lost.",confirmLabel:"Discard changes",confirmVariant:"danger"}))||(l&&q(l),R(""),T(""),O(!1))},children:"Cancel"}),V?t.jsx("small",{className:"ws-meta",children:"Unsaved changes"}):null]})]})]})]});var ne}function qd({onDirtyChange:e}){return t.jsxs("section",{className:"workspace-settings-panel","aria-label":"Workspace settings",children:[t.jsx("p",{className:"workspace-settings-panel__intro ws-meta",children:"This information is visible to people in the TokenWorks Workspace."}),t.jsx(zd,{onDirtyChange:e})]})}const Bd=Object.freeze(["paragraph","heading","bulletList","orderedList","blockquote","codeBlock"]),Wd=Object.freeze(["text","hardBreak"]),Vd=Object.freeze(["doc","listItem"]);Object.freeze([...Vd,...Bd,...Wd]);const Hd=Object.freeze(["bold","italic","underline","code","link"]),Kd=Object.freeze(Object.fromEntries(Hd.map((e,t)=>[e,t]))),Gd=Object.freeze({type:"doc",content:[{type:"paragraph"}]});new Set(Bd);const Jd=new Set(Hd),Yd=new Set([...Bd,"listItem"]);function Qd(e){if("link"!==e?.type)return{type:e?.type};const t=e.attrs?.title;return{type:"link",attrs:{href:e.attrs?.href,...null==t?{}:{title:t}}}}function Xd(e){return Array.isArray(e)?e.flatMap(e=>function(e){const t=e?.type;if("text"===t){if("string"!=typeof e.text||""===e.text)return[];const t=function(e){if(!Array.isArray(e)||!e.length)return;const t=e.filter(e=>Jd.has(e?.type)).map(Qd).sort((e,t)=>Kd[e.type]-Kd[t.type]);return t.length?t:void 0}(e.marks);return[{type:"text",...t?{marks:t}:{},text:e.text}]}if("hardBreak"===t)return[{type:"hardBreak"}];if(!Yd.has(t))return Xd(e?.content);const a={type:t};if("heading"===t){const t=[2,3].includes(e.attrs?.level)?e.attrs.level:2;a.attrs={level:t}}const n=Xd(e?.content);n.length&&(a.content=n);return[a]}(e)):[]}function Zd(e){return{type:"doc",content:Xd(e?.content)}}function eu(e){return JSON.stringify(Zd(e))}
2const tu=new Set(["doc","listItem",...Bd,"text","hardBreak"]);function au(e){const t=String(e||""),a=[...t].some(e=>{const t=e.charCodeAt(0);return t<32||127===t});if(!t||t.length>2048||/\s/u.test(t)||a||t.startsWith("//"))throw new TypeError("Invalid private note link");const n=new URL(t);if("https:"!==n.protocol||!n.hostname||n.username||n.password)throw new TypeError("Invalid private note link");return n.href}function nu(e){try{return au(e),!0}catch{return!1}}const su=new Set(["A","BLOCKQUOTE","BR","CODE","EM","H2","H3","I","LI","OL","P","PRE","STRONG","B","U","UL"]);function ru(e){const t=(new DOMParser).parseFromString(String(e||""),"text/html");return t.body.querySelectorAll("script,iframe,object,embed,form,input,button,style,link,meta,svg,math,img,audio,video,hr").forEach(e=>e.remove()),t.body.querySelectorAll("*").forEach(e=>{if(su.has(e.tagName)){for(const t of[...e.attributes]){"A"===e.tagName&&("href"===t.name||"title"===t.name)||e.removeAttribute(t.name)}if("A"===e.tagName&&e.hasAttribute("href"))try{e.setAttribute("href",au(e.getAttribute("href")))}catch{e.removeAttribute("href")}}else e.replaceWith(...e.childNodes)}),t.body.innerHTML}function iu({label:e,active:a=null,disabled:n=!1,toolbarIndex:s,currentToolbarIndex:r,onToolbarFocus:i,buttonRef:l=null,expanded:o,controls:c,onClick:d,children:u}){return t.jsxs("button",{ref:l,type:"button",className:"private-note-toolbar__button","aria-label":e,"aria-pressed":null===a?void 0:a,"aria-expanded":o,"aria-controls":c,title:e,disabled:n,"data-toolbar-control":!0,"data-toolbar-index":s,tabIndex:n||s!==r?-1:0,onFocus:()=>i(s),onClick:d,children:[u,t.jsx("span",{children:e})]})}function lu({document:n=Gd,readOnly:s=!1,onChange:r,onValidityChange:i,onUnsupportedContentStripped:l,accessibleLabel:o=(s?"Private note document":"Private note editor")}){const c=e.useId(),d=e.useId(),u=e.useId(),h=e.useId(),m=e.useId(),p=e.useRef(null),g=e.useRef(null),f=e.useRef(null),[b,x]=e.useState(0),[v,j]=e.useState(!1),[y,k]=e.useState(!1),[w,N]=e.useState("https://"),[S,C]=e.useState(""),[R,E]=e.useState(""),I=e.useMemo(()=>[Xt.configure({heading:{levels:[2,3]},codeBlock:{HTMLAttributes:{"aria-label":"Code block",...s?{tabIndex:0}:{}}},link:!1,underline:!1,strike:!1,horizontalRule:!1}),aa,Zt.configure({openOnClick:s,enableClickSelection:!s,autolink:!1,protocols:["https"],HTMLAttributes:{target:null,rel:"noopener noreferrer"},isAllowedUri:e=>nu(e),shouldAutoLink:e=>nu(e)})],[s]),_=ea({extensions:I,content:n||Gd,editable:!s,editorProps:{attributes:{class:"private-note-document","aria-label":o,role:s?"document":"textbox",...s?{}:{"aria-multiline":"true"}},transformPastedHTML:ru},onUpdate:({editor:e})=>{const t=e.getJSON(),a=Zd(t);(function(e){let t=!1;const a=e=>{!t&&e&&"object"==typeof e&&(tu.has(e.type)?Array.isArray(e.marks)&&e.marks.some(e=>!Jd.has(e?.type))?t=!0:(e.content||[]).forEach(a):t=!0)};return a(e),t})(t)&&(e.commands.setContent(a,{emitUpdate:!1}),l?.()),r?.(a)}},[o,s]);if(e.useEffect(()=>{_?.setEditable(!s)},[_,s]),e.useEffect(()=>{var e,t;_&&n&&(e=_.getJSON(),t=n,eu(e)!==eu(t)&&_.commands.setContent(n,{emitUpdate:!1}))},[n,_]),e.useEffect(()=>{i?.(Boolean(_))},[_,i]),!_)return t.jsx("div",{className:"private-note-editor-loading",children:"Preparing editorâ¦"});const T=[["Bold",ke,()=>_.chain().focus().toggleBold().run(),_.isActive("bold"),!_.can().chain().focus().toggleBold().run()],["Italic",we,()=>_.chain().focus().toggleItalic().run(),_.isActive("italic"),!_.can().chain().focus().toggleItalic().run()],["Underline",Be,()=>_.chain().focus().toggleUnderline().run(),_.isActive("underline"),!_.can().chain().focus().toggleUnderline().run()],["Heading 2",Ne,()=>_.chain().focus().toggleHeading({level:2}).run(),_.isActive("heading",{level:2}),!_.can().chain().focus().toggleHeading({level:2}).run()],["Heading 3",Se,()=>_.chain().focus().toggleHeading({level:3}).run(),_.isActive("heading",{level:3}),!_.can().chain().focus().toggleHeading({level:3}).run()],["Bulleted list",Ce,()=>_.chain().focus().toggleBulletList().run(),_.isActive("bulletList"),!_.can().chain().focus().toggleBulletList().run()],["Numbered list",Re,()=>_.chain().focus().toggleOrderedList().run(),_.isActive("orderedList"),!_.can().chain().focus().toggleOrderedList().run()],["Block quote",Ee,()=>_.chain().focus().toggleBlockquote().run(),_.isActive("blockquote"),!_.can().chain().focus().toggleBlockquote().run()],["Inline code",_e,()=>_.chain().focus().toggleCode().run(),_.isActive("code"),!_.can().chain().focus().toggleCode().run()],["Code block",Te,()=>_.chain().focus().toggleCodeBlock().run(),_.isActive("codeBlock"),!_.can().chain().focus().toggleCodeBlock().run()]],A=({restoreToolbarFocus:e=!1}={})=>{j(!1),C(""),f.current=null,e&&requestAnimationFrame(()=>g.current?.focus())},O=()=>{let e=_.chain().focus();return f.current&&(e=e.setTextSelection(f.current)),e.extendMarkRange("link")},D=[{label:"Text style",controls:T.slice(0,3),start:0},{label:"Document structure",controls:T.slice(3,8),start:3},{label:"Code formatting",controls:T.slice(8,10),start:8}
2],P=!_.can().chain().focus().undo().run(),L=!_.can().chain().focus().redo().run(),$=11===b&&P||12===b&&L?0:b;return t.jsxs("div",{className:"private-note-editor"+(s?" is-read-only":""),children:[s?null:t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:p,className:"private-note-toolbar",role:"toolbar","aria-label":"Text formatting",onKeyDown:e=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;const t=[...p.current.querySelectorAll("[data-toolbar-control]:not(:disabled)")],a=t.indexOf(globalThis.document?.activeElement);if(a<0)return;e.preventDefault();const n="Home"===e.key?0:"End"===e.key?t.length-1:"ArrowRight"===e.key?(a+1)%t.length:(a-1+t.length)%t.length;x(Number(t[n]?.dataset.toolbarIndex||0)),t[n]?.focus()},children:[D.map(e=>t.jsx("div",{className:"private-note-toolbar__group",role:"group","aria-label":e.label,children:e.controls.map(([n,s,r,i,l],o)=>t.jsx(iu,{label:n,active:i,disabled:l,toolbarIndex:e.start+o,currentToolbarIndex:$,onToolbarFocus:x,onClick:r,children:a.createElement(s,{size:17,"aria-hidden":!0})},n))},e.label)),t.jsx("div",{className:"private-note-toolbar__group",role:"group","aria-label":"Links",children:t.jsx(iu,{buttonRef:g,label:"Add or edit link",active:_.isActive("link"),expanded:v,controls:d,toolbarIndex:10,currentToolbarIndex:$,onToolbarFocus:x,onClick:()=>{if(v)return void A({restoreToolbarFocus:!0});const e=_.state.selection,t=_.isActive("link");if(e.empty&&!t)return E("Select text to add a link."),void C("");f.current={from:e.from,to:e.to},k(t),N(_.getAttributes("link").href||"https://"),C(""),E(""),j(!0)},children:t.jsx(Oe,{size:17,"aria-hidden":"true"})})}),t.jsxs("div",{className:"private-note-toolbar__group",role:"group","aria-label":"Edit history",children:[t.jsx(iu,{label:"Undo",disabled:P,toolbarIndex:11,currentToolbarIndex:$,onToolbarFocus:x,onClick:()=>_.chain().focus().undo().run(),children:t.jsx(ae,{size:17,"aria-hidden":"true"})}),t.jsx(iu,{label:"Redo",disabled:L,toolbarIndex:12,currentToolbarIndex:$,onToolbarFocus:x,onClick:()=>_.chain().focus().redo().run(),children:t.jsx(Ae,{size:17,"aria-hidden":"true"})})]})]}),R&&!v?t.jsx("p",{className:"private-note-link-guidance",role:"status","aria-live":"polite",children:R}):null,v?t.jsxs("form",{id:d,className:"private-note-link-control",role:"dialog","aria-labelledby":u,onSubmit:e=>{e.preventDefault(),(()=>{try{const e=au(w);if(!O().setLink({href:e}).run())throw new Error("link command unavailable");C(""),j(!1),f.current=null}catch{C("Use a complete HTTPS link without a username or password.")}})()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),A({restoreToolbarFocus:!0}))},children:[t.jsxs("div",{className:"private-note-link-control__field",children:[t.jsx("strong",{id:u,children:y?"Edit link":"Add link"}),t.jsx("label",{htmlFor:c,children:"HTTPS link"}),t.jsx("input",{id:c,type:"url",inputMode:"url",maxLength:2048,value:w,"aria-invalid":Boolean(S),"aria-describedby":`${h}${S?` ${m}`:""}`,onChange:e=>{N(e.target.value),S&&C("")},autoFocus:!0}),t.jsx("span",{id:h,children:"Use a complete, secure HTTPS address."})]}),t.jsxs("div",{className:"private-note-link-control__actions",children:[t.jsx("button",{type:"submit",children:"Apply link"}),y?t.jsx("button",{type:"button",onClick:()=>{O().unsetLink().run(),j(!1),C(""),f.current=null},children:"Remove link"}):null,t.jsx("button",{type:"button",onClick:()=>A({restoreToolbarFocus:!0}),children:"Cancel"})]}),S?t.jsx("p",{id:m,role:"alert",children:S}):null]}):null]}),t.jsx("div",{className:"private-note-editor__canvas",children:t.jsx(ta,{editor:_})})]})}function ou({value:a=[],onChange:n,multiple:s=!0,collapsible:r=!1,endpoint:i="/api/workspace/v1/resource-packs",request:l=null,label:o="Resources",searchPlaceholder:c="Search Resources by name, purpose, or file",allowTargets:d=!0,disabled:h=!1,showSelected:m=!0,selectedListScrollable:p=!1,className:f="",showAttachedState:b=!1,singleTargetPerPack:v=!1,announceResults:y=!1}){const{makeAuthRequest:k}=Yn(),w=l||k,[N,S]=e.useState(""),[C,R]=e.useState(""),[E,I]=e.useState([]),[_,T]=e.useState(!1),[A,O]=e.useState(null),[D,P]=e.useState(!r),[L,$]=e.useState(null),[M,U]=e.useState({}),[F,z]=e.useState({}),[q,B]=e.useState(""),[W,V]=e.useState(""),[K,G]=e.useState(0),J=e.useRef(0),Y=e.useRef(0),Q=e.useRef(null),X=e.useRef(null),Z=e.useRef(!1),ee=e.useId(),te=e.useId(),ae=e.useId(),ne=e.useId(),se=e.useMemo(()=>{const e=i.split("?")[1]||"";return new URLSearchParams(e).get("scope")||"mine"},[i]);e.useLayoutEffect(()=>{D&&Z.current&&(Z.current=!1,X.current?.scrollTo?.({top:0}
2),Q.current?.focus?.({preventScroll:!0}))},[D]),e.useEffect(()=>{const e=setTimeout(()=>R(N),250);return()=>clearTimeout(e)},[N]),e.useEffect(()=>{const e=setTimeout(()=>V(q),250);return()=>clearTimeout(e)},[q]),e.useEffect(()=>{if(!D||h)return;const e=++J.current;let t=!1;return async function(){T(!0),O(null);try{const a=i.includes("?")?"&":"?",n=await w(`${i}${a}limit=30${C?`&search=${encodeURIComponent(C)}`:""}`);t||e!==J.current||I(n.data?.resources||[])}catch(a){t||e!==J.current||(I([]),O(a))}finally{t||e!==J.current||T(!1)}}(),()=>{t=!0}},[C,h,i,D,K,w]);const re=e.useMemo(()=>a.map(e=>"string"==typeof e?{id:e,title:e}:e),[a]),ie=e.useMemo(()=>new Set(re.map(ln)),[re]),le=e.useMemo(()=>new Set(re.map(on)),[re]),oe=E,de=(e,t={})=>{const a=e.packTitle||e.title||"Workspace Resource",r={...e,resourceId:e.resourceId||e.id,packTitle:a,targetKind:t.targetKind||"pack",folderId:t.folderId||null,objectId:t.objectId||null,targetLabel:t.targetLabel||t.title||null,title:a};ie.has(ln(r))||n(s?[...re,r]:[r])},he=e.useCallback(async(e,{query:t="",appendKind:a=null}={})=>{const n=++Y.current,s=M[e.id]||{},r="objects"===a?"objectPagination":"folderPagination",i=a?s[r]?.nextCursor:null;z(t=>({...t,[e.id]:null})),U(n=>({...n,[e.id]:{...n[e.id]||{},loading:!a,loadingMore:a,query:t}}));try{const s=a?[a]:["objects","folders"],r=await Promise.all(s.map(a=>w(function(e,t,{scope:a,search:n="",cursor:s=null}={}){const r=new URLSearchParams({limit:String(40),scope:a});return n&&r.set("search",n),s&&r.set("cursor",s),`/api/workspace/v1/resource-packs/${e}/${t}?${r}`}(e.id,a,{scope:se,search:t,cursor:i}))));if(n!==Y.current)return;U(n=>{const i=n[e.id]||{},l={...i,loading:!1,loadingMore:null,query:t};return s.forEach((e,t)=>{const n="objects"===e?"object":"folder",s=r[t].data?.[e]||[];l[e]=a?[...new Map([...i[e]||[],...s].map(e=>[e.id,e])).values()]:s,l[`${n}Pagination`]=r[t].data?.pagination||{hasMore:!1,nextCursor:null}}),{...n,[e.id]:l}})}catch(l){if(n!==Y.current)return;U(t=>({...t,[e.id]:{...t[e.id]||{},loading:!1,loadingMore:null}})),z(t=>({...t,[e.id]:l.safeMessage||"Resource contents could not be loaded."}))}},[se,w,M]),me=(e,t=!1)=>{if(!t&&L===e.id)return Y.current+=1,void $(null);B(""),V(""),$(e.id),he(e,{query:""})};e.useEffect(()=>{if(!L)return;const e=E.find(e=>e.id===L),t=M[L]?.query;e&&t!==W&&he(e,{query:W})},[W,L,he,E,M]),e.useEffect(()=>()=>{Y.current+=1},[]);const pe=e=>{const t=ie.has(ln(e)),a=le.has(on(e));return{exact:t,unavailable:t||v&&a,message:t?"Attached":v&&a?"Another target from this Resource is attached. Detach it before choosing this target.":null}};return t.jsxs("div",{className:`resource-pack-picker${r?" is-collapsible":""}${f?` ${f}`:""}`,children:[r?t.jsxs("button",{type:"button",className:"resource-pack-picker-disclosure","aria-expanded":D,"aria-controls":ee,disabled:h,onClick:()=>{D||(Z.current=!0),P(e=>!e)},children:[t.jsx(We,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:D?re.length?`Hide attachments · ${re.length} Resource${1===re.length?"":"s"} attached`:"Hide attachments":re.length?`${re.length} Resource${1===re.length?"":"s"} attached`:"Attach Resources"}),t.jsx(u,{className:"resource-pack-picker-disclosure-chevron"+(D?" is-expanded":""),size:16,"aria-hidden":"true"})]}):null,D?t.jsxs("div",{className:"resource-pack-picker-body",id:ee,ref:X,children:[t.jsxs("label",{className:"resource-pack-picker-search",htmlFor:te,children:[t.jsx("span",{children:o}),t.jsxs("span",{className:"resource-pack-picker-search-field",children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{ref:Q,id:te,type:"search",value:N,disabled:h,onChange:e=>S(e.target.value),placeholder:c,"aria-controls":ae,autoComplete:"off"})]})]}),m&&re.length?t.jsx("ul",{className:"resource-pack-picker-selected"+(p?" is-scrollable":""),"aria-label":p?`Selected Resources (${re.length})`:"Selected Resources",tabIndex:p?0:void 0,children:re.map(e=>{const a=cn(e);return t.jsxs("li",{children:[t.jsx(x,{size:14,"aria-hidden":"true"}),t.jsx("span",{title:a.label,children:a.label}),t.jsx("button",{type:"button",disabled:h,onClick:()=>(e=>{const t=ln(e);n(re.filter(e=>ln(e)!==t))})(e),"aria-label":`Remove ${a.label}`,children:t.jsx(g,{size:14,"aria-hidden":"true"})})]},ln(e))})}):null,y?t.jsx("p",{className:"sr-only",role:"status","aria-live":"polite",children:_?"Searching Resourcesâ¦":A?"":`${oe.length} ${1===oe.length?"Resource":"Resources"} available.`}):null,t.jsxs("div",{id:ae,className:"resource-pack-picker-results","aria-busy":_?"true":"false","aria-live":y?void 0:"polite",children:[_?t.jsx("p",{children:"Searchingâ¦"}):null,A?t.jsxs("div",{className:"resource-pack-picker-error",role:"alert",children:[t.jsx("p",{children:A.safeMessage||"Resources could not be loaded."}),t.jsxs("button",{type:"button",disabled:h,onClick:()=>G(e=>e+1),children:[t.jsx(ce,{size:15,"aria-hidden":"true"})," Retry"]})]}
2):null,_||A||oe.length?null:t.jsx("p",{children:C?"No Resources match this search.":"No Resources are available."}),oe.map(e=>{const a={...e,resourceId:e.resourceId||e.id,folderId:null,objectId:null},n=pe(a);return t.jsxs("div",{className:"resource-pack-picker-option",children:[t.jsxs("button",{type:"button",disabled:h||b&&n.unavailable,"aria-disabled":h||b&&n.unavailable,onClick:()=>de(e),children:[t.jsx(x,{size:18,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:e.title}),t.jsx("small",{children:e.purpose||e.description||"Workspace Resource"}),t.jsxs("small",{children:[e.category||"Uncategorized"," · ",Number(e.objectCount||1)," ","file",1===Number(e.objectCount||1)?"":"s"," ·"," ",Nc(e.totalBytes??e.sizeBytes)]}),b&&n.message?t.jsxs("small",{className:"resource-pack-picker-attached-state",children:[n.exact?t.jsx(Ve,{size:14,"aria-hidden":"true"}):null,n.message]}):null]})]}),d?t.jsxs("button",{type:"button",className:"resource-pack-picker-browse","aria-expanded":L===e.id,disabled:h,onClick:()=>me(e),children:[t.jsx(u,{size:16,"aria-hidden":"true"})," Choose a folder or file"]}):null,L===e.id?t.jsxs("div",{className:"resource-pack-picker-targets",children:[t.jsxs("label",{className:"resource-pack-picker-target-search",htmlFor:ne,children:[t.jsxs("span",{children:["Search folders and files in ",e.title]}),t.jsxs("span",{className:"resource-pack-picker-search-field",children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{id:ne,type:"search",value:q,disabled:h,onChange:e=>B(e.target.value),placeholder:"Search this Resource",autoComplete:"off"})]})]}),M[e.id]?.loading&&!F[e.id]?t.jsx("p",{role:"status",children:"Loading contentsâ¦"}):null,F[e.id]?t.jsxs("div",{className:"resource-pack-picker-target-error",role:"alert",children:[t.jsx("p",{children:F[e.id]}),t.jsxs("button",{type:"button",disabled:h,onClick:()=>(e=>{U(t=>{const a={...t};return delete a[e.id],a}),me(e,!0)})(e),children:[t.jsx(ce,{size:15,"aria-hidden":"true"})," Retry contents"]})]}):null,M[e.id]?.loading||F[e.id]?null:t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"resource-pack-picker-target-group",children:[t.jsxs("h3",{children:["Folders (",M[e.id]?.folders?.length||0,M[e.id]?.folderPagination?.hasMore?"+":"",")"]}),(M[e.id]?.folders||[]).map(a=>{const n=a.path||a.name,s={resourceId:e.id,folderId:a.id,objectId:null},r=pe(s);return t.jsxs("button",{type:"button",disabled:h||b&&r.unavailable,"aria-disabled":h||b&&r.unavailable,onClick:()=>de(e,{targetKind:"folder",folderId:a.id,targetLabel:n}),children:[t.jsx(H,{size:16,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:n}),t.jsxs("small",{children:[e.title," · Folder"]})]}),b&&r.message?t.jsx("small",{children:r.message}):null]},a.id)}),M[e.id]?.folderPagination?.hasMore?t.jsx("button",{type:"button",className:"resource-pack-picker-load-more",disabled:h||Boolean(M[e.id]?.loadingMore),onClick:()=>he(e,{query:W,appendKind:"folders"}),children:"folders"===M[e.id]?.loadingMore?"Loading more foldersâ¦":"Load more folders"}):null]}),t.jsxs("section",{className:"resource-pack-picker-target-group",children:[t.jsxs("h3",{children:["Files (",M[e.id]?.objects?.length||0,M[e.id]?.objectPagination?.hasMore?"+":"",")"]}),(M[e.id]?.objects||[]).map(a=>{const n=a.relativePath||a.originalFilename,s={resourceId:e.id,folderId:null,objectId:a.id},r=pe(s);return t.jsxs("button",{type:"button",disabled:h||b&&r.unavailable,"aria-disabled":h||b&&r.unavailable,onClick:()=>de(e,{targetKind:"object",objectId:a.id,targetLabel:n}),children:[t.jsx(j,{size:16,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:n}),t.jsxs("small",{children:[e.title," · File"]})]}),b&&r.message?t.jsx("small",{children:r.message}):null]},a.id)}),M[e.id]?.objectPagination?.hasMore?t.jsx("button",{type:"button",className:"resource-pack-picker-load-more",disabled:h||Boolean(M[e.id]?.loadingMore),onClick:()=>he(e,{query:W,appendKind:"objects"}),children:"objects"===M[e.id]?.loadingMore?"Loading more filesâ¦":"Load more files"}):null]}),M[e.id]?.folders?.length||M[e.id]?.objects?.length?null:t.jsx("p",{children:W?"No folders or files match this search.":"No folders or files are available."})]})]}):null]},e.id)})]})]}):null]})}const cu=["general","onboarding","meeting","performance","research","administrative"];function du(e){return{format:"tokenworks.note.prosemirror",version:1,document:e}}const uu={PERSON_NOTE_ACCESS_DENIED:"You don't have permission to perform this Notes action.",PERSON_NOTE_SUBJECT_INELIGIBLE:"This person is not an active Worksp
2ace member, so a meeting note cannot be created for them.",PRIVATE_NOTE_FEATURE_DISABLED:"Notes are not available yet.",PRIVATE_NOTE_ACCESS_BOUNDARY_UNVERIFIED:"Notes are temporarily unavailable. Try again shortly.",PRIVATE_NOTE_ONTOLOGY_UNVERIFIED:"Notes are temporarily unavailable. Try again shortly.",PRIVATE_NOTE_ONTOLOGY_INVALID:"Notes are temporarily unavailable. Try again shortly.",PRIVATE_NOTE_CONFIGURATION_INVALID:"Notes are temporarily unavailable. Try again shortly.",PRIVATE_NOTE_SERVICE_UNAVAILABLE:"Notes are temporarily unavailable. Your unsaved draft is still in this browser tab.",PRIVATE_NOTE_SERVICE_CREDENTIAL_DENIED:"Notes are temporarily unavailable. Your unsaved draft is still in this browser tab.",PRIVATE_NOTE_DOCUMENT_INVALID:"This note contains formatting that Notes doesn't support. The unsupported formatting has been removed â try saving again.",PRIVATE_NOTE_DOCUMENT_TOO_LARGE:"This note is too long to save. Shorten it and try again.",PRIVATE_NOTE_LINK_INVALID:"A link in this note is not a valid HTTPS address.",PERSON_NOTE_TITLE_INVALID:"That title contains characters Notes cannot store. Adjust it and try again.",PERSON_NOTE_CATEGORY_INVALID:"Choose a valid category before saving.",PERSON_NOTE_MEETING_DATE_INVALID:"Enter a valid meeting date before saving.",PERSON_NOTE_ARCHIVED:"This note is archived. Restore it from the archive before editing.",PERSON_NOTE_REPAIR_PENDING:"This note is being repaired after a synchronization problem. Try again shortly.",PERSON_NOTE_REVISION_INVALID:"This revision could not be displayed safely. Contact an operator for review.",PERSON_NOTE_REVISION_CONFLICT:"This note changed in another session. Reload the latest version before saving.",PERSON_NOTE_CONTENT_NOT_FOUND:"This note is being repaired. Try again shortly.",PERSON_NOTE_ENTITY_BINDING_MISMATCH:"This note is being repaired. Try again shortly.",PERSON_NOTE_NOT_FOUND:"This note could not be found. It may have been archived or removed.",RATE_LIMITED:"Too many Notes changes in a short time. Wait a moment and try again."};function hu(e){return uu[e?.code]||e?.safeMessage||e?.message||"Notes could not be loaded."}function mu(e){return["PRIVATE_NOTE_SERVICE_UNAVAILABLE","PRIVATE_NOTE_SERVICE_CREDENTIAL_DENIED"].includes(e?.code)?"Notes are temporarily unavailable. Try again shortly.":uu[e?.code]||e?.safeMessage||"Notes could not be loaded."}function pu(e){return"PERSON_NOTE_NOT_FOUND"===e?.code?"Private note not found":["PERSON_NOTE_REPAIR_PENDING","PERSON_NOTE_CONTENT_NOT_FOUND","PERSON_NOTE_ENTITY_BINDING_MISMATCH"].includes(e?.code)?"This private note is being repaired":"Private note could not be loaded"}function gu(e){if(!e)return"time unavailable";try{return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}catch{return String(e)}}function fu(e){if(!e)return"";if("text"===e.type)return e.text||"";if("hardBreak"===e.type)return"\n";const t=(e.content||[]).map(fu).join("");return["paragraph","heading","blockquote","codeBlock","listItem"].includes(e.type)?`${t}\n`:t}function bu(e){return JSON.stringify(e.map(e=>({resourceId:e.id||e.resourceId,folderId:e.folderId||null,objectId:e.objectId||null,unavailable:Boolean(e.unavailable)})))}function xu({noteId:a,request:n,readOnly:s,onDirtyChange:r}){const[i,l]=e.useState([]),[o,c]=e.useState(null),[d,u]=e.useState(null),[h,m]=e.useState(!0),[p,g]=e.useState(!1),[f,b]=e.useState(0),[x,v]=e.useState("");e.useEffect(()=>{let e=!1;return m(!0),u(null),v(""),n(`/api/employee/notes/personal/${a}/resources`).then(t=>{if(e)return;const a=t.data?.resources||[];l(a),c(bu(a)),u(null)}).catch(t=>{e||(l([]),c(null),u(hu(t)))}).finally(()=>{e||m(!1)}),()=>{e=!0}},[a,f,n]);const j=i.filter(e=>!e.unavailable),y=null!==o&&bu(i)!==o;e.useEffect(()=>(r?.(y),()=>r?.(!1)),[y,r]);return t.jsxs(Yo,{title:"Linked Resources",children:[h?t.jsx("p",{className:"private-note-muted",role:"status",children:"Loading linked Resourcesâ¦"}):null,!h&&d&&null===o?t.jsxs(Xo,{className:"private-note-error",role:"alert",children:[t.jsx(be,{size:20,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:d}),t.jsxs(ec,{variant:"secondary",onClick:()=>b(e=>e+1),children:[t.jsx(ce,{size:16,"aria-hidden":"true"})," Retry"]})]})]}):null,!h&&i.some(e=>e.unavailable)?t.jsx("p",{className:"private-note-muted",children:"One or more linked Resources are unavailable because access was revoked or the Resource was removed."}):null,h||null===o||s?null:t.jsx(ou,{value:j,onChange:e=>{const t=new Map;for(const a of e)t.set(a.id||a.resourceId,a);l([...t.values()]),v("")},request:n}),!h&&null!==o&&s&&j.length?t.jsx("ul",{className:"private-note-resource-list","aria-label":"Linked Resources",children:j.map(e=>t.jsx("li",{children:e.title||"Resource"},`${e.resourceId}:${e.folderId||""}:${e.objectId||""}`))}):null,h||null===o||!s||j.length||i.length?null:t.jsx("p",{className:"private-note-muted",children:"No Resources are linked to this note."}),!s&&y?t.jsx(ec,{variant:"secondary",onClick:async()=>{g(!0),u(null),v("");try{await n(`/api/employee/notes/personal/${a}/resources`,{method:"PUT",body:JSON.stringify({resourceRefs:j.map(e=>({resourceId:e.id||e.resourceId,objectId:e.objectId||null,folderId:e.folderId||null}))})}),l(j),c(bu(j)),v("Resource links saved.")}catch(e){u(hu(e))}finally{g(!1)}},disabled:p,children:p?"Saving linksâ¦":"Save Resource links"}):null,null!==o&&d?t.jsx("p",{role:"alert",children:d}):null,x?t.jsx("p",{className:"private-note-muted",role:"status",children:x}):null]})}function vu({mode:a,personId:n,personName:s="this person",noteId:r=null,onNoteIdChange:i,onDirtyChange:l}){const{makeAuthRequest:o}=Yn(),c=e.useMemo(()=>function(e,t){return"admin"===e?`/api/admin/personnel/${encodeURIComponent(t)}/notes`:"personal"===e?"/api/employee/notes/personal":"/api/employee/notes/meeting"}(a,n),[a,n]),d="subject"!==a,u="subject"!==a,h="subject"!==a,[m,p]=e.useState([]),[g,f]=e.useState(null),[b,x]=e.useState(Gd),[v,j]=e.useState(eu(Gd)),[y,k]=e.useState(""),[w,N]=e.useState(""),[S,C]=e.useState("admin"===a?"meeting":"general"),[R,E]=e.useState("admin"===a?"meeting":"general"),[I,_]=e.useState((new Date).toISOString().slice(0,10)),[T,A]=e.useState((new Date).toISOString().slice(0,10)),[O,D]=e.useState(r||null),[P,L]=e.useState(Boolean(r)),[$,M]=e.useState(null),[U,F]=e.useState(!0),[z,q]=e.useState(null),[B,W]=e.useState(!1),[V,H]=e.useState(!1),[K,J]=e.useState(!1),[Y,Q]=e.useState(!1),[X,Z]=e.useState(null),[ee,te]=e.useState("No unsaved changes"),[ae,se]=e.useState(null),[re,ie]=e.useState(null),[le,oe]=e.useState(null),[de,ue]=e.useState(null),[he,me]=e.useState(null),[pe,fe]=e.useState(""),[ve,je]=e.useState(!1),[ye,ke]=e.useState(0),we=e.useRef(null),Ne=e.useRef(null),Se=e.useRef(null),Ce=e.useRef(null),Re=e.useRef(null),Ee=e.useRef(!1),Ie=e.useRef(0),_e=e.useRef(0),Te=e.useRef(null),Ae=e.useRef(null),Oe=e.useRef(i),De=e.useCallback(()=>{fe("Some formatting isn't supported in Notes and was removed.")},[]),Pe=!0===g?.isNew,Le=d&&(eu(b)!==v||y!==w||S!==R||"admin"===a&&I!==T),$e=Le||ve;Oe.current=i,Ae.current={dirty:$e,selected:g,requestedNoteId:O,loadedEndpoint:Te.current},e.useEffect(()=>{if(!$e)return;const e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[$e]),e.useEffect(()=>(l?.($e),()=>l?.(!1)),[$e,l]),e.useEffect(()=>{if(!$e)return;const e=e=>{const t=e.target.closest?.("a[href]");if(!t)return;const a=t.getAttribute("href")||"";"_blank"===t.target||a.startsWith("#")||/^[a-z]+:\/\//i.test(a)||window.confirm("Discard your unsaved private-note changes?")||(e.preventDefault(),e.stopPropagation())};return globalThis.document.addEventListener("click",e,!0),()=>globalThis.document.removeEventListener("click",e,!0)},[$e]),e.useEffect(()=>{B||de||X||te(e=>$e?"Unsaved changes":"Unsaved changes"===e?"No unsaved changes":e)},[de,$e,X,B]),e.useEffect(()=>{if(g||O||P||!Ce.current)return;const e=Ce.current;requestAnimationFrame(()=>
2{globalThis.document?.querySelector(`[data-private-note-id="${e}"]`)?.focus(),Ce.current=null})},[P,O,g]);const Ue=e.useCallback(e=>{const t=e.revision.document.document,a=e.note.privateTitle||"",n=e.note.category||"general",s=wc(e.note.meetingDate,"");f(e.note),x(t),j(eu(t)),k(a),N(a),C(n),E(n),_(s),A(s),ie(null),oe(null),ue(null),me(null),M(null),Z(null),fe(""),ke(e=>e+1),te(`Saved · revision ${e.revision.revisionId} · ${gu(e.revision.timestamp)}`)},[]),Fe=e.useCallback(async()=>{const e=++_e.current;F(!0),q(null);try{const t=u?"?archived=all":"",a=await o(`${c}${t}`);if(e!==_e.current)return;p(a.data.notes||[])}catch(t){if(e!==_e.current)return;q(t)}finally{e===_e.current&&F(!1)}},[u,c,o]),ze=e.useCallback(async e=>{const t=++Ie.current;D(e),L(!0),M(null),f(null),Z(null),se(null),ie(null),oe(null);try{const a=await o(`${c}/${encodeURIComponent(e)}`);if(t!==Ie.current)return;Te.current=c,Ue(a.data),requestAnimationFrame(()=>Ne.current?.focus())}catch(a){if(t!==Ie.current)return;M(a)}finally{t===Ie.current&&L(!1)}},[Ue,c,o]);e.useEffect(()=>{Fe()},[Fe]),e.useEffect(()=>{const e=Ae.current,t=r?`${c}:${r}`:null,a=e?.selected?.isNew?null:e?.selected?.id||e?.requestedNoteId||null,n=e?.selected?e.selected.isNew?"new":`${e.loadedEndpoint}:${e.selected.id}`:e?.requestedNoteId?`${c}:${e.requestedNoteId}`:null;if(!e?.selected||t!==n)return e?.dirty&&t!==n&&!window.confirm("Discard your unsaved private-note changes?")?(Ce.current=a,void Oe.current?.(a)):(r?ze(r):(Ie.current+=1,Te.current=null,D(null),L(!1),M(null),f(null),se(null)),()=>{Ie.current+=1})},[c,ze,r]),e.useEffect(()=>{const e=Se.current?.closest(".employee-workspace");if(e)return e.classList.toggle("employee-workspace--note-open",Boolean(g||O)),()=>e.classList.remove("employee-workspace--note-open")},[O,g]);const qe=()=>!$e||window.confirm("Discard your unsaved private-note changes?"),Be=()=>{qe()&&(Ie.current+=1,Te.current=null,D(null),L(!1),M(null),f(null),se(null),ie(null),oe(null),fe(""),i?.(null),Fe())},We=()=>{if(!qe())return;Ie.current+=1,Te.current=null;const e=(new Date).toISOString().slice(0,10);D(null),L(!1),M(null),f({isNew:!0}),x(Gd),j(eu(Gd)),k(""),N(""),C("admin"===a?"meeting":"general"),E("admin"===a?"meeting":"general"),_(e),A(e),Z(null),ue(null),fe(""),ke(e=>e+1),te("Not saved yet"),requestAnimationFrame(()=>Ne.current?.focus())},Ve=async()=>{if(Le&&!Ee.current){Ee.current=!0,W(!0),Z(null),ue(null),te("Savingâ¦");try{const e={idempotencyKey:crypto.randomUUID(),operationId:crypto.randomUUID(),title:y,category:S,meetingDate:"admin"===a?I:null,document:du(b)};let t;Pe?(e.noteId=crypto.randomUUID(),t=await o(c,{method:"POST",body:JSON.stringify(e)})):(e.expectedRevisionId=g.currentRevisionId,e.expectedChecksum=g.contentSha256,t=await o(`${c}/${encodeURIComponent(g.id)}`,{method:"PATCH",body:JSON.stringify(e)}));const n=t.data.note;f(n),j(eu(b)),N(y),E(S),A(I),fe(""),te(`Saved · revision ${n.currentRevisionId} · ${gu(n.updatedAt)}`),Fe(),Pe&&(i?.(n.id),i||await ze(n.id))}catch(e){"PERSON_NOTE_REVISION_CONFLICT"===e.code?(ue(e.details?.details||{}),te("Conflict detected"),requestAnimationFrame(()=>we.current?.focus())):(Z(e),te("Save failed"))}finally{Ee.current=!1,W(!1)}}};Re.current=Ve,e.useEffect(()=>{if(!d||g?.archivedAt)return;const e=e=>{e.shiftKey||e.altKey||(e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()&&(e.preventDefault(),Re.current?.())};return globalThis.document.addEventListener("keydown",e),()=>globalThis.document.removeEventListener("keydown",e)},[d,g?.archivedAt]);const Je=async e=>{if(window.confirm(`Restore revision ${e} as a new current revision?`)){W(!0);try{await o(`${c}/${encodeURIComponent(g.id)}/restore`,{method:"POST",body:JSON.stringify({revisionId:e,idempotencyKey:crypto.randomUUID(),operationId:crypto.randomUUID(),expectedRevisionId:g.currentRevisionId,expectedChecksum:g.contentSha256,title:y,category:S,meetingDate:"admin"===a?I:null})}),await ze(g.id),se(null)}catch(t){Z(t),te("PERSON_NOTE_REVISION_CONFLICT"===t.code?"Conflict detected":"Save failed")}finally{W(!1)}}},Ye="personal"===a?"Personal notes":"Meeting notes",Qe="personal"===a?"Only you can view these notes through TokenWorks.":"subject"===a?"Meeting notes shared with you. You can read the current version only.":`Meeting notes shared with ${s}. Each explicit save creates an authoritative revision.`,Xe="personal"===a?"Self-only access. Ordinary administrators cannot read these notes.":"subject"===a?"Read-only. Only the current revision is shared with you.":`Visible to authorized admins/cofounders and ${s}.`;if(!g&&O){const e=$?{code:$.code,safeMessage:mu($)}:null;return t.jsxs("section",{ref:Se,className:"private-note-workspace","aria-label":"Private note workspace",children:[t.jsx("header",{className:"private-note-workspace__header",children:t.jsxs(ec,{variant:"ghost",onClick:Be,children:[t.jsx(G,{size:17,"aria-hidden":"true"})," Back to notes"]})}),t.jsx(bc,{loading:P,error:e,loadingLabel:"Loading private noteâ¦",errorLabel:pu($),onRetry:()=>ze(O)})]})}return g?t.jsxs("section",{ref:Se,className:"private-note-workspace","aria-label":"Private note workspace",children:[t.jsxs("header",{className:"private-note-workspace__header",children:[t.jsxs(ec,{variant:"ghost",onClick:Be,children:[t.jsx(G,{size:17,"aria-hidden":"true"})," Back to notes"]}),t.jsxs("div",{className:"private-note-heading",children:[t.jsxs("div",{className:"private-note-privacy",children:[t.jsx(xe,{size:17,"aria-hidden":"true"}),t.jsx("span",{children:"personal"===a?"Only you":"subject"===a?"Shared with you · current revision only":`${s} can read the current revision`})]}
2),t.jsx("h2",{ref:Ne,tabIndex:-1,children:Pe?"New private note":y||"Untitled private note"}),t.jsx("p",{children:"admin"===a?s:"personal"===a?"Personal note":"Shared with you"})]}),t.jsxs("div",{className:"private-note-workspace__actions",children:[d?t.jsxs(ec,{variant:"secondary",onClick:We,children:[t.jsx(He,{size:17,"aria-hidden":"true"})," New note"]}):null,h&&!Pe?t.jsxs(ec,{variant:"secondary",onClick:async()=>{const e=Ie.current;Z(null),H(!0);try{const t=await o(`${c}/${encodeURIComponent(g.id)}/history`);if(e!==Ie.current)return;se(t.data.revisions||[])}catch(t){e===Ie.current&&Z(t)}finally{e===Ie.current&&H(!1)}},disabled:V,children:[t.jsx(ge,{size:17,"aria-hidden":"true"}),V?"Loading historyâ¦":"History"]}):null,u&&!Pe?t.jsxs(ec,{variant:"secondary",onClick:async()=>{if(!g?.id||!qe())return;const e=!g.archivedAt;if(!e||window.confirm("Archive this note? Its revision history will be preserved.")){W(!0);try{const t=await o(`${c}/${encodeURIComponent(g.id)}/archive`,{method:"POST",body:JSON.stringify({archived:e})});f(t.data.note),te(e?"Archived":"No unsaved changes"),e&&Be()}catch(t){Z(t),te("Save failed")}finally{W(!1)}}},disabled:B,children:[g.archivedAt?t.jsx(Me,{size:17,"aria-hidden":"true"}):t.jsx(Ke,{size:17,"aria-hidden":"true"}),g.archivedAt?"Restore from archive":"Archive"]}):null,d&&!g.archivedAt?t.jsxs(ec,{className:"private-note-desktop-save",variant:"primary",onClick:Ve,disabled:!Le||B,title:"Save private note (Ctrl/Command+S)",children:[t.jsx(ne,{size:17,"aria-hidden":"true"})," ",B?"Savingâ¦":"Save"]}):null]})]}),t.jsx("p",{ref:we,className:"private-note-save-state"+(de||X?" is-alert":""),role:de||X?"alert":"status","aria-live":"polite",tabIndex:de?-1:void 0,children:g.archivedAt?"Archived · read-only":d?ee:"Read-only"}),t.jsxs("div",{className:"private-note-workspace__body",children:[X?t.jsxs(Xo,{className:"private-note-error",role:"alert",children:[t.jsx(be,{size:20,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:hu(X)}),!Pe&&g.id?t.jsxs(ec,{variant:"secondary",onClick:()=>ze(g.id),children:[t.jsx(ce,{size:16,"aria-hidden":"true"})," Retry"]}):null]})]}):null,de?t.jsxs(Xo,{className:"private-note-conflict",children:[t.jsxs("div",{children:[t.jsx(be,{size:20,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:"Another saved revision is now current."}),t.jsx("p",{children:"Your unsaved draft is still here. It has not been merged or overwritten."})]})]}),t.jsxs("div",{className:"private-note-conflict__actions",children:[t.jsx(ec,{variant:"primary",onClick:async()=>{const e=Ie.current;try{const t=await o(`${c}/${encodeURIComponent(g.id)}`);if(e!==Ie.current)return;me(t.data)}catch(t){e===Ie.current&&Z(t)}},children:"Compare your draft with latest"}),t.jsxs(ec,{variant:"secondary",onClick:async()=>{try{if(!navigator.clipboard?.writeText)throw new Error("clipboard unavailable");await navigator.clipboard.writeText(fu(b).trim()),te("Unsaved content copied")}catch{te("Copy failed"),Z({safeMessage:"Your browser could not copy the draft. The draft remains here."})}},children:[t.jsx(Ge,{size:16,"aria-hidden":"true"})," Copy unsaved content as plain text"]}),t.jsx(ec,{variant:"danger",onClick:()=>{he&&window.confirm("Replace your unsaved draft with the latest saved revision?")&&Ue(he)},disabled:!he,children:"Discard draft and load latest"})]}),de.latestRevisionId?t.jsxs("p",{className:"private-note-muted",children:["Latest revision: ",de.latestRevisionId]}):null]}):null,he?t.jsxs("section",{className:"private-note-compare","aria-label":"Draft and latest comparison",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Your unsaved draft"}),t.jsx(lu,{document:b,readOnly:!0,accessibleLabel:"Your unsaved private-note draft"})]}),t.jsxs("div",{children:[t.jsxs("h3",{children:["Latest saved revision ",he.revision.revisionId]}),t.jsx(lu,{document:he.revision.document.document,readOnly:!0,accessibleLabel:`Latest saved private-note revision ${he.revision.revisionId}`})]})]}):null,ae?t.jsxs("section",{className:"private-note-history","aria-label":"Version history",children:[t.jsxs("header",{children:[t.jsx("h3",{children:"Version history"}),t.jsx(ec,{variant:"ghost",onClick:()=>se(null),children:"Close history"})]}),0===ae.length?t.jsx("p",{className:"private-note-muted",children:"No saved revisions are available."}):null,ae.map((e,n)=>t.jsxs("div",{className:"private-note-history__row",children:[t.jsxs("span",{children:[t.jsxs("strong",{children:["Revision ",e.revisionId]}),t.jsx("small",{children:gu(e.timestamp)}),t.jsx("small",{children:"tokenworks_service"===e.writerKind?"Saved through TokenWorks":"Writer unavailable"})]}),t.jsx(ec,{variant:"ghost",onClick:()=>(async e=>{const t=Ie.current;Z(null),J(!0);try{const a=await o(`${c}/${encodeURIComponent(g.id)}/revisions/${e}`);if(t!==Ie.current)return;ie(a.data),oe(null)}catch(a){t===Ie.current&&Z(a)}finally{t===Ie.current&&J(!1)}})(e.revisionId),disabled:K,"aria-label":`Open revision ${e.revisionId}`,children:K?"Openingâ¦":"Open"}),"admin"===a&&ae[n+1]?t.jsx(ec,{variant:"ghost",onClick:()=>(async(e,t)=>{if("admin"!==a)return;const n=Ie.current;Z(null),Q(!0);try{const a=await o(`${c}/${encodeURIComponent(g.id)}/diff?from=${e}&to=${t}`);if(n!==Ie.current)return;oe(a.data),ie(null)}catch(s){n===Ie.current&&Z(s)}finally{n===Ie.current&&Q(!1)}})(ae[n+1].revisionId,e.revisionId),disabled:Y,"aria-label":`Compare revision ${e.revisionId} with revision ${ae[n+1].revisionId}`,children:Y?"Comparingâ¦":"Compare"}):null,t.jsx(ec,{variant:"ghost",onClick:()=>Je(e.revisionId),disabled:B,"aria-label":`Restore revision ${e.revisionId} as a new revision`,children:"Restore"})]},e.revisionId))]}):null,re?t.jsxs("section",{className:"private-note-history-preview",children:[t.jsxs("header",{children:[t.jsxs("h3",{children:["Revision ",re.revision.revisionId]}),t.jsxs("div",{className:"private-note-history-preview__actions",children:[t.jsx(ec,{variant:"ghost",onClick:()=>ie(null),children:"Close preview"}),t.jsx(ec,{variant:"secondary",onClick:()=>Je(re.revision.revisionId),disabled:B,children:"Restore as new revision"})]})]}),t.jsx(lu,{document:re.revision.document.document,readOnly:!0,accessibleLabel:`Private note revision ${re.revision.revisionId}`})]}):null,le?t.jsxs("section",{className:"private-note-diff","aria-label":"Revision comparison",children:[t.jsxs("header",{children:[t.jsxs("h3",{children:["Revision ",le.fromRevisionId," to ",le.toRevisionId]}),t.jsx(ec,{variant:"ghost",onClick:()=>oe(null),children:"Close comparison"})]}),le.changes.map(e=>t.jsxs("div",{className:`private-note-diff__row is-${e.state}`,children:[t.jsx("strong",{children:Sc(e.state)}),e.before?t.jsxs("p",{children:["Before: ",e.before.text||"Empty block"]}):null,e.after?t.jsxs("p",{children:["After: ",e.after.text||"Empty block"]}):null]},e.index))]}):null,he||re||le?null:t.jsxs("div",{className:"private-note-composer",children:[d?t.jsxs("div",{className:"private-note-metadata",children:[t.jsxs("label",{children:["Title",t.jsx("input",{value:y,onChange:e=>k(e.target.value),maxLength:200,disabled:Boolean(g.archivedAt)})]}),t.jsxs("label",{children:["Category",t.jsx("select",{value:S,onChange:e=>C(e.target.value),disabled:Boolean(g.archivedAt),children:cu.map(e=>t.jsx("option",{value:e,children:Sc(e)},e))})]}),"admin"===a?t.jsxs("label",{children:["Meeting date",t.jsx("input",{type:"date",value:I,onChange:e=>_(e.target.value),disabled:Boolean(g.archivedAt)})]}):null]}):t.jsxs("dl",{className:"private-note-read-metadata",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Category"}),t.jsx("dd",{children:Sc(g.category)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Meeting date"}),t.jsx("dd",{children:wc(g.meetingDate)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Author"}),t.jsx("dd",{children:g.author?.name||"Author unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Current revision"}),t.jsx("dd",{children:g.currentRevisionId})]})]}),pe?t.jsx("p",{className:"private-note-format-notice",role:"status","aria-live":"polite",children:pe}):null,t.jsx(lu,{document:b,readOnly:!d||Boolean(g.archivedAt),onChange:x,onUnsupportedContentStripped:De},`note-editor:${Pe?"new":g.id}:${g.currentRevisionId??"draft"}:${ye}`),"personal"!==a||Pe?null:t.jsx(xu,{noteId:g.id,request:o,readOnly:Boolean(g.archivedAt),onDirtyChange:je})]})]}),d&&!g.archivedAt?t.jsxs("div",{className:"private-note-mobile-save",children:[t.jsx("span",{"aria-live":"polite",children:Le?"Unsaved changes":ve?"Unsaved Resource links":ee.startsWith("Saved ·")?"Saved":ee}),t.jsxs(ec,{variant:"primary",onClick:Ve,disabled:!Le||B,children:[t.jsx(ne,{size:17,"aria-hidden":"true"})," ",B?"Savingâ¦":"Save note"]})]}):null]}):t.jsxs(Yo,{className:"private-notes",title:Ye,description:Qe,actions:d?t.jsxs(ec,{variant:"primary",onClick:We,"aria-label":"personal"===a?"New personal note":"New meeting note",children:[t.jsx(He,{size:17,"aria-hidden":"true"})," New note"]}):null,children:[t.jsxs("div",{className:"private-note-privacy",children:[t.jsx(xe,{size:18,"aria-hidden":"true"}),t.jsx("span",{children:Xe})]}),z?t.jsxs(Xo,{className:"private-note-error",role:"alert",children:[t.jsx(be,{size:20,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:hu(z)}),t.jsxs(ec,{variant:"secondary",onClick:()=>Fe(),children:[t.jsx(ce,{size:16,"aria-hidden":"true"})," Retry"]})]})]}):null,U&&!m.length?t.jsx("p",{className:"private-note-muted",children:"Loading notesâ¦"}):null,U||z||0!==m.length?null:t.jsxs("div",{className:"private-note-empty",children:[t.jsx("p",{children:"subject"===a?"No meeting notes are shared with you.":"No notes yet."}),d?t.jsx(ec,{variant:"secondary",onClick:We,children:"Create your first note"}):null]}),t.jsx("div",{className:"private-note-list",role:"list","aria-label":`${Ye} list`,children:m.map(e=>{const n=e.privateTitle||Sc(e.category);
2return t.jsxs("button",{type:"button","data-private-note-id":e.id,className:"private-note-list-item",onClick:()=>{return t=e.id,Ce.current=t,void(i?i(t):qe()&&ze(t));var t},"aria-label":`Open ${n}`,children:[t.jsx("strong",{children:n}),t.jsxs("span",{children:["admin"===a?`${wc(e.meetingDate)} · `:"",Sc(e.category)," · revision ",e.currentRevisionId]}),t.jsxs("span",{className:"private-note-list-item__meta",children:["Updated ",gu(e.updatedAt),e.archivedAt?" · Archived":"",e.degraded?" · Being repaired":""]})]},e.id)})})]})}function ju({mode:a="personal",notes:n=null,canManageTeamNotes:s=!1,canUseSelfNotes:r=!0,canReadSharedNotes:i=!0,notesAvailable:l=!0,selectedPersonId:o=null,selectedNoteId:c=null,onModeChange:d,onSelectedPersonChange:u,onNoteIdChange:h,onDirtyChange:m}){const{user:p}=Yn(),g=e.useId(),f=e.useRef(null),b=n||{},x=b.available??l,v=Boolean(b.degraded),j=b.canManageTeamNotes??s,y=b.canUsePersonalNotes??r,k=b.canReadSharedNotes??i,w=e.useMemo(()=>[...j?[{id:"team",label:"Team notes"}]:[],...y?[{id:"personal",label:"Personal notes"}]:[],...k?[{id:"shared",label:"Shared with me"}]:[]],[j,y,k]),N=w.some(e=>e.id===a)?a:w.find(e=>"personal"===e.id)?.id||w[0]?.id||null;if(!x)return t.jsx(Yo,{title:"Notes",className:"employee-notes-panel employee-notes-panel--empty",children:t.jsxs(Xo,{className:"employee-notes-unavailable",children:[t.jsx(P,{size:22,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:"Notes are not available yet."}),t.jsx("p",{children:"The Notes service is being set up. Check back soon â your access does not need any action."})]})]})});if(!N)return t.jsx(Yo,{title:"Notes",className:"employee-notes-panel employee-notes-panel--empty",children:t.jsxs(Xo,{className:"employee-notes-unavailable",children:[t.jsx(P,{size:22,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:"Notes aren't available for your Workspace role."}),t.jsx("p",{children:"Personal and meeting notes are for internal Workspace members. If you think this is wrong, contact an administrator."})]})]})});return t.jsxs("section",{className:"employee-panel-grid employee-notes-panel",children:[v?t.jsx("p",{className:"employee-notes-degraded",role:"status",children:"Some Notes features are temporarily degraded. Saved notes are safe."}):null,w.length>1?t.jsx("nav",{ref:f,className:"employee-subsection-tabs",role:"tablist","aria-label":"Workspace notes",onKeyDown:e=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;e.preventDefault();const t=w.findIndex(e=>e.id===N),a="Home"===e.key?0:"End"===e.key?w.length-1:"ArrowRight"===e.key?(t+1)%w.length:(t-1+w.length)%w.length;!1!==d?.(w[a].id)&&requestAnimationFrame(()=>f.current?.querySelectorAll('[role="tab"]')?.[a]?.focus())},children:w.map(e=>t.jsx("button",{type:"button",role:"tab",id:`${g}-${e.id}-tab`,"aria-selected":N===e.id,"aria-controls":`${g}-${e.id}-panel`,tabIndex:N===e.id?0:-1,onClick:()=>d?.(e.id),children:e.label},e.id))}):null,t.jsxs("section",{role:"tabpanel",id:`${g}-${N}-panel`,"aria-labelledby":w.length>1?`${g}-${N}-tab`:void 0,tabIndex:0,children:["shared"===N?t.jsx(vu,{mode:"subject",personId:p.id,personName:p.name||"you",noteId:c,onNoteIdChange:h,onDirtyChange:m}):null,"personal"===N?t.jsx(vu,{mode:"personal",personId:p.id,personName:p.name||"you",noteId:c,onNoteIdChange:h,onDirtyChange:m}):null,"team"===N&&j?t.jsx(yu,{selectedPersonId:o,selectedNoteId:c,onSelectedPersonChange:u,onNoteIdChange:h,onDirtyChange:m}):null]})]})}function yu({selectedPersonId:e,selectedNoteId:a,onSelectedPersonChange:n,onNoteIdChange:s,onDirtyChange:r}){const{data:i,loading:l,error:o,refresh:c}=kc("/api/workspace/v1/people?scope=all",{initialData:{people:[]}}),d=(i?.people||[]).filter(e=>e.hasProfile&&function(e){const t=Array.isArray(e?.roles)?e.roles:[],a=t.some(e=>ku.has(e)),n=e?.status??e?.personnelStatus??null,s=!n||wu.has(n);return t.length?a&&s:s}(e)),u=d.find(t=>t.id===e)||null;return t.jsxs(Yo,{title:"Team meeting notes",description:"Choose a person, then create or revise the meeting notes shared with them.",className:"employee-team-notes",children:[t.jsxs("label",{className:"employee-team-notes__person",children:[t.jsx("span",{children:"Note subject"}),t.jsxs("select",{"aria-label":"Note subject",value:e||"",onChange:e=>n?.(e.target.value||null),children:[t.jsx("option",{value:"",children:"Choose a person"}),d.map(e=>t.jsxs("option",{value:e.id,children:[e.name||"Unnamed",e.personnelType?` · ${Sc(e.personnelType)}`:""]},e.id))]})]}),t.jsx(bc,{loading:l,error:o,isEmpty:!l&&!d.length,loadingLabel:"Loading peopleâ¦",errorLabel:"People could not be loaded",emptyLabel:"No eligible Worksp
2ace members are available for meeting notes.",onRetry:c,children:u?t.jsx(vu,{mode:"admin",personId:u.id,personName:u.name||"this person",noteId:a,onNoteIdChange:s,onDirtyChange:r}):t.jsx(Xo,{children:"Choose a person to view or write their meeting notes."})})]})}const ku=new Set(["intern","staff","employee","admin","cofounder"]),wu=new Set(["onboarding","active","paused"]);const Nu=Object.freeze({singleFileBytes:5*1024**3,interactiveFiles:500,folderFiles:5e3,folderBytes:20*1024**3,fileConcurrency:3,partConcurrency:4,pathDepth:32,zipEntries:1e4,zipExpandedBytes:20*1024**3,zipExpansionRatio:100}),Su=Nu.fileConcurrency,Cu=Nu.partConcurrency,Ru="tokenworks.workspace-resource-upload-sessions.v2",Eu=8388608;function Iu(){return"undefined"==typeof window?"server":window.location.origin}function _u(){try{const e=JSON.parse(localStorage.getItem(Ru)||"[]");if(!Array.isArray(e))return[];const t=Date.now(),a=e.filter(e=>2===e?.version&&e.actorId&&e.environment&&e.packId&&e.uploadId&&e.contentChecksum&&Date.parse(e.expiresAt||"")>t);return a.length!==e.length&&localStorage.setItem(Ru,JSON.stringify(a)),a}catch{return[]}}function Tu({actorId:e,environment:t=Iu()}={}){return _u().filter(a=>(!e||a.actorId===e)&&a.environment===t)}function Au(e,t={}){const{actorId:a,environment:n=Iu()}=t;localStorage.setItem(Ru,JSON.stringify(_u().filter(t=>t.uploadId!==e||a&&t.actorId!==a||t.environment!==n)))}function Ou(e,{folder:t=!1}={}){const a=Array.from(e||[]),n=t?Nu.folderFiles:Nu.interactiveFiles;if(a.length>n)throw new Error(`Select no more than ${n.toLocaleString()} files at once.`);const s=a.reduce((e,t)=>e+Number(t.size||0),0);if(s>Nu.folderBytes)throw new Error("This selection exceeds the 20 GiB upload limit.");for(const r of a){if(Number(r.size||0)>Nu.singleFileBytes)throw new Error(`${r.name} exceeds the 5 GiB per-file limit.`);const e=r.relativePath||r.webkitRelativePath||r.name;if(String(e).split("/").filter(Boolean).length>Nu.pathDepth)throw new Error(`${r.name} exceeds the maximum folder depth of 32.`)}return{files:a,totalBytes:s}}async function Du(e,t){const a=new na;for(let r=0;r<e.size;r+=Eu){t?.throwIfAborted();const n=await e.slice(r,r+Eu).arrayBuffer();a.update(new Uint8Array(n)),await Promise.resolve()}t?.throwIfAborted();const n=await a.digest();let s="";for(const r of new Uint8Array(n))s+=String.fromCharCode(r);return btoa(s)}function Pu(e,t,a,n,s){return new Promise((r,i)=>{const l=new XMLHttpRequest;l.open("PUT",e),Object.entries(a||{}).forEach(([e,t])=>l.setRequestHeader(e,t)),l.upload.addEventListener("progress",e=>{e.lengthComputable&&n(e.loaded,e.total)}),l.addEventListener("load",()=>{l.status>=200&&l.status<300?r({etag:l.getResponseHeader("ETag")}):i(new Error(`S3 upload failed with status ${l.status}`))}),l.addEventListener("error",()=>i(new Error("Network error during S3 upload"))),l.addEventListener("abort",()=>i(new DOMException("Upload cancelled","AbortError")));const o=()=>l.abort();s?.addEventListener("abort",o,{once:!0}),l.addEventListener("loadend",()=>s?.removeEventListener("abort",o)),l.send(t)})}async function Lu(e,t=3){let a;for(let s=0;s<t;s+=1)try{return await e(s)}catch(n){if(a=n,"AbortError"===n?.name||s===t-1)throw n;await new Promise(e=>setTimeout(e,400*2**s))}throw a}async function $u(e,t,a){const n=new Array(e.length);let s=0;return await Promise.all(Array.from({length:Math.min(t,e.length)},async function(){for(;s<e.length;){const t=s;s+=1,n[t]=await a(e[t],t)}})),n}function Mu({request:t,actorId:a,environment:n=Iu(),scope:s="mine",concurrency:r=Su,partConcurrency:i=Cu}){const[l,o]=e.useState([]),c=e.useRef(new Map),d=Math.max(1,Math.min(Number(r)||Su,Nu.fileConcurrency)),u=Math.max(1,Math.min(Number(i)||Cu,Nu.partConcurrency)),h=e.useCallback((e,t)=>{o(a=>a.find(t=>t.key===e)?a.map(a=>a.key===e?{...a,...t}:a):[...a,{key:e,...t}])},[]),m=e.useCallback(async(e,r,i=r.webkitRelativePath||r.name,{archiveMode:l="extract",contentChecksum:o=null}={})=>{const d=`${e}:${i}:${r.size}:${r.lastModified}`,m=new AbortController;let p;c.current.set(d,m),h(d,{name:i,file:r,packId:e,relativePath:i,sizeBytes:r.size,uploadedBytes:0,status:"preparing"});try{const c=o||await Du(r,m.signal);p=await t(`/api/workspace/v1/resource-packs/${e}/uploads?scope=${s}`,{method:"POST",headers:{"Idempotency-Key":crypto.randomUUID()},body:JSON.stringify({filename:r.name,relativePath:i,mimeType:r.type||"application/octet-stream",sizeBytes:r.size,checksumSha256:c,archiveMode:l})});const g=p.data;if(function(e){if(!e.expiresAt||Date.parse(e.expiresAt)<=Date.now())return;const t=_u().filter(t=>t.uploadId!==e.uploadId);t.push(e),localStorage.setItem(Ru,JSON.stringify(t.slice(-100)))}({version:2,actorId:a,environment:n,uploadId:g.uploadId,packId:e,relativePath:i,sizeBytes:r.size,lastModified:r.lastModified,contentChecksum:c,expiresAt:g.expiresAt,archiveMode:l,mode:g.mode}),h(d,{uploadId:g.uploadId,status:"uploading"}),"single"===g.mode)await Lu(()=>Pu(g.uploadUrl,r,g.uploadHeaders,e=>h(d,{uploadedBytes:e}),m.signal)),await t(`/api/workspace/v1/resource-packs/${e}/uploads/${g.uploadId}/complete?scope=${s}`,{method:"POST",body:JSON.stringify({})});else{const a=await t(`/api/workspace/v1/resource-packs/${e}/uploads/${g.uploadId}?scope=${s}`),n=new Map((a.data?.parts||[]).map(e=>[Number(e.partNumber),e])),i=Math.ceil(r.size/g.partSizeBytes),l=Array.from({length:i},(e,t)=>({partNumber:t+1,start:t*g.partSizeBytes,end:Math.min(r.size,(t+1)*g.partSizeBytes)})),o=[...n.values()].reduce((e,t)=>
2e+Number(t.sizeBytes||0),0);h(d,{uploadedBytes:o});const c=new Map,p=await $u(l,u,async a=>{const i=n.get(a.partNumber);if(i)return i;const l=r.slice(a.start,a.end),u=await Du(l,m.signal),p=await t(`/api/workspace/v1/resource-packs/${e}/uploads/${g.uploadId}/parts?scope=${s}`,{method:"POST",body:JSON.stringify({partNumber:a.partNumber,checksumSha256:u})}),f=await Lu(()=>Pu(p.data.uploadUrl,l,p.data.uploadHeaders,e=>{c.set(a.partNumber,e);const t=[...c.values()].reduce((e,t)=>e+t,0);h(d,{uploadedBytes:o+t})},m.signal));if(!f.etag)throw new Error("S3 did not expose the uploaded part ETag");return c.set(a.partNumber,l.size),{partNumber:a.partNumber,etag:f.etag,checksumSha256:u}});await t(`/api/workspace/v1/resource-packs/${e}/uploads/${g.uploadId}/complete?scope=${s}`,{method:"POST",body:JSON.stringify({parts:p})})}return Au(p.data.uploadId,{actorId:a,environment:n}),h(d,{uploadedBytes:r.size,status:"scanning",error:null}),p.data}catch(g){throw h(d,{status:"AbortError"===g?.name?"cancelled":"failed",error:g.safeMessage||g.message||"Upload failed"}),g}finally{c.current.delete(d)}},[a,n,u,t,s,h]),p=e.useCallback(async e=>{if(!e?.file||!e?.uploadId||!e?.packId)return null;const r=new AbortController;let i;c.current.set(e.key,r),h(e.key,{status:"resuming",error:null});try{const a=await t(`/api/workspace/v1/resource-packs/${e.packId}/uploads/${e.uploadId}?scope=${s}`);i=a.data}catch{return await t(`/api/workspace/v1/resource-packs/${e.packId}/uploads/${e.uploadId}?scope=${s}`,{method:"DELETE"}).catch(()=>{}),Au(e.uploadId,{actorId:a,environment:n}),c.current.delete(e.key),m(e.packId,e.file,e.relativePath,{archiveMode:e.archiveMode,contentChecksum:e.contentChecksum})}try{if("completed"===i.state)return Au(e.uploadId,{actorId:a,environment:n}),h(e.key,{uploadedBytes:e.file.size,status:"scanning",error:null}),i;if(h(e.key,{status:"uploading"}),"single"===i.mode){if(!i.uploadUrl)throw new Error("Upload session did not return a resumable URL");await Lu(()=>Pu(i.uploadUrl,e.file,i.uploadHeaders,t=>h(e.key,{uploadedBytes:t}),r.signal)),await t(`/api/workspace/v1/resource-packs/${e.packId}/uploads/${e.uploadId}/complete?scope=${s}`,{method:"POST",body:"{}"})}else{const a=new Map((i.parts||[]).map(e=>[Number(e.partNumber),e])),n=Math.ceil(e.file.size/i.partSizeBytes),l=Array.from({length:n},(t,a)=>({partNumber:a+1,start:a*i.partSizeBytes,end:Math.min(e.file.size,(a+1)*i.partSizeBytes)})),o=[...a.values()].reduce((e,t)=>e+Number(t.sizeBytes||0),0),c=new Map,d=await $u(l,u,async n=>{const l=e.file.slice(n.start,n.end),d=await Du(l,r.signal),u=a.get(n.partNumber);if(u)return{...u,checksumSha256:d};if("completing"===i.state)return{partNumber:n.partNumber,etag:"completion-recovery",checksumSha256:d};const m=await t(`/api/workspace/v1/resource-packs/${e.packId}/uploads/${e.uploadId}/parts?scope=${s}`,{method:"POST",body:JSON.stringify({partNumber:n.partNumber,checksumSha256:d})}),p=await Lu(()=>Pu(m.data.uploadUrl,l,m.data.uploadHeaders,t=>{c.set(n.partNumber,t),h(e.key,{uploadedBytes:o+[...c.values()].reduce((e,t)=>e+t,0)})},r.signal));if(!p.etag)throw new Error("S3 did not expose the uploaded part ETag");return{partNumber:n.partNumber,etag:p.etag,checksumSha256:d}});await t(`/api/workspace/v1/resource-packs/${e.packId}/uploads/${e.uploadId}/complete?scope=${s}`,{method:"POST",body:JSON.stringify({parts:d})})}return Au(e.uploadId,{actorId:a,environment:n}),h(e.key,{uploadedBytes:e.file.size,status:"scanning",error:null}),i}catch(l){throw h(e.key,{status:"AbortError"===l?.name?"cancelled":"failed",error:l.safeMessage||l.message||"Upload failed"}),l}finally{c.current.delete(e.key)}},[a,n,u,t,s,h,m]),g=e.useCallback((e,t)=>{const s=e.relativePath||t.webkitRelativePath||t.name,r=`${e.packId}:${s}:${t.size}:${t.lastModified}`;if(e.actorId!==a||e.environment!==n||Date.parse(e.expiresAt||"")<=Date.now())throw new Error("This upload session cannot be resumed in the current account or environment.");const i={key:r,uploadId:e.uploadId,packId:e.packId,relativePath:s,name:s,sizeBytes:t.size,uploadedBytes:0,status:"resuming",file:t,archiveMode:e.archiveMode,contentChecksum:e.contentChecksum};return h(r,i),p(i)},[a,n,p,h]),f=e.useCallback(async(e,t,{archiveMode:s="extract",folder:r=!1}={})=>{const{files:i}=Ou(t,{folder:r});return $u(i.map(e=>({file:e,relativePath:e.relativePath||e.webkitRelativePath||e.name})),d,async({file:t,relativePath:r})=>{const i=`${e}:${r}:${t.size}:${t.lastModified}`,l=new AbortController;c.current.set(i,l),h(i,{name:r,file:t,packId:e,relativePath:r,sizeBytes:t.size,uploadedBytes:0,status:"preparing"});try{const o=await Du(t,l.signal);c.current.delete(i);const d=Tu({actorId:a,environment:n}).find(a=>a.packId===e&&a.relativePath===r&&Number(a.sizeBytes)===t.size&&Number(a.lastModified)===t.lastModified&&a.contentChecksum===o&&a.archiveMode===s);return{status:"fulfilled",value:d?await g(d,t):await m(e,t,r,{archiveMode:s,contentChecksum:o}),file:t}}catch(o){return c.current.delete(i),h(i,{status:"AbortError"===o?.name?"cancelled":"failed",error:"AbortError"===o?.name?null:o.safeMessage||o.message}),{status:"rejected",reason:o,file:t}}})},[a,n,d,g,h,m]),b=e.useCallback(async e=>{c.current.get(e.key)?.abort(),e.uploadId&&(await t(`/api/workspace/v1/resource-packs/${e.packId}/uploads/${e.uploadId}?scope=${s}`,{method:"DELETE"}).catch(()=>{}),Au(e.uploadId,{actorId:a,environment:n})),h(e.key,{status:"cancelled",error:null})},[a,n,t,s,h]),x=e.useMemo(()=>{const e=l.reduce((e,t)=>
2e+Number(t.sizeBytes||0),0),t=l.reduce((e,t)=>e+Number(t.uploadedBytes||0),0),a=l.reduce((e,t)=>(e.total+=1,"scanning"===t.status||"complete"===t.status?e.succeeded+=1:"failed"===t.status?e.failed+=1:"cancelled"===t.status?e.cancelled+=1:e.active+=1,e),{total:0,active:0,succeeded:0,failed:0,cancelled:0});return{total:e,loaded:t,percent:e?Math.round(t/e*100):0,counts:a}},[l]);return{uploads:l,overall:x,uploadFiles:f,resumeSession:g,retry:p,cancel:b,resumableSessions:Tu({actorId:a,environment:n})}}function Uu({children:e,className:a=""}){return t.jsx("div",{className:`admin-ui-shell ${a}`.trim(),children:e})}function Fu({title:e,description:a,badge:n,actions:s,className:r=""}){return t.jsxs("header",{className:`admin-ui-page-header ${r}`.trim(),children:[t.jsxs("div",{className:"admin-ui-page-header__copy",children:[t.jsx("h1",{children:e}),a?t.jsx("p",{children:a}):null]}),n||s?t.jsxs("div",{className:"admin-ui-page-header__actions",children:[n,s]}):null]})}function zu({children:e,className:a="",ariaLabel:n="List controls"}){return t.jsx("div",{className:`admin-ui-collection-toolbar ${a}`.trim(),role:"group","aria-label":n,children:e})}function qu({children:e,align:a="start",className:n=""}){return t.jsx("div",{className:`admin-ui-action-group admin-ui-action-group--${a} ${n}`.trim(),children:e})}function Bu({children:e,className:a="",minWidth:n="580px",ariaLabel:s="Data table",focusable:r=!0}){return t.jsx("div",{className:"admin-ui-table-wrap",style:{"--admin-table-min-width":n},role:"region","aria-label":s,tabIndex:r?0:void 0,children:t.jsx("table",{className:`admin-ui-table ${a}`.trim(),children:e})})}function Wu({label:e,htmlFor:a,children:n,hint:s,hintId:r,className:i=""}){return t.jsxs("div",{className:`admin-ui-form-field ${i}`.trim(),children:[t.jsx("label",{className:"admin-ui-form-label",htmlFor:a,children:e}),n,s?t.jsx("span",{id:r,className:"admin-ui-form-hint",children:s}):null]})}function Vu({children:e,variant:a="default",className:n=""}){return t.jsx(li,{variant:a,className:`admin-ui-status-badge ${n}`.trim(),children:e})}function Hu({children:e,className:a=""}){return t.jsx("p",{className:`admin-ui-empty-state ${a}`.trim(),children:e})}function Ku({title:e,children:a,tone:n="empty",action:s,className:r=""}){const i="error"===n?"alert":"status";return t.jsxs("div",{className:`admin-ui-collection-state admin-ui-collection-state--${n} ${r}`.trim(),role:i,children:[t.jsx("strong",{children:e}),a?t.jsx("div",{className:"admin-ui-collection-state__copy",children:a}):null,s?t.jsx("div",{className:"admin-ui-collection-state__action",children:s}):null]})}function Gu({total:e,limit:a,offset:n,onOffsetChange:s,onLimitChange:r,pageSizes:i=[20,50,100],label:l="Results",disabled:o=!1}){const c=Math.max(0,Number(e)||0),d=Math.max(1,Number(a)||1),u=Math.max(0,Number(n)||0),h=0===c?0:u+1,m=Math.min(u+d,c),p=Math.floor(u/d)+1,g=Math.max(1,Math.ceil(c/d));return t.jsxs("nav",{className:"admin-ui-pagination","aria-label":`${l} pagination`,children:[t.jsxs("p",{className:"admin-ui-pagination__summary","aria-live":"polite",children:[t.jsxs("strong",{children:[h,"â",m]})," ","of ",c," ",l.toLowerCase()]}),t.jsxs("div",{className:"admin-ui-pagination__controls",children:[r?t.jsxs("label",{className:"admin-ui-pagination__size",children:[t.jsx("span",{children:"Per page"}),t.jsx("select",{value:d,onChange:e=>r(Number(e.target.value)),disabled:o,children:i.map(e=>t.jsx("option",{value:e,children:e},e))})]}):null,t.jsxs("span",{className:"admin-ui-pagination__page",children:["Page ",p," of ",g]}),t.jsx(ds,{type:"button",variant:"secondary",size:"small",disabled:o||0===u,onClick:()=>s(Math.max(0,u-d)),"aria-label":`Previous ${l.toLowerCase()} page`,children:"Previous"}),t.jsx(ds,{type:"button",variant:"secondary",size:"small",disabled:o||u+d>=c,onClick:()=>s(u+d),"aria-label":`Next ${l.toLowerCase()} page`,children:"Next"})]})]})}function Ju({children:e,className:a="",...n}){return t.jsx(Ss,{className:`admin-ui-modal ${a}`.trim(),...n,children:e})}function Yu({children:e,className:a=""}){return t.jsx("div",{className:`admin-ui-modal-body ${a}`.trim(),children:e})}function Qu({children:e,className:a=""}){return t.jsx("div",{className:`admin-ui-modal-actions ${a}`.trim(),children:e})}function Xu({loading:e=!1,children:a,disabled:n,...s}){return t.jsx(ds,{disabled:n||e,...s,children:e?"Working...":a})}function Zu({endpoint:t,request:a,search:n,dataKey:s,fallbackDataKey:r=null}){const[i,l]=e.useState([]),[o,c]=e.useState(!1),[d,u]=e.useState(!1),[h,m]=e.useState(!1),[p,g]=e.useState(null),f=e.useRef([]),b=e.useRef(0);e.useEffect(()=>{f.current=i},[i]);const x=e.useCallback(async({append:e=!1}={})=>{const i=++b.current;e?u(!0):c(!0),g(null);try{const o=new URLSearchParams({limit:String(51),offset:e?String(f.current.length):"0"});n&&o.set("search",n);const c=t.includes("?")?"&":"?",d=await a(`${t}${c}${o.toString()}`);if(i!==b.current)return;const u=d.data?.[s]||(r?d.data?.[r]:null)||[],h=u.slice(0,50);
2l(e?[...f.current,...h]:h),m(u.length>50)}catch(o){if(i!==b.current)return;g(o.message||`Unable to load ${s}`)}finally{i===b.current&&(e?u(!1):c(!1))}},[s,t,r,a,n]);return e.useEffect(()=>{x()},[x]),{items:i,loading:o,loadingMore:d,hasMore:h,error:p,retry:x,loadMore:()=>x({append:!0})}}function eh({value:a=[],onChange:n,multiple:s=!1,label:r="Projects",endpoint:i="/api/admin/projects",allowedRoles:l=[]}){const{makeAuthRequest:o}=Yn(),c=e.useId(),[d,u]=e.useState(""),h=e.useMemo(()=>new Set(a.map(e=>e.projectId||e.id)),[a]),{items:m,loading:p,loadingMore:g,hasMore:f,error:b,retry:x,loadMore:v}=Zu({endpoint:i,request:o,search:d,dataKey:"projects"}),j=e.useMemo(()=>m.filter(e=>!e.archivedAt),[m]),y=[...a.filter(e=>!j.some(t=>t.id===(e.projectId||e.id))).map(e=>({...e,id:e.projectId||e.id})),...j];return t.jsxs("div",{className:"project-picker admin-picker",children:[t.jsxs("label",{children:[t.jsx("span",{children:r}),t.jsx("input",{value:d,onChange:e=>u(e.target.value),placeholder:"Search projects"})]}),p?t.jsx("p",{children:"Loading projects..."}):null,b?t.jsxs("div",{className:"admin-picker__error",role:"alert",children:[t.jsx("p",{className:"admin-workspace-error",children:b}),t.jsx(Xu,{type:"button",variant:"secondary",onClick:x,children:"Retry projects"})]}):null,p||b||y.length?null:t.jsx(Hu,{children:"No projects found."}
2),t.jsx("div",{className:"project-picker-list admin-picker__results",role:"group","aria-label":`${r} results`,children:y.map(e=>{const r=a.find(t=>(t.projectId||t.id)===e.id);return t.jsxs("div",{className:"project-picker-option",children:[t.jsxs("label",{className:"project-picker-option__selection",htmlFor:`${c}-${e.id}`,children:[t.jsx("input",{id:`${c}-${e.id}`,name:s?void 0:`${c}-selection`,type:s?"checkbox":"radio",checked:h.has(e.id),onChange:()=>(e=>{if(h.has(e.id))return void n(a.filter(t=>(t.projectId||t.id)!==e.id));const t={projectId:e.id,id:e.id,name:e.name,status:e.status,priority:e.priority,owner:e.owner,projectRole:l[0]||e.projectRole||"contributor"};n(s?[...a,t]:[t])})(e)}),t.jsxs("span",{children:[t.jsx("strong",{children:e.name}),t.jsx("small",{children:[e.status,e.priority,e.owner?.name].filter(Boolean).join(" · ")})]})]}),r&&l.length?t.jsx("select",{"aria-label":`Project role for ${e.name}`,value:r.projectRole||l[0],onChange:t=>{return s=e.id,r=t.target.value,void n(a.map(e=>(e.projectId||e.id)===s?{...e,projectRole:r}:e));var s,r},children:l.map(e=>t.jsx("option",{children:e},e))}):null]},e.id)})}),f?t.jsx(Xu,{type:"button",variant:"secondary",disabled:g,onClick:v,children:g?"Loading more...":"Load more projects"}):null]})}function th({value:a=[],onChange:n,allowedRoles:s=[],multiple:r=!0,label:i="Teams",endpoint:l="/api/admin/teams",disabled:o=!1}){const{makeAuthRequest:c}=Yn(),d=e.useId(),[u,h]=e.useState(""),m=e.useMemo(()=>new Map(a.map(e=>[e.teamId,e])),[a]),{items:p,loading:g,loadingMore:f,hasMore:b,error:x,loadMore:v}=Zu({endpoint:l,request:c,search:u,dataKey:"teams"}),j=[...a.filter(e=>!p.some(t=>t.id===e.teamId)).map(e=>({id:e.teamId,name:e.name,description:e.description,members:Array.from({length:e.memberCount||0}),memberCount:e.memberCount||0})),...p];return t.jsxs("div",{className:"project-picker",children:[t.jsxs("label",{children:[t.jsx("span",{children:i}),t.jsx("input",{value:u,onChange:e=>h(e.target.value),placeholder:"Search teams",disabled:o})]}),g?t.jsx("p",{children:"Loading teams..."}):null,x?t.jsx("p",{className:"admin-workspace-error",children:x}):null,g||j.length?null:t.jsx(Hu,{children:"No teams found."}),t.jsx("div",{className:"project-picker-list",children:j.map(e=>{const i=m.get(e.id);return t.jsxs("div",{className:"project-picker-option",children:[t.jsxs("label",{className:"project-picker-option__selection",htmlFor:`${d}-${e.id}`,children:[t.jsx("input",{id:`${d}-${e.id}`,name:r?void 0:`${d}-selection`,type:r?"checkbox":"radio",checked:Boolean(i),onChange:()=>(e=>{if(o)return;if(m.get(e.id))return void n(a.filter(t=>t.teamId!==e.id));const t={teamId:e.id,projectRole:s[0]||"contributor",name:e.name,description:e.description,memberCount:e.memberCount||e.members?.length||0};n(r?[...a,t]:[t])})(e),disabled:o}),t.jsxs("span",{children:[t.jsx("strong",{children:e.name}),t.jsxs("small",{children:[e.memberCount||e.members?.length||0," members",e.description?` · ${e.description}`:""]})]})]}),i&&s.length?t.jsx("select",{"aria-label":`Project role for ${e.name}`,value:i.projectRole,onChange:t=>{return s=e.id,r=t.target.value,void(o||n(a.map(e=>e.teamId===s?{...e,projectRole:r}:e)));var s,r},disabled:o,children:s.map(e=>t.jsx("option",{children:e},e))}):null]},e.id)})}),b?t.jsx(Xu,{variant:"secondary",disabled:o||f,onClick:v,children:f?"Loading more...":"Load more teams"}):null]})}function ah({value:a=[],onChange:n,allowedRoles:s=[],multiple:r=!0,allowEmpty:i=!1,emptyLabel:l="Unassigned",label:o="People",excludeUserIds:c=[],filterPerson:d=null,endpoint:u="/api/admin/personnel",request:h=null,disabled:m=!1}){const{makeAuthRequest:p}=Yn(),g=h||p,f=e.useId(),[b,x]=e.useState(""),v=e.useMemo(()=>new Map(a.map(e=>[e.userId,e])),[a]),{items:j,loading:y,loadingMore:k,hasMore:w,error:N,retry:S,loadMore:C}=Zu({endpoint:u,request:g,search:b,dataKey:"personnel",fallbackDataKey:"people"}),R=e.useMemo(()=>j.filter(e=>!e.status||["onboarding","active","paused"].includes(e.status)),[j]),E=[...a.filter(e=>!R.some(t=>t.id===e.userId)).map(e=>({id:e.userId,name:e.name,title:e.title,personnelType:e.personnelType,status:e.status})),...R.filter(e=>!c.includes(e.id)&&(!d||d(e)))];return t.jsxs("div",{className:"project-picker admin-picker",children:[t.jsxs("label",{children:[t.jsx("span",{children:o}),t.jsx("input",{value:b,onChange:e=>x(e.target.value),placeholder:"Search people",disabled:m})]}),y?t.jsx("p",{children:"Loading people..."}):null,N?t.jsxs("div",{className:"admin-picker__error",role:"alert",children:[t.jsx("p",{className:"admin-workspace-error",children:N}),t.jsx(Xu,{type:"button",variant:"secondary",onClick:S,disabled:m,children:"Retry people"})]}):null,y||N||E.length?null:t.jsx(Hu,{children:"No eligible personnel found."}
2),t.jsxs("div",{className:"project-picker-list admin-picker__results",role:"group","aria-label":`${o} results`,children:[!r&&i?t.jsx("div",{className:"project-picker-option",children:t.jsxs("label",{className:"project-picker-option__selection",htmlFor:`${f}-unassigned`,children:[t.jsx("input",{id:`${f}-unassigned`,name:`${f}-selection`,type:"radio",checked:!a.length,onChange:()=>n([]),disabled:m}),t.jsx("span",{children:t.jsx("strong",{children:l})})]})}):null,E.map(e=>{const i=v.get(e.id);return t.jsxs("div",{className:"project-picker-option",children:[t.jsxs("label",{className:"project-picker-option__selection",htmlFor:`${f}-${e.id}`,children:[t.jsx("input",{id:`${f}-${e.id}`,name:r?void 0:`${f}-selection`,type:r?"checkbox":"radio",checked:Boolean(i),onChange:()=>(e=>{if(m)return;if(v.get(e.id))return void n(a.filter(t=>t.userId!==e.id));const t={userId:e.id,projectRole:s[0]||"contributor",name:e.name,title:e.title,personnelType:e.personnelType,status:e.status};n(r?[...a,t]:[t])})(e),disabled:m}),t.jsxs("span",{children:[t.jsx("strong",{children:e.name||"Unnamed"}),t.jsx("small",{children:[e.title,e.personnelType,e.status].filter(Boolean).join(" · ")})]})]}),i&&s.length?t.jsx("select",{"aria-label":`Project role for ${e.name||"Unnamed"}`,value:i.projectRole,onChange:t=>{return s=e.id,r=t.target.value,void(m||n(a.map(e=>e.userId===s?{...e,projectRole:r}:e)));var s,r},disabled:m,children:s.map(e=>t.jsx("option",{children:e},e))}):null]},e.id)})]}),w?t.jsx(Xu,{type:"button",variant:"secondary",disabled:m||k,onClick:C,children:k?"Loading more...":"Load more people"}):null]})}function nh({resource:a,request:n,onSaved:s,assignmentsEndpoint:r,peopleEndpoint:i,teamsEndpoint:l,projectsEndpoint:o,capabilityLevels:c=!1}){const[d,u]=e.useState(!1),[h,m]=e.useState([]),[p,g]=e.useState([]),[f,b]=e.useState([]),[x,v]=e.useState(!1),[j,y]=e.useState("idle"),[k,w]=e.useState(0),[N,S]=e.useState(null),[C,R]=e.useState(null),E=e.useRef(0),I=e.useCallback(e=>{u(Boolean(e.allInternal??a?.isAllInternal)),m((e.users||[]).map(e=>({userId:e.id||e.userId||e.subjectId,name:e.name||e.subjectName,pictureUrl:e.pictureUrl,capability:e.capability||"viewer"}))),g((e.teams||[]).map(e=>({teamId:e.id||e.teamId||e.subjectId,name:e.name||e.subjectName,memberCount:e.memberCount,capability:e.capability||"viewer"}))),b((e.projects||[]).map(e=>({projectId:e.id||e.projectId,id:e.id||e.projectId,name:e.name,status:e.status})))},[a?.isAllInternal]);if(e.useEffect(()=>{const e=a?.id,t=++E.current,s=new AbortController;return u(!1),m([]),g([]),b([]),R(null),S(null),e?(y("loading"),n(r,{signal:s.signal}).then(e=>{if(t!==E.current)return;const a=e?.data?.assignments;if(!a||!Array.isArray(a.users)||!Array.isArray(a.teams)||o&&!Array.isArray(a.projects))throw new Error("The assignment response was incomplete.");I({...a,allInternal:e?.data?.isAllInternal??a.allInternal,projects:a.projects||[]}),y("ready")}).catch(e=>{s.signal.aborted||t!==E.current||(y("error"),S(e.safeMessage||e.message||"Current assignments could not be loaded."))}),()=>{s.abort(),E.current+=1}):(y("idle"),()=>s.abort())},[I,r,k,o,n,a?.id]),!a)return null;return t.jsxs("section",{className:"admin-workspace-detail",children:[t.jsx("h3",{children:"Assignments"}),"loading"===j?t.jsx(oc,{children:"Loading current assignmentsâ¦"}):null,N?t.jsx(oc,{type:"error",children:N}):null,"error"===j?t.jsx(ec,{variant:"ghost",onClick:()=>w(e=>e+1),children:"Retry assignments"}):null,C?t.jsx(oc,{type:"success",children:C}
2):null,t.jsxs(ic,{legend:"Workspace access",description:"Assignments supplement the existing protected resource access checks.",disabled:"ready"!==j||x,children:[t.jsxs("label",{className:"resources-admin-all-access",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:e=>u(e.target.checked)}),t.jsx("span",{children:"All internal users"})]}),t.jsx(ah,{label:"Assigned people",value:h,onChange:m,endpoint:i}),c&&h.length?t.jsx("div",{className:"resources-admin-capability-list","aria-label":"People permission levels",children:h.map(e=>t.jsxs("label",{children:[t.jsx("span",{children:e.name||"Workspace member"}),t.jsxs("select",{"aria-label":`Permission level for ${e.name||"Workspace member"}`,value:e.capability||"viewer",onChange:t=>m(a=>a.map(a=>a.userId===e.userId?{...a,capability:t.target.value}:a)),children:[t.jsx("option",{value:"viewer",children:"Viewer"}),t.jsx("option",{value:"editor",children:"Editor"}),t.jsx("option",{value:"manager",children:"Manager"})]})]},e.userId))}):null,t.jsx(th,{label:"Assigned teams",value:p,onChange:g,endpoint:l}),c&&p.length?t.jsx("div",{className:"resources-admin-capability-list","aria-label":"Team permission levels",children:p.map(e=>t.jsxs("label",{children:[t.jsx("span",{children:e.name||"Workspace team"}),t.jsxs("select",{"aria-label":`Permission level for ${e.name||"Workspace team"}`,value:e.capability||"viewer",onChange:t=>g(a=>a.map(a=>a.teamId===e.teamId?{...a,capability:t.target.value}:a)),children:[t.jsx("option",{value:"viewer",children:"Viewer"}),t.jsx("option",{value:"editor",children:"Editor"}),t.jsx("option",{value:"manager",children:"Manager"})]})]},e.teamId))}):null,o?t.jsx(eh,{label:"Assigned projects",value:f,onChange:b,multiple:!0,endpoint:o}):null]}),t.jsx(lc,{children:t.jsx(ec,{variant:"primary",onClick:async()=>{const e=a.id;if("ready"===j&&!x&&e){v(!0),S(null),R(null);try{const t=c?{metadataVersion:a.metadataVersion,isAllInternal:d,users:h.map(e=>({userId:e.userId,capability:e.capability||"viewer"})),teams:p.map(e=>({teamId:e.teamId,capability:e.capability||"viewer"}))}:{isAllInternal:d,userIds:h.map(e=>e.userId),teamIds:p.map(e=>e.teamId),projectIds:f.map(e=>e.projectId||e.id)};if(await n(r,{method:"PUT",body:JSON.stringify(t)}),e!==a.id)return;R("Resource assignments saved."),await(s?.()),w(e=>e+1)}catch(t){S(t.safeMessage||t.message||"Unable to save assignments.")}finally{v(!1)}}},disabled:"ready"!==j||x,children:x?"Saving assignmentsâ¦":"Save Assignments"})})]})}const sh=/^[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/u,rh=/^[A-Za-z0-9_-]{43}$/u;function ih(e){const t=String(e||"").normalize("NFKC");return t&&!t.startsWith(".")&&!/[\\/\p{Cc}\p{Cf}]/u.test(t)&&t.toLowerCase().endsWith(".ipynb")&&(new TextEncoder).encode(t).length<=240?t:"notebook.ipynb"}function lh({enabled:e,sourceFilename:n,versionId:s,buttonLabel:r="Import private copy"}){const{makeAuthRequest:i}=Yn(),[l,o]=a.useState(!1),[c,d]=a.useState(()=>ih(n)),[u,h]=a.useState("fail"),[m,p]=a.useState(!1),[g,f]=a.useState(!1),[b,x]=a.useState(!1),[v,j]=a.useState(null),[y,k]=a.useState(null),w=a.useRef(null);if(a.useEffect(()=>{d(ih(n)),h("fail"),p(!1),f(!1),o(!1),j(null),k(null),w.current=null},[n,s]),!e||!s)return null;const N=()=>{w.current=null,j(null),k(null)},S=()=>
2{b||(o(!1),f(!1),k(null),j(null),w.current=null)};return t.jsxs(t.Fragment,{children:[t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>o(!0),children:r}),t.jsxs(cc,{isOpen:l,onClose:S,variant:"modal",title:"Import an independent notebook copy",description:"Choose the destination for a private one-use import.",closeLabel:"Close notebook import",closeOnBackdrop:!b,children:[t.jsxs("div",{className:"jupyter-snapshot-warning",role:"note",children:[t.jsx("strong",{children:"Review before running cells."}),t.jsx("p",{children:"This creates a private, independent copy. It will not update automatically, and later revocation will not remove it. Notebook code and saved outputs are untrusted."})]}),t.jsxs("form",{className:"jupyter-snapshot-form",onSubmit:async e=>{e.preventDefault(),j(null),k(null);const t=function(){const e=window.open("","_blank");return e?(e.opener=null,e.document.title="Preparing notebook importâ¦",e.document.body.textContent="TokenWorks is preparing a one-use notebook importâ¦",e):null}();if(t){x(!0);try{w.current||=crypto.randomUUID();const e=await i(`/api/employee/jupyter/versions/${s}/import-claims`,{method:"POST",headers:{"Idempotency-Key":w.current},body:JSON.stringify({requestedFilename:c,collisionBehavior:u,collisionConfirmed:m})}),a=e.data?.claim,n=function(e){try{const t=new URL(String(e||"")),a=new URL(t.searchParams.get("next")||""),n=[...t.searchParams.keys()].sort();return"https:"!==t.protocol||t.username||t.password||t.hash||"grant,next"!==n.join(",")||!rh.test(t.searchParams.get("grant")||"")||"https:"!==a.protocol||a.username||a.password||a.search||a.hash||"/tokenworks-import/"!==a.pathname||a.port!==t.port||!a.hostname.endsWith(`.${t.hostname}`)?null:t.toString()}catch{return null}}(e.data?.launchUrl);if(!sh.test(String(a||""))||!n)throw new Error("Jupyter returned an invalid import response.");if(t.closed)throw new Error("The Jupyter import window was closed.");t.name=JSON.stringify({type:"tokenworks-notebook-import",claim:a}),t.location.replace(n),k("Jupyter opened. Review the warning there, then confirm the one-use private import."),w.current=null}catch(a){t.closed||t.close(),j(a.safeMessage||a.message||"The notebook import could not start.")}finally{x(!1)}}else j("Allow pop-ups for TokenWorks, then try the import again.")},children:[t.jsx(rc,{label:"Destination filename",required:!0,children:t.jsx("input",{type:"text",value:c,maxLength:240,onChange:e=>{d(e.target.value),N()}})}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:"If that filename already exists"}),t.jsxs("label",{className:"jupyter-snapshot-acknowledgement",children:[t.jsx("input",{type:"radio",name:`jupyter-import-collision-${s}`,checked:"fail"===u,onChange:()=>{h("fail"),p(!1),N()}}),t.jsx("span",{children:"Stop without changing the existing file"})]}),t.jsxs("label",{className:"jupyter-snapshot-acknowledgement",children:[t.jsx("input",{type:"radio",name:`jupyter-import-collision-${s}`,checked:"suffix"===u,onChange:()=>{h("suffix"),p(!1),N()}}),t.jsx("span",{children:"Create a numbered copy"})]}),"suffix"===u?t.jsxs("label",{className:"jupyter-snapshot-acknowledgement",children:[t.jsx("input",{type:"checkbox",checked:m,onChange:e=>{p(e.target.checked),N()}}),t.jsx("span",{children:"I confirm TokenWorks may choose a numbered destination filename."})]}):null]}),t.jsxs("label",{className:"jupyter-snapshot-acknowledgement",children:[t.jsx("input",{type:"checkbox",checked:g,onChange:e=>f(e.target.checked)}),t.jsx("span",{children:"I understand this is an independent copy containing untrusted content."})]}),v?t.jsx(oc,{type:"error",children:v}):null,y?t.jsx(oc,{type:"success",children:y}):null,t.jsxs(lc,{children:[t.jsx(ec,{type:"button",variant:"ghost",onClick:S,disabled:b,children:"Close"}),t.jsx(ec,{variant:"primary",type:"submit",disabled:b||!g||!c||"suffix"===u&&!m,children:b?"Preparing importâ¦":"Continue in Jupyter"})]})]})]})]})}const oh="application/x-tokenworks-workspace-resource";function ch({label:a,items:n}){const[s,r]=e.useState(!1),i=e.useId(),l=e.useRef(null),o=e.useRef(null),c=e.useRef(null);e.useEffect(()=>{if(!s)return;const e=e=>{l.current?.contains(e.target)||r(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),r(!1),o.current?.focus())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[s]);return t.jsxs("div",{className:"resource-explorer-menu",ref:l,children:[t.jsx(ec,{ref:o,iconOnly:!0,size:"compact",variant:"ghost","aria-label":a,"aria-haspopup":"menu","aria-expanded":s,"aria-controls":s?i:void 0,onClick:()=>r(e=>!e),onKeyDown:e=>
2{["ArrowDown","ArrowUp"].includes(e.key)&&(e.preventDefault(),r(!0),((e="first")=>{requestAnimationFrame(()=>{const t=Array.from(c.current?.querySelectorAll('[role="menuitem"]')||[]);("last"===e?t.at(-1):t[0])?.focus()})})("ArrowUp"===e.key?"last":"first"))},children:t.jsx(Ze,{size:18,"aria-hidden":"true"})}),s?t.jsx("div",{ref:c,id:i,className:"resource-explorer-menu__popover",role:"menu","aria-label":a,onKeyDown:e=>{const t=Array.from(c.current?.querySelectorAll('[role="menuitem"]')||[]);if(!t.length||!["ArrowDown","ArrowUp","Home","End"].includes(e.key))return;e.preventDefault();const a=Math.max(0,t.indexOf(document.activeElement));t["Home"===e.key?0:"End"===e.key?t.length-1:"ArrowDown"===e.key?(a+1)%t.length:(a-1+t.length)%t.length].focus()},children:n.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:e.danger?"is-danger":void 0,onClick:()=>{r(!1),e.onSelect()},children:[e.icon,t.jsx("span",{children:e.label})]},e.label))}):null]})}function dh(e,t){const a=new Set([t]);let n=!0;for(;n;)n=!1,e.forEach(e=>{e.parentFolderId&&a.has(e.parentFolderId)&&!a.has(e.id)&&(a.add(e.id),n=!0)});return a}function uh(e){return e.mimeType?.startsWith("image/")?"Image":"application/pdf"===e.mimeType?"PDF":"application/zip"===e.mimeType?"ZIP":e.fileExtension?.replace(".","").toUpperCase()||"File"}function hh({resource:n,resources:s=[],request:r,admin:i,scope:l="mine",folderId:o,onFolderChange:c,onBackToLibrary:d,onChanged:u,onError:h,onFolderPathChange:m,onUploadFiles:p,onUploadFolder:f,onUploadZip:b,onDownloadAll:x,onOpenDetails:v,onDropFiles:j}){const[y,k]=e.useState(""),[w,N]=e.useState("name"),[S,C]=e.useState(()=>new Set),[R,E]=e.useState(null),[I,_]=e.useState(!1),[T,A]=e.useState(null),[O,D]=e.useState(""),[P,L]=e.useState(null),[$,M]=e.useState(""),[U,F]=e.useState(null),[z,q]=e.useState(null),[B,W]=e.useState(!1),[V,K]=e.useState(null),[X,ae]=e.useState(null),[ne,se]=e.useState(()=>n.objects||[]),[re,ie]=e.useState(()=>n.folders||[]),[le,oe]=e.useState([]),[ce,de]=e.useState(!1),[he,me]=e.useState(null),[pe,ge]=e.useState({objects:null,folders:null}),fe=e.useRef(null),be=e.useRef(null),xe=n.effectiveAccess||n.capabilities||{},ve=Boolean(xe.canOrganize??xe.canEditResource??i),je=Boolean(xe.canEditContent??xe.canUploadResource??i),ye=Boolean(xe.canTrashContent??xe.canArchiveResource??i),ke=e.useMemo(()=>s.filter(e=>{const t=e.effectiveAccess||e.capabilities||{};return e.id!==n.id&&!["archived","trashed","deleting","deleted"].includes(e.status)&&Boolean(t.canOrganize??t.canEditResource??i)}),[i,n.id,s]),we=ne,Ne=e.useMemo(()=>{const e=new Map;return[...le,...re].forEach(t=>e.set(t.id,t)),[...e.values()]},[le,re]),Se=e.useMemo(()=>new Map(Ne.map(e=>[e.id,e])),[Ne]),Ce=e.useCallback(e=>{const t=[],a=new Set;let n=e?Se.get(e):null;for(;n&&!a.has(n.id);)a.add(n.id),t.unshift(n),n=n.parentFolderId?Se.get(n.parentFolderId):null;return t},[Se]),Re=e.useCallback(e=>Ce(e).map(e=>e.name).join("/"),[Ce]),Ee=o?Se.get(o):null,Ie=Ce(o);e.useEffect(()=>{const e=new AbortController,t=window.setTimeout(async()=>{de(!0),me(null);const t=new URLSearchParams({scope:l,limit:"100"});y.trim()?t.set("search",y.trim()):o&&t.set("folderId",o);const a=new URLSearchParams(t);a.delete("folderId"),!y.trim()&&o&&a.set("parentFolderId",o);try{const[s,i,c]=await Promise.all([r(`/api/workspace/v1/resource-packs/${n.id}/folders?${a}`,{signal:e.signal}),r(`/api/workspace/v1/resource-packs/${n.id}/objects?${t}`,{signal:e.signal}),o?r(`/api/workspace/v1/resource-packs/${n.id}/folders?scope=${l}&ancestorsOf=${o}`,{signal:e.signal}):Promise.resolve({data:{folders:[]}})]);Array.isArray(s.data?.folders)&&ie(s.data.folders),Array.isArray(i.data?.objects)&&se(i.data.objects),Array.isArray(c.data?.folders)&&oe(c.data.folders),ge({folders:s.data?.pagination||null,objects:i.data?.pagination||null})}catch(s){"AbortError"!==s?.name&&me(s.safeMessage||s.message||"Folder contents could not be loaded.")}finally{e.signal.aborted||de(!1)}},y.trim()?250:0);return()=>{window.clearTimeout(t),e.abort()}},[o,r,n.contentVersion,n.id,l,y]),e.useEffect(()=>{C(new Set),E(null)},[o,n.id,y]),e.useEffect(()=>{m?.(Re(o))},[o,Re,m]),e.useEffect(()=>{if(!I)return;const e=e=>{fe.current?.contains(e.target)||_(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),_(!1),be.current?.focus())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[I]);const _e=e.useMemo(()=>{const e=y.trim().toLocaleLowerCase(),t=e?Ne.filter(t=>Re(t.id).toLocaleLowerCase().includes(e)):Ne.filter(e=>(e.parentFolderId||null)===(o||null)),a=e?we.filter(t=>String(t.relativePath||t.originalFilename).toLocaleLowerCase().includes(e)):we.filter(e=>(e.folderId||null)===(o||null)),n=(e,t,a)=>{if("updated"===w)return new Date(t.updatedAt||0).getTime()-new Date(e.updatedAt||0).getTime();if("size"===w&&"file"===a)return Number(t.sizeBytes||0)-Number(e.sizeBytes||0);if("type"===w&&"file"===a)return uh(e).localeCompare(uh(t))||e.originalFilename.localeCompare(t.originalFilename);const n="folder"===a?e.name:e.originalFilename,s="folder"===a?t.name:t.originalFilename;return n.localeCompare(s,void 0,{sensitivity:"base"})};return{folders:[...t].sort((e,t)=>
2n(e,t,"folder")),files:[...a].sort((e,t)=>n(e,t,"file")),searching:Boolean(e)}},[o,Re,Ne,we,y,w]),Te=e.useMemo(()=>[..._e.folders.map(e=>({...e,kind:"folder"})),..._e.files.map(e=>({...e,kind:"file"}))],[_e.files,_e.folders]),Ae=e=>`${e.kind}:${e.id}`,Oe=e.useMemo(()=>Te.filter(e=>S.has(Ae(e))),[S,Te]),De=(e,t={})=>{const a=Ae(e),n=Te.map(Ae);C(e=>{if(t.shiftKey&&R&&n.includes(R)){const e=n.indexOf(R),t=n.indexOf(a);return new Set(n.slice(Math.min(e,t),Math.max(e,t)+1))}if(t.ctrlKey||t.metaKey){const t=new Set(e);return t.has(a)?t.delete(a):t.add(a),t}return new Set([a])}),E(a)},Pe=async(e,t=null,a=Oe)=>{const s=a.map(e=>({kind:e.kind,id:e.id,metadataVersion:e.metadataVersion}));if(!s.length)return!1;const r=await $e(`/api/workspace/v1/resource-packs/${n.id}/batch`,{method:"POST",body:JSON.stringify({action:e,items:s,destinationFolderId:t})});return r&&(C(new Set),E(null)),r},Le=e.useMemo(()=>{const e=[],t=(a,n)=>{Ne.filter(e=>(e.parentFolderId||null)===a).sort((e,t)=>e.name.localeCompare(t.name)).forEach(a=>{e.push({folder:a,depth:n}),t(a.id,n+1)})};return t(null,0),e},[Ne]),$e=async(e,t)=>{W(!0),q(null),h?.(null);try{return await r(`${e}${e.includes("?")?"&":"?"}scope=${l}`,t),await u(),!0}catch(a){const e=a.safeMessage||a.message||"Resource could not be changed.";return q(e),h?.(e),!1}finally{W(!1)}},Me=async(e,t)=>{try{h?.(null);const a=await r(`/api/workspace/v1/resource-packs/${n.id}/objects/${e.id}/access`,{method:"POST",body:JSON.stringify({preview:t})});window.open(a.data.url,t?"_blank":"_self","noopener,noreferrer")}catch(a){h?.(a.safeMessage||a.message||"The file could not be opened.")}},Ue=(e,t=null)=>{A({type:e,item:t}),D("rename"===e&&(t?.name||t?.originalFilename)||""),L(["move","batch-move"].includes(e)?t?.parentFolderId??t?.folderId??o??null:o||null),M("cross-move"===e&&ke[0]?.id||""),F(null),q(null)},Fe=()=>{B||(A(null),q(null),D(""),M(""),F(null))},ze=async()=>{if(!T?.item||!$)return q("Choose another Resource as the destination."),!1;W(!0),q(null),h?.(null);const e=T.item,t={kind:e.kind,..."folder"===e.kind?{folderId:e.id}:{objectId:e.id},destinationPackId:$,destinationFolderId:null,metadataVersion:e.metadataVersion};try{const e=await r(`/api/workspace/v1/resource-packs/${n.id}/moves?scope=${l}`,{method:"POST",body:JSON.stringify({...t,...U?{confirmed:!0}:{preflight:!0}})});return U?(await u(),!0):(F(e.data),!1)}catch(a){const e=a.safeMessage||a.message||"The item could not be moved.";return q(e),h?.(e),!1}finally{W(!1)}},qe=async e=>{if(e?.preventDefault(),!T)return;const{type:t,item:a}=T;if(["create","rename"].includes(t)&&!O.trim())return void q("Enter a folder or file name.");let s=!1;"create"===t?s=await $e(`/api/workspace/v1/resource-packs/${n.id}/folders`,{method:"POST",body:JSON.stringify({name:O.trim(),parentFolderId:o||null})}):"rename"===t&&"folder"===a.kind?s=await $e(`/api/workspace/v1/resource-packs/${n.id}/folders/${a.id}`,{method:"PATCH",body:JSON.stringify({name:O.trim(),parentFolderId:a.parentFolderId||null,metadataVersion:a.metadataVersion})}):"rename"===t?s=await $e(`/api/workspace/v1/resource-packs/${n.id}/objects/${a.id}`,{method:"PATCH",body:JSON.stringify({filename:O.trim(),folderId:a.folderId||null,metadataVersion:a.metadataVersion})}):"move"===t?s=await Be(a,P):"batch-move"===t?s=await Pe("move",P):"batch-trash"===t?s=await Pe("trash"):"cross-move"===t?s=await ze():"delete"===t&&"folder"===a.kind?(s=await $e(`/api/workspace/v1/resource-packs/${n.id}/folders/${a.id}`,{method:"DELETE",body:JSON.stringify({})}),s&&dh(Ne,a.id).has(o)&&c?.(a.parentFolderId||null,{replace:!0})):"delete"===t&&(s=await $e(`/api/workspace/v1/resource-packs/${n.id}/objects/${a.id}`,{method:"DELETE",body:JSON.stringify({})})),s&&Fe()},Be=async(e,t)=>{if("folder"===e.kind){const a=dh(Ne,e.id);return t&&a.has(t)?(q("A folder cannot move into itself or one of its descendants."),h?.("A folder cannot move into itself or one of its descendants."),!1):(e.parentFolderId||null)===(t||null)||$e(`/api/workspace/v1/resource-packs/${n.id}/folders/${e.id}`,{method:"PATCH",body:JSON.stringify({name:e.name,parentFolderId:t||null,metadataVersion:e.metadataVersion})})}return(e.folderId||null)===(t||null)||$e(`/api/workspace/v1/resource-packs/${n.id}/objects/${e.id}`,{method:"PATCH",body:JSON.stringify({filename:e.originalFilename,folderId:t||null,metadataVersion:e.metadataVersion})})},We=(e,t)=>
2{if(!ve)return;const a={items:(S.has(Ae(t))?Oe:[t]).map(e=>({kind:e.kind,id:e.id,metadataVersion:e.metadataVersion}))};K(t),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData(oh,JSON.stringify(a)),e.dataTransfer.setData("text/plain",t.name||t.originalFilename)},Ve=()=>{K(null),ae(null)},He=async(e,t)=>{if(!ve)return;let a=V,n=[];if(!a)try{const t=JSON.parse(e.dataTransfer?.getData(oh)||"{}");n=Array.isArray(t.items)?t.items:[];const s=n[0];if(s){const e=("folder"===s.kind?Ne:we).find(e=>e.id===s.id);e&&(a={...e,kind:s.kind})}}catch{return}const s=S.has(Ae(a||{}))?Oe:a?[a]:[];(s.length||n.length)&&(e.preventDefault(),e.stopPropagation(),s.length>1||n.length>1?await Pe("move",t,s.length?s:n):await Be(s[0],t),Ve())},Ge=e=>"folder"===e.kind?[{label:"Open",icon:t.jsx(H,{size:17,"aria-hidden":"true"}),onSelect:()=>c?.(e.id)},...ve?[{label:"Rename",icon:t.jsx(ee,{size:17,"aria-hidden":"true"}),onSelect:()=>Ue("rename",e)},{label:"Move toâ¦",icon:t.jsx(Qe,{size:17,"aria-hidden":"true"}),onSelect:()=>Ue("move",e)},...ke.length?[{label:"Move to another Resourceâ¦",icon:t.jsx(Qe,{size:17,"aria-hidden":"true"}),onSelect:()=>Ue("cross-move",e)}]:[]]:[],...ye?[{label:"Move to trash",icon:t.jsx(te,{size:17,"aria-hidden":"true"}),danger:!0,onSelect:()=>Ue("delete",e)}]:[]]:[...e.previewSupported?[{label:"Preview",icon:t.jsx(Q,{size:17,"aria-hidden":"true"}),onSelect:()=>Me(e,!0)}]:[],{label:"Download",icon:t.jsx(Je,{size:17,"aria-hidden":"true"}),onSelect:()=>Me(e,!1)},...ve?[{label:"Rename",icon:t.jsx(ee,{size:17,"aria-hidden":"true"}),onSelect:()=>Ue("rename",e)},{label:"Move toâ¦",icon:t.jsx(Qe,{size:17,"aria-hidden":"true"}),onSelect:()=>Ue("move",e)},...ke.length?[{label:"Move to another Resourceâ¦",icon:t.jsx(Qe,{size:17,"aria-hidden":"true"}),onSelect:()=>Ue("cross-move",e)}]:[]]:[],...ye?[{label:"Move to trash",icon:t.jsx(te,{size:17,"aria-hidden":"true"}),danger:!0,onSelect:()=>Ue("delete",e)}]:[]],Ze=e.useMemo(()=>{if("batch-trash"===T?.type)return{folderCount:Oe.filter(e=>"folder"===e.kind).length,fileCount:Oe.filter(e=>"file"===e.kind).length,bytes:Oe.filter(e=>"file"===e.kind).reduce((e,t)=>e+Number(t.sizeBytes||0),0)};if("delete"!==T?.type||"folder"!==T.item?.kind)return null;const e=dh(Ne,T.item.id),t=we.filter(t=>e.has(t.folderId));return{folderCount:e.size,fileCount:t.length,bytes:t.reduce((e,t)=>e+Number(t.sizeBytes||0),0)}},[T,Ne,we,Oe]),et=e.useMemo(()=>["move","batch-move"].includes(T?.type)?new Set([..."folder"===T.item?.kind?[T.item]:[],..."batch-move"===T.type?Oe.filter(e=>"folder"===e.kind):[]].flatMap(e=>[...dh(Ne,e.id)])):new Set,[T,Ne,Oe]),tt=Ee?`Back to ${Ee.parentFolderId?Se.get(Ee.parentFolderId)?.name:n.title}`:"Back to Resources";return t.jsxs("section",{className:"resource-explorer"+("current"===X?" is-drop-target":""),role:"region","aria-label":`${n.title} file explorer`,onDragOver:e=>{je&&(e.preventDefault(),ae("current"))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||ae(null)},onDrop:async e=>{je&&(V||Array.from(e.dataTransfer?.types||[]).includes(oh)?await He(e,o||null):(e.preventDefault(),e.stopPropagation(),ae(null),await(j?.(e))))},children:[t.jsxs("header",{className:"resource-explorer__header",children:[t.jsxs("div",{className:"resource-explorer__heading",children:[t.jsxs(ec,{variant:"ghost",onClick:()=>{Ee?c?.(Ee.parentFolderId||null):d?.()},"aria-label":tt,children:[t.jsx(G,{size:18,"aria-hidden":"true"})," Back"]}),t.jsxs("div",{children:[t.jsx("h2",{children:n.title}),t.jsx("p",{children:n.purpose||n.description||"Workspace Resource"})]})]}),t.jsxs("div",{className:"resource-explorer__header-actions",children:[t.jsxs(ec,{variant:"ghost",onClick:v,"aria-label":"Resource details",children:[t.jsx(Y,{size:17,"aria-hidden":"true"})," Details"]}),t.jsxs(ec,{variant:"primary",onClick:x,children:[t.jsx(Je,{size:17,"aria-hidden":"true"})," Download all"]})]})]}),t.jsxs("nav",{"aria-label":"Resource folder breadcrumbs",className:"resource-drive-breadcrumbs",children:[t.jsx("button",{type:"button",onClick:d,children:"Resources"}),t.jsx(J,{size:14,"aria-hidden":"true"}),t.jsx("button",{type:"button",onClick:()=>c?.(null),"aria-current":o?void 0:"page",children:n.title}),Ie.map(e=>t.jsxs(a.Fragment,{children:[t.jsx(J,{size:14,"aria-hidden":"true"}),t.jsx("button",{type:"button",onClick:()=>c?.(e.id),"aria-current":e.id===o?"page":void 0,title:e.name,children:e.name})]},e.id))]}),t.jsxs("div",{className:"resource-explorer__toolbar",children:[t.jsxs("label",{className:"resource-explorer__search",children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{type:"search",value:y,onChange:e=>k(e.target.value),placeholder:"Search this Resource","aria-label":"Search f
2iles in Resource"})]}),t.jsxs("label",{className:"resource-explorer__sort",children:[t.jsx("span",{children:"Sort"}),t.jsxs("select",{value:w,onChange:e=>N(e.target.value),children:[t.jsx("option",{value:"name",children:"Name"}),t.jsx("option",{value:"updated",children:"Updated"}),t.jsx("option",{value:"size",children:"Size"}),t.jsx("option",{value:"type",children:"Type"})]})]}),je?t.jsxs("div",{className:"resource-explorer-new",ref:fe,children:[t.jsxs(ec,{ref:be,variant:"primary","aria-haspopup":"menu","aria-expanded":I,onClick:()=>_(e=>!e),onKeyDown:e=>{["ArrowDown","ArrowUp"].includes(e.key)&&(e.preventDefault(),_(!0),requestAnimationFrame(()=>{const t=Array.from(fe.current?.querySelectorAll('[role="menuitem"]')||[]);("ArrowUp"===e.key?t.at(-1):t[0])?.focus()}))},children:[t.jsx(Z,{size:17,"aria-hidden":"true"})," New"]}),I?t.jsxs("div",{className:"resource-explorer-new__menu",role:"menu","aria-label":"New in folder",onKeyDown:e=>{const t=Array.from(fe.current?.querySelectorAll('[role="menuitem"]')||[]);if(!["ArrowDown","ArrowUp","Home","End"].includes(e.key))return;e.preventDefault();const a=Math.max(0,t.indexOf(document.activeElement)),n="Home"===e.key?0:"End"===e.key?t.length-1:"ArrowDown"===e.key?(a+1)%t.length:(a-1+t.length)%t.length;t[n]?.focus()},children:[t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{_(!1),Ue("create")},children:[t.jsx(H,{size:17,"aria-hidden":"true"})," New folder"]}),t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{_(!1),p?.()},children:[t.jsx(Ye,{size:17,"aria-hidden":"true"})," Upload files"]}),t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{_(!1),f?.()},children:[t.jsx(H,{size:17,"aria-hidden":"true"})," Upload folder"]}),t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{_(!1),b?.()},children:[t.jsx(Ke,{size:17,"aria-hidden":"true"})," Upload ZIP"]})]}):null]}):null]}),Oe.length?t.jsxs("div",{className:"resource-explorer__selection",role:"toolbar","aria-label":"Selected items",children:[t.jsxs("strong",{children:[Oe.length," selected"]}),ve?t.jsxs(ec,{variant:"ghost",onClick:()=>Ue("batch-move"),children:[t.jsx(Qe,{size:17,"aria-hidden":"true"})," Move"]}):null,ye?t.jsxs(ec,{variant:"danger",onClick:()=>Ue("batch-trash"),children:[t.jsx(te,{size:17,"aria-hidden":"true"})," Move to trash"]}):null,t.jsxs(ec,{variant:"ghost",onClick:()=>{C(new Set),E(null)},children:[t.jsx(g,{size:17,"aria-hidden":"true"})," Clear"]})]}):null,he?t.jsx(oc,{type:"error",children:he}):null,ce?t.jsx("p",{role:"status",children:"Loading folder contentsâ¦"}):null,X?t.jsx("div",{className:"resource-explorer__drop-message",role:"status",children:V?`Move ${V.name||V.originalFilename} to ${Ee?.name||n.title}`:`Drop to upload into â${Ee?.name||n.title}â`}):null,t.jsxs("div",{className:"resource-explorer-table",role:"table","aria-label":`Files in ${Ee?.name||n.title}`,"aria-multiselectable":"true",children:[t.jsxs("div",{className:"resource-explorer-table__head",role:"row",children:[t.jsx("span",{role:"columnheader",children:t.jsx("input",{type:"checkbox","aria-label":"Select all items on this page",checked:Boolean(Te.length)&&Oe.length===Te.length,onChange:e=>{C(e.target.checked?new Set(Te.map(Ae)):new Set),E(null)}})}),t.jsx("span",{role:"columnheader",children:"Name"}),t.jsx("span",{role:"columnheader",children:"Type"}),t.jsx("span",{role:"columnheader",children:"Updated"}),t.jsx("span",{role:"columnheader",children:"Size"}),t.jsx("span",{role:"columnheader","aria-label":"Actions"})]}),_e.folders.map(e=>{const a={...e,kind:"folder"},n=S.has(`folder:${e.id}`);return t.jsxs("div",{role:"row",tabIndex:0,"aria-label":`${e.name} Folder ${new Date(e.updatedAt||0).toLocaleDateString()}`,"aria-selected":n,className:`resource-explorer-row${n?" is-selected":""}${X===e.id?" is-drop-target":""}`,draggable:ve,onClick:e=>{e.target.closest("button, input, a")||De(a,e)},onDoubleClick:()=>c?.(e.id),onKeyDown:t=>{"Enter"===t.key&&c?.(e.id)," "===t.key&&(t.preventDefault(),De(a,t))},onDragStart:e=>We(e,a),onDragEnd:Ve,onDragOver:t=>{ve&&(t.preventDefault(),t.stopPropagation(),ae(e.id))},onDragLeave:()=>ae(null),onDrop:t=>He(t,e.id),children:[t.jsx("span",{role:"cell",className:"resource-explorer-row__select",children:t.jsx("input",{type:"checkbox",checked:n,"aria-label":`Select folder ${e.name}`,onClick:e=>e.stopPropagation(),onChange:e=>De(a,e.nativeEvent)})}),t.jsxs("span",{role:"cell",className:"resource-explorer-row__name",children:[t.jsx(H,{size:20,"aria-hidden":"true"}),t.jsxs("button",{type:"button","aria-label":`Open folder ${e.name}`,onClick:()=>{_e.searching&&k(""),c?.(e.id)},children:[t.jsx("strong",{children:e.name}),_e.searching&&Re(e.parentFolderId)?t.jsx("small",{children:Re(e.parentFolderId)}):null]})]}),t.jsx("span",{role:"cell",children:"Folder"}),t.jsx("span",{role:"cell",children:new Date(e.updatedAt||0).toLocaleDateString()}),t.jsx("span",{role:"cell",children:"â"}),t.jsx("span",{role:"cell",className:"resource-explorer-row__actions",children:t.jsx(ch,{label:`Actions for ${e.name}`,items:Ge(a)})})]},e.id)}),_e.files.map(e=>{const a={...e,kind:"file"},n=S.has(`file:${e.id}`);return t.jsxs("div",{role:"row",tabIndex:0,"aria-label":`${e.originalFilename} ${uh(e)} ${Nc(e.sizeBytes)}
2`,"aria-selected":n,className:"resource-explorer-row"+(n?" is-selected":""),draggable:ve,onClick:e=>{e.target.closest("button, input, a")||De(a,e)},onDoubleClick:()=>Me(e,Boolean(e.previewSupported)),onKeyDown:t=>{"Enter"===t.key&&Me(e,Boolean(e.previewSupported))," "===t.key&&(t.preventDefault(),De(a,t))},onDragStart:e=>We(e,a),onDragEnd:Ve,children:[t.jsx("span",{role:"cell",className:"resource-explorer-row__select",children:t.jsx("input",{type:"checkbox",checked:n,"aria-label":`Select file ${e.originalFilename}`,onClick:e=>e.stopPropagation(),onChange:e=>De(a,e.nativeEvent)})}),t.jsxs("span",{role:"cell",className:"resource-explorer-row__name",children:[t.jsx(Xe,{size:20,"aria-hidden":"true"}),t.jsxs("button",{type:"button",onClick:()=>{_e.searching?(k(""),c?.(e.folderId||null)):Me(e,Boolean(e.previewSupported))},children:[t.jsx("strong",{children:_e.searching?e.relativePath:e.originalFilename}),_e.searching&&e.folderId?t.jsx("small",{children:Re(e.folderId)}):null]})]}),t.jsx("span",{role:"cell",children:uh(e)}),t.jsx("span",{role:"cell",children:new Date(e.updatedAt||0).toLocaleDateString()}),t.jsx("span",{role:"cell",children:Nc(e.sizeBytes)}),t.jsx("span",{role:"cell",className:"resource-explorer-row__actions",children:t.jsx(ch,{label:`Actions for ${e.originalFilename}`,items:Ge(a)})})]},e.id)}),_e.folders.length||_e.files.length?null:t.jsx("div",{className:"resource-explorer-empty",role:"row",children:t.jsxs("span",{role:"cell",children:[t.jsx(H,{size:24,"aria-hidden":"true"}),t.jsx("strong",{children:_e.searching?"No matching files or folders":"This folder is empty"}),t.jsx("small",{children:je&&!_e.searching?"Use New or drop files here to add content.":"Try another folder or search term."})]})})]}),pe.objects?.hasMore||pe.folders?.hasMore?t.jsx("div",{className:"resource-drive-load-more",children:t.jsx(ec,{variant:"ghost",disabled:ce,onClick:async()=>{de(!0),me(null);try{const e=new URLSearchParams({scope:l,limit:"100"});y.trim()?e.set("search",y.trim()):o&&e.set("folderId",o);const t=[];if(pe.objects?.nextCursor){const a=new URLSearchParams(e);a.set("cursor",pe.objects.nextCursor),t.push(r(`/api/workspace/v1/resource-packs/${n.id}/objects?${a}`).then(e=>({kind:"objects",response:e})))}if(pe.folders?.nextCursor){const a=new URLSearchParams(e);a.delete("folderId"),!y.trim()&&o&&a.set("parentFolderId",o),a.set("cursor",pe.folders.nextCursor),t.push(r(`/api/workspace/v1/resource-packs/${n.id}/folders?${a}`).then(e=>({kind:"folders",response:e})))}const a=await Promise.all(t);for(const{kind:n,response:s}of a)"objects"===n?se(e=>[...e,...s.data?.objects||[]]):ie(e=>[...e,...s.data?.folders||[]]),ge(e=>({...e,[n]:s.data?.pagination||null}))}catch(e){me(e.safeMessage||e.message||"More items could not be loaded.")}finally{de(!1)}},children:ce?"Loadingâ¦":"Load more"})}):null,t.jsxs(cc,{isOpen:Boolean(T),onClose:Fe,variant:"modal",title:"create"===T?.type?"New folder":"rename"===T?.type?"Rename "+("folder"===T.item?.kind?"folder":"file"):"move"===T?.type?`Move â${T.item?.name||T.item?.originalFilename}â`:"cross-move"===T?.type?`Move â${T.item?.name||T.item?.originalFilename}â to another Resource`:"batch-move"===T?.type?`Move ${Oe.length} selected items`:"batch-trash"===T?.type?`Move ${Oe.length} selected items to trash?`:`Move â${T?.item?.name||T?.item?.originalFilename}â to trash?`,description:["move","batch-move"].includes(T?.type)?"Choose a destination in this Resource.":"cross-move"===T?.type?"Review the destination and audience change before confirming.":["delete","batch-trash"].includes(T?.type)?"Items remain recoverable for 30 days.":null,footer:t.jsxs(lc,{children:[t.jsx(ec,{variant:"ghost",onClick:Fe,disabled:B,children:"Cancel"}),t.jsx(ec,{variant:["delete","batch-trash"].includes(T?.type)?"danger":"primary",onClick:"cross-move"===T?.type?ze:qe,disabled:B||["create","rename"].includes(T?.type)&&!O.trim()||"cross-move"===T?.type&&(!$||U&&!U.canMove),children:B?"Workingâ¦":"create"===T?.type?"Create":"rename"===T?.type?"Rename":["move","batch-move"].includes(T?.type)?"Move here":"cross-move"===T?.type?U?"Confirm move":"Review move":"Move to trash"})]}),children:[["create","rename"].includes(T?.type)?t.jsx("form",{onSubmit:qe,children:t.jsx(rc,{label:"create"===T?.type?"Folder name":"Name",required:!0,error:z,children:t.jsx("input",{value:O,onChange:e=>D(e.target.value),autoComplete:"off"})})}):null,["move","batch-move"].includes(T?.type)?t.jsxs("div",{className:"resource-explorer-folder-tree",role:"radiogroup","aria-label":"Destination folder",children:[t.jsxs("button",{type:"button",role:"radio","aria-checked":null===P,onClick:()=>L(null),children:[t.jsx(H,{size:17,"aria-hidden":"true"})," ",n.title]}),Le.map(({folder:e,depth:a})=>t.jsxs("button",{type:"button",role:"radio","aria-checked":P===e.id,disabled:et.has(e.id),style:{"--resource-folder-depth":a},onClick:()=>L(e.id),children:[t.jsx(H,{size:17,"aria-hidden":"true"})," ",e.name]},e.id)),z?t.jsx(oc,{type:"error",children:z}):null]}):null,"cross-move"===T?.type?t.jsxs("div",{className:"resource-explorer-cross-move",children:[t.jsx(rc,{label:"Destination Resource",required:!0,children:t.jsx("select",{value:$,disabled:Boolean(U),onChange:e=>{M(e.target.value),F(null)},children:ke.map(e=>t.jsx("option",{value:e.id,children:e.title},e.id))})}),U?t.jsxs("div",{role:"status",className:"resource-explorer-delete-summary",children:[t.jsxs("p",{children:["Move from ",t.jsx("strong",{children:U.source.title})," (",U.source.audience,") to"," ",t.jsx("strong",{children:U.destination.title})," (",U.destination.audience,")."]}),t.jsxs("p",{children:[U.folderCount," folders · ",U.fileCount," files"]}),U.accessWillChange?t.jsx(oc,{type:"warning",children:"Access will change because the destination has a different audience."}):null,U.linkedReferenceCount?t.jsxs(oc,{type:"error",children:["This item has ",U.linkedReferenceCount," stable Worksp
2ace references or comments. Remove them before moving across Resources."]}):t.jsx("p",{children:"Stable item identity will be preserved."})]}):null,z?t.jsx(oc,{type:"error",children:z}):null]}):null,["delete","batch-trash"].includes(T?.type)?t.jsxs("div",{className:"resource-explorer-delete-summary",children:[Ze?t.jsxs(t.Fragment,{children:[t.jsx("p",{children:"This moves to trash:"}),t.jsxs("dl",{children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Folders"}),t.jsx("dd",{children:Ze.folderCount})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Files"}),t.jsx("dd",{children:Ze.fileCount})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Size"}),t.jsx("dd",{children:Nc(Ze.bytes)})]})]}),t.jsx("p",{children:"Historical Workspace references remain as unavailable tombstones until restore."})]}):t.jsx("p",{children:"The file becomes unavailable immediately but stored bytes are retained during the 30-day recovery window."}),z?t.jsx(oc,{type:"error",children:z}):null]}):null]})]})}const mh={title:"",description:"",purpose:"",usageNotes:"",category:"",tags:""};function ph(e){const t=e[0];if(!t)return"New Resource";const a=t.webkitRelativePath||t.relativePath||"";return a.includes("/")?a.split("/")[0]:e.length>1?`${e.length} uploaded files`:t.name.replace(/\.[^.]+$/,"")||t.name}function gh(e){return"application/zip"===e?.type||/\.zip$/i.test(e?.name||"")}async function fh(e,t=""){if(e.isFile)return new Promise((a,n)=>e.file(e=>a([Object.assign(e,{relativePath:`${t}${e.name}`})]),n));if(!e.isDirectory)return[];const a=e.createReader(),n=[];for(;;){const e=await new Promise((e,t)=>a.readEntries(e,t));if(!e.length)break;n.push(...e)}return(await Promise.all(n.map(a=>fh(a,`${t}${e.name}/`)))).flat()}async function bh(e){const t=Array.from(e.dataTransfer?.items||[]).map(e=>e.webkitGetAsEntry?.()).filter(Boolean);return t.length?(await Promise.all(t.map(e=>fh(e)))).flat():Array.from(e.dataTransfer?.files||[])}function xh({resource:e}){return t.jsxs("span",{className:"resource-drive-quick-info","aria-hidden":"true",children:[t.jsx("strong",{children:e.title}),t.jsx("span",{children:e.description||e.purpose||"No description provided."}),t.jsxs("span",{children:[e.objectCount," files · ",Nc(e.totalBytes)]}),t.jsx("span",{children:e.creator?.name?`Uploaded by ${e.creator.name}`:"Workspace Resource"}),e.category?t.jsx("span",{children:e.category}):null,e.tags?.length?t.jsx("span",{children:e.tags.join(" · ")}):null,t.jsxs("span",{children:["Updated ",new Date(e.updatedAt).toLocaleDateString()]})]})}function vh({upload:e}){return e.uploads.length?t.jsxs("section",{className:"resource-drive-upload-progress","aria-live":"polite","aria-atomic":"true",children:[t.jsxs("strong",{children:["Upload progress: ",e.overall.percent,"% · ",e.overall.counts.succeeded," scanning or uploaded · ",e.overall.counts.failed," failed"]}),e.uploads.map(a=>t.jsxs("div",{children:[t.jsx("span",{children:a.name}),t.jsx("progress",{max:a.sizeBytes||1,value:a.uploadedBytes}),t.jsx("span",{children:"scanning"===a.status?"Uploaded · security scan pending":a.status}),a.error?t.jsx(oc,{type:"error",children:a.error}):null,"failed"===a.status?t.jsx(ec,{type:"button",variant:"ghost",onClick:()=>e.retry(a),children:"Retry"}):null,["preparing","uploading","resuming"].includes(a.status)?t.jsx(ec,{type:"button",variant:"ghost",onClick:()=>e.cancel(a),children:"Cancel"}):null]},a.key))]}):null}function jh({value:e,onChange:a}){const n=t=>n=>a({...e,[t]:n.target.value});return t.jsxs(ic,{legend:"Resource context",children:[t.jsx(rc,{label:"Title",required:!0,children:t.jsx("input",{required:!0,value:e.title,onChange:n("title")})}),t.jsx(rc,{label:"Description",children:t.jsx("textarea",{value:e.description,onChange:n("description")})}),t.jsx(rc,{label:"Purpose",help:"Explain why this exists and who should use it.",children:t.jsx("textarea",{value:e.purpose,onChange:n("purpose")})}),t.jsx(rc,{label:"Usage notes",children:t.jsx("textarea",{value:e.usageNotes,onChange:n("usageNotes")})}),t.jsx(rc,{label:"Category",children:t.jsx("input",{value:e.category,onChange:n("category")})}),t.jsx(rc,{label:"Tags",help:"Separate tags with commas.",children:t.jsx("input",{value:e.tags,onChange:n("tags")})})]})}function yh({resource:a,request:n,actorId:s,scope:r}){const[i,l]=e.useState([]),[o,c]=e.useState(""),[d,u]=e.useState(null),[h,m]=e.useState(!1),p=e.useCallback(async()=>{try{const e=await n(`/api/workspace/v1/resource-packs/${a.id}/comments?limit=100&scope=${r}`);l(e.data?.comments||[]),u(null)}catch(e){u(e.safeMessage||"Comments could not be loaded.")}},[n,a.id,r]);e.useEffect(()=>{p()},[p]);return t.jsxs("section",{"aria-labelledby":"resource-comments-heading",children:[t.jsx("h3",{id:"resource-comments-heading",children:"Comments"}),i.length?t.jsx("ol",{className:"resource-drive-activity",children:i.map(e=>t.jsxs("li",{children:[t.jsx("strong",{children:e.deletedAt?"Comment removed":e.author?.name||"Employee"}),e.body?t.jsx("span",{children:e.body}
2):null,t.jsx("span",{children:new Date(e.createdAt).toLocaleString()}),e.deletedAt||e.author?.id!==s&&!a.effectiveAccess?.canManageSharing?null:t.jsx(ec,{variant:"ghost",size:"compact",onClick:()=>(async e=>{u(null);try{await n(`/api/workspace/v1/resource-packs/${a.id}/comments/${e.id}?scope=${r}`,{method:"DELETE"}),await p()}catch(t){u(t.safeMessage||"Comment could not be removed.")}})(e),children:"Remove"})]},e.id))}):t.jsx("p",{children:"No comments yet."}),!1!==a.effectiveAccess?.canComment?t.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),o.trim()){m(!0),u(null);try{await n(`/api/workspace/v1/resource-packs/${a.id}/comments?scope=${r}`,{method:"POST",body:JSON.stringify({body:o})}),c(""),await p()}catch(t){u(t.safeMessage||"Comment could not be added.")}finally{m(!1)}}},children:[t.jsx(rc,{label:"Add a comment",help:"Plain text, up to 4,000 characters.",children:t.jsx("textarea",{value:o,maxLength:4e3,onChange:e=>c(e.target.value)})}),t.jsx(ec,{type:"submit",variant:"primary",disabled:h||!o.trim(),children:h?"Addingâ¦":"Add comment"})]}):null,d?t.jsx(oc,{type:"error",children:d}):null]})}function kh({selectedResourceId:a,selectedFolderId:n,onSelectedResourceChange:s,onSelectedFolderChange:r,scope:i="mine"}){const{makeAuthRequest:l,hasMinimumRole:o,user:c}=Yn(),d="all"===i&&o("admin"),[u,h]=e.useState(null),[m,p]=e.useState(""),[g,f]=e.useState("updated"),[b,v]=e.useState(""),[j,y]=e.useState("list"),[k,w]=e.useState(!1),[N,S]=e.useState([]),[C,R]=e.useState("extract"),[E,I]=e.useState(!1),[_,T]=e.useState(!1),[A,O]=e.useState(!1),[D,P]=e.useState(null),[L,$]=e.useState(""),[U,F]=e.useState(!1),[z,q]=e.useState(mh),[B,W]=e.useState(null),[V,K]=e.useState("details"),[G,J]=e.useState(""),Y=e.useRef(null),Q=e.useRef(null),X=e.useRef(null),ae=e.useRef(null),ne=e.useRef(null),se=e.useRef(null),re=e.useRef(0),ie=Mu({request:l,actorId:c?.id,scope:i}),le=e.useMemo(()=>{const e=new URLSearchParams({scope:i,sort:g});return m&&e.set("search",m),b&&d&&e.set("status",b),`/api/workspace/v1/resource-packs?${e}`},[d,i,m,g,b]),{data:oe,loading:ce,error:de,refresh:he,hasMore:me,loadMore:pe,loadingMore:ge,loadMoreError:fe}=kc(le,{initialData:{resources:[]},collectionKey:"resources"}),be=oe?.resources||[],xe=Boolean(d&&"all"===oe?.scope&&oe?.capabilities?.canCreateResource),ve=Boolean(u?.effectiveAccess?.canEditContent||d),je=Boolean(u?.effectiveAccess?.canOrganize||d),ye=Boolean(u?.effectiveAccess?.canManageSharing||d),ke=Boolean(u?.effectiveAccess?.canArchive||d),we=Boolean(u?.effectiveAccess?.canPermanentlyDelete||d),Ne=de?de.safeMessage||"Resources could not be loaded.":"";e.useEffect(()=>{xe||(w(!1),S([]),R("extract"),q(mh),I(!1))},[xe]);const Se=e.useCallback(async(e=a)=>{const t=++re.current;if(!e)return h(null),null;let n=(await l(`/api/workspace/v1/resource-packs/${e}?scope=${i}`)).data.resource;if(d){const t=await l(`/api/workspace/v1/resources/${e}?scope=all`).catch(()=>null);t?.data?.resource&&(n={...n,assignmentContext:t.data.resource.assignmentContext})}return t!==re.current?null:(h(n),n)},[d,l,i,a]);e.useEffect(()=>{let e=!1;if(P(null),O(!1),a)return h(null),Se().catch(t=>{e||(h(null),P(t.safeMessage||"This Resource could not be loaded."))}),()=>{e=!0,re.current+=1};h(null)},[Se,a]),e.useEffect(()=>{let e=!1;if(u?.jupyterNotebookVersionId&&u.owner?.id!==c?.id)return l("/api/employee/jupyter/status").then(t=>{e||F(Boolean(t.data?.enabled&&t.data?.notebookImportEnabled))}).catch(()=>!e&&F(!1)),()=>{e=!0};F(!1)},[l,u?.jupyterNotebookVersionId,u?.owner?.id,c?.id]);const Re=async e=>{if(!xe)return;const t=Array.from(e||[]);if(t.length){try{Ou(t,{folder:t.some(e=>(e.webkitRelativePath||e.relativePath||"").includes("/"))})}catch(a){return void P(a.message)}S(t),R(t.some(gh)?null:"extract"),q(e=>({...e,title:e.title||ph(t)})),I(!0)}},Ee=()=>Promise.all([he(),Se(u.id)]),Ie=async e=>{if(e?.length&&u){P(null);try{const t=Array.from(e).some(gh)?function(){const e=window.prompt("How should this ZIP be added? Enter âextractâ to unpack it or âstoreâ to keep the ZIP file.");if(null===e)return null;const t=e.trim().toLowerCase();if("extract"===t||"store"===t)return t;throw new Error("Choose either âextractâ or âstoreâ for the ZIP.")}():"extract";if(!t)return;const a=Array.from(e).map(e=>{const t=e.relativePath||e.webkitRelativePath||e.name;return Object.assign(e,{relativePath:G?`${G}/${t}`:t})}),n=await ie.uploadFiles(u.id,a,{archiveMode:t,folder:a.some(e=>e.relativePath?.includes("/"))}),s=n.filter(e=>"rejected"===e.status);s.length&&P(`${s.length} of ${n.length} files failed. Successful uploads remain queued for scanning.`),await Ee()}catch(t){P(t.safeMessage||"One or more files could not be uploaded.")}}},_e=async e=>{await Ie(e.target.files),e.target.value=""},Te=async e=>{const t=e?`Delete â${u.title}â permanently?\n\nAll files, folders, source archives, and generated downloads will be removed. Historical links will show âResource deleted.â This cannot be undone.`:`Archive â${u.title}â? Historical links will be preserved.`;if(window.confirm(t)){P(null);try{await l(`/api/workspace/v1/resource-packs/${u.id}?scope=${i}`,{method:"DELETE",...e?{body:JSON.stringify({permanent:!0})}:{}}),O(!1),s?.(null),await he()}catch(a){P(a.safeMessage||(e?"Resource deletion could not be started.":"Resource could not be archived."))}}};return t.jsxs("section",{className:"resource-drive"+(k?" is-dragging":""),onDragEnter:e=>{xe&&!u&&(e.preventDefault(),w(!0))},onDragOver:e=>{xe&&!u&&e.preventDefault()},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||w(!1)},onDrop:async e=>{xe&&!u&&(e.preventDefault(),w(!1),await Re(await bh(e)))},children:[xe||ve?t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Y,hidden:!0,type:"file",multiple:!0,onChange:e=>{Re(e.target.files)}}),t.jsx("input",{ref:Q,hidden:!0,type:"file",multiple:!0,webkitdirectory:"",onCh
2ange:e=>{Re(e.target.files)}}),t.jsx("input",{ref:X,hidden:!0,type:"file",accept:".zip,application/zip",onChange:e=>{Re(e.target.files)}}),t.jsx("input",{ref:ae,hidden:!0,type:"file",multiple:!0,onChange:_e}),t.jsx("input",{ref:ne,hidden:!0,type:"file",multiple:!0,webkitdirectory:"",onChange:_e}),t.jsx("input",{ref:se,hidden:!0,type:"file",accept:".zip,application/zip",onChange:_e})]}):null,a&&!u?t.jsx(dc,{type:D?"error":"loading",title:D?"Resource could not be loaded":"Loading Resourceâ¦",description:D,action:D?t.jsx(ec,{onClick:()=>s?.(null),children:"Back to Resources"}):null}):u?t.jsxs(t.Fragment,{children:[t.jsx(hh,{resource:u,resources:be,request:l,admin:je,scope:i,folderId:n||null,onFolderChange:r,onBackToLibrary:()=>s?.(null),onChanged:Ee,onError:P,onFolderPathChange:J,onUploadFiles:()=>ae.current?.click(),onUploadFolder:()=>ne.current?.click(),onUploadZip:()=>se.current?.click(),onDownloadAll:async()=>{if(u){$("Preparing downloadâ¦"),P(null);try{const e=await l(`/api/workspace/v1/resource-packs/${u.id}/exports?scope=${i}`,{method:"POST",body:"{}"});if("object"===e.data.kind&&e.data.objectId){const t=await l(`/api/workspace/v1/resource-packs/${u.id}/objects/${e.data.objectId}/access?scope=${i}`,{method:"POST",body:"{}"});return $("Download ready"),void window.open(t.data.url,"_self","noopener,noreferrer")}const t=e.data.exportId;if(!t)throw new Error("The Resource export could not be started.");for(let a=0;a<60;a+=1){const e=await l(`/api/workspace/v1/resource-packs/${u.id}/exports/${t}?scope=${i}`);if("ready"===e.data.state){const e=await l(`/api/workspace/v1/resource-packs/${u.id}/exports/${t}/access?scope=${i}`,{method:"POST",body:"{}"});return $("Download ready"),void window.open(e.data.url,"_self","noopener,noreferrer")}if(["failed","expired"].includes(e.data.state))throw new Error("The Resource ZIP could not be prepared. Try again.");$("Building Resource ZIPâ¦"),await new Promise(e=>setTimeout(e,2e3))}throw new Error("The Resource ZIP is still processing. Try again shortly.")}catch(e){$(""),P(e.safeMessage||e.message||"Download failed.")}}},onOpenDetails:()=>O(!0),onDropFiles:async e=>Ie(await bh(e))}),D?t.jsx(oc,{type:"error",children:D}):null,L?t.jsx("p",{role:"status",children:L}):null,t.jsx(vh,{upload:ie})]}):t.jsxs(t.Fragment,{children:[t.jsx("header",{className:"resource-drive-header",children:t.jsxs("div",{children:[t.jsx("h2",{children:"Resources"}),t.jsx("p",{children:"Shared files, collections, and guidance for Workspace work."})]})}),t.jsxs(sc,{resultCount:be.length,resultLabel:me?`${be.length} loaded`:null,children:[t.jsxs("label",{children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{type:"search",value:m,onChange:e=>p(e.target.value),placeholder:"Search Resources","aria-label":"Search Resources"})]}),t.jsxs("select",{value:g,onChange:e=>f(e.target.value),"aria-label":"Sort Resources",children:[t.jsx("option",{value:"updated",children:"Recently updated"}),t.jsx("option",{value:"name",children:"Name"}),t.jsx("option",{value:"size",children:"Size"}),t.jsx("option",{value:"created",children:"Created"})]}),xe?t.jsxs("select",{value:b,onChange:e=>v(e.target.value),"aria-label":"Filter Resource status",children:[t.jsx("option",{value:"",children:"All active states"}),t.jsx("option",{value:"ready",children:"Ready"}),t.jsx("option",{value:"uploading",children:"Uploading"}),t.jsx("option",{value:"processing",children:"Processing"}),t.jsx("option",{value:"failed",children:"Failed"})]}):null,t.jsxs("span",{className:"resource-drive-view-toggle",role:"group","aria-label":"Resource view",children:[t.jsx(ec,{iconOnly:!0,variant:"ghost","aria-pressed":"list"===j,"aria-label":"List view",onClick:()=>y("list"),children:t.jsx(Ce,{size:17})}),t.jsx(ec,{iconOnly:!0,variant:"ghost","aria-pressed":"grid"===j,"aria-label":"Grid view",onClick:()=>y("grid"),children:t.jsx(et,{size:17})})]}),xe?t.jsxs(t.Fragment,{children:[t.jsxs(ec,{variant:"ghost",onClick:()=>{S([]),I(!0)},children:[t.jsx(Z,{size:16})," New Resource"]}),t.jsxs(ec,{variant:"primary",onClick:()=>Y.current?.click(),children:[t.jsx(Ye,{size:16})," Upload files"]}),t.jsxs(ec,{variant:"ghost",onClick:()=>Q.current?.click(),children:[t.jsx(H,{size:16})," Upload folder"]}),t.jsxs(ec,{variant:"ghost",onClick:()=>X.current?.click(),children:[t.jsx(Ke,{size:16})," Upload ZIP"]})]}):null]}),k?t.jsxs("div",{className:"resource-drive-drop-target",role:"status",children:[t.jsx(Ye,{size:28}),t.jsx("strong",{children:"Drop files or folders to add a Resource"}),t.jsx("span",{children:"You can review its name and context before upload."})]}):null,Ne||a&&D?t.jsx(dc,{type:"error",title:"Resources could not be loaded",description:Ne||D,action:t.jsx(ec,{onClick:he,children:"Retry"})}):null,ce&&!be.length?t.jsx(dc,{type:"loading",title:"Loading Resourcesâ¦"}):null,ce||be.length||de?null:t.jsx(dc,{type:m?"no-results":"empty",title:m?"No Resources match this search":"No Resources are available yet",description:xe?"Upload files, a folder, or a ZIP to create the first Resource.":"An administrator has not shared a Resource with you yet."}),be.length?t.jsxs("div",{className:`resource-drive-list resource-drive-list--${j}`,"aria-label":"Workspace Resources",children:[t.jsxs("div",{className:"resource-drive-columns","aria-hidden":"true",children:[t.jsx("span",{children:"Name"}),t.jsx("span",{children:"Owner"}),t.jsx("span",{children:"Updated"}),t.jsx("span",{children:"Size"}),t.jsx("span",{children:"Status"})]}),be.map(e=>t.jsxs("button",{type:"button","aria-label":`Open Resource ${e.title}`,className:"resource-drive-row",onClick:()=>s?.(e.id),children:[t.jsxs("span",{className:"resource-drive-name",children:[t.jsx("span",{className:"resource-drive-icon",children:e.objectCount>1||"archive"===e.packKind?t.jsx(M,{size:20}):t.jsx(x,{size:20})}),t.jsxs("span",{children:[t.jsx("strong",{children:e.title}),t.jsxs("small",{children:[e.purpose||e.description||"Workspace Resource"," ·"," ",e.objectCount," file",1===e.objectCount?"":"s"]})]})]}),t.jsx("span",{"data-label":"Owner",children:e.owner?.name||e.creator?.name||"Workspace"}),t.jsx("span",{"data-label":"Updated",children:new Date(e.updatedAt).toLocaleDateString()}),t.jsx("span",{"data-label":"Size",children:Nc(e.totalBytes)}),t.jsx("span",{"data-label":"Status",children:t.jsx(tc,{value:e.status})}),t.jsx(xh,{resource:e})]},e.id))]}):null,fe?t.jsxs(oc,{type:"error",children:["More Resources could not be loaded."," ",t.jsx(ec,{variant:"ghost",size:"compact",onClick:pe,children:"Retry"})]}):null,me?t.jsx("div",{className:"resource-drive-load-more",children:t.jsx(ec,{onClick:pe,disabled:ge,children:ge?"Loading moreâ¦":"Load more resources"})}):null]}),t.jsx(cc,{isOpen:A&&Boolean(u),onClose:()=>O(!1),title:`${u?.title||"Resource"} details`,description:u?`${u.objectCount} files · ${Nc(u.totalBytes)}`:null,variant:"wide",children:u?t.jsxs("div",{className:"resource-drive-detail",children:[t.jsxs("div",{className:"resource-drive-detail-meta",children:[t.jsx(tc,{value:u.status}),t.jsxs("span",{children:["Uploaded by ",u.creator?.name||"Workspace"," ·"," ",new Date(u.createdAt).toLocaleDateString()]}),u.category?t.jsx("span",{children:u.category}):null]}),D?t.jsx(oc,{type:"error",children:D}):null,ye||ke||we?t.jsxs("div",{className:"resource-drive-detail-actions",children:[ye?t.jsxs(ec,{variant:"ghost",onClick:()=>
2{W({title:u.title,description:u.description||"",purpose:u.purpose||"",usageNotes:u.usageNotes||"",category:u.category||"",tags:u.tags?.join(", ")||"",isAllInternal:u.isAllInternal,metadataVersion:u.metadataVersion}),T(!0)},children:[t.jsx(ee,{size:16})," Edit details"]}):null,["failed","partially_failed"].includes(u.status)&&"archive"===u.packKind?t.jsxs(ec,{variant:"ghost",onClick:async()=>{P(null);try{await l(`/api/workspace/v1/resource-packs/${u.id}?scope=${i}`,{method:"POST",body:JSON.stringify({action:"retry_processing"})}),await Ee()}catch(e){P(e.safeMessage||"Processing could not be retried.")}},children:[t.jsx(Me,{size:16})," Retry processing"]}):null,ke?t.jsxs(ec,{variant:"danger",onClick:()=>Te(!1),children:[t.jsx(Ke,{size:16})," Archive"]}):null,we?t.jsxs(ec,{variant:"danger",onClick:()=>Te(!0),children:[t.jsx(te,{size:16})," Delete permanently"]}):null]}):null,t.jsx("nav",{className:"resource-drive-tabs",role:"tablist","aria-label":"Resource details",children:["details",...ye?["assignments","activity"]:[]].map(e=>t.jsx("button",{type:"button",role:"tab","aria-selected":V===e,onClick:()=>K(e),children:e[0].toUpperCase()+e.slice(1)},e))}),t.jsxs("div",{role:"tabpanel",children:["details"===V?t.jsxs(t.Fragment,{children:[t.jsxs("dl",{className:"resource-drive-details",children:[t.jsx("dt",{children:"Purpose"}),t.jsx("dd",{children:u.purpose||"â"}),t.jsx("dt",{children:"Description"}),t.jsx("dd",{children:u.description||"â"}),t.jsx("dt",{children:"Usage notes"}),t.jsx("dd",{children:u.usageNotes||"â"}),t.jsx("dt",{children:"Category"}),t.jsx("dd",{children:u.category||"â"}),t.jsx("dt",{children:"Tags"}),t.jsx("dd",{children:u.tags?.join(", ")||"â"}),t.jsx("dt",{children:"Updated"}),t.jsx("dd",{children:new Date(u.updatedAt).toLocaleString()})]}),t.jsx(lh,{enabled:U,versionId:u.jupyterNotebookVersionId,sourceFilename:u.objects?.[0]?.originalFilename}),t.jsx(yh,{resource:u,request:l,actorId:c?.id,scope:i})]}):null,"assignments"===V&&ye?t.jsx(nh,{resource:u,request:l,onSaved:Ee,assignmentsEndpoint:`/api/workspace/v1/resource-packs/${u.id}/permissions?scope=${i}
2`,peopleEndpoint:"/api/employee/people",teamsEndpoint:`/api/workspace/v1/teams?scope=${i}`,capabilityLevels:!0}):null,"activity"===V&&ye?t.jsx("ol",{className:"resource-drive-activity",children:(u.events||[]).map(e=>t.jsxs("li",{children:[t.jsx("strong",{children:String(e.eventType).replaceAll("."," ")}),t.jsxs("span",{children:[e.actorName||"System"," · ",new Date(e.createdAt).toLocaleString()]})]},e.id))}):null]})]}):null}),t.jsx(cc,{isOpen:_,onClose:()=>T(!1),title:"Edit Resource details",description:"Keep the context people need to use this Resource correctly.",variant:"wide",children:B?t.jsxs("form",{onSubmit:async e=>{e.preventDefault(),P(null);try{const e=await l(`/api/workspace/v1/resource-packs/${u.id}?scope=${i}`,{method:"PATCH",body:JSON.stringify({...B,tags:B.tags.split(",").map(e=>e.trim()).filter(Boolean)})});h(e.data.resource),T(!1),await he()}catch(t){P(t.safeMessage||"Resource details could not be saved.")}},children:[t.jsx(jh,{value:B,onChange:W}),D?t.jsx(oc,{type:"error",children:D}):null,t.jsxs(lc,{children:[t.jsx(ec,{type:"button",variant:"ghost",onClick:()=>T(!1),children:"Cancel"}),t.jsx(ec,{type:"submit",variant:"primary",children:"Save changes"})]})]}):null}),t.jsx(cc,{isOpen:E&&xe,onClose:()=>I(!1),title:"Add Resource",description:"Give people enough context to use these files confidently.",variant:"wide",children:t.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),xe){P(null);try{const e=(await l(`/api/workspace/v1/resource-packs?scope=${i}`,{method:"POST",body:JSON.stringify({...z,tags:z.tags.split(",").map(e=>e.trim()).filter(Boolean)})})).data.resource;if(N.length){const t=await ie.uploadFiles(e.id,N,{archiveMode:C,folder:N.some(e=>(e.webkitRelativePath||e.relativePath||"").includes("/"))}),a=t.filter(e=>"rejected"===e.status);if(a.length)return void P(`${a.length} of ${t.length} files failed. Successful uploads remain queued for scanning; retry failed items below.`)}I(!1),S([]),q(mh),await he(),s?.(e.id)}catch(t){P(t.safeMessage||"The Resource could not be created.")}}else I(!1)},children:[t.jsx(jh,{value:z,onChange:q}),t.jsxs(ic,{legend:"Files",description:"Files upload directly to the private Resource S3 bucket.",children:[t.jsxs("div",{className:"resource-drive-choose",children:[t.jsx(ec,{type:"button",variant:"ghost",onClick:()=>Y.current?.click(),children:"Choose files"}),t.jsx(ec,{type:"button",variant:"ghost",onClick:()=>Q.current?.click(),children:"Choose folder"}),t.jsx(ec,{type:"button",variant:"ghost",onClick:()=>X.current?.click(),children:"Choose ZIP"})]}),N.length?t.jsxs(t.Fragment,{children:[t.jsx("ul",{children:N.map(e=>t.jsxs("li",{children:[e.webkitRelativePath||e.relativePath||e.name," ·"," ",Nc(e.size)]},`${e.webkitRelativePath||e.relativePath||e.name}-${e.size}`))}),N.some(gh)?t.jsxs("fieldset",{children:[t.jsx("legend",{children:"How should the ZIP be added?"}),t.jsxs("label",{children:[t.jsx("input",{type:"radio",name:"archiveMode",value:"extract",checked:"extract"===C,onChange:()=>R("extract")}),"Extract its files into the Resource"]}),t.jsxs("label",{children:[t.jsx("input",{type:"radio",name:"archiveMode",value:"store",checked:"store"===C,onChange:()=>R("store")}),"Keep the ZIP as one file"]})]}):null]}):t.jsx("p",{children:"No files selected yet."})]}),t.jsx(vh,{upload:ie}),D?t.jsx(oc,{type:"error",children:D}):null,t.jsxs(lc,{children:[t.jsx(ec,{type:"button",variant:"ghost",onClick:()=>I(!1),children:"Cancel"}),t.jsx(ec,{variant:"primary",type:"submit",disabled:!xe||!z.title||N.some(gh)&&!C,children:N.length?"Upload Resource":"Create Resource"})]})]})})]})}function wh({selectedResourceId:e=null,selectedFolderId:a=null,onSelectedResourceChange:n,onSelectedFolderChange:s,scope:r="mine"}){return t.jsx(kh,{selectedResourceId:e,selectedFolderId:a,onSelectedResourceChange:n,onSelectedFolderChange:s,scope:r})}function Nh({project:e,onSelect:a,opening:n=!1}){const s=e.taskSummary||{},r=Number(s.total||0),i=Number(s.completed||0),l=Number(s.blocked||0),o=Number(s.overdue||0),c=r?Math.round(i/r*100):0,d="overdue"===Ko(e.dueDate).key||o>0?"danger":l>0?"warning":"neutral",u=e.status&&"active"!==e.status,h=["high","urgent"].includes(e.priority);return t.jsxs(Qo,{className:"employee-project-card",tone:d,boundary:"elevated",children:[t.jsxs("header",{className:"employee-project-card-header",children:[t.jsx("h3",{className:"ws-record-title",children:e.name}),u||h?t.jsxs("div",{className:"employee-project-badges","aria-label":"Project status and priority",children:[u?t.jsx(tc,{value:e.status}):null,h?t.jsx(ac,{value:e.priority}):null]}):null]}),t.jsx(wd,{text:e.description||"No project description.",className:"employee-project-description ws-body"}),t.jsxs("div",{className:"employee-project-progress",children:[t.jsxs("div",{children:[t.jsx("span",{className:"ws-label",children:"Task progress"}),t.jsx("span",{className:"ws-meta",children:r?`${i} of ${r} complete`:"No tasks yet"})]}),t.jsxs("progress",{max:"100",value:c,"aria-label":r?`${e.name} task progress: ${c}%`:`${e.name} has no tasks`,children:[c,"%"]})]}),l||o?t.jsxs("div",{className:"employee-project-health","aria-label":"Project task health",children:[l?t.jsxs("span",{className:"is-warning",children:[t.jsx(be,{size:15,"aria-hidden":"true"}),t.jsx("strong",{children:l})," ",t.jsx("span",{children:"Blocked"})]}):null,o?t.jsxs("span",{className:"is-danger",children:[t.jsx(be,{size:15,"aria-hidden":"true"}),t.jsx("strong",{children:o})," ",t.jsx("span",{children:"Overdue"})]}):null]}):null,t.jsxs("div",{className:"employee-project-context ws-meta",children:[t.jsxs("span",{children:["Owner: ",e.owner?.name||"Unassigned"]}),t.jsx(nc,{value:e.dueDate})]}),t.jsx("footer",{className:"employee-project-card-footer",children:t.jsx(ec,{variant:"secondary","data-
2project-open-id":e.id,disabled:n,"aria-busy":n?"true":void 0,onClick:t=>a(e,t.currentTarget),children:n?"Opening projectâ¦":"Open Project"})})]})}const Sh=["planned","active","paused","completed","cancelled"],Ch=["low","normal","high","urgent"];function Rh(e){return{name:e?.name||"",description:e?.description||"",status:e?.status||"planned",priority:e?.priority||"normal",startDate:e?.startDate?String(e.startDate).slice(0,10):"",dueDate:e?.dueDate?String(e.dueDate).slice(0,10):""}}function Eh(e){return e?.owner?.id?[{userId:e.owner.id,name:e.owner.name}]:[]}function Ih(e){return{form:Rh(e),ownerSelection:Eh(e)}}function _h(e){return JSON.stringify({...e.form,ownerUserId:e.ownerSelection[0]?.userId||null})}function Th({project:n,request:s,onSaved:r,onCancel:i=null,onBeforeCancel:l=null,onDirtyChange:o=null,onDirtyDescriptorChange:c=null,onPendingChange:d=null,manageNavigationGuards:u=!0,showHeading:h=!0,endpointPrefix:m="/api/admin/projects"}){const[p,g]=e.useState(()=>Ih(n)),[f,b]=e.useState(()=>Rh(n)),[x,v]=e.useState(()=>Eh(n)),[j,y]=e.useState(!1),[k,w]=e.useState(null),[N,S]=e.useState(!1),[C,R]=e.useState(!1),E=e.useRef(n?.id||null),I=e.useRef(null),_=e.useRef(null),T=e.useRef(null);e.useEffect(()=>{const e=Ih(n),t=n?.id||null;g(e),b(e.form),v(e.ownerSelection),w(null),E.current!==t&&(S(!1),R(!1)),E.current=t},[n]);const A=Boolean(n?.id),O=A?"project settings":"new project",D=A?"Saving project settingsâplease wait before leaving.":"Creating projectâplease wait before leaving.",P=e.useMemo(()=>_h({form:f,ownerSelection:x})!==_h(p),[p,f,x]),L=(e,t)=>{w(null),S(!1),b(a=>({...a,[e]:t}))},$=a.useCallback(()=>{b(p.form),v(p.ownerSelection),w(null),S(!1)},[p]);e.useEffect(()=>{o?.(P),c?.(P,P?{label:"project settings",message:"Discard your unsaved project settings changes?",discard:$}:null)},[P,o,c,$]),e.useEffect(()=>()=>{o?.(!1),c?.(!1,null),d?.(!1,null)},[o,c,d]),e.useEffect(()=>{if(!u||!P)return;const e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[P,u]),e.useEffect(()=>{if(!u||!P)return;const e=e=>{const t=e.target.closest?.("a[href]");if(!t)return;const a=t.getAttribute("href")||"";"_blank"===t.target||a.startsWith("#")||/^[a-z]+:\/\//i.test(a)||window.confirm("Discard your unsaved project changes?")||(e.preventDefault(),e.stopPropagation())};return globalThis.document.addEventListener("click",e,!0),()=>globalThis.document.removeEventListener("click",e,!0)},[P,u]);const M="name"===k?.field?k.message:null,U="dates"===k?.field?k.message:null,F=k&&!k.field?k:null,z=j?{message:D,tone:"saving"}:F?{message:F.message,tone:F.type||"error"}:C?{message:P?"Unsaved changes. Your previous save succeeded, but project information may be out of date. Save or cancel these changes, then reload to update this view.":"Project saved, but the project list or detail view could not refresh. Reload to update this view.",tone:"warning"}:N?{message:"Project saved.",tone:"success"}:P?{message:"Unsaved changes",tone:"dirty"}:{message:A?"No changes":"Ready to create",tone:"pristine"};return t.jsxs("form",{className:"projects-admin-editor","aria-label":n?.id?"Edit project":"Create project","aria-busy":j,onSubmit:async e=>{if(e.preventDefault(),j||A&&!P)return;if(!f.name.trim())return w({field:"name",message:"Project name is required."}),void requestAnimationFrame(()=>I.current?.focus());if(f.startDate&&f.dueDate&&f.dueDate<f.startDate)return w({field:"dates",message:"Due date must be on or after the start date."}),void requestAnimationFrame(()=>_.current?.focus());d?.(!0,{label:O,message:D}),y(!0),w(null),S(!1);const t={...f,name:f.name.trim(),ownerUserId:x[0]?.userId||null,startDate:f.startDate||null,dueDate:f.dueDate||null};try{const e=n?.id?`${m}/${n.id}`:m,a=await s(e,{method:n?.id?"PATCH":"POST",body:JSON.stringify(t)}),i=a?.data?.project?Ih(a.data.project):{form:{...f,name:t.name,startDate:t.startDate||"",dueDate:t.dueDate||""},ownerSelection:x};g(i),b(i.form),v(i.ownerSelection),o?.(!1),c?.(!1,null),S(!0);try{await(r?.(a?.data?.project||null)),R(!1)}catch{S(!1),R(!0),requestAnimationFrame(()=>T.current?.focus())}}catch(a){S(!1),w({field:null,message:a?.safeMessage||a?.message||"Unable to save this project."}),requestAnimationFrame(()=>T.current?.focus())}finally{y(!1),d?.(!1,null)}},noValidate:!0,children:[h?t.jsx("h3",{children:n?.id?"Edit Project":"Create Project"}
2):null,t.jsxs(ic,{legend:"Project basics",description:"Name the work and explain its outcome.",disabled:j,children:[t.jsx(rc,{label:"Name",required:!0,error:M,className:"projects-admin-field--wide",children:t.jsx("input",{ref:I,value:f.name,onChange:e=>L("name",e.target.value),autoFocus:!n?.id,maxLength:200})}),t.jsx(rc,{label:"Description",className:"projects-admin-field--wide",children:t.jsx("textarea",{rows:"5",value:f.description,onChange:e=>L("description",e.target.value)})})]}),t.jsxs(ic,{legend:"Planning",description:"Set working status, priority, and schedule.",disabled:j,children:[t.jsx(rc,{label:"Status",children:t.jsx("select",{value:f.status,onChange:e=>L("status",e.target.value),children:Sh.map(e=>t.jsx("option",{value:e,children:e.replaceAll("_"," ")},e))})}),t.jsx(rc,{label:"Priority",children:t.jsx("select",{value:f.priority,onChange:e=>L("priority",e.target.value),children:Ch.map(e=>t.jsx("option",{value:e,children:e},e))})}),t.jsx(rc,{label:"Start date",children:t.jsx("input",{type:"date",value:f.startDate,onChange:e=>L("startDate",e.target.value)})}),t.jsx(rc,{label:"Due date",error:U,children:t.jsx("input",{ref:_,type:"date",value:f.dueDate,min:f.startDate||void 0,onChange:e=>L("dueDate",e.target.value)})})]}),t.jsx(ic,{legend:"Ownership",description:"Choose one accountable owner, or leave the project unassigned.",disabled:j,children:t.jsx("div",{className:"projects-admin-owner projects-admin-field--wide",children:t.jsx(ah,{label:"Project owner",value:x,onChange:e=>{w(null),S(!1),v(e)},multiple:!1,allowEmpty:!0})})}),t.jsx("div",{className:"projects-admin-editor-footer",children:t.jsxs(lc,{className:"projects-admin-editor-actions",children:[t.jsx("p",{ref:T,className:`projects-admin-save-state is-${z.tone}`,role:"status","aria-live":"polite","aria-atomic":"true",tabIndex:j||F||C?-1:void 0,children:z.message}),A||i?t.jsx(ec,{variant:"ghost",onClick:async()=>{l&&!1===await l()||($(),i?.())},disabled:j||A&&!P,children:"Cancel"}):null,t.jsx(ec,{variant:"primary",type:"submit",disabled:j||A&&!P,children:j?n?.id?"Saving projectâ¦":"Creating projectâ¦":n?.id?"Save Project":"Create Project"})]})})]})}function Ah(e=[]){return e.map(e=>({userId:e.userId,projectRole:e.projectRole,name:e.name,title:e.title,personnelType:e.personnelType,status:e.status}))}function Oh(e=[]){return e.map(e=>({teamId:e.teamId,projectRole:e.projectRole,name:e.name,description:e.description,memberCount:e.memberCount}))}function Dh(e,t){return JSON.stringify({users:e.map(e=>[e.userId,e.projectRole]).sort(([e],[t])=>e.localeCompare(t)),teams:t.map(e=>[e.teamId,e.projectRole]).sort(([e],[t])=>e.localeCompare(t))})}function Ph({project:a,request:n,onSaved:s,onDirtyChange:r=null,onPendingChange:i=null,endpointPrefix:l="/api/admin/projects"}){const o=$s(),[c,d]=e.useState([]),[u,h]=e.useState([]),[m,p]=e.useState(null),[g,f]=e.useState([]),[b,x]=e.useState([]),[v,j]=e.useState(null),[y,k]=e.useState({status:"clean",message:null}),w=e.useRef(!1),N=e.useRef(null),C=e.useRef(null),R=e.useRef(null),E=e.useRef(null),I=e.useRef(null),_=e.useRef(null),T=e.useRef(0),A=e.useRef(!1);e.useEffect(()=>{if(!a||v)return;const e=Ah(a.directMembers),t=Oh(a.assignedTeams);d(e),h(t),f(e),x(t),p(a.assignmentFingerprint||null)},[v,a]);const O=e.useMemo(()=>Dh(g,b)!==Dh(c,u),[u,c,b,g]);e.useEffect(()=>{v&&(O&&"clean"===y.status&&k({status:"dirty",message:null}),O||"dirty"!==y.status||k({status:"clean",message:null}))},[O,v,y.status]);const D=e.useCallback(()=>{f(Ah(c)),x(Oh(u)),k({status:"clean",message:null}),j(null)},[u,c]);if(e.useEffect(()=>{const e="teams"===v?"team":"member";r?.(Boolean(v&&O),v&&O?{label:`project ${e} assignments`,message:`Discard your unsaved project ${e} assignment changes?`,discard:D}:null)},[O,D,v,r]),e.useEffect(()=>()=>{T.current+=1,A.current=!1,r?.(!1,null),i?.(!1,null)},[r,i]),!a)return null;const P=e=>{A.current||"saving"===y.status||(f(Ah(c)),x(Oh(u)),k({status:"clean",message:null}),R.current="teams"===e?_.current:I.current,j(e))},L=async()=>{if(A.current||"saving"===y.status||w.current)return!1;if(!O)return D(),!0;w.current=!0,N.current=document.activeElement===document.body?C.current:document.activeElement;const e="teams"===v?"team":"member";try{return await o({title:`Discard ${e} assignment draft?`,message:`Your unsaved project ${e} assignment changes will be lost.`,confirmLabel:`Discard ${e} changes`,cancelLabel:"Keep editing",confirmVariant:"danger"})?(D(),requestAnimationFrame(()=>R.current?.focus()),!0):(requestAnimationFrame(()=>{N.current?.isConnected&&N.current.focus()}),!1)}finally{w.current=!1}},$=e=>{const t=Ah(e.users),a=Oh(e.teams);d(t),h(a),f(t),x(a),p(e.assignmentFingerprint)},M=y.message?t.jsx(oc,{ref:"saving"===y.status?E:null,tabIndex:"saving"===y.status?-1:void 0,type:"error"===y.status||"conflict"===y.status?"error":"warning"===y.status?"warning":"saved"===y.status?"success":"status",className:"project-assignments-feedback",children:y.message}):null;return t.jsxs("div",{className:"project-assignments-management",children:[t.jsxs("div",{className:"project-assignments-actions","aria-label":"Project assignment actions",children:[t.jsxs(ec,{ref:I,variant:"secondary",disabled:"saving"===y.status,onClick:()=>P("users"),children:[t.jsx(S,{size:16,"aria-hidden":"true"})," Manage members"]}),t.jsx(ec,{ref:_,variant:"secondary",disabled:"saving"===y.status,onClick:()=>P("teams"),children:"Manage teams"})]}),v?null:M,t.jsx(cc,{isOpen:Boolean(v),onClose:L,returnFocusRef:R,title:"teams"===v?"Manage project teams":"Manage project members",description:"teams"===v?`${b.length} ${1===b.length?"team":"teams"} selected`:`${g.length} ${1===g.length?"person":"people"} selected`,className:"project-assignments-overlay",busy:"saving"===y.status,footer:t.jsxs(lc,{className:"project-assignments-overlay-actions",children:[t.jsx("span",{className:"project-assignments-dirty-state","aria-live":"polite",children:O?"Unsaved changes":"saved"===y.status?"Saved":"No changes"}),"conflict"===y.status?t.jsx(ec,{variant:"secondary",onClick:async()=>{k({status:"saving",message:"Reloading current assignmentsâ¦"});try{const e=await n(`${l}/${a.id}/assignments`);$(e.data);try{await(s?.(e.data))}catch{return void k({status:"warning",message:"Current assignments reloaded, but the rest of this view could not refresh. Reload to see the latest project details."})}k({status:"clean",message:"Current assignments reloaded."})}catch(e){k({status:"error",message:e?.safeMessage||e?.message||"Unable to reload assignments."})}},children:"Reload current assignments"}):null,t.jsx(ec,{variant:"ghost",onClick:L,disabled:"saving"===y.status,children:"Cancel"}),t.jsx(ec,{variant:"primary",onClick:async()=>
2{if(!O||A.current||"saving"===y.status)return;const e=++T.current;A.current=!0,i?.(!0,{label:"project assignments",message:"Saving project assignmentsâplease wait before leaving.",restoreFocus:()=>{const e=E.current;return!!e?.isConnected&&(e.focus(),document.activeElement===e)}}),k({status:"saving",message:"Saving assignments⦠Please wait before closing."});try{const t=await n(`${l}/${a.id}/assignments`,{method:"PUT",body:JSON.stringify({users:g,teams:b,expectedAssignmentFingerprint:m})});if(e!==T.current)return;$(t.data),r?.(!1,null),k({status:"saving",message:"Assignments saved. Refreshing projectâ¦"});try{await(s?.(t.data))}catch{if(e!==T.current)return;return k({status:"warning",message:"Assignments saved, but this view could not refresh. Reload to see the latest."}),void j(null)}if(e!==T.current)return;k({status:"saved",message:"Assignments saved."}),j(null)}catch(t){if(e!==T.current)return;if("PROJECT_ASSIGNMENT_CONFLICT"===t?.code)return void k({status:"conflict",message:"Someone else changed this project. Your draft is still unsaved; reload the current assignments before applying it again."});k({status:"error",message:t?.safeMessage||t?.message||"Assignments could not be saved. Your draft is still unsaved."})}finally{e===T.current&&(A.current=!1,i?.(!1,null))}},disabled:!O||"saving"===y.status||"conflict"===y.status,children:"saving"===y.status?"Applyingâ¦":"Apply"})]}),children:t.jsxs("div",{className:"project-assignments-overlay-body",onFocusCapture:e=>{C.current=e.target},children:["users"===v?t.jsx(ah,{value:g,onChange:f,allowedRoles:["manager","contributor","viewer"],label:"Available people",disabled:"saving"===y.status}):null,"teams"===v?t.jsx(th,{value:b,onChange:x,allowedRoles:["contributor","viewer"],label:"Available teams",disabled:"saving"===y.status}):null,M]})})]})}const Lh="temp-task:";function $h(){return globalThis.crypto?.randomUUID?`${Lh}${globalThis.crypto.randomUUID()}`:`${Lh}${Date.now()}-${Math.random().toString(36).slice(2)}`}function Mh(e){return Boolean(e?.id&&String(e.id).startsWith(Lh))}function Uh(e){return Mh(e)||e?.isTemporary||"failed"===e?.createStatus}function Fh(e){if(!e)return null;const t=new Map((e.columns||[]).map(e=>[e.id,[]]));return(e.tasks||[]).forEach(e=>{t.has(e.columnId)&&t.get(e.columnId).push(e)}),{...e,columns:(e.columns||[]).map(e=>({...e,tasks:t.get(e.id)||[]}))}}function zh(e,t){if(!e)return e;const a=(n=t,n?(n.columns||[]).flatMap(e=>e.tasks||[]).filter(e=>Uh(e)||"pending"===e.createStatus):[]).filter(t=>!e.columns?.some(e=>e.tasks?.some(e=>e.id===t.id)));var n;return a.length?{...e,columns:(e.columns||[]).map(e=>({...e,tasks:[...e.tasks||[],...a.filter(t=>t.columnId===e.id)]}))}:e}function qh(e,t){return e?{...e,columns:(e.columns||[]).map(e=>({...e,tasks:(e.tasks||[]).map(a=>t(a,e))}))}:e}function Bh(e,t){for(const a of e?.columns||[]){const e=(a.tasks||[]).findIndex(e=>e.id===t);if(e>=0)return{column:a,index:e,task:a.tasks[e]}}return null}function Wh(e,t){return e?{...e,columns:(e.columns||[]).map(e=>({...e,tasks:(e.tasks||[]).filter(e=>e.id!==t)}))}:e}function Vh(){const[t,a]=e.useState(null),[n,s]=e.useState({}),[r,i]=e.useState(null),l=e.useRef(null),o=e.useRef(new Map),c=e.useRef(new Map),d=e.useRef(new Map),u=e.useRef(0);e.useEffect(()=>()=>{o.current.forEach(e=>clearTimeout(e)),o.current.clear(),c.current.forEach(e=>clearTimeout(e)),c.current.clear()},[]),e.useEffect(()=>{l.current=t},[t]);const h=e.useCallback(e=>{a(t=>zh(Fh(e),t))},[]),m=e.useCallback(({columnId:e,title:t,tempId:n=$h()})=>(a(a=>a?{...a,columns:(a.columns||[]).map(s=>{if(s.id!==e)return s;const r=s.tasks?.length||0;return{...s,tasks:[...s.tasks||[],{id:n,projectId:a.project?.id||a.board?.projectId,boardId:a.board?.id,columnId:e,title:t,description:"",priority:"normal",dueDate:null,position:r,isBlocked:!1,blockerReason:null,version:0,assignees:[],linkedResources:[],resourceCount:0,commentCount:0,createStatus:"pending",createError:null,isTemporary:!0}]}})}:a),n),[]),p=e.useCallback(e=>{a(t=>qh(t,t=>t.id===e?{...t,createStatus:"pending",createError:null,isTemporary:!0}:t))},[]),g=e.useCallback((e,t)=>{const n={...t,createStatus:"confirmed",createError:null};a(t=>qh(t,t=>t.id===e?n:t));const s=setTimeout(()=>{a(e=>qh(e,e=>e.id===t.id&&"confirmed"===e.createStatus?{...e,createStatus:null}:e)),o.current.delete(t.id)},1200);
2o.current.set(t.id,s)},[]),f=e.useCallback((e,t)=>{a(a=>qh(a,a=>a.id===e?{...a,createStatus:"failed",createError:t||"Unable to create task.",isTemporary:!0}:a))},[]),b=e.useCallback(e=>{a(t=>Wh(t,e))},[]),x=e.useCallback((e,t)=>{a(a=>qh(a,a=>a.id!==e||Uh(a)?a:function(e,t){return e&&t?{...e,...t,id:e.id,projectId:e.projectId,boardId:e.boardId,columnId:e.columnId,position:e.position,moveStatus:e.moveStatus,createStatus:e.createStatus,createError:e.createError,isTemporary:e.isTemporary}:e}(a,t)))},[]),v=e.useCallback(e=>{a(t=>Wh(t,e))},[]),j=e.useCallback(({task:e,targetColumnId:t,targetIndex:n})=>{const r=e?.id;if(!r||Uh(e)||d.current.has(r))return{ok:!1,changed:!1,reason:"disabled"};const o=l.current,c=function(e,t,a,n){if(!e||!t||!a)return{board:e,changed:!1,reason:"missing"};const s=Bh(e,t),r=(e.columns||[]).find(e=>e.id===a);if(!s||!r)return{board:e,changed:!1,reason:"missing"};if(Uh(s.task))return{board:e,changed:!1,reason:"unsaved"};const i=r.id===s.column.id?Math.max(0,(r.tasks||[]).length-1):r.tasks?.length||0,l=Math.max(0,Math.min(Number.isFinite(Number(n))?Number(n):0,i)),o={...s.task,columnId:a,moveStatus:"pending"},c=(e.columns||[]).map(e=>{let n=(e.tasks||[]).filter(e=>e.id!==t);return e.id===a&&(n=[...n.slice(0,l),o,...n.slice(l)]),e.id!==s.column.id&&e.id!==a||(n=n.map((e,t)=>e.position===t?e:{...e,position:t})),{...e,tasks:n}}),d={...e,columns:c},u=Bh(d,t),h=s.column.id!==u?.column.id||s.index!==u?.index;return{board:h?d:e,changed:h,sourceColumnId:s.column.id,sourceIndex:s.index,targetColumnId:a,targetIndex:l,reason:h?void 0:"noop"}}(o,r,t,n);if(!c.changed)return{ok:!0,changed:!1,reason:c.reason||"noop"};const h=++u.current,m={mutationId:h,taskId:r,sourceColumnId:c.sourceColumnId,sourceIndex:c.sourceIndex,targetColumnId:c.targetColumnId,targetIndex:c.targetIndex,previousBoard:o};return d.current.set(r,m),s(e=>({...e,[r]:m})),i(null),a(c.board),{ok:!0,changed:!0,mutationId:h,taskId:r,targetIndex:c.targetIndex}},[]),y=e.useCallback(e=>{a(t=>qh(t,t=>t.id===e&&"confirmed"===t.moveStatus?{...t,moveStatus:null}:t)),c.current.delete(e)},[]),k=e.useCallback(({taskId:e,mutationId:t,snapshot:n})=>{const r=d.current.get(e);if(!r||r.mutationId!==t)return!1;d.current.delete(e),s(t=>{const a={...t};return delete a[e],a}),a(t=>qh(zh(Fh(n),t),t=>t.id===e?{...t,moveStatus:"confirmed"}:t));const i=c.current.get(e);i&&clearTimeout(i);const l=setTimeout(()=>y(e),800);return c.current.set(e,l),!0},[y]),w=e.useCallback(({taskId:e,mutationId:t,message:n,code:r})=>{const l=d.current.get(e);return!(!l||l.mutationId!==t)&&(d.current.delete(e),s(t=>{const a={...t};return delete a[e],a}),a(l.previousBoard),i({taskId:e,code:r||"MOVE_FAILED",message:n||"Unable to move task. The card was restored."}),!0)},[]),N=e.useCallback(()=>i(null),[]);return{board:t,pendingMovesByTaskId:n,movementError:r,replaceBoard:h,addOptimisticCreate:m,markCreateRetry:p,confirmOptimisticCreate:g,failOptimisticCreate:f,removeOptimisticCreate:b,patchTaskConfirmed:x,removeTaskConfirmed:v,beginOptimisticMove:j,confirmOptimisticMove:k,failOptimisticMove:w,clearMovementError:N}}const Hh=new Set(["TASK_VERSION_CONFLICT","TASK_NOT_FOUND","BOARD_COLUMN_NOT_FOUND","PROJECT_BOARD_NOT_FOUND"]);function Kh(e){return 1===e.length?e[0]:2===e.length?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function Gh(e=[],t=3){const a=(e||[]).filter(Boolean);if(!a.length)return"Unassigned";const n=a.slice(0,t),s=n.map(e=>e.name||"Assigned user"),r=a.length-n.length;return r?`Assigned to ${Kh([...s,`${r} ${1===r?"other":"others"}`])}`:`Assigned to ${Kh(s)}`}function Jh(e){const t=String(e||"").trim();if(!t)return"?";const a=t.split(/\s+/).filter(Boolean);return 1===a.length?a[0].slice(0,2).toUpperCase():`${a[0][0]}${a[a.length-1][0]}`.toUpperCase()}function Yh({person:a,size:n}){const[s,r]=e.useState(null),i=a.name||"Assigned user",l=a.avatarUrl||a.pictureUrl||null,o=Boolean(l)&&s!==l;return t.jsx("span",{className:"avatar-stack__item",style:{"--avatar-size":`${n}px`},title:i,children:o?t.jsx("img",{className:"avatar-stack__image",src:l,alt:"",loading:"lazy",decoding:"async",onError:()=>r(l)}
2):t.jsx("span",{className:"avatar-stack__fallback","aria-hidden":"true",children:Jh(a.name)})})}function Qh({people:e=[],max:a=3,size:n=24,className:s=""}){const r=(e||[]).filter(Boolean);if(!r.length)return null;const i=r.slice(0,a),l=r.length-i.length,o=Gh(r,a);return t.jsxs("span",{className:["avatar-stack",s].filter(Boolean).join(" "),role:"img","aria-label":o,title:o,children:[i.map((e,a)=>t.jsx(Yh,{person:e,size:n},e.userId||e.id||e.name||a)),l>0?t.jsxs("span",{className:"avatar-stack__item avatar-stack__overflow",style:{"--avatar-size":`${n}px`},"aria-hidden":"true",children:["+",l]}):null]})}const Xh="project-task-column:";function Zh({columnName:a,draft:n,onDraftChange:s,onSubmit:r,onCancel:i}){const l=e.useRef(null),o=e.useId(),c=n.trim(),[d,u]=e.useState("");e.useEffect(()=>{l.current?.focus()},[]);const h=()=>{const e=n.trim();if(!e)return u("Task title is required."),void l.current?.focus();if(e.length>240)return u("Task title must be 240 characters or fewer."),void l.current?.focus();u(""),r(e);const t=()=>l.current?.focus();globalThis.requestAnimationFrame?requestAnimationFrame(t):setTimeout(t,0)};return t.jsxs("div",{className:"project-task-composer","data-testid":"inline-card-composer",children:[t.jsxs("label",{htmlFor:o,children:["Card title for ",a]}),t.jsx("input",{ref:l,id:o,value:n,onChange:e=>{u(""),s(e.target.value)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),h()),"Escape"===e.key&&(e.preventDefault(),i())},maxLength:240,placeholder:"Enter a title for this card","aria-invalid":d?"true":"false","aria-describedby":d?`${o}-error`:void 0}),d?t.jsx("p",{id:`${o}-error`,className:"project-task-composer-error",children:d}):null,t.jsxs("div",{className:"project-task-composer-actions",children:[t.jsx(ec,{size:"compact",variant:"primary",onClick:h,disabled:!c,children:"Add"}),t.jsx(ec,{size:"compact",variant:"ghost",onClick:i,children:"Cancel"})]})]})}function em({task:s,columns:r,currentColumnId:i,index:l,columnTaskCount:o,onMoveTask:c}){const[d,u]=e.useState(!1),[h,m]=e.useState(null),p=e.useId(),g=e.useRef(null),f=e.useRef(null),b=r.find(e=>e.id===i),x=r.filter(e=>e.id!==i),v=a.useCallback(()=>{const e=g.current;if(!e)return;const t=e.getBoundingClientRect(),a=Math.max(8,Math.min(t.right-224,window.innerWidth-224-8)),n=window.innerHeight-t.bottom,s=n<260&&t.top>n;m({left:a,top:s?void 0:t.bottom+6,bottom:s?window.innerHeight-t.top+6:void 0,width:224})},[]);e.useLayoutEffect(()=>{d&&v()},[d,v]),e.useEffect(()=>{if(!d)return;const e=e=>{g.current?.contains(e.target)||f.current?.contains(e.target)||u(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),u(!1),g.current?.focus())},a=()=>v();return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),window.addEventListener("resize",a),window.addEventListener("scroll",a,!0),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t),window.removeEventListener("resize",a),window.removeEventListener("scroll",a,!0)}},[d,v]);const j=(e,t)=>{u(!1),g.current?.focus();const a=c?.(s,e,t);a&&"function"==typeof a.catch&&a.catch(()=>{})},y=xs();return t.jsxs("div",{className:"project-task-move-menu",children:[t.jsx("button",{ref:g,type:"button",className:"project-task-icon-button","aria-label":`Move ${s.title} to another position`,"aria-haspopup":"menu","aria-expanded":d?"true":"false","aria-controls":d?p:void 0,onClick:()=>u(e=>!e),children:t.jsx(at,{size:16,"aria-hidden":"true"})}),d&&y?n.createPortal(t.jsxs("div",{ref:f,id:p,className:"project-task-move-popover",role:"group","aria-label":`Move ${s.title}`,style:{position:"fixed",left:h?.left??-9999,top:h?.top,bottom:h?.bottom,width:h?.width??224,visibility:h?"visible":"hidden"},children:[t.jsx("p",{children:b?.name||"Column"}),t.jsx("button",{type:"button",disabled:l<=0,onClick:()=>j(i,0),children:"Move to top"}),t.jsx("button",{type:"button",disabled:l<=0,onClick:()=>j(i,l-1),children:"Move up"}),t.jsx("button",{type:"button",disabled:l>=o-1,onClick:()=>j(i,l+1),children:"Move down"}),t.jsx("button",{type:"button",disabled:l>=o-1,onClick:()=>j(i,Math.max(0,o-1)),children:"Move to bottom"}),x.length?t.jsx("hr",{}):null,x.map(e=>t.jsxs("button",{type:"button",onClick:()=>j(e.id,e.tasks?.length||0),children:["Move to ",e.name]},e.id))]}),y):null]})}const tm=e.memo(function({task:a,isSelected:n=!1,index:s=0,columnTaskCount:r=0,columns:i=[],enableDrag:l=!1,showMoveControls:o=!1,isDragging:c=!1,isOverlay:d=!1,dragDisabled:u=!0,dragHandleProps:h={},cardRef:m,onOpen:p,onMoveTask:g,onRetryCreate:f,onRemoveCreate:b}
2){const x=e.useId(),v=Mh(a)||a.isTemporary,j="pending"===a.createStatus,y="failed"===a.createStatus,k="confirmed"===a.createStatus,w="pending"===a.moveStatus,N="confirmed"===a.moveStatus,S=v||j||y,C=Ko(a.dueDate),R="overdue"===C.key&&!a.completedAt,E=C.known&&!a.completedAt,I=d?"":function(e){const t=String(e.description||"").replace(/\s+/g," ").trim();return t.length>140?`${t.slice(0,139)}â¦`:t}(a),_=a.assignees?.length?Gh(a.assignees,3):null,T=y||a.isBlocked||a.dependencyBlocked||R?"danger":"urgent"===a.priority||"high"===a.priority?"warning":a.completedAt?"complete":"neutral",A=["project-task-card",n?"project-task-card--active":"",j?"project-task-card--pending":"",y?"project-task-card--failed":"",k?"project-task-card--confirmed":"",w?"project-task-card--moving":"",N?"project-task-card--confirmed":"",l?"project-task-card--draggable":"",o?"project-task-card--has-menu":"",c?"project-task-card--dragging":"",d?"project-task-card--overlay":""].filter(Boolean).join(" ");return t.jsxs(Qo,{as:"article",tone:T,boundary:"elevated",className:A,"data-task-id":a.id,"aria-busy":j||w?"true":void 0,"aria-live":j||y||w?"polite":void 0,children:[l?t.jsx("button",{ref:h.setActivatorNodeRef,type:"button",className:"project-task-drag-handle","aria-label":`Move task ${a.title}`,disabled:u,...h.attributes,...h.listeners,children:t.jsx(tt,{size:16,"aria-hidden":"true"})}):null,t.jsxs("button",{ref:m,type:"button",className:"project-task-card-main",disabled:S,onClick:()=>p?.(a),"aria-label":v?`Unsaved task ${a.title}`:`Open task ${a.title}`,"aria-describedby":_?x:void 0,children:[t.jsx("strong",{className:"project-task-card-title",children:a.title}),I?t.jsx("span",{className:"project-task-card-description",children:I}):null,a.isBlocked||a.dependencyBlocked||["high","urgent"].includes(a.priority)||E?t.jsxs("span",{className:"project-task-card-semantic",children:[a.isBlocked?t.jsx(li,{variant:"danger",className:"project-task-card-blocked",children:"Blocked"}):null,a.dependencyBlocked?t.jsxs(li,{variant:"danger",className:"project-task-card-blocked",children:[t.jsx(Oe,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:a.dependencyBlockingCount||""}),t.jsx("span",{className:"project-task-visually-hidden",children:` blocked by ${a.dependencyBlockingCount||"a"} incomplete prerequisite ${1===a.dependencyBlockingCount?"task":"tasks"}`})]}):null,["high","urgent"].includes(a.priority)?t.jsx(ac,{value:a.priority}):null,E?t.jsx(nc,{value:a.dueDate}):null]}):null,a.commentCount||a.resourceCount||a.dependencyCount&&!a.dependencyBlocked||(a.assignees||[]).length?t.jsxs("span",{className:"project-task-card-meta",children:[t.jsxs("span",{className:"project-task-card-meta-counts",children:[a.dependencyCount&&!a.dependencyBlocked?t.jsxs("span",{className:"project-task-card-count",children:[t.jsx(Oe,{size:13,"aria-hidden":"true"}),t.jsx("span",{children:a.dependencyCount}),t.jsx("span",{className:"project-task-visually-hidden",children:` prerequisite${1===a.dependencyCount?"":"s"}, all complete`})]}):null,a.commentCount?t.jsxs("span",{className:"project-task-card-count",children:[t.jsx(le,{size:13,"aria-hidden":"true"}),t.jsx("span",{children:a.commentCount}),t.jsxs("span",{className:"project-task-visually-hidden",children:["comment",1===a.commentCount?"":"s"]})]}):null,a.resourceCount?t.jsxs("span",{className:"project-task-card-count",children:[t.jsx(We,{size:13,"aria-hidden":"true"}),t.jsx("span",{children:a.resourceCount}),t.jsxs("span",{className:"project-task-visually-hidden",children:["resource",1===a.resourceCount?"":"s"]})]}):null]}),a.assignees?.length?t.jsx(Qh,{people:a.assignees,size:22}):null]}):null,_?t.jsx("span",{id:x,className:"project-task-visually-hidden",children:_}):null,t.jsxs("span",{className:"project-task-card-badges",children:[j?t.jsx("span",{className:"project-task-state",children:"Saving..."}):null,k?t.jsx("span",{className:"project-task-state",children:"Saved"}):null,w?t.jsx("span",{className:"project-task-state",children:"Moving..."}):null,N?t.jsx("span",{className:"project-task-state",children:"Moved"}):null,y?t.jsx("span",{className:"project-task-state project-task-state--danger",children:"Not saved"}):null]})]}),!o||Uh(a)||w?null:t.jsx(em,{task:a,columns:i,currentColumnId:a.columnId,index:s,columnTaskCount:r,onMoveTask:g}),y?t.jsxs("div",{className:"project-task-card-error",role:"alert",children:[t.jsx("span",{children:a.createError||"Unable to create task."}),t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>{const e=f?.(a);e&&"function"==typeof e.catch&&e.catch(()=>{})},children:"Retry"}),t.jsx("button",{type:"button",onClick:()=>b?.(a),children:"Remove"})]})]}):null]})});function am({task:e,index:a,columnTaskCount:n,columns:s,canMoveTask:r,selectedTaskId:i,enableDrag:l,showMoveControls:o,onSelectTask:c,onMoveTask:d,onRetryCreate:u,onRemoveCreate:h,registerCard:m}
2){const p=!l||!r(e),{attributes:g,listeners:f,setActivatorNodeRef:b,setNodeRef:x,transform:v,transition:j,isDragging:y}=fa({id:e.id,disabled:p,data:{type:"task",task:e,columnId:e.columnId,index:a}}),k={transform:ba.Transform.toString(v),transition:j};return t.jsx("div",{ref:x,style:k,children:t.jsx(tm,{task:e,index:a,columnTaskCount:n,columns:s,isSelected:i===e.id,enableDrag:l,showMoveControls:o&&!p,isDragging:y,dragDisabled:p,dragHandleProps:{attributes:g,listeners:f,setActivatorNodeRef:b},cardRef:t=>m(e.id,t),onOpen:c,onMoveTask:d,onRetryCreate:u,onRemoveCreate:h})})}function nm({column:a,active:n,isComposerActive:s,insertionIndex:r=null,canCreateTasks:i,draft:l,onOpenComposer:o,onDraftChange:c,onSubmitDraft:d,onCancelComposer:u,children:h,mobileActive:m=!1}){const p=e.useId(),g=e.useRef(null),f=e.useRef(s),{setNodeRef:b}=ga({id:(x=a.id,`${Xh}${x}`),data:{type:"column",columnId:a.id}});var x;return e.useEffect(()=>{f.current&&!s&&g.current?.focus(),f.current=s},[s]),t.jsxs("section",{id:`project-task-column-${a.id}`,className:n?"project-task-column project-task-column--target":"project-task-column","aria-labelledby":p,"data-mobile-active":m?"true":"false",children:[t.jsx("h4",{id:p,className:"project-task-column-heading",children:a.name}),t.jsxs("div",{className:"project-task-column-header","aria-hidden":"true",children:[t.jsx("span",{children:a.name}),t.jsx("span",{className:"project-task-rail-col__count",children:a.tasks?.length||0})]}),t.jsxs("div",{ref:b,className:"project-task-card-list",role:"list","aria-labelledby":p,"data-column-id":a.id,children:[a.tasks?.length||0!==r?null:t.jsx("div",{className:"project-task-insertion-line","aria-hidden":"true"}),h]}),i?s?t.jsx(Zh,{columnName:a.name,draft:l,onDraftChange:c,onSubmit:d,onCancel:u}):t.jsxs("button",{ref:g,type:"button",className:"project-task-add-card",onClick:o,children:[t.jsx(Z,{size:16,"aria-hidden":"true"})," Add card"]}):null]})}function sm({message:e}){return t.jsx("div",{className:"project-task-live-region","aria-live":"assertive","aria-atomic":"true",children:e})}function rm({board:a,selectedTaskId:n=null,focusTaskId:s=null,canCreateTasks:r=!1,enableDrag:i=!1,showMoveControls:l=!1,movementError:o=null,onClearMovementError:c,onSelectTask:d,onFocusTaskHandled:u,onMoveTask:h,onCreateTask:m,onRetryCreate:p,onRemoveCreate:g}){const[f,b]=e.useState(null),[x,v]=e.useState({}),[j,y]=e.useState(null),[k,w]=e.useState(null),[N,S]=e.useState(null),[C,R]=e.useState(""),[E,I]=e.useState(null),_=e.useRef(null),T=e.useRef(null),A=e.useRef(null),O=e.useRef(new Map),D=e.useMemo(()=>a?.columns||[],[a?.columns]);!function(t,a,n,s){e.useEffect(()=>{const e=t.current,s=a.current;if(!e||!s)return;let r=0;const i=()=>{r=0,s.style.transform=`translateX(${-e.scrollLeft}px)`},l=()=>{r||(r=requestAnimationFrame(i))},o=()=>{const e=n.current?.closest(".employee-workspace-main")?.querySelector(":scope > .employee-workspace-header")||document.querySelector(".employee-workspace-header"),t=e&&["sticky","fixed"].includes(getComputedStyle(e).position)?Math.round(e.getBoundingClientRect().height):0;n.current?.style.setProperty("--board-rail-offset",`${t}px`)};let c;return i(),o(),e.addEventListener("scroll",l,{passive:!0}),window.addEventListener("resize",o),"undefined"!=typeof ResizeObserver&&(c=new ResizeObserver(()=>{i(),o()}),c.observe(e)),()=>{r&&cancelAnimationFrame(r),e.removeEventListener("scroll",l),window.removeEventListener("resize",o),c?.disconnect()}},[s])}(T,A,_,D.length),e.useEffect(()=>{D.length?D.some(e=>e.id===E)||I(D[0].id):I(null)},[D,E]);const P=e.useMemo(()=>j?D.flatMap(e=>e.tasks||[]).find(e=>e.id===j):null,[j,D]),L=sa(ra(pa,{activationConstraint:{distance:7}}),ra(ma,{activationConstraint:{delay:220,tolerance:6}}),ra(ha,{coordinateGetter:ua})),$=(e,t)=>{t?O.current.set(e,t):O.current.delete(e)},M=e=>{const t=()=>{const t=O.current.get(e);t?t.focus():_.current?.focus()};globalThis.requestAnimationFrame?requestAnimationFrame(t):setTimeout(t,0)};e.useEffect(()=>{s&&(M(s),u?.(s))},[s]);const U=e=>i&&!Uh(e)&&"pending"!==e.moveStatus&&(e.capabilities?!0===e.capabilities.canMoveTask:!1!==e.permissions?.canMove),F=e=>{for(const t of D){const a=(t.tasks||[]).findIndex(t=>t.id===e);if(a>=0)return{column:t,index:a}}return null},z=({active:e,over:t})=>
2{if(!e?.id||!t?.id)return null;const a=F(e.id);if(!a)return null;if(n=t.id,String(n||"").startsWith(Xh)){const e=function(e){return String(e||"").slice(20)}(t.id),n=D.find(t=>t.id===e);if(!n)return null;const s=n.tasks?.length||0;return{columnId:e,index:e===a.column.id&&a.index<s?Math.max(0,s-1):s}}var n;const s=F(t.id);if(!s)return null;const r=e.rect.current.translated||e.rect.current.initial,i=t.rect,l=(r?r.top+r.height/2:0)>(i?i.top+i.height/2:0),o=s.index+(l?1:0);return{columnId:s.column.id,index:s.column.id===a.column.id&&a.index<o?Math.max(0,o-1):o}},q=(e,t,a)=>{M(e.id);const n=h?.(e,t,a);return n&&"function"==typeof n.then?n.then(()=>M(e.id)).catch(()=>M(e.id)):M(e.id),n};return a?t.jsxs("section",{ref:_,className:"project-task-board-shell",tabIndex:-1,"aria-label":"Task board",children:[t.jsx(sm,{message:C||o?.message||""}),o?t.jsxs("div",{className:"project-task-board-error",role:"alert",children:[t.jsx("span",{children:o.message}),t.jsx("button",{type:"button",onClick:c,children:"Dismiss"})]}):null,D.length?t.jsx("div",{className:"project-task-board-status-switcher",role:"group","aria-label":"Choose board column",children:D.map(e=>t.jsxs("button",{type:"button","aria-pressed":E===e.id,"aria-controls":`project-task-column-${e.id}`,onClick:()=>I(e.id),children:[t.jsx("span",{children:e.name}),t.jsx("strong",{children:e.tasks?.length||0})]},e.id))}):null,t.jsxs(ia,{sensors:L,collisionDetection:la,autoScroll:{threshold:{x:.2,y:.2}},onDragStart:({active:e})=>{y(e.id);const t=O.current.get(e.id)?.closest(".project-task-card"),a=t?.getBoundingClientRect().width;w(a?Math.round(a):null),R(`Picked up ${e.data.current?.task?.title||"task"}.`)},onDragOver:e=>{const t=z(e);if(S(t),t){const e=D.find(e=>e.id===t.columnId);R(`Moved over ${e?.name||"column"}.`)}},onDragCancel:()=>{j&&M(j),R("Move cancelled."),y(null),w(null),S(null)},onDragEnd:e=>{const t=z(e),a=e.active.data.current?.task;if(y(null),w(null),S(null),!a||!t)return R("Move cancelled."),void(a?.id&&M(a.id));R(`Dropped ${a.title}.`);const n=q(a,t.columnId,t.index);n&&"function"==typeof n.then&&n.then(e=>{R(e?.moved?`Move confirmed for ${a.title}.`:o?.message||`Move cancelled for ${a.title}.`)})},children:[t.jsxs("div",{className:"project-task-board-canvas",children:[t.jsx("div",{className:"project-task-board-rail","aria-hidden":"true",children:t.jsx("div",{className:"project-task-board-rail-track",ref:A,children:D.map(e=>t.jsxs("div",{className:"project-task-rail-col",children:[t.jsx("span",{children:e.name}),t.jsx("span",{className:"project-task-rail-col__count",children:e.tasks?.length||0})]},e.id))})}),t.jsx("div",{className:"project-task-board-scroller",ref:T,children:t.jsx("section",{className:"project-task-board",role:"region","aria-label":"Task board columns",tabIndex:0,children:D.map(a=>t.jsx(nm,{column:a,mobileActive:E===a.id,active:N?.columnId===a.id,insertionIndex:N?.columnId===a.id?N.index:null,canCreateTasks:r,isComposerActive:f===a.id,draft:x[a.id]||"",onOpenComposer:()=>b(a.id),onDraftChange:e=>v(t=>({...t,[a.id]:e})),onSubmitDraft:e=>((e,t)=>{v(t=>({...t,[e]:""}));const a=m?.({columnId:e,title:t});a&&"function"==typeof a.catch&&a.catch(()=>{})})(a.id,e),onCancelComposer:()=>b(null),children:t.jsxs(oa,{items:(a.tasks||[]).map(e=>e.id),strategy:ca,children:[(a.tasks||[]).map((s,r)=>t.jsxs(e.Fragment,{children:[N?.columnId===a.id&&N.index===r?t.jsx("div",{className:"project-task-insertion-line","aria-hidden":"true"}):null,t.jsx("div",{role:"listitem",children:t.jsx(am,{task:s,index:r,columnTaskCount:a.tasks?.length||0,columns:D,canMoveTask:U,selectedTaskId:n,enableDrag:i,showMoveControls:l,onSelectTask:d,onMoveTask:q,onRetryCreate:p,onRemoveCreate:g,registerCard:$})})]},s.id)),N?.columnId===a.id&&N.index===(a.tasks||[]).length?t.jsx("div",{className:"project-task-insertion-line","aria-hidden":"true"}):null]})},a.id))})})]}),t.jsx(da,{children:P?t.jsx("div",{className:"project-task-overlay-sizer",style:{width:k?`${k}px`:"min(280px, 88vw)"},children:t.jsx(tm,{task:P,columns:D,enableDrag:!1,showMoveControls:!1,isOverlay:!0})}):null})]})]}):null}function im(e,t="Unable to load this task."){return 401===e?.status||403===e?.status||"TASK_ACCESS_DENIED"===e?.code?"This task is unavailable or you no longer have access.":404===e?.status||"TASK_NOT_FOUND"===e?.code?"This task is unavailable.":"TASK_VERSION_CONFLICT"===e?.code?"This task changed elsewhere. Refresh the task before saving again.":e?.safeMessage||e?.message||t}function lm(e,t){if(e?.data?.permissions)return e.data.permissions;const a=t?.capabilities;
2return a?{canEdit:Boolean(a.canEditTask),canMove:Boolean(a.canMoveTask),canComment:Boolean(a.canCommentOnTask),canBlock:Boolean(a.canBlockTask),canArchive:Boolean(a.canArchiveTask),canRestore:Boolean(a.canRestoreTask),canDelete:Boolean(a.canDeleteTask),canAssignSelf:Boolean(a.canAssignSelf),canUnassignSelf:Boolean(a.canUnassignSelf),canManageAssignees:Boolean(a.canManageTaskAssignees),canManageResources:Boolean(a.canManageTaskResources)}:null}const om=["low","normal","high","urgent"];function cm({form:e,onChange:a,titleError:n=null}){return t.jsxs(ic,{legend:"Task details",description:"Describe the work and when it should be done.",children:[t.jsx(rc,{label:"Title",required:!0,error:n,className:"task-form-field--wide",children:t.jsx("input",{value:e.title,onChange:e=>a("title",e.target.value),maxLength:240})}),t.jsx(rc,{label:"Description",className:"task-form-field--wide",children:t.jsx("textarea",{value:e.description,onChange:e=>a("description",e.target.value)})}),t.jsx(rc,{label:"Priority",children:t.jsx("select",{value:e.priority,onChange:e=>a("priority",e.target.value),children:om.map(e=>t.jsx("option",{value:e,children:e},e))})}),t.jsx(rc,{label:"Due date",children:t.jsx("input",{type:"date",value:e.dueDate||"",onChange:e=>a("dueDate",e.target.value)})})]})}function dm(e,t){return e?.safeMessage||e?.message||t}function um({project:a,task:n,request:s,endpointPrefix:r,onChanged:i}){const l=e.useMemo(()=>n?.dependencies||[],[n?.dependencies]),[o,c]=e.useState(""),[d,u]=e.useState(""),[h,m]=e.useState([]),[p,f]=e.useState(!1),[b,x]=e.useState(null),[v,j]=e.useState(null),y=e.useRef(0);e.useEffect(()=>{const e=setTimeout(()=>u(o.trim()),250);return()=>clearTimeout(e)},[o]);const k=a?.id&&n?.id?`${r}/${a.id}/tasks/${n.id}/dependencies`:null,w=e.useCallback(async()=>{if(!k)return;const e=++y.current;f(!0);try{const t=d?`?search=${encodeURIComponent(d)}`:"",a=await s(`${k}${t}`);if(e!==y.current)return;m(a.data.candidates||[])}catch(t){e===y.current&&j(dm(t,"Unable to load tasks."))}finally{e===y.current&&f(!1)}},[k,d,s]);e.useEffect(()=>{w()},[w]);return t.jsxs("div",{className:"task-dependency-editor",children:[t.jsx("h4",{children:"Blocked by"}),t.jsx("p",{className:"task-detail-muted",children:"This task stays dependency-blocked until every prerequisite below is complete."}),l.length?t.jsx("ul",{className:"task-dependency-editor__current",children:l.map(e=>t.jsxs("li",{children:[t.jsx("span",{className:"task-dependency-row__state","aria-hidden":"true",children:e.completedAt?t.jsx(Ve,{size:14}):t.jsx(nt,{size:12})}),t.jsxs("span",{className:"task-dependency-editor__title",children:[e.title,e.completedAt?t.jsx("small",{children:" · Complete"}):null,e.archivedAt?t.jsx("small",{children:" · Archived"}):null]}),t.jsx("button",{type:"button",className:"task-dependency-editor__remove",onClick:()=>(async e=>{if(k&&!b){x(e.id),j(null);try{const t=await s(`${k}/${e.id}`,{method:"DELETE"});i?.(t.data.task),w()}catch(t){j(dm(t,"Unable to remove that prerequisite."))}finally{x(null)}}})(e),disabled:b===e.id,"aria-label":`Remove prerequisite ${e.title}`,children:t.jsx(g,{size:15,"aria-hidden":"true"})})]},e.id))}):t.jsx("p",{className:"task-detail-muted",children:"No prerequisites yet."}),t.jsxs("label",{className:"task-dependency-editor__search",children:[t.jsx(ue,{size:15,"aria-hidden":"true"}),t.jsx("span",{className:"task-detail-visually-hidden",children:"Search tasks in this project"}),t.jsx("input",{value:o,onChange:e=>c(e.target.value),placeholder:"Add a prerequisite taskâ¦"})]}),p?t.jsx("p",{className:"task-detail-muted",children:"Searchingâ¦"}):h.length?t.jsx("ul",{className:"task-dependency-editor__candidates",children:h.map(e=>t.jsxs("li",{children:[t.jsx("span",{className:"task-dependency-row__state","aria-hidden":"true",children:e.completedAt?t.jsx(Ve,{size:14}):t.jsx(nt,{size:12})}),t.jsxs("span",{className:"task-dependency-editor__title",children:[e.title,e.column?.name?t.jsxs("small",{children:[" · ",e.column.name]}):null]}),t.jsxs(ec,{variant:"secondary",size:"compact",onClick:()=>(async e=>{if(k&&!b){x(e.id),j(null);try{const t=await s(k,{method:"POST",body:JSON.stringify({dependsOnTaskId:e.id})});i?.(t.data.task),m(t=>t.filter(t=>t.id!==e.id))}catch(t){j(dm(t,"Unable to add that prerequisite."))}finally{x(null)}}})(e),disabled:b===e.id,children:[t.jsx(Z,{size:14,"aria-hidden":"true"})," Add"]})]},e.id))}):t.jsx("p",{className:"task-detail-muted",children:d?"No matching tasks in this project.":"No other tasks available to link."}),v?t.jsx("p",{className:"task-detail-error",role:"alert",children:v}):null]})}const hm=Object.freeze({pending:"Queued",processing:"Cleaning up",retry:"Retrying",blocked:"Blocked",completed:"Completed",dead_lettered:"Failed",cancelled:"Cancelled",quarantined:"Quarantined"}),mm=Object.freeze({pending:"warning",processing:"warning",retry:"warning",blocked:"danger",completed:"success",dead_lettered:"danger",cancelled:"default",quarantined:"danger"});function pm(e){return hm[e]||"Unknown"}function gm(e){const t=e?.details?.details?.blockers||e?.details?.blockers||e?.error?.details?.blockers;return Array.isArray(t)?t:null}const fm=new Set(["Request failed","Failed to fetch",""]);function bm(e,t){const a="string"==typeof e?.code&&e.code?e.code:null,n=Number.isInteger(e?.status)?e.status:null,s=e?.safeMessage||e?.message||"",r=s&&!fm.has(s);let i=r?s:t;return!r&&n&&(i=`${t} The server responded with HTTP ${n}.`),{message:i,code:a&&"REQUEST_FAILED"!==a?a:null,status:n}}function xm(e,{subject:t="The account"}={}){return"completed"===e?.state?{tone:"success",type:"success",message:`${t} was permanently deleted.`}:{tone:"warning",type:"warning",message:`${t} is suspended now. Permanent cleanup becomes eligible after the 30-day grace deadline and can be cancelled before execution is leased;
2 track it under Deletion operations.`}}function vm({entityType:a,entityName:n,archived:s=!1,canArchive:r=!1,canRestore:i=!1,canDelete:l=!1,request:o,endpoint:c,archiveAction:d="archive",restoreAction:u="restore",archiveLabel:h=null,restoreLabel:m=null,deleteLabel:p=null,permanentUserDeletion:g=!1,onChanged:f,onDeleted:b,onPendingChange:x,triggerLabel:v=null,triggerVariant:j="ghost",triggerDescriptionId:y,disabled:k=!1,focusableDisabled:w=!1}){const[N,S]=e.useState(!1),[C,R]=e.useState(null),[E,I]=e.useState(null),[_,T]=e.useState(!1),[A,O]=e.useState(!1),[D,P]=e.useState(null),[L,$]=e.useState(""),M=e.useId(),[U,F]=e.useState("administrative_request"),[z,q]=e.useState(""),B=e.useRef(null),W=e.useRef(0),V=e.useRef(0),H=e.useRef(!1),K=e.useRef(c),G=e.useRef(null),J=e.useRef(null),Y=e.useRef(null),Q=a.toLowerCase(),X=h||`Archive ${Q}`,Z=m||`Restore ${Q}`,ee=p||`Delete ${Q} permanently`,ae=r||i||l;K.current=c,e.useEffect(()=>(H.current=!0,()=>{H.current=!1,W.current+=1,V.current+=1}),[]),e.useEffect(()=>{if(!N)return;const e=e=>{G.current?.contains(e.target)||S(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[N]),e.useEffect(()=>{k&&S(!1)},[k]);const ne=()=>{A||(W.current+=1,R(null),I(null),T(!1),P(null),$(""),q(""))},se=async()=>{const e=W.current+1;W.current=e,I(null),T(!0),P(null);try{const t=await o(c);if(W.current!==e)return;I(t.data)}catch(t){if(W.current!==e)return;P(bm(t,"Unable to check dependencies."))}finally{W.current===e&&T(!1)}};if(!ae)return null;const re=E?.blockers||[],ie=E?.ownershipSuccessors||[],le=E&&!E.canDelete,oe=re.some(e=>String(e.key||"").startsWith("owned_")),ce=re.some(e=>!String(e.key||"").startsWith("owned_")),de=g&&E&&L===E.confirmationText&&!ce&&(!oe||Boolean(z)),ue=n||`this ${Q}`;return t.jsxs("div",{className:"entity-lifecycle",ref:G,children:[t.jsxs(ec,{id:M,ref:J,variant:j,iconOnly:!v,disabled:k&&!w,"aria-disabled":k?"true":void 0,className:"entity-lifecycle__trigger","aria-label":`${a} lifecycle actions`,"aria-describedby":y,"aria-haspopup":"menu","aria-expanded":N,onClick:e=>{k?e.preventDefault():S(e=>!e)},onKeyDown:e=>{if(!k)return"Escape"===e.key&&N?(e.preventDefault(),e.stopPropagation(),void S(!1)):void("ArrowDown"!==e.key&&"ArrowUp"!==e.key||(e.preventDefault(),S(!0),((e="first")=>{requestAnimationFrame(()=>{const t=Array.from(Y.current?.querySelectorAll('[role="menuitem"]')||[]),a="last"===e?t.at(-1):t[0];a?.focus()})})("ArrowUp"===e.key?"last":"first")));["Enter"," ","ArrowDown","ArrowUp"].includes(e.key)&&e.preventDefault()},children:[t.jsx(Ze,{size:20,"aria-hidden":"true"}),v]}),N?t.jsxs("div",{className:"entity-lifecycle__menu",role:"menu","aria-labelledby":M,ref:Y,onKeyDown:e=>{const t=Array.from(Y.current?.querySelectorAll('[role="menuitem"]')||[]);if("Escape"===e.key)return e.preventDefault(),e.stopPropagation(),S(!1),void J.current?.focus();if(!["ArrowDown","ArrowUp","Home","End"].includes(e.key)||!t.length)return;e.preventDefault();const a=Math.max(0,t.indexOf(document.activeElement));t["Home"===e.key?0:"End"===e.key?t.length-1:"ArrowDown"===e.key?(a+1)%t.length:(a-1+t.length)%t.length].focus()},children:[!s&&r?t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{S(!1),R("archive")},children:[t.jsx(Ke,{size:17,"aria-hidden":"true"}),X]}):null,s&&i?t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{S(!1),R("restore")},children:[t.jsx(Me,{size:17,"aria-hidden":"true"}),Z]}):null,l&&(!s&&r||s&&i)?t.jsx("span",{className:"entity-lifecycle__separator","aria-hidden":"true"}):null,l?t.jsxs("button",{type:"button",role:"menuitem",className:"is-danger",onClick:()=>{S(!1),R("delete"),$(""),q(""),B.current=globalThis.crypto.randomUUID(),se()},children:[t.jsx(te,{size:17,"aria-hidden":"true"}),ee]}):null]}):null,t.jsxs(cc,{isOpen:Boolean(C),onClose:ne,returnFocusRef:J,busy:A,variant:"modal",className:"entity-lifecycle__dialog",title:"delete"===C?`Delete â${ue}â permanently?`:"archive"===C?`${X.replace(/^./,e=>e.toUpperCase())}?`:`${Z.replace(/^./,e=>e.toUpperCase())}?`,description:"delete"===C?"This action cannot be undone.":"archive"===C?`It will leave active ${Q} views. Existing history will be preserved.`:"The record will return to active views. Historical access is not recreated.",closeLabel:"Close lifecycle dialog",footer:t.jsxs("div",{className:"entity-lifecycle__dialog-actions",children:[t.jsx(ec,{variant:"ghost",onClick:ne,disabled:A,children:"Cancel"}),"delete"===C&&le&&!g&&!s&&r?t.jsxs(ec,{variant:"secondary",onClick:()=>{R("archive"),I(null),P(null)},disabled:A,children:[X," instead"]}):null,t.jsx(ec,{variant:"delete"===C?"danger":"primary",onClick:async()=>
2{if(A)return;const e=V.current+1;V.current=e;const t=c,a=()=>H.current&&V.current===e,n=()=>a()&&K.current===t;let s=!0;const r=()=>!(!s||!a())&&(s=!1,x?.(!1),!0);O(!0),P(null),x?.(!0);try{if("delete"===C){const e=g?{confirmation:L,reasonCategory:U,idempotencyKey:B.current,...z?{transferToUserId:z}:{}}:{},t=await o(c,{method:"DELETE",body:JSON.stringify(e)});if(!n())return;if(r(),await(b?.(t.data)),!n())return;R(null)}else{const e="archive"===C?d:u;if(await o(c,{method:"POST",body:JSON.stringify({action:e})}),!n())return;if(r(),await(f?.(e)),!n())return;R(null)}}catch(i){if(!n())return;const e=gm(i);Array.isArray(e)&&I(t=>({...t,canDelete:!1,blockers:e})),P(bm(i,"Unable to update this record."))}finally{a()&&(r(),O(!1))}},disabled:A||"delete"===C&&(g?!de:!E||le),children:A?"Workingâ¦":"delete"===C?ee:"archive"===C?X:Z})]}),children:[D?t.jsxs("div",{className:"entity-lifecycle__error",children:[t.jsxs(oc,{type:"error",children:[D.message,D.code?` (${D.code})`:""]}),"delete"!==C||E||_?null:t.jsx(ec,{variant:"secondary",onClick:se,children:"Retry dependency check"})]}):null,"delete"===C&&_?t.jsx("p",{role:"status",children:"Checking dependenciesâ¦"}):null,"delete"===C&&E?.canDelete?t.jsx(oc,{type:"success",children:g?"The account is eligible for permanent deletion.":"No retained history blocks permanent deletion."}):null,"delete"===C&&le?t.jsxs("div",{className:"entity-lifecycle__blocked",children:[t.jsx(oc,{type:"warning",children:g?"Resolve the blockers below before permanent deletion.":s?"Permanent deletion is unavailable. This record remains safely archived.":r?"Permanent deletion is unavailable. Archive this record instead.":"Permanent deletion is unavailable because retained history must be preserved."}),t.jsx("ul",{className:"entity-lifecycle__blockers",children:re.map(e=>t.jsxs("li",{children:[e.label,": ",e.count,e.remediation?` â ${e.remediation}`:""]},e.key))})]}):null,"delete"===C&&g&&E?t.jsxs("div",{className:"entity-lifecycle__permanent-user-fields",children:[oe&&!ce?t.jsxs("label",{children:["Transfer all owned records to",t.jsxs("select",{value:z,onChange:e=>q(e.target.value),disabled:A,children:[t.jsx("option",{value:"",children:"Choose an active internal user"}),ie.map(e=>t.jsx("option",{value:e.id,children:e.name||e.id},e.id))]})]}):null,t.jsxs("label",{children:["Reason",t.jsxs("select",{value:U,onChange:e=>F(e.target.value),disabled:A,children:[t.jsx("option",{value:"administrative_request",children:"Administrative request"}),t.jsx("option",{value:"privacy_request",children:"Privacy request"}),t.jsx("option",{value:"employment_ended",children:"Employment ended"}),t.jsx("option",{value:"test_cleanup",children:"Test cleanup"}),t.jsx("option",{value:"other",children:"Other approved reason"})]})]}),t.jsxs("label",{children:["Type ",E.confirmationText," to confirm",t.jsx("input",{value:L,onChange:e=>$(e.target.value),autoComplete:"off",spellCheck:"false",disabled:A||ce})]}),t.jsx("p",{children:"Access is suspended immediately. Permanent cleanup becomes eligible only after the database-generated 30-day grace deadline and can be cancelled before execution is leased. Retained work and security evidence will show Deleted User after completion."})]}):null]})]})}function jm(e,t){return"TASK_VERSION_CONFLICT"===e?.code?"This task changed elsewhere. Refresh the task before saving again.":401===e?.status||403===e?.status?"You do not have permission to perform this action.":e?.safeMessage||e?.message||t}function ym(e){return{title:e?.title||"",description:e?.description||"",priority:e?.priority||"normal",dueDate:e?.dueDate||"",isBlocked:Boolean(e?.isBlocked),blockerReason:e?.blockerReason||""}}function km({comments:e}){return e?.length?t.jsx("div",{className:"task-detail-comments",children:e.map(e=>t.jsxs("article",{className:"task-detail-comment",children:[t.jsxs("header",{children:[t.jsx("strong",{children:e.author?.name||"Someone"}),e.createdAt?t.jsx("span",{children:Go(e.createdAt)}):null]}),t.jsx(wd,{text:e.body})]},e.id))}):t.jsx("p",{className:"task-detail-muted",children:"No comments yet."})}function wm({resources:a,projectId:n,taskId:s,request:r,endpointPrefix:i}){const[l,o]=e.useState(null);return a?.length?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-detail-resource-list",children:a.map(e=>t.jsxs("button",{type:"button",onClick:()=>(async e=>{o(null);try{const t=await r(`${i}/${n}/tasks/${s}/resources/${e.id}/access`,{method:"POST",body:JSON.stringify({})}),a=t.data.url||t.data.href;if(!a)throw new Error("This Resource is unavailable.");window.open(a,t.data.url?"_blank":"_self","noopener,noreferrer")}catch(t){o(t?.safeMessage||t?.message||"Unable to open resource.")}})(e),children:[t.jsx(j,{size:16,"aria-hidden":"true"}),t.jsxs("span",{children:[e.title||e.originalFilename,t.jsxs("small",{children:[e.originalFilename," · ",Sc(e.resourceKind)]})]}),t.jsx(Ue,{size:14,"aria-hidden":"true"})]},e.id))}),l?t.jsx("p",{className:"task-detail-error",role:"alert",children:l}):null]}):t.jsx("p",{className:"task-detail-muted",children:"No linked resources."})}function Nm({link:e,onOpenTask:a}){const n=Boolean(e.completedAt),s=Boolean(e.archivedAt),r=Ko(e.dueDate),i=[];return s?i.push("Archived"):n?i.push(`Completed ${Go(e.completedAt)}`):e.column?.name&&i.push(e.column.name),e.isBlocked&&!n&&i.push("Blocked"),!n&&r.known&&i.push(`${r.label} ${Go(e.dueDate)}`),t.jsxs("li",{className:"task-dependency-row"+(n?" task-dependency-row--done":""),children:[t.jsx("span",{className:"task-dependency-row__state","aria-hidden":"true",children:n?t.jsx(Ve,{size:15}):t.jsx(nt,{size:13})}),t.jsxs("span",{className:"task-dependency-row__body",children:[a&&e.taskId?t.jsx("button",{type:"button",className:"task-dependency-row__title",onClick:()=>a({id:e.taskId,projectId:e.projectId,title:e.title}),children:e.title}):t.jsx("span",{className:"task-dependency-row__title",children:e.title}),i.length?t.jsx("span",{className:"task-dependency-row__meta",children:i.join(" · ")}):null]}),e.assignees?.length?t.jsx(Qh,{people:e.assignees,size:20}):null,t.jsx("span",{className:"task-detail-visually-hidden",children:n?"Complete":"Not complete"})]})}function Sm({isOpen:a,role:s="employee",project:r,taskId:i,request:l,endpointPrefix:o,onClose:c,onTaskUpdated:d,onTaskArchived:u,onOpenTask:h,renderAssigneesEditor:m,renderResourcesEditor:p,enforceServerCapabilities:f=!1}){const b=$s(),x=e.useId(),v=e.useRef(null),j=e.useRef(null),y=e.useRef(null),{detail:k,permissions:w,status:N,error:S,reload:C,applyTask:R,patchDetail:E}=function({taskId:t,projectId:a,request:n,endpointPrefix:s,enabled:r=!0}){const[i,l]=e.useState(null),[o,c]=e.useState(null),[d,u]=e.useState("idle"),[h,m]=e.useState(null),p=e.useRef(0),g=e.useMemo(()=>t&&a&&s?`${s}/${a}/tasks/${t}`:null,[s,a,t]),f=e.useCallback(async()=>
2{if(!r||!g)return l(null),c(null),u("idle"),m(null),null;const e=++p.current;l(null),c(null),u("loading"),m(null);try{const t=await n(g);if(e!==p.current)return null;const a=t.data.task;return l(a),c(lm(t,a)),u("ready"),a}catch(t){return e!==p.current||(l(null),c(null),u(403===t?.status||404===t?.status?"unavailable":"error"),m({code:t?.code,status:t?.status,message:im(t)})),null}},[r,n,g]);e.useEffect(()=>(f(),()=>{p.current+=1}),[f]);const b=e.useCallback(e=>{l(e);const t=lm(null,e);t&&c(t),u("ready"),m(null)},[]),x=e.useCallback(e=>{l(t=>t?{...t,...e}:t)},[]);return{detail:i,permissions:o,status:d,loading:"loading"===d,error:h,taskUrl:g,reload:f,applyTask:b,patchDetail:x,setError:m}}({taskId:i,projectId:r?.id,request:l,endpointPrefix:o,enabled:a}),[I,_]=e.useState("view"),[T,A]=e.useState(ym(null)),[O,D]=e.useState("idle"),[P,L]=e.useState(null),[$,M]=e.useState(null),[U,F]=e.useState(""),[z,q]=e.useState(!1),[B,W]=e.useState(null),[V,H]=e.useState(!1),[K,G]=e.useState(null),J=!f&&"admin"===s,Y=w?.canEdit??J,Q=w?.canBlock??J,X=w?.canComment??J,Z=!0===w?.canArchive,ee=!0===w?.canRestore,te=!0===w?.canDelete,ae=w?.canAssignSelf??!1,ne=w?.canUnassignSelf??!1,se=w?.canManageAssignees??J,re=w?.canManageResources??J,ie=(f||function(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&["canArchive","canRestore","canDelete"].every(t=>"boolean"==typeof e[t])}(w))&&(Z||ee||te),oe=Y||Q,ce=e.useMemo(()=>k?.dependencies||[],[k?.dependencies]),de=e.useMemo(()=>k?.dependents||[],[k?.dependents]),ue=ce.filter(e=>!e.archivedAt&&!e.completedAt),he=k?.dependencyBlocked??ue.length>0,me=k?.title||"Task detail",pe=Boolean(k&&JSON.stringify(T)!==JSON.stringify(ym(k))),ge="edit"===I,fe=ys({isOpen:a,panelRef:v,initialFocusRef:j,onRequestClose:e.useCallback(async e=>{if(ge&&pe){if(!(await b({title:"Discard unsaved task changes?",message:"Your unsaved field changes will be lost.",confirmLabel:"Discard changes",confirmVariant:"danger"})))return!1}return c?.(e),!0},[b,ge,pe,c])});e.useEffect(()=>{k&&y.current!==k.id&&(y.current=k.id,A(ym(k)))},[k]),e.useEffect(()=>{y.current=null,_("view"),A(ym(null)),D("idle"),L(null),M(null),F(""),W(null),G(null)},[a,i]);const be=(e,t)=>{L(null),M(null),A(a=>({...a,[e]:t}))},xe=async()=>{const e=await C();return e&&(y.current=e.id,A(ym(e)),M(null),L(null),D("idle")),e},ve=e.useMemo(()=>k?.assignees||[],[k?.assignees]);if(!a||"undefined"==typeof document)return null;const je=k?.id===i&&"ready"===N,ye=je&&"overdue"===Ko(k.dueDate).key&&!k.completedAt,ke=t.jsx("div",{className:"task-detail-overlay",onMouseDown:e=>{e.target===e.currentTarget&&fe("backdrop")},children:t.jsxs("section",{ref:v,className:"task-detail-dialog",role:"dialog","aria-modal":"true","aria-labelledby":x,tabIndex:-1,children:[t.jsxs("header",{className:"task-detail-header",children:[t.jsxs("div",{className:"task-detail-header-identity",children:[t.jsxs("p",{className:"task-detail-eyebrow",children:[r?.name||k?.project?.name||("admin"===s?"Admin task":"Task"),k?.column?.name?` · ${k.column.name}`:""]}),t.jsx("h2",{ref:j,id:x,tabIndex:-1,children:me})]}),t.jsxs("div",{className:"task-detail-header-actions",children:[je&&!ge&&oe?t.jsxs(ec,{variant:"secondary",size:"compact",onClick:()=>{k&&(A(ym(k)),L(null),M(null),_("edit"))},children:[t.jsx(st,{size:16,"aria-hidden":"true"})," Edit"]}):null,je&&!ge&&ie?t.jsx(vm,{entityType:"Task",entityName:k.title,archived:Boolean(k.archivedAt),canArchive:Z,canRestore:ee,canDelete:te,request:l,endpoint:`${o}/${r.id}/tasks/${k.id}/lifecycle`,onChanged:async e=>{if("archive"===e)return u?.(k.id,{action:"archive",title:k.title}),void c?.({archivedTaskId:k.id});const t=await xe();t&&d?.(t)},onDeleted:()=>{u?.(k.id,{action:"delete",title:k.title}),c?.({archivedTaskId:k.id})}}):null,t.jsx("button",{type:"button",className:"task-detail-close",onClick:()=>fe("close-button"),"aria-label":"Close task detail",children:t.jsx(g,{size:20,"aria-hidden":"true"})})]})]}),t.jsxs("div",{className:"task-detail-body",children:["loading"===N||"idle"===N?t.jsx("div",{className:"task-detail-loading","aria-live":"polite",children:"Loading taskâ¦"}):null,"unavailable"===N||"error"===N?t.jsxs("section",{className:"task-detail-state","aria-live":"assertive",children:[t.jsx("h3",{children:"unavailable"===N?"Task unavailable":"Unable to load task"}),t.jsx("p",{children:S?.message||"This task is unavailable."}),"error"===N?t.jsx(ec,{onClick:xe,children:"Retry"}):null]}):null,je?t.jsxs(t.Fragment,{children:[$?t.jsxs("div",{className:"task-detail-conflict",role:"alert",children:[t.jsx("span",{children:$}),t.jsx(ec,{size:"compact",onClick:xe,children:"Refresh task"})]}):null,k.completedAt||k.isBlocked||he||["high","urgent"].includes(k.priority)||k.dueDate?t.jsxs("div",{className:"task-detail-status-row",children:[k.completedAt?t.jsx(li,{variant:"success",children:"Completed"}):null,k.isBlocked?t.jsx(li,{variant:"danger",children:"Blocked"}):null,he?t.jsxs(li,{variant:"danger",children:[t.jsx(Oe,{size:13,"aria-hidden":"true"})," Blocked by ",ue.length]}):null,["high","urgent"].includes(k.priority)?t.jsx(ac,{value:k.priority}):null,k.dueDate?t.jsx("span",{className:ye?"task-detail-due task-detail-due--overdue":"task-detail-due",children:t.jsx(nc,{value:k.dueDate})}):null]}):null,ge?t.jsxs("section",{className:"task-detail-section task-detail-edit",children:[Y?t.jsx(cm,{form:T,onChange:be}):null,Q?t.jsxs("div",{className:"task-detail-block-controls",children:[t.jsxs("label",{className:"task-detail-check",children:[t.jsx("input",{type:"checkbox",checked:Boolean(T.isBlocked),onChange:e=>be("isBlocked",e.target.checked)})," ","Manually blocked"]}),T.isBlocked?t.jsxs("label",{className:"task-detail-field",children:[t.jsx("span",{children:"Blocker reason"}),t.jsx("textarea",{value:T.blockerReason,onChange:e=>be("blockerReason",e.target.value)})]}):null]}):null,t.jsxs("div",{className:"task-detail-footer","aria-live":"polite",children:[t.jsx(ec,{variant:"primary",onClick:async()=>
2{if(!k||"saving"===O)return;D("saving"),L(null),M(null);const e=Y?{...T,dueDate:T.dueDate||null,blockerReason:T.isBlocked?T.blockerReason:"",expectedVersion:k.version}:{isBlocked:T.isBlocked,blockerReason:T.isBlocked?T.blockerReason||"Blocked by assignee":"",expectedVersion:k.version};try{const t=await l(`${o}/${r.id}/tasks/${k.id}`,{method:"PATCH",body:JSON.stringify(e)});R(t.data.task),y.current=t.data.task.id,A(ym(t.data.task)),d?.(t.data.task),D("idle"),_("view")}catch(t){const e=jm(t,"Unable to save task.");"TASK_VERSION_CONFLICT"===t?.code&&M(e),L(e),D("error")}},disabled:"saving"===O,children:"saving"===O?"Savingâ¦":"Save changes"}),t.jsx(ec,{variant:"ghost",onClick:async()=>{if(pe){if(!(await b({title:"Discard unsaved task changes?",message:"Your unsaved field changes will be lost.",confirmLabel:"Discard changes",confirmVariant:"danger"})))return}A(ym(k)),L(null),M(null),D("idle"),_("view")},children:"Cancel"}),P?t.jsx("span",{className:"task-detail-error",role:"alert",children:P}):null]}),Y?t.jsx(um,{project:r,task:k,request:l,endpointPrefix:o,onChanged:e=>{e&&(R(e),y.current=e.id,d?.(e))}}):null,se&&m?m(k,e=>{const t=e?.assignees||[],a=Number(e?.assignmentRevision||k.assignmentRevision||1);E({assignees:t,assignmentRevision:a}),d?.({id:k.id,assignees:t,assignmentRevision:a})}):null,re&&p?p(k,e=>{const t=e?.resources||[];E({linkedResources:t,resourceCount:t.length}),d?.({id:k.id,linkedResources:t,resourceCount:t.length})}):null]}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"task-detail-section","aria-labelledby":`${x}-desc`,children:[t.jsx("h3",{id:`${x}-desc`,children:"Description"}),k.description?t.jsx("div",{className:"task-detail-description",children:t.jsx(wd,{text:k.description})}):t.jsx("p",{className:"task-detail-muted",children:"No description."})]}),k.isBlocked?t.jsxs("section",{className:"task-detail-section task-detail-blocker",children:[t.jsx("h3",{children:"Manually blocked"}),t.jsx(wd,{text:k.blockerReason||"No reason provided."})]}):null,ce.length?t.jsxs("section",{className:"task-detail-section","aria-labelledby":`${x}-blockedby`,children:[t.jsxs("h3",{id:`${x}-blockedby`,children:["Blocked by",he?t.jsxs("span",{className:"task-detail-count task-detail-count--danger",children:[ue.length," incomplete"]}):t.jsx("span",{className:"task-detail-count",children:"all complete"})]}),t.jsx("ul",{className:"task-dependency-list",children:ce.map(e=>t.jsx(Nm,{link:e,onOpenTask:h},e.id))})]}):null,de.length?t.jsxs("section",{className:"task-detail-section","aria-labelledby":`${x}-blocking`,children:[t.jsxs("h3",{id:`${x}-blocking`,children:["Blocking",t.jsx("span",{className:"task-detail-count",children:de.length})]}),t.jsx("ul",{className:"task-dependency-list",children:de.map(e=>t.jsx(Nm,{link:e,onOpenTask:h},e.id))})]}):null,t.jsxs("section",{className:"task-detail-section task-detail-facts",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Assignees"}),ve.length?t.jsxs("div",{className:"task-detail-assignees",children:[t.jsx(Qh,{people:ve,size:26}),t.jsx("span",{children:ve.map(e=>e.name||"Assigned").join(", ")})]}):t.jsx("p",{className:"task-detail-muted",children:"Unassigned"}),ae||ne?t.jsxs("div",{className:"task-detail-inline-action","aria-live":"polite",children:[t.jsx(ec,{variant:"secondary",size:"compact",onClick:()=>(async e=>{if(k&&!V){H(!0),G(null);try{const t=await l(`${o}/${r.id}/tasks/${k.id}/assignees/self`,{method:"PUT",body:JSON.stringify({assigned:e})});R(t.data.task),d?.(t.data.task)}catch(t){G(jm(t,"Unable to change your assignment."))}finally{H(!1)}}})(ae),disabled:V,children:V?"Updatingâ¦":ae?"Assign to me":"Unassign me"}),K?t.jsx("span",{className:"task-detail-error",role:"alert",children:K}):null]}):null]}),t.jsxs("div",{children:[t.jsx("h3",{children:"Resources"}),t.jsx(wm,{resources:k.linkedResources,projectId:r.id,taskId:k.id,request:l,endpointPrefix:o})]})]}),t.jsxs("section",{className:"task-detail-section",children:[t.jsxs("h3",{children:[t.jsx(le,{size:16,"aria-hidden":"true"})," Comments"]}),t.jsx(km,{comments:k.comments||[]}),X?t.jsxs("div",{className:"task-detail-comment-form",children:[t.jsxs("label",{className:"task-detail-field",children:[t.jsx("span",{children:"Add comment"}),t.jsx("textarea",{value:U,onChange:e=>{W(null),F(e.target.value)},placeholder:"Add comment"})]}),t.jsx(ec,{variant:"primary",size:"compact",onClick:async()=>{const e=U.trim();if(k&&e&&!z){q(!0),W(null);try{const t=(await l(`${o}/${r.id}/tasks/${k.id}/comments`,{method:"POST",body:JSON.stringify({body:e})})).data.comments||[];E({comments:t,commentCount:t.length}),d?.({id:k.id,commentCount:t.length}),F("")}catch(t){W(jm(t,"Unable to add comment."))}finally{q(!1)}}},disabled:z||!U.trim(),children:z?"Commentingâ¦":"Comment"}),B?t.jsx("p",{className:"task-detail-error",role:"alert",children:B}):null]}):null]}),t.jsxs("p",{className:"task-detail-timestamps",children:["Created ",Go(k.createdAt),k.updatedAt?` · Updated ${Go(k.updatedAt)}`:""]})]})]}):null]})]})});return n.createPortal(ke,xs())}function Cm({endpoint:e="/api/workspace/v1/resource-packs?scope=all",...a}){return t.jsx(ou,{endpoint:e,...a})}function Rm({project:a,columns:n=[],request:s,endpointPrefix:r,canManageAssignees:i=!0,canManageResources:l=!0,onCreated:o,onCancel:c}){const[d,u]=e.useState(()=>function(e){return{title:"",description:"",priority:"normal",dueDate:"",columnId:e[0]?.id||"",isBlocked:!1,blockerReason:""}}(n)),[h,m]=e.useState([]),[p,g]=e.useState([]),[f,b]=e.useState([]),[x,v]=e.useState(!0),[j,y]=e.useState(!1),[k,w]=e.useState(null),[N,S]=e.useState({}),C=e.useRef({material:null,key:null}),R=r.startsWith("/api/workspace/v1/");e.useEffect(()=>{!d.columnId&&n[0]?.id&&u(e=>({...e,columnId:n[0].id}))},[n,d.columnId]),e.useEffect(()=>{let e=!1;return async function(){if(!i)return b([]),void v(!1);v(!0);try{let t;if(r.startsWith("/api/workspace/v1/")){t=(await s(`${r}/${a.id}/task-assignees`)).data.people||[]}else{const e=[...a.owner?.id?[{userId:a.owner.id,name:a.owner.name,projectRole:"owner"}]:[],...a.directMembers||[]],n=(await Promise.all((a.assignedTeams||[]).map(e=>s(`/api/admin/teams/${e.teamId}/members`).catch(()=>({data:{members:[]}}))))).flatMap(e=>e.data.members||[]).map(e=>({userId:e.userId,name:e.name,projectRole:"team"}));t=[...e,...n]}e||b([...new Map(t.map(e=>[e.userId||e.id,{...e,userId:e.userId||e.id}])).values()])}catch(t){e||w(t?.safeMessage||t?.message||"Unable to load eligible project people.")}finally{e||v(!1)}}(),()=>{e=!0}},[i,r,a,s]);const E=e.useMemo(()=>new Set(f.map(e=>
2e.userId)),[f]),I=(e,t)=>{w(null),S(t=>({...t,[e]:null})),u(a=>({...a,[e]:t}))};return t.jsxs("form",{className:"task-create-form","aria-label":"Create task",onSubmit:async e=>{if(e.preventDefault(),j)return;const t={};if(d.title.trim()||(t.title="Task title is required."),d.columnId||(t.columnId="Choose a board column."),d.isBlocked&&!d.blockerReason.trim()&&(t.blockerReason="Blocker reason is required for a blocked task."),Object.keys(t).length)S(t);else{y(!0),w(null);try{const e={...d,title:d.title.trim(),dueDate:d.dueDate||null,blockerReason:d.isBlocked?d.blockerReason.trim():"",assigneeUserIds:i?h.map(e=>e.userId):[],resourceIds:l?p.map(e=>e.id||e.resourceId):[],resourceRefs:l?p.map(e=>({resourceId:e.id||e.resourceId,objectId:e.objectId||null,folderId:e.folderId||null})):[]},t=JSON.stringify(e);if(C.current.material!==t){const e=globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random()}`;C.current={material:t,key:`task-create:${e}`}}let c;try{c=await s(`${r}/${a.id}/tasks`,{method:"POST",headers:{"Idempotency-Key":C.current.key},body:t})}catch(n){if("TASK_RESOURCE_GRANT_REQUIRED"!==n.code||!window.confirm("Some project members cannot access these Resources. Grant viewer access and create the task?"))throw n;c=await s(`${r}/${a.id}/tasks`,{method:"POST",headers:{"Idempotency-Key":C.current.key},body:JSON.stringify({...e,grantResourceAccess:!0})})}await(o?.(c.data.task))}catch(n){w(n?.safeMessage||n?.message||"Unable to create task.")}finally{y(!1)}}},noValidate:!0,children:[k?t.jsx(oc,{type:"error",children:k}):null,t.jsx(cm,{form:d,onChange:I,titleError:N.title}),t.jsxs(ic,{legend:"Board and state",description:"Choose placement and record blockers.",children:[t.jsx(rc,{label:"Board column",required:!0,error:N.columnId,children:t.jsx("select",{value:d.columnId,onChange:e=>I("columnId",e.target.value),children:n.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))})}),t.jsxs("div",{className:"task-form-blocking",children:[t.jsxs("label",{className:"task-form-check",children:[t.jsx("input",{type:"checkbox",checked:d.isBlocked,onChange:e=>I("isBlocked",e.target.checked)}),"Mark task as blocked"]}),d.isBlocked?t.jsx(rc,{label:"Blocker reason",required:!0,error:N.blockerReason,children:t.jsx("textarea",{value:d.blockerReason,onChange:e=>I("blockerReason",e.target.value)})}):null]})]}),i?t.jsx(ic,{legend:"Assignees",description:"Only people who can view this project may be assigned.",children:t.jsxs("div",{className:"task-form-field--wide",children:[x?t.jsx("p",{role:"status",children:"Loading eligible peopleâ¦"}):null,t.jsx(ah,{label:"Eligible project people",value:h,onChange:m,multiple:!0,filterPerson:e=>E.has(e.id),endpoint:R?"/api/employee/people":void 0,request:s})]})}):t.jsx(oc,{type:"info",children:"Create the task first, then use Assign to me from task detail."}),l?t.jsx(ic,{legend:"Resources",description:"Link ready workspace resources now or later.",children:t.jsx("div",{className:"task-form-field--wide",children:t.jsx(Cm,{value:p,onChange:g,multiple:!0,endpoint:R?"/api/workspace/v1/resource-packs":void 0,request:s})})}):null,t.jsxs(lc,{className:"task-create-actions",children:[t.jsx(ec,{variant:"ghost",onClick:c,disabled:j,children:"Cancel"}),t.jsx(ec,{variant:"primary",type:"submit",disabled:j,children:j?"Creating taskâ¦":"Create task"})]})]})}function Em({project:a,task:n,request:s,onSaved:r,endpointPrefix:i="/api/admin/projects"}){const[l,o]=e.useState([]),[c,d]=e.useState([]),[u,h]=e.useState(!1),[m,p]=e.useState(!1),[g,f]=e.useState(Number(n?.assignmentRevision||1)),[b,x]=e.useState(null),[v,j]=e.useState(null),[y,k]=e.useState(!1),w=e.useMemo(()=>new Set(c.map(e=>e.userId)),[c]),N=e.useCallback(async()=>{if(a?.id&&n?.id){h(!0),x(null),j(null),k(!1);try{const e=await s(`${i}/${a.id}/tasks/${n.id}/assignees`);let t;if(i.startsWith("/api/workspace/v1/")){t=(await s(`${i}/${a.id}/task-assignees`)).data.people||[]}else{const e=await Promise.all((a.assignedTeams||[]).map(e=>s(`/api/admin/teams/${e.teamId}/members`).catch(()=>({data:{members:[]}})))),n=[...a.owner?.id?[{userId:a.owner.id,name:a.owner.name,projectRole:"owner"}]:[],...a.directMembers||[]],r=e.flatMap(e=>e.data.members||[]).map(e=>({userId:e.userId,name:e.name,projectRole:"team"}));t=[...n,...r]}const r=new Map(t.map(e=>[e.userId||e.id,{...e,userId:e.userId||e.id}]));d([...r.values()]),f(Number(e.data.assignmentRevision||1)),o((e.data.assignees||[]).map(e=>({...e,userId:e.userId||e.id})))}catch(e){x(e.message||"Unable to load assignees")}finally{h(!1)}}},[i,a,s,n?.id]);e.useEffect(()=>{N()},[N]);return u?t.jsx("p",{children:"Loading existing task assignments..."}):t.jsxs("section",{className:"task-editor-section",children:[t.jsx("h4",{children:"Manage assignees"}),l.length?null:t.jsx(Hu,{children:"No assignees."}),t.jsx(Im,{items:l,getKey:e=>e.userId,getLabel:e=>e.name||"User",onRemove:e=>o(t=>t.filter(t=>
2t.userId!==e.userId))}),t.jsx(ah,{label:"Eligible project people",value:l,onChange:e=>{j(null),o(e)},multiple:!0,filterPerson:e=>w.has(e.id),endpoint:i.startsWith("/api/workspace/v1/")?"/api/employee/people":void 0,request:s}),b?t.jsx(oc,{type:"error",children:b}):null,v?t.jsx(oc,{type:"success",children:v}):null,t.jsxs("div",{className:"task-create-actions",children:[y?t.jsx(ec,{variant:"ghost",onClick:N,disabled:u||m,children:"Reload assignments"}):null,t.jsx(ec,{variant:"primary",onClick:async()=>{const e=l.find(e=>!w.has(e.userId));if(e)x(`${e.name||"Selected user"} cannot view this project.`);else{p(!0),x(null),j(null);try{const e=await s(`${i}/${a.id}/tasks/${n.id}/assignees`,{method:"PUT",body:JSON.stringify({userIds:l.map(e=>e.userId),expectedAssignmentRevision:g})}),t=(e.data.assignees||[]).map(e=>({...e,userId:e.userId||e.id}));o(t),f(Number(e.data.assignmentRevision||g)),await(r?.({assignees:t,assignmentRevision:Number(e.data.assignmentRevision||g)})),j("Assignees saved.")}catch(t){"TASK_ASSIGNMENT_CONFLICT"===t?.code?(k(!0),x("Assignments changed elsewhere. Reload them before saving your changes.")):x(t.safeMessage||t.message||"Unable to save assignees")}finally{p(!1)}}},disabled:m||y,children:m?"Saving...":"Save Assignees"})]})]})}function Im({items:e,getKey:a,getLabel:n,onRemove:s}){return e.length?t.jsx("div",{className:"project-board-admin-chip-list",children:e.map(e=>t.jsxs("span",{children:[n(e),t.jsx("button",{type:"button","aria-label":`Remove ${n(e)}`,onClick:()=>s(e),children:"Remove"})]},a(e)))}):null}function _m({project:a,task:n,request:s,onSaved:r,endpointPrefix:i="/api/admin/projects"}){const[l,o]=e.useState([]),[c,d]=e.useState(!1),[u,h]=e.useState(!1),[m,p]=e.useState(null),[g,f]=e.useState(null),b=e.useCallback(async()=>{if(a?.id&&n?.id){d(!0),p(null),f(null);try{const e=await s(`${i}/${a.id}/tasks/${n.id}/resources`);o(e.data.resources||[])}catch(e){p(e.message||"Unable to load linked resources")}finally{d(!1)}}},[i,a?.id,s,n?.id]);e.useEffect(()=>{b()},[b]);return c?t.jsx("p",{children:"Loading existing task resources..."}):t.jsxs("section",{className:"task-editor-section",children:[t.jsx("h4",{children:"Linked Resources"}),l.length?null:t.jsx(Hu,{children:"No linked resources."}),t.jsx("div",{className:"project-board-admin-resource-list",children:l.map(e=>t.jsxs("span",{children:[t.jsxs("button",{type:"button",onClick:()=>(async e=>{const t=await s(`${i}/${a.id}/tasks/${n.id}/resources/${e.id}/access`,{method:"POST",body:JSON.stringify({})}),r=t.data.url||t.data.href;if(!r)throw new Error("This Resource is unavailable.");window.open(r,t.data.url?"_blank":"_self","noopener,noreferrer")})(e),children:[t.jsx(Ue,{size:14})," ",e.title||e.originalFilename,t.jsxs("small",{children:[e.originalFilename," · ",e.resourceKind," ·"," ",Nc(e.sizeBytes)]})]}),t.jsx("button",{type:"button","aria-label":`Remove ${e.title||e.originalFilename}`,onClick:()=>o(t=>t.filter(t=>(t.id||t.resourceId)!==(e.id||e.resourceId))),children:"Remove"})]},e.id||e.resourceId))}),t.jsx(Cm,{value:l,onChange:e=>{f(null),o(e)},multiple:!0,endpoint:i.startsWith("/api/workspace/v1/")?"/api/workspace/v1/resource-packs?scope=all":void 0,request:s}),m?t.jsx(oc,{type:"error",children:m}):null,g?t.jsx(oc,{type:"success",children:g}):null,t.jsx(ec,{variant:"primary",onClick:async()=>{h(!0),p(null),f(null);try{const t={resourceIds:l.map(e=>e.id||e.resourceId),resourceRefs:l.map(e=>({resourceId:e.id||e.resourceId,objectId:e.objectId||null,folderId:e.folderId||null}))};let c;try{c=await s(`${i}/${a.id}/tasks/${n.id}/resources`,{method:"PUT",body:JSON.stringify(t)})}catch(e){if("TASK_RESOURCE_GRANT_REQUIRED"!==e.code||!window.confirm("Some project members cannot access these Resources. Grant viewer access and link them?"))throw e;c=await s(`${i}/${a.id}/tasks/${n.id}/resources`,{method:"PUT",body:JSON.stringify({...t,grantResourceAccess:!0})})}const d=c.data.resources||[];o(d),await(r?.({resources:d})),f("Linked resources saved.")}catch(t){p(t.safeMessage||t.message||"Unable to save resources")}finally{h(!1)}},disabled:u,children:u?"Saving...":"Save Resources"})]})}function Tm({project:a,request:n,selectedTaskId:s=null,onSelectedTaskChange:r,endpointPrefix:i="/api/admin/projects",enforceServerCapabilities:l=!1,hideHeading:o=!1}){const c=Ds(),{board:d,replaceBoard:u,addOptimisticCreate:h,markCreateRetry:m,confirmOptimisticCreate:p,failOptimisticCreate:g,removeOptimisticCreate:f,beginOptimisticMove:b,confirmOptimisticMove:x,failOptimisticMove:v,patchTaskConfirmed:j,removeTaskConfirmed:y,movementError:k,clearMovementError:w}=Vh(),[N,S]=e.useState(""),[C,R]=e.useState(!1),[E,I]=e.useState(null),[_,T]=e.useState(null),[A,O]=e.useState(!1),D=e.useRef(new Map),P=e.useCallback(async()=>
2{if(a?.id){R(!0);try{const e=await n(`${i}/${a.id}/board`);u(e.data),I(null)}catch(e){I(e)}finally{R(!1)}}},[i,a?.id,u,n]);e.useEffect(()=>{u(null),P()},[P,u]);const L=async({columnId:e,title:t,tempId:s=null})=>{I(null);const r=s||h({columnId:e,title:t});if(s&&m(s),!D.current.has(r)){const e=globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random()}`;D.current.set(r,`task-create:${e}`)}try{const s=await n(`${i}/${a.id}/tasks`,{method:"POST",headers:{"Idempotency-Key":D.current.get(r)},body:JSON.stringify({title:t,columnId:e})});D.current.delete(r),p(r,s.data.task)}catch(l){const e=l?.safeMessage||l?.message||"Unable to create task";g(r,e),401!==l?.status&&403!==l?.status||I({safeMessage:e})}},$=function({projectId:t,request:a,endpointPrefix:n,boardState:s,reloadBoard:r,onMoveFailed:i}){return e.useCallback(async(e,l,o)=>{if(!t||!e?.id||Uh(e))return{moved:!1,reason:"disabled"};const c=s.beginOptimisticMove({task:e,targetColumnId:l,targetIndex:o});if(!c.ok||!c.changed)return{moved:!1,reason:c.reason};try{const r=await a(`${n}/${t}/tasks/${e.id}/move`,{method:"PUT",body:JSON.stringify({targetColumnId:l,targetIndex:c.targetIndex,expectedVersion:e.version})});return s.confirmOptimisticMove({taskId:e.id,mutationId:c.mutationId,snapshot:r.data}),{moved:!0}}catch(E){const a=function(e){return"TASK_VERSION_CONFLICT"===e?.code?"This task changed elsewhere. The board has been refreshed.":401===e?.status||403===e?.status||"TASK_ACCESS_DENIED"===e?.code?"You do not have permission to move this task. The card was restored.":"TASK_NOT_FOUND"===e?.code||"BOARD_COLUMN_NOT_FOUND"===e?.code||"PROJECT_BOARD_NOT_FOUND"===e?.code?"The board changed while you were moving this task. The board has been refreshed.":e?.status>=500||e?.retryable?"Unable to move task right now. The card was restored; try again when the connection is steady.":e?.safeMessage||e?.message||"Unable to move task. The card was restored."}(E);if(s.failOptimisticMove({taskId:e.id,mutationId:c.mutationId,message:a,code:E?.code}),Hh.has(E?.code)&&r)try{await r({preserveMovementError:!0})}catch(d){}return i?.({taskId:e.id,message:a,code:E?.code}),{moved:!1,error:E}}},[s,n,i,t,r,a])}({projectId:a?.id,request:n,endpointPrefix:i,boardState:{beginOptimisticMove:b,confirmOptimisticMove:x,failOptimisticMove:v},reloadBoard:P});if(!a)return t.jsx(Hu,{children:"Select a project to view its board."});const M=!l||!0===d?.capabilities?.canCreateTask,U=!l||!0===d?.capabilities?.canManageBoardColumns,F=!o||M||U;return t.jsxs("section",{className:"project-board-admin",children:[F?t.jsxs("div",{className:o?"project-board-admin-header project-board-admin-header--actions-only":"project-board-admin-header",children:[o?null:t.jsxs("div",{children:[t.jsx("h3",{children:"Task Board"}),t.jsx("p",{children:a.name})]}),t.jsxs("div",{className:"project-board-admin-header-actions",children:[M?t.jsxs(ec,{variant:"primary",onClick:()=>O(!0),children:[t.jsx(Z,{size:16,"aria-hidden":"true"})," Create task"]}):null,U?t.jsxs("div",{className:"project-board-admin-column-form",children:[t.jsx("input",{value:N,onChange:e=>S(e.target.value),placeholder:"Column name","aria-label":"New column name"}),t.jsxs(Xu,{variant:"secondary",onClick:async()=>{N.trim()&&(await n(`${i}/${a.id}/board/columns`,{method:"POST",body:JSON.stringify({name:N})}),S(""),await P())},children:[t.jsx(Z,{size:16})," Column"]})]}):null]})]}):null,t.jsx(bc,{loading:C&&!d,error:E,isEmpty:Boolean(d)&&!d.columns?.length,loadingLabel:"Loading boardâ¦",errorLabel:"Board could not be loaded",emptyLabel:"This board has no columns yet",emptyDescription:U?"Add a column above to start organising tasks.":null,onRetry:P,children:t.jsx(rm,{board:d,selectedTaskId:s,focusTaskId:_,canCreateTasks:M,enableDrag:!0,showMoveControls:!0,movementError:k,onClearMovementError:w,onSelectTask:e=>{Mh(e)||(e?.id&&e.projectId===a.id?r?.(e.id):I({safeMessage:"This item is unavailable or you no longer have access."}))},onFocusTaskHandled:()=>T(null),onMoveTask:$,onCreateTask:L,onRetryCreate:e=>{if(Mh(e))return L({columnId:e.columnId,title:e.title,tempId:e.id})},onRemoveCreate:e=>{D.current.delete(e.id),f(e.id)}})}),t.jsx(cc,{isOpen:A,onClose:()=>O(!1),title:"Create task",description:`Add a fully specified task to ${a.name}.`,closeLabel:"Close create task",children:t.jsx(Rm,{project:a,columns:d?.columns||[],request:n,endpointPrefix:i,canManageAssignees:!1!==d?.capabilities?.canManageTaskAssignees,canManageResources:!1!==d?.capabilities?.canManageTaskResources,onCancel:()=>O(!1),onCreated:async e=>{O(!1),await P(),r?.(e.id)}})}),t.jsx(Sm,{isOpen:Boolean(s),role:"admin",project:a,taskId:s,request:n,endpointPrefix:i,enforceServerCapabilities:l,onClose:({archivedTaskId:e}={})=>{e||T(s),r?.(null)},onOpenTask:e=>{e?.id&&e.id!==s&&r?.(e.id)},onTaskUpdated:e=>j(e.id,e),onTaskArchived:(e,t)=>{y(e),T(e),c({type:"success",message:"delete"===t?.action?`Task permanently deleted: ${t.title||"Task"}`:`Task archived: ${t?.title||"Task"}`})},renderAssigneesEditor:(e,s)=>t.jsx(Em,{project:a,task:e,request:n,onSaved:s,endpointPrefix:i}),renderResourcesEditor:(e,s)=>t.jsx(_m,{project:a,task:e,request:n,onSaved:s,endpointPrefix:i})})]})}
2function Am(e){return"string"==typeof e?e:e?.resourceId||e?.id}function Om(e){return"string"==typeof e?{resourceId:e,folderId:null,objectId:null}:{resourceId:Am(e),folderId:e?.folderId||null,objectId:e?.objectId||null}}function Dm(e){return JSON.stringify(e.map(Om).filter(e=>e.resourceId).sort((e,t)=>`${e.resourceId}:${e.folderId||""}:${e.objectId||""}`.localeCompare(`${t.resourceId}:${t.folderId||""}:${t.objectId||""}`)))}function Pm({resource:e,canManage:a,canOpen:n,disabled:s,onOpen:r,onRemove:i,primaryActionRef:l}){const{Icon:o,label:c}=function(e){return e?.objectId||"object"===e?.targetKind?{Icon:j,label:e.targetLabel||"Specific file"}:e?.folderId||"folder"===e?.targetKind?{Icon:M,label:e.targetLabel||"Specific folder"}:{Icon:it,label:"Whole Resource"}}(e),d=e?.title||"Untitled Resource",u=[e?.originalFilename,null==e?.sizeBytes?null:Nc(e.sizeBytes)].filter(Boolean).join(" · ");return t.jsxs(Qo,{as:"li",className:"employee-project-resource-row",children:[t.jsx(o,{className:"employee-project-resource-row__icon",size:19,"aria-hidden":"true"}),t.jsxs("span",{className:"employee-project-resource-row__content",children:[t.jsx("strong",{children:d}),t.jsx("small",{children:c}),u?t.jsx("small",{children:u}):null]}),t.jsxs("span",{className:"employee-project-resource-row__actions",children:[r?t.jsx(ec,{ref:n?l:void 0,variant:"ghost",size:"compact",disabled:s||!n,"aria-label":n?`Open Resource ${d}, ${c}`:`Save Resource ${d}, ${c} to open`,onClick:()=>r(e),children:n?t.jsxs(t.Fragment,{children:["Open ",t.jsx(Ue,{size:15,"aria-hidden":"true"})]}):"Save to open"}):null,a?t.jsxs(ec,{ref:r&&n?void 0:l,variant:"ghost",size:"compact",disabled:s,"aria-label":`Detach Resource ${d}, ${c}`,onClick:()=>i(e),children:["Detach ",t.jsx(rt,{size:15,"aria-hidden":"true"})]}):null]})]})}function Lm({project:n,request:s,onSaved:r,onOpenResource:i,onDirtyChange:l=null,onPendingChange:o=null,canManage:c=!1,endpointPrefix:d="/api/workspace/v1/projects"}){const[u,h]=e.useState(()=>n?.linkedResources||[]),[m,p]=e.useState(()=>n?.linkedResources||[]),[g,f]=e.useState(()=>Dm(n?.linkedResources||[])),[b,x]=e.useState(!1),[v,j]=e.useState(null),[y,k]=e.useState(null),[w,N]=e.useState(""),S=e.useRef(n?.id),C=e.useRef(!1),R=e.useRef(null),E=e.useRef(new Map);e.useEffect(()=>{const e=n?.linkedResources||[],t=S.current!==n?.id;S.current=n?.id,!t&&C.current||(h(e),p(e),f(Dm(e)),j(null),k(null),N(""))},[n?.id,n?.linkedResources]);const I=e.useMemo(()=>Dm(u),[u]),_=e.useMemo(()=>new Set(JSON.parse(g).map(ln)),[g]),T=I!==g;C.current=T;const A=a.useCallback(()=>{h(m),j(null),k(null),N("")},[m]);if(e.useEffect(()=>{l?.(T,T?{label:"Project Resources",message:"Discard your unsaved Project Resources changes?",discard:A}:null)},[T,l,A]),e.useEffect(()=>()=>{l?.(!1,null),o?.(!1,null)},[l,o]),!n)return null;const O=e=>{h(e||[]),j(null),N("")},D=e=>{const t=ln(e),a=u.findIndex(e=>ln(e)===t),n=u.filter(e=>ln(e)!==t),s=n[a]||n[a-1]||null;O(n),requestAnimationFrame(()=>{s?E.current.get(ln(s))?.focus():R.current?.focus()})},P=async e=>{if(i){k(null);try{await i(e)}catch(t){k(t?.safeMessage||t?.message||"This Resource could not be opened.")}}};return t.jsxs("div",{className:"employee-project-resources-workspace"+(c?" is-manageable":" is-read-only"),children:[c?t.jsxs("section",{className:"employee-project-resources-browser","aria-labelledby":"find-resources-title",children:[t.jsxs("header",{children:[t.jsx("h3",{id:"find-resources-title",children:"Find Resources"}),t.jsx("p",{children:"Attach a whole Resource, or choose a specific folder or file."})]}),t.jsx(Cm,{className:"employee-project-resource-picker",value:u,onChange:O,request:s,disabled:b,label:"Search available Resources",showSelected:!1,showAttachedState:!0,singleTargetPerPack:!0,announceResults:!0})]}):null,t.jsxs("section",{className:"employee-project-resources-attached","aria-labelledby":"attached-resources-title",children:[t.jsxs("header",{className:"employee-project-resources-attached__header",children:[t.jsxs("div",{children:[t.jsx("h3",{id:"attached-resources-title",ref:R,tabIndex:-1,children:"Attached to this project"}),t.jsxs("p",{children:[u.length," ",1===u.length?"Resource":"Resources"," available from this project."]})]}),c?t.jsx("span",{className:"employee-project-resource-save-state"+(T?" is-dirty":""),children:T?"Unsaved changes":"Up to date"}):null]}),u.length?t.jsx("ul",{className:"employee-project-resource-list","aria-label":"Project Resources",children:u.map(e=>t.jsx(Pm,{resource:e,canManage:c,canOpen:_.has(ln(e)),disabled:b,onOpen:i?P:null,onRemove:D,primaryActionRef:t=>{const a=ln(e);t?E.current.set(a,t):E.current.delete(a)}},`${Am(e)}:${e?.folderId||""}:${e?.objectId||""}`))}):t.jsx(dc,{type:"empty",title:"No Resources attached",description:c?"Search available Resources to attach the first one.":"No Resources are currently available from this project."}),y?t.jsx(oc,{type:"error",children:y}):null,c?t.jsxs("footer",{className:"employee-project-resources-footer",children:[t.jsxs("div",{children:[v?t.jsxs(oc,{type:"error",children:[v," ",T?"Your unsaved selection is still here; try again.":"The saved selection remains available here."]}):null,w?t.jsx(oc,{type:"success",children:w}):null,b?t.jsx(oc,{type:"warning",children:"Saving Project Resourcesâplease wait before leaving."}):null,b||v||w||!T?null:t.jsx(oc,{type:"warning",children:"Save to update Resources for everyone on this project."})]}),t.jsx(lc,{children:t.jsx(ec,{variant:"primary",disabled:!T||b,onClick:async()=>
2{if(!c||!T||b)return;o?.(!0,{label:"Project Resources",message:"Saving Project Resourcesâplease wait before leaving."}),x(!0),j(null),N("");const e=u.map(Om),t={resourceIds:e.map(e=>e.resourceId),resourceRefs:e};try{let e;try{e=await s(`${d}/${n.id}/resources`,{method:"PUT",body:JSON.stringify(t)})}catch(a){if("PROJECT_RESOURCE_GRANT_REQUIRED"!==a?.code||!window.confirm("Some project members cannot access these Resources. Grant viewer access and link them?"))throw a;e=await s(`${d}/${n.id}/resources`,{method:"PUT",body:JSON.stringify({...t,grantResourceAccess:!0})})}const i=e?.data?.resources||u;h(i),p(i),f(Dm(i)),l?.(!1,null);try{await(r?.({resources:i})),N("Project Resources saved.")}catch{j("Project Resources were saved, but the project could not be refreshed.")}}catch(a){j(function(e){return e?.safeMessage||e?.message||"Project Resources could not be saved."}(a))}finally{x(!1),o?.(!1,null)}},children:b?"Saving Resourcesâ¦":"Save Resources"})})]}):null]})]})}function $m(e){return 1===e.length?e[0].message:`Discard these unsaved project drafts: ${e.map(e=>e.label).join(", ")}?`}const Mm={settings:"Canât leave Project settings while it is saving. Try again when saving finishes.",resources:"Canât leave Project Resources while it is saving. Try again when saving finishes.",assignments:"Canât leave project assignments while they are saving. Try again when saving finishes.","create-team":"Canât leave the Create project team form while it is saving. Try again when saving finishes.",lifecycle:"Canât leave this project while its lifecycle is updating. Try again when it finishes."};function Um({project:n,onClose:s,onOpenResource:r,selectedTaskId:i,onOpenTask:l,onCloseTask:o,onNavigateActivity:c,onOpenConversation:d,onOpenUpdates:u,request:h,readerRequest:m,endpointPrefix:p="/api/workspace/v1/projects",onProjectChanged:g,onProjectMutationApplied:f,onProjectRefreshRequired:b=g,onProjectArchived:x,projectView:v,projectDirty:j=!1,onProjectViewChange:y,onDirtyChange:k,headingRef:w,closePending:N=!1}){const S=e.useId(),C=`${S}-lifecycle-guard`,R=e.useRef(null),E=e.useRef(null),I=e.useRef(null),_=e.useRef({}),T=e.useRef({}),A=e.useRef(null),O=e.useRef(null),D=e.useRef(n?.id),P=e.useRef(!1),L=e.useRef(n?.id),[$,M]=a.useState({}),[U,F]=a.useState({}),[z,q]=a.useState({activeChannel:1,messages:["",""]}),[B,W]=a.useState(!1),V="function"==typeof y,[H,K]=a.useState(i?"board":"overview"),[G,J]=a.useState({name:"",description:"",projectRole:"contributor"}),[Y,Q]=a.useState({saving:!1,error:null,saved:!1,refreshWarning:!1});L.current=n?.id,e.useEffect(()=>(P.current=!0,()=>{P.current=!1}),[]);const X=a.useCallback((e,t,a=null)=>{const n=_.current;if(!t){if(!n[e])return;const t={...n};return delete t[e],_.current=t,void M(t)}if(!a)return;const s={...n,[e]:a};_.current=s,M(s)},[]),Z=a.useCallback((e,t,a=null)=>{const n=T.current;if(!t){if(!n[e])return;const t={...n};return delete t[e],T.current=t,void F(t)}if(!a)return;const s={...n,[e]:a};T.current=s,F(s)},[]),ee=a.useCallback(()=>{requestAnimationFrame(()=>{const e=Object.values(T.current)[0];if(e?.restoreFocus?.())return;const t=A.current;if(t?.isConnected&&!t.disabled)return void t.focus();const a=E.current?.querySelector('[role="tab"][aria-selected="true"]');a?a.focus():O.current?.focus()})},[]),te=a.useCallback(()=>{const e=Object.keys(T.current)[0],t=Mm[e];t&&q(e=>{const a=0===e.activeChannel?1:0,n=["",""];return n[a]=t,{activeChannel:a,messages:n}})},[]),ae=a.useCallback(()=>Object.keys(T.current).length>0,[]),ne=a.useCallback(()=>{ae()&&te(),ee()},[te,ae,ee]),se=a.useCallback(()=>{const e=Object.values(_.current);_.current={},M({}),e.forEach(e=>e.discard?.())},[]),re=a.useCallback((e,t)=>X("settings",e,t),[X]),ie=a.useCallback((e,t)=>X("resources",e,t),[X]),oe=a.useCallback((e,t)=>X("assignments",e,t),[X]),ce=a.useCallback((e,t)=>Z("settings",e,t),[Z]),de=a.useCallback((e,t)=>Z("resources",e,t),[Z]),ue=a.useCallback((e,t)=>Z("assignments",e,t),[Z]),he=a.useCallback(e=>Z("lifecycle",e,e?{label:"project lifecycle",message:"Updating project lifecycleâplease wait before leaving."}:null),[Z]),me=a.useCallback(async(...e)=>{const t=n?.id;P.current&&L.current===t&&await(x?.(...e))},[x,n?.id]),pe=a.useCallback(async e=>{f?.(n?.id,t=>{const a=Array.isArray(e?.users)?e.users:t.directMembers,n=Array.isArray(e?.teams)?e.teams:t.assignedTeams;return{directMembers:a,assignedTeams:n,memberCount:a?.length||0,teamCount:n?.length||0,assignmentFingerprint:e?.assignmentFingerprint||t.assignmentFingerprint}}),await(g?.())},[g,f,n?.id]),ge=a.useMemo(()=>Object.values($),[$]),fe=a.useMemo(()=>Object.values(U),[U]),be=a.useMemo(()=>fe.length?{pending:!0,message:fe[0].message,isPending:ae,isDirty:()=>Object.keys(_.current).length>0,onBlocked:ne}:ge.length?{dirty:!0,message:$m(ge),discardAll:se,isDirty:()=>Object.keys(_.current).length>0,isPending:ae,onBlocked:ne}:null,[ge,se,ne,ae,fe]),xe=ge.length>0,ve=fe.length>0,je=j||xe||ve,ye=ve?`${fe[0].message} Project lifecycle actions are unavailable until it finishes.`:xe?function(e){const t=e.map(e=>e.label).join(", ");return 1===e.length?`Unsaved draft: ${t}. Save or discard it before using project lifecycle actions.`:`Unsaved drafts: ${t}. Save or discard them before using project lifecycle actions.`}(ge):j?"Save or discard your project changes before using project lifecycle actions.":"";e.useEffect(()=>{k?.(be)},[k,be]),e.useEffect(()=>()=>k?.(null),[k]),e.useEffect(()=>{D.current!==n?.id&&(D.current=n?.id,_.current={},T.current={},M({}),F({}),q({activeChannel:1,messages:["",""]}),k?.(null))},[k,n?.id]),e.useEffect(()=>{ve||q(e=>e.messages.some(Boolean)?{activeChannel:1,messages:["",""]}:e)},[ve]),e.useEffect(()=>{if(!xe&&!ve)return;const e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[xe,ve]),e.useEffect(()=>{if(!xe&&!ve)return;const e=e=>{const t=e.target.closest?.("a[href]");if(!t)return;const a=t.getAttribute("href")||"";if("_blank"===t.target||a.startsWith("#")||/^[a-z]+:\/\//i.test(a))return;if(Object.keys(T.current).length)return e.preventDefault(),e.stopPropagation(),void ne();const n=Object.values(_.current);n.length&&(window.confirm($m(n))?se():(e.preventDefault(),e.stopPropagation()))};return globalThis.document.addEventListener("click",e,!0),()=>globalThis.document.removeEventListener("click",e,!0)},[se,ne,xe,ve]);const ke=n?.capabilities||{}
2,we=n?.assignmentContext,Ne=!we||Boolean(we.isOwner||we.directRole||we.teams?.length),Se=we?.directRole?we.directRole:we?.isOwner?"owner":we?.teams?.length?"team access":we?"oversight access":"team access",Ce=Boolean(n?.archivedAt),Re=ke.canManageProjectMembers||ke.canManageProjectTeams,Ee=[{id:"overview",label:"Overview"},...Ce?[]:[{id:"board",label:"Board"}],{id:"members",label:"Members"},{id:"resources",label:"Resources"},{id:"activity",label:"Activity"},...ke.canEditProject||ke.canArchiveProject||ke.canRestoreProject||ke.canDeleteProject?[{id:"settings",label:"Settings"}]:[]],Ie=Ee.map(e=>e.id).join("|"),_e=e=>Ee.some(t=>t.id===e),Te=i&&_e("board")?"board":"overview",Ae=V?_e(v)?v:Te:_e(H)?H:Te,Oe=e=>{if(Object.keys(T.current).length)return te(),!1;const t=Object.values(_.current);if(t.length){if(!window.confirm($m(t)))return!1;se()}return V?!1!==y(e):(K(e),!0)},De=a.useCallback(()=>{if(I.current=null,!P.current)return;const e=E.current,t=e?.querySelectorAll('[role="tab"]'),a=t?.[t.length-1];if(!e||!a)return void W(!1);const n=e.scrollWidth-e.clientWidth>1,s=e.getBoundingClientRect(),r=a.getBoundingClientRect(),i="rtl"===getComputedStyle(e).direction?r.left<s.left-1:r.right>s.right+1;W(n&&i)},[]),Pe=a.useCallback(()=>{null===I.current&&(I.current=requestAnimationFrame(De))},[De]);e.useEffect(()=>{const e=E.current;if(!e)return;e.addEventListener("scroll",Pe,{passive:!0}),window.addEventListener("resize",Pe);const t="function"==typeof ResizeObserver?new ResizeObserver(Pe):null;return t?.observe(e),e.querySelectorAll('[role="tab"]').forEach(e=>t?.observe(e)),Pe(),()=>{e.removeEventListener("scroll",Pe),window.removeEventListener("resize",Pe),t?.disconnect(),null!==I.current&&(cancelAnimationFrame(I.current),I.current=null)}},[Pe,Ie]),e.useEffect(()=>{const e=Array.from(E.current?.querySelectorAll('[role="tab"]')||[]).find(e=>"true"===e.getAttribute("aria-selected"));e?.scrollIntoView?.({block:"nearest",inline:"nearest",behavior:"auto"}),Pe()},[Ae,Pe]);const Le=a.useCallback(()=>{J({name:"",description:"",projectRole:"contributor"}),Q({saving:!1,error:null,saved:!1,refreshWarning:!1})},[]),$e=Boolean(G.name)||Boolean(G.description)||"contributor"!==G.projectRole;e.useEffect(()=>{X("create-team",$e,$e?{label:"new project team",message:"Discard your unsaved new project team draft?",discard:Le}:null)},[Le,$e,X]),e.useEffect(()=>()=>X("create-team",!1),[X]);const Me=(e,t)=>{J(a=>({...a,[e]:t})),Q(e=>e.saving?e:{saving:!1,error:null,saved:!1,refreshWarning:!1})};if(!n)return null;return t.jsxs("article",{ref:R,className:"employee-project-detail",onFocusCapture:e=>{R.current?.contains(e.target)&&(A.current=e.target)},children:[t.jsx(Yo,{className:"employee-project-detail-identity",title:n.name,headingRef:w,headingTabIndex:w?-1:void 0,description:`${n.owner?.name||"No owner"} · ${Se}`,actions:t.jsxs(t.Fragment,{children:[t.jsxs(ec,{variant:"secondary",onClick:()=>d?.(n),children:[t.jsx(le,{size:16,"aria-hidden":"true"})," ",n.conversationId?"Open project chat":"Start project chat"]}),"settings"!==Ae?t.jsx(vm,{entityType:"Project",entityName:n.name,archived:Ce,canArchive:ke.canArchiveProject,canRestore:ke.canRestoreProject,canDelete:ke.canDeleteProject,request:h,endpoint:`${p}/${n.id}/lifecycle`,onChanged:me,onDeleted:me,onPendingChange:he,triggerDescriptionId:je?C:void 0,disabled:je,focusableDisabled:!0}):null,t.jsx(ec,{className:"employee-project-back",variant:"ghost",disabled:N,"aria-disabled":ve?"true":void 0,onClick:()=>{if(Object.keys(T.current).length)return ne(),!1;const e=Object.values(_.current);if(e.length){if(!window.confirm($m(e)))return!1;se()}return s?.()},children:N?"Returning to projectsâ¦":"Back to Projects"})]}),children:t.jsxs("div",{className:"employee-project-badges",children:[t.jsx(tc,{value:n.status}),t.jsx(ac,{value:n.priority}),t.jsx(nc,{value:n.dueDate})]})}),je?t.jsx("p",{ref:ve?O:void 0,id:C,className:"employee-project-draft-status"+(ve?" is-pending":""),tabIndex:ve?-1:0,children:ye}):null,t.jsx("div",{className:"sr-only","aria-label":"Project navigation status",children:z.messages.map((e,a)=>t.jsx("p",{role:"status","aria-live":"polite","aria-atomic":"true","data-project-exit-announcer":a,children:e},a))}),t.jsxs("div",{className:"employee-project-detail-nav-shell",children:[t.jsx("nav",{ref:E,className:"employee-project-detail-nav",role:"tablist","aria-orientation":"horizontal","aria-label":"Project sections",onKeyDown:e=>
2{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;e.preventDefault();const t=Ee.findIndex(e=>e.id===Ae),a="Home"===e.key?0:"End"===e.key?Ee.length-1:"ArrowRight"===e.key?(t+1)%Ee.length:(t-1+Ee.length)%Ee.length;Oe(Ee[a].id)&&requestAnimationFrame(()=>E.current?.querySelectorAll('[role="tab"]')?.[a]?.focus())},children:Ee.map(e=>t.jsx("button",{type:"button",role:"tab",id:`${S}-${e.id}-tab`,"aria-selected":Ae===e.id,"aria-disabled":ve?"true":void 0,"aria-controls":`${S}-panel`,tabIndex:Ae===e.id?0:-1,onClick:()=>{return t=e.id,void(Oe(t)||requestAnimationFrame(()=>E.current?.querySelector('[role="tab"][aria-selected="true"]')?.focus()));var t},children:e.label},e.id))}),B?t.jsxs("p",{className:"employee-project-detail-nav-cue",children:["Scroll to see more sections",t.jsx(lt,{size:15,"aria-hidden":"true"})]}):null]}),t.jsxs("section",{className:"employee-project-detail-section",role:"tabpanel",id:`${S}-panel`,"aria-labelledby":`${S}-${Ae}-tab`,tabIndex:0,children:["overview"===Ae?t.jsxs(t.Fragment,{children:[t.jsxs(Yo,{title:"Project overview",children:[t.jsx(wd,{text:n.description||"No project description.",className:"employee-project-description ws-body"}),t.jsxs("dl",{className:"employee-project-detail-summary",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Owner"}),t.jsx("dd",{children:n.owner?.name||"Unassigned"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Start date"}),t.jsx("dd",{children:wc(n.startDate,"Not set")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Due date"}),t.jsx("dd",{children:wc(n.dueDate,"Not set")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Members"}),t.jsx("dd",{children:Number(n.memberCount||n.directMembers?.length||0)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Teams"}),t.jsx("dd",{children:Number(n.teamCount||n.assignedTeams?.length||0)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Resources"}),t.jsx("dd",{children:Number(n.linkedResourceCount||n.linkedResources?.length||0)})]})]})]}),Ne?t.jsx(Wc,{projectId:n.id,request:m||h,onOpenUpdate:e=>u?.(n.id,e),onViewAll:()=>u?.(n.id)}):null]}):null,"board"===Ae?t.jsx(Yo,{title:"Task board",description:"Move, open, and create project tasks.",children:t.jsx(Tm,{project:n,request:h,selectedTaskId:i,onSelectedTaskChange:e=>{var t;e?(t={id:e,projectId:n.id},l?.(t)):o?.()},endpointPrefix:p,enforceServerCapabilities:!0,hideHeading:!0})}):null,"members"===Ae?t.jsxs(Yo,{title:"Members and teams",children:[t.jsxs(Xo,{children:[t.jsx("h3",{children:"Members"}),t.jsxs("div",{className:"employee-project-record-list",children:[(n.directMembers||[]).map(e=>t.jsx(Qo,{className:"employee-project-assignment-record",children:t.jsxs("div",{children:[t.jsxs("strong",{children:[e.name||"Unnamed"," · ",Sc(e.projectRole)]}),t.jsx("small",{children:e.title||Sc(e.personnelType)})]})},e.userId)),n.directMembers?.length?null:t.jsx("p",{children:"No direct members"})]})]}),t.jsxs(Xo,{boundary:"divided",children:[t.jsx("h3",{children:"Teams"}),t.jsxs("div",{className:"employee-project-record-list",children:[(n.assignedTeams||[]).map(e=>t.jsx(Qo,{className:"employee-project-assignment-record",children:t.jsxs("div",{children:[t.jsxs("strong",{children:[e.name," · ",Sc(e.projectRole)]}),t.jsxs("small",{children:[Number(e.memberCount||0)," members"]})]})},e.teamId)),n.assignedTeams?.length?null:t.jsx("p",{children:"No assigned teams"})]})]}),Re?t.jsx(Ph,{project:n,request:h,onSaved:pe,endpointPrefix:p,onDirtyChange:oe,onPendingChange:ue}):null,ke.canManageProjectTeams?t.jsxs("form",{className:"projects-admin-team-create","aria-busy":Y.saving?"true":void 0,onSubmit:async e=>{if(e.preventDefault(),G.name.trim()&&ke.canManageProjectTeams&&!Y.saving){Z("create-team",!0,{label:"new project team",message:"Creating project teamâplease wait before leaving."}),Q({saving:!0,error:null,saved:!1,refreshWarning:!1});try{const e=await h(`${p}/${n.id}/teams`,{method:"POST",body:JSON.stringify({...G,name:G.name.trim()})}),t=e?.data?.team;(t?.id||t?.teamId)&&f?.(n.id,e=>{const a=t.teamId||t.id,n=(e.assignedTeams||[]).filter(e=>e.teamId!==a);return n.push({teamId:a,name:t.name,description:t.description||"",memberCount:Number(t.memberCount||0),projectRole:t.projectRole||G.projectRole}),{assignedTeams:n,teamCount:n.length}}),J({name:"",description:"",projectRole:"contributor"}),X("create-team",!1),Q({saving:!0,error:null,saved:!0,refreshWarning:!1});try{await(g?.())}catch{Q({saving:!0,error:null,saved:!0,refreshWarning:!0})}}catch(t){Q({saving:!1,error:t?.safeMessage||t?.message||"Unable to create team.",saved:!1,refreshWarning:!1})}finally{Z("create-team",!1),Q(e=>({...e,saving:!1}))}}},children:[t.jsxs(ic,{legend:"Create project team",description:"Create a team scoped to this project.",disabled:Y.saving,children:[t.jsx(rc,{label:"Team name",required:!0,children:t.jsx("input",{value:G.name,onChange:e=>Me("name",e.target.value)})}),t.jsx(rc,{label:"Project role",children:t.jsxs("select",{value:G.projectRole,onChange:e=>Me("projectRole",e.target.value),children:[t.jsx("option",{value:"contributor",children:"Contributor"}),t.jsx("option",{value:"viewer",children:"Viewer"})]})}),t.jsx(rc,{label:"Description",className:"projects-admin-field--wide",children:t.jsx("input",{value:G.description,onChange:e=>Me("description",e.target.value)})})]}),Y.error?t.jsx(oc,{type:"error",children:Y.error}):null,Y.saving?t.jsx(oc,{type:"warning",children:"Creating project teamâplease wait before leaving."}):null,!Y.saving&&Y.saved?t.jsx(oc,{type:Y.refreshWarning?"warning":"success",children:Y.refreshWarning?"Team created, but this view could not refresh. Reload to see the latest.":"Team created."}):null,t.jsx(lc,{children:t.jsx(ec,{variant:"primary",type:"submit",disabled:Y.saving||!G.name.trim(),children:Y.saving?"Creating teamâ¦":"Create team"})})]}):null]}):null,"resources"===Ae?t.jsx(Yo,{title:"Project Resources",description:"Open what is already attached or update the project's shared Resource set.",children:t.jsx(Lm,{project:n,request:h,canManage:ke.canManageProjectResources,onOpenResource:e=>r?.(n,e),onSaved:b,endpointPrefix:p,onDirtyChange:ie,onPendingChange:de})}):null,"activity"===Ae?t.jsx(Yo,{title:"Project activity",children:t.jsx(xc,{endpoint:`/api/employee/projects/${n.id}/activity`,onNavigate:c})}
2):null,"settings"===Ae?t.jsx(Yo,{title:"Project settings",description:`Update the working details and lifecycle for ${n.name}.`,children:t.jsxs("div",{className:"employee-project-management"+(ke.canEditProject?" has-editor":" is-lifecycle-only"),children:[ke.canEditProject?t.jsx(Th,{project:n,request:h,onSaved:b,endpointPrefix:p,showHeading:!1,manageNavigationGuards:!1,onDirtyDescriptorChange:re,onPendingChange:ce}):null,ke.canArchiveProject||ke.canRestoreProject||ke.canDeleteProject?t.jsxs("aside",{className:"employee-project-lifecycle-guidance","aria-label":"Project lifecycle guidance",children:[t.jsxs("div",{className:"employee-project-lifecycle-control",children:[t.jsx(vm,{entityType:"Project",entityName:n.name,archived:Ce,canArchive:ke.canArchiveProject,canRestore:ke.canRestoreProject,canDelete:ke.canDeleteProject,request:h,endpoint:`${p}/${n.id}/lifecycle`,onChanged:me,onDeleted:me,onPendingChange:he,triggerLabel:"Project lifecycle actions",triggerVariant:"secondary",triggerDescriptionId:je?C:void 0,disabled:je,focusableDisabled:!0}),t.jsx("p",{className:"ws-meta",children:je?"Save or cancel your project changes before using lifecycle actions.":"Review the confirmation before any lifecycle change."})]}),ke.canArchiveProject||ke.canRestoreProject?t.jsxs(Xo,{boundary:"callout",className:"employee-project-lifecycle-callout",children:[t.jsx("h3",{children:Ce?"Restore to active work":"Archive from active work"}),t.jsx("p",{children:Ce?t.jsx(t.Fragment,{children:"Restoring makes this project available in active project views again. Its tasks and history are already retained."}):t.jsx(t.Fragment,{children:"Archiving hides this project from active work without removing its tasks or history. You can restore it later."})})]}):null,ke.canDeleteProject?t.jsxs(Xo,{boundary:"callout",className:"employee-project-danger-zone",children:[t.jsx("h3",{children:"Permanent deletion"}),t.jsx("p",{children:"Deletion is permanent. TokenWorks checks dependencies first, and retained project history may block removal."})]}):null]}):null]})}):null]})]})}function Fm(e,t="mine"){const[a,n=""]=String(e).split("?"),s=new URLSearchParams(n);return s.set("scope","all"===t?"all":"mine"),`${a}?${s.toString()}`}function zm(e,t){return!e||!t||e.bottom<=e.top?0:t.top<e.top?t.top-e.top:t.bottom>e.bottom?t.bottom-e.bottom:0}function qm(e){const t=e?.closest?.(".employee-workspace-main"),a=t?globalThis.getComputedStyle?.(t)?.overflowY:null,n=t&&/^(auto|scroll|overlay)$/.test(a)?t:globalThis.document?.scrollingElement||globalThis.document?.documentElement;return n?{element:n,top:n.scrollTop,left:n.scrollLeft}:null}function Bm(e,t,{restoreCaptured:a=!1}={}){if(!e?.element||!t)return;const n=e.element;a&&(n.scrollTop=e.top,n.scrollLeft=e.left),t.focus({preventScroll:!0});const s=function(e){const t=globalThis.document?.documentElement;if([globalThis.document?.scrollingElement,t,globalThis.document?.body].includes(e))return{top:0,bottom:globalThis.innerHeight||t?.clientHeight||0};const a=e?.getBoundingClientRect?.();if(!a)return null;const n=globalThis.innerHeight||t?.clientHeight||a.bottom;return{top:Math.max(0,a.top),bottom:Math.min(n,a.bottom)}}(n),r=zm(s,t.getBoundingClientRect?.());r&&(n.scrollTop+=r);if(zm(s,t.getBoundingClientRect?.())&&t.scrollIntoView){const e=function(e,t){const a=new Set([t,globalThis.document?.scrollingElement,globalThis.document?.documentElement,globalThis.document?.body]);let n=e.parentElement;for(;n;)a.add(n),n=n.parentElement;return[...a].filter(Boolean).map(e=>[e,e.scrollLeft])}(t,n);t.scrollIntoView({block:"nearest",inline:"nearest",behavior:"auto"}),e.forEach(([e,t])=>{e.scrollLeft=t})}t.focus({preventScroll:!0})}const Wm=Bm,Vm=["","planned","active","paused","completed","cancelled"],Hm=["","low","normal","high","urgent"];function Km({selectedProjectId:n,selectedTaskId:s,onOpenProject:r,onCloseProject:i,onOpenTask:l,onCloseTask:o,onNavigateActivity:c,onOpenConversation:d,onOpenUpdates:u,selectedProjectView:h,projectDirty:m=!1,onProjectViewChange:p,onProjectDirtyChange:g,scope:f="mine"}){const{makeAuthRequest:b}=Yn(),x=$s(),[v,j]=e.useState(""),[y,k]=e.useState(""),[w,N]=e.useState(""),[S,C]=e.useState("active"),[R,E]=e.useState(null),[I,_]=e.useState(null),[T,A]=e.useState(!1),[O,D]=e.useState(!1),[P,L]=e.useState(!1),[$,M]=e.useState(null),[U,F]=e.useState(null),[z,q]=e.useState({activeChannel:1,messages:["",""]}),[B,W]=e.useState(null),[V,H]=e.useState(null),[K,G]=e.useState(!1),[J,Y]=e.useState(null),Q=e.useRef(n),X=e.useRef(0),Z=e.useRef(null),ee=e.useRef(!0),te=e.useRef(r),ae=e.useRef(null),ne=e.useRef(null),se=e.useRef(null),re=e.useRef(null),ie=e.useRef(!1),le=e.useRef(!1),oe=e.useRef(!1),ce=e.useRef(null),de=e.useRef(null),he=e.useRef(null),me=e.useRef(null),pe=e.useRef(null),ge=e.useRef(null),fe=e.useRef(!1),be=e.useMemo(()=>{const e=new URLSearchParams;return v&&e.set("search",v),y&&e.set("status",y),w&&e.set("priority",w),"all"===f&&e.set("archiveState",S),Fm(`/api/workspace/v1/projects?${e.toString()}`,f)},[S,w,f,v,y]),{data:xe,loading:ve,error:je,refresh:ye,hasMore:ke,loadMore:we,loadingMore:Ne,loadMoreError:Se,requestLifecycle:Ce}=kc(be,{initialData:{projects:[]},collectionKey:"projects"}),Re=e.useRef(Ce);Re.current=Ce;const Ee=Boolean(P&&$?.endpoint===be),Ie=Ee?$.data:xe,_e=Ce.endpoint===be&&"refresh"===Ce.operation?Ce:null,Te=Boolean(Ee&&_e?.requestToken===$.requestToken);let Ae=null;P&&"error"===_e?.status&&!Te?Ae=_e.error:P&&!Ee&&(Ae=je);const Oe=Boolean(P&&"pending"===_e?.status),De=Boolean(!P&&U?.endpoint===be&&"success"===_e?.status&&_e.generation===U.generation),Pe=a.useCallback((e,t)=>b(Fm(e,f),t),[b,f]),Le=a.useCallback((e,t)=>b(Fm(e,"mine"),t),[b]),$e=I===f?R:null,Me=X.current,Ue=[v,y,w].filter(
2Boolean).length+Number("active"!==S),Fe=Ie?.projects||[],ze=Boolean(ve&&!P&&Fe.length>0),qe=()=>{j(""),k(""),N(""),C("active")},Be=a.useCallback(()=>{if(!oe.current)return;q(e=>{const t=0===e.activeChannel?1:0,a=["",""];return a[t]="Canât leave Create project while it is saving. Try again when saving finishes.",{activeChannel:t,messages:a}});const e=()=>{const e=de.current;!e?.isConnected||e.disabled?ce.current?.querySelector('.projects-admin-save-state[role="status"]')?.focus():e.focus()};e(),requestAnimationFrame(e)},[]),We=a.useCallback(()=>{le.current=!1,oe.current=!1,D(!1),q({activeChannel:1,messages:["",""]}),g?.(null),A(!1)},[g]),Ve=e.useMemo(()=>({dirty:!0,message:"Discard your unsaved project changes?",isDirty:()=>le.current,isPending:()=>oe.current,onBlocked:Be,discardAll:We}),[We,Be]),He=a.useCallback(()=>{g?.(le.current||oe.current?Ve:null)},[Ve,g]),Ke=a.useCallback(e=>{le.current=Boolean(e),He()},[He]),Ge=a.useCallback(e=>{oe.current=Boolean(e),D(Boolean(e)),e||q({activeChannel:1,messages:["",""]}),He()},[He]),Je=a.useCallback((e=null)=>{const t=()=>{if(e){const t=Re.current;if(t.endpoint!==e.endpoint||t.generation!==e.generation||"error"!==t.status)return}const t=he.current;t?.isConnected&&!t.disabled&&t.focus({preventScroll:!0})};return t(),requestAnimationFrame(t)},[]),Ye=a.useCallback(e=>(ge.current=null,F(null),ye(e)),[ye]),Qe=a.useCallback(async()=>{if(me.current?.endpoint===be||ve)return null;const e=Symbol(be),t={endpoint:be,token:e};me.current=t,ge.current=null,F(null);try{return await ye({rejectOnError:!0,requestToken:e})}catch{return null}},[be,ve,ye]);a.useEffect(()=>{const e=me.current,t=Boolean(e&&Ce.endpoint===e.endpoint&&Ce.requestToken===e.token);if(e&&!t&&(me.current=null),P&&Ce.endpoint===be&&"refresh"===Ce.operation){if("success"===Ce.status){if(t){const e={endpoint:be,generation:Ce.generation};ge.current=e,F(e),me.current=null}return L(!1),void M(null)}"error"===Ce.status&&t&&(me.current=null,Je({endpoint:be,generation:Ce.generation}))}},[P,be,Je,Ce]),a.useEffect(()=>{if(!De||!ge.current)return;const e=ge.current;ge.current=null;const t=requestAnimationFrame(()=>{const t=Re.current;t.endpoint===e?.endpoint&&t.generation===e?.generation&&"success"===t.status&&pe.current?.focus({preventScroll:!0})});return()=>cancelAnimationFrame(t)},[De]),a.useEffect(()=>{if(T||!P||!fe.current)return;fe.current=!1;const e=Je();return()=>cancelAnimationFrame(e)},[P,Je,T]),a.useEffect(()=>{if(!T)return;const e=e=>{(le.current||oe.current)&&(e.preventDefault(),e.returnValue="")};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[T]);const Xe=()=>{F(null),A(!0)},Ze=a.useCallback(async()=>{if(oe.current)return Be(),!1;if(!le.current)return!0;if(ie.current)return!1;ie.current=!0;try{return await x({title:"Discard project draft?",message:"Your unsaved project details will be lost.",confirmLabel:"Discard draft",cancelLabel:"Keep editing",confirmVariant:"danger"})}finally{ie.current=!1}},[x,Be]),et=a.useCallback(async()=>!!(await Ze())&&(We(),!0),[Ze,We]);te.current=r;const tt=a.useCallback(async(e,t=!1,a=null,{preserveSelectionOnError:n=!1}={})=>{const s=e?.id||e;if(!s)return!1;if(Z.current===s)return!1;const r=++X.current;Z.current=s,Y(s),a&&(se.current=s,re.current=qm(a)),W(null),G(!1);try{const e=await Pe(`/api/workspace/v1/projects/${s}`);return!(!ee.current||r!==X.current)&&(E(e.data.project),_(f),t&&te.current?.(e.data.project),!0)}catch(i){if(!ee.current||r!==X.current)return!1;if(n)throw i;return E(null),W("This item is unavailable or you no longer have access."),!1}finally{ee.current&&r===X.current&&Z.current===s&&(Z.current=null,Y(null))}},[f,Pe]);a.useEffect(()=>(ee.current=!0,()=>{ee.current=!1,X.current+=1}),[]),a.useEffect(()=>{X.current+=1,Z.current=null,Y(null),G(!1)},[f]),a.useEffect(()=>{if(!$e?.id)return;const e=requestAnimationFrame(()=>ae.current?.focus({preventScroll:!0}));return()=>cancelAnimationFrame(e)},[$e?.id]),a.useEffect(()=>{Q.current&&!n&&(X.current+=1,Z.current=null,Y(null),E(null),_(null),W(null),G(!1)),Q.current=n,n&&$e?.id!==n&&tt(n,!1)},[tt,n,$e?.id]),a.useEffect(()=>{const e=se.current;if(n||R||B||!ne.current||!e)return;let t;const a=requestAnimationFrame(()=>{const a=Array.from(ne.current?.querySelectorAll("[data-project-open-id]")||[]).find(t=>t.dataset.projectOpenId===String(e)),n=re.current;Bm(n,a,{restoreCaptured:!0}),t=requestAnimationFrame(()=>{Bm(n,a),se.current=null,re.current=null})});return()=>{cancelAnimationFrame(a),t&&cancelAnimationFrame(t)}},[xe?.projects,R,n,B]);const at=a.useCallback(()=>{!1!==i?.()&&(X.current+=1,Z.current=null,Y(null),H(null),W(null),n?G(!0):(E(null),_(null)))},[i,n]),nt=a.useCallback(async(e=!1)=>{const t=()=>{if(e)throw new Error("Project refresh was superseded before surrounding details were confirmed.");return!1};if(Me!==X.current)return t();const a=$e?.id;if(!a)return t();const n=await Ye({rejectOnError:e});if(!ee.current||Me!==X.current)return t();if(!n)return t();try{return!!(await tt(a,!1,null,{preserveSelectionOnError:!0}))||t()}catch(s){if(e)throw s;return!1}},[Me,tt,Ye,$e?.id]),st=a.useCallback(()=>nt(!0),[nt]),rt=a.useCallback(()=>nt(!0),[nt]),it=a.useCallback((e,t)=>{Me===X.current&&E(a=>{if(!a||a.id!==e)return a;const n="function"==typeof t?t(a):t;return n?{...a,...n}:a})},[Me]),lt=async(e,t)=>{const a=await Pe(`/api/workspace/v1/projects/${e.id}/resources/${t.id}/access`,{method:"POST",body:JSON.stringify({})}),n=a?.data?.url||a?.data?.href;if(!n){const e=new Error("This Resource does not have an available destination.");throw e.safeMessage=e.message,e}window.open(n,a.data.url?"_blank":"_self","noopener,noreferrer")},ot=async e=>{H(null);try{if(e.conversationId)return void d?.(e.conversationId);const t=await Pe("/api/workspace/v1/messages",{method:"POST",body:JSON.stringify({conversationType:"project",projectId:e.id})}),a=t?.data?.conversation;if(!a?.id)throw new Error("Project chat could not be opened");d?.(a.id)}catch(t){H(t.safeMessage||"Project chat could not be opened.")}};return $e?t.jsxs(t.Fragment,{children:[V?t.jsx("p",{className:"workspace-inline-error",role:"alert",children:V}):null,t.jsx(Um,{project:$e,request:Pe,readerRequest:Le,endpointPrefix:"/api/workspace/v1/projects",onProjectChanged:st,onProjectMutationApplied:it,onProjectRefreshRequired:rt,onProjectArchived:async()=>{at(),await Ye()},onClose:at,closePending:K,onOpenResource:lt,selectedTaskId:s,onOpenTask:l,onCloseTask:o,onNavigateActivity:c,onOpenConversation:ot,onOpenUpdates:u,projectView:h,projectDirty:m,onProjectViewChange:p,onDirtyChange:g,headingRef:ae})]}):t.jsxs("section",{className:"employee-projects-panel",children:[Ie?.capabilities?.canCreateProject&&Ie?.projects?.length?t.jsx("div",{className:"employee-projects-actions",children:t.jsx(ec,{variant:"primary",onClick:Xe,children:"Create project"})}):null,Ie?.capabilities?.canCreateProject||T?t.jsx(cc,{isOpen:T,onClose:et,title:"Create project",description:"Define the project, schedule, priority, and owner.",closeLabel:"Close create project",busy:O,children:t.jsxs("div",{ref:ce,onFocusCapture:e=>{de.current=e.target},children:[t.jsx("div",{className:"sr-only","aria-label":"Create project navigation status",children:z.messages.map((e,a)=>t.jsx("p",{role:"status","aria-live":"polite","aria-atomic":"true","data-create-project-exit-announcer":a,children:e},a))}),t.jsx(Th,{project:null,request:Pe,endpointPrefix:"/api/workspace/v1/projects",showHeading:!1,onBeforeCancel:Ze,onCancel:We,onDirtyChange:Ke,onPendingChange:Ge,onSaved:async()=>{const e=Ie,t=be,a=Symbol(t);try{await Ye({rejectOnError:!0,requestToken:a})?(L(!1),M(null)):(fe.current=!0,M({endpoint:t,data:e,requestToken:a}),L(!0))}catch{fe.current=!0,M({endpoint:t,data:e,requestToken:a}),L(!0)}finally{We()}}})]})}):null,t.jsxs(sc,{label:"Project filters",resultCount:(Ie?.projects||[]).length,activeFilterCount:Ue,onClear:qe,mobileCollapsible:!0,children:[t.jsxs("label",{className:"employee-project-search",children:[t.jsx("span",{className:"ws-label",children:"Search"}),t.jsxs("span",{className:"employee-project-search-control",children:[t.jsx(ue,{size:16,"aria-hidden":"true"}
2),t.jsx("input",{value:v,onChange:e=>j(e.target.value),placeholder:"Search projects","aria-label":"Search projects"})]})]}),t.jsxs("label",{children:[t.jsx("span",{className:"ws-label",children:"Status"}),t.jsx("select",{value:y,onChange:e=>k(e.target.value),"aria-label":"Project status",children:Vm.map(e=>t.jsx("option",{value:e,children:e?Sc(e):"All statuses"},e))})]}),"all"===f?t.jsxs("label",{children:[t.jsx("span",{className:"ws-label",children:"Lifecycle"}),t.jsxs("select",{value:S,onChange:e=>C(e.target.value),"aria-label":"Project lifecycle state",children:[t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"archived",children:"Archived"}),t.jsx("option",{value:"all",children:"All"})]})]}):null,t.jsxs("label",{children:[t.jsx("span",{className:"ws-label",children:"Priority"}),t.jsx("select",{value:w,onChange:e=>N(e.target.value),"aria-label":"Project priority",children:Hm.map(e=>t.jsx("option",{value:e,children:e?Sc(e):"All priorities"},e))})]})]}),P?t.jsx(dc,{type:Ae?"error":"unavailable",title:Ae?"Project created, but this project list could not be loaded":"Project created, but the project list may be out of date",description:Ae?.safeMessage||(Ae?"The current project list could not be refreshed. Please try again.":"Your project was created successfully. Retry to load the latest projects."),action:t.jsx(ec,{ref:he,variant:"secondary",onClick:Qe,disabled:Oe,"aria-busy":Oe?"true":void 0,children:Oe?"Refreshing project listâ¦":"Retry project list"})}):null,De?t.jsx(oc,{ref:pe,type:"success",className:"employee-project-list-refresh-success",tabIndex:-1,"aria-atomic":"true",children:"Project list refreshed."}):null,B?t.jsxs("div",{className:"employee-panel",children:[t.jsx("p",{className:"employee-error",children:B}),t.jsx(ec,{variant:"ghost",disabled:K,onClick:at,children:K?"Returning to projectsâ¦":"Back"})]}):null,t.jsx(bc,{loading:ve&&!P&&!Ie?.projects?.length,error:P?null:je,isEmpty:!P&&!(Ie?.projects||[]).length,loadingLabel:"Loading projectsâ¦",errorLabel:"Projects could not be loaded",emptyLabel:Ue?"No projects match these filters.":"No visible projects yet.",emptyDescription:Ue?"Clear filters to see all visible projects.":null,emptyType:Ue?"no-results":"empty",emptyAction:Ue?t.jsx(ec,{variant:"ghost",onClick:qe,children:"Clear filters"}):Ie?.capabilities?.canCreateProject?t.jsx(ec,{variant:"primary",onClick:Xe,children:"Create project"}):null,onRetry:Ye,children:t.jsxs("div",{className:"employee-project-results",role:"region","aria-label":"Project results","aria-busy":ze?"true":void 0,children:[ze?t.jsx("p",{className:"employee-project-results__status",role:"status","aria-live":"polite",children:"Updating projectsâ¦"}):null,t.jsx("div",{ref:ne,className:"employee-card-grid",children:Fe.map(e=>t.jsx(Nh,{project:e,opening:J===e.id,onSelect:(e,t)=>tt(e,!0,t)},e.id))}),ke&&!Se?t.jsx("div",{className:"employee-collection-more",children:t.jsx(ec,{variant:"ghost",disabled:Ne,onClick:we,children:Ne?"Loading moreâ¦":"Load more projects"})}):null,Se?t.jsxs(oc,{type:"error",children:["More projects could not be loaded."," ",t.jsx(ec,{variant:"ghost",onClick:we,children:"Retry loading more"})]}):null]})})]})}function Gm({refresh:t,enabled:a=!0,intervalMs:n=3e4,focusThrottleMs:s=5e3,jitterRatio:r=.1,runOnMount:i=!0}){const l=e.useRef(t),o=e.useRef(null),c=e.useRef(null),d=e.useRef(0),u=e.useRef(!1),h=e.useRef(0),[m,p]=e.useState(null),[g,f]=e.useState(null),[b,x]=e.useState(!1);e.useEffect(()=>{l.current=t},[t]);const v=e.useCallback(({background:e=!0,reason:t="manual"}={})=>{if(!a)return Promise.resolve(null);if(o.current)return o.current;const n=++d.current,s=new AbortController;c.current=s,x(!0);const r=(async()=>{try{const a=await l.current({background:e,reason:t,signal:s.signal});if(!u.current||n!==d.current)return null;const r=Date.now();return h.current=r,p(r),f(null),a}catch(a){return u.current&&n===d.current&&"AbortError"!==a?.name&&f(a),null}finally{n===d.current&&(c.current=null,o.current=null,u.current&&x(!1))}})();return o.current=r,r},[a]),j=e.useCallback(()=>{"undefined"!=typeof document&&"hidden"===document.visibilityState||Date.now()-h.current<s||v({background:!0,reason:"visibility"})},[v,s]);e.useEffect(()=>(u.current=!0,a&&i&&v({background:!1,reason:"mount"}),()=>{u.current=!1,d.current+=1,c.current?.abort(),c.current=null,o.current=null}),[a,v,t,i]),e.useEffect(()=>{if(!a||"undefined"==typeof window)return;let e=null;const t=()=>{const a=n*r*(2*Math.random()-1);e=window.setTimeout(async()=>
2{"hidden"!==document.visibilityState&&await v({background:!0,reason:"interval"}),t()},Math.max(1e3,n+a))},s=()=>j(),i=()=>{"visible"===document.visibilityState&&j()};return window.addEventListener("focus",s),document.addEventListener("visibilitychange",i),t(),()=>{window.removeEventListener("focus",s),document.removeEventListener("visibilitychange",i),e&&window.clearTimeout(e)}},[a,v,n,r,j]);return{invalidate:e.useCallback((e={})=>v({background:!0,reason:"invalidate",...e}),[v]),refreshing:b,lastSuccessAt:m,backgroundError:g}}const Jm=["","low","normal","high","urgent"],Ym=Object.freeze([]),Qm=[{value:"",label:"Any due date"},{value:"overdue",label:"Overdue"},{value:"today",label:"Due today"},{value:"week",label:"Due this week"},{value:"none",label:"No due date"}];function Xm({selectedTaskId:a,selectedProjectId:n=null,onOpenTask:s,onCloseTask:r,scope:i="mine"}){const{user:l,makeAuthRequest:o}=Yn(),[c,d]=e.useState({endpoint:null,tasks:[]}),[u,h]=e.useState(""),[m,p]=e.useState(""),[g,f]=e.useState(""),[b,x]=e.useState(""),[v,j]=e.useState(!1),[y,k]=e.useState(""),[w,N]=e.useState("active"),[S,C]=e.useState(!0),[R,E]=e.useState(null),[I,_]=e.useState(""),T=e.useRef(0),A=e.useRef(new Map),O=e.useRef(null),D=e.useRef(c),P=e.useRef(null);e.useEffect(()=>{D.current=c},[c]),e.useEffect(()=>{const e=setTimeout(()=>p(u),300);return()=>clearTimeout(e)},[u]);const L=e.useMemo(()=>{const e=new URLSearchParams;return m&&e.set("search",m),g&&e.set("projectId",g),b&&e.set("priority",b),v&&e.set("blocked","true"),y&&e.set("due",y),"all"===i&&e.set("archiveState",w),Fm(`/api/workspace/v1/tasks?${e.toString()}`,i)},[w,v,y,b,g,m,i]),$=c.endpoint===L?c.tasks:Ym;e.useEffect(()=>{const e=P.current;if(!e||c.endpoint!==L)return;P.current=null;const t=e.taskId?A.current.get(e.taskId):null;t?.isConnected?t.focus?.():O.current?.focus?.()},[L,c]);const M=e.useCallback((e,t)=>o(Fm(e,i),t),[o,i]),U=Gm({refresh:e.useCallback(async({background:e=!1,signal:t}={})=>{const a=++T.current;e||(C(!0),E(null));try{const n=await o(L,{signal:t});if(a!==T.current)return;const s=n.data.tasks||[],r=[...A.current].find(([,e])=>e===document.activeElement),i=r?.[0]||null;if(e&&i&&!s.some(e=>e.id===i)){const e=D.current.tasks.findIndex(e=>e.id===i),t=s[Math.min(Math.max(e,0),s.length-1)]||null;P.current={taskId:t?.id||null},_("Tasks updated")}d({endpoint:L,tasks:s})}catch(n){if(a!==T.current)return;throw e||"AbortError"===n?.name||E(n),n}finally{a!==T.current||e||C(!1)}},[L,o]),intervalMs:3e4}),F=$.find(e=>e.id===a)||null,z=F?.project?.id||n||null,q=e.useMemo(()=>z?Fm(`/api/workspace/v1/projects/${z}`,i):null,[z,i]),{data:B}=kc(q),W=B?.project||{id:z},V=e.useMemo(()=>Fm("/api/workspace/v1/projects?limit=100",i),[i]),{data:H}=kc(V),K=H?.projects||[],G=Boolean(u||g||b||v||y||"active"!==w),J=e=>{const t=(e.assignees||[]).some(e=>(e.id||e.userId)===l?.id),a=("all"!==i||"active"===w?!e.archivedAt:"archived"!==w||Boolean(e.archivedAt))&&("all"===i||t)&&(!m||`${e.title||""} ${e.description||""}`.toLowerCase().includes(m.toLowerCase()))&&(!g||e.project?.id===g||e.projectId===g)&&(!b||e.priority===b)&&(!v||e.isBlocked)&&function(e,t){if(!t)return!0;if("none"===t)return!e.dueDate;if(!e.dueDate)return!1;const a=String(e.dueDate).slice(0,10),n=new Date,s=n.toISOString().slice(0,10);if("overdue"===t)return a<s&&!e.completedAt;if("today"===t)return a===s;if("week"===t){const e=new Date(n);return e.setUTCDate(e.getUTCDate()+7),a>=s&&a<=e.toISOString().slice(0,10)}return!0}(e,y);d(t=>{if(t.endpoint!==L)return t;const n=t.tasks.find(t=>t.id===e.id);return a?{...t,tasks:n?t.tasks.map(t=>t.id===e.id?{...t,...e}:t):[e,...t.tasks]}:{...t,tasks:t.tasks.filter(t=>t.id!==e.id)}})},Y=e=>{d(t=>t.endpoint===L?{...t,tasks:t.tasks.filter(t=>t.id!==e)}:t)};return t.jsxs("section",{className:"employee-tasks-panel",children:[t.jsx("h2",{ref:O,tabIndex:-1,className:"employee-visually-hidden",children:"My Tasks"}),t.jsx("span",{className:"employee-visually-hidden",role:"status","aria-live":"polite",children:I}),t.jsxs(sc,{className:"employee-task-filters",label:"Task filters",resultCount:$.length,activeFilterCount:[u,g,b,v,y].filter(
2Boolean).length+Number("active"!==w),onClear:()=>{h(""),p(""),f(""),x(""),j(!1),k(""),N("active")},mobileCollapsible:!0,children:[t.jsxs("label",{children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("span",{className:"employee-visually-hidden",children:"Search tasks"}),t.jsx("input",{value:u,onChange:e=>h(e.target.value),placeholder:"Search tasks"})]}),t.jsxs("label",{children:[t.jsx("span",{className:"employee-filter-label",children:"Project"}),t.jsxs("select",{value:g,onChange:e=>f(e.target.value),children:[t.jsx("option",{value:"",children:"All projects"}),K.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]})]}),t.jsxs("label",{children:[t.jsx("span",{className:"employee-filter-label",children:"Priority"}),t.jsx("select",{value:b,onChange:e=>x(e.target.value),children:Jm.map(e=>t.jsx("option",{value:e,children:e?Sc(e):"Any priority"},e))})]}),t.jsxs("label",{children:[t.jsx("span",{className:"employee-filter-label",children:"Due"}),t.jsx("select",{value:y,onChange:e=>k(e.target.value),children:Qm.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))})]}),t.jsxs("label",{className:"employee-filter-checkbox",children:[t.jsx("input",{type:"checkbox",checked:v,onChange:e=>j(e.target.checked)}),t.jsx("span",{children:"Blocked only"})]}),"all"===i?t.jsxs("label",{children:[t.jsx("span",{className:"employee-filter-label",children:"Lifecycle"}),t.jsxs("select",{value:w,onChange:e=>N(e.target.value),children:[t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"archived",children:"Archived"}),t.jsx("option",{value:"all",children:"All"})]})]}):null]}),t.jsx(bc,{loading:S&&!$.length,error:R,isEmpty:!$.length,loadingLabel:"Loading tasksâ¦",errorLabel:"Tasks could not be loaded",emptyLabel:G?"No tasks match these filters.":"No assigned tasks yet.",emptyDescription:G?"Try resetting the filters.":null,emptyType:G?"no-results":"empty",onRetry:()=>U.invalidate({background:!1,reason:"retry"}),children:t.jsx("ul",{className:"employee-task-list",children:$.map(e=>{const n=Ko(e.dueDate),r=[e.resourceCount?`${e.resourceCount} resources`:null,e.commentCount?`${e.commentCount} comments`:null].filter(Boolean),i=e.isBlocked||"overdue"===n.key?"danger":"urgent"===e.priority||"high"===e.priority?"warning":e.completedAt?"complete":"neutral";return t.jsx("li",{children:t.jsxs(Qo,{as:"button",interactive:!0,tone:i,type:"button",ref:t=>{t?A.current.set(e.id,t):A.current.delete(e.id)},className:a===e.id?"employee-task-row active":"employee-task-row","aria-current":a===e.id?"true":void 0,onClick:()=>s?.(e),children:[t.jsx("strong",{className:"ws-record-title",children:e.title}),t.jsxs("span",{className:"employee-task-row-context ws-meta",children:[e.project?.name||"Project"," · ",e.column?.name||"Column"]}),t.jsxs("span",{className:"employee-task-row-health",children:[t.jsx(tc,{value:e.completedAt?"completed":e.isBlocked?"blocked":e.column?.name}),"high"===e.priority||"urgent"===e.priority?t.jsx(ac,{value:e.priority}):null,t.jsx(nc,{value:e.dueDate})]}),r.length?t.jsx("span",{className:"ws-meta",children:r.join(" · ")}):null,e.isBlocked&&e.blockerReason?t.jsx("span",{className:"employee-task-blocker",children:e.blockerReason}):null]})},e.id)})})}),t.jsx(Sm,{isOpen:Boolean(a&&z),role:"employee",project:W,taskId:a,request:M,endpointPrefix:"/api/workspace/v1/projects",onOpenTask:e=>e?.id&&s?.(e),onClose:()=>{const e=A.current.get(a);r?.(),window.requestAnimationFrame(()=>{if(e?.isConnected)e.focus?.();else{const e=[...A.current.values()].find(e=>e?.isConnected);e?e.focus?.():O.current?.focus?.()}})},onTaskUpdated:e=>{"archived"!==w||e.archivedAt?J(e):Y(e.id)},onTaskArchived:Y,enforceServerCapabilities:!0,renderAssigneesEditor:(e,a)=>B?.project?t.jsx(Em,{project:B.project,task:e,request:M,onSaved:a,endpointPrefix:"/api/workspace/v1/projects"}):null,renderResourcesEditor:(e,a)=>t.jsx(_m,{project:W,task:e,request:M,onSaved:a,endpointPrefix:"/api/workspace/v1/projects"})})]})}function Zm(e){const t=e?.lastMessage?.createdAt||e?.lastMessageAt||e?.updatedAt||e?.createdAt,a=t?new Date(t).getTime():0;return Number.isFinite(a)?a:0}function ep(e=[]){return[...e].sort((e,t)=>
2Zm(t)-Zm(e)||String(e.id).localeCompare(String(t.id)))}function tp(e,t){if(!t?.id)return ep(e);const a=e.find(e=>e.id===t.id);return ep([a?{...a,...t}:t,...e.filter(e=>e.id!==t.id)])}const ap={conversations:[],loading:!0,loadingMore:!1,loadMoreError:null,hasMore:!1,error:null};function np(e,t){const a=new Map(e.map(e=>[e.id,e]));return t.forEach(e=>{a.set(e.id,{...a.get(e.id),...e})}),ep([...a.values()])}function sp(e,t){switch(t.type){case"loading":return{...e,loading:!0,error:null};case"loaded":return{conversations:ep(t.conversations),loading:!1,loadingMore:!1,loadMoreError:null,hasMore:t.hasMore,error:null};case"failed":return{...e,loading:!1,error:t.error};case"loading-more":return{...e,loadingMore:!0,loadMoreError:null};case"loaded-more":return{...e,conversations:np(e.conversations,t.conversations),loadingMore:!1,loadMoreError:null,hasMore:t.hasMore};case"failed-more":return{...e,loadingMore:!1,loadMoreError:t.error};case"cancel-loading-more":return{...e,loadingMore:!1,loadMoreError:null};case"merge":return{...e,conversations:tp(e.conversations,t.conversation)};default:return e}}function rp({value:a=[],onChange:n,excludeIds:s=[],maxSelections:r=Number.POSITIVE_INFINITY,inputRef:i=null,validationError:l=null}){const{makeAuthRequest:o}=Yn(),[c,d]=e.useState(""),[u,h]=e.useState(""),[m,p]=e.useState([]),[f,b]=e.useState(!1),[x,v]=e.useState(null),j=e.useRef(0),y=e.useId(),k=e.useId(),w=e.useId(),N=e.useId(),S=e.useRef(null),C=e.useRef(new Map),R=i||S;e.useEffect(()=>{const e=setTimeout(()=>h(c),300);return()=>clearTimeout(e)},[c]),e.useEffect(()=>{const e=++j.current;let t=!1;return async function(){b(!0),v(null);try{const a=new URLSearchParams({limit:"25"});u&&a.set("search",u);const n=await o(`/api/employee/people?${a.toString()}`);if(t||e!==j.current)return;p(n.data.people||[])}catch(a){if(t||e!==j.current)return;v(a)}finally{t||e!==j.current||b(!1)}}(),()=>{t=!0}},[u,o]);const E=new Set(a.map(e=>e.id)),I=new Set(s),_=a.length>=r,T=_?[]:m.filter(e=>!E.has(e.id)&&!I.has(e.id));return t.jsxs("div",{className:"conversation-picker",children:[t.jsx("label",{htmlFor:N,children:t.jsx("span",{className:"conversation-picker-label",children:1===r?"Recipient":"Participants"})}),t.jsx("input",{ref:R,id:N,type:"search",value:c,onChange:e=>d(e.target.value),placeholder:"Search people by name, title, or department","aria-controls":y,"aria-describedby":[k,l?w:null].filter(Boolean).join(" "),"aria-invalid":l?"true":void 0,autoComplete:"off"}),t.jsx("p",{id:k,className:"conversation-picker-result-count",role:"status",children:f?"Searching people":`${T.length} result${1===T.length?"":"s"} · ${a.length} selected`}),l?t.jsx("p",{id:w,className:"ws-form-field__error",children:l}):null,a.length?t.jsx("ul",{className:"conversation-picker-selected","aria-label":1===r?"Selected recipient":"Selected participants",children:a.map(e=>t.jsxs("li",{children:[t.jsx("span",{children:e.name||"Unnamed"}),t.jsx("button",{ref:t=>{t?C.current.set(e.id,t):C.current.delete(e.id)},type:"button",onClick:()=>((e,t)=>{n(a.filter(t=>t.id!==e.id)),requestAnimationFrame(()=>{const e=a[t+1]||a[t-1];e?C.current.get(e.id)?.focus?.():R.current?.focus?.()})})(e,a.indexOf(e)),"aria-label":`Remove ${e.name||"participant"}`,children:t.jsx(g,{size:14,"aria-hidden":"true"})})]},e.id))}):t.jsx("p",{className:"conversation-picker-empty",children:1===r?"No recipient selected yet.":"No participants selected yet."}),t.jsxs("div",{id:y,className:"conversation-picker-options",children:[f?t.jsx("p",{role:"status","aria-live":"polite",children:"Searching peopleâ¦"}):null,x?t.jsx("p",{role:"alert",children:x.safeMessage||"People could not be loaded."}):null,f||x||T.length||_?null:t.jsx("p",{children:"No matching people."}),_?t.jsx("p",{children:"Selection limit reached."}):null,T.map(e=>t.jsxs("button",{type:"button",onClick:()=>(e=>{E.has(e.id)||_||n([...a,e])})(e),children:[t.jsx("span",{children:e.name||"Unnamed"}
2),t.jsx("small",{children:[e.title,e.department].filter(Boolean).join(" · ")||Sc(e.personnelType)})]},e.id))]})]})}function ip(e){return e?.title||e?.name||e?.originalFilename||"Selected Resource"}function lp({audience:e,resources:a}){return t.jsxs("div",{className:"employee-resource-grant-confirmation",children:[t.jsxs("p",{children:["Some people in ",t.jsx("strong",{children:e})," cannot currently open every selected Resource."]}),t.jsx("p",{children:"Grant viewer access so they can open these Resources from this conversation:"}),t.jsx("ul",{"aria-label":"Resources to share",children:(a||[]).map((e,a)=>t.jsx("li",{children:ip(e)},e?.id||e?.resourceId||`${ip(e)}-${a}`))}),t.jsx("p",{children:"Viewer access permits opening these Resources; it does not grant editing access."})]})}function op(e){return t.jsx(ou,{...e,label:"Attachments (optional)"})}const cp=Object.freeze([{id:"direct",label:"Direct",description:"One person"},{id:"group",label:"Group",description:"Three to 25 people"},{id:"team",label:"Team",description:"A team you belong to"},{id:"project",label:"Project",description:"A project you work on"}]);function dp(e,t){if(!t)return null;const a="team"===e?"Team":"Project";return t.safeMessage||`${a} choices could not be loaded.`}function up({mode:e,options:a,value:n,onChange:s,loading:r,error:i,inputRef:l,invalid:o}){const c="team"===e?"Team":"Project",d=dp(e,i)||(o?`Choose a ${e}.`:null);return t.jsx(rc,{label:c,required:!0,error:d,children:t.jsxs("select",{ref:l,value:n,onChange:e=>s(e.target.value),disabled:r,children:[t.jsx("option",{value:"",children:r?`Loading ${c.toLowerCase()}sâ¦`:`Select a ${c.toLowerCase()}`}),a.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]})})}function hp({isOpen:a,onClose:n,onCreated:s,currentUserId:r}){const{makeAuthRequest:i}=Yn(),l=$s(),[o,c]=e.useState("direct"),[d,u]=e.useState([]),[h,m]=e.useState(""),[p,g]=e.useState(""),[f,b]=e.useState({team:[],project:[]}),[x,v]=e.useState(!1),[j,y]=e.useState(null),[k,w]=e.useState(""),[N,S]=e.useState([]),[C,R]=e.useState(!1),[E,I]=e.useState(null),[_,T]=e.useState(null),A=e.useRef(!1),O=e.useRef(!0),D=e.useRef(null),P=e.useRef(null),L=e.useRef(null),$=e.useRef(null),M=e.useRef(!1),U=e.useId(),F=e.useId();e.useEffect(()=>(O.current=!0,()=>{O.current=!1}),[]),e.useEffect(()=>{!C&&M.current&&(M.current=!1,$.current?.focus?.())},[C]);const z=e.useCallback(()=>{c("direct"),u([]),m(""),g(""),w(""),S([]),I(null),T(null)},[]),q=e.useCallback(()=>{A.current||(z(),n?.())},[n,z]);e.useEffect(()=>{if(!a)return;let e=!1;return async function(){v(!0),y(null);try{const[t,a]=await Promise.all([i("/api/workspace/v1/teams?scope=mine&limit=100"),i("/api/workspace/v1/projects?scope=mine&limit=100")]);if(e)return;b({team:t?.data?.teams||[],project:a?.data?.projects||[]})}catch(t){e||y(t)}finally{e||v(!1)}}(),()=>{e=!0}},[a,i]);const B=(e,t)=>{T(e),requestAnimationFrame(()=>{t?.current?.focus?.(),t?.current?.scrollIntoView?.({block:"center",behavior:"smooth"})})};return a?t.jsx(cc,{isOpen:a,onClose:q,title:"New conversation",description:"Choose the audience first; access is checked again when you create it.",closeLabel:"Close new conversation",className:"conversation-composer-overlay",footer
2:t.jsxs(lc,{children:[t.jsx(ec,{variant:"ghost",onClick:q,disabled:C,children:"Cancel"}),t.jsx(ec,{ref:$,variant:"primary",type:"submit",form:F,disabled:C,children:C?"Startingâ¦":"Start conversation"})]}),children:t.jsxs("form",{id:F,className:"conversation-composer",onSubmit:async e=>{if(e?.preventDefault?.(),!A.current)if("direct"!==o||1===d.length)if("group"===o&&(d.length<2||d.length>24))B("Choose between two and 24 other people.",D);else if(!["team","project"].includes(o)||p)if(k.trim()){T(null),I(null),A.current=!0,R(!0);try{const e={conversationType:o,..."direct"===o?{targetUserId:d[0].id}:{},..."group"===o?{participantUserIds:d.map(e=>e.id),title:h.trim()||null}:{},..."team"===o?{teamId:p}:{},..."project"===o?{projectId:p}:{},initialMessage:k.trim(),resourceIds:N.map(e=>e.id||e.resourceId),resourceRefs:N.map(e=>({resourceId:e.id||e.resourceId,objectId:e.objectId||null,folderId:e.folderId||null}))},n=function(e,t,a,n,s){if("direct"===e)return t[0]?.name||"the selected recipient";if("group"===e){const e=t.map(e=>e.name).filter(Boolean).join(", ");return a.trim()?`the â${a.trim()}â group${e?` (${e})`:""}`:e?`the group with ${e}`:"the selected group"}const r=(s[e]||[]).find(e=>e.id===n);return r?.name?`the ${r.name} ${e}`:`the selected ${e}`}(o,d,h,p,f);let r;try{r=await i("/api/workspace/v1/messages?scope=mine",{method:"POST",body:JSON.stringify(e)})}catch(a){if("MESSAGE_RESOURCE_GRANT_REQUIRED"!==a.code)throw a;if(!(await l({title:"Grant viewer access and send?",message:t.jsx(lp,{audience:n,resources:N}),confirmLabel:"Grant viewer access and send",cancelLabel:"Keep draft",surface:"workspace"}))||!O.current)return void(O.current&&(M.current=!0));r=await i("/api/workspace/v1/messages?scope=mine",{method:"POST",body:JSON.stringify({...e,grantResourceAccess:!0})})}if(!O.current)return;const c=r?.data?.conversation;if(!c?.id)throw new Error("Conversation could not be opened");z(),s?.(c,Boolean(r?.data?.reused))}catch(a){O.current&&I(a)}finally{A.current=!1,O.current&&R(!1)}}else B("Write a first message.",L);else B(dp(o,j)||`Choose a ${o}.`,P);else B("Choose one person to message.",D)},noValidate:!0,children:[_?t.jsx(oc,{type:"error",children:_}):null,t.jsx(ic,{legend:"Conversation type",description:"Each type has its own audience rules.",children:t.jsx("div",{className:"conversation-mode-control",role:"group","aria-label":"Conversation type",children:cp.map(e=>t.jsxs("button",{type:"button",className:o===e.id?"is-active":"","aria-pressed":o===e.id,onClick:()=>{return t=e.id,c(t),u([]),g(""),m(""),void T(null);var t},children:[t.jsx("strong",{children:e.label}),t.jsx("small",{children:e.description})]},e.id))})}),"direct"===o||"group"===o?t.jsx(ic,{legend:"direct"===o?"Recipient":"Participants",description:"direct"===o?"Choose exactly one person.":`Choose 2â24 other people · ${d.length+1} selected including you.`,children:t.jsx("div",{className:"conversation-composer-field--wide",children:t.jsx(rp,{value:d,onChange:e=>{T(null),u(e)},excludeIds:r?[r]:[],maxSelections:"direct"===o?1:24,inputRef:D,validationError:_&&(_.startsWith("Choose one")||_.startsWith("Choose between"))?_:null})})}):t.jsx(ic,{legend:"team"===o?"Team conversation":"Project conversation",description:`Only ${o}s you can naturally message are listed.`,children:t.jsx(up,{mode:o,options:f[o],value:p,onChange:e=>{g(e),T(null)},loading:x,error:j,inputRef:P,invalid:_===`Choose a ${o}.`})}),"group"===o?t.jsx(ic,{legend:"Group identity",description:"Optional. Names are used when blank.",children:t.jsx(rc,{label:"Group title",help:`${h.length}/160 characters`,children:t.jsx("input",{value:h,maxLength:160,onChange:e=>m(e.target.value),placeholder:"Research sprint"})})}):null,t.jsx(ic,{legend:"First message",description:"Give the conversation useful context.",children:t.jsx(rc,{label:"Message",required:!0,error:"Write a first message."===_?_:null,className:"conversation-composer-field--wide",children:t.jsx("textarea",{ref:L,id:U,value:k,onChange:e=>{T(null),w(e.target.value)},placeholder:"Write the first message",rows:4})})}),t.jsx(ic,{legend:"Attachments",description:"Optional resources must be visible to you; each recipient keeps their own access boundary.",children:t.jsx("div",{className:"conversation-composer-field--wide",children:t.jsx(op,{value:N,onChange:S})})}),E?t.jsx(oc,{type:"error",children:E.safeMessage||"The conversation could not be started. Please try again."}):null]})}):null}function mp({isOpen:n,conversation:s,currentUserId:r,onClose:i,onConversationChange:l,onConversationClosed:o}){const{makeAuthRequest:c}=Yn(),d=$s(),[u,h]=e.useState(s?.title||""),[m,p]=e.useState([]),[g,f]=e.useState(null),[b,x]=e.useState(null),v=e.useId(),j=a.useRef(null),y=s?.capabilities||{},k=s?.participants||[];e.useEffect(()=>{h(s?.title||""),p([]),x(null)},[s?.id,s?.title,n]);const w=async(e,t,a,{closesConversation:n=!1}={})=>
2{if(!g){f(e),x(null);try{const e=await c(`${t}?scope=mine`,a);return n?o?.():e?.data?.conversation&&l?.(e.data.conversation),e}catch(s){return x(s),null}finally{f(null)}}};if(!n||!s)return null;const N=`/api/workspace/v1/messages/${s.id}`,S=k.map(e=>e.id),C=Math.max(0,25-k.length);return t.jsx(cc,{isOpen:n,onClose:i,title:"Group information",description:`${k.length} participant${1===k.length?"":"s"} · ${"organizer"===s.participantRole?"You are an organizer":"You are a participant"}`,closeLabel:"Close group information",footer:t.jsx(ec,{variant:"primary",onClick:i,children:"Done"}),children:t.jsxs("div",{className:"employee-group-info",children:[y.canRenameGroup?t.jsxs("form",{id:v,onSubmit:e=>{e.preventDefault(),w("rename",`${N}/group`,{method:"PATCH",body:JSON.stringify({title:u.trim()||null})})},children:[t.jsx(ic,{legend:"Group name",description:"Leave blank to use participant names.",children:t.jsx(rc,{label:"Title",help:`${u.length}/160 characters`,children:t.jsx("input",{value:u,maxLength:160,onChange:e=>h(e.target.value)})})}),t.jsx(lc,{children:t.jsx(ec,{type:"submit",variant:"secondary",disabled:Boolean(g),children:"rename"===g?"Savingâ¦":"Save name"})})]}):null,t.jsx("div",{ref:j,tabIndex:-1,children:t.jsx(ic,{legend:"Participants",description:"Organizers can manage group membership.",children:t.jsx("div",{className:"employee-group-participants",children:k.map(e=>t.jsxs(Qo,{as:"div",className:"employee-group-participant",children:[t.jsxs("div",{children:[t.jsx("strong",{children:e.name||"Unnamed participant"}),t.jsxs("small",{children:["organizer"===e.participantRole?"Organizer":"Participant",e.id===r?" · You":""]})]}),y.canPromoteGroupOrganizer&&"organizer"!==e.participantRole?t.jsxs(ec,{variant:"ghost",size:"compact",disabled:Boolean(g),onClick:()=>{w("promote",`${N}/participants/${e.id}`,{method:"PATCH",body:JSON.stringify({role:"organizer"})})},children:[t.jsx(ot,{size:15,"aria-hidden":"true"})," Promote"]}):null,y.canRemoveGroupParticipants&&e.id!==r?t.jsxs(ec,{variant:"ghost",size:"compact",disabled:Boolean(g),onClick:async()=>{if(!(await d({title:`Remove ${e.name||"participant"}?`,message:"They will immediately lose normal access to this group history.",confirmLabel:"Remove participant",confirmVariant:"danger"})))return;await w("remove",`${N}/participants/${e.id}`,{method:"DELETE"})&&requestAnimationFrame(()=>j.current?.focus())},children:[t.jsx(ct,{size:15,"aria-hidden":"true"})," Remove"]}):null]},e.id))})})}),y.canAddGroupParticipants&&C>0?t.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),!m.length)return;await w("add",`${N}/participants`,{method:"POST",body:JSON.stringify({userIds:m.map(e=>e.id)})})&&p([])},children:[t.jsx(ic,{legend:"Add people",description:`${C} place${1===C?"":"s"} available.`,children:t.jsx(rp,{value:m,onChange:p,excludeIds:S,maxSelections:C})}),t.jsx(lc,{children:t.jsxs(ec,{type:"submit",variant:"secondary",disabled:!m.length||Boolean(g),children:[t.jsx(dt,{size:15,"aria-hidden":"true"}),"add"===g?"Addingâ¦":"Add to group"]})})]}):null,b?t.jsx(oc,{type:"error",children:b.safeMessage||"The group could not be updated. Please try again."}):null,t.jsxs("section",{className:"employee-group-lifecycle","aria-labelledby":`${v}-lifecycle`,children:[t.jsx("h3",{id:`${v}-lifecycle`,children:"Group lifecycle"}),t.jsx("p",{children:"Leaving removes your normal access. Organizers must transfer their final role first."}),t.jsxs("div",{children:[y.canLeaveGroup?t.jsx(ec,{variant:"secondary",disabled:Boolean(g),onClick:async()=>{await d({title:"Leave this group?",message:"You will immediately lose normal access to this group history.",confirmLabel:"Leave group",confirmVariant:"danger"})&&w("leave",`${N}/leave`,{method:"POST",body:JSON.stringify({})},{closesConversation:!0})},children:"leave"===g?"Leavingâ¦":"Leave group"}):null,y.canArchiveGroup?t.jsx(ec,{variant:"danger",disabled:Boolean(g),onClick:async()=>{await d({title:"Archive this group?",message:"The group will close for every participant while its history is retained.",confirmLabel:"Archive group",confirmVariant:"danger"})&&w("archive",`${N}/group`,{method:"DELETE"},{closesConversation:!0}
2)},children:"archive"===g?"Archivingâ¦":"Archive group"}):null]})]})]})})}function pp(e,t){if(!t?.conversation?.id)return e;if(e?.conversation?.id!==t.conversation.id)return t;const a=new Map((e.messages||[]).map(e=>[e.id,e]));for(const n of t.messages||[])a.set(n.id,{...a.get(n.id),...n});return{...e,...t,conversation:{...e.conversation,...t.conversation},messages:[...a.values()].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()||String(e.id).localeCompare(String(t.id)))}}function gp(e,t){const a=new Error(t);return a.code=e,a.safeMessage=t,a}async function fp({requestAccess:e,openWindow:t=(...e)=>window.open(...e),isCurrent:a=()=>!0,allowSameOriginPath:n=!1,loadingTitle:s="Loading protected Resourceâ¦",popupBlockedMessage:r="Allow pop-ups to open this Resource.",unavailableMessage:i="This Resource preview could not be opened safely. Try again."}){if(!a())return!1;let l;try{l=t("","_blank")}catch{l=null}if(!l)throw gp("WORKSPACE_RESOURCE_POPUP_BLOCKED",r);const o=()=>{try{l.close()}catch{}};try{l.opener=null,l.document&&(l.document.title=s)}catch{throw o(),gp("WORKSPACE_RESOURCE_PREVIEW_UNAVAILABLE",i)}try{const t=await e();if(!a())return o(),!1;const s="string"==typeof t?.data?.url?t.data.url.trim():"",r="string"==typeof t?.data?.href?t.data.href.trim():"",c=s||r;let d;try{d=new URL(c,window.location.origin)}catch{throw gp("WORKSPACE_RESOURCE_PREVIEW_UNAVAILABLE",i)}const u=Boolean(s)&&"https:"===d.protocol&&Boolean(d.hostname),h=n&&Boolean(r)&&r.startsWith("/")&&d.origin===window.location.origin;if(!u&&!h||d.username||d.password)throw gp("WORKSPACE_RESOURCE_PREVIEW_UNAVAILABLE",i);if(l.closed)throw gp("WORKSPACE_RESOURCE_PREVIEW_UNAVAILABLE","The Resource preview window was closed before it was ready. Open it again to retry.");return l.location.replace(d.href),!0}catch(c){throw o(),c}}async function bp(e,t,a=(...e)=>window.open(...e),n=()=>!0){try{return await fp({requestAccess:()=>t(`/api/workspace/v1/resource-packs/${encodeURIComponent(e.id)}/objects/${encodeURIComponent(e.objectId)}/access?scope=mine`,{method:"POST",body:JSON.stringify({preview:!0,...e.updateId?{updateId:e.updateId}:{}})}),openWindow:a,isCurrent:n})}catch(s){throw"WORKSPACE_RESOURCE_POPUP_BLOCKED"===s.code?s.code="WORKSPACE_UPDATE_RESOURCE_POPUP_BLOCKED":"WORKSPACE_RESOURCE_PREVIEW_UNAVAILABLE"===s.code&&(s.code="WORKSPACE_UPDATE_RESOURCE_PREVIEW_UNAVAILABLE"),s}}function xp(e){return e?.displayIdentity||{name:e?.title||e?.projectName||e?.teamName||"Direct message",initials:"?",pictureUrl:null,contextLabel:Sc(e?.conversationType,"Conversation")}}function vp(e){if(!e)return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const a=new Date;return t.toDateString()===a.toDateString()?new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(t):new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}).format(t)}function jp(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(t)}function yp(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(t)}function kp(e,t){const a=e[e.length-1];if(!a)return"";const n=a.author?.id===t?"you":a.author?.name||"the Workspace system",s=String(a.body||"").replace(/\s+/g," ").trim(),r=(s.length>80?`${s.slice(0,77).trimEnd()}â¦`:s)||(a.resources?.length?"Sent an attachment.":"Sent a message.");return 1===e.length?`New message from ${n}: ${r}`:`${e.length} new messages. Latest from ${n}: ${r}`}function wp(e,a=""){return t.jsx("span",{className:`employee-message-avatar ${a}`.trim(),"aria-hidden":"true",children:e.pictureUrl?t.jsx("img",{src:e.pictureUrl,alt:""}):e.initials||"?"})}function Np(e,t,a){return`${e}:${t}:${a}`}function Sp({selectedConversationId:n,onOpenConversation:s,onSelectedConversationChange:r}){const{user:i,makeAuthRequest:l}=Yn(),o=$s(),{conversations:c,loading:d,error:u,refresh:h,refreshing:m,backgroundError:p,lastSuccessAt:g,mergeConversation:f,hasMore:b,loadMore:x,loadingMore:v,loadMoreError:j}=function(t){const[a,n]=e.useReducer(sp,ap),s=e.useRef(0),r=e.useRef(0),i=e.useRef(null),l=e.useCallback(async({background:e=!1,signal:a}={})=>{i.current&&(i.current.abort(),i.current=null,n({type:"cancel-loading-more"}));const l=++s.current;e||n({type:"loading"});try{const e=await t("/api/workspace/v1/messages?scope=mine&limit=51&offset=0",{signal:a});if(l!==s.current)return null;const i=e.data.conversations||[];return n({type:"loaded",conversations:i.slice(0,50),hasMore:i.length>50}),r.current=Math.min(i.length,50),e.data}catch(o){if(l!==s.current)return null;throw e||"AbortError"===o?.name||n({type:"failed",error:o}),o}},[t]),o=e.useCallback(async()=>
2{if(!a.hasMore||a.loadingMore)return null;const e=++s.current,l=new AbortController;i.current=l,n({type:"loading-more"});try{const a=await t(`/api/workspace/v1/messages?scope=mine&limit=51&offset=${r.current}`,{signal:l.signal});if(e!==s.current)return null;const i=a.data.conversations||[];return n({type:"loaded-more",conversations:i.slice(0,50),hasMore:i.length>50}),r.current+=Math.min(i.length,50),a.data}catch(o){return e===s.current&&n({type:"failed-more",error:o}),null}finally{i.current===l&&(i.current=null)}},[t,a.hasMore,a.loadingMore]);e.useEffect(()=>()=>{s.current+=1,i.current?.abort(),i.current=null},[]);const c=Gm({refresh:l,intervalMs:3e4}),d=e.useCallback(e=>{n({type:"merge",conversation:e})},[]);return{...a,refresh:c.invalidate,refreshing:c.refreshing,backgroundError:c.backgroundError,lastSuccessAt:c.lastSuccessAt,mergeConversation:d,loadMore:o}}(l),[y,k]=e.useState(null),[w,N]=e.useState(null),[S,C]=e.useState(!1),[R,I]=e.useState(!1),[_,T]=e.useState(null),[A,O]=e.useState(""),[D,P]=e.useState({conversationId:null,marker:null,loading:!1,error:null}),[L,$]=e.useState(0),[M,U]=e.useState(null),[F,z]=e.useState(()=>new Set),[q,B]=e.useState(!1),[W,V]=e.useState(!1),[H,K]=e.useState(!1),[J,Y]=e.useState({conversationId:null,messageId:null}),[Q,X]=e.useState(null),[Z,ee]=e.useState(""),[te,ae]=e.useState(""),ne=Cn(i?.id,n),se=Rn(i?.id,n),re=ne.body,ie=ne.resources,le=Boolean(ne.pending),ce="failure"===se?.status?{safeMessage:se.safeMessage}:null,de=e.useRef(0),ue=e.useRef(0),he=e.useRef(0),me=e.useRef(null),pe=e.useRef(!0),ge=e.useRef(null),fe=e.useRef(null),be=e.useRef(null),xe=e.useRef(null),ve=e.useRef(null),je=e.useRef(!1),ye=e.useRef(null),ke=e.useRef(null),we=e.useRef(new Map),Ne=e.useRef(null),Se=e.useRef(null),Ce=e.useRef(null),Re=e.useRef(n),Ee=e.useRef(null),Ie=e.useRef(null),_e=e.useRef(!1),Te=e.useRef(y),Ae=e.useRef(new Map),Oe=e.useRef(new Set),De=e.useRef(new Map),Pe=e.useRef(null),Le=e.useRef(null),$e=e.useRef(null),Me=y?.conversation?.id===n?y:null;Re.current=n,e.useEffect(()=>(pe.current=!0,()=>{pe.current=!1}),[]),e.useEffect(()=>{Te.current=y},[y]);const Ue=e.useCallback((e,t)=>{const a=t?.[t.length-1];return!(!a?.id||!e||Re.current!==e)&&(Y(t=>t.conversationId===e&&t.messageId===a.id?t:{conversationId:e,messageId:a.id}),!0)},[]),Fe=Gm({refresh:e.useCallback(async({background:e=!1,signal:t}={})=>
2{if(!n)return null;const a=++de.current,s=Ce.current!==n;e||(C(!0),N(null));try{const r=await l(`/api/workspace/v1/messages/${n}?scope=mine`,{signal:t});if(a!==de.current||Re.current!==n||!pe.current)return null;const o=r.data,c=Te.current,d=new Set(c?.conversation?.id===n?(c.messages||[]).map(e=>e.id):[]),u=(o.messages||[]).filter(e=>!d.has(e.id));if(u.length&&e){X({key:`${n}:${u.map(e=>e.id).join(":")}`,text:kp(u,i?.id)});const e=Ee.current;Boolean(e?.dataset.conversationId===n&&e.scrollHeight-e.scrollTop-e.clientHeight<80)?(_e.current=!0,Ue(n,o.messages)):K(!0)}return k(e=>{const t=pp(e,o);return e?.conversation?.id===n&&(e.messages?.length||0)>(o.messages?.length||0)?{...t,pagination:e.pagination}:t}),f(o.conversation),Ce.current=n,s&&(Ue(n,o.messages),K(!1),X(null),_e.current=!0,window.requestAnimationFrame(()=>xe.current?.focus?.())),o}catch(r){if(a!==de.current||Re.current!==n||!pe.current)return null;throw e||"AbortError"===r?.name||(s&&k(null),N(r)),r}finally{a===de.current&&Re.current===n&&pe.current&&!e&&C(!1)}},[Ue,l,f,n,i?.id]),enabled:Boolean(n),intervalMs:15e3}),ze=Boolean(p&&c.length),qe=Boolean(Fe.backgroundError&&Me),Be=n||"conversation-list";e.useEffect(()=>{if(ze||qe)return $e.current=Be,void ae("");$e.current===Be&&ae("Message updates are current again."),$e.current=null},[qe,ze,Be]),e.useEffect(()=>{ee("")},[n]),e.useEffect(()=>{const e=ke.current;!le&&e&&(ke.current=null,n===e&&ye.current?.focus?.())},[n,le]),e.useEffect(()=>{"success"===se?.status&&n&&(se.data?.conversation?.id===n&&(_e.current=!0,Ue(n,se.data.messages),k(e=>{const t=pp(e,se.data);return e?.conversation?.id===n&&(e.messages?.length||0)>(se.data.messages?.length||0)?{...t,pagination:e.pagination}:t}),f(se.data.conversation),ee("Message sent")),function(e,t,a){const n=fn(e,t);if(!n)return!1;const s=gn(),r=s.sendOutcomes.get(n);!r||a&&r.token!==a||(s.sendOutcomes.delete(n),kn(n,s))}(i?.id,n,se.token))},[Ue,f,n,se,i?.id]);const Ve=J.conversationId===n?J.messageId:null;e.useEffect(()=>{if(U(null),Le.current=null,V(!1),X(null),he.current+=1,me.current?.abort(),me.current=null,I(!1),T(null),O(""),Y({conversationId:n||null,messageId:null}),n)return;de.current+=1,Ce.current=null,k(null),N(null),C(!1),K(!1),V(!1);const e=Se.current;Se.current=null,e&&window.requestAnimationFrame(()=>{const t=we.current.get(e)||fe.current;t?.focus?.()})},[n]),e.useEffect(()=>()=>{he.current+=1,me.current?.abort()},[]),e.useEffect(()=>{if(!Me?.conversation?.id||!Ve)return;const e=Me.conversation.id,t=++ue.current;return P(t=>{const a=t.conversationId===e&&t.marker===Ve;return{conversationId:e,marker:Ve,loading:!0,error:a?t.error:null}}),(async()=>{try{const a=await l(`/api/workspace/v1/messages/${e}/read?scope=mine`,{method:"POST",body:JSON.stringify({visibleMessageId:Ve})});if(t!==ue.current||Re.current!==e||!pe.current)return;Ae.current.get(e)!==Ve&&(Ae.current.set(e,Ve),function(e){"undefined"==typeof window||"string"!=typeof e||!e.trim()||window.dispatchEvent(new CustomEvent(Rr,{detail:{conversationId:e}}))}(e)),f(a.data.conversation),P({conversationId:e,marker:Ve,loading:!1,error:null}),je.current&&(je.current=!1,window.requestAnimationFrame(()=>xe.current?.focus?.()))}catch(a){if(t!==ue.current||Re.current!==e||!pe.current)return;P({conversationId:e,marker:Ve,loading:!1,error:a}),je.current&&(je.current=!1,window.requestAnimationFrame(()=>ve.current?.focus?.()))}})(),()=>{ue.current===t&&(ue.current+=1)}},[Ve,l,f,L,Me?.conversation?.id]);const He=()=>{const e=Ne.current||n;Se.current=e,r?.(null)},Ke=async(e,t)=>{const a=Me?.conversation?.id;if(!a||a!==n)return;const s=Np(a,e.id,t.id);if(!Oe.current.has(s)){Oe.current.add(s),z(e=>new Set(e).add(s)),U(e=>e?.accessKey===s?e:null);try{if(await fp({requestAccess:()=>l(`/api/workspace/v1/messages/${a}/messages/${e.id}/resources/${t.id}/access?scope=mine`,{method:"POST",body:JSON.stringify({})}),isCurrent:()=>Re.current===a&&pe.current,allowSameOriginPath:!0,loadingTitle:`Opening ${t.title||"attachment"}â¦`,popupBlockedMessage:"Allow pop-ups to open this attachment.",unavailableMessage:"This attachment could not be opened because no s
2afe destination was provided. Please try again."}),Re.current!==a||!pe.current)return;U(e=>e?.accessKey===s?null:e),Le.current===s&&(Le.current=null,window.requestAnimationFrame(()=>De.current.get(s)?.focus?.({preventScroll:!0})))}catch(r){if(Re.current!==a||!pe.current)return;U({accessKey:s,messageId:e.id,resource:t,requestError:r}),Le.current===s&&(Le.current=null,window.requestAnimationFrame(()=>Pe.current?.focus?.({preventScroll:!0})))}finally{Oe.current.delete(s),pe.current&&z(e=>{if(!e.has(s))return e;const t=new Set(e);return t.delete(s),t})}}},Ge=async()=>{const e=n,t=i?.id;if(!e||!re.length&&!ie.length)return;const a=ne.pending?.token||null,s=Boolean(a);await o({title:s?"Discard the next draft?":"Discard this draft?",message:s?"Your next-message text and selected Resources will be removed. The message already sending will continue.":"Your unsent text and selected Resources will be removed.",confirmLabel:s?"Discard next draft":"Discard draft",cancelLabel:"Keep draft",confirmVariant:"danger",surface:"workspace"})&&function(e,t,a={}){const n=fn(e,t);if(!n)return!1;const s=gn(),r=Nn(n,s);Object.prototype.hasOwnProperty.call(a,"expectedPendingToken")&&(r.pending?.token||null)!==a.expectedPendingToken||("failure"===s.sendOutcomes.get(n)?.status&&s.sendOutcomes.delete(n),wn(n,{...r,body:"",resources:[]},s))}(t,e,{expectedPendingToken:a})},Je=e.useCallback(()=>B(!1),[]),Ye=e.useCallback(e=>{B(!1),f(e),h({background:!0}),Ne.current=e.id,s?.(e),r?.(e.id)},[h,f,s,r]),Qe=e.useMemo(()=>{let e=null,t=null;return(Me?.messages||[]).map(a=>{const n=function(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return{key:"unknown",label:"Messages"};const a=new Date,n=new Date;n.setDate(a.getDate()-1);const s=t.toDateString()===a.toDateString()?"Today":t.toDateString()===n.toDateString()?"Yesterday":new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(t);return{key:t.toDateString(),label:s}}(a.createdAt),s=a.author?.id?a.author.id===i?.id?"sent":"received":"system",r=e?new Date(e.createdAt).getTime():0,l=new Date(a.createdAt).getTime(),o=Boolean(e&&t===n.key&&e.author?.id===a.author?.id&&l-r<3e5),c=t!==n.key;return e=a,t=n.key,{message:a,day:n,direction:s,grouped:o,showDay:c}})},[Me?.messages,i?.id]);e.useEffect(()=>{_e.current&&Ee.current&&(_e.current=!1,Ee.current.scrollTop=Ee.current.scrollHeight,K(!1))},[Me?.messages?.length]);const Xe=xp(Me?.conversation),Ze=Boolean(n),et=j?"Retry loading more":v?"Loading moreâ¦":"Load more conversations",tt=_?"Retry loading earlier messages":R?"Loading earlierâ¦":"Load earlier messages",at=ze&&qe?"Conversation list and this thread may be out of date.":ze?"Conversation list may be out of date.":qe?"This thread may be out of date.":"",nt=[ze?g:null,qe?Fe.lastSuccessAt:null].filter(e=>Number.isFinite(e)),st=nt.length?Math.min(...nt):null,rt=ze&&m||qe&&Fe.refreshing;return t.jsxs("section",{className:"employee-messages-panel"+(Ze?" is-thread-open":""),"aria-label":"Conversations",children:[t.jsxs("div",{className:"employee-messages-sync-region",children:[at?t.jsxs(oc,{type:"warning",className:"employee-messages-sync-warning",children:[t.jsxs("span",{className:"employee-messages-sync-copy",children:[t.jsx("span",{children:at}),st?t.jsxs("time",{dateTime:new Date(st).toISOString(),children:["Last successful update: ",yp(st),"."]}):null]}),t.jsx(ec,{type:"button",variant:"secondary",size:"compact",disabled:rt,"aria-busy":rt?"true":void 0,onClick:()=>{(()=>{const e=[];ze&&e.push(h({background:!0,reason:"retry"})),qe&&e.push(Fe.invalidate({background:!0,reason:"retry"})),Promise.all(e)})()},children:rt?"Retrying message updatesâ¦":"Retry message updates"})]}):null,t.jsx("span",{className:"employee-visually-hidden",role:"status","aria-live":"polite","aria-atomic":"true",children:te})]}),t.jsxs("div",{className:"employee-messages-list",children:[t.jsxs("div",{className:"employee-messages-list-header",children:[t.jsxs("div",{children:[t.jsx("span",{className:"ws-micro",children:"Workspace"}),t.jsx("h2",{ref:fe,tabIndex:-1,className:"employee-messages-list-title",children:"Messages"})]}),t.jsxs(ec,{ref:ge,variant:"primary",onClick:()=>B(!0),className:"employee-new-conversation",children:[t.jsx(E,{size:16,"aria-hidden":"true"})," New conversation"]})]}),t.jsxs(bc,{loading:d&&!c.length,error:u,isEmpty:!c.length,loadingLabel:"Loading conversationsâ¦",errorLabel:"Conversations could not be loaded",emptyLabel:"No conversations yet.",emptyDescription:"Start one with the New conversation button.",onRetry:()=>h(),children:[t.jsx("ul",{className:"employee-conversation-list",children:c.map(e=>{const a=xp(e),i=n===e.id;return t.jsx("li",{children:t.jsxs("button",{ref:t=>{t?we.current.set(e.id,t):we.current.delete(e.id)},type:"button",className:i?"active":"","aria-current":i?"true":void 0,onClick:()=>(e=>{Ne.current=e.id,s?.(e),r?.(e.id)})(e),children:[wp(a),t.jsxs("span",{className:"employee-conversation-copy",children:[t.jsxs("span",{className:"employee-conversation-heading",children:[t.jsx("strong",{children:a.name}),t.jsx("time",{dateTime:e.lastMessageAt||void 0,children:vp(e.lastMessageAt)}
2)]}),t.jsx("span",{className:"employee-conversation-preview",children:e.lastMessage?.preview||a.contextLabel})]}),e.unreadCount?t.jsxs("small",{className:"employee-conversation-unread","aria-label":`${e.unreadCount} unread messages`,children:[e.unreadCount,t.jsx("span",{className:"employee-conversation-unread-label",children:" unread"})]}):null]})},e.id)})}),j?t.jsx(oc,{type:"error",children:"More conversations could not be loaded."}):null,b||j?t.jsx(ec,{ref:be,variant:"ghost",disabled:v,"aria-busy":v?"true":void 0,onClick:()=>{(async()=>{const e="undefined"!=typeof document&&document.activeElement===be.current,t=new Set(c.map(e=>e.id)),a=await x();if(!e)return;const n=a?.conversations||[],s=n.slice(0,50).find(e=>!t.has(e.id)),r=n.length>50;window.requestAnimationFrame(()=>{let e=be.current||fe.current;a&&!r&&(e=we.current.get(s?.id)||fe.current),e?.focus?.({preventScroll:!0})})})()},children:et}):null]})]}),t.jsxs("div",{className:"employee-messages-thread",children:[n?t.jsxs("div",{className:"employee-thread-header",children:[t.jsxs(ec,{variant:"ghost",onClick:He,className:"employee-thread-back",children:[t.jsx(G,{size:16,"aria-hidden":"true"})," Back"]}),Me?wp(Xe,"employee-thread-avatar"):null,t.jsxs("div",{children:[t.jsx("h2",{ref:xe,tabIndex:-1,children:Me?Xe.name:"Conversation"}),t.jsx("span",{children:Me?Xe.contextLabel:"Loading conversation"})]}),"group"===Me?.conversation?.conversationType?t.jsx(ec,{variant:"ghost",iconOnly:!0,className:"employee-thread-info","aria-label":"Open group information",onClick:()=>V(!0),children:t.jsx(ut,{size:20,"aria-hidden":"true"})}):null]}):null,n?t.jsx(bc,{loading:S&&!Me,error:w,loadingLabel:"Loading conversationâ¦",errorLabel:"This conversation could not be opened",onRetry:()=>Fe.invalidate({background:!1,reason:"retry"}),children:Me?t.jsxs("div",{className:"employee-thread-body",children:[D.error&&D.conversationId===Me.conversation.id&&D.marker===Ve?t.jsxs(oc,{type:"error",className:"employee-message-read-error",children:[t.jsxs("span",{children:["This conversation is still marked unread because its read status could not be saved.",D.error.safeMessage?` ${D.error.safeMessage}`:""]}),t.jsx(ec,{ref:ve,type:"button",variant:"ghost",size:"compact",disabled:D.loading,"aria-busy":D.loading?"true":void 0,onClick:()=>{je.current=document.activeElement===ve.current,$(e=>e+1)},children:D.loading?"Retrying read statusâ¦":"Retry read status"})]}):null,t.jsxs("div",{className:"employee-message-history-region",children:[t.jsxs("ol",{ref:Ee,className:"employee-message-history","aria-label":"Message history","data-conversation-id":n,tabIndex:0,onScroll:e=>{const t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<80&&(Ue(n,Te.current?.messages),K(!1))},children:[Me.pagination?.hasMore||_?t.jsxs("li",{className:"employee-message-history-pagination",children:[_?t.jsx(oc,{type:"error",children:"Earlier messages could not be loaded."}):null,t.jsx(ec,{ref:Ie,variant:"ghost",size:"compact",disabled:R,"aria-busy":R?"true":void 0,onClick:()=>{(async()=>{const e=Me?.conversation?.id,t=Me?.pagination?.beforeCursor;if(!e||!t||R)return;const a=++he.current,n=new AbortController;me.current?.abort(),me.current=n;const s=Ee.current,r=s?.scrollHeight||0,i=s?.scrollTop||0,o="undefined"!=typeof document&&document.activeElement===Ie.current;I(!0),T(null),O("Loading earlier messagesâ¦");try{const s=await l(`/api/workspace/v1/messages/${e}?scope=mine&limit=50&beforeCursor=${encodeURIComponent(t)}`,{signal:n.signal});if(n.signal.aborted||a!==he.current||Re.current!==e)return;const c=s.data,d=(c.messages||[]).filter(e=>!(Me.messages||[]).some(t=>t.id===e.id)).length;k(e=>({...pp(e,c),pagination:c.pagination})),O(d?`${d} earlier message${1===d?"":"s"} loaded.`:"No earlier messages remain."),window.requestAnimationFrame(()=>{if(Ee.current&&Re.current===e&&(Ee.current.scrollTop=i+(Ee.current.scrollHeight-r),o)){const e=c.pagination?.hasMore?Ie.current:Ee.current;e?.focus?.({preventScroll:!0})}})}catch(c){n.signal.aborted||a!==he.current||(T(c),O("Earlier messages could not be loaded."),o&&window.requestAnimationFrame(()=>Ie.current?.focus?.({preventScroll:!0})))}finally{a===he.current&&(I(!1),me.current===n&&(me.current=null))}})()},children:tt})]}):null,Qe.map(({message:e,day:n,direction:s,grouped:r,showDay:i})=>t.jsxs(a.Fragment,{children:[i?t.jsx("li",{className:"employee-message-day","aria-label":n.label,children:t.jsx("span",{children:n.label})}):null,t.jsx("li",{className:`employee-message-${s}${r?" is-grouped":""}`,children:t.jsxs("article",{className:"employee-message-bubble",children:[r?t.jsxs("span",{className:"employee-visually-hidden",children:["sent"===s?"You"
2:e.author?.name||"Workspace system",", ","system"===s?"system message":s]}):t.jsxs("header",{className:"employee-message-author",children:[t.jsx("strong",{children:"sent"===s?"You":e.author?.name||"Workspace system"}),"received"===s?t.jsx("span",{className:"employee-visually-hidden",children:"received"}):null,t.jsx("time",{dateTime:e.createdAt,children:jp(e.createdAt)})]}),t.jsx(wd,{text:e.body}),e.resources?.length?t.jsx("div",{className:"employee-message-resources",children:e.resources.map(a=>{const n=Np(Me.conversation.id,e.id,a.id),s=F.has(n);return t.jsxs("button",{ref:e=>{e?De.current.set(n,e):De.current.delete(n)},type:"button",disabled:s,"aria-busy":s?"true":void 0,onClick:()=>Ke(e,a),children:[t.jsxs("span",{children:[s?`Opening ${a.title||"attachment"}â¦`:a.title,t.jsxs("small",{children:[a.originalFilename," ·"," ",Sc(a.resourceKind)," ·"," ",Nc(a.sizeBytes)]})]}),t.jsx(We,{size:14,"aria-hidden":"true"})]},a.id)})}):null,M?.messageId===e.id?t.jsxs(oc,{type:"error",className:"employee-message-resource-error",children:[M.requestError?.safeMessage||"This attachment could not be opened. Please try again."," ",t.jsx(ec,{ref:Pe,variant:"ghost",size:"compact",disabled:F.has(M.accessKey),"aria-busy":F.has(M.accessKey)?"true":void 0,onClick:()=>{Le.current=M.accessKey,Ke(e,M.resource)},children:F.has(M.accessKey)?"Retrying attachmentâ¦":"Retry opening attachment"})]}):null,r?t.jsx("time",{className:"employee-message-group-time",dateTime:e.createdAt,children:jp(e.createdAt)}):null]})})]},e.id)),Qe.length?null:t.jsx("li",{className:"employee-message-empty",children:"No messages yet."})]}),H?t.jsx(ec,{variant:"secondary",size:"compact",className:"employee-message-new-indicator",onClick:e=>{const t=Ee.current;if(!t)return;const a=0===e?.detail&&document.activeElement===e.currentTarget;t.scrollTop=t.scrollHeight,Ue(n,Te.current?.messages),a&&t.focus({preventScroll:!0}),K(!1)},children:"New messages"}):null]}),t.jsx("span",{className:"employee-visually-hidden",role:"status","aria-live":"polite","aria-atomic":"true",children:A}),t.jsx("span",{className:"employee-visually-hidden",role:"status","aria-live":"polite","aria-atomic":"true",children:Q?t.jsx("span",{children:Q.text},Q.key):null}),t.jsxs("form",{className:"employee-messages-reply",onSubmit:async e=>{e?.preventDefault?.();const a=Me?.conversation?.id;if(!a||a!==n)return;const s=function(e,t){const a=fn(e,t);if(!a)return null;const n=gn(),s=Nn(a,n);if(s.pending||!s.body.trim())return null;pn+=1;const r=`${Date.now().toString(36)}-${pn.toString(36)}`;return n.activeSendTokens.add(r),n.sendOutcomes.delete(a),wn(a,{body:"",resources:[],pending:{token:r,body:s.body,resources:s.resources}},n),{token:r,body:s.body,resources:s.resources}}(i?.id,a);if(!s)return;ee("");const r=s.body,c=s.resources;try{const e={body:r,resourceIds:c.map(e=>e.id||e.resourceId),resourceRefs:c.map(e=>({resourceId:e.id||e.resourceId,objectId:e.objectId||null,folderId:e.folderId||null}))};let n;try{n=await l(`/api/workspace/v1/messages/${a}/messages?scope=mine`,{method:"POST",body:JSON.stringify(e)})}catch(d){if("MESSAGE_RESOURCE_GRANT_REQUIRED"!==d.code||Re.current!==a||!pe.current)throw d;const r=xp(Me.conversation);if(!(await o({title:"Grant viewer access and send?",message:t.jsx(lp,{audience:`the â${r.name}â conversation`,resources:c}),confirmLabel:"Grant viewer access and send",cancelLabel:"Keep draft",surface:"workspace"}))||Re.current!==a||!pe.current)return function(e,t,a){const n=gn();n.activeSendTokens.delete(a);const s=fn(e,t);if(!s)return!1;const r=Nn(s,n);r.pending?.token===a&&(n.sendOutcomes.delete(s),wn(s,{body:jn(r.pending.body,r.body),resources:vn(r.pending.resources,r.resources),pending:null},n))}(i?.id,a,s.token),void(pe.current&&(ke.current=a));n=await l(`/api/workspace/v1/messages/${a}/messages?scope=mine`,{method:"POST",body:JSON.stringify({...e,grantResourceAccess:!0})})}!function(e,t,a,n){const s=gn();s.activeSendTokens.delete(a);const r=fn(e,t);if(!r)return!1;const i=Nn(r,s);i.pending?.token===a&&(wn(r,{...i,pending:null},s),s.sendOutcomes.set(r,{status:"success",token:a,data:n}),kn(r,s))}(i?.id,a,s.token,n.data)}catch(d){!function(e,t,a,n){const s=gn();s.activeSendTokens.delete(a);const r=fn(e,t);if(!r)return!1;const i=Nn(r,s);if(i.pending?.token!==a)return!1;wn(r,{body:jn(i.pending.body,i.body),resources:vn(i.pending.resources,i.resources),pending:null},s);
2const l="string"==typeof n?.safeMessage?n.safeMessage.trim().slice(0,500):"";s.sendOutcomes.set(r,{status:"failure",token:a,safeMessage:l}),kn(r,s)}(i?.id,a,s.token,d)}},children:[t.jsx("span",{className:"employee-visually-hidden",role:"status","aria-live":"polite","aria-atomic":"true",children:le?"Sending messageâ¦":Z}),t.jsx("label",{htmlFor:"employee-message-draft",className:"employee-visually-hidden",children:"Message"}),t.jsx("textarea",{id:"employee-message-draft",value:re,onChange:e=>En(i?.id,n,{body:e.target.value}),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||e.nativeEvent.isComposing||"undefined"!=typeof window&&(window.innerWidth<=767||"function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches)||(e.preventDefault(),e.currentTarget.form?.requestSubmit())},placeholder:"Write a reply",rows:2}),t.jsxs("div",{className:"employee-messages-reply-scroll",children:[t.jsxs("div",{className:"employee-messages-composer-tools",children:[t.jsx(op,{value:ie,onChange:e=>En(i?.id,n,{resources:e}),collapsible:!0}),t.jsx("span",{className:"employee-message-key-hint employee-message-key-hint--desktop",children:"Enter to send · Shift+Enter for line"}),t.jsx("span",{className:"employee-message-key-hint employee-message-key-hint--mobile",children:"Enter for a new line · Use Send to send"})]}),ce?t.jsx(oc,{type:"error",children:ce.safeMessage||"That message could not be sent. Please try again."}):null]}),t.jsxs("div",{className:"employee-message-composer-actions",children:[re.length||ie.length?t.jsx(ec,{variant:"ghost",type:"button",onClick:()=>{Ge()},children:le?"Discard next draft":"Discard draft"}):null,t.jsxs(ec,{ref:ye,variant:"primary",type:"submit",disabled:!re.trim()||le,children:[t.jsx(oe,{size:16,"aria-hidden":"true"})," ",le?"Sendingâ¦":"Send"]})]})]})]}):null}):t.jsx(bc,{isEmpty:!0,emptyLabel:"No conversation selected",emptyDescription:"Choose a conversation from the list, or start a new one."})]}),t.jsx(hp,{isOpen:q,onClose:Je,onCreated:Ye,currentUserId:i?.id}),t.jsx(mp,{isOpen:W&&Boolean(Me),conversation:Me?.conversation,currentUserId:i?.id,onClose:()=>V(!1),onConversationChange:e=>{k(t=>t?{...t,conversation:{...t.conversation,...e}}:t),f(e)},onConversationClosed:()=>{V(!1),h({background:!0}),He()}})]})}const Cp="/api/workspace/v1/messages/oversight";function Rp(e){return e?.displayIdentity?.name||e?.title||e?.projectName||e?.teamName||"Direct conversation"}function Ep(e){const t=(e?.participants||[]).map(e=>e.name).filter(Boolean);return t.length?t.join(", "):"Participants unavailable"}function Ip(e){const t=(e?.participants||[]).map(e=>e.name).filter(Boolean);return t.length?t.length<=2?t.join(", "):`${t.slice(0,2).join(", ")} +${t.length-2}`:"Participants unavailable"}function _p(e){if(!e?.recordedAt)return"This access is recorded in the privacy audit.";const t=new Date(e.recordedAt);return`Privacy audit recorded ${Number.isNaN(t.getTime())?"now":t.toLocaleString()}.`}function Tp(e){if(!e)return"Time unavailable";const t=new Date(e);return Number.isNaN(t.getTime())?"Time unavailable":new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(t)}function Ap({selectedConversationId:n,onOpenConversation:s,onSelectedConversationChange:r}){const{makeAuthRequest:i}=Yn(),[l,o]=e.useState([]),[c,d]=e.useState(null),[u,h]=e.useState(!0),[m,p]=e.useState(null),[g,f]=e.useState(0),[b,x]=e.useState(!1),[v,j]=e.useState(!1),[y,k]=e.useState(null),[w,N]=e.useState(null),[S,C]=e.useState(!1),[R,E]=e.useState(null),[I,_]=e.useState(0),[T,A]=e.useState(!1),[O,D]=e.useState(null),[P,L]=e.useState(""),$=e.useRef(null),M=e.useRef(null),U=e.useRef(null),F=e.useRef(new Map),z=e.useRef(null),q=e.useRef(null),B=e.useRef(0),W=e.useRef(null),V=e.useRef(null),H=e.useRef(null),K=e.useRef(0),J=e.useRef(null),Y=e.useMemo(()=>{const e=new URLSearchParams({scope:"all",limit:String(50),offset:"0"});return`${Cp}?${e.toString()}`},[]),X=e.useMemo(()=>{let e=null;return(w?.messages||[]).map(t=>{const a=function(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return{key:"unknown",label:"Messages"};const a=new Date,n=new Date;n.setDate(a.getDate()-1);const s=t.toDateString()===a.toDateString()?"Today":t.toDateString()===n.toDateString()?"Yesterday":new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(t);return{key:t.toDateString(),label:s}}(t.createdAt),n=e!==a.key;return e=a.key,{message:t,day:a,showDay:n}})},[w?.messages]);e.useEffect(()=>{const e=++B.current,t=new AbortController;return W.current?.abort(),h(!0),p(null),j(!1),k(null),(async()=>{try{const a=await i(Y,{signal:t.signal});if(t.signal.aborted||e!==B.current)return;const n=a.data?.conversations||[];o(n),x(!0===a.data?.pagination?.hasMore),d(a.data?.audit||null)}catch(a){t.signal.aborted||e!==B.current||(o([]),x(!1),d(null),p(a))}finally{t.signal.aborted||e!==B.current||h(!1)}})(),()=>{t.abort(),W.current?.abort()}},[g,Y,i]);e.useEffect(()=>{if(K.current+=1,J.current?.abort(),J.current=null,A(!1),D(null),L(""),!n)return N(null),E(null),void C(!1);const e=new AbortController;return N(null),E(null),C(!0),(async()=>{try{const t=await i(`${Cp}/${n}?scope=all&limit=50`,{signal:e.signal});e.signal.aborted||(N(t.data),D(null),L(""))}catch(t){e.signal.aborted||E(t)}
2finally{e.signal.aborted||C(!1)}})(),()=>{e.abort(),K.current+=1,J.current?.abort(),J.current=null}},[I,i,n]),e.useEffect(()=>{if(n){if(w?.conversation?.id!==n)return;return void window.requestAnimationFrame(()=>U.current?.focus?.())}const e=q.current;q.current=null,e&&window.requestAnimationFrame(()=>{const t=F.current.get(e)||$.current;t?.focus?.()})},[w?.conversation?.id,n]);const Z=y?"Retry loading more":v?"Loading moreâ¦":"Load more conversations",ee=O?"Retry loading earlier messages":T?"Loading earlierâ¦":"Load earlier messages";return t.jsxs("section",{className:"employee-messages-panel employee-message-oversight"+(n?" is-thread-open":""),"aria-label":"Conversation oversight",children:[t.jsxs(Xo,{className:"employee-oversight-notice",role:"status",children:[t.jsx(Q,{size:20,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:"Audited oversight · read-only"}),t.jsx("p",{children:"Private conversation views are recorded. This mode cannot reply, mark messages read, impersonate a participant, or open attachments."})]})]}),t.jsxs("div",{className:"employee-messages-list",children:[t.jsx("div",{className:"employee-messages-list-header employee-oversight-list-header",children:t.jsx("h2",{ref:$,tabIndex:-1,className:"employee-oversight-list-title",children:"Workspace conversations"})}),c?t.jsx("p",{className:"employee-oversight-audit",children:_p(c)}):null,t.jsxs(bc,{loading:u&&!l.length,error:m,isEmpty:!u&&!l.length,loadingLabel:"Loading audited conversationsâ¦",errorLabel:"Conversation oversight could not be loaded",emptyLabel:"No conversations found.",onRetry:()=>f(e=>e+1),children:[t.jsx("ul",{className:"employee-conversation-list",children:l.map(e=>t.jsx("li",{children:t.jsxs("button",{ref:t=>{t?F.current.set(e.id,t):F.current.delete(e.id)},type:"button",className:n===e.id?"active":"","aria-current":n===e.id?"true":void 0,onClick:()=>(e=>{z.current=e.id,s?.(e),r?.(e.id)})(e),children:[t.jsxs("span",{className:"employee-oversight-conversation-copy",children:[t.jsx("strong",{children:Rp(e)}),t.jsx("span",{className:"employee-oversight-participant-summary","aria-hidden":"true",children:Ip(e)}),t.jsxs("span",{className:"sr-only",children:["Participants: ",Ep(e)]})]}),t.jsx("small",{children:Vo(e.conversationType,"Conversation")})]})},e.id))}),y?t.jsx(oc,{type:"error",children:"More audited conversations could not be loaded."}):null,b||y?t.jsx(ec,{ref:M,variant:"ghost",disabled:v,"aria-busy":v?"true":void 0,onClick:()=>{(async()=>{if(v)return;const e="undefined"!=typeof document&&document.activeElement===M.current,t=B.current,a=l.length,n=new Set(l.map(e=>e.id)),s=new AbortController;W.current?.abort(),W.current=s,j(!0),k(null);const r=new URLSearchParams({scope:"all",limit:String(50),offset:String(a)});try{const l=await i(`${Cp}?${r.toString()}`,{signal:s.signal});if(s.signal.aborted||t!==B.current)return;const c=l.data?.conversations||[],u=c.find(e=>!n.has(e.id)),h=!0===l.data?.pagination?.hasMore;o(e=>{if(e.length!==a)return e;const t=new Set(e.map(e=>e.id));return[...e,...c.filter(e=>!t.has(e.id))]}),x(h),d(l.data?.audit||null),e&&window.requestAnimationFrame(()=>{const e=h?M.current:F.current.get(u?.id)||$.current;e?.focus?.({preventScroll:!0})})}catch(c){s.signal.aborted||t!==B.current||(k(c),e&&window.requestAnimationFrame(()=>M.current?.focus?.({preventScroll:!0})))}finally{s.signal.aborted||t!==B.current||j(!1)}})()},children:Z}):null]})]}),t.jsxs("div",{className:"employee-messages-thread",children:[n?t.jsxs("div",{className:"employee-thread-header",children:[t.jsxs(ec,{variant:"ghost",onClick:()=>{q.current=z.current||n,z.current=null,r?.(null)},className:"employee-thread-back",children:[t.jsx(G,{size:16,"aria-hidden":"true"})," Back to conversations"]}),t.jsx("div",{children:t.jsx("h2",{ref:U,tabIndex:-1,children:w?Rp(w.conversation):"Audited conversation"})})]}):null,n?t.jsx(bc,{loading:S,error:R,loadingLabel:"Recording access and loading conversationâ¦",errorLabel:"This conversation could not be opened",onRetry:()=>_(e=>e+1),children:w?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"employee-oversight-detail-context",children:[t.jsx("strong",{children:Ep(w.conversation)}),t.jsx("span",{children:_p(w.audit)})]}),t.jsxs("ol",{ref:V,className:"employee-message-history","aria-label":"Audited message history",tabIndex:0,children:[w.pagination?.hasMore||O?t.jsxs("li",{className:"employee-message-history-pagination",children:[O?t.jsx(oc,{type:"error",children:"Earlier audited messages could not be loaded."}):null,t.jsx(ec,{ref:H,variant:"ghost",size:"compact",disabled:T,"aria-busy":T?"true":void 0,onClick:()=>{(async()=>{const e=w?.conversation?.id,t=w?.pagination?.beforeCursor;if(!e||!t||T)return;const a=++K.current,s=new AbortController;J.current?.abort(),J.current=s;const r=V.current,l=r?.scrollHeight||0,o=r?.scrollTop||0,c="undefined"!=typeof document&&document.activeElement===H.current;A(!0),D(null),L("Loading earlier audited messagesâ¦");const d=()=>!s.signal.aborted&&a===K.current;try{const a=await i(`${Cp}/${e}?scope=all&limit=50&beforeCursor=${encodeURIComponent(t)}`,{signal:s.signal});if(!d()||n!==e)return;const r=a.data,u=new Set((w.messages||[]).map(e=>e.id)),h=(r.messages||[]).filter(e=>!u.has(e.id));N(e=>({...e,...r,conversation:{...e.conversation,...r.conversation},messages:[...h,...e.messages||[]],pagination:r.pagination})),L(h.length?`${h.length} earlier audited message${1===h.length?"":"s"} loaded.`:"No earlier audited messages remain."),window.requestAnimationFrame(()=>{if(d()&&V.current&&(V.current.scrollTop=o+(V.current.scrollHeight-l),c)){const e=r.pagination?.hasMore?H.current:V.current;e?.focus?.({preventScroll:!0})}})}catch(u){d()&&(D(u),L("Earlier audited messages could not be loaded."),c&&window.requestAnimationFrame(()=>{d()&&H.current?.focus?.({preventScroll:!0})}
2))}finally{a===K.current&&(A(!1),J.current===s&&(J.current=null))}})()},children:ee})]}):null,X.map(({message:e,day:n,showDay:s})=>t.jsxs(a.Fragment,{children:[s?t.jsx("li",{className:"employee-message-day","aria-label":n.label,children:t.jsx("span",{children:n.label})}):null,t.jsx("li",{className:"employee-message-audit",children:t.jsxs(Qo,{as:"article",children:[t.jsxs("header",{className:"employee-message-author",children:[t.jsx("strong",{children:e.author?.name||"Unknown"}),t.jsx("span",{className:"employee-oversight-message-meta",children:t.jsx("time",{dateTime:e.createdAt||void 0,children:Tp(e.createdAt)})})]}),t.jsx("p",{className:"employee-oversight-message-body",children:e.body})]})})]},e.id)),X.length?null:t.jsx("li",{children:"No messages yet."})]}),t.jsx("span",{className:"employee-visually-hidden",role:"status","aria-live":"polite","aria-atomic":"true",children:P})]}):null}):t.jsx(bc,{isEmpty:!0,emptyLabel:"No oversight conversation selected",emptyDescription:"Choose a conversation to create a durable access record and inspect its history."})]})]})}function Op({mode:e="normal",onChange:a,oversightDescriptionId:n}){return t.jsxs("div",{className:"employee-workspace-scope",role:"group","aria-label":"Message access mode",children:[t.jsx("button",{type:"button","aria-pressed":"normal"===e,onClick:()=>a?.("normal"),children:"Normal inbox"}),t.jsx("button",{type:"button","aria-pressed":"oversight"===e,"aria-describedby":n,onClick:()=>a?.("oversight"),children:"Audited oversight"})]})}function Dp({team:e,onSelect:a,onOpenConversation:n}){return t.jsxs(Qo,{className:"employee-team-card",tone:e.overdueTasks?"danger":"neutral",boundary:"elevated",children:[t.jsxs("header",{className:"employee-team-card__identity",children:[t.jsx("span",{className:"employee-team-card__icon","aria-hidden":"true",children:t.jsx(L,{size:20})}),t.jsxs("div",{children:[t.jsx("h3",{className:"ws-record-title",children:e.name}),t.jsx("span",{className:"ws-meta",children:Sc(e.membershipRole)})]}),t.jsx(tc,{value:e.archivedAt?"archived":"active"})]}),t.jsx(wd,{text:e.description||"No description",className:"ws-body"}),t.jsxs("dl",{className:"employee-team-card__summary",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Members"}),t.jsx("dd",{children:Number(e.memberCount||0)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Projects"}),t.jsx("dd",{children:Number(e.assignedProjectCount||0)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Resources"}),t.jsx("dd",{children:Number(e.directResourceCount||0)})]}),t.jsxs("div",{className:e.overdueTasks?"is-danger":"",children:[t.jsx("dt",{children:"Overdue"}),t.jsx("dd",{children:Number(e.overdueTasks||0)})]})]}),t.jsx("div",{className:"employee-team-card__work ws-meta",children:t.jsxs("span",{children:[Number(e.openTasks||0)," open tasks"]})}),t.jsxs("div",{className:"employee-team-actions",children:[t.jsx(ec,{variant:"secondary","data-team-open-id":e.id,"aria-label":`View team ${e.name}`,onClick:t=>a(e,t.currentTarget),children:"View team"}),e.conversationId?t.jsxs(ec,{variant:"ghost","aria-label":`Open ${e.name} conversation`,onClick:()=>n(e.conversationId),children:[t.jsx(le,{size:16,"aria-hidden":"true"})," Conversation"]}):null]})]})}function Pp({detail:e,headingRef:a,onClose:n,onOpenProject:s,onOpenConversation:r,onStartConversation:i,onOpenResource:l,onNavigateActivity:o,conversationLoading:c=!1,openingResourceId:d=null,closePending:u=!1}){const{team:h,members:m=[],projects:p=[],resources:g=[],taskSummary:f={}}=e||{};return h?t.jsxs("article",{className:"employee-team-detail","aria-labelledby":`employee-team-${h.id}-title`,children:[t.jsxs("header",{className:"employee-team-detail-header",children:[t.jsxs("div",{className:"employee-team-detail-header__identity",children:[t.jsx("h2",{id:`employee-team-${h.id}-title`,ref:a,tabIndex:-1,children:h.name}),t.jsxs("p",{className:"ws-meta",children:[Sc(h.membershipRole)," ·"," ",Number(h.memberCount||m.length)," members"]})]}),t.jsx("div",{className:"employee-team-detail-header__actions",children:t.jsx(ec,{variant:"ghost",disabled:u,onClick:n,children:u?"Returning to teamsâ¦":"Back to teams"})})]}),t.jsxs("div",{className:"employee-team-detail__overview",children:[t.jsx(wd,{text:h.description||"No description provided.",className:"employee-team-detail__description ws-body"}),t.jsx("dl",{className:"employee-team-detail__health",children:["open","overdue","blocked","completed"].map(e=>t.jsxs("div",{className:Number(f[e]||0)&&"open"!==e?`is-${e}`:"",children:[t.jsx("dt",{children:Sc(e)}),t.jsx("dd",{children:Number(f[e]||0)})]},e))}),t.jsxs(ec,{variant:"secondary",disabled:c,onClick:()=>h.conversationId?r(h.conversationId):i(h),children:[t.jsx(le,{size:16,"aria-hidden":"true"})," ",c?"Opening team chatâ¦":h.conversationId?"Open team chat":"Start team chat"]})]}),t.jsx(Yo,{boundary:"divided",title:"Members",description:"People with active membership in this team.",children:t.jsxs("ul",{className:"employee-team-list employee-team-member-list",children:[m.map(e=>t.jsxs(Qo,{as:"li",children:[t.jsx("strong",{children:e.name||"Member"}),t.jsx("span",{className:"ws-meta",children:Sc(e.membershipRole)})]}
2,e.userId)),m.length?null:t.jsx(Xo,{as:"li",children:"No active members."})]})}),t.jsx(Yo,{boundary:"divided",title:"Projects",children:t.jsxs("ul",{className:"employee-team-list",children:[p.map(e=>t.jsxs(Qo,{as:"li",className:"employee-team-linked-record",children:[t.jsxs("div",{className:"employee-team-linked-record__identity",children:[t.jsx("strong",{children:e.name}),t.jsx("span",{className:"ws-meta",children:"Assigned project"})]}),t.jsxs("div",{className:"employee-team-linked-record__status",children:[t.jsx(tc,{value:e.status}),t.jsx(ac,{value:e.priority})]}),t.jsx(ec,{variant:"ghost","aria-label":`View project ${e.name}`,onClick:()=>s(e.id),children:"View project"})]},e.id)),p.length?null:t.jsx(Xo,{as:"li",children:"No assigned projects."})]})}),t.jsx(Yo,{boundary:"divided",title:"Direct resources",children:t.jsxs("ul",{className:"employee-team-list",children:[g.map(e=>t.jsxs(Qo,{as:"li",className:"employee-team-linked-record employee-team-linked-record--resource",children:[t.jsxs("div",{className:"employee-team-linked-rec
2ord__identity",children:[t.jsx("strong",{children:e.title}),t.jsxs("span",{className:"ws-meta",children:[e.originalFilename||"File"," · ",Nc(e.sizeBytes)]})]}),t.jsxs(ec,{variant:"ghost","aria-label":`Open resource ${e.title}`,disabled:d===e.id,onClick:()=>l(e),children:[d===e.id?"Opening resourceâ¦":"Open resource"," ",t.jsx(Ue,{size:14,"aria-hidden":"true"})]})]},e.id)),g.length?null:t.jsx(Xo,{as:"li",children:"No direct resources."})]})}),t.jsx("div",{className:"employee-team-detail__activity",children:t.jsx(xc,{endpoint:`/api/employee/teams/${h.id}/activity`,onNavigate:o})})]}):null}const Lp=["lead","member","observer"],$p=Object.freeze({});function Mp(e={}){return{name:e.name||"",description:e.description||""}}function Up(e=[]){return e.filter(e=>!e.leftAt).map(e=>({userId:e.userId,name:e.name,membershipRole:e.membershipRole,status:e.status}))}function Fp(e=[]){return e.map(e=>({...e,projectId:e.projectId||e.id}))}function zp(e=[]){return JSON.stringify(e.map(e=>({userId:String(e.userId||""),membershipRole:e.membershipRole||"member"})).filter(e=>e.userId).sort((e,t)=>`${e.userId}:${e.membershipRole}`.localeCompare(`${t.userId}:${t.membershipRole}`)))}function qp(e=[],t=["id"]){return JSON.stringify([...new Set(e.map(e=>t.map(t=>e?.[t]).find(Boolean)))].filter(Boolean).map(String).sort())}
2function Bp(e,t,a,n){if(!t?.team?.id)return e;const s=String(t.team.id),r=e.findIndex(e=>String(e.id)===s);if(r<0)return e;const i={...e[r],...t.team,members:t.members||e[r].members};return function(e,t,a){const n=Boolean(e.archivedAt||e.archived_at);if("active"===a&&n)return!1;if("archived"===a&&!n)return!1;const s=t.trim().toLocaleLowerCase();return!s||[e.name,e.description].some(e=>String(e||"").toLocaleLowerCase().includes(s))}(i,a,n)?e.map((e,t)=>t===r?i:e):e.filter(e=>String(e.id)!==s)}function Wp({selectedTeamId:a=null,onSelectedTeamChange:n,onOpenMessages:s,apiBase:r="/api/admin/teams",scope:i=null,canonical:l=!1,onDirtyChange:o}){const{makeAuthRequest:c}=Yn(),d=$s(),[u,h]=e.useState([]),[m,p]=e.useState(null),[g,f]=e.useState(""),[b,x]=e.useState("active"),[v,j]=e.useState({name:"",description:""}),[y,k]=e.useState([]),[w,N]=e.useState([]),[S,C]=e.useState([]),[R,E]=e.useState({name:"",description:""}),[I,_]=e.useState("[]"),[T,A]=e.useState("[]"),[O,D]=e.useState("[]"),[P,L]=e.useState(null),[$,M]=e.useState(null),[U,F]=e.useState(!1),[z,q]=e.useState(!1),[B,W]=e.useState(null),[V,H]=e.useState(!1),[K,G]=e.useState(0),[J,Y]=e.useState(!1),[Q,X]=e.useState(null),[Z,ee]=e.useState(null),[te,ae]=e.useState(""),[ne,se]=e.useState($p),[re,ie]=e.useState(null),[oe,ce]=e.useState("identity"),[de,he]=e.useState(!0),[me,pe]=e.useState(!1),[ge,fe]=e.useState({name:"",description:""}),[be,xe]=e.useState(null),ve=e.useRef(a),je=e.useRef(n),ye=e.useRef(0),ke=e.useRef(0),we=e.useRef(0),Ne=e.useRef(!0),Se=e.useRef(null),Ce=e.useRef(null),Re=e.useRef(null),Ee=e.useRef(null),Ie=e.useRef(null),_e=e.useRef(null),Te=e.useRef(null),Ae=e.useId();Se.current=m?.team?.id||null;const Oe=e.useCallback(()=>{we.current+=1},[]),De=e.useCallback(e=>({generation:we.current,teamId:String(e||"")}),[]),Pe=e.useCallback(()=>({generation:we.current}),[]),Le=e.useCallback(e=>Boolean(Ne.current&&e?.generation===we.current),[]),$e=e.useCallback(e=>Boolean(Le(e)&&String(Se.current||"")===e?.teamId),[Le]),Me=e.useCallback((e="")=>{const t=`${r}${e}`;return i?`${t}${t.includes("?")?"&":"?"}scope=${i}`:t},[r,i]);e.useEffect(()=>{je.current=n},[n]);const Ue=e.useCallback(({offset:e=0,limit:t=(l?51:null)}={})=>{const a=new URLSearchParams;return g&&a.set("search",g),l?a.set("archiveState",b):"archived"===b?a.set("archived","true"):"all"===b&&a.set("archived","all"),l&&t&&(a.set("limit",String(Math.min(t,100))),a.set("offset",String(e))),i&&a.set("scope",i),a},[b,l,i,g]),Fe=e.useCallback(async({append:e=!1,offset:t=0}={})=>{const a=++ye.current;e?q(!0):(F(!0),h([]),H(!1),G(0)),M(null),W(null);const n=Ue({offset:t});try{const s=await c(`${r}?${n.toString()}`);if(a!==ye.current)return;const i=s.data.teams||[],o=l?i.slice(0,50):i;h(t=>e?[...t,...o]:o),G(e?t+o.length:o.length),H(Boolean(l&&i.length>50))}catch(s){if(a!==ye.current)return;const t=s.safeMessage||s.message||"Unable to load teams.";e?W(t):M(s)}finally{a===ye.current&&(F(!1),q(!1))}},[r,l,Ue,c]),ze=e.useCallback(async(e=null,t="identity")=>{if(e&&!$e(e))return!1;if(!l||!K)return!0;const a=++ye.current,n=K,s=new Map;let i=0;try{for(;s.size<=n;){const t=Math.min(100,n+1-s.size),l=Ue({offset:i,limit:t}),o=await c(`${r}?${l.toString()}`);if(e&&!$e(e))return!1;if(a!==ye.current)return!1;const d=o.data.teams||[];if(d.forEach(e=>s.set(String(e.id),e)),i+=d.length,d.length<t)break}const t=[...s.values()];return h(t.slice(0,n)),G(Math.min(n,t.length)),H(t.length>n),!0}catch{return e&&!$e(e)||(a!==ye.current||ee({section:t,message:"Your changes were saved, but the latest team list could not be refreshed. Try again."})),!1}},[r,l,$e,Ue,K,c]),qe=e.useCallback(async(e,t=null,{focusHeading:a=!0,resetSection:n=!0,retainSelected:s=!1,preserveOnError:i=!1,refreshSection:o=null,action:d=null,panelAction:u=null}={})=>{if(d&&!$e(d))return null;if(u&&!Le(u))return null;d||u||Oe();const h=++ke.current;t&&(Ee.current=e,Ie.current=function(e){const t=e?.closest?.(".employee-workspace-main"),a=t?globalThis.getComputedStyle?.(t)?.overflowY:null,n=t&&/^(auto|scroll|overlay)$/.test(a)?t:globalThis.document?.scrollingElement||globalThis.document?.documentElement;return n?{element:n,top:n.scrollTop,left:n.scrollLeft}:null}(t),ae("")),s||(p(null),se($p),he(!0)),Y(!0),X(null),ee(null),L(null);try{const t=await c(l?Me(`/${e}`):`${r}/${e}/context?includeInactive=true`);if(d&&!$e(d))return null;if(u&&!Le(u))return null;if(h!==ke.current)return null;const s=t.data,i=Mp(s.team),o=Up(s.members),m=Fp(s.projects),g=s.resources||[];return p(s),j(i),k(o),N(m),C(g),E(i),_(zp(o)),A(qp(m,["projectId","id"])),D(qp(g,["id","resourceId"])),n&&ce("identity"),je.current?.(s.team.id),a&&requestAnimationFrame(()=>Ce.current?.focus()),s}catch{return d&&!$e(d)||(u&&!Le(u)||h!==ke.current)?null:i?(ee({section:o||"identity",message:"Your changes were saved, but the latest team data could not be refreshed. Try again."}),null):(p(null),X("This item is unavailable or you no longer have access."),null)}
2finally{h===ke.current&&Y(!1)}},[r,l,Me,Oe,$e,Le,c]);e.useEffect(()=>{Fe()},[Fe]),e.useEffect(()=>{ve.current&&!a&&(ke.current+=1,Oe(),p(null),Y(!1),X(null),ee(null),j({name:"",description:""}),k([]),N([]),C([]),E({name:"",description:""}),_("[]"),A("[]"),D("[]"),se($p),ce("identity"),he(!0),ie(null)),ve.current=a,a&&m?.team?.id!==a&&qe(a)},[Oe,qe,m?.team?.id,a]),e.useEffect(()=>(Ne.current=!0,()=>{Ne.current=!1,ye.current+=1,ke.current+=1,Oe()}),[Oe]);const Be=v.name!==R.name||v.description!==R.description,We=zp(y)!==I,Ve=qp(w,["projectId","id"])!==T,He=qp(S,["id","resourceId"])!==O,Ke=Be||We||Ve||He;e.useEffect(()=>{o?.(Ke)},[Ke,o]),e.useEffect(()=>()=>o?.(!1),[o]),e.useEffect(()=>{if(!Ke)return;const e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[Ke]),e.useEffect(()=>{if(!Ke)return;const e=e=>{const t=e.target.closest?.("a[href]");if(!t)return;const a=t.getAttribute("href")||"";"_blank"===t.target||a.startsWith("#")||/^[a-z]+:\/\//i.test(a)||window.confirm("Discard your unsaved team changes?")||(e.preventDefault(),e.stopPropagation())};return globalThis.document.addEventListener("click",e,!0),()=>globalThis.document.removeEventListener("click",e,!0)},[Ke]),e.useEffect(()=>{const e=Ee.current;if(m||J||Q||!Re.current||!e)return;let t;const a=requestAnimationFrame(()=>{const a=Array.from(Re.current?.querySelectorAll("[data-team-open-id]")||[]).find(t=>t.dataset.teamOpenId===String(e)),n=Ie.current;Wm(n,a,{restoreCaptured:!0}),t=requestAnimationFrame(()=>{Wm(n,a),Ee.current=null,Ie.current=null})});return()=>{cancelAnimationFrame(a),t&&cancelAnimationFrame(t)}},[m,Q,J,u]);const Ge=async({skipConfirm:e=!1,expectedAction:t=null}={})=>{const a=t||De(m?.team?.id);if(!$e(a))return!1;if(Ke&&!e){const e=await d({title:"Discard unsaved team changes?",message:"Your unsaved identity, member, project, and resource changes will be lost.",confirmLabel:"Discard changes",confirmVariant:"danger"});if(!$e(a)||!e)return!1}return Oe(),ke.current+=1,p(null),Y(!1),X(null),ee(null),j({name:"",description:""}),k([]),N([]),C([]),E({name:"",description:""}),_("[]"),A("[]"),D("[]"),se($p),ce("identity"),he(!0),ie(null),je.current?.(null,{skipDirtyConfirm:e||Ke}),!0},Je=async(e,t)=>{if(!$e(e))return;if(!(await Ge({skipConfirm:!0,expectedAction:e}))||!Ne.current)return;const a=Pe();Le(a)&&(await Fe(),Le(a)&&ae(t))},Ye=async(e,t,a={},n)=>{if(!$e(n))return null;const s={draft:v,members:y,projects:w,resources:S},r=Be,i=We,l=Ve,o=He,c=await qe(m.team.id,null,{focusHeading:!1,resetSection:!1,retainSelected:!0,preserveOnError:!0,refreshSection:e,action:n});if(!$e(n))return null;if(!c){const n={...m,team:{...m.team,...a.team||{}}};if("identity"===e){const e=Mp({...t,...a.team||{}});n.team={...n.team,...e},j(e),E(e)}else if("members"===e){const e=Array.isArray(a.members)?Up(a.members):t;n.members=e,n.team={...n.team,memberCount:a.team?.memberCount??e.length},k(e),_(zp(e))}else if("projects"===e){const e=Array.isArray(a.projects)?Fp(a.projects):t;n.projects=e,N(e),A(qp(e,["projectId","id"]))}else if("resources"===e){const e=Array.isArray(a.resources)?a.resources:t;n.resources=e,C(e),D(qp(e,["id","resourceId"]))}return p(n),h(e=>Bp(e,n,g,b)),!1}return h(e=>Bp(e,c,g,b)),"identity"!==e&&r&&j(s.draft),"members"!==e&&i&&k(s.members),"projects"!==e&&l&&N(s.projects),"resources"!==e&&o&&C(s.resources),!0},Qe=Boolean(m?.team?.archivedAt),Xe=m?De(m.team.id):null,et=[{id:"identity",label:"Identity"},...Qe?[]:[{id:"members",label:"Members"},{id:"work",label:"Projects and resources"}]],tt=e=>{const t=_e.current;if(!t||!e)return;const a=e.offsetLeft,n=a+e.offsetWidth,s=t.scrollLeft,r=s+t.clientWidth;a<s?t.scrollLeft=a:n>r&&(t.scrollLeft=n-t.clientWidth),e.scrollIntoView?.({behavior:"auto",block:"nearest",inline:"nearest"})},at=Boolean(m||J||Q||a),nt=Boolean(re),st=Boolean(m?.team?.capabilities?.canArchiveTeam||m?.team?.capabilities?.canRestoreTeam||m?.team?.capabilities?.canDeleteTeam),rt=e=>{const a=Z?.section===e?Z:null,n=a||ne[e];return n?t.jsxs(oc,{type:a?"error":n.type,className:"teams-admin-section-feedback",children:[t.jsx("span",{children:n.message}),a?t.jsx(ec,{variant:"ghost",disabled:nt,onClick:()=>{(async()=>
2{const e=De(m?.team?.id),t=Z?.section||"identity",a={draft:v,members:y,projects:w,resources:S,canonicalDraft:R,canonicalMembers:I,canonicalProjects:T,canonicalResources:O},n={identityDirty:Be,membersDirty:We,projectsDirty:Ve,resourcesDirty:He},s=Object.values(n).some(Boolean);ie("refresh"),ae("");const r=await qe(m.team.id,null,{focusHeading:!1,resetSection:!1,retainSelected:!0,preserveOnError:!0,refreshSection:t,action:e});if($e(e)){if(r){n.identityDirty&&(j(a.draft),E(a.canonicalDraft)),n.membersDirty&&(k(a.members),_(a.canonicalMembers)),n.projectsDirty&&(N(a.projects),A(a.canonicalProjects)),n.resourcesDirty&&(C(a.resources),D(a.canonicalResources)),h(e=>Bp(e,r,g,b));const i=!l||await ze(e,t);if(!$e(e))return;i&&se(e=>({...e,[t]:{type:"success",message:s?"Team data refreshed. Unsaved changes were preserved.":"Team data refreshed."}}))}$e(e)&&ie(null)}})()},children:"refresh"===re?"Refreshingâ¦":"Retry refresh"}):null]}):null};return t.jsxs("section",{className:"teams-admin-panel"+(at?" is-record-open":""),children:[te?t.jsx(oc,{type:"success",className:"teams-admin-feedback",children:te}):null,at?null:t.jsxs(sc,{label:"Team administration filters",resultCount:u.length,activeFilterCount:Number(Boolean(g))+Number("active"!==b),onClear:()=>{f(""),x("active")},children:[t.jsxs("label",{children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{value:g,onChange:e=>f(e.target.value),placeholder:"Search teams","aria-label":"Search teams"})]}),t.jsxs("select",{value:b,onChange:e=>x(e.target.value),"aria-label":"Team lifecycle state",children:[t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"archived",children:"Archived"}),t.jsx("option",{value:"all",children:"All"})]}),t.jsx(ec,{variant:"primary",onClick:()=>{ae(""),pe(!0)},children:"New Team"})]}),t.jsx("div",{className:"teams-admin-layout",children:at?J?t.jsxs("article",{className:"teams-admin-record teams-admin-record--request","aria-busy":"true",children:[t.jsx(ec,{variant:"ghost",onClick:()=>{Ge()},children:"Back to teams"}),t.jsx(bc,{loading:!0,loadingLabel:"Opening teamâ¦"})]}):Q?t.jsx("article",{className:"teams-admin-record teams-admin-record--request",children:t.jsxs(oc,{type:"error",children:[Q,t.jsx(ec,{variant:"ghost",onClick:()=>{Ge()},children:"Back to teams"})]})}):m?t.jsxs("article",{className:"teams-admin-record","aria-labelledby":`${Ae}-team-title`,children:[t.jsxs("header",{className:"teams-admin-identity",children:[t.jsxs("div",{children:[t.jsx("h2",{id:`${Ae}-team-title`,ref:Ce,tabIndex:-1,children:m.team.name}),t.jsxs("p",{className:"ws-meta",children:[y.length," active members"]})]}),t.jsxs("div",{className:"teams-admin-identity__actions",children:[l&&st?Ke||nt?t.jsx(ec,{variant:"ghost",iconOnly:!0,disabled:!0,"aria-label":"Team lifecycle actions unavailable while changes are unsaved or saving",title:"Save or discard changes before using team lifecycle actions",children:t.jsx(Ze,{size:18,"aria-hidden":"true"})}):t.jsx(vm,{entityType:"Team",entityName:m.team.name,archived:Boolean(m.team.archivedAt),canArchive:m.team.capabilities?.canArchiveTeam,canRestore:m.team.capabilities?.canRestoreTeam,canDelete:m.team.capabilities?.canDeleteTeam,request:c,endpoint:Me(`/${m.team.id}/lifecycle`),onChanged:async()=>{await Je(Xe,"Team lifecycle updated.")},onDeleted:async()=>{await Je(Xe,"Team permanently deleted.")}}):null,t.jsx(tc,{value:m.team.archivedAt?"archived":"active"}),t.jsx(ec,{variant:"ghost",disabled:nt,onClick:()=>{Ge()},children:"Back to teams"})]})]}),P?t.jsx(oc,{type:"error",children:P}):null,t.jsx("p",{className:"teams-admin-save-state"+(Ke?" is-dirty":""),role:"status","aria-live":"polite",children:Ke?`Unsaved changes: ${[Be?"identity":null,We?"members":null,Ve?"projects":null,He?"resources":null].filter(Boolean).join(", ")}.${st?" Save or discard changes before using lifecycle actions.":""}`:"All team changes saved"}),t.jsx("nav",{ref:_e,className:"teams-admin-tabs",role:"tablist","aria-label":"Team sections",onKeyDown:e=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;e.preventDefault();const t=et.findIndex(e=>e.id===oe),a="Home"===e.key?0:"End"===e.key?et.length-1:"ArrowRight"===e.key?(t+1)%et.length:(t-1+et.length)%et.length;ce(et[a].id),requestAnimationFrame(()=>{const e=_e.current?.querySelectorAll('[role="tab"]')?.[a];e?.focus({preventScroll:!0}),tt(e)})},children:et.map(e=>t.jsx("button",{type:"button",role:"tab",id:`${Ae}-${e.id}-tab`,"aria-selected":oe===e.id,"aria-controls":`${Ae}-${e.id}
2-panel`,tabIndex:oe===e.id?0:-1,disabled:nt,onClick:()=>ce(e.id),onFocus:e=>tt(e.currentTarget),children:e.label},e.id))}),t.jsxs("section",{className:"teams-admin-tabpanel",role:"tabpanel",id:`${Ae}-${oe}-panel`,"aria-labelledby":`${Ae}-${oe}-tab`,tabIndex:0,children:["identity"===oe?t.jsxs(Yo,{title:"Team Detail",children:[t.jsxs("form",{className:"teams-admin-form","aria-label":"Edit team",onSubmit:e=>{e.preventDefault(),(async()=>{if(!v.name.trim())return void se(e=>({...e,identity:{type:"error",message:"Team name is required."}}));const e=De(m?.team?.id);ie("team"),L(null),ee(e=>"identity"===e?.section?null:e),se(e=>({...e,identity:null})),ae("");try{const t={...v,name:v.name.trim()},a=await c(Me(`/${m.team.id}`),{method:"PATCH",body:JSON.stringify(t)});if(!$e(e))return;const n=await Ye("identity",t,a.data||{},e);if(!$e(e))return;const s=await ze(e,"identity");if(!$e(e))return;n&&s&&se(e=>({...e,identity:{type:"success",message:"Team details saved."}}))}catch(t){if(!$e(e))return;se(e=>({...e,identity:{type:"error",message:t.safeMessage||t.message||"Unable to save team details."}}))}finally{$e(e)&&ie(null)}})()},noValidate:!0,children:[t.jsxs(ic,{legend:"Team identity",description:"Keep the team name and purpose concise.",disabled:nt,children:[t.jsx(rc,{label:"Name",required:!0,children:t.jsx("input",{value:v.name,onChange:e=>{se(e=>({...e,identity:null})),j(t=>({...t,name:e.target.value}))},disabled:Qe||nt})}),t.jsx(rc,{label:"Description",className:"teams-admin-field--wide",children:t.jsx("textarea",{value:v.description,onChange:e=>{se(e=>({...e,identity:null})),j(t=>({...t,description:e.target.value}))},disabled:Qe||nt})})]}),t.jsxs("p",{className:"ws-meta",children:["Created"," ",m.team.createdAt?new Date(m.team.createdAt).toLocaleString():"unknown"," ","· Updated"," ",m.team.updatedAt?new Date(m.team.updatedAt).toLocaleString():"unknown"]}),t.jsxs(lc,{children:[rt("identity"),t.jsx(ec,{variant:"primary",type:"submit",disabled:Qe||nt||!Be,children:"team"===re?"Saving teamâ¦":"Save Team"}),t.jsxs(ec,{variant:"secondary",onClick:async()=>{const e=De(m?.team?.id);if(Ke){const t=await d({title:"Discard unsaved team changes?",message:"Opening the team conversation will leave this editor and discard your drafts.",confirmLabel:"Discard and open conversation",confirmVariant:"danger"});if(!$e(e)||!t)return}ie("conversation"),L(null);try{const t=await c(Me(`/${m.team.id}/conversation`),{method:"POST",body:JSON.stringify({})});if(!$e(e))return;s?.(t.data.conversationId,{skipDirtyConfirm:Ke})}catch(t){if(!$e(e))return;L(t.safeMessage||t.message||"Unable to open team conversation.")}finally{$e(e)&&ie(null)}},disabled:Qe||nt,children:[t.jsx(le,{size:16,"aria-hidden":"true"})," Open Team Conversation"]})]})]}),t.jsxs(Xo,{boundary:"callout",className:"teams-admin-danger",children:[t.jsx("h3",{children:"Lifecycle"}),t.jsx("p",{children:"Archived teams cannot grant live Workspace access or receive new work."}),l||Qe?null:t.jsx(ec,{variant:"danger",onClick:async()=>{const e=De(m?.team?.id),t=await d({title:"Archive team?",message:"This will remove the team from active workspace views.",confirmLabel:"Archive team",confirmVariant:"danger"});if($e(e)&&t){ie("archive"),L(null),ae("");try{if(await c(Me(`/${m.team.id}`),{method:"DELETE"}),!$e(e))return;await Je(e,"Team archived.")}catch(a){if(!$e(e))return;L(a.safeMessage||a.message||"Unable to archive team.")}finally{$e(e)&&ie(null)}}},disabled:nt||Ke,children:"archive"===re?"Archiving teamâ¦":"Archive Team"})]})]}):null,"members"===oe?t.jsx(Yo,{title:"Members",description:"Manage active membership separately from team identity.",children:t.jsxs("fieldset",{className:"teams-admin-editor-fieldset",disabled:nt,children:[t.jsx("legend",{className:"teams-admin-visually-hidden",children:"Member assignments"}),t.jsx(ah,{value:y,onChange:e=>{se(e=>({...e,members:null})),k(e)},multiple:!0,endpoint:l?"/api/employee/people":void 0}),y.length?t.jsxs("div",{className:"teams-admin-selected-editor",children:[t.jsxs("div",{className:"teams-admin-selected-editor__header",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"Selected member roles"}),t.jsxs("span",{className:"ws-meta",children:[y.length," ",1===y.length?"member":"members"]})]}),t.jsx(ec,{variant:"ghost",size:"compact","aria-expanded":de,"aria-controls":`${Ae}-selected-members`,onClick:()=>he(e=>!e),children:de?"Hide member controls":"Manage member roles"})]}),t.jsx("div",{id:`${Ae}-selected-members`,className:"teams-admin-selected-region",role:"region","aria-label":`Selected member role controls (${y.length})`,tabIndex:0,hidden:!de,children:t.jsx("div",{className:"teams-admin-chip-list",role:"list",children:y.map(e=>t.jsxs(Xo,{as:"div",role:"listitem",children:[t.jsx("strong",{children:e.name||"Member"}),t.jsx("select",{value:e.membershipRole||"member","aria-label":`Role for ${e.name||"member"}`,onChange:t=>{se(e=>({...e,members:null})),k(a=>a.map(a=>a.userId===e.userId?{...a,membershipRole:t.target.value}:a))},children:Lp.map(e=>t.jsx("option",{children:e},e))}),t.jsx(ec,{variant:"ghost",onClick:()=>{se(e=>({...e,members:null})),k(t=>t.filter(t=>
2t.userId!==e.userId))},children:"Remove"})]},e.userId))})})]}):t.jsx(Xo,{children:"No active members."}),t.jsxs(lc,{className:"teams-admin-section-actions",children:[rt("members"),We?t.jsx("span",{className:"teams-admin-section-dirty-state",children:"Unsaved member changes"}):null,t.jsx(ec,{variant:"primary",onClick:async()=>{L(null),ee(e=>"members"===e?.section?null:e),se(e=>({...e,members:null})),ae("");const e=y.find(e=>"offboarded"===e.status);if(e)return void se(t=>({...t,members:{type:"error",message:`${e.name||"Selected person"} is offboarded and cannot be newly assigned.`}}));const t=De(m?.team?.id);ie("members");try{const e=y.map(e=>({...e})),a=await c(Me(`/${m.team.id}/members`),{method:"PUT",body:JSON.stringify({members:e.map(e=>({userId:e.userId,membershipRole:e.membershipRole||"member"}))})});if(!$e(t))return;const n=await Ye("members",e,a.data||{},t);if(!$e(t))return;n&&se(e=>({...e,members:{type:"success",message:"Team members updated."}}))}catch(a){if(!$e(t))return;se(e=>({...e,members:{type:"error",message:a.safeMessage||a.message||"Unable to save members."}}))}finally{$e(t)&&ie(null)}},disabled:!We,children:"members"===re?"Saving membersâ¦":"Save Members"})]})]})}):null,"work"===oe?t.jsxs(Yo,{title:"Projects and resources",children:[t.jsxs(ic,{legend:"Projects",disabled:nt,children:[t.jsx(eh,{value:w,onChange:e=>{se(e=>({...e,projects:null})),N(e)},multiple:!0,endpoint:l?"/api/workspace/v1/projects?scope=all":void 0}),t.jsxs(lc,{children:[rt("projects"),t.jsx(ec,{variant:"primary",onClick:async()=>{const e=De(m?.team?.id);ie("projects"),L(null),ee(e=>"projects"===e?.section?null:e),se(e=>({...e,projects:null})),ae("");try{const t=w.map(e=>({...e})),a=await c(Me(`/${m.team.id}/projects`),{method:"PUT",body:JSON.stringify({projectIds:t.map(e=>e.projectId||e.id)})});if(!$e(e))return;const n=await Ye("projects",t,a.data||{},e);if(!$e(e))return;n&&se(e=>({...e,projects:{type:"success",message:"Team projects updated."}}))}catch(t){if(!$e(e))return;se(e=>({...e,projects:{type:"error",message:t.safeMessage||t.message||"Unable to save projects."}}))}finally{$e(e)&&ie(null)}},disabled:!Ve,children:"projects"===re?"Saving projectsâ¦":"Save Projects"})]})]}),t.jsxs(ic,{legend:"Resource packs",description:"Selecting a pack grants access to all files in it.",disabled:nt,children:[t.jsx(Cm,{className:"teams-admin-resource-picker",label:"Resource packs",searchPlaceholder:"Search resource packs by name or purpose",value:S,onChange:e=>{se(e=>({...e,resources:null})),C(e)},multiple:!0,allowTargets:!1,selectedListScrollable:!0,endpoint:l?"/api/workspace/v1/resource-packs?scope=all":void 0}),t.jsxs(lc,{className:"teams-admin-section-actions",children:[rt("resources"),He?t.jsx("span",{className:"teams-admin-section-dirty-state",children:"Unsaved resource changes"}):null,t.jsx(ec,{variant:"primary",onClick:async()=>{const e=De(m?.team?.id);ie("resources"),L(null),ee(e=>"resources"===e?.section?null:e),se(e=>({...e,resources:null})),ae("");try{const t=S.map(e=>({...e})),a=await c(Me(`/${m.team.id}/resources`),{method:"PUT",body:JSON.stringify({resourceIds:t.map(e=>e.id||e.resourceId)})});if(!$e(e))return;const n=await Ye("resources",t,a.data||{},e);if(!$e(e))return;n&&se(e=>({...e,resources:{type:"success",message:"Team resources updated."}}))}catch(t){if(!$e(e))return;se(e=>({...e,resources:{type:"error",message:t.safeMessage||t.message||"Unable to save resources."}}))}finally{$e(e)&&ie(null)}},disabled:!He,children:"resources"===re?"Saving resourcesâ¦":"Save Resources"})]})]})]}):null]})]}):null:t.jsxs(Yo,{className:"teams-admin-list",title:"Teams",children:[$&&u.length?t.jsxs(oc,{type:"error",children:[$.safeMessage||"Teams could not be refreshed.",t.jsx(ec,{variant:"ghost",onClick:()=>Fe(),children:"Retry"})]}):null,t.jsxs(bc,{loading:U&&!u.length,error:$,isEmpty:!u.length,loadingLabel:"Loading teamsâ¦",errorLabel:"Teams could not be loaded",emptyLabel:g||"active"!==b?"No teams match these filters.":"No teams found.",emptyDescription:g||"active"!==b?"Clear the filters to return to active teams.":"Create a team to begin assigning members and work.",emptyType:g||"active"!==b?"no-results":"empty",emptyAction:g||"active"!==b?t.jsx(ec,{variant:"ghost",onClick:()=>{f(""),x("active")},children:"Clear filters"}):null,onRetry:()=>Fe(),children:[t.jsxs("div",{ref:Re,className:"teams-admin-record-list",role:"region","aria-label":"Workspace teams",children:[t.jsxs("div",{className:"teams-admin-record-list__header","aria-hidden":"true",children:[t.jsx("span",{children:"Name"}),t.jsx("span",{children:"Status"}),t.jsx("span",{children:"Members"}),t.jsx("span",{children:"Creator"}),t.jsx("span",{children:"Action"})]}),t.jsx("ul",{children:u.map(e=>{const a=e.archived_at||e.archivedAt?"archived":"active";return t.jsxs(Qo,{as:"li",className:"teams-admin-record-row",children:[t.jsxs("div",{className:"teams-admin-record-row__name",children:[t.jsx("span",{className:"teams-admin-record-row__label",children:"Name"}),t.jsx("strong",{children:e.name})]}),t.jsxs("div",{children:[t.jsx("span",{className:"teams-admin-record-row__label",children:"Status"}),t.jsx(tc,{value:a})]}),t.jsxs("div",{children:[t.jsx("span",{className:"teams-admin-record-row__label",children:"Members"}),t.jsx("span",{children:e.memberCount??e.members?.length??0})]}),t.jsxs("div",{children:[t.jsx("span",{className:"teams-admin-record-row__label",children:"Creator"}),t.jsx("span",{children:e.creator_name||e.creator?.name||"Unknown"})]}),t.jsx("div",{className:"teams-admin-record-row__action",children:t.jsx(ec,{variant:"secondary","data-team-open-id":e.id,"aria-label":`Open team ${e.name}`,onClick:t=>qe(e.id,t.currentTarget),children:"Open"})})]},e.id)})})]}),V&&!B?t.jsx("div",{className:"teams-admin-pagination",children:t.jsx(ec,{variant:"secondary",disabled:z,onClick:()=>Fe({append:!0,offset:K}),children:z?"Loading moreâ¦":"Load more teams"})}):null,B?t.jsxs(oc,{type:"error",children:[B,t.jsx(ec,{variant:"ghost",disabled:z,onClick:()=>Fe({append:!0,offset:K}),children:"Try again"})]}):null]})]})}),t.jsx(cc,{isOpen:me,onClose:()=>{"create"!==re&&pe(!1)},title:"Create team",description:"Create the team identity first, then add membership and work assignments.",closeLabel:"Close create team",initialFocusRef:Te,children:t.jsxs("form",{className:"teams-admin-form","aria-label":"Create team",onSubmit:e=>{e.preventDefault(),(async()=>
2{if(!ge.name.trim())return void xe("Team name is required.");const e=Pe();ie("create"),xe(null),ae("");try{const t=await c(Me(),{method:"POST",body:JSON.stringify({...ge,name:ge.name.trim()})});if(!Le(e))return;if(pe(!1),await Fe(),!Le(e))return;Ee.current=null;const a=await qe(t.data.team.id,null,{panelAction:e});if(!Le(e)||!a)return;fe({name:"",description:""}),ae("Team created.")}catch(t){if(!Le(e))return;xe(t.safeMessage||t.message||"Unable to create team.")}finally{Le(e)&&ie(null)}})()},noValidate:!0,children:[be?t.jsx(oc,{type:"error",children:be}):null,t.jsxs(ic,{legend:"Team identity",disabled:"create"===re,children:[t.jsx(rc,{label:"Name",required:!0,error:"Team name is required."===be?be:null,children:t.jsx("input",{ref:Te,value:ge.name,onChange:e=>{xe(null),fe(t=>({...t,name:e.target.value}))},disabled:"create"===re})}),t.jsx(rc,{label:"Description",className:"teams-admin-field--wide",children:t.jsx("textarea",{value:ge.description,onChange:e=>fe(t=>({...t,description:e.target.value})),disabled:"create"===re})})]}),t.jsxs(lc,{children:[t.jsx(ec,{variant:"ghost",onClick:()=>pe(!1),disabled:"create"===re,children:"Cancel"}),t.jsx(ec,{variant:"primary",type:"submit",disabled:"create"===re,children:"create"===re?"Creating teamâ¦":"Create Team"})]})]})})]})}const Vp=["","lead","member","observer"];function Hp({selectedTeamId:a,onOpenTeam:n,onCloseTeam:s,onOpenProject:r,onOpenConversation:i,onNavigateActivity:l,onListReady:o,onAdminDirtyChange:c,scope:d="mine"}){const{makeAuthRequest:u}=Yn(),[h,m]=e.useState(""),[p,g]=e.useState(""),[f,b]=e.useState(null),[x,v]=e.useState(!1),[j,y]=e.useState(null),[k,w]=e.useState(!1),[N,S]=e.useState(null),[C,R]=e.useState(null),[E,I]=e.useState(!1),[_,T]=e.useState(null),A=e.useRef(a),O=e.useRef(0),D=e.useRef(0),P=e.useRef(!0),L=e.useRef(null),$=e.useRef(null),M=e.useRef(null),U=e.useRef(null),F=e.useRef(null),z=e.useMemo(()=>{const e=new URLSearchParams;return h&&e.set("search",h),p&&e.set("role",p),Fm(`/api/workspace/v1/teams?${e.toString()}`,d)},[p,d,h]),{data:q,loading:B,error:W,refresh:V,hasMore:H,loadMore:K,loadingMore:G,loadMoreError:J}=kc(z,{initialData:{teams:[]},collectionKey:"teams",pageSize:24});L.current=f?.team?.id||null;const Y=e.useCallback(()=>{D.current+=1},[]),Q=e.useCallback(e=>({generation:D.current,teamId:String(e)}),[]),X=e.useCallback(e=>Boolean(P.current&&e?.generation===D.current&&String(L.current||"")===e?.teamId),[]),Z=e.useCallback(async(e,t=null)=>{const a=e?.id||e;Y();const s=++O.current;t&&(U.current=a,F.current=qm(t)),b(null),v(!0),y(null),w(!1),S(null),R(null),I(!1),T(null);try{const e=await u(Fm(`/api/workspace/v1/teams/${a}`,d));if(s!==O.current)return;b(e.data),n?.(e.data.team,{teamId:U.current,scroll:F.current}),requestAnimationFrame(()=>$.current?.focus())}catch{if(s!==O.current)return;b(null),y("This item is unavailable or you no longer have access.")}finally{s===O.current&&v(!1)}},[Y,u,n,d]);e.useEffect(()=>(P.current=!0,()=>{P.current=!1,O.current+=1,Y()}),[Y]),e.useEffect(()=>Y(),[Y,d]),e.useEffect(()=>{A.current&&!a&&(O.current+=1,Y(),b(null),v(!1),y(null),w(!1),I(!1),T(null)),A.current=a,a&&f?.team?.id!==a&&Z(a)},[Y,Z,f?.team?.id,a]),e.useEffect(()=>{a||f||x||j||!M.current||o?.(M.current)},[q?.teams,o,f,a,j,x]),e.useEffect(()=>{const e=U.current;if(a||f||x||j||!M.current||!e)return;let t;const n=requestAnimationFrame(()=>{const a=Array.from(M.current?.querySelectorAll("[data-team-open-id]")||[]).find(t=>t.dataset.teamOpenId===String(e)),n=F.current;Wm(n,a,{restoreCaptured:!0}),t=requestAnimationFrame(()=>{Wm(n,a),U.current=null,F.current=null})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[q?.teams,f,a,j,x]);const ee=e.useCallback(()=>{if(O.current+=1,Y(),S(null),R(null),I(!1),T(null),a)return w(!0),void s?.();b(null),v(!1),y(null),s?.()},[Y,s,a]),te=async e=>{const t=Q(f?.team?.id);R(null),T(e.id);try{const a=await u(`/api/employee/resources/${e.id}/access`,{method:"POST",body:JSON.stringify({})});if(!X(t))return;a?.data?.url&&window.open(a.data.url,"_blank","noopener,noreferrer")}catch(a){if(!X(t))return;R(a)}finally{X(t)&&T(null)}},ae=async e=>{const t=Q(e.id);S(null),I(!0);try{const a=await u("/api/workspace/v1/messages?scope=mine",{method:"POST",body:JSON.stringify({conversationType:"team",teamId:e.id})});if(!X(t))return;const n=a?.data?.conversation;if(!n?.id)throw new Error("Team chat could not be opened");i?.(n.id)}catch(a){if(!X(t))return;S(a.safeMessage||"Team chat could not be opened.")}finally{X(t)&&I(!1)}};if("all"===d)return t.jsx(Wp,{apiBase:"/api/workspace/v1/teams",scope:"all",canonical:!0,selectedTeamId:a,onDirtyChange:c,onSelectedTeamChange:(e,t={})=>{e?n?.({id:e}):s?.(t)},onOpenMessages:i});if(f||x||j)return t.jsxs("section",{className:"employee-teams-panel employee-teams-panel--detail",children:[N?t.jsx(oc,{type:"error",children:N}):null,C?t.jsx("p",{className:"workspace-inline-error",role:"alert",children:C.safeMessage||"That resource could not be opened."}):null,x?t.jsxs("div",{className:"employee-team-detail employee-team-detail--request",children:[t.jsx(ec,{variant:"ghost",disabled:k,onClick:ee,children:k?"Returning to teamsâ¦":"Back to teams"}),t.jsx(bc,{loading:!0,loadingLabel:"Opening teamâ¦"})]}):null,j?t.jsx("div",{className:"employee-team-detail employee-team-detail--request",children:t.jsxs(oc,{type:"error",children:[j,t.jsx(ec,{variant:"ghost",disabled:k,onClick:ee,children:k?"Returning to teamsâ¦":"Back to teams"})]})}):null,f?t.jsx(Pp,{detail:f,headingRef:$,onClose:ee,onOpenProject:r,onOpenConversation:i,onStartConversation:ae,onOpenResource:te,onNavigateActivity:l,conversationLoading:E,openingResourceId:_,closePending:k}):null]});const ne=Number(Boolean(h))+Number(Boolean(p)),se=()=>{m(""),g("")};return t.jsxs("section",{className:"employee-teams-panel",children:[t.jsxs(sc,{label:"Team filters",resultCount:(q?.teams||[]).length,activeFilterCount:ne,onClear:se,children:[t.jsxs("label",{children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{value:h,onChange:e=>m(e.target.value),placeholder:"Search teams","aria-label":"Search teams"})]}),t.jsx("select",{value:p,onChange:e=>g(e.target.value),"aria-label":"Membership role",children:Vp.map(e=>t.jsx("option",{value:e,children:e?Sc(e):"All roles"},e))})]}),t.jsxs(bc,{loading:B&&!q?.teams?.length,error:W,isEmpty:!(q?.teams||[]).length,loadingLabel:"Loading teamsâ¦",errorLabel:"Teams could not be loaded",emptyLabel:ne?"No teams match these filters.":"No teams found.",emptyDescription:ne?"Clear filters to return to your teams.":null,emptyType:ne?"no-results":"empty",emptyAction:ne?t.jsx(ec,{variant:"ghost",onClick:se,children:"Clear filters"}):null,onRetry:V,children:[t.jsx("div",{ref:M,className:"employee-team-record-list",children:(q?.teams||[]).map(e=>t.jsx(Dp,{team:e,onSelect:Z,onOpenConversation:i},e.id))}),H&&!J?t.jsx("div",{className:"employee-team-pagination",children:t.jsx(ec,{variant:"secondary",onClick:K,disabled:G,children:G?"Loading moreâ¦":"Load more teams"})}):null,J?t.jsxs(oc,{type:"error",children:[J.safeMessage||"More teams could not be loaded.",t.jsx(ec,{variant:"ghost",onClick:K,disabled:G,children:"Try again"})]}):null]})]})}const Kp=new Set(["awaiting_discovery_approval","discovery_approved","file_selected","awaiting_file_approval","approved","artifact_creating","available","viewed"]),Gp={targetUserId:"",caseReference:"",reasonCategory:"security_incident",reason:"",requestedDurationSeconds:1800,notificationPolicy:"immediate",notificationDelayReason:"",notifyAfter:""};function Jp({request:e}){return t.jsxs("dl",{className:"jupyter-break-glass-evidence",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Requester"}),t.jsx("dd",{children:e.requester.name||"Qualified security requester"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Discovery approver"}),t.jsx("dd",{children:e.discoveryApprover?.name||"Awaiting independent approval"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Exact-file approver"}),t.jsx("dd",{children:e.approver?.name||"Awaiting independent approval"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Owner notice"}),t.jsx("dd",{children:e.notifiedAt?`Delivered ${wc(e.notifiedAt,"")}
2`:"delayed"===e.notificationPolicy?"Approved delay pending delivery":"Delivered when approval commits"})]})]})}function Yp({targetUsers:e=[]}){const{makeAuthRequest:n,user:s}=Yn(),r=kc("/api/workspace/v1/jupyter/admin-access/requests?scope=all",{initialData:null}),[i,l]=a.useState(Gp),[o,c]=a.useState(!1),[d,u]=a.useState(null),[h,m]=a.useState(null),[p,g]=a.useState(null),[f,b]=a.useState({}),x=r.data?.capabilities;if(!x)return null;const v=x.canRequestNotebookBreakGlass,j=x.canApproveNotebookBreakGlass;if(!v&&!j)return null;const y=async(e,t,a={},s=null)=>{u(e),g(null),m(null);try{const e=await n(t,a);return await r.refresh(),s&&m(s),e.data}catch(i){return g(i.safeMessage||i.message||"Private notebook access failed safely."),null}finally{u(null)}},k=async e=>{const t=await y(`view-${e.id}`,`/api/workspace/v1/jupyter/admin-access/artifacts/${e.artifact.id}/view-grants?scope=all`,{method:"POST",body:JSON.stringify({})});t&&function(e){const t=document.createElement("form"),a=document.createElement("input");t.method="POST",t.action=e.viewerUrl,t.target="_blank",t.hidden=!0,a.type="hidden",a.name=e.fieldName,a.value=e.grant,t.append(a),document.body.append(t),t.submit(),t.remove()}(t)},w=r.data?.requests||[];return t.jsxs("section",{className:"jupyter-break-glass","aria-labelledby":"jupyter-break-glass-title",children:[t.jsxs("div",{className:"employee-section-heading",children:[t.jsxs("div",{children:[t.jsx("h3",{id:"jupyter-break-glass-title",children:"Break-glass requests"}),t.jsx("p",{children:"Exceptional one-file inspection only. It never opens a private home, live server, terminal, kernel, or unrestricted download."})]}),t.jsx(ec,{variant:"ghost",onClick:r.refresh,disabled:r.loading,children:"Refresh queue"})]}),t.jsxs("div",{className:"jupyter-break-glass-warning",role:"note",children:[t.jsx("strong",{children:"Private-content warning"}),t.jsx("p",{children:"Notebook code and saved output may contain personal or confidential information. Every name disclosure, approval, view, notice, expiry, and destruction is recorded."})]}),p?t.jsx(oc,{type:"error",children:p}):null,h?t.jsx(oc,{type:"success",children:h}):null,v?t.jsx("form",{className:"jupyter-break-glass-form",onSubmit:async e=>{if(e.preventDefault(),!o)return;const t={targetUserId:i.targetUserId,caseReference:i.caseReference,reasonCategory:i.reasonCategory,reason:i.reason,requestedDurationSeconds:Number(i.requestedDurationSeconds),notificationPolicy:i.notificationPolicy,..."delayed"===i.notificationPolicy?{notificationDelayReason:i.notificationDelayReason,notifyAfter:new Date(i.notifyAfter).toISOString()}:{}};await y("create","/api/workspace/v1/jupyter/admin-access/requests?scope=all",{method:"POST",body:JSON.stringify(t)},"Break-glass request recorded. A different qualified person must approve discovery.")&&(l(Gp),c(!1))},children:t.jsxs("fieldset",{children:[t.jsx("legend",{children:"Request one private notebook"}),t.jsxs("label",{children:["Target user",t.jsxs("select",{required:!0,value:i.targetUserId,onChange:e=>l({...i,targetUserId:e.target.value}),children:[t.jsx("option",{value:"",children:"Select one person"}),e.filter(e=>e.userId!==s?.id).map(e=>t.jsx("option",{value:e.userId,children:e.person.name||"Unnamed user"},e.userId))]})]}),t.jsxs("label",{children:["Case reference",t.jsx("input",{required:!0,minLength:"3",maxLength:"160",value:i.caseReference,onChange:e=>l({...i,caseReference:e.target.value})})]}),t.jsxs("label",{children:["Reason category",t.jsxs("select",{value:i.reasonCategory,onChange:e=>l({...i,reasonCategory:e.target.value}),children:[t.jsx("option",{value:"security_incident",children:"Security incident"}),t.jsx("option",{value:"legal",children:"Legal"}),t.jsx("option",{value:"compliance",children:"Compliance"}),t.jsx("option",{value:"support",children:"Support"})]})]}),t.jsxs("label",{children:["Protected reason",t.jsx("textarea",{required:!0,minLength:"20",maxLength:"4000",value:i.reason,onChange:e=>l({...i,reason:e.target.value})})]}),t.jsxs("label",{children:["Viewer duration",t.jsxs("select",{value:i.requestedDurationSeconds,onChange:e=>l({...i,requestedDurationSeconds:Number(e.target.value)}),children:[t.jsx("option",{value:"300",children:"5 minutes"}),t.jsx("option",{value:"900",children:"15 minutes"}),t.jsx("option",{value:"1800",children:"30 minutes (default and maximum)"})]})]}),t.jsxs("label",{children:["Owner notification",t.jsxs("select",{value:i.notificationPolicy,onChange:e=>l({...i,notificationPolicy:e.target.value}),children:[t.jsx("option",{value:"immediate",children:"Immediate (default)"}),x.canDelayBreakGlassNotification?t.jsx("option",{value:"delayed",children:"Delayed â separate approval required"}):null]})]}),"delayed"===i.notificationPolicy?t.jsxs(t.Fragment,{children:[t.jsxs("label",{children:["Notification-delay reason",t.jsx("textarea",{required:!0,minLength:"20",maxLength:"2000",value:i.notificationDelayReason,onChange:e=>l({...i,notificationDelayReason:e.target.value})})]}),t.jsxs("label",{children:["Notify owner by",t.jsx("input",{required:!0,type:"datetime-local",value:i.notifyAfter,onChange:e=>l({...i,notifyAfter:e.target.value})})]})]}):null,t.jsxs("label",{className:"jupyter-break-glass-acknowledgement",children:[t.jsx("input",{type:"checkbox",checked:o,onChange:e=>c(e.target.checked)}),t.jsx("span",{children:"I acknowledge this request is exceptional, limited to one approved .ipynb file, owner-notified, time-limited, and durably audited."})]}),t.jsx(ec,{variant:"primary",type:"submit",disabled:!o||"create"===d,children:"Submit break-glass request"})]})}):null,t.jsxs("div",{className:"jupyter-break-glass-queue","aria-live":"polite",children:[t.jsx("h4",{children:"Approval queue"}),w.length?null:t.jsx("p",{children:"No break-glass requests."}),w.map(e=>{const a=e.requester.id===s?.id,n=!a,r=f[e.id]||[];return t.jsxs(Qo,{className:"jupyter-break-glass-request",children:[t.jsxs("div",{className:"jupyter-publication-heading",children:[t.jsxs("div",{children:[t.jsx("h5",{children:e.caseReference}),t.jsxs("p",{children:[e.target.name||"Target user"," ·"," ",Sc(e.reasonCategory)," · one .ipynb"]})]}),t.jsx("strong",{children:Sc(e.state)})]}),t.jsx(Jp,{request:e}),"discovery_approved"!==e.state||r.length?null:t.jsx("p",{children:"Private notebook
2names remain hidden until the requester discloses them."}),r.length?t.jsx("ul",{className:"jupyter-break-glass-notebooks","aria-label":"Approved notebook names",children:r.map(n=>t.jsxs("li",{children:[t.jsxs("span",{children:[t.jsx("strong",{children:n.displayFilename}),t.jsx("small",{children:Nc(n.sizeBytes)})]}),t.jsx(ec,{size:"compact",disabled:!a||d===`select-${e.id}`,onClick:()=>y(`select-${e.id}`,`/api/workspace/v1/jupyter/admin-access/requests/${e.id}/select-file?scope=all`,{method:"POST",body:JSON.stringify({fileLocator:n.fileLocator})},"One exact notebook selected. Independent file approval is required."),children:"Select exact file"})]},n.fileLocator))}):null,t.jsxs("div",{className:"jupyter-row-actions",children:[j&&n&&"awaiting_discovery_approval"===e.state?t.jsx(ec,{size:"compact",variant:"primary",onClick:()=>y(`approve-discovery-${e.id}`,`/api/workspace/v1/jupyter/admin-access/requests/${e.id}/approve-discovery?scope=all`,{method:"POST",body:JSON.stringify({})},"Private-name discovery approved."),children:"Approve name discovery"}):null,v&&a&&"discovery_approved"===e.state?t.jsx(ec,{size:"compact",variant:"primary",onClick:()=>(async e=>{const t=await y(`discovery-${e}`,`/api/workspace/v1/jupyter/admin-access/requests/${e}/notebooks?scope=all`);t&&(b(a=>({...a,[e]:t.entries||[]})),m("Approved notebook names disclosed and durably audited."))})(e.id),disabled:d===`discovery-${e.id}`,children:"Reveal approved notebook names"}):null,x.canDelayBreakGlassNotification&&n&&"delayed"===e.notificationPolicy&&!e.notificationDelayApproved&&Kp.has(e.state)?t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>y(`approve-delay-${e.id}`,`/api/workspace/v1/jupyter/admin-access/requests/${e.id}/approve-notification-delay?scope=all`,{method:"POST",body:JSON.stringify({})},"Notification delay independently approved."),children:"Approve notification delay"}):null,j&&n&&["file_selected","awaiting_file_approval"].includes(e.state)?t.jsx(ec,{size:"compact",variant:"primary",onClick:()=>y(`approve-file-${e.id}`,`/api/workspace/v1/jupyter/admin-access/requests/${e.id}/approve?scope=all`,{method:"POST",body:JSON.stringify({})},"One exact notebook approved."),children:"Approve exact file"}):null,v&&a&&"approved"===e.state?t.jsx(ec,{size:"compact",variant:"primary",onClick:()=>y(`artifact-${e.id}`,`/api/workspace/v1/jupyter/admin-access/requests/${e.id}/artifacts?scope=all`,{method:"POST",body:JSON.stringify({})},"Isolated read-only artifact verified."),children:"Prepare isolated viewer"}):null,v&&a&&e.artifact&&["available","viewed"].includes(e.state)?t.jsx(ec,{size:"compact",variant:"primary",onClick:()=>k(e),disabled:d===`view-${e.id}`,children:"Open sanitized one-use viewer"}):null,j&&n&&["awaiting_discovery_approval","discovery_approved","file_selected"].includes(e.state)?t.jsx(ec,{size:"compact",variant:"danger",onClick:()=>y(`deny-${e.id}`,`/api/workspace/v1/jupyter/admin-access/requests/${e.id}/deny?scope=all`,{method:"POST",body:JSON.stringify({})},"Break-glass request denied."),children:"Deny"}):null,a&&Kp.has(e.state)?t.jsx(ec,{size:"compact",variant:"danger",onClick:()=>y(`cancel-${e.id}`,`/api/workspace/v1/jupyter/admin-access/requests/${e.id}/cancel?scope=all`,{method:"POST",body:JSON.stringify({})},"Break-glass access cancelled; destruction is scheduled."),children:"Cancel access"}):null]})]},e.id)})]})]})}function Qp(e){return{disabled:"Access disabled",stopped:"Stopped",starting:"Starting",running:"Running",stopping:"Stopping",unavailable:"Temporarily unavailable",error:"Error"}[e]||Sc(e)}const Xp=[15*1024**3],Zp=[["accounts","Accounts"],["publications","Published notebooks"],["private-access","Private access"],["audit","Audit"]];function eg({audience:e}){return`${e?.people?.length||0} people · ${e?.teams?.length||0}
2 teams · ${e?.projects?.length||0} projects`}function tg(){const{makeAuthRequest:e}=Yn(),{data:n,loading:s,error:r,refresh:i}=kc("/api/workspace/v1/jupyter/users?scope=all",{initialData:{users:[],overview:null}}),[l,o]=a.useState(null),[c,d]=a.useState(null),[u,h]=a.useState("accounts"),[m,p]=a.useState(null),g=a.useRef(null),f=a.useId(),b=kc("audit"===u?"/api/workspace/v1/jupyter/audit?scope=all":null,{initialData:{events:[]}}),x=kc("/api/workspace/v1/jupyter/publications?scope=all",{initialData:{publications:[],overview:null}}),v=async(t,a,n,s="POST")=>{d(t),o(null);try{await e(a,{method:s,body:JSON.stringify(n)}),await i(),"audit"===u&&await b.refresh()}catch(r){o(r.safeMessage||r.message||"Jupyter control failed.")}finally{d(null)}},j=n?.overview||{},y=(n?.users||[]).find(e=>e.userId===m);return t.jsx(bc,{loading:s&&!n,error:r,loadingLabel:"Loading Jupyter oversightâ¦",errorLabel:"Jupyter oversight could not be loaded",onRetry:i,children:t.jsxs("section",{className:"employee-panel jupyter-workspace jupyter-admin"+(y?" is-user-open":""),"aria-labelledby":"jupyter-admin-title",children:[t.jsx(Yo,{className:"jupyter-admin-boundary",children:t.jsxs("div",{className:"employee-section-heading",children:[t.jsxs("div",{children:[t.jsx("h2",{id:"jupyter-admin-title",children:"Jupyter oversight"}),t.jsx("p",{children:"Private notebook names and contents are not available in normal oversight. Published immutable resources and lifecycle metadata are available below."})]}),t.jsx(tc,{value:n?.hubAvailable?"ready":"paused",label:n?.hubAvailable?"Hub verified":"Hub unverified"})]})}),t.jsx("nav",{ref:g,className:"jupyter-tabs jupyter-admin-tabs","aria-label":"Jupyter oversight sections",role:"tablist",children:Zp.map(([e,a])=>t.jsx("button",{type:"button",role:"tab",id:`${f}-${e}-tab`,"aria-selected":u===e,"aria-controls":`${f}-${e}-panel`,tabIndex:u===e?0:-1,onClick:()=>{h(e),p(null)},onKeyDown:t=>((e,t)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;e.preventDefault();const a=Zp.findIndex(([e])=>e===t),n="Home"===e.key?0:"End"===e.key?Zp.length-1:(a+("ArrowRight"===e.key?1:-1)+Zp.length)%Zp.length;h(Zp[n][0]),window.requestAnimationFrame(()=>g.current?.querySelectorAll('[role="tab"]')[n]?.focus())})(t,e),children:a},e))}),l?t.jsx(oc,{type:"error",children:l}):null,"accounts"===u?t.jsxs("section",{className:"jupyter-admin-tabpanel",role:"tabpanel",id:`${f}-accounts-panel`,"aria-labelledby":`${f}-accounts-tab`,children:[t.jsx(Zo,{label:"Jupyter oversight summary",items:[{label:"Enabled",value:j.enabledCount,tone:"active"},{label:"Running",value:j.running,tone:"success"},{label:"Starting",value:j.starting,tone:"warning"},{label:"Stopped",value:j.stopped},{label:"Errors",value:j.errors,tone:j.errors?"danger":null},{label:"Capacity",value:j.capacity?.activeServerLimit},{label:"Published",value:j.publications?.published},{label:"Shared",value:j.publications?.shared}]}),n?.hubAvailable?null:t.jsx(oc,{children:"Live Hub state, capacity, and backup health are currently unverified."}),t.jsxs("div",{className:"jupyter-admin-account-layout",children:[t.jsx(Yo,{className:"jupyter-admin-account-list",title:"Jupyter accounts",description:"Open a person to manage lifecycle metadata and approved controls.",children:t.jsx(uc,{label:"Jupyter users",children:(n?.users||[]).map(e=>t.jsxs(Qo,{as:"button",type:"button",interactive:!0,"aria-current":m===e.userId?"true":void 0,onClick:()=>p(e.userId),children:[t.jsx(I,{size:18,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:e.person.name||"Unnamed"}),t.jsxs("small",{children:[e.enabled?"Enabled":"Disabled"," ·"," ",Qp(e.serverState)]})]}),t.jsx(tc,{value:e.serverState,label:Qp(e.serverState)})]},e.userId))})}),y?t.jsx(ag,{account:y,busy:c===y.userId,onBack:()=>p(null),onMutate:v,onReasonedAction:(e,t)=>{const a=window.prompt(`Reason to ${t} ${e.person.name||"this user"}:`);a?.trim()&&("disable"!==t?v(e.userId,`/api/workspace/v1/jupyter/users/${e.userId}/${t}?scope=all`,{reason:a.trim()}):v(e.userId,`/api/workspace/v1/jupyter/users/${e.userId}?scope=all`,{enabled:!1,reason:a.trim()},"PATCH"))}}):t.jsx(Yo,{className:"jupyter-admin-account-empty",title:"Select an account",description:"Choose a person to review safe lifecycle metadata and controls."})]})]}):null,"publications"===u?t.jsx(ng,{tabsId:f,source:x}):null,"private-access"===u?t.jsx("section",{className:"jupyter-admin-tabpanel",role:"tabpanel",id:`${f}-private-access-panel`,"aria-labelledby":`${f}-private-access-tab`,children:t.jsx(Yp,{targetUsers:n?.users||[]})}):null,"audit"===u?t.jsx("section",{className:"jupyter-admin-tabpanel",role:"tabpanel",id:`${f}-audit-panel`,"aria-labelledby":`${f}-audit-tab`,children:t.jsx(bc,{loading:b.loading,error:b.error,isEmpty:!(b.data?.events||[]).length,emptyLabel:"No Jupyter audit events yet.",onRetry:b.refresh,children:t.jsx(Yo,{title:"Jupyter audit",children:t.jsx("ul",{className:"jupyter-audit-list",children:(b.data?.events||[]).map(e=>t.jsxs("li",{children:[t.jsx("strong",{children:Sc(e.eventType)})," ",t.jsx("span",{children:wc(e.createdAt,"")})]},e.id))})})})}):null]})})}function ag({account:e,busy:a,onBack:n,onMutate:s,onReasonedAction:r}){return t.jsxs(Yo,{className:"jupyter-admin-account-detail",title:e.person.name||"Jupyter account",description:"Account state and lifecycle c
2ontrols only; private content remains unavailable.",actions:t.jsxs(ec,{variant:"ghost",onClick:n,children:[t.jsx(G,{size:16,"aria-hidden":"true"})," Back to accounts"]}),children:[t.jsx(Zo,{label:`Jupyter status for ${e.person.name||"selected user"}`,items:[{label:"Access",value:e.enabled?"Enabled":"Disabled"},{label:"Server",value:Qp(e.serverState)},{label:"Last active",value:wc(e.lastActiveAt,"None")},{label:"Published",value:e.publishedPublicationCount},{label:"Shared",value:e.sharedPublicationCount}]}),t.jsxs(Xo,{className:"jupyter-admin-account-controls",children:[t.jsxs("label",{children:[t.jsx("span",{children:"Compute profile"}),t.jsx("select",{"aria-label":`Compute profile for ${e.person.name||"user"}`,value:e.computeProfile,disabled:a,onChange:t=>s(e.userId,`/api/workspace/v1/jupyter/users/${e.userId}?scope=all`,{computeProfile:t.target.value},"PATCH"),children:t.jsx("option",{value:"standard",children:"Standard"})})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Storage quota"}),t.jsxs("select",{"aria-label":`Storage quota for ${e.person.name||"user"}`,value:e.storageQuotaBytes||"",disabled:a,onChange:t=>s(e.userId,`/api/workspace/v1/jupyter/users/${e.userId}?scope=all`,{storageQuotaBytes:Number(t.target.value)},"PATCH"),children:[e.storageQuotaBytes?null:t.jsx("option",{value:"",children:"Unverified"}),[...new Set([e.storageQuotaBytes,...Xp].filter(Boolean))].sort((e,t)=>e-t).map(e=>t.jsx("option",{value:e,children:Nc(e)},e))]})]}),t.jsxs("div",{className:"jupyter-row-actions",children:[e.enabled?t.jsx(ec,{size:"compact",variant:"danger",onClick:()=>r(e,"disable"),disabled:a,children:"Disable"}):t.jsx(ec,{size:"compact",variant:"primary",onClick:()=>s(e.userId,`/api/workspace/v1/jupyter/users/${e.userId}?scope=all`,{enabled:!0},"PATCH"),disabled:a,children:"Enable"}),t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>r(e,"stop"),disabled:a,children:"Stop"}),t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>r(e,"restart"),disabled:a||!e.enabled,children:"Restart"})]})]})]})}function ng({tabsId:e,source:a}){return t.jsx("section",{className:"jupyter-admin-tabpanel",role:"tabpanel",id:`${e}-publications-panel`,"aria-labelledby":`${e}-publications-tab`,children:t.jsxs(Yo,{title:"Published notebook oversight",description:"Deliberately published Workspace resources only. Private Jupyter homes are not scanned or indexed.",children:[t.jsx(Zo,{label:"Published notebook summary",items:[{label:"Publications",value:a.data?.overview?.publicationCount},{label:"Active",value:a.data?.overview?.activePublicationCount,tone:"success"},{label:"Shared",value:a.data?.overview?.sharedPublicationCount,tone:"active"}]}),t.jsx(bc,{loading:a.loading,error:a.error,isEmpty:!(a.data?.publications||[]).length,emptyLabel:"No published notebooks are available for oversight.",onRetry:a.refresh,children:t.jsx(uc,{label:"Published notebook records",className:"jupyter-publication-list",children:(a.data?.publications||[]).map(e=>t.jsxs(Qo,{className:"jupyter-publication",children:[t.jsxs("div",{className:"jupyter-publication-heading",children:[t.jsxs("div",{children:[t.jsx("h4",{children:e.title}),t.jsx("p",{children:e.description||"No description"})]}),t.jsx(tc,{value:e.state})]}),t.jsxs("dl",{children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Owner"}),t.jsx("dd",{children:e.owner.name})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Published file"}),t.jsx("dd",{children:e.currentVersion.sourceDisplayFilename})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Version evidence"}),t.jsxs("dd",{children:[e.versionCount," versions ·"," ",Nc(e.currentVersion.sizeBytes)]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Current audience"}),t.jsx("dd",{children:t.jsx(eg,{audience:e.audience})})]})]}),t.jsx("div",{className:"jupyter-row-actions",children:t.jsx(ec,{as:"a",size:"compact",variant:"secondary",href:`?section=resources&scope=all&resourceId=${e.currentVersion.resourceId}`,children:"Open published Resource details"})})]},e.id))})})]})})}const sg=[["workspace","My workspace"],["published","Published by me"],["shared","Shared with me"],["project","Project notebooks"]];function rg({people:e,teams:t,projects:a}){return{userIds:e.map(e=>e.userId),teamIds:t.map(e=>e.teamId),projectIds:a.map(e=>e.projectId||e.id)}}
2function ig({audience:e}){const a=[...(e?.people||[]).map(e=>e.name),...(e?.teams||[]).map(e=>`Team: ${e.name}`),...(e?.projects||[]).map(e=>`Project: ${e.name}`)];return t.jsx("span",{children:a.length?a.join(" · "):"No current recipients"})}function lg({access:e}){const a=[...e?.sharedDirectly?["Shared directly"]:[],...(e?.teams||[]).map(e=>`Team: ${e.name}`),...(e?.projects||[]).map(e=>`Project: ${e.name}`)];return t.jsx("span",{children:a.length?a.join(" · "):"Access unavailable"})}function og({publication:e,onClose:a,onDownload:n,importEnabled:s}){return e?t.jsxs("section",{className:"jupyter-version-history","aria-labelledby":"version-history-title",children:[t.jsxs("div",{className:"jupyter-publication-heading",children:[t.jsxs("h4",{id:"version-history-title",children:["Version history: ",e.title]}),t.jsx(ec,{variant:"secondary",size:"compact",onClick:a,children:"Close history"})]}),t.jsx("ol",{children:(e.versions||[]).map(e=>t.jsxs("li",{children:[t.jsxs("div",{children:[t.jsxs("strong",{children:["v",e.versionNumber," ",e.current?"(current)":""]}),t.jsxs("span",{children:[wc(e.publishedAt,"Unknown")," · ",e.publisher.name," ·"," ",Nc(e.sizeBytes)," · SHA-256 ",e.sha256.slice(0,12),"â¦"]})]}),t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>n(e),children:"Download immutable snapshot"}),t.jsx(lh,{enabled:s,versionId:e.id,sourceFilename:e.sourceDisplayFilename})]},e.id))})]}):null}function cg({source:e,emptyLabel:a,onHistory:n,onDownload:s,importEnabled:r}){return t.jsx(bc,{loading:e.loading,error:e.error,isEmpty:!e.data?.publications?.length,emptyLabel:a,onRetry:e.refresh,children:t.jsx("div",{className:"jupyter-publication-list",children:(e.data?.publications||[]).map(e=>t.jsxs(Qo,{className:"jupyter-publication",children:[t.jsxs("div",{className:"jupyter-publication-heading",children:[t.jsxs("div",{children:[t.jsx("h4",{children:e.title}),t.jsx("p",{children:e.description||"No description"})]}),t.jsxs("strong",{children:["v",e.currentVersion.versionNumber," current"]})]}),t.jsxs("dl",{children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Shared by"}),t.jsx("dd",{children:e.owner.name})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Published"}),t.jsx("dd",{children:wc(e.currentVersion.publishedAt,"Unknown")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Access through"}),t.jsx("dd",{children:t.jsx(lg,{access:e.access})})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Versions"}),t.jsx("dd",{children:e.versionCount})]})]}),t.jsxs("div",{className:"jupyter-row-actions",children:[t.jsx(ec,{as:"a",size:"compact",variant:"secondary",href:`?section=resources&resourceId=${e.currentVersion.resourceId}`,children:"Open Resource details"}),t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>s(e.currentVersion),children:"Download current snapshot"}),t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>n(e),children:"View version history"}),t.jsx(lh,{enabled:r,versionId:e.currentVersion.id,sourceFilename:e.currentVersion.sourceDisplayFilename})]})]},e.id))})})}function dg({jupyterEnabled:e,notebookImportEnabled:n}){const{makeAuthRequest:s}=Yn(),[r,i]=a.useState("workspace"),[l,o]=a.useState([]),[c,d]=a.useState(null),[u,h]=a.useState([{label:"My notebooks"}]),[m,p]=a.useState(!1),[g,f]=a.useState(null),[b,x]=a.useState(null),[v,j]=a.useState(null),[y,k]=a.useState(""),[w,N]=a.useState(""),[S,C]=a.useState([]),[R,E]=a.useState([]),[I,_]=a.useState([]),[T,A]=a.useState(!1),[O,D]=a.useState(!1),[P,L]=a.useState(null),[$,M]=a.useState(null),[U,F]=a.useState(null),[z,q]=a.useState(null),B=kc("/api/employee/jupyter/publications?view=published-by-me",{initialData:{publications:[]}}),W=kc("/api/employee/jupyter/publications?view=shared-with-me",{initialData:{publications:[]}}),V=kc("/api/employee/jupyter/publications?view=project",{initialData:{publications:[]}}),H=async({directoryToken:e=null,cursor:t=null,append:a=!1}={})=>{p(!0),f(null);try{const n=new URLSearchParams({pageSize:"50"});e&&n.set("directoryToken",e),t&&n.set("cursor",t);const r=await s(`/api/employee/jupyter/notebooks?${n}`);o(e=>a?[...e,...r.data?.entries||[]]:r.data?.entries||[]),d(r.data?.nextCursor||null)}catch(n){f(n.safeMessage||n.message||"Your notebooks could not be listed.")}finally{p(!1)}},K=()=>{x(null),j(null),k(""),N(""),C([]),E([]),_([]),A(!1)},G=async e=>{L(null);try{const t=await s(`/api/employee/jupyter/publications/${e.id}`);F(t.data?.publication||null)}catch(t){L(t.safeMessage||t.message||"Version history is unavailable.")}},J=async e=>{L(null);try{const t=await s(`/api/employee/jupyter/versions/${e.id}/access`,{method:"POST",body:JSON.stringify({})}),a=new URL(t.data?.access?.url);if("https:"!==a.protocol)throw new Error("The notebook URL was invali
2d.");window.open(a.toString(),"_blank","noopener,noreferrer")}catch(t){L(t.safeMessage||t.message||"The notebook could not be downloaded.")}},Y=S.length+R.length+I.length>0,Q=b&&T&&(v||y.trim()&&Y);return t.jsxs(Yo,{className:"jupyter-sharing-card",children:[t.jsx("div",{className:"jupyter-sharing-heading",children:t.jsxs("div",{children:[t.jsx("h3",{children:"Notebook sharing"}),t.jsx("p",{children:"Private by default. Only immutable snapshots you deliberately publish are shared."})]})}),t.jsx("nav",{className:"jupyter-tabs","aria-label":"Jupyter notebook views",role:"tablist",children:sg.map(([e,a])=>t.jsx("button",{type:"button",role:"tab","aria-selected":r===e,tabIndex:r===e?0:-1,"aria-controls":`jupyter-${e}-panel`,id:`jupyter-${e}-tab`,onClick:()=>i(e),onKeyDown:t=>((e,t)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;e.preventDefault();const a=sg.findIndex(([e])=>e===t),n="Home"===e.key?0:"End"===e.key?sg.length-1:(a+("ArrowRight"===e.key?1:-1)+sg.length)%sg.length,s=sg[n][0];i(s),window.requestAnimationFrame(()=>document.getElementById(`jupyter-${s}-tab`)?.focus())})(t,e),children:a},e))}),P?t.jsx(oc,{type:"error",children:P}):null,$?t.jsx(oc,{type:"success",children:$}):null,"workspace"===r?t.jsxs("section",{role:"tabpanel",id:"jupyter-workspace-panel","aria-labelledby":"jupyter-workspace-tab",className:"jupyter-tab-panel",children:[t.jsxs("div",{className:"jupyter-browser-heading",children:[t.jsxs("div",{children:[t.jsx("h4",{children:v?`New version of ${v.title}`:"My notebooks"}),t.jsx("p",{children:"Only safe directories and .ipynb files in your own Jupyter home are listed."})]}),t.jsx(ec,{variant:"secondary",onClick:async()=>{h([{label:"My notebooks"}]),x(null),await H()},disabled:m||!e,children:"Browse my notebooks"})]}),l.length||u.length>1?t.jsxs("div",{className:"jupyter-browser","aria-label":"My Jupyter notebooks",children:[t.jsxs("div",{className:"jupyter-browser-path",children:[u.length>1?t.jsx(ec,{variant:"ghost",size:"compact",onClick:async()=>{const e=u.slice(0,-1),t=e.at(-1);h(e),x(null),await H({directoryToken:t?.directoryToken||null})},disabled:m,children:"Back"}):null,t.jsx("span",{children:u.map(e=>e.label).join(" / ")})]}),t.jsx("ul",{className:"jupyter-browser-list",children:l.map(e=>t.jsx("li",{children:t.jsxs("button",{type:"button",className:b?.sourceToken===e.sourceToken?"selected":"",onClick:()=>"directory"===e.kind?(async e=>{x(null),h(t=>[...t,{label:e.displayFilename,directoryToken:e.sourceToken}]),await H({directoryToken:e.sourceToken})})(e):(e=>{x(e),k(t=>t||e.displayFilename.replace(/\.ipynb$/iu,"")),L(null),M(null)})(e),children:[t.jsxs("span",{children:[t.jsxs("strong",{children:["directory"===e.kind?"Folder: ":"Notebook: ",e.displayFilename]}),t.jsx("small",{children:e.displayPath})]}),t.jsxs("span",{children:["file"===e.kind?Nc(e.sizeBytes):"Directory"," ·"," ",wc(new Date(1e3*e.modifiedAt).toISOString(),"Unknown")]})]})},`${e.kind}:${e.sourceToken}`))}),c?t.jsx(ec,{variant:"secondary",onClick:()=>H({cursor:c,append:!0}),disabled:m,children:"Load more"}):null]}):null,m?t.jsx("p",{role:"status",children:"Loading your notebooksâ¦"}):null,g?t.jsx("p",{className:"employee-error",role:"alert",children:g}):null,b?t.jsxs(Xo,{as:"form",className:"jupyter-snapshot-form",onSubmit:async e=>{e.preventDefault(),D(!0),L(null),M(null);try{const e=Boolean(v),t=e?`/api/employee/jupyter/publications/${v.id}/versions`:"/api/employee/jupyter/publications",a=e?{sourceToken:b.sourceToken}:{sourceToken:b.sourceToken,title:y,description:w,...rg({people:S,teams:R,projects:I})};await s(t,{method:"POST",headers:{"Idempotency-Key":crypto.randomUUID()},body:JSON.stringify(a)}),M(e?"New immutable version published.":"Notebook published."),K(),await B.refresh(),i("published")}catch(t){L(t.safeMessage||t.message||"The notebook could not be published.")}finally{D(!1)}},children:[t.jsx("h4",{children:v?"Publish new version":"Publish immutable snapshot"}),t.jsxs("p",{children:["Selected notebook: ",t.jsx("strong",{children:b.displayFilename})]}),v?null:t.jsxs(t.Fragment,{children:[t.jsxs("label",{children:[t.jsx("span",{children:"Publication title"}),t.jsx("input",{value:y,onChange:e=>k(e.target.value),maxLength:240,required:!0})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Description (optional)"}),t.jsx("textarea",{value:w,onChange:e=>N(e.target.value),maxLength:1e4})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:"Share with people, teams, or projects"}),t.jsx(ah,{label:"People",value:S,onChange:C,endpoint:"/api/workspace/v1/people?scope=mine"}),t.jsx(th,{label:"Teams",value:R,onChange:E,endpoint:"/api/workspace/v1/teams?scope=mine"}),t.jsx(eh,{label:"Projects",value:I,onChange:_,multiple:!0,endpoint:"/api/workspace/v1/projects?scope=mine"})]})]}),t.jsxs("div",{className:"jupyter-snapshot-warning",role:"note",children:[t.jsx("strong",{children:"Review before publishing."}),t.jsx("p",{children:"This immutable snapshot includes notebook code and saved outputs. It may contain credentials or internal data. Recipients can download or import independent copies; revocation cannot recall copies they already received."})]}),t.jsxs("label",{className:"jupyter-snapshot-acknowledgement",children:[t.jsx("input",{type:"checkbox",checked:T,onChange:e=>A(e.target.checked)}),t.jsx("span",{children:"I reviewed this notebook and understand the immutable-copy warning."})]}),t.jsxs("div",{className:"jupyter-actions",children:[t.jsx(ec,{variant:"primary",type:"submit",disabled:O||!Q,children:O?"Publishingâ¦":v?"Publish new version":"Publish notebook"}),t.jsx(ec,{variant:"ghost",type:"button",onClick:K,children:"Cancel"})]})]}):null]}):null,"published"===r?t.jsxs("section",{role:"tabpanel",id:"jupyter-published-panel","aria-labelledby":"jupyter-published-tab",className:"jupyter-tab-panel",children:[t.jsx(bc,{loading:B.loading,error:B.error,
2isEmpty:!B.data?.publications?.length,emptyLabel:"You have not published a notebook yet.",onRetry:B.refresh,children:t.jsx("div",{className:"jupyter-publication-list",children:(B.data?.publications||[]).map(e=>t.jsxs(Qo,{className:"jupyter-publication",children:[t.jsxs("div",{className:"jupyter-publication-heading",children:[t.jsxs("div",{children:[t.jsx("h4",{children:e.title}),t.jsx("p",{children:e.description||"No description"})]}),t.jsx("strong",{children:"active"===e.state?"Active":"Archived"})]}),t.jsxs("dl",{children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Current version"}),t.jsxs("dd",{children:["v",e.currentVersion.versionNumber," (current)"]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Published"}),t.jsx("dd",{children:wc(e.currentVersion.publishedAt,"Unknown")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Versions"}),t.jsx("dd",{children:e.versionCount})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Audience"}),t.jsx("dd",{children:t.jsx(ig,{audience:e.audience})})]})]}),t.jsxs("div",{className:"jupyter-row-actions",children:[t.jsx(ec,{as:"a",size:"compact",variant:"secondary",href:`?section=resources&resourceId=${e.currentVersion.resourceId}`,children:"Open Resource details"}),t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>G(e),children:"View version history"}),"active"===e.state?t.jsxs(t.Fragment,{children:[t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>(e=>{j(e),x(null),o([]),i("workspace"),M("Choose the notebook that will become the next immutable version.")})(e),children:"Publish new version"}),t.jsx(ec,{size:"compact",variant:"secondary",onClick:()=>(e=>{const t=function(e){return{people:(e.audience?.people||[]).map(e=>({userId:e.id,name:e.name,status:e.active?"active":"unavailable"})),teams:(e.audience?.teams||[]).map(e=>({teamId:e.id,name:e.name})),projects:(e.audience?.projects||[]).map(e=>({id:e.id,projectId:e.id,name:e.name,status:e.active?"active":"archived"}))}}(e);C(t.people),E(t.teams),_(t.projects),q(e.id),L(null)})(e),children:"Manage access"}),t.jsx(ec,{size:"compact",variant:"danger",onClick:()=>(async e=>{if(window.confirm(`Archive â${e.title}â and block future access?`)){D(!0),L(null);try{await s(`/api/employee/jupyter/publications/${e.id}/archive`,{method:"POST",headers:{"Idempotency-Key":crypto.randomUUID()},body:JSON.stringify({})}),M("Publication archived."),await B.refresh()}catch(t){L(t.safeMessage||t.message||"The publication was not archived.")}finally{D(!1)}}})(e),children:"Archive"})]}):null]}),z===e.id?t.jsxs("div",{className:"jupyter-manage-audience",children:[t.jsx("p",{children:"Replacing access updates every retained version. Revocation blocks future TokenWorks access, but existing short-lived URLs and downloaded or imported copies cannot be recalled."}),t.jsx(ah,{label:"People",value:S,onChange:C,endpoint:"/api/workspace/v1/people?scope=mine"}),t.jsx(th,{label:"Teams",value:R,onChange:E,endpoint:"/api/workspace/v1/teams?scope=mine"}),t.jsx(eh,{label:"Projects",value:I,onChange:_,multiple:!0,endpoint:"/api/workspace/v1/projects?scope=mine"}),t.jsxs("div",{className:"jupyter-actions",children:[t.jsx(ec,{variant:"primary",onClick:()=>(async e=>{D(!0),L(null);try{await s(`/api/employee/jupyter/publications/${e}/audience`,{method:"PUT",headers:{"Idempotency-Key":crypto.randomUUID()},body:JSON.stringify(rg({people:S,teams:R,projects:I}))}),q(null),C([]),E([]),_([]),M("Publication access updated for every retained version."),await B.refresh()}catch(t){L(t.safeMessage||t.message||"Access could not be updated.")}finally{D(!1)}})(e.id),disabled:O,children:"Save access"}),t.jsx(ec,{variant:"ghost",onClick:()=>q(null),children:"Cancel"})]})]}):null]},e.id))})}),t.jsx(og,{publication:U,onClose:()=>F(null),onDownload:J,importEnabled:!1})]}):null,["shared","project"].includes(r)?t.jsxs("section",{role:"tabpanel",id:`jupyter-${r}-panel`,"aria-labelledby":`jupyter-${r}-tab`,className:"jupyter-tab-panel",children:[t.jsx("h4",{children:"shared"===r?"Shared with me":"Project notebooks"}),t.jsx("p",{children:"Access is checked live through direct, team, and project Resource assignments. Private source paths are never shown."}),t.jsx(cg,{source:"shared"===r?W:V,emptyLabel:"shared"===r?"No notebooks are currently shared with you.":"No notebooks are currently shared through your projects.",onHistory:G,onDownload:J,importEnabled:e&&n}),t.jsx(og,{publication:U,onClose:()=>F(null),onDownload:J,importEnabled:e&&n})]}):null]})}function ug(){const e=window.open("","_blank");return e&&(e.opener=null,e.document.title="Starting Jupyterâ¦",e.document.body.textContent="TokenWorks is preparing your private Jupyter workspaceâ¦"),e}function hg({onStatus:e}){const{makeAuthRequest:n}=Yn(),{data:s,loading:r,error:i,refresh:l}=kc("/api/employee/jupyter/status"),[o,c]=a.useState(null),[d,u]=a.useState(!1),h=a.useRef(null),m=a.useRef(!1);a.useEffect(()=>e?.(s||null),[s,e]),a.useEffect(()=>{if(!["starting","stopping"].includes(s?.state))return;const e=window.setInterval(l,3e3);return()=>window.clearInterval(e)},[s?.state,l]);const p=a.useCallback(async(e=null)=>{if(!m.current){m.current=!0;try{const t=await n("/api/employee/jupyter/launch-grant",{method:"POST",body:JSON.stringify({})}),a=function(e){try{const t=new URL(String(e||""));return"https:"!==t.protocol||t.username||t.password?null:t.toString()}catch{return null}}(t.data?.launchUrl);
2if(!a)throw new Error("Jupyter returned an invalid launch URL.");e&&!e.closed?e.location.replace(a):window.open(a,"_blank","noopener,noreferrer")}catch(t){e&&!e.closed&&e.close(),c(t.safeMessage||t.message||"Jupyter could not be opened.")}finally{h.current=null,m.current=!1}}},[n]);a.useEffect(()=>{"running"===s?.state&&h.current&&p(h.current)},[s?.state,p]);return t.jsx(bc,{loading:r&&!s,error:i,loadingLabel:"Loading Jupyter statusâ¦",errorLabel:"Jupyter is temporarily unavailable",onRetry:l,children:t.jsxs(Yo,{className:"jupyter-status-card",children:[t.jsxs("div",{className:"employee-card-heading",children:[t.jsxs("div",{children:[t.jsx("h2",{id:"jupyter-title",children:"Jupyter Workspace"}),t.jsx("p",{children:"Your private notebook server uses your TokenWorks identity."})]}),t.jsx(tc,{value:s?.state,label:Qp(s?.state)})]}),t.jsx(Zo,{label:"Jupyter workspace status",items:[{label:"Status",value:Qp(s?.state),tone:"active"},{label:"Compute profile",value:Sc(s?.computeProfile)},{label:"Storage",value:`${null===s?.storageUsedBytes?"Usage unavailable":Nc(s?.storageUsedBytes)} / ${s?.storageQuotaBytes?Nc(s.storageQuotaBytes):"Unavailable"}`},{label:"Last active",value:wc(s?.lastActiveAt,"No activity recorded")}]}),o?t.jsx("p",{className:"employee-error",role:"alert",children:o}):null,t.jsxs("div",{className:"jupyter-actions",children:[t.jsx(ec,{variant:"primary",onClick:()=>(async({launch:e=!1}={})=>{c(null);const t=e?ug():null;e&&(h.current=t),u(!0);try{const a=await n("/api/employee/jupyter/start",{method:"POST",body:JSON.stringify({})});"running"===a.data?.state&&e&&await p(t),await l()}catch(a){t&&!t.closed&&t.close(),h.current=null,c(a.safeMessage||a.message||"Jupyter could not be started.")}finally{u(!1)}})({launch:!0}),disabled:d||!s?.canStart,children:"Launch Jupyter"}),t.jsx(ec,{variant:"secondary",onClick:()=>p(ug()),disabled:d||!s?.canLaunch,children:"Open Jupyter"}),t.jsx(ec,{variant:"secondary",onClick:async()=>{c(null),u(!0);try{await n("/api/employee/jupyter/stop",{method:"POST",body:JSON.stringify({})}),await l()}catch(e){c(e.safeMessage||e.message||"Jupyter could not be stopped.")}finally{u(!1)}},disabled:d||!s?.canStop,children:"Stop Server"}),t.jsx(ec,{variant:"ghost",onClick:l,disabled:d||r,children:"Refresh Status"})]})]})})}function mg(){const[e,n]=a.useState(null);return t.jsxs("section",{className:"employee-panel jupyter-workspace","aria-labelledby":"jupyter-title",children:[t.jsx(hg,{onStatus:n}),e?.notebookSharingEnabled?t.jsx(dg,{jupyterEnabled:Boolean(e?.enabled),notebookImportEnabled:Boolean(e?.notebookImportEnabled)}):null]})}function pg({scope:e="mine"}){return"all"===e?t.jsx(tg,{}):t.jsx(mg,{})}function gg(e){return Number(e?.scoreBasisPoints||0)/100+"%"}function fg({assignmentId:e,assignmentStatus:n,quiz:s,makeAuthRequest:r,onAssignmentUpdated:i}){const[l,o]=a.useState(null),[c,d]=a.useState({}),[u,h]=a.useState(null),[m,p]=a.useState({}),[g,f]=a.useState(""),[b,x]=a.useState(!1),v=a.useRef(new Map),j=a.useRef(null),y=s?.attempts?.at(-1)||null,k=["completed","waived","cancelled","superseded"].includes(n),w=async()=>{x(!0),f(""),p({});try{const t=await r(`/api/workspace/v1/onboarding/assignments/${e}/quiz/start`,{method:"POST",body:JSON.stringify({})});o(t.data),d({}),h(null),j.current=null}catch(t){f(t.safeMessage||"Unable to start the quiz right now.")}finally{x(!1)}};if(!s)return null;if(k){const e=s.attempts.find(e=>e.passed);return t.jsxs("div",{className:"onboarding-quiz-state onboarding-quiz-state--passed",children:[t.jsx("strong",{children:e?`Passed with ${gg(e)}`:"Quiz is read-only"}),t.jsx("span",{children:"Your recorded onboarding history remains available for review."})]})}if(!s.available)return t.jsxs("div",{className:"onboarding-quiz-state","aria-live":"polite",children:[t.jsx("strong",{children:"Quiz locked"}),t.jsx("span",{children:"The final quiz unlocks after every required lesson is complete or waived."})]});if(u?.attempt?.passed)return t.jsxs("div",{className:"onboarding-quiz-state onboarding-quiz-state--passed",role:"status",children:[t.jsxs("strong",{children:["Quiz passed · ",gg(u.attempt)]}),t.jsx("span",{children:"Your onboarding assignment is complete."})]});if(!l){const e=u||(!1===y?.passed?{attempt:y}:null);return t.jsxs("div",{className:"onboarding-quiz-start",children:[e?t.jsxs("div",{className:"onboarding-quiz-state onboarding-quiz-state--failed",role:"status",children:[t.jsxs("strong",{children:["Attempt ",e.attempt.attemptNumber,": ",gg(e.attempt)," · Not passed yet"]}),u?.remediation?.length?t.jsxs("div",{children:[t.jsx("span",{children:"Review these topics before trying again:"}),t.jsx("ul",{children:u.remediation.map(e=>t.jsxs("li",{children:[e.moduleTitle,": ",e.topic]},`${e.moduleKey}:${e.topic}`))})]}):null]}):null,g?t.jsx(oc,{type:"error",children:g}):null,t.jsx(ec,{variant:"primary",onClick:w,disabled:b,children:b?"Preparing quizâ¦":e?"Retake quiz":y?"Resume quiz":"Start quiz"})]})}return t.jsxs("form",{className:"onboarding-quiz-form",onSubmit:async t=>{t.preventDefault();const a={};for(const e of l.quiz.questions)(c[e.id]||[]).length||(a[e.id]="Select an answer.");p(a);const n=Object.keys(a)[0];
2if(n)v.current.get(n)?.focus();else{x(!0),f(""),j.current||(j.current=function(){if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();const e=new Uint8Array(16);globalThis.crypto?.getRandomValues?globalThis.crypto.getRandomValues(e):e.forEach((t,a)=>{e[a]=Math.floor(256*Math.random())}),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=[...e].map(e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}());try{const t=await r(`/api/workspace/v1/onboarding/assignments/${e}/quiz/submit`,{method:"POST",body:JSON.stringify({submissionId:j.current,answers:l.quiz.questions.map(e=>({questionId:e.id,selectedOptionIds:c[e.id]}))})});h(t.data),t.data.attempt.passed||o(null),await(i?.(t.data.assignment))}catch(s){f(s.safeMessage||"Unable to submit the quiz right now.")}finally{x(!1)}}},noValidate:!0,children:[t.jsxs("div",{className:"onboarding-quiz-instructions",children:[t.jsxs("strong",{children:["Attempt ",l.attempt.attemptNumber," · Pass at ",l.quiz.passingBasisPoints/100,"%"]}),t.jsx("span",{children:"Answer every question. Failed attempts show review topics, not the answer key."})]}),l.quiz.questions.map((e,a)=>{const n="multiple_choice"===e.type,s=`onboarding-quiz-error-${e.id}`;return t.jsxs("fieldset",{className:"onboarding-quiz-question",ref:t=>{t?v.current.set(e.id,t):v.current.delete(e.id)},tabIndex:"-1","aria-invalid":Boolean(m[e.id]),"aria-describedby":m[e.id]?s:void 0,children:[t.jsxs("legend",{children:[a+1,". ",e.prompt]}),n?t.jsx("p",{children:"Select all that apply."}):null,t.jsx("div",{className:"onboarding-quiz-options",children:e.options.map(a=>{const s=`onboarding-quiz-${e.id}-${a.id}`,r=c[e.id]||[];return t.jsxs("div",{className:"onboarding-quiz-option",children:[t.jsx("input",{id:s,type:n?"checkbox":"radio",name:`question-${e.id}`,value:a.id,checked:r.includes(a.id),onChange:t=>((e,t,a)=>{d(n=>{const s=n[e.id]||[],r="multiple_choice"===e.type?a?[...s,t]:s.filter(e=>e!==t):[t];return{...n,[e.id]:r}}),p(t=>({...t,[e.id]:""})),f("")})(e,a.id,t.target.checked)}),t.jsx("label",{htmlFor:s,children:a.label})]},a.id)})}),m[e.id]?t.jsx("p",{className:"onboarding-quiz-error",id:s,children:m[e.id]}):null]},e.id)}),g?t.jsx(oc,{type:"error",children:g}):null,t.jsx(ec,{variant:"primary",type:"submit",disabled:b,children:b?"Submittingâ¦":"Submit quiz"})]})}function bg({resources:e=[],reading:a=!1,inputId:n,checked:s,disabled:r,onToggle:i}){if(!e.length)return null;const o=t.jsxs("div",{className:"onboarding-reading-completion",children:[t.jsx("input",{id:n,type:"checkbox",checked:s,disabled:r,onChange:e=>i?.(e.target.checked)}),t.jsxs("label",{htmlFor:n,children:[t.jsxs("strong",{children:["I finished ",1===e.length?"this required reading":"these required readings"]}),t.jsx("span",{children:"Opening a guide does not mark it complete. Confirm after you finish reading."})]})]});return t.jsxs("section",{className:"onboarding-resources","aria-label":a?"Required readings":"Learning resources",children:[t.jsx("h4",{children:a?"Required reading":"Learning resources"}),t.jsx("div",{className:"onboarding-resource-grid",children:e.map((n,s)=>t.jsxs("article",{className:"onboarding-resource-card",children:[t.jsx(ht,{size:22,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsxs("span",{className:"onboarding-resource-kind",children:[a||n.required?"Required reading":"Supporting guide",n.estimatedMinutes?` · ~${n.estimatedMinutes} min`:""]}),t.jsx("h5",{children:n.title}),t.jsx("p",{children:n.description}),t.jsxs(ec,{as:l,variant:"secondary",className:"onboarding-resource-link",to:n.href,target:"_blank",rel:"noopener noreferrer",children:[a?"Open reading":"Open guide",t.jsx(Le,{size:17,"aria-hidden":"true"})]}),a&&1===e.length&&0===s?o:null]})]},n.key))}),a&&e.length>1?o:null]})}function xg({practice:e,inputId:n,checked:s,disabled:r,onToggle:i}){const[l,o]=a.useState(""),c=a.useId();if(!e)return null;const d=e.starterFiles||[{filename:"starter.js",language:e.language,content:e.starterCode}],u=e.expectedChecks||e.checkYourWork,h=async(e,t)=>{try{await navigator.clipboard.writeText(e),o(t)}catch{o("Copy failed. Select the visible text and copy it manually.")}};return t.jsxs("section",{className:"onboarding-practice","aria-labelledby":c,children:[t.jsxs("div",{className:"onboarding-practice-heading",children:[t.jsxs("div",{children:[t.jsx("span",{className:"onboarding-eyebrow",children:"Try it yourself"}),t.jsx("h4",{id:c,children:e.objective})]}),t.jsxs("span",{children:[e.estimatedMinutes," min"]})]}),t.jsx("p",{className:"onboarding-practice-boundary",children:"Work locally with the synthetic example. TokenWorks does not upload, run, grade, or store your co
2de."}),e.context?t.jsxs("div",{className:"onboarding-practice-context",children:[t.jsx("h5",{children:"Why this matters"}),t.jsx("p",{children:e.context})]}):null,t.jsxs("div",{className:"onboarding-practice-code-heading",children:[t.jsxs("h5",{children:["Starter ",1===d.length?"code":`files · ${d.length} files`]}),t.jsxs(ec,{variant:"secondary",type:"button",onClick:()=>h(d.map(e=>`// ${e.filename}\n${e.content}`).join("\n\n"),1===d.length?"Starter code copied. Paste it into your local IDE.":"All starter files copied. Paste them into matching files in your local project."),children:[t.jsx(mt,{size:17,"aria-hidden":"true"}),1===d.length?"Copy starter code":"Copy all starter files"]})]}),t.jsx("div",{className:"onboarding-practice-files",children:d.map(e=>t.jsxs("section",{className:"onboarding-practice-file",children:[t.jsxs("div",{className:"onboarding-practice-file-heading",children:[t.jsx("h6",{children:e.filename}),t.jsx("span",{children:e.language}),d.length>1?t.jsxs(ec,{variant:"ghost",size:"compact",type:"button",onClick:()=>h(e.content,`${e.filename} copied. Paste it into your local project.`),children:[t.jsx(mt,{size:16,"aria-hidden":"true"})," Copy file"]}):null]}),t.jsx("pre",{className:"onboarding-practice-code",children:t.jsx("code",{children:e.content})})]},e.filename))}),t.jsx("p",{className:"onboarding-live-status",role:"status","aria-live":"polite",children:l}),t.jsx("h5",{children:"Your task"}),t.jsx("ol",{className:"onboarding-practice-instructions",children:e.instructions.map(e=>t.jsx("li",{children:e},e))}),e.sampleInput?t.jsxs("div",{children:[t.jsx("h5",{children:"Sample input"}),t.jsx("pre",{className:"onboarding-practice-code",children:t.jsx("code",{children:e.sampleInput})})]}):null,e.commands?.length?t.jsxs("div",{className:"onboarding-practice-commands",children:[t.jsx("h5",{children:"Run locally"}),t.jsx("pre",{className:"onboarding-practice-code",children:t.jsx("code",{children:e.commands.join("\n")})})]}):null,t.jsxs("div",{className:"onboarding-practice-checks",children:[t.jsx("h5",{children:"Expected behavior"}),t.jsx("p",{children:e.expectedBehavior}),t.jsx("h5",{children:"Run these checks"}),t.jsx("ul",{children:u.map(e=>t.jsx("li",{children:e},e))})]}),t.jsxs("details",{className:"onboarding-practice-hints",children:[t.jsxs("summary",{children:[t.jsx(ie,{size:17,"aria-hidden":"true"})," Hints"]}),t.jsx("ul",{children:e.hints.map(e=>t.jsx("li",{children:e},e))})]}),e.reflectionPrompt?t.jsxs("aside",{className:"onboarding-practice-reflection",children:[t.jsx("h5",{children:"Reflect"}),t.jsx("p",{children:e.reflectionPrompt}),t.jsx("small",{children:"This reflection is not graded or stored."})]}):null,t.jsxs("div",{className:"onboarding-practice-completion",children:[t.jsx("input",{id:n,type:"checkbox",checked:s,disabled:r,onChange:e=>i?.(e.target.checked)}),t.jsxs("label",{htmlFor:n,children:[t.jsx("strong",{children:"I completed this implementation in my IDE"}),t.jsx("span",{children:"Self-attestation records progress only. TokenWorks never receives your code."})]})]})]})}function vg({blocks:e=[]}){return e.map((e,a)=>t.jsxs("div",{className:"onboarding-lesson-block",children:[t.jsx("h4",{children:e.heading}),t.jsx("p",{children:e.body}),e.bullets?.length?t.jsx("ul",{children:e.bullets.map(e=>t.jsx("li",{children:e},e))}):null]},`${e.heading}-${a}`))}function jg({item:e,assignmentId:a,assignmentStatus:n,quiz:s,busy:r,makeAuthRequest:i,onChange:l,onAssignmentUpdated:o}){const c=`onboarding-item-${e.id}`,d=["completed","waived"].includes(e.progress.status),u=["completed","waived","cancelled","superseded"].includes(n),h=["READ","ACKNOWLEDGE","TRY_IT"].includes(e.type),m=u||r||!h||"waived"===e.progress.status,p="TRY_IT"===e.type,g="READ"===e.type,f="OPEN_RESOURCE"===e.type,b=g&&e.learnerResources?.length>0;return t.jsxs("article",{className:`onboarding-item onboarding-item--${e.progress.status} onboarding-item--${e.type.toLowerCase()}`,children:[t.jsx("div",{className:"onboarding-item-heading",children:!h||p||b?p?t.jsxs("div",{className:"onboarding-practice-item-heading",children:[t.jsx("span",{className:"onboarding-eyebrow",children:"Local implementation"}),t.jsx("h3",{children:e.title}),t.jsxs("small",{children:[e.required?"Required":"Optional"," · Self-attested"]})]}):b||f?t.jsxs("div",{className:"onboarding-reading-item-heading",children:[t.jsx("span",{className:"onboarding-eyebrow",children:f?"Guides library · Optional":"Required reading"}),t.jsx("h3",{children:e.title})]}):t.jsxs("div",{className:"onboarding-system-item-heading",children:[d?t.jsx(pe,{size:22,"aria-hidden":"true"}):t.jsx(xe,{size:22,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("h3",{children:e.title}),t.jsxs("small",{children:["Server-confirmed · ",e.required?"Required":"Optional"]})]})]}):t.jsxs("div",{className:"onboarding-checkbox-row",children:[t.jsx("input",{id:c,t
2ype:"checkbox",checked:d,disabled:m,onChange:t=>l(e,t.target.checked)}),t.jsxs("label",{htmlFor:c,children:[t.jsx("span",{children:e.title}),t.jsxs("small",{children:["ACKNOWLEDGE"===e.type?"Acknowledgement":"TRY_IT"===e.type?"Local self-attested practice":"Reading"," ","· ",e.required?"Required":"Optional"]})]})]})}),t.jsx("p",{className:"onboarding-item-description",children:e.description}),t.jsx(vg,{blocks:e.content}),t.jsx(bg,{resources:e.learnerResources,reading:b,inputId:b?c:void 0,checked:b?d:void 0,disabled:b?m:void 0,onToggle:b?t=>l(e,t):void 0}),p?t.jsx(xg,{practice:e.practice,inputId:c,checked:d,disabled:m,onToggle:t=>l(e,t)}):null,"waived"===e.progress.status?t.jsx("p",{className:"onboarding-item-state",children:"Waived by an authorized administrator."}):null,"QUIZ"===e.type?t.jsx(fg,{assignmentId:a,assignmentStatus:n,quiz:s,makeAuthRequest:i,onAssignmentUpdated:o}):null]})}function yg({module:e,detail:a=!1,onOpen:n,assignmentId:s,assignmentStatus:r,quiz:i,busyItemId:l,makeAuthRequest:o,onItemChange:c,onAssignmentUpdated:d}){const u=`onboarding-module-${e.id}`,h=e.items.filter(e=>e.required),m=h.filter(e=>["completed","waived"].includes(e.progress.status)).length,p=e.items.filter(e=>"TRY_IT"===e.type),g=p.reduce((e,t)=>e+Number(t.practice?.estimatedMinutes||0),0),f=e.progress.status.replaceAll("_"," ");if(!a){const a="completed"===e.progress.status?"Review module":"not_started"===e.progress.status?"Start module":"Continue module";return t.jsxs(Qo,{className:"onboarding-module-card",boundary:"elevated","aria-labelledby":u,children:[t.jsxs("div",{children:[t.jsxs("span",{className:"onboarding-module-position",children:["Module ",e.position]}),t.jsx("h3",{id:u,children:e.title}),t.jsx("p",{children:e.purpose})]}),t.jsxs("dl",{className:"onboarding-module-summary",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Estimated time"}),t.jsxs("dd",{children:["~",e.expectedMinutes," minutes"]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Progress"}),t.jsxs("dd",{children:[m," of ",h.length," requirements complete"]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Status"}),t.jsx("dd",{children:f})]})]}),p.length?t.jsxs("div",{className:"onboarding-module-practice-preview",children:[t.jsx(pt,{size:24,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:"Hands-on code practice included"}),t.jsxs("span",{children:[p.length," local exercise",1===p.length?"":"s"," · ~",g," minutes · starter code and runnable checks"]})]})]}):null,t.jsx(ec,{variant:"primary",onClick:n,children:a})]})}const b=[{key:"readings",title:"Required readings",description:"Open each guide, read it, then self-attest when you have finished.",items:e.items.filter(e=>"READ"===e.type)},{key:"lessons",title:"Lesson and examples",description:"Connect the readings to TokenWorks working practices and boundaries.",items:e.items.filter(e=>["ACKNOWLEDGE","OPEN_RESOURCE"].includes(e.type))},{key:"practice",title:"Try it yourself",description:"Implement the synthetic exercise locally. Nothing is uploaded to TokenWorks.",items:e.items.filter(e=>"TRY_IT"===e.type)},{key:"quiz",title:"Knowledge check",description:"The final quiz is scored by the server after all required lessons are complete.",items:e.items.filter(e=>"QUIZ"===e.type)}].filter(e=>e.items.length);return t.jsxs("section",{className:"onboarding-module onboarding-module--detail","aria-labelledby":u,children:[t.jsxs("header",{className:"onboarding-module-heading",children:[t.jsxs("div",{children:[t.jsxs("span",{className:"onboarding-module-position",children:["Module ",e.position]}),t.jsx("h2",{id:u,children:e.title}),t.jsx("p",{children:e.purpose})]}),t.jsxs("span",{className:"onboarding-module-meta",children:["~",e.expectedMinutes," min · ",f]})]}),t.jsxs("section",{className:"onboarding-learning-objectives","aria-labelledby":`${u}-learn`,children:[t.jsx("h3",{id:`${u}-learn`,children:"What you'll learn"}),e.learningObjectives?.length?t.jsx("ul",{children:e.learningObjectives.map(e=>t.jsx("li",{children:e},e))}):t.jsx("p",{children:e.purpose}),e.timeBreakdown?t.jsxs("dl",{className:"onboarding-time-breakdown","aria-label":"Estimated module time",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Read"}),t.jsxs("dd",{children:[e.timeBreakdown.readingMinutes," min"]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Lesson"}),t.jsxs("dd",{children:[e.timeBreakdown.lessonMinutes," min"]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Practice"}),t.jsxs("dd",{children:[e.timeBreakdown.practiceMinutes," min"]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Review"}),t.jsxs("dd",{children:[e.timeBreakdown.reviewMinutes," min"]})]})]}):null]}),t.jsxs("nav",{className:"onboarding-module-jump-nav","aria-label":"Module sections",children:[t.jsx("a",{href:`#${u}-learn`,children:"What you'll learn"}),b.map(e=>t.jsx("a",{href:`#${u}-${e.key}`,children:e.title},e.key)),t.jsx("a",{href:`#${u}-completion`,children:"Completion"})]}),p.length?t.jsxs("aside",{className:"onboarding-practice-callout","aria-labelledby":`${u}-practice-callout`,children:[t.jsx(pt,{size:28,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("h3",{id:`${u}-practice-callout`,children:"Build it yourself in your IDE"}),t.jsxs("p",{children:["This module includes ",p.length," local coding exercise",1===p.length?"":"s"," with starter files, commands, assertions, hints, and a reflection prompt. TokenWorks never uploads or runs your code."]}),t.jsx("a",{href:`#${u}-practice`,children:"Jump to code practice"})]})]}):null,t.jsx("div",{className:"onboarding-module-sections",children:b.map(e=>t.jsxs("section",{id:`${u}-${e.key}`,className:`onboarding-module-section onboarding-module-section--${e.key}`,children:[t.jsxs("header",{children:[t.jsx("h3",{children:e.title}),t.jsx("p",{children:e.description})]}),t.jsx("div",{className:"onboarding-module-items",children:e.items.map(e=>t.jsx(jg,{item:e,assignmentId:s,assignmentStatus:r,quiz:i,busy:l===e.id,makeAuthRequest:o,onChange:c,onAssignmentUpdated:d},e.id))})]},e.key))}),t.jsxs("aside",{id:`${u}-completion`,className:"onboarding-completion-requirements",children:[t.jsx("h3",{children:"Completion requirements"}),t.jsxs("p",{children:["Complete ",h.length," required item",1===h.length?"":"s"," in this module. Your current progress is ",m," of ",h.length,"."]})]})]})}function kg({assignmentId:e,moduleKey:n,onModuleChange:s,onAssignmentUpdated:r}){const{makeAuthRequest:i}=Yn(),l=e?`/api/workspace/v1/onboarding/assignments/${e}`:null,{data:o,loading:c,error:d,refresh:u}
2=kc(l),h=o?.assignment||null,[m,p]=a.useState(null),[g,f]=a.useState(!1),[b,x]=a.useState(""),[v,j]=a.useState(""),y=h?.modules?.find(e=>e.key===n)||null,k=y?.items?.filter(e=>e.required)||[],w=k.filter(e=>["completed","waived"].includes(e.progress.status)).length,N=a.useCallback(async()=>{const e=await u();return await(r?.(e?.assignment||null)),e?.assignment||null},[r,u]);return t.jsx(bc,{loading:c&&!o,error:d,loadingLabel:"Loading onboardingâ¦",errorLabel:"Onboarding could not be loaded",onRetry:u,isEmpty:!c&&!d&&!h,emptyLabel:"No onboarding assignment is available.",children:h?t.jsxs("div",{className:"employee-onboarding-panel",children:[t.jsxs("section",{className:"onboarding-overview","aria-labelledby":"onboarding-program-title",children:[t.jsxs("div",{children:[t.jsxs("span",{className:"onboarding-eyebrow",children:["Version ",h.program.version]}),t.jsx("h2",{id:"onboarding-program-title",children:h.program.name}),t.jsx("p",{children:"Work at your own pace. Onboarding is guidance and never blocks other work you are already authorized to do."})]}),"assigned"===h.status?t.jsx(ec,{variant:"primary",onClick:async()=>{f(!0),x("");try{await i(`${l}/start`,{method:"POST",body:JSON.stringify({})}),await N(),j("Onboarding started.")}catch(e){x(e.safeMessage||"Unable to start onboarding right now.")}finally{f(!1)}},disabled:g,children:g?"Startingâ¦":"Start onboarding"}):null]}),t.jsx(vc,{progress:h.progress,status:h.status}),b?t.jsx(oc,{type:"error",children:b}):null,t.jsx("p",{className:"onboarding-live-status",role:"status","aria-live":"polite",children:v}),y?t.jsxs("div",{className:"onboarding-module-detail-shell",children:[t.jsxs("div",{className:"onboarding-module-sticky-header",children:[t.jsx(ec,{variant:"ghost",className:"onboarding-back-button",onClick:()=>s?.(""),children:"Back to module overview"}),t.jsxs("div",{children:[t.jsx("strong",{children:y.title}),t.jsxs("span",{children:[w," of ",k.length," required items complete"]})]})]}),t.jsx(yg,{module:y,detail:!0,assignmentId:h.id,assignmentStatus:h.status,quiz:h.quiz,busyItemId:m,makeAuthRequest:i,onItemChange:async(e,t)=>{p(e.id),x(""),j("");try{await i(`${l}/items/${e.id}`,{method:"PATCH",headers:{"Idempotency-Key":globalThis.crypto?.randomUUID?`progress:${globalThis.crypto.randomUUID()}`:`progress:${Date.now()}:${Math.random().toString(36).slice(2)}`},body:JSON.stringify({completed:t,expectedRevision:h.revision})}),await N(),j(t?`${e.title} completed.`:`${e.title} reopened.`)}catch(a){"ONBOARDING_PROGRESS_CONFLICT"===a.code&&await N(),x(a.safeMessage||"Unable to update this checklist item right now.")}finally{p(null)}},onAssignmentUpdated:N})]}):t.jsxs("section",{className:"onboarding-module-overview","aria-labelledby":"module-overview-title",children:[t.jsxs("div",{className:"onboarding-module-overview-heading",children:[t.jsx("span",{className:"onboarding-eyebrow",children:"Course outline"}),t.jsx("h2",{id:"module-overview-title",children:"Open a module to begin the lesson"}),t.jsx("p",{children:"Each learning module contains expanded readings, visual explanations, optional links into the Guides library, and a hands-on coding problem with starter files and runnable local checks."})]}),t.jsx("div",{className:"onboarding-modules",children:h.modules.map(e=>t.jsx(yg,{module:e,onOpen:()=>s?.(e.key)},e.id))})]})]}):null})}function wg({activeSection:e,availability:a=null,unreadConversations:n=0,onNavigate:s=null,collapsed:r=!1,showOnboarding:i=!1,showWikibase:o=!1,id:c}){const d=Number(n)||0,u=function({includeOnboarding:e=!1,includeWikibase:t=!1}={}){const a=t?Mr:Mr.filter(e=>"wikibase"!==e.id);return e?[Ur,...a]:a}({includeOnboarding:i,includeWikibase:o}),h=Fr.icon,m=e===Fr.id;return t.jsxs("nav",{id:c,className:"employee-workspace-nav"+(r?" employee-workspace-nav--collapsed":""),"aria-label":"Workspace",children:[t.jsx("ul",{className:"employee-workspace-nav-list",children:u.map(n=>{const r=n.icon,i=n.id===e,o=fc(a,n.id),c="messages"===n.id&&o&&d>0;return t.jsx("li",{children:t.jsxs(l,{to:Vr(n.id),className:["employee-workspace-nav-item",i?"is-active":"",o?"":"is-unavailable"].filter(
2Boolean).join(" "),"aria-current":i?"page":void 0,"aria-disabled":!o||void 0,onClick:s||void 0,children:[t.jsx("span",{className:"employee-workspace-nav-icon","aria-hidden":"true",children:t.jsx(r,{size:18})}),t.jsx("span",{className:"employee-workspace-nav-label",children:n.label}),o?null:t.jsx("span",{className:"employee-workspace-nav-note",children:" (unavailable)"}),c?t.jsxs("span",{className:"employee-workspace-nav-badge",children:[d>99?"99+":d,t.jsxs("span",{className:"employee-workspace-visually-hidden",children:[" ","unread conversations"]})]}):null]})},n.id)})}),t.jsxs("div",{className:"employee-workspace-nav-secondary",children:[t.jsxs(l,{to:Vr(Fr.id),className:["employee-workspace-nav-item","employee-workspace-nav-item--secondary",m?"is-active":""].filter(Boolean).join(" "),"aria-current":m?"page":void 0,onClick:s||void 0,children:[t.jsx("span",{className:"employee-workspace-nav-icon","aria-hidden":"true",children:t.jsx(h,{size:18})}),t.jsx("span",{className:"employee-workspace-nav-label",children:Fr.label})]}),t.jsxs(l,{to:"/dashboard",className:"employee-workspace-nav-item employee-workspace-nav-item--secondary",onClick:s||void 0,children:[t.jsx("span",{className:"employee-workspace-nav-icon","aria-hidden":"true",children:t.jsx(it,{size:18})}),t.jsx("span",{className:"employee-workspace-nav-label",children:"TokenWorks Library"})]})]})]})}const Ng={people:"People",teams:"Teams",projects:"Projects",tasks:"Tasks",conversations:"Conversations",resources:"Resources"};function Sg(e,a){const n=String(e||""),s=String(a||"").trim();if(!s)return n;const r=n.toLowerCase().indexOf(s.toLowerCase());return r<0?n:t.jsxs(t.Fragment,{children:[n.slice(0,r),t.jsx("mark",{children:n.slice(r,r+s.length)}),n.slice(r+s.length)]})}function Cg({data:e,query:a,activeIndex:n,onHover:s,onSelect:r,listboxId:i}){const l=e?.groups||{};let o=-1;return t.jsx("div",{className:"workspace-search-results",role:"listbox",id:i,children:Object.entries(Ng).map(([e,c])=>{const d=l[e]||[];return d.length?t.jsxs("section",{children:[t.jsx("h4",{children:c}),d.map(e=>{o+=1;const l=o;return t.jsxs(Qo,{as:"button",interactive:!0,id:`${i}-option-${l}`,type:"button",role:"option","aria-selected":n===l,className:n===l?"active":"",onMouseEnter:()=>s(l),onClick:()=>r(e),children:[t.jsx("small",{className:"workspace-search-result-type",children:c}),t.jsx("strong",{children:Sg(e.title,a)}),t.jsx("span",{children:Sg(e.subtitle||e.context,a)})]},`${e.type}-${e.id}`)})]},e):null})})}function Rg({endpoint:a,placeholder:n="Search workspace",onNavigate:s}){const[r,i]=e.useState(""),[l,o]=e.useState(!1),[c,d]=e.useState(0),u=e.useId(),{data:h,loading:m,error:p}=function(t,a){const{makeAuthRequest:n}=Yn(),[s,r]=e.useState(null),[i,l]=e.useState(!1),[o,c]=e.useState(null),d=e.useRef(0);return e.useEffect(()=>{const e=String(a||"").trim(),s=d.current+1;d.current=s;const i=new AbortController;if(r(null),c(null),e.length<2)return l(!1),()=>i.abort();l(!0);const o=setTimeout(async()=>{try{const a=t.includes("?")?"&":"?",l=new URLSearchParams({q:e}),o=await n(`${t}${a}${l.toString()}`,{signal:i.signal});i.signal.aborted||d.current!==s||r(o.data)}catch(a){i.signal.aborted||d.current!==s||c(a.message||"Search failed")}finally{i.signal.aborted||d.current!==s||l(!1)}},300);return()=>{clearTimeout(o),i.abort()}},[t,n,a]),{data:s,loading:i,error:o}}(a,r),g=e.useMemo(()=>Object.values(h?.groups||{}).flat(),[h]),f=e=>{s?.(e),o(!1),i(""),d(0)};return t.jsxs("div",{className:"workspace-search",children:[t.jsxs("label",{children:[t.jsx(ue,{size:16}),t.jsx("span",{children:"Workspace search"}),t.jsx("input",{role:"combobox","aria-autocomplete":"list","aria-expanded":l&&r.trim().length>=2,"aria-controls":u,"aria-activedescendant":l&&g.length?`${u}-option-${c}`:void 0,value:r,onFocus:()=>o(!0),onChange:e=>{i(e.target.value),o(!0)},onKeyDown:e=>{"Escape"!==e.key?g.length&&("ArrowDown"===e.key&&(e.preventDefault(),d(e=>Math.min(e+1,g.length-1))),"ArrowUp"===e.key&&(e.preventDefault(),d(e=>Math.max(e-1,0))),"Enter"===e.key&&(e.preventDefault(),f(g[c]))):o(!1)},placeholder:n})]}),l&&r.trim().length>=2?t.jsxs("div",{className:"workspace-search-popover",children:[m?t.jsx("p",{children:"Searching..."}):null,p?t.jsx("p",{className:"workspace-search-error",children:p}):null,m||p||0!==h?.total?null:t.jsx("p",{children:"No results found."}),h?.total?t.jsx(Cg,{listboxId:u,data:h,query:r,activeIndex:c,onHover:d,onSelect:f}):null]}):null]})}function Eg({mobile:e,children:t}){return e&&"undefined"!=typeof document?n.createPortal(t,document.body):t}function Ig({onNavigate:a=null,beginNotificationsReadReconciliation:n=null,controllerRef:s=null}){const{visible:r,notifications:i,unread:l,loading:o,error:c,unavailable:d,mutationPending:u,recoveryPending:h,loadList:m,markRead:p,markAllRead:f}=Ar(),[b,x]=e.useState(!1),[v,j]=e.useState(()=>"undefined"!=typeof window&&Boolean(window.matchMedia?.("(max-width: 767px)").matches)),[y,k]=e.useState(null),[w,N]=e.useState(!1),S=e.useRef(null),C=e.useRef(null),R=e.useRef(null),E=e.useRef(new Map),I=e.useRef(null),_=e.useRef(!1),A=e.useRef(0),O=e.useRef(0),D=e.useRef(null),P=e.useRef(!1),L=e.useId(),$=e.useId(),M=e.useCallback((e=!0)=>{const t=I.current||S.current;return k(null),N(!1),x(!1),I.current=null,_.current=!1,e&&t?.focus?.({preventScroll:!0}),t},[]),U=e.useCallback(()=>{I.current=null,_.current=!1,x(!0)},[]);e.useImperativeHandle(s,()=>({openNotifications({returnFocusTo:e=null}={}){I.current=e?.isConnected?e:null,_.current=!0,x(!0)}}),[]),e.useEffect(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(max-width: 767px)"),t=()=>j(e.matches);return t(),e.addEventListener?.("change",t),()=>e.removeEventListener?.("change",t)},[]),e.useEffect(()=>{b&&(_.current||v)&&C.current?.focus?.({preventScroll:!0})},[v,b]),e.useEffect(()=>{if(!r||!b||!v||"undefined"==typeof document)return;const e=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=e}},[v,b,r]);const F=e.useCallback(e=>{e.id<=O.current||(O.current=e.id,D.current=e.reconcileUnread?e:null)},[]),q=e.useCallback(async e=>{const t=D.current;t&&(D.current=null,await t.reconcileUnread(e))},[]),B=e.useCallback(async()=>{const e=await m();null!==e&&await q(e)},[q,m]);if(e.useEffect(()=>{!h&&D.current&&q(l)},[q,h,l]),e.useEffect(()=>{if(!b)return;let e=!0;return B().then(()=>
2{if(!e||!_.current||!C.current?.isConnected)return;const t=C.current.querySelector('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])');(t||C.current).focus?.({preventScroll:!0}),_.current=!1}),()=>{e=!1}},[B,b]),e.useEffect(()=>{if(!b||"undefined"==typeof document)return;const e=e=>{if("Escape"===e.key)return e.stopPropagation(),void M();if("Tab"!==e.key||!v)return;const t=Array.from(C.current?.querySelectorAll('a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])')||[]);if(!t.length)return e.preventDefault(),void C.current?.focus?.();const a=t[0],n=t[t.length-1];!e.shiftKey||document.activeElement!==a&&document.activeElement!==C.current?e.shiftKey||document.activeElement!==n||(e.preventDefault(),a.focus()):(e.preventDefault(),n.focus())},t=e=>{C.current?.contains(e.target)||S.current?.contains(e.target)||M()};return document.addEventListener("keydown",e),document.addEventListener("mousedown",t),()=>{document.removeEventListener("keydown",e),document.removeEventListener("mousedown",t)}},[M,v,b]),e.useEffect(()=>{if(!b||!y)return;const e=E.current.get(y)||C.current;e?.focus?.({preventScroll:!0}),k(null)},[y,i,b]),e.useEffect(()=>{if(!b||!w||o)return;const e=c?R.current:E.current.values().next().value||C.current;e?.focus?.({preventScroll:!0}),N(!1)},[c,o,i,b,w]),!r)return null;const W=l?`, ${l} unread`:"";return t.jsxs("div",{className:"notification-bell",children:[t.jsxs(ec,{ref:S,iconOnly:!0,variant:"secondary","aria-label":`Notifications${W}`,"aria-expanded":b,"aria-haspopup":"dialog","aria-controls":L,"aria-disabled":u,disabled:u,onClick:()=>b?M(!1):U(),children:[t.jsx(z,{size:18,"aria-hidden":"true"}),l?t.jsx("span",{"aria-hidden":"true",children:l>99?"99+":l}):null]}),b?t.jsx(Eg,{mobile:v,children:t.jsxs(t.Fragment,{children:[v?t.jsx("div",{className:"notification-panel-scrim","aria-hidden":"true",onPointerDown:e=>{e.preventDefault(),e.stopPropagation();const t=M();Promise.resolve().then(()=>t?.focus?.({preventScroll:!0}))}}):null,t.jsxs("div",{className:"notification-panel",id:L,ref:C,role:"dialog",tabIndex:-1,"aria-modal":v?"true":"false","aria-labelledby":$,"aria-busy":u||o,children:[t.jsxs("div",{className:"notification-panel-header",children:[t.jsx("strong",{id:$,children:"Notifications"}),t.jsxs("span",{className:"notification-panel-header-actions",children:[t.jsx(ec,{variant:"ghost",size:"compact",onClick:()=>{(async()=>{if(P.current)return;P.current=!0;const e={id:++A.current,reconcileUnread:n?.()};try{const t=await f(()=>F(e));null!==t&&await q(t)}finally{P.current=!1}})()},"aria-disabled":u||o||d||!l,disabled:u||o||d||!l,children:"Mark all read"}),v?t.jsxs(ec,{variant:"ghost",size:"compact","aria-label":"Close notifications",onClick:()=>M(),children:[t.jsx(g,{size:16,"aria-hidden":"true"})," Close"]}):null]})]}),d?t.jsx("p",{role:"status",children:"Notifications will appear after workspace messaging is ready."}):null,c?t.jsxs(oc,{type:"error",className:"notification-feedback",children:[t.jsx("span",{className:"notification-feedback-copy",children:c.safeMessage||"Notifications could not be updated."}),t.jsx(ec,{ref:R,variant:"ghost",size:"compact",onClick:()=>{N(!0),B()},children:"Retry"})]}):null,o?t.jsx("p",{role:"status","aria-live":"polite",children:"Loading notificationsâ¦"}):null,i.map(e=>{const s=null!==Lr(e),r=Or(e.createdAt),i="workspace_update"===e.entityType,l=i?T:z;return t.jsxs(Qo,{as:s?"button":"article",interactive:s,ref:t=>{t?E.current.set(e.id,t):E.current.delete(e.id)},type:s?"button":void 0,tabIndex:s?void 0:-1,"aria-disabled":s&&u?"true":void 0,disabled:s?u:void 0,className:`notification-record${e.readAt?"":" unread"}${i?" is-workspace-update":""}`,onClick:s?()=>{(async e=>{if(P.current)return;const t=Lr(e);let s=!0;try{t&&a&&(s=!1!==await a(t))}catch{s=!1}if(!s){const t=E.current.get(e.id)||C.current;return void t?.focus?.({preventScroll:!0})}P.current=!0;const r={id:++A.current,reconcileUnread:n?.()};M(!1);try{const t=await p([e.id],!1,()=>F(r));null!==t&&await q(t)}finally{P.current=!1}})(e)}:void 0,children:[t.jsx("span",{className:"notification-record-icon","aria-hidden":"true",children:t.jsx(l,{size:17})}),t.jsxs("span",{className:"notification-record-copy",children:[t.jsx("strong",{children:e.title}),t.jsx("span",{children:e.summary||(i?"New Workspace Update":"Workspace notification")}),r?t.jsx("small",{className:"notification-time",children:t.jsx("time",{dateTime:e.createdAt,children:r})}):null,e.readAt?null:t.jsx("small",{className:"notification-unread-tag",children:"Unread"}),s?null:t.jsxs("span",{className:"notification-record-no-target",children:[t.jsx("small",{children:"This notification has no destination."}),e.readAt?null:t.jsx(ec,{variant:"ghost",size:"compact","aria-label":`Mar
2k ${e.title} read`,onClick:()=>{(async e=>{if(P.current)return;P.current=!0;const t={id:++A.current,reconcileUnread:n?.()};try{const a=await p([e.id],!1,()=>F(t));null!==a&&(await q(a),C.current?.isConnected&&k(e.id))}finally{P.current=!1}})(e)},children:"Mark as read"})]})]})]},e.id)}),o||i.length||d?null:t.jsx("p",{children:"No notifications."})]})]})}):null]})}function _g({sectionLabel:e,searchEndpoint:a,onSearchNavigate:n,onNotificationNavigate:s,beginNotificationsReadReconciliation:r,notificationControllerRef:i,onOpenMenu:l,menuButtonRef:o,drawerId:c,isMenuOpen:d=!1}){return t.jsxs("div",{className:"employee-workspace-header",role:"group","aria-label":"Workspace controls",children:[t.jsx("button",{type:"button",ref:o,className:"employee-workspace-icon-button employee-workspace-menu-button",onClick:l,"aria-label":"Open workspace menu","aria-expanded":d,"aria-controls":c,children:t.jsx(q,{size:20,"aria-hidden":"true"})}),t.jsxs("div",{className:"employee-workspace-header-context",children:[t.jsx("span",{className:"employee-workspace-header-eyebrow",children:"Workspace"}),t.jsx("span",{className:"employee-workspace-header-section",children:e})]}),t.jsxs("div",{className:"employee-workspace-header-actions",children:[t.jsx(Rg,{endpoint:a,placeholder:"Search Workspace",onNavigate:n}),t.jsx(Ig,{onNavigate:s,beginNotificationsReadReconciliation:r,controllerRef:i}),t.jsx("span",{id:"employee-workspace-cookie-settings-slot",className:"employee-workspace-cookie-settings-slot"})]})]})}function Tg({isOpen:e,onClose:a,title:n="Menu",children:s}){return t.jsx(fr,{isOpen:e,onClose:a,title:n,side:"left",closeLabel:"Close workspace menu",classNames:{overlay:"employee-workspace-drawer-overlay",panel:"employee-workspace-drawer",header:"employee-workspace-drawer-header",body:"employee-workspace-drawer-body",closeButton:"employee-workspace-icon-button"},children:s})}function Ag({title:e,description:a=null,status:n=null,filters:s=null,actions:r=null,headingId:i,headingRef:l=null}){return t.jsxs("header",{className:"employee-workspace-page-header",children:[t.jsxs("div",{className:"employee-workspace-page-header-row",children:[t.jsxs("div",{className:"employee-workspace-page-heading",children:[t.jsx("h1",{id:i,ref:l,tabIndex:l?-1:void 0,children:e}),a?t.jsx("p",{className:"employee-workspace-page-description",children:a}):null]}),n?t.jsx("div",{className:"employee-workspace-page-status",children:n}):null,r?t.jsx("div",{className:"employee-workspace-page-actions",children:r}):null]}),s?t.jsx("div",{className:"employee-workspace-page-filters",children:s}):null]})}function Og({activeSection:a,availability:n=null,unreadConversations:s=0,searchEndpoint:r="/api/workspace/v1/search?scope=mine",onSearchNavigate:i,onNotificationNavigate:l,beginNotificationsReadReconciliation:o,notificationControllerRef:c,pageHeaderStatus:d=null,pageHeaderActions:u=null,pageHeaderDescription:h=null,showOnboarding:m=!1,showWikibase:p=!1,hidePageHeader:g=!1,pageHeadingRef:f=null,children:b}){const x=Wr(a),[v,j]=e.useState(!1),[y,k]=e.useState(!1),w=e.useRef(null),N=e.useRef(null),S=e.useId(),C=e.useId(),R=e.useCallback(()=>j(!1),[]);e.useLayoutEffect(()=>{const e=w.current,t=document.querySelector(".header");if(!e||!t)return;const a=()=>{e.style.setProperty("--employee-header-offset",`${t.getBoundingClientRect().height}px`)};a();const n="undefined"==typeof ResizeObserver?null:new ResizeObserver(a);return n?.observe(t),window.addEventListener("resize",a),()=>{n?.disconnect(),window.removeEventListener("resize",a)}},[]);const E=e.useCallback(()=>j(!1),[]);return e.useEffect(()=>{j(!1)},[a]),t.jsxs("div",{ref:w,className:["employee-workspace",`employee-workspace--${x.width}`,`employee-workspace--section-${x.id}`,y?"employee-workspace--collapsed":""].filter(Boolean).join(" "),children:[t.jsxs("aside",{className:"employee-workspace-sidebar",children:[t.jsxs("div",{className:"employee-workspace-sidebar-head",children:[t.jsx("span",{className:"employee-workspace-brand",children:"Workspace"}),t.jsx("button",{type:"button",className:"employee-workspace-icon-button employee-workspace-collapse-button",onClick:()=>k(e=>!e),"aria-label":y?"Expand sidebar":"Collapse sidebar","aria-pressed":y,children:y?t.jsx(B,{size:18,"aria-hidden":"true"}):t.jsx(W,{size:18,"aria-hidden":"true"})})]}),t.jsx(wg,{activeSection:x.id,availability:n,unreadConversations:s,collapsed:y,showOnboarding:m,showWikibase:p})]}),t.jsxs("div",{className:"employee-workspace-main",children:[t.jsx(_g,{sectionLabel:x.label,searchEndpoint:r,onSearchNavigate:i,onNotificationNavigate:l,beginNotificationsReadReconciliation:o,notificationControllerRef:c,onOpenMenu:()=>j(!0),menuButtonRef:N,drawerId:S,isMenuOpen:v}),t.jsxs("main",{className:"employee-workspace-content","aria-labelledby":g?void 0:C,"aria-label":g?x.title:void 0,children:[g?null:t.jsx(Ag,{title:x.title,de
2scription:h??x.description,status:d,actions:u,headingId:C,headingRef:f}),t.jsx("div",{className:"employee-workspace-section",children:b})]})]}),t.jsx(Tg,{isOpen:v,onClose:R,title:"Workspace",children:t.jsx("div",{id:S,children:t.jsx(wg,{activeSection:x.id,availability:n,unreadConversations:s,onNavigate:E,showOnboarding:m,showWikibase:p})})})]})}function Dg({scope:e="mine",onChange:a}){return t.jsxs("div",{className:"employee-workspace-scope",role:"group","aria-label":"Workspace scope",children:[t.jsx("button",{type:"button","aria-pressed":"mine"===e,onClick:()=>a?.("mine"),children:"My work"}),t.jsx("button",{type:"button","aria-pressed":"all"===e,onClick:()=>a?.("all"),children:"All workspace"})]})}const Pg=new Set(["filename","identifier","url","email","name"]);function Lg({value:e,fallback:a="Unavailable",mode:n="name",className:s=""}){const r=null!=e&&""!==String(e).trim(),i=r?String(e):a,l=Pg.has(n)?n:"name";return t.jsx("span",{className:`resilient-value resilient-value--${l}${s?` ${s}`:""}`,dir:"auto","data-empty":r?void 0:"true",children:i})}function $g({message:e="Loading..."}){return t.jsxs("div",{className:"loading-state",role:"status","aria-live":"polite",children:[t.jsx("div",{className:"spinner","aria-hidden":"true"}),t.jsx("p",{children:e})]})}function Mg({title:e,children:a,className:n="",scrollable:s=!1}){const r=`admin-user-panel-card ${s?"admin-user-panel-card--scroll":""} ${n}`.trim();return t.jsxs("div",{className:r,children:[e?t.jsx("h4",{children:e}):null,s?t.jsx("div",{className:"admin-user-scroll-region",children:a}):a]})}function Ug({label:e,value:a}){return t.jsxs("div",{className:"admin-user-metric",children:[t.jsx("span",{children:e}),t.jsx("strong",{children:a})]})}const Fg=[{id:"metrics",label:"Admin Home",group:"Overview",description:"Monitor the platform and move quickly into priority administration work.",icon:v},{id:"analytics",label:"Analytics",group:"Overview",description:"Review account, subscription, document, and consent trends.",icon:gt}
2,{id:"infrastructure-health",label:"Infrastructure Health",group:"Platform",description:"Inspect bounded, read-only service health and operational signals.",icon:ft},{id:"users",label:"Users",group:"People & access",description:"Find accounts, inspect access, and perform authorized account operations.",icon:bt},{id:"people",label:"People",group:"People & access",description:"Manage personnel records and workspace participation.",icon:$},{id:"teams",label:"Teams",group:"People & access",description:"Continue team administration in the canonical Workspace experience.",icon:S},{id:"resources",label:"Resources",group:"Workspace",description:"Continue protected resource administration in Workspace.",icon:A},{id:"projects",label:"Projects",group:"Workspace",description:"Continue project and task administration in Workspace.",icon:N},{id:"messages",label:"Messages",group:"Workspace",description:"Open normal conversations or audited workspace oversight.",icon:D},{id:"operations",label:"Operations",group:"Workspace",description:"Triage workspace exceptions, workload, and recent administrative activity.",icon:xt},{id:"uploads",label:"Upload Reviews",group:"Content",description:"Review, publish, reward, message, approve, or reject submitted documents.",icon:y},{id:"documents",label:"Documents",group:"Content",description:"Browse the complete document catalog and manage access or publication state.",icon:vt},{id:"text-coverage",label:"Wikibase Status",group:"Content",description:"Inspect each documentâs Wikibase mapping, page-text coverage, synchronization, and search-index status.",icon:jt},{id:"tools",label:"Tools",group:"Platform",description:"Triage platform exceptions, health, usage, catalogs, and manual operations.",icon:k},{id:"updates",label:"Updates",group:"Communications",description:"Create, publish, and archive internal Workspace Updates.",icon:T},{id:"announcements",label:"Customer Announcements",group:"Communications",description:"Publish the single current notice shown to authenticated TokenWorks dashboard users.",icon:yt},{id:"requests",label:"Requests",group:"Communications",description:"Triage inbound consultation, support, partnership, and access requests.",icon:ve},{id:"feedback",label:"Feedback",group:"Communications",description:"Review product feedback, record internal notes, and respond to submitters.",icon:kt},{id:"careers",label:"Careers",group:"People & access",description:"Triage applications and deliberately manage published career positions.",icon:N}];const zg=function({infrastructureHealthEnabled:e=true}={}){return Fg.filter(t=>"infrastructure-health"!==t.id||e).map(e=>{return{...e,href:(t=e.id,"documents"===t?"/admin/documents":`/admin?tab=${t}`)};var t})}(),qg=zg.map(e=>e.id),Bg=[{label:"Overview"},{label:"People & access",shortLabel:"People"},{label:"Workspace"},{label:"Content"},{label:"Communications"},{label:"Platform"}].map(e=>({...e,tabs:zg.filter(t=>t.group===e.label)}));function Wg({activeTab:a,onChange:n,onExit:s}){const r=e.useRef(null),i=e.useRef(null),o=e.useMemo(()=>Bg.find(e=>e.tabs.some(e=>e.id===a))||Bg[0],[a]);e.useEffect(()=>{r.current?.scrollIntoView?.({block:"nearest",inline:"nearest"}),i.current?.scrollIntoView?.({block:"nearest",inline:"nearest"})},[a]);const c=async(e,t)=>{(function(e){return 0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey})(e)||(e.preventDefault(),await t())};return t.jsxs("nav",{className:"admin-dashboard-tabs","aria-label":"Admin panel navigation",children:[t.jsxs("div",{className:"admin-dashboard-tabs__utility",children:[t.jsxs("div",{className:"admin-dashboard-tabs__identity",children:[t.jsx("strong",{children:"Admin panel"}),t.jsxs("span",{children:[o.label," workflow"]})]}),t.jsxs("div",{className:"admin-dashboard-tabs__exits","aria-label":"Leave Admin panel",children:[t.jsxs(l,{to:"/dashboard",onClick:e=>c(e,()=>s("/dashboard")),children:[t.jsx(G,{size:16,"aria-hidden":"true"}),"Dashboard"]}),t.jsxs(l,{to:"/dashboard/employee?tab=home&scope=all",onClick:e=>c(e,()=>s("/dashboard/employee?tab=home&scope=all")),children:[t.jsx(N,{size:16,"aria-hidden":"true"}),"Workspace"]})]})]}),t.jsx("div",{className:"admin-dashboard-tabs__scroll",tabIndex:"0","aria-label":"Admin workflows",children:t.jsx("ul",{className:"admin-dashboard-tabs__workflows",children:Bg.map(e=>{const a=e.tabs[0],s=e.label===o.label;return t.jsx("li",{children:t.jsx(l,{ref:s?r:null,to:a.href,className:s?"active":void 0,"aria-current":s?"location":void 0,onClick:e=>c(e,()=>n(a.id)),children:e.shortLabel||e.label})},e.label)})})}),t.jsx("div",{className:"admin-dashboard-tabs__scroll",tabIndex:"0","aria-label":`${o.label} destinations`,children:t.jsx("ul",{className:"admin-dashboard-tabs__destinations",children:o.tabs.map(e=>{const s=e.id===a;return t.jsx("li",{children:t.jsx(l,{ref:s?i:null,to:e.href,className:s?"active":void 0,"aria-current":s?"page":void 0,onClick:t=>c(t,()=>n(e.id)),children:e.label})},e.id)})})})]})}const Vg={draft:"warning",empty:"neutral",error:"danger",loading:"info",published:"success",unavailable:"danger"},Hg="/admin?tab=announcements",Kg="/admin?tab=updates";function Gg({audience:e,description:a,href:n,icon:s,label:r,status:i,summary:o}){const c=i?.label||"Status unavailable",d=i?.variant||Vg[i?.state]||"neutral";return t.jsxs("article",{className:"communications-summary__audience",children:[t.jsxs("div",{className:"communications-summary__audience-heading",children:[t.jsx("span",{className:"communications-summary__icon","aria-hidden":"true",children:t.jsx(s,{size:20})}),t.jsxs("div",{children:[t.jsx("p",{className:"communications-summary__context",children:e}),t.jsx("h3",{children:r})]}),t.jsx(li,{variant:d,children:c})]}),t.jsx("p",{className:"communications-summary__description",children:a}),t.jsx("p",{className:"communications-summary__status",children:o||"No publishing summary available."}),t.jsxs(l,{className:"communications-summary__link",to:n,children:["Manage ",r.toLowerCase()]})]})}function Jg({customer:e,workspace:a}){return t.jsxs("section",{className:"communications-summary","aria-labelledby":"admin-home-communications-title",children:[t.jsxs("div",{className:"admin-home-v2__section-heading",children:[t.jsxs("div",{children:[t.jsx("p",{className:"admin-home-v2__context",children:"Publishing"}),t.jsx("h2",{id:"admin-home-communications-title",children:"Communications"})]}),t.jsx("p",{children:"These audiences use separate publishing systems. Check the audience before opening a manager."})]}),t.jsxs("div",{className:"communications-summary__grid",children:[t.jsx(Gg,{audience:"Internal audience",description:"Updates for employees, staff, interns, and other authorized Workspace members.",href:Kg,icon:T,label:"Workspace Updates",status:a.status,summary:a.summary}),t.jsx(Gg,{audience:"Customer audience",description:"Announcements shown to authenticated TokenWorks dashboard users.",href:Hg,icon:yt,label:"Customer Announcements",status:e.status,summary:e.summary})]})]})}
2Gg.propTypes={audience:Yt.string.isRequired,description:Yt.string.isRequired,href:Yt.string.isRequired,icon:Yt.elementType.isRequired,label:Yt.string.isRequired,status:Yt.shape({label:Yt.string,state:Yt.oneOf(["draft","empty","error","loading","published","unavailable"]),variant:Yt.string}),summary:Yt.string};const Yg=Yt.shape({status:Yt.shape({label:Yt.string,state:Yt.oneOf(["draft","empty","error","loading","published","unavailable"]),variant:Yt.string}),summary:Yt.string});Jg.propTypes={customer:Yg.isRequired,workspace:Yg.isRequired};const Qg=[{id:"users",label:"Manage users",href:"/admin?tab=users"},{id:"uploads",label:"Review uploads",href:"/admin?tab=uploads"},{id:"requests",label:"Handle requests",href:"/admin?tab=requests"}],Xg={danger:"danger",info:"info",warning:"warning"},Zg={danger:"Urgent",info:"New",warning:"Review"};function ef({error:e,items:a,onRetry:n,state:s}){if("loading"===s)return t.jsx(Ku,{title:"Loading items that need attentionâ¦",tone:"loading"});if("error"===s)return t.jsx(Ku,{title:"Attention items are unavailable",tone:"error",action:n?t.jsx(ds,{variant:"secondary",onClick:n,children:"Try again"}):null,children:e||"Try again before relying on this operational summary."});const r="stale"===s?t.jsx(Ku,{title:"Attention refresh failed",tone:"error",action:n?t.jsx(ds,{variant:"secondary",onClick:n,children:"Try again"}):null,children:e||"Showing the last known summary. Retry before relying on its freshness."}):null;return 0===a.length?t.jsxs(t.Fragment,{children:[r,t.jsxs("div",{className:"admin-home-v2__clear-state",role:"status",children:[t.jsx(pe,{size:20,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:"stale"===s?"No urgent items in the last known summary":"No urgent items"}),t.jsx("p",{children:"stale"===s?"Refresh before relying on this result.":"There are no pending exceptions in the current summary."})]})]})]}):t.jsxs(t.Fragment,{children:[r,t.jsx("ul",{className:"admin-home-v2__attention-list",children:a.map(e=>t.jsxs("li",{className:"admin-home-v2__attention-item",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"admin-home-v2__attention-title",children:[t.jsx(li,{variant:Xg[e.tone]||"neutral",children:e.badge||Zg[e.tone]||"Notice"}),t.jsx("strong",{children:e.title})]}),e.detail?t.jsx("p",{children:e.detail}):null]}),e.href&&e.actionLabel?t.jsxs(l,{className:"admin-home-v2__row-link",to:e.href,children:[e.actionLabel,t.jsx(de,{size:16,"aria-hidden":"true"})]}):null]},e.id))})]})}function tf({attentionError:e="",attentionItems:a=[],attentionState:n="ready",communications:s,freshness:r="Freshness unavailable",onRetryAttention:i,pulseItems:o=[],quickLinks:c=Qg,recentActivity:d=[],recentActivityState:u="unavailable"}){return t.jsxs("div",{className:"admin-home-v2",children:[t.jsx("p",{className:"admin-home-v2__freshness",role:"status",children:r}),t.jsxs("div",{className:"admin-home-v2__priority-grid",children:[t.jsxs("section",{className:"admin-home-v2__attention","aria-labelledby":"admin-home-attention-title",children:[t.jsxs("div",{className:"admin-home-v2__section-heading admin-home-v2__section-heading--compact",children:[t.jsxs("div",{children:[t.jsx("p",{className:"admin-home-v2__context",children:"Priority"}),t.jsx("h2",{id:"admin-home-attention-title",children:"Needs attention"})]}),"ready"===n&&a.length>0?t.jsxs(li,{variant:"warning",children:[a.length," open ",1===a.length?"item":"items"]}):null]}),t.jsx(ef,{error:e,items:a,onRetry:i,state:n})]}),t.jsxs("nav",{className:"admin-home-v2__quick-paths","aria-labelledby":"admin-home-quick-paths-title",children:[t.jsx("div",{className:"admin-home-v2__section-heading admin-home-v2__section-heading--compact",children:t.jsxs("div",{children:[t.jsx("p",{className:"admin-home-v2__context",children:"Shortcuts"}),t.jsx("h2",{id:"admin-home-quick-paths-title",children:"Actions"})]})}),t.jsx("ul",{children:c.map(e=>t.jsx("li",{children:t.jsxs(l,{to:e.href,children:[t.jsx("span",{children:e.label}),t.jsx(de,{size:16,"aria-hidden":"true"})]})},e.id))})]})]}),t.jsxs("section",{className:"admin-home-v2__flat-section","aria-labelledby":"admin-home-pulse-title",children:[t.jsxs("div",{className:"admin-home-v2__section-heading admin-home-v2__section-heading--compact",children:[t.jsxs("div",{children:[t.jsx("p",{className:"admin-home-v2__context",children:"Current state"}),t.jsx("h2",{id:"admin-home-pulse-title",children:"Customer pulse"})]}),t.jsx(l,{className:"admin-home-v2__text-link",to:"/admin?tab=analytics",children:"View Analytics"})]}),o.length>0?t.jsx("dl",{className:"admin-home-v2__pulse-list",children:o.slice(0,4).map(e=>t.jsxs("div",{children:[t.jsx("dt",{children:e.label}),t.jsx("dd",{children:e.value}),e.detail?t.jsx("span",{children:e.detail}):null]},e.id))}):t.jsx("p",{className:"admin-home-v2__quiet-state",children:"No customer pulse is available."})]}),t.jsxs("div",{className:"admin-home-v2__communications-activity-grid",children:[t.jsx(Jg,{...s}),t.jsxs("section",{className:"admin-home-v2__flat-section admin-home-v2__recent-changes","aria-labelledby":"admin-home-activity-title",children:[t.jsx("div",{className:"admin-home-v2__section-heading admin-home-v2__section-heading--compact",children:t.jsxs("div",{children:[t.jsx("p",{className:"admin-home-v2__context",children:"Accountability"}),t.jsx("h2",{id:"admin-home-activity-title",children:"Recent operational changes"})]})}),d.length>0?t.jsx("ol",{className:"admin-home-v2__activity-list",children:d.map(e=>t.jsxs("li",{children:[t.jsxs("div",{children:[t.jsx("strong",{children:e.title}),e.detail?t.jsx("p",{children:e.detail}):null]}),e.time?t.jsx("time",{dateTime:e.dateTime,children:e.time}):null]},e.id))}):t.jsx("p",{className:"admin-home-v2__quiet-state",children:"not_instrumented"===u?"A privacy-safe recent changes feed is not instrumented yet.":"No recent operational changes are available."})]})]})]})}ef.propTypes={error:Yt.string,items:Yt.arrayOf(Yt.shape({actionLabel:Yt.string,badge:Yt.string,detail
2:Yt.string,href:Yt.string,id:Yt.string.isRequired,title:Yt.string.isRequired,tone:Yt.oneOf(["danger","info","warning"])})).isRequired,onRetry:Yt.func,state:Yt.oneOf(["error","loading","ready","stale"]).isRequired},tf.propTypes={attentionError:Yt.string,attentionItems:ef.propTypes.items,attentionState:ef.propTypes.state,communications:Yt.shape({customer:Yt.object.isRequired,workspace:Yt.object.isRequired}).isRequired,freshness:Yt.string,onRetryAttention:Yt.func,pulseItems:Yt.arrayOf(Yt.shape({detail:Yt.string,id:Yt.string.isRequired,label:Yt.string.isRequired,value:Yt.node.isRequired})),quickLinks:Yt.arrayOf(Yt.shape({href:Yt.string.isRequired,id:Yt.string.isRequired,label:Yt.string.isRequired})),recentActivity:Yt.arrayOf(Yt.shape({dateTime:Yt.string,detail:Yt.string,id:Yt.string.isRequired,time:Yt.string,title:Yt.string.isRequired})),recentActivityState:Yt.string};const af={author:null,id:"default",message:"",updatedAt:null,version:0};function nf(e){return{author:e?.author&&"object"==typeof e.author?e.author:null,id:"string"==typeof e?.id?e.id:af.id,message:"string"==typeof e?.message?e.message:"",updatedAt:"string"==typeof e?.updatedAt?e.updatedAt:null,version:Number.isInteger(Number(e?.version))?Number(e.version):0}}function sf(e,t){return{code:e?.error?.code||"ANNOUNCEMENT_REQUEST_FAILED",message:e?.error?.message||t}}function rf(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat("en",{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(t)}function lf({endpoint:a="/api/admin/announcement",makeAuthRequest:n,onAnnouncementChange:s,onDirtyChange:r}){const i=$s(),l=e.useId(),o=e.useId(),c=e.useId(),d=e.useId(),u=e.useId(),h=e.useRef(0),m=e.useRef(!0),[p,g]=e.useState(null),[f,b]=e.useState(""),[x,v]=e.useState(!0),[j,y]=e.useState(!1),[k,w]=e.useState(!1),[N,S]=e.useState(!1),[C,R]=e.useState(""),[E,I]=e.useState(null),[_,T]=e.useState(null),[A,O]=e.useState(""),D=e.useCallback(async({preserveDraft:e=!1}={})=>{const t=h.current+1;h.current=t,v(!0),R(""),O("");try{const s=await n(a);if(!s?.ok)throw sf(s,"Customer announcement could not be loaded.");if(!m.current||t!==h.current)return;const r=nf(s.data);g(r),e||b(r.message),I(null),e?(T(r),O("Current published version loaded. Your unsaved draft is preserved.")):T(null)}catch(s){if(!m.current||t!==h.current)return;R(s?.message||"Customer announcement could not be loaded.")}finally{m.current&&t===h.current&&v(!1)}},[a,n]);e.useEffect(()=>(m.current=!0,D(),()=>{m.current=!1,h.current+=1}),[D]);const P=p?.message||"",L=Boolean(p)&&f!==P;e.useEffect(()=>{if(r?.(L),!L)return;const e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[L,r]),e.useEffect(()=>()=>r?.(!1),[r]);if(x&&!p)return t.jsxs("section",{className:"customer-announcement-manager","aria-labelledby":u,children:[t.jsx("h1",{id:u,children:"Customer Announcements"}),t.jsx(Ku,{title:"Loading customer announcementâ¦",tone:"loading"})]});if(C&&!p)return t.jsxs("section",{className:"customer-announcement-manager","aria-labelledby":u,children:[t.jsx("h1",{id:u,children:"Customer Announcements"}),t.jsx(Ku,{title:"Customer announcement is unavailable",tone:"error",action:t.jsx(ds,{variant:"secondary",onClick:()=>D(),children:"Try again"}),children:C})]});const $=p||af,M="default"!==$.id&&Boolean($.message),U=1200-f.length,F=f.trim()===$.message,z="ANNOUNCEMENT_VERSION_CONFLICT"===E?.code,q=j||k||N;return t.jsxs("section",{id:"customer-announcement-manager",className:"customer-announcement-manager","aria-labelledby":u,children:[t.jsxs("div",{className:"customer-announcement-manager__heading",children:[t.jsxs("div",{children:[t.jsx("p",{className:"admin-home-v2__context",children:"Customer audience"}),t.jsx("h1",{id:u,children:"Customer Announcements"}),t.jsx("p",{children:"Publish one dashboard message to authenticated TokenWorks dashboard users. Workspace members do not receive this communication through Workspace Updates."})]}),t.jsx("span",{className:"customer-announcement-manager__state","aria-hidden":"true",children:L?"Unsaved changes":M?"Published":"No active announcement"}),t.jsx("span",{id:d,className:"sr-only","aria-live":"polite","aria-atomic":"true",children:L?"Announcement has unsaved changes.":"Announcement has no unsaved changes."})]}),$.updatedAt?t.jsxs("p",{className:"customer-announcement-manager__meta",children:["Current version ",$.version,$.author?.name?` · Published by ${$.author.name}`:"",rf($.updatedAt)?` · Updated ${rf($.updatedAt)} UTC`:""]}):null,t.jsxs("form",{onSubmit:async e=>{e.preventDefault();const t=f.trim();if(!t)return void I({code:"INVALID_MESSAGE",message:"Write an announcement before publishing."});if(!p||j||k||N)return;y(!0);const r="default"!==p.id&&Boolean(p.message);let l=!1;
2try{l=await i({title:r?"Update customer announcement?":"Publish customer announcement?",message:`This will ${r?"replace":"publish"} the message shown to authenticated TokenWorks dashboard users.`,confirmLabel:r?"Update announcement":"Publish announcement",confirmVariant:"primary"})}catch(o){l=!1}if(m.current&&(y(!1),l)){w(!0),I(null),O("");try{const e=await n(a,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({announcementId:p.id,expectedVersion:p.version,message:t})});if(!e?.ok){if(!m.current)return;return void I(sf(e,"Customer announcement could not be published."))}if(!m.current)return;const i=nf(e.data);g(i),b(i.message),T(null),O(r?"Customer announcement updated.":"Customer announcement published."),s?.(i)}catch(c){if(!m.current)return;I({code:c?.code||"ANNOUNCEMENT_UPDATE_FAILED",message:c?.message||"Customer announcement could not be published."})}finally{m.current&&w(!1)}}},children:[t.jsx(Wu,{htmlFor:l,label:"Announcement shown on customer dashboards",hint:"Plain text only. State the essential information and any action customers need to take.",hintId:c,children:t.jsx("textarea",{id:l,value:f,maxLength:1200,rows:8,disabled:q,"aria-describedby":`${c} ${o} ${d}`,onChange:e=>{b(e.target.value),I(null),O("")}})}),t.jsxs("div",{className:"customer-announcement-manager__form-footer",children:[t.jsxs("span",{id:o,className:"customer-announcement-manager__count",children:[U," characters remaining"]}),t.jsxs("div",{className:"customer-announcement-manager__actions",children:[t.jsx(ds,{variant:"secondary",disabled:q||F,onClick:()=>{b($.message),I(null),T(null),O("Draft reset to the published announcement.")},children:"Reset changes"}),t.jsx(ds,{variant:"danger",disabled:q||!M,onClick:async()=>{if(!p||"default"===p.id||N||k)return;if(await i({title:"Delete customer announcement?",message:"This removes the announcement from authenticated TokenWorks dashboard users. This action cannot be undone.",confirmLabel:"Delete announcement",confirmVariant:"danger"})){S(!0),I(null),O("");try{const e=await n(a,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({announcementId:p.id,expectedVersion:p.version})});if(!e?.ok){if(!m.current)return;return void I(sf(e,"Customer announcement could not be deleted."))}if(!m.current)return;const t=nf(e.data);g(t),b(t.message),T(null),O("Customer announcement deleted."),s?.(t)}catch(e){if(!m.current)return;I({code:e?.code||"ANNOUNCEMENT_DELETE_FAILED",message:e?.message||"Customer announcement could not be deleted."})}finally{m.current&&S(!1)}}},children:N?"Deletingâ¦":"Delete announcement"}),t.jsx(ds,{type:"submit",disabled:q||!f.trim()||F,children:k?M?"Updatingâ¦":"Publishingâ¦":M?"Update announcement":"Publish announcement"})]})]})]}),_?t.jsxs("section",{className:"customer-announcement-manager__comparison","aria-labelledby":`${u}-comparison`,children:[t.jsxs("div",{className:"customer-announcement-manager__comparison-heading",children:[t.jsxs("div",{children:[t.jsx("h2",{id:`${u}-comparison`,children:"Compare concurrent changes"}),t.jsxs("p",{children:["Review both messages before publishing against version ",$.version,"."]})]}),t.jsxs("div",{className:"customer-announcement-manager__actions",children:[t.jsx(ds,{variant:"secondary",onClick:async()=>{try{await navigator.clipboard.writeText(f),O("Local draft copied.")}catch(e){O("Copy is unavailable in this browser. Your local draft is still preserved.")}},disabled:q,children:"Copy local draft"}),t.jsx(ds,{variant:"danger",onClick:async()=>{if(!_)return;await i({title:"Replace the local draft?",message:"This discards your unsaved local draft and replaces it with the current published announcement.",confirmLabel:"Replace local draft",confirmVariant:"danger"})&&m.current&&(b(_.message),T(null),O("Local draft replaced with the current published announcement."))},disabled:q,children:"Replace with current"})]})]}),t.jsxs("div",{className:"customer-announcement-manager__comparison-grid",children:[t.jsxs("article",{children:[t.jsx("h3",{children:"Your preserved draft"}),t.jsx("p",{children:f.trim()||"Empty draft"})]}),t.jsxs("article",{children:[t.jsx("h3",{children:"Current published version"}),t.jsx("p",{children:_.message||"No active announcement"})]})]})]}):null,t.jsxs("section",{className:"customer-announcement-manager__preview","aria-labelledby":`${u}-preview`,children:[t.jsxs("div",{children:[t.jsx("p",{className:"admin-home-v2__context",children:"Preview"}),t.jsx("h3",{id:`${u}-preview`,children:"Customer dashboard message"})]}),f.trim()?t.jsx("p",{children:f.trim()}):t.jsx("p",{className:"customer-announcement-manager__preview-empty",children:"Write an announcement to preview the customer message."})]}),x?t.jsx("p",{className:"customer-announcement-manager__notice",role:"status","aria-live":"polite",children:"Reloading current announcementâ¦"}):null,C&&p?t.jsxs("div",{className:"customer-announcement-manager__notice is-error",role:"alert",children:[t.jsx("p",{children:C}),t.jsx(ds,{variant:"secondary",onClick:()=>D(),disabled:q||x,children:"Try reload again"})]}):null,E?t.jsxs("div",{className:"customer-announcement-manager__notice is-error",role:"alert",children:[t.jsx("p",{children:E.message}),z?t.jsx(ds,{variant:"secondary",onClick:()=>D({preserveDraft:!0}),disabled:q||x,children:"Load current version; keep draft"}):null]}):null,t.jsx("p",{className:"customer-announcement-manager__notice",role:"status","aria-live":"polite","aria-atomic":"true",children:A})]})}lf.propTypes={endpoint:Yt.string,makeAuthRequest:Yt.func.isRequired,onAnnouncementChange:Yt.func,onDirtyChange:Yt.func};const of=Object.freeze(["overview","customers","workspace","content","revenue","operations"]),cf=Object.freeze([1,7,30,90]),df=Object.freeze({overview:{label:"Overview",description:"Customers, revenue, and work needing administrator attention.",primary:["active_paid_customers","new_customer_signups","paid_revenue_by_currency","instrumented_active_customers"],attention:["past_due_customers","pending_customer_upload_requests","workspace_resource_job_health"]},customers:{label:"Customers",description:"Account, subscription, and consented product-activity signals for customer operations.",primary:["customer_accounts","active_paid_customers","new_customer_signups","instrumented_active_customers"],attention:["unresolved_payment_failures","past_due_customers","scheduled_cancellations","cancellation_flow"]}
2,workspace:{label:"Workspace",description:"Aggregate Workspace adoption and work health, protected by the server cohort threshold.",primary:["eligible_members","workspace_active_members_7d","workspace_active_members_30d","feature_adoption_by_surface"],attention:["task_exceptions","stale_projects","resource_jobs_by_state","update_publication_health"]},content:{label:"Content",description:"Document supply, successful access, saved-content, and per-document engagement signals.",primary:["documents_created","unique_document_viewers","successful_document_views","recorded_opens"],attention:["upload_requests_by_status"]},revenue:{label:"Revenue",description:"Local payment and subscription records, kept separate by currency and stated in minor units.",primary:["processing_credit_purchases","processing_credit_consumption","paid_revenue_by_currency","nominal_mrr_by_currency","cancellation_flow"],attention:["non_paid_rows_by_status"]},operations:{label:"Operations & Consent",description:"Current pipeline exceptions and bounded analytics-ingestion health for operator triage.",primary:["document_pipeline_by_status","analytics_events_ingested"],attention:["pending_customer_upload_requests","workspace_resource_job_health"]}}),uf=new Set(["customer_accounts","active_paid_customers","trialing_customers","past_due_customers","scheduled_cancellations","documents_by_status","recorded_opens","favorites","saved_documents","nominal_mrr_by_currency","active_paid_accounts","eligible_members","personnel_by_state","onboarding_by_status","task_exceptions","projects_by_status","overdue_projects","resources_by_status","ready_resource_bytes","resource_jobs_by_state","updates_by_status","document_pipeline_by_status","pending_customer_upload_requests","workspace_resource_job_health"]),hf=Object.freeze({customer_accounts:"Customer accounts",new_customer_signups:"New customer signups",active_paid_customers:"Active paid customers",trialing_customers:"Trialing customers",past_due_customers:"Past-due customers",cancellation_flow:"Cancellations",scheduled_cancellations:"Scheduled cancellations",instrumented_active_customers:"Instrumented active customers",documents_by_status:"Documents by status",documents_created:"Documents created",recorded_opens:"Recorded opens",unique_document_viewers:"Unique document viewers",successful_document_views:"Successful document views",upload_requests_by_status:"Upload requests by status",favorites:"Favorite flags",saved_documents:"Saved-document flags",paid_revenue_by_currency:"Paid revenue by currency",paid_payments_by_currency:"Paid payments by currency",non_paid_rows_by_status:"Non-paid rows by status",nominal_mrr_by_currency:"Nominal MRR by currency",active_paid_accounts:"Active paid accounts",eligible_members:"Eligible Workspace members",personnel_by_state:"Personnel by state",onboarding_by_status:"Onboarding by status",task_exceptions:"Task exceptions",task_completions:"Task completions",projects_by_status:"Projects by status",overdue_projects:"Overdue projects",resources_by_status:"Resources by status",ready_resource_bytes:"Ready Resource storage",resource_jobs_by_state:"Resource jobs by state",updates_by_status:"Workspace Updates by status",updates_published:"Workspace Updates published",document_pipeline_by_status:"Document pipeline by status",pending_customer_upload_requests:"Pending customer upload requests",workspace_resource_job_health:"Workspace Resource job health",analytics_events_ingested:"Analytics events ingested",signup_to_ever_paid_conversion:"Signup-to-paid conversion",unresolved_payment_failures:"Unresolved payment failures",processing_credit_purchases:"Processing Credit purchases",processing_credit_consumption:"Processing Credit consumption",workspace_active_members_7d:"Workspace active members (7d)",workspace_active_members_30d:"Workspace active members (30d)",feature_adoption_by_surface:"Workspace feature adoption",stale_projects:"Stale projects",update_publication_health:"Workspace Update publication health",recent_operational_changes:"Recent operational changes"}),mf=Object.freeze({available:{label:"Available",tone:"available"},partial:{label:"Partial data",tone:"warning"},stale:{label:"Stale snapshot",tone:"warning"},unavailable:{label:"Unavailable",tone:"unavailable"},not_instrumented:{label:"Not instrumented",tone:"unavailable"},suppressed:{label:"Suppressed for privacy",tone:"suppressed"}});function pf(e){return of.includes(e)?e:"overview"}function gf(e){const t=Number(e);return Number.isInteger(t)&&t>=1&&t<=365?t:30}function ff(e){return String(e||"").replaceAll("_"," ").replace(/\b\w/g,e=>e.toUpperCase())}function bf(e){return hf[e]||ff(e)}function xf(e){return uf.has(e)?"snapshot":"interval"}function vf(e){return mf[e]||{label:e?ff(e):"Unknown status",tone:"unavailable"}}function jf(e){if(!e)return"Unavailable";const t=new Date(e);return Number.isNaN(t.getTime())?"Unavailable":new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"UTC",timeZoneName:"short"}).format(t)}function yf(e){const t=Number(e);return Number.isFinite(t)?new Intl.NumberFormat("en-US",{maximumFractionDigits:2}).format(t):"Unavailable"}function kf(e){const t=Number(e);if(!Number.isFinite(t))return"Unavailable";if(0===t)return"0 bytes";
2if(t<0)return"Unavailable";const a=["bytes","KB","MB","GB","TB"],n=Math.min(Math.floor(Math.log(t)/Math.log(1024)),a.length-1),s=t/1024**n;return`${new Intl.NumberFormat("en-US",{maximumFractionDigits:1}).format(s)} ${a[n]}`}function wf(e,t){const a=Number(e),n=String(t||"").toUpperCase();if(!Number.isFinite(a)||!n)return"Unavailable";try{return new Intl.NumberFormat("en-US",{style:"currency",currency:n,currencyDisplay:"code"}).format(a/100)}catch(s){return`${n} ${yf(a/100)}`}}function Nf({status:e}){const a=vf(e);return t.jsx("span",{className:`admin-analytics-status admin-analytics-status--${a.tone}`,children:a.label})}function Sf({metricId:e,metric:a}){const n=!(s=a.value)||"object"!=typeof s||Array.isArray(s)?[]:Object.entries(s).map(([e,t])=>[e,Number(t)]).filter(([,e])=>Number.isFinite(e)).sort(([e],[t])=>e.localeCompare(t));var s;if(0===n.length)return t.jsx("strong",{className:"admin-analytics-value",children:"0"});const r=Math.max(...n.map(([,e])=>Math.abs(e)),1),i="minor_currency_units"===a.unit;return t.jsx("div",{className:"admin-analytics-breakdown",children:t.jsxs("table",{children:[t.jsxs("caption",{className:"sr-only",children:[bf(e)," values"]}),t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{scope:"col",children:i?"Currency":"State"}),t.jsx("th",{scope:"col",children:"Value"})]})}),t.jsx("tbody",{children:n.map(([e,a])=>t.jsxs("tr",{children:[t.jsx("th",{scope:"row",children:i?e.toUpperCase():ff(e)}),t.jsxs("td",{children:[t.jsx("span",{className:"admin-analytics-breakdown-value",children:i?wf(a,e):yf(a)}),t.jsx("span",{className:"admin-analytics-breakdown-track","aria-hidden":"true",children:t.jsx("span",{style:{inlineSize:`${Math.min(Math.abs(a)/r*100,100)}%`}})})]})]},e))})]})})}function Cf({metric:e}){const a=Object.entries(e.value||{}).filter(([,e])=>e&&"object"==typeof e&&!Array.isArray(e)).sort(([e],[t])=>e.localeCompare(t));return 0===a.length?t.jsx("strong",{className:"admin-analytics-value",children:"0"}):t.jsx("div",{className:"admin-analytics-breakdown admin-analytics-purchases",children:t.jsxs("table",{children:[t.jsx("caption",{className:"sr-only",children:"Processing Credit purchase values"}),t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{scope:"col",children:"Currency"}),t.jsx("th",{scope:"col",children:"Orders"}),t.jsx("th",{scope:"col",children:"Amount"}),t.jsx("th",{scope:"col",children:"Credits"})]})}),t.jsx("tbody",{children:a.map(([e,a])=>t.jsxs("tr",{children:[t.jsx("th",{scope:"row",children:e.toUpperCase()}),t.jsx("td",{"data-label":"Orders",children:yf(a.orders)}),t.jsx("td",{"data-label":"Amount",className:"admin-analytics-purchases__currency",children:wf(a.amount_cents,e)}),t.jsx("td",{"data-label":"Credits",children:yf(a.credit_units)})]},e))})]})})}function Rf({metric:e}){const a=e.value||{};return t.jsxs("div",{className:"admin-analytics-publication-health",children:[t.jsxs("dl",{children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Published in selected range"}),t.jsx("dd",{children:yf(a.published_in_range)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Latest publication"}),t.jsx("dd",{children:a.latest_published_at?jf(a.latest_published_at):"Never published"})]})]}),t.jsx(Sf,{metricId:"updates_by_status",metric:{...e,value:a.by_status||{}}})]})}function Ef({metricId:e,metric:a}){if("available"!==a.status||null===a.value||void 0===a.value){const e=vf(a.status);return t.jsx("strong",{className:"admin-analytics-value admin-analytics-value--unavailable",children:e.label})}return a.value&&"object"==typeof a.value&&!Array.isArray(a.value)?"processing_credit_purchases"===e?t.jsx(Cf,{metric:a}):"update_publication_health"===e?t.jsx(Rf,{metric:a}):t.jsx(Sf,{metricId:e,metric:a}):"logical_bytes"===a.unit?t.jsx("strong",{className:"admin-analytics-value",children:kf(a.value)}):t.jsx("strong",{className:"admin-analytics-value",children:yf(a.value)})}function If(e,t,a){if(!a)return"Unavailable";if(t?.measurement_window){const e=t.measurement_window;return`${jf(e.start)} to ${jf(e.end)} (end excluded) · fixed trailing ${e.days} days · ${e.time_zone}`}return"snapshot"===xf(e)?`Current snapshot at ${jf(a.end)}`:`${jf(a.start)} to ${jf(a.end)} (end excluded) · ${a.days} days · ${a.time_zone}`}function _f(e){const t=Number(e);return Number.isFinite(t)?0===t?"No change":`${t>0?"+":"â"}${yf(Math.abs(t))}`:"Unavailable"}function Tf({metricId:e,metric:a}
2){if("snapshot"===xf(e))return t.jsx("p",{children:"Current snapshot; prior-period comparison does not apply."});if(a.measurement_window)return t.jsx("p",{children:"Fixed trailing window; selected-range comparison does not apply."});const n=a.comparison;if(!n)return t.jsx("p",{children:"Previous equal-duration complete period; comparison unavailable."});const s="flat"===n.direction?"unchanged":n.direction,r="processing_credit_purchases"===e?"Orders change: ":"";return 0===n.prior_value?t.jsxs("p",{children:[r,"Prior period was zero; ",_f(n.absolute_change)," ","absolute change, ",s,". Percentage suppressed."]}):t.jsxs("p",{children:[r,_f(n.absolute_change)," (",yf(Math.abs(n.percent_change)),"%), ",s,", versus ",yf(n.prior_value)," in the previous equal-duration period."]})}function Af({metricId:e,metric:a,sources:n,range:s,variant:r="detail"}){const i=`admin-analytics-metric-${e}`,l=n?.[a.source],o=l?.as_of,c=function(e){if("available"!==e?.status)return!1;if(0===Number(e.value)&&null!==e.value&&""!==e.value)return!0;if(!e.value||"object"!=typeof e.value||Array.isArray(e.value))return!1;const t=e=>{if(null!==e&&""!==e&&"object"!=typeof e){const t=Number(e);return Number.isFinite(t)?[t]:[]}return!e||"object"!=typeof e||Array.isArray(e)?[]:Object.values(e).flatMap(t)},a=t(e.value);return 0===a.length||a.every(e=>0===e)}(a);return t.jsxs("article",{className:`admin-analytics-metric admin-analytics-metric--${r} admin-analytics-metric--${e}`,"aria-labelledby":i,children:[t.jsxs("div",{className:"admin-analytics-metric__heading",children:[t.jsx("h4",{id:i,children:bf(e)}),"available"!==a.status?t.jsx(Nf,{status:a.status}):null]}),t.jsx(Ef,{metricId:e,metric:a}),c?t.jsx("p",{className:"admin-analytics-zero",children:"Reported zero â source is available."}):null,t.jsx("div",{className:"admin-analytics-comparison",children:t.jsx(Tf,{metricId:e,metric:a})}),t.jsxs("details",{className:"admin-analytics-metric__details",children:[t.jsx("summary",{children:"Definition and source"}),t.jsx("p",{className:"admin-analytics-definition",children:a.definition||"Definition unavailable."}),t.jsxs("dl",{className:"admin-analytics-metadata",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Source"}),t.jsx("dd",{children:a.source||"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"As of"}),t.jsx("dd",{children:jf(o)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Range"}),t.jsx("dd",{children:If(e,a,s)})]}),a.minimum_cohort?t.jsxs("div",{children:[t.jsx("dt",{children:"Privacy threshold"}),t.jsxs("dd",{children:["Minimum cohort ",a.minimum_cohort]})]}):null,a.coverage_start?t.jsxs("div",{children:[t.jsx("dt",{children:"Coverage begins"}),t.jsx("dd",{children:jf(a.coverage_start)})]}):null]}),a.caveat?t.jsxs("p",{className:"admin-analytics-caveat",children:["Caveat: ",a.caveat]}):null]})]})}const Of=Object.freeze({SOURCE_NOT_INSTALLED:"Source is not installed",SOURCE_QUERY_FAILED:"Source query failed",COHORT_BELOW_THRESHOLD:"Suppressed below the privacy threshold",NO_PRODUCER_COVERAGE:"No approved events have been recorded",NO_SAFE_ALLOWLISTED_FEED:"No privacy-safe change feed is instrumented"});function Df({sources:e,cache:a,servedAt:n}){const s=Object.entries(e||{}).sort(([e],[t])=>e.localeCompare(t)),r=s.filter(([,e])=>"available"!==e.status).length;return t.jsxs("section",{className:"admin-analytics-section","aria-labelledby":"admin-analytics-source-heading",children:[t.jsx("div",{className:"admin-analytics-section__heading",children:t.jsxs("div",{children:[t.jsx("h3",{id:"admin-analytics-source-heading",children:"Source health"}),t.jsx("p",{children:"Availability and freshness for every source used by this category."})]})}),t.jsxs("details",{className:"admin-analytics-source-details",open:r>0||void 0,children:[t.jsxs("summary",{children:[t.jsxs("span",{children:[s.length-r," current · ",r," ",1===r?"issue":"issues"]}),t.jsxs("span",{children:["Served ",jf(n)]})]}),s.length?t.jsx("div",{className:"admin-analytics-sources",children:s.map(([e,a])=>{const n=vf(a.status);return t.jsxs("article",{className:"admin-analytics-source",children:[t.jsxs("div",{children:[t.jsx("h4",{children:ff(e)}),t.jsx("p",{children:a.as_of?`As of ${jf(a.as_of)}`:"No source timestamp"})]}),t.jsxs("div",{className:"admin-analytics-source__state",children:["available"!==a.status?t.jsx(Nf,{status:a.status}):null,a.error_code?t.jsxs("span",{children:[t.jsx("span",{children:Of[a.error_code]||n.label}),t.jsx("code",{children:a.error_code})]}):t.jsx("span",{children:n.label})]})]},e)})}):t.jsx("p",{className:"admin-analytics-empty",children:"No source-health records were returned."}),t.jsxs("dl",{className:"admin-analytics-cache",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Cache result"}),t.jsx("dd",{children:a?.status?ff(a.status):"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Cache TTL"}),t.jsx("dd",{children:Number.isFinite(Number(a?.ttl_seconds))?`${a.ttl_seconds} seconds`:"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Cache scope"}),t.jsxs("dd",{children:[a?a.shared_across_instances?"Shared across instances":"Process-local only":"Unavailable",a?.scope?t.jsx("code",{children:a.scope}):null]})]})]})]})]})}const Pf=Object.freeze([{id:"reads",label:"Reads",valueLabel:"Successful views",secondaryLabel:"Unique readers"},{id:"favorites",label:"Favorites",valueLabel:"Favorite flags"},{id:"saved",label:"Saved",valueLabel:"Saved flags"},{id:"bookmarks",label:"Bookmarks",valueLabel:"Page bookmarks"},{id:"opens",label:"Recorded opens",valueLabel:"Recorded opens"}]);function Lf(e,t){return"selected_interval"===e?`${t?.days||30}-day interval ending ${jf(t?.end)}`:"current_snapshot"===e?"Current snapshot":"all_time"===e?"All-time total":"Measurement window unavailable"}function $f(e){return`/admin?${new URLSearchParams({tab:"text-coverage",doc:e}).toString()}`}function Mf({engagement:a,range:n}){const[s,r]=e.useState("reads"),i=a?.rankings||{},o=Pf.find(e=>e.id===s)||Pf[0],c=i[o.id]||{status:"unavailable",rows:[],definition:"Definition unavailable."},d=Array.isArray(c.rows)?c.rows:[],u=Math.max(...d.map(e=>Number(e.value)||0),1);return t.jsxs("section",{className:"admin-analytics-section admin-content-engagement","aria-labelledby":"admin-content-engagement-heading",children:[t.jsxs("div",{className:"admin-analytics-section__heading admin-content-engagement__heading",children:[t.jsxs("div",{children:[t.jsx("h3",{id:"admin-content-engagement-heading",children:"Document engagement"}),t.jsx("p",{children:"Compare the most-read, favorited, saved, bookmarked, and opened documents, then inspect each documentâs Wikibase and text-processing status."})]}),t.jsx(l,{className:"admin-content-engagement__status-link",to:"/admin?tab=text-coverage",children:"Open Wikibase status"})]}),t.jsx("div",{className:"admin-content-engagement__controls",role:"group","aria-label":"Document engagement ranking",children:Pf.map(e=>{const a=i[e.id],n=a?.status||"unavailable";return t.jsxs("button",{type:"button","aria-label":`${e.label}${"available"===n?"":" unavailable"}`,"aria-pressed":e.id===o.id,onClick:()=>r(e.id),children:[e.label,"available"!==n?t.jsx("span",{className:"admin-content-engagement__control-state",children:" Unavailable"}):null]},e.id)})}),t.jsxs("div",{className:"admin-content-engagement__summary",children:[t.jsxs("div",{children:[t.jsx("h4",{children:o.label}),t.jsx("p",{children:Lf(c.scope,n)})]}),"available"!==c.status?t.jsx(Nf,{status:c.status}):null]}),"available"!==c.status?t.jsx("div",{className:"admin-content-engagement__state",role:"status",children:(h=c.status,"not_instrumented"===h?"No approved read events have been recorded yet. Other engagement rankings remain available.":"This ranking source is unavailable. Choose another engagement signal or check Source health.")}):0===d.length?t.jsxs("div",{className:"admin-content-engagement__state",role:"status",children:["No ",o.label.toLowerCase()," have been recorded for this measurement window."]}):t.jsxs(t.Fragment,{children:[t.jsx("ol",{className:"admin-content-engagement__bars","aria-label":`${o.label} document ranking`,children:d.map((e,a)=>{const n=Number(e.value)||0;return t.jsxs("li",{children:[t.jsxs("div",{className:"admin-content-engagement__bar-label",children:[t.jsx("span",{className:"admin-content-engagement__rank","aria-label":`Rank ${a+1}
2`,children:a+1}),t.jsx(l,{to:$f(e.document_id),children:e.title||"Untitled document"}),t.jsx("strong",{children:yf(n)})]}),t.jsx("span",{className:"admin-content-engagement__track","aria-hidden":"true",children:t.jsx("span",{style:{inlineSize:`${Math.max(n/u*100,2)}%`}})}),c.secondary_label?t.jsxs("span",{className:"admin-content-engagement__secondary",children:[yf(e.secondary_value)," ",c.secondary_label.toLowerCase()]}):null]},e.document_id)})}),t.jsxs("details",{className:"admin-content-engagement__table-disclosure",children:[t.jsx("summary",{children:"View ranking data table"}),t.jsx("div",{className:"admin-content-engagement__table-scroll",children:t.jsxs("table",{children:[t.jsxs("caption",{children:[o.label," by document"]}),t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{scope:"col",children:"Rank"}),t.jsx("th",{scope:"col",children:"Document"}),t.jsx("th",{scope:"col",children:o.valueLabel}),c.secondary_label?t.jsx("th",{scope:"col",children:c.secondary_label}):null]})}),t.jsx("tbody",{children:d.map((e,a)=>t.jsxs("tr",{children:[t.jsx("td",{children:a+1}),t.jsx("th",{scope:"row",children:t.jsx(l,{to:$f(e.document_id),children:e.title||"Untitled document"})}),t.jsx("td",{children:yf(e.value)}),c.secondary_label?t.jsx("td",{children:yf(e.secondary_value)}):null]},e.document_id))})]})})]})]}),t.jsx("p",{className:"admin-content-engagement__definition",children:c.definition})]});var h}const Uf=["#22d3ee","#6366f1","#f59e0b","#10b981","#ef4444","#ec4899","#8b5cf6","#14b8a6"],Ff=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e,zf=({active:e,payload:a,labelKey:n})=>{if(!e||!a?.length)return null;const s=a[0]?.payload;return t.jsxs("div",{className:"chart-tooltip-custom",children:[t.jsx("span",{className:"chart-tooltip-label",children:s?.[n]??s?.label}),a.map((e,a)=>t.jsxs("span",{className:"chart-tooltip-value",style:{color:e.color},children:["value"!==e.name?`${e.name}: `:"","number"==typeof e.value?e.value.toLocaleString():e.value]},a))]})},qf=({type:a="bar",data:n=[],title:s,height:r=300,color:i="#22d3ee",showGrid:l=!0,showLegend:o=!1,stacked:c=!1,dataKeys:d,colors:u,centerLabel:h,ariaLabel:m="Data visualization"})=>{const p=(e=>!e||e.startsWith("var(")?"#22d3ee":e)(i),g=e.useId().replaceAll(":","");if(!n||0===n.length)return t.jsxs("div",{className:"chart-wrapper",children:[s&&t.jsx("h3",{className:"chart-title",children:s}),t.jsx("div",{className:"chart-container",style:{height:r},children:t.jsx("div",{className:"chart-empty",children:"No data available"})})]});const f={fontSize:11,fill:"rgba(148,163,184,0.7)"},b={strokeDasharray:"3 3",stroke:"rgba(148,163,184,0.12)",vertical:!1},x=n.length>20?Math.ceil(n.length/8):1,v=(e,t)=>t%x!==0?"":n[t]?.label??"";return t.jsxs("div",{className:"chart-wrapper",role:"group","aria-label":m,children:[s&&t.jsx("h3",{className:"chart-title",children:s}),"line"===a&&(()=>{const e=d||["value"],a=u||[p,"#6366f1","#f59e0b","#10b981"];return t.jsx(ka,{width:"100%",height:r,children:t.jsxs(wa,{data:n,margin:{top:8,right:8,left:-12,bottom:0},children:[l&&t.jsx(Na,{...b}),t.jsx(Sa,{dataKey:"label",tick:f,tickLine:!1,axisLine:!1,tickFormatter:v,interval:0}),t.jsx(Ca,{tick:f,tickLine:!1,axisLine:!1,tickFormatter:Ff}),t.jsx(Ra,{content:t.jsx(zf,{labelKey:"label"})}),o&&t.jsx(Ea,{wrapperStyle:{fontSize:12}}),e.map((e,n)=>t.jsx(Ia,{type:"monotone",dataKey:e,stroke:a[n%a.length],strokeWidth:2.25,dot:!1,activeDot:{r:4,strokeWidth:2,stroke:"#0f172a"}},e))]})})})(),"area"===a&&(()=>{const e=d||["value"],a=u||[p,"#6366f1","#f59e0b","#10b981"];return t.jsx(ka,{width:"100%",height:r,children:t.jsxs(_a,{data:n,margin:{top:8,right:8,left:-12,bottom:0},children:[t.jsx("defs",{children:e.map((e,n)=>t.jsxs("linearGradient",{id:`grad-${g}-${String(e).replaceAll(/[^a-zA-Z0-9_-]/g,"-")}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{offset:"0%",stopColor:a[n%a.length],stopOpacity:.3}),t.jsx("stop",{offset:"100%",stopColor:a[n%a.length],stopOpacity:0})]},e))}),l&&t.jsx(Na,{...b}),t.jsx(Sa,{dataKey:"label",tick:f,tickLine:!1,axisLine:!1,tickFormatter:v,interval:0}
2),t.jsx(Ca,{tick:f,tickLine:!1,axisLine:!1,tickFormatter:Ff}),t.jsx(Ra,{content:t.jsx(zf,{labelKey:"label"})}),o&&t.jsx(Ea,{wrapperStyle:{fontSize:12}}),e.map((e,n)=>t.jsx(Ta,{type:"monotone",dataKey:e,stroke:a[n%a.length],strokeWidth:2,fill:`url(#grad-${g}-${String(e).replaceAll(/[^a-zA-Z0-9_-]/g,"-")})`,dot:!1,activeDot:{r:4,strokeWidth:2,stroke:"#0f172a"},stackId:c?"stack":void 0},e))]})})})(),"bar"===a&&(()=>{const e=d||["value"],a=u||[p,"#6366f1","#f59e0b","#10b981"];return t.jsx(ka,{width:"100%",height:r,children:t.jsxs(Aa,{data:n,margin:{top:8,right:8,left:-12,bottom:0},barGap:4,children:[l&&t.jsx(Na,{...b}),t.jsx(Sa,{dataKey:"label",tick:f,tickLine:!1,axisLine:!1,tickFormatter:v,interval:0}),t.jsx(Ca,{tick:f,tickLine:!1,axisLine:!1,tickFormatter:Ff}),t.jsx(Ra,{content:t.jsx(zf,{labelKey:"label"}),cursor:{fill:"rgba(148,163,184,0.06)"}}),o&&t.jsx(Ea,{wrapperStyle:{fontSize:12}}),e.map((e,n)=>t.jsx(Oa,{dataKey:e,fill:a[n%a.length],radius:[4,4,0,0],stackId:c?"stack":void 0,maxBarSize:48},e))]})})})(),"pie"===a&&(()=>{const e=n.reduce((e,t)=>e+(t.value||0),0);return t.jsxs("div",{className:"chart-donut-wrapper",children:[t.jsx(ka,{width:"100%",height:r,children:t.jsxs(Da,{children:[t.jsx(Pa,{data:n,dataKey:"value",nameKey:"label",cx:"50%",cy:"50%",innerRadius:"55%",outerRadius:"80%",paddingAngle:2,strokeWidth:0,children:n.map((e,a)=>t.jsx(La,{fill:e.color||Uf[a%Uf.length]},a))}),t.jsx(Ra,{content:t.jsx(zf,{labelKey:"label"})}),o&&t.jsx(Ea,{wrapperStyle:{fontSize:12}})]})}),h&&t.jsxs("div",{className:"chart-donut-center",children:[t.jsx("span",{className:"chart-donut-center-value",children:h}),t.jsx("span",{className:"chart-donut-center-label",children:"total"})]}),t.jsx("div",{className:"chart-pie-legend",children:n.map((a,n)=>{const s=e>0?(a.value/e*100).toFixed(1):"0.0";return t.jsxs("div",{className:"chart-pie-legend-item",children:[t.jsx("span",{className:"chart-pie-legend-color",style:{backgroundColor:a.color||Uf[n%Uf.length]}}),t.jsx("span",{className:"chart-pie-legend-label",children:a.label}),t.jsxs("span",{className:"chart-pie-legend-value",children:[a.value," (",s,"%)"]})]},n)})})]})})()]})},Bf=({data:e=[],metricKeys:a=[],metricOptions:n=[],chartMode:s="area",height:r=380,ariaLabel:i="Analytics chart"})=>{const l=n.filter(e=>a.includes(e.id)).map(e=>e.color);if(0===a.length)return t.jsx("div",{className:"analytics-main-chart-empty",children:"Select at least one metric to render this chart."});return e.some(e=>a.some(t=>Number(e?.[t]||0)>0))?t.jsx("div",{className:"analytics-main-chart-wrap",children:t.jsx(qf,{type:"stacked"===s?"bar":s,data:e,dataKeys:a,colors:l,stacked:"stacked"===s,showLegend:!0,height:r,ariaLabel:i})}):t.jsx("div",{className:"analytics-main-chart-empty",children:"No activity is available for the selected metrics and range."})};function Wf(t){const a=e.useRef(0),[n,s]=e.useState(0),[r,i]=e.useState({data:null,loading:!0,error:null}),l=e.useCallback(()=>s(e=>e+1),[]);return e.useEffect(()=>{const e=a.current+1;a.current=e;let n=!0;return i(e=>({...e,loading:!0,error:null})),async function(){try{if("function"!=typeof t)throw new Error("Visualization data request is not configured.");const s=function(e){if(!1===e?.ok)throw new Error(e.error?.message||"Visualization data could not be loaded.");const t=e?.data??e;if(!t||"object"!=typeof t)throw new Error("Visualization data returned an invalid response.");return t}(await t("/api/admin/metrics"));if(!n||e!==a.current)return;i({data:s,loading:!1,error:null})}catch(s){if(!n||e!==a.current)return;i(e=>({...e,loading:!1,error:s?.message||"Visualization data could not be loaded."}))}}(),()=>{n=!1}},[t,n]),{...r,reload:l}}const Vf=Object.freeze([{id:"New users",source:"new_users_weekly",color:"#22d3ee"},{id:"Active users",source:"active_users_weekly",color:"#a78bfa"},{id:"Subscriptions",source:"subscriptions_weekly",color:"#34d399"},{id:"Documents",source:"documents_weekly",color:"#fbbf24"},{id:"Cancellations",source:"cancellations_weekly",color:"#fb7185"}]);function Hf(e){return Array.isArray(e)?e:[]}const Kf=[12,26,52],Gf=[{id:"line",label:"Lines"},{id:"bar",label:"Bars"}];function Jf({title:e,data:a,columns:n}){return a.length?t.jsxs("details",{className:"admin-analytics-data-table",children:[t.jsx("summary",{children:"View data table"}),t.jsx("div",{children:t.jsxs("table",{children:[t.jsx("caption",{children:e}),t.jsx("thead",{children:t.jsx("tr",{children:n.map(e=>t.jsx("th",{scope:"col",children:e.label},e.key))})}),t.jsx("tbody",{children:a.map((e,a)=>t.jsx("tr",{children:n.map((a,n)=>{const s=e[a.key];return 0===n?t.jsx("th",{scope:"row",children:s}
2,a.key):t.jsx("td",{children:Number(s||0).toLocaleString()},a.key)})},`${e.label||"row"}-${a}`))})]})})]}):null}function Yf({title:e,description:a,type:n,data:s,color:r,centerLabel:i}){return t.jsxs("figure",{className:"admin-analytics-visual-card",children:[t.jsxs("figcaption",{children:[t.jsx("h4",{children:e}),t.jsx("p",{children:a})]}),t.jsx(qf,{type:n,data:s,height:260,color:r,centerLabel:i,ariaLabel:`${e}. ${a}`}),t.jsx(Jf,{title:`${e} values`,data:s,columns:[{key:"label",label:"Category"},{key:"value",label:"Value"}]})]})}function Qf({makeAuthRequest:a}){const{data:n,loading:s,error:r,reload:i}=Wf(a),[l,o]=e.useState(12),[c,d]=e.useState("line"),[u,h]=e.useState(["New users","Active users","Documents"]),m=e.useMemo(()=>function(e,t=12){const a=new Map,n=[12,26,52].includes(Number(t))?Number(t):12;return Vf.forEach(t=>{Hf(e?.growth?.[t.source]).slice(-n).forEach((e,n)=>{const s=e?.week_start||`${e?.label||"week"}-${n}`,r=a.get(s)||{sortKey:e?.week_start||String(n).padStart(3,"0"),label:e?.label||`Week ${n+1}`};r[t.id]=Number(e?.value||0),a.set(s,r)})}),[...a.values()].sort((e,t)=>String(e.sortKey).localeCompare(String(t.sortKey))).map(({sortKey:e,...t})=>t)}(n,l),[n,l]),p=e.useMemo(()=>{return e=n,Hf(e?.user_distribution?.by_role).map(e=>({label:String(e?.role_name||"Unassigned").replaceAll("_"," "),value:Number(e?.count||0)})).filter(e=>e.value>0).sort((e,t)=>t.value-e.value);var e},[n]),g=e.useMemo(()=>{return e=n,Hf(e?.subscription_overview?.by_status).map(e=>({label:String(e?.status||"unknown").replaceAll("_"," "),value:Number(e?.count||0)})).filter(e=>e.value>0).sort((e,t)=>t.value-e.value);var e},[n]),f=e.useMemo(()=>{return e=n,Hf(e?.consent_analytics?.daily_activity).map((e,t)=>({label:e?.label||`Day ${t+1}`,"Page views":Number(e?.page_views||0),"Navigation clicks":Number(e?.nav_clicks||0),"Consent updates":Number(e?.consent_updates||0)}));var e},[n]),b=Vf.filter(e=>u.includes(e.id)),x=m.at(-1);return t.jsxs("section",{className:"admin-analytics-visuals","aria-labelledby":"admin-analytics-visuals-heading",children:[t.jsxs("div",{className:"admin-analytics-section__heading",children:[t.jsxs("div",{children:[t.jsx("h3",{id:"admin-analytics-visuals-heading",children:"Explore the data"}),t.jsx("p",{children:"Compare weekly platform activity, then inspect current audience and subscription composition. Charts use aggregate administrator metrics and never expose identities."})]}),t.jsx("button",{type:"button",onClick:i,disabled:s,children:s&&n?"Refreshing chartsâ¦":"Refresh charts"})]}),s&&!n?t.jsx("div",{className:"admin-analytics-visual-state",role:"status","aria-live":"polite",children:"Loading visualizationsâ¦"}):null,r?t.jsxs("div",{className:"admin-analytics-visual-state admin-analytics-visual-state--error",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"Visualizations unavailable"}),t.jsx("span",{children:r}),n?t.jsx("span",{children:"Existing chart data remains visible."}):null]}),t.jsx("button",{type:"button",onClick:i,disabled:s,children:"Retry charts"})]}):null,n?t.jsxs(t.Fragment,{children:[t.jsxs("figure",{className:"admin-analytics-trend-explorer",children:[t.jsxs("figcaption",{children:[t.jsxs("div",{children:[t.jsx("h4",{children:"Weekly activity"}),t.jsx("p",{children:"Choose a range, display, and metrics. Hover, click, or use the keyboard for exact values."})]}),x?t.jsxs("p",{className:"admin-analytics-chart-summary","aria-live":"polite",children:["Latest (",x.label,"):"," ",u.map(e=>`${e} ${Number(x[e]||0).toLocaleString()}`).join(" · ")]}):null]}),t.jsxs("div",{className:"admin-analytics-chart-controls",children:[t.jsxs("div",{role:"group","aria-label":"Weekly trend range",children:[t.jsx("span",{children:"Range"}),Kf.map(e=>t.jsxs("button",{type:"button","aria-pressed":l===e,onClick:()=>o(e),children:[e," weeks"]},e))]}),t.jsxs("div",{role:"group","aria-label":"Weekly trend display",children:[t.jsx("span",{children:"Display"}),Gf.map(e=>t.jsx("button",{type:"button","aria-pressed":c===e.id,onClick:()=>d(e.id),children:e.label},e.id))]})]}),t.jsx("div",{className:"admin-analytics-metric-toggles",role:"group","aria-label":"Trend metrics",children:Vf.map(e=>{const a=u.includes(e.id);return t.jsxs("button",{type:"button","aria-pressed":a,onClick:()=>{return t=e.id,void h(e=>e.includes(t)?1===e.length?e:e.filter(e=>e!==t):Vf.map(e=>e.id).filter(a=>e.includes(a)||a===t));var t},children:[t.jsx("span",{style:{backgroundColor:e.color},"aria-hidden":"true"}),e.id]},e.id)})}),t.jsx(Bf,{data:m,metricKeys:u,metricOptions:Vf,chartMode:c,height:360,ariaLabel:`Weekly activity over ${l} weeks for ${u.join(", ")}`}),t.jsx(Jf,{title:`Weekly activity over ${l} weeks`,data:m,columns:[{key:"label",label:"Week"},...b.map(e=>({key:e.id,label:e.id}))]})]}),t.jsxs("div",{className:"admin-analytics-visual-grid",children:[t.jsx(Yf,{title:"Users by role",description:"Active role assignments, including the customer fallback for accounts without an active grant.",type:"bar",data:p,color:"#22d3ee"}),t.jsx(Yf,{title:"Subscription status",description:"Current and recently ended subscription records grouped by lifecycle state.",type:"pie",data:g,centerLabel:String(g.reduce((e,t)=>
2e+t.value,0))})]}),f.length?t.jsxs("figure",{className:"admin-analytics-visual-card admin-analytics-visual-card--wide",children:[t.jsxs("figcaption",{children:[t.jsx("h4",{children:"Consented product activity"}),t.jsx("p",{children:"Daily aggregate events from visitors who allowed analytics during the last 30 days."})]}),t.jsx(qf,{type:"line",data:f,dataKeys:["Page views","Navigation clicks","Consent updates"],colors:["#a78bfa","#22d3ee","#fbbf24"],showLegend:!0,height:280,ariaLabel:"Daily consented page views, navigation clicks, and consent updates"}),t.jsx(Jf,{title:"Daily consented product activity",data:f,columns:[{key:"label",label:"Day"},{key:"Page views",label:"Page views"},{key:"Navigation clicks",label:"Navigation clicks"},{key:"Consent updates",label:"Consent updates"}]})]}):null]}):null]})}function Xf({makeAuthRequest:t,category:a,days:n,timeZone:s="UTC"}){const r=e.useRef(0),[i,l]=e.useState(0),[o,c]=e.useState({key:"",data:null,loading:!0,refreshing:!1,error:null}),d=pf(a),u=gf(n),h="UTC"===s?s:"UTC",m=`${d}:${u}:${h}`,p=e.useCallback(()=>l(e=>e+1),[]);return e.useEffect(()=>{const e="operations"===d?6e4:3e5,t=window.setInterval(p,e);return()=>window.clearInterval(t)},[p,d]),e.useEffect(()=>{const e=r.current+1;r.current=e;let a=!0;return c(e=>{const t=e.key===m&&e.data;return{key:m,data:t?e.data:null,loading:!t,refreshing:Boolean(t),error:null}}),async function(){try{if("function"!=typeof t)throw new Error("Admin analytics request is not configured.");const n=function(e){if(!1===e?.ok)throw new Error(e.error?.message||"Admin analytics could not be loaded.");const t=e?.data??e;if(!t||"object"!=typeof t||!t.metrics||!t.sources)throw new Error("Admin analytics returned an invalid response.");return t}(await t(`/api/admin/analytics/${d}?days=${u}&time_zone=${h}`));if("admin-analytics/v1"!==n.schema_version||n.category!==d||n.range?.days!==u||n.range?.time_zone!==h)throw new Error("Admin analytics returned a response for a different request.");if(!a||e!==r.current)return;c({key:m,data:n,loading:!1,refreshing:!1,error:null})}catch(n){if(!a||e!==r.current)return;c(e=>({...e,loading:!1,refreshing:!1,error:n?.message||"Admin analytics could not be loaded."}))}}(),()=>{a=!1}},[t,i,m,d,u,h]),{...o,reload:p,category:d,days:u}}function Zf({status:e}){if("available"===e)return null;const a=vf(e),n={partial:"Some sources are unavailable. Known values remain visible and missing values are marked.",stale:"A refresh failed, so this is the last successful snapshot. Check source health before acting.",unavailable:"No source returned usable data for this category.",suppressed:"Values are hidden because the eligible cohort is below the privacy threshold."}[e];return t.jsxs("div",{className:`admin-analytics-notice admin-analytics-notice--${a.tone}`,role:"unavailable"===e?"alert":"status",children:[t.jsx("strong",{children:a.label}),t.jsx("span",{children:n||"The response status needs administrator review."})]})}function eb(){return t.jsxs("div",{className:"admin-analytics-loading",role:"status","aria-live":"polite",children:[t.jsx("strong",{children:"Loading analyticsâ¦"}),t.jsx("span",{children:"Requesting the selected category and range."})]})}function tb({title:e,description:a,metricIds:n,metrics:s,data:r,variant:i}){const l=n.filter(e=>s[e]);return l.length?t.jsxs("section",{className:"admin-analytics-section","aria-labelledby":`admin-analytics-${i}-heading`,children:[t.jsx("div",{className:"admin-analytics-section__heading",children:t.jsxs("div",{children:[t.jsx("h3",{id:`admin-analytics-${i}-heading`,children:e}),t.jsx("p",{children:a})]})}),t.jsx("div",{className:`admin-analytics-metrics admin-analytics-metrics--${i}`,children:l.map(e=>t.jsx(Af,{metricId:e,metric:s[e],sources:r.sources,range:r.range,variant:i},e))})]}):null}function ab({makeAuthRequest:a,category:n,days:s,onCategoryChange:r,onDaysChange:i,timeZone:l="UTC",className:o=""}){const[c,d]=e.useState("overview"),[u,h]=e.useState(30),m=pf(n??c),p=gf(s??u),[g,f]=e.useState(String(p)),[b,x]=e.useState(!cf.includes(p)),v=df[m],{data:j,loading:y,refreshing:k,error:w,reload:N}=Xf({makeAuthRequest:a,category:m,days:p,timeZone:l});function S(e){void 0===n&&d(e),r?.(e)}function C(e){void 0===s&&h(e),i?.(e)}e.useEffect(()=>{f(String(p)),cf.includes(p)||x(!0)},[p]);const R=j?.metrics||{},E=v.primary.filter(e=>R[e]).slice(0,4),I=v.attention.filter(e=>R[e]&&!E.includes(e)),_=new Set([...E,...I]),T=function(e,t){const a=df[e],n=[...a.primary,...a.attention],s=Object.keys(t||{});return[...n.filter((e,t)=>
2s.includes(e)&&n.indexOf(e)===t),...s.filter(e=>!n.includes(e)).sort()]}(m,R).filter(e=>!_.has(e));return t.jsxs("section",{className:`admin-analytics-v2 ${o}`.trim(),"aria-labelledby":"admin-analytics-heading","aria-busy":y||k,children:[t.jsxs("header",{className:"admin-analytics-header",children:[t.jsxs("div",{children:[t.jsx("h1",{id:"admin-analytics-heading",children:"Analytics"}),t.jsx("h2",{children:v.label}),t.jsx("p",{children:v.description})]}),t.jsxs("div",{className:"admin-analytics-header__status",children:[j?t.jsx(Nf,{status:j.status}):null,t.jsx("button",{type:"button",onClick:N,disabled:y||k,children:k?"Refreshingâ¦":"Refresh data"})]})]}),t.jsx("nav",{className:"admin-analytics-categories","aria-label":"Analytics categories",children:of.map(e=>t.jsx("button",{type:"button","aria-current":e===m?"page":void 0,onClick:()=>S(e),children:df[e].label},e))}),t.jsxs("div",{className:"admin-analytics-mobile-controls",children:[t.jsxs("label",{children:[t.jsx("span",{children:"Category"}),t.jsx("select",{"aria-label":"Analytics category",value:m,onChange:e=>S(e.target.value),children:of.map(e=>t.jsx("option",{value:e,children:df[e].label},e))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Range"}),t.jsxs("select",{"aria-label":"Analytics range selection",value:b?"custom"
2:String(p),onChange:e=>{"custom"!==e.target.value?(x(!1),C(Number(e.target.value))):x(!0)},children:[cf.map(e=>t.jsx("option",{value:e,children:1===e?"24 hours":`${e} days`},e)),t.jsxs("option",{value:"custom",children:["Custom (",p," days)"]})]})]}),b?t.jsxs("form",{className:"admin-analytics-mobile-custom-range",onSubmit:e=>{e.preventDefault(),C(gf(g))},children:[t.jsxs("label",{htmlFor:"admin-analytics-mobile-custom-days",children:[t.jsx("span",{children:"Custom days"}),t.jsx("input",{id:"admin-analytics-mobile-custom-days",type:"number",min:"1",max:"365",step:"1",inputMode:"numeric",value:g,onChange:e=>f(e.target.value)})]}),t.jsx("button",{type:"submit",children:"Apply custom range"})]}):null]}),t.jsxs("div",{className:"admin-analytics-range",role:"group","aria-label":"Analytics time range",children:[t.jsx("span",{children:"Range"}),cf.map(e=>t.jsx("button",{type:"button","aria-pressed":e===p,onClick:()=>C(e),children:1===e?"24 hours":`${e} days`},e)),t.jsxs("form",{className:"admin-analytics-custom-range",onSubmit:e=>{e.preventDefault(),C(gf(g))},children:[t.jsx("label",{htmlFor:"admin-analytics-custom-days",children:"Custom days"}),t.jsx("input",{id:"admin-analytics-custom-days",type:"number",min:"1",max:"365",step:"1",inputMode:"numeric",value:g,onChange:e=>f(e.target.value)}),t.jsx("button",{type:"submit",children:"Apply"})]}),t.jsx("span",{className:"admin-analytics-time-zone",children:"UTC"})]}),y&&!j?t.jsx(eb,{}):null,w?t.jsxs("div",{className:"admin-analytics-notice admin-analytics-notice--error",role:"alert",children:[t.jsx("strong",{children:j?"Refresh failed":"Analytics unavailable"}),t.jsx("span",{children:w}),j?t.jsxs("span",{children:["Showing the last response generated ",jf(j.generated_at),"."]}):null,t.jsx("button",{type:"button",onClick:N,disabled:k,children:"Retry"})]}):null,"overview"!==m||j?null:t.jsx(Qf,{makeAuthRequest:a}),j?t.jsxs(t.Fragment,{children:[t.jsx(Zf,{status:j.status}),t.jsx(tb,{title:"Primary indicators",description:"At most four decision-oriented indicators for the selected category.",metricIds:E,metrics:R,data:j,variant:"primary"}),t.jsxs("div",{className:"admin-analytics-response-meta",role:"status","aria-live":"polite",children:[t.jsxs("span",{children:["Generated"," ",t.jsx("time",{dateTime:j.generated_at,children:jf(j.generated_at)})]}),t.jsxs("span",{children:["Exact interval:"," ",t.jsx("time",{dateTime:j.range?.start,children:jf(j.range?.start)})," to"," ",t.jsx("time",{dateTime:j.range?.end,children:jf(j.range?.end)}),", end excluded"]}),t.jsxs("span",{children:[j.range?.days," days · ",j.range?.time_zone]})]}),"content"===m?t.jsx(Mf,{engagement:j.details?.document_engagement,range:j.range}):null,"overview"===m?t.jsx(Qf,{makeAuthRequest:a}):null,t.jsx(tb,{title:"Needs attention",description:"Exceptions and operational follow-up signals. A reported zero remains distinct from unavailable data.",metricIds:I,metrics:R,data:j,variant:"attention"}),t.jsx(tb,{title:"Category detail",description:"Supporting definitions and breakdowns for this category only.",metricIds:T,metrics:R,data:j,variant:"detail"}),t.jsx(Df,{sources:j.sources,cache:j.cache,servedAt:j.served_at})]}):null]})}const nb=["general","company","project","research","operations","resource"],sb=["all","draft","published","archived"];function rb(e){return e?`${e.charAt(0).toUpperCase()}${e.slice(1).replaceAll("_"," ")}`:"Uncategorized"}function ib(){return{id:null,title:"",summary:"",bodyDocument:Cc,category:"general",isPinned:!1,isImportant:!1,audience:{workspaceWide:!0,projectIds:[],userIds:[]},resourceRefs:[],linkPreviews:[],status:"draft",version:null}}function lb(e){return{id:e.id,title:e.title||"",summary:e.summary||"",bodyDocument:e.bodyDocument||Cc,category:e.category||"general",isPinned:Boolean(e.isPinned),isImportant:Boolean(e.isImportant),audience:e.audience||{workspaceWide:!0,projectIds:[],userIds:[]},resourceRefs:e.resourceRefs||[],linkPreviews:e.linkPreviews||[],status:e.status,version:e.version}}function ob(e){return{title:e.title.trim(),summary:e.summary.trim()||null,bodyDocument:e.bodyDocument,category:e.category||null,isPinned:e.isPinned,isImportant:e.isImportant,audie
2nce:e.audience,resourceRefs:e.resourceRefs.map(e=>({resourceId:e.resourceId||e.id,folderId:e.folderId||null,objectId:e.objectId||null})),linkPreviewIds:e.linkPreviews.map(e=>e.id)}}function cb(e){if(e.workspaceWide)return"Everyone in Workspace";const t=e.projectIds.length,a=e.userIds.length;return`${t} project${1===t?"":"s"} · ${a} additional ${1===a?"person":"people"}`}function db(e){const t=e.resourceId||e.id,a=e.targetLabel||null;return{id:t,title:e.packTitle||e.title||"Workspace Resource",targetKind:e.targetKind||(e.objectId?"object":e.folderId?"folder":"pack"),targetLabel:e.targetUnavailable?`${a||"Exact target"} (unavailable)`:a,folderId:e.folderId||null,objectId:e.objectId||null}}function ub({value:a,onChange:n,projects:s,people:r,disabled:i=!1,focusRef:l}){const[o,c]=e.useState(""),[d,u]=e.useState(""),h=new Set(a.projectIds),m=new Set(a.userIds),p=(e,t)=>{const s=new Set(a[e]);s.has(t)?s.delete(t):s.add(t),n({...a,[e]:[...s]})},f=s.filter(e=>e.name?.toLocaleLowerCase().includes(o.toLocaleLowerCase())),b=r.filter(e=>`${e.name||""} ${e.title||""}`.toLocaleLowerCase().includes(d.toLocaleLowerCase())),x=[...a.projectIds.map(e=>({id:e,label:s.find(t=>t.id===e)?.name||"Selected project",field:"projectIds"})),...a.userIds.map(e=>({id:e,label:r.find(t=>t.id===e)?.name||"Selected person",field:"userIds"}))];return t.jsxs("fieldset",{ref:l,className:"workspace-update-audience",tabIndex:-1,children:[t.jsx("legend",{children:"Audience"}),t.jsx("p",{children:"Choose who can discover and open this Update. Project access remains dynamic."}),t.jsxs("label",{className:"workspace-update-audience-mode",children:[t.jsx("input",{type:"radio",name:"update-audience-mode",checked:a.workspaceWide,disabled:i,onChange:()=>n({workspaceWide:!0,projectIds:[],userIds:[]})}),t.jsxs("span",{children:[t.jsx("strong",{children:"Everyone in Workspace"}),t.jsx("small",{children:"All currently eligible internal Workspace members."})]})]}),t.jsxs("label",{className:"workspace-update-audience-mode",children:[t.jsx("input",{type:"radio",name:"update-audience-mode",checked:!a.workspaceWide,disabled:i,onChange:()=>n({...a,workspaceWide:!1})}),t.jsxs("span",{children:[t.jsx("strong",{children:"Selected audiences"}),t.jsx("small",{children:"Current members of selected projects plus selected people."})]})]}),a.workspaceWide?null:t.jsxs("div",{className:"workspace-update-audience-selection",children:[t.jsxs("div",{className:"workspace-update-audience-selected-header",children:[t.jsx("strong",{children:"Current selection"}),x.length?t.jsx("button",{type:"button",disabled:i,onClick:()=>n({...a,projectIds:[],userIds:[]}),children:"Clear selection"}):null]}),x.length?t.jsx("ul",{className:"workspace-update-audience-selected","aria-label":"Selected audiences",children:x.map(e=>t.jsxs("li",{children:[t.jsx("span",{children:e.label}),t.jsx("button",{type:"button",disabled:i,"aria-label":`Remove ${e.label}`,onClick:()=>p(e.field,e.id),children:t.jsx(g,{size:15,"aria-hidden":"true"})})]},`${e.field}:${e.id}`))}):t.jsx("p",{children:"No projects or people selected yet."}),t.jsxs("div",{className:"workspace-update-audience-pickers",children:[t.jsxs("section",{children:[t.jsxs("label",{children:["Search projects",t.jsx("input",{type:"search",value:o,disabled:i,onChange:e=>c(e.target.value)})]}),t.jsxs("div",{className:"workspace-update-check-list",role:"group","aria-label":"Projects",children:[f.map(e=>t.jsxs("label",{children:[t.jsx("input",{type:"checkbox",checked:h.has(e.id),disabled:i,onChange:()=>p("projectIds",e.id)}),t.jsx("span",{children:e.name})]},e.id)),f.length?null:t.jsx("p",{children:"No matching active projects."})]})]}),t.jsxs("section",{children:[t.jsxs("label",{children:["Search people",t.jsx("input",{type:"search",value:d,disabled:i,onChange:e=>u(e.target.value)})]}),t.jsxs("div",{className:"workspace-update-check-list",role:"group","aria-label":"People",children:[b.map(e=>t.jsxs("label",{children:[t.jsx("input",{type:"checkbox",checked:m.has(e.id),disabled:i,onChange:()=>p("userIds",e.id)}),t.jsxs("span",{children:[e.name||"Unnamed person",e.title?t.jsx("small",{children:e.title}):null]})]},e.id)),b.length?null:t.jsx("p",{children:"No matching eligible people."})]})]})]})]}),t.jsxs("p",{className:"workspace-update-audience-summary",role:"status",children:["Publishing audience: ",cb(a),"."]})]})}function hb({updateId:a,onClose:n,onSaved:s,onDirtyChange:r}){const{makeAuthRequest:i}=Yn(),l=$s(),o=e.useRef(null),c=e.useRef(!1),d=e.useRef(null),u=e.useRef(null),h=e.useRef(null),m=e.useRef(null),p=e.useRef(null),g=e.useRef(0),[f,b]=e.useState(ib),[x,v]=e.useState(null),[j,y]=e.useState([]),[k,w]=e.useState([]),[N,S]=e.useState(!0),[C,R]=e.useState(!1),[E,I]=e.useState(null),[_,T]=e.useState(!0),[A,O]=e.useState(a?"Loading Updateâ¦":"New draft"),[D,P]=e.useState(null),[L,$]=e.useState(null),[M,U]=e.useState(!1),[F,q]=e.useState(""),[B,W]=e.useState(!1),V=null!==x&&JSON.stringify(f)!==x,H="archived"===f.status,K=_||H,J=f.audie
2nce.workspaceWide||f.audience.projectIds.length||f.audience.userIds.length,Y=function(e){const t=e=>!(!e||"object"!=typeof e)&&(!("text"!==e.type||"string"!=typeof e.text||!e.text.trim())||Array.isArray(e.content)&&e.content.some(t));return t(e?.document)}(f.bodyDocument),X=Boolean(f.title.trim()&&Y&&J),Z=f.resourceRefs.filter(e=>!0!==e.targetUnavailable),ee=f.resourceRefs.length-Z.length,te=e.useCallback(async({explicitRetry:e=!1}={})=>{const t=++g.current;S(!0),R(e),e||I(null);const[a,n]=await Promise.allSettled([i("/api/workspace/v1/projects?scope=all&limit=100"),i("/api/workspace/v1/people?scope=all&limit=100")]);t===g.current&&("fulfilled"===a.status&&y(a.value.data?.projects||[]),"fulfilled"===n.status&&w(n.value.data?.people||[]),"rejected"===a.status||"rejected"===n.status?(I("Some audience choices could not be loaded. Audience controls remain disabled until the complete list is available."),e&&window.requestAnimationFrame(()=>p.current?.focus())):e&&(I(null),O("Audience choices loaded."),window.requestAnimationFrame(()=>{const e=m.current;e&&(e.focus({preventScroll:!0}),e.scrollIntoView?.({block:"start",behavior:"auto"}))})),S(!1),R(!1))},[i]);e.useEffect(()=>()=>{g.current+=1},[]);const ae=e.useCallback(e=>{const t=lb(e);b(t),v(JSON.stringify(t)),$(null)},[]);e.useEffect(()=>{let e=!1;return async function(){let t="Ready";try{if(a){te();const n=await i(`/api/workspace/v1/updates/${encodeURIComponent(a)}?scope=all`);e||ae(n.data.update),"archived"===n.data.update.status&&(t="Archived · read-only")}else{await te();const t=ib();e||(b(t),v(JSON.stringify(t)))}e||O(t)}catch(n){e||P(n.safeMessage||"The composer could not be loaded.")}finally{e||T(!1)}}(),()=>{e=!0}},[ae,te,i,a]),e.useEffect(()=>{a||_||D||c.current||(c.current=!0,o.current?.focus())},[_,D,a]),e.useEffect(()=>{if(!M)return;const e=window.requestAnimationFrame(()=>{const e=u.current;e&&(e.focus({preventScroll:!0}),e.scrollIntoView?.({block:"start",behavior:"auto"}))});return()=>window.cancelAnimationFrame(e)},[M]);const ne=()=>{const e=h.current;h.current=null,U(!1),window.requestAnimationFrame(()=>{d.current?.focus({preventScroll:!0}),e&&window.scrollTo({left:e.left,top:e.top,behavior:"auto"})})};e.useEffect(()=>{const e=e=>{V&&(e.preventDefault(),e.returnValue="")};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[V]),e.useEffect(()=>{r?.(V)},[V,r]),e.useEffect(()=>()=>r?.(!1),[r]);const se=async()=>{T(!0),P(null),O("Saving draftâ¦");try{const e=Boolean(f.id),t=await i(e?`/api/workspace/v1/updates/${encodeURIComponent(f.id)}?scope=all`:"/api/workspace/v1/updates?scope=all",{method:e?"PATCH":"POST",body:JSON.stringify({...ob(f),...e?{expectedVersion:f.version}:{}})});return ae(t.data.update),O(e?"Changes saved.":"Draft created."),await(s?.()),t.data.update}catch(e){return"WORKSPACE_UPDATE_VERSION_CONFLICT"===e.code?($(e.details?.current||null),O("Local changes preserved. The server version changed.")):(P(e.safeMessage||"The Update could not be saved."),O("Save failed. Your local changes are still here.")),null}finally{T(!1)}},re=async e=>{T(!0);try{const t=await i(`/api/workspace/v1/link-previews/${encodeURIComponent(e.id)}/refresh?scope=all`,{method:"POST",body:JSON.stringify({})});b(a=>({...a,linkPreviews:a.linkPreviews.map(a=>a.id===e.id?t.data.preview:a)}))}catch(t){P(t.safeMessage||"The preview could not be refreshed yet.")}finally{T(!1)}};return _&&!x?t.jsx("p",{role:"status",children:"Loading the Update composerâ¦"}):D&&!x?t.jsx("p",{role:"alert",children:D}):t.jsxs("div",{className:"workspace-update-composer"+(H?" is-archived":""),children:[t.jsxs("div",{className:"workspace-update-composer-header",children:[t.jsxs("button",{type:"button",onClick:async()=>{if(V){if(!(await l({title:"Discard unsaved changes?",message:"Your current local edits have not been saved.",confirmLabel:"Discard changes",confirmVariant:"danger"})))return}n()},children:[t.jsx(G,{size:17,"aria-hidden":"true"})," Back to Updates"]}),t.jsxs("div",{children:[t.jsx("h1",{children:H?"Archived Workspace Update":f.id?"Edit Worksp
2ace Update":"Create Workspace Update"}),t.jsx("p",{children:H?"This Update is archived and read-only. Preview the saved article or return to Updates.":"published"===f.status?"Saved edits appear immediately to readers.":"Build and review the article before publishing."})]}),t.jsx("span",{className:`workspace-update-save-state${V?" is-dirty":""}${H?" is-archived":""}`,role:"status","aria-live":"polite",children:H?"Archived":A})]}),L?t.jsxs("section",{className:"workspace-update-conflict",role:"alert",children:[t.jsx("h2",{children:"The server version changed"}),t.jsxs("p",{children:["Your local article is still in the composer. Server version ",L.version," is titled â",L.title,"â."]}),t.jsxs("div",{children:[t.jsxs(ds,{variant:"secondary",onClick:async()=>{P(null);try{if(!navigator.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(JSON.stringify(ob(f),null,2)),O("Local draft copied.")}catch{P("The local draft could not be copied. Keep this tab open before reloading.")}},children:[t.jsx(Ge,{size:16,"aria-hidden":"true"})," Copy local draft"]}),t.jsx(ds,{variant:"danger",onClick:async()=>{await l({title:"Reload the server version?",message:"Copy your local draft first if you need to keep these edits.",confirmLabel:"Reload server version",confirmVariant:"danger"})&&ae(L)},children:"Reload server version"})]})]}):null,D?t.jsx("p",{className:"workspace-update-composer-error",role:"alert",children:D}):null,E?t.jsxs("div",{className:"workspace-update-composer-error workspace-update-target-error",role:"alert","aria-busy":C,children:[t.jsx("p",{children:E}),t.jsx(ds,{ref:p,type:"button",variant:"secondary",disabled:N||_,onClick:()=>{te({explicitRetry:!0})},children:C?"Retrying audience choicesâ¦":"Retry audience choices"})]}):null,t.jsxs("div",{className:"workspace-update-composer-layout","aria-busy":_,children:[t.jsxs("div",{className:"workspace-update-document-canvas",children:[t.jsxs("label",{children:["Title",t.jsx("input",{ref:o,value:f.title,disabled:K,maxLength:160,required:!0,placeholder:"A clear, specific headline",onChange:e=>b(t=>({...t,title:e.target.value}))})]}),t.jsxs("span",{className:"workspace-update-character-count",children:[[...f.title].length,"/160"]}),t.jsxs("label",{children:["Summary ",t.jsx("small",{children:"Optional · shown in feeds and notifications"}),t.jsx("textarea",{rows:3,maxLength:320,value:f.summary,disabled:K,onChange:e=>b(t=>({...t,summary:e.target.value}))})]}),t.jsxs("span",{className:"workspace-update-character-count",children:[[...f.summary].length,"/320"]}),t.jsx(Tc,{value:f.bodyDocument,disabled:K,onChange:e=>b(t=>({...t,bodyDocument:e}))})]}),t.jsxs("aside",{className:"workspace-update-composer-controls",children:[t.jsxs("section",{children:[t.jsx("h2",{children:"Attachments"}),t.jsx("p",{children:"Attachments keep their own permissions. Publishing is blocked when a known audience mismatch exists."}),t.jsx(Cm,{value:f.resourceRefs,onChange:e=>b(t=>({...t,resourceRefs:e})),request:i,collapsible:!0,showAttachedState:!0,disabled:K})]}),t.jsxs("section",{children:[t.jsx("h2",{children:"External links"}),t.jsxs("form",{className:"workspace-update-link-form",onSubmit:async e=>{if(e.preventDefault(),F.trim()&&!_){T(!0),P(null);try{const e=(await i("/api/workspace/v1/link-previews?scope=all",{method:"POST",body:JSON.stringify({url:F.trim()})})).data.preview;b(t=>({...t,linkPreviews:t.linkPreviews.some(t=>t.id===e.id)?t.linkPreviews:[...t.linkPreviews,e]})),q(""),O("ready"===e.status?"Link preview attached.":"Link saved without a preview.")}catch(t){P(t.safeMessage||"A safe preview could not be created for that URL.")}finally{T(!1)}}},children:[t.jsxs("label",{children:["URL",t.jsx("input",{type:"url",inputMode:"url",value:F,disabled:K,placeholder:"https://â¦",onChange:e=>q(e.target.value)})]}),t.jsx(ds,{type:"submit",variant:"secondary",disabled:K||!F.trim(),children:"Fetch preview"})]}),f.linkPreviews.map((e,a)=>t.jsx(Mc,{preview:e,authoring:!0,ordinal:a+1,busy:K,onRefresh:H?null:re,onRemove:H?null:()=>b(t=>({...t,linkPreviews:t.linkPreviews.filter(t=>t.id!==e.id)}
2))},e.id))]}),t.jsx(ub,{focusRef:m,value:f.audience,onChange:e=>b(t=>({...t,audience:e})),projects:j,people:k,disabled:K||N||Boolean(E)}),t.jsxs("section",{children:[t.jsx("h2",{children:"Publishing"}),t.jsxs("label",{children:["Category",t.jsx("select",{value:f.category,disabled:K,onChange:e=>b(t=>({...t,category:e.target.value})),children:nb.map(e=>t.jsx("option",{value:e,children:rb(e)},e))})]}),"draft"===f.status?t.jsxs("label",{className:"workspace-update-check",children:[t.jsx("input",{type:"checkbox",checked:B,disabled:_,onChange:e=>W(e.target.checked)})," ",t.jsx(z,{size:15,"aria-hidden":"true"})," Notify in Workspace"]}):null,t.jsxs("label",{className:"workspace-update-check",children:[t.jsx("input",{type:"checkbox",checked:f.isPinned,disabled:K,onChange:e=>b(t=>({...t,isPinned:e.target.checked}))})," ","Pinned"]}),t.jsxs("label",{className:"workspace-update-check",children:[t.jsx("input",{type:"checkbox",checked:f.isImportant,disabled:K,onChange:e=>b(t=>({...t,isImportant:e.target.checked}))})," ","Important"]})]})]})]}),M?t.jsxs("section",{id:"workspace-update-reader-preview",ref:u,className:"workspace-update-admin-preview","aria-labelledby":"workspace-update-reader-preview-heading",tabIndex:-1,children:[t.jsxs("div",{className:"workspace-update-admin-preview-header",children:[t.jsx("h2",{id:"workspace-update-reader-preview-heading",children:"Reader preview"}),t.jsx("button",{type:"button",onClick:ne,children:"Close preview"})]}),t.jsxs("article",{className:"workspace-update-article","aria-labelledby":"workspace-update-reader-title",children:[t.jsx($c,{update:{...f,publishedAt:(new Date).toISOString(),audienceContext:{label:f.audie
2nce.workspaceWide?"Workspace":"Selected audiences"},isRead:!0}}),t.jsx("h3",{id:"workspace-update-reader-title",className:"workspace-update-preview-title",children:f.title||"Untitled Update"}),f.summary?t.jsx("p",{className:"workspace-update-article-summary",children:f.summary}):null,t.jsx(Ic,{document:f.bodyDocument,headingOffset:2}),t.jsx(Fc,{linkPreviews:f.linkPreviews.filter(e=>!0===e.readerVisible),resources:Z.map(db),restrictedResourceCount:ee,authoring:!0,headingLevel:4,idPrefix:"admin-update-preview"})]})]}):null,t.jsx("p",{className:"sr-only",role:"status","aria-live":"polite",children:M?"Reader preview opened.":""}),t.jsxs("footer",{className:`workspace-update-publish-bar is-${f.status}`,role:"group","aria-label":"Update actions",children:[t.jsxs(ds,{ref:d,variant:"secondary",onClick:()=>{M?ne():(h.current={left:window.scrollX,top:window.scrollY},U(!0))},disabled:_,"aria-label":"Preview","aria-controls":"workspace-update-reader-preview","aria-expanded":M,children:[t.jsx(Q,{size:16,"aria-hidden":"true"}),t.jsx("span",{className:"workspace-update-preview-label",children:"Preview"})]}),"archived"!==f.status?t.jsxs(ds,{variant:"secondary",onClick:se,disabled:_||!f.title.trim(),"aria-label":_?"Saving":f.id?"Save changes":"Save draft",children:[t.jsx("span",{className:"workspace-update-action-label-full",children:_?"Savingâ¦":f.id?"Save changes":"Save draft"}),t.jsx("span",{className:"workspace-update-action-label-short","aria-hidden":"true",children:_?"Savingâ¦":"Save"})]}):null,"draft"===f.status?t.jsxs(ds,{onClick:async()=>{if(!X)return void P("Add a title, article content, and at least one audience before publishing.");let e,t=f;if(!f.id||V){const e=await se();if(!e)return;t=lb(e)}T(!0),P(null),O("Checking audience and Resource accessâ¦");try{e=(await i(`/api/workspace/v1/updates/${encodeURIComponent(t.id)}/readiness?scope=all`)).data.readiness}catch(n){return P(n.safeMessage||"Audience and Resource compatibility could not be confirmed."),O("Publishing stopped. The saved draft remains available."),void T(!1)}T(!1);
2const a=cb(t.audience);if(await l({title:"Publish this Workspace Update?",message:`${a}. ${e.recipientCount} current recipient${1===e.recipientCount?"":"s"}. Workspace notification: ${B?"on":"off"}. ${e.resourceCount} attached Resource${1===e.resourceCount?"":"s"} checked; all current recipients have access. This Update becomes live immediately.`,confirmLabel:"Publish Update",confirmVariant:"primary"})){T(!0),P(null),O("Publishingâ¦");try{const e=await i(`/api/workspace/v1/updates/${encodeURIComponent(t.id)}/lifecycle?scope=all`,{method:"POST",body:JSON.stringify({action:"publish",expectedVersion:t.version,notifyWorkspace:B})});ae(e.data.update),O(B?"Published and Workspace notified.":"Published."),await(s?.())}catch(n){P(n.safeMessage||"The Update could not be published."),O("Publishing failed. The saved draft remains available.")}finally{T(!1)}}else O("Publish cancelled. The saved draft remains available.")},disabled:_||!X,"aria-label":"Publish Update",children:[t.jsx("span",{className:"workspace-update-action-label-full",children:"Publish Update"}),t.jsx("span",{className:"workspace-update-action-label-short","aria-hidden":"true",children:"Publish"})]}):null,"published"===f.status?t.jsx(ds,{variant:"danger",onClick:async()=>{if(await l({title:"Archive this Workspace Update?",message:"Readers will no longer be able to discover or open it.",confirmLabel:"Archive Update",confirmVariant:"danger"})){T(!0);try{const e=await i(`/api/workspace/v1/updates/${encodeURIComponent(f.id)}/lifecycle?scope=all`,{method:"POST",body:JSON.stringify({action:"archive",expectedVersion:f.version,notifyWorkspace:!1})});ae(e.data.update),O("Update archived."),await(s?.())}catch(e){P(e.safeMessage||"The Update could not be archived.")}finally{T(!1)}}},disabled:_,children:"Archive"}):null,"draft"!==f.status||X?null:t.jsxs("span",{className:"workspace-update-publish-readiness",role:"status",children:["Add ",f.title.trim()?null:"a title, ",Y?null:"article content, ",J?null:"an audience, ","then publish."]}),t.jsx("span",{className:"workspace-update-publish-status"+(D?" has-error":""),"aria-hidden":"true",children:H?"Archived":A})]})]})}function mb({onDirtyChange:a,onEditorStateChange:n}){const{makeAuthRequest:s}=Yn(),r=e.useRef(null),[i,l]=e.useState({search:"",submittedSearch:"",status:"all",category:""}),[o,c]=e.useState({loading:!0,updates:[],cursor:null,error:null}),[d,u]=e.useState(void 0),[h,m]=e.useState(""),p=e.useRef(0),g=e.useMemo(()=>{const e=new URLSearchParams({scope:"all",limit:"20",status:i.status});return i.submittedSearch&&e.set("q",i.submittedSearch),i.category&&e.set("category",i.category),`/api/workspace/v1/updates?${e}`},[i]),f=e.useCallback(async({cursor:e=null,append:t=!1}={})=>{const a=++p.current;c(e=>({...e,loading:!0,error:null}));try{const n=await s(e?`${g}&cursor=${encodeURIComponent(e)}`:g);if(a!==p.current)return;c(e=>({loading:!1,updates:t?[...e.updates,...n.data.updates||[]]:n.data.updates||[],cursor:n.data.pagination?.nextCursor||null,error:null}))}catch(n){a===p.current&&c(e=>({...e,loading:!1,error:n}))}},[g,s]);return e.useEffect(()=>{void 0===d&&f()},[d,f]),e.useEffect(()=>(n?.(void 0!==d),()=>n?.(!1)),[d,n]),void 0!==d?t.jsx(hb,{updateId:d||null,onDirtyChange:a,onSaved:()=>f(),onClose:()=>{u(void 0),requestAnimationFrame(()=>r.current?.querySelector("button")?.focus())}}):t.jsxs("section",{className:"workspace-updates-manager","aria-labelledby":"workspace-updates-manager-heading",children:[t.jsxs("header",{children:[t.jsxs("div",{children:[t.jsx("h2",{id:"workspace-updates-manager-heading",children:"Publishing archive"}),t.jsx("p",{children:"Review drafts, live articles, and archived Updates."})]}),t.jsx("span",{ref:r,children:t.jsxs(ds,{onClick:()=>u(null),children:[t.jsx(He,{size:17,"aria-hidden":"true"})," Create Update"]})})]}),t.jsxs("form",{className:"workspace-updates-manager-filters",onSubmit:e=>{e.preventDefault();const t=i.search.trim();1!==t.length?(m(""),l(e=>({...e,submittedSearch:t}))):m("Enter at least 2 characters to search Updates.")},children:[t.jsxs("label",{children:[t.jsx("span",{children:"Search"}),t.jsxs("span",{children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{type:"search",value:i.search,"aria-invalid":Boolean(h),"aria-describedby":h?"workspace-update-admin-search-error":void 0,onChange:e=>l(t=>({...t,search:e.target.value}))})]})]}),t.jsxs("label",{children:["Status",t.jsx("select",{value:i.status,onChange:e=>l(t=>({...t,status:e.target.value})),children:sb.map(e=>t.jsx("option",{value:e,children:rb(e)},e))})]}),t.jsxs("label",{children:["Category",t.jsxs("select",{value:i.category,onChange:e=>l(t=>({...t,category:e.target.value})),children:[t.jsx("option",{value:"",children:"All categories"}),nb.map(e=>t.jsx("option",{value:e,children:rb(e)},e))]})]}),t.jsx(ds,{type:"submit",variant:"secondary",children:"Search"})]}),h?t.jsx("p",{id:"workspace-update-admin-search-error",role:"alert",children:h}):null,o.loading&&!o.updates.length?t.jsx("p",{role:"status",children:"Loading Worksp
2ace Updatesâ¦"}):null,o.error?t.jsxs(Js,{className:"workspace-updates-manager-error",children:[t.jsx("p",{role:"alert",children:o.error.safeMessage||"Workspace Updates could not be loaded."}),t.jsx(ds,{onClick:()=>f(),children:"Try again"})]}):null,o.loading||o.error||o.updates.length?null:t.jsx("p",{className:"workspace-updates-manager-empty",children:i.submittedSearch||"all"!==i.status||i.category?"No Updates match these filters.":"No Workspace Updates yet. Create the first draft when there is something worth sharing."}),t.jsx("div",{className:"workspace-updates-manager-list",children:o.updates.map(e=>{return t.jsxs("article",{children:[t.jsxs("div",{children:[t.jsx("span",{className:`workspace-update-admin-status is-${e.status}`,children:rb(e.status)}),t.jsx("span",{children:rb(e.category)}),e.isPinned?t.jsx("span",{children:"Pinned"}):null,e.isImportant?t.jsx("span",{children:"Important"}):null]}),t.jsx("h3",{children:e.title}),t.jsxs("p",{children:[e.audienceSummary?.workspaceWide?"Everyone in Workspace":`${e.audienceSummary?.projectCount||0} projects · ${e.audienceSummary?.userCount||0} people`," ","· ",(a=e.publishedAt||e.updatedAt,a?new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(a)):"Not published")]}),t.jsx(ds,{variant:"secondary",onClick:()=>u(e.id),children:"archived"===e.status?"View archive":"Open editor"})]},e.id);var a})}),o.cursor?t.jsx("div",{className:"workspace-updates-manager-more",children:t.jsx(ds,{variant:"secondary",disabled:o.loading,onClick:()=>f({cursor:o.cursor,append:!0}),children:o.loading?"Loadingâ¦":"Load more"})}):null]})}function pb(){return t.jsx("div",{className:"admin-workspace-panel",children:t.jsxs("section",{className:"admin-workspace-detail",children:[t.jsx("h2",{children:"Personnel operations moved to Workspace"}),t.jsx("p",{children:"Operational profiles, status, team memberships, and project assignments use the canonical People workspace."}),t.jsx(l,{className:"btn btn-primary btn-medium",to:"/dashboard/employee?tab=people&scope=all",children:"Open All workspace"})]})})}const gb=["","task_created","task_moved","task_updated","message_created","team_memberships_replaced","team_projects_replaced","team_resources_replaced","workspace_project_updated"],fb={active:"Active",archived:"Archived",blocked:"Blocked",blockedTasks:"Blocked tasks",completed:"Completed",dueSoon:"Due soon",open:"Open",openTasks:"Open tasks",overdue:"Overdue",overdueTasks:"Overdue tasks",total:"Total",unread:"Unread"};function bb(e){return fb[e]||e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").replace(/^./,e=>e.toUpperCase())}function xb({onNavigate:a}){const{makeAuthRequest:n}=Yn(),[s,r]=e.useState(null),[i,l]=e.useState([]),[o,c]=e.useState([]),[d,u]=e.useState({search:"",personnelType:"",department:"",sort:"name",direction:"asc"}),[h,m]=e.useState({eventType:"",dateFrom:"",dateTo:""}),[p,g]=e.useState({search:"",department:""}),[f,b]=e.useState(!0),[x,v]=e.useState(null),[j,y]=e.useState(!0),[k,w]=e.useState(null),[N,S]=e.useState(!0),[C,R]=e.useState(null),E=e.useRef(0),I=e.useRef(0),_=e.useRef(0);e.useEffect(()=>{const e=window.setTimeout(()=>g(e=>e.search===d.search&&e.department===d.department?e:{search:d.search,department:d.department}),300);return()=>window.clearTimeout(e)},[d.department,d.search]);const T=e.useCallback(async()=>{const e=++E.current;b(!0),v(null);try{const t=await n("/api/admin/workspace-overview");if(e!==E.current)return;r(t.data)}catch(t){e===E.current&&v(t.message||"Unable to load the operational summary.")}finally{e===E.current&&b(!1)}},[n]),A=e.useCallback(async()=>{const e=++I.current;y(!0),w(null);const t=new URLSearchParams;Object.entries({search:p.search,department:p.department,personnelType:d.personnelType,sort:d.sort,direction:d.direction}).forEach(([e,a])=>{a&&t.set(e,a)});try{const a=await n(`/api/admin/workspace-workload?${t.toString()}`);if(e!==I.current)return;l(a.data.workload||[])}catch(a){e===I.current&&w(a.message||"Unable to load workload details.")}finally{e===I.current&&y(!1)}},[p,n,d.direction,d.personnelType,d.sort]),O=e.useCallback(async()=>{const e=++_.current;S(!0),R(null);const t=new URLSearchParams({limit:"25"});
2Object.entries(h).forEach(([e,a])=>{a&&t.set(e,a)});try{const a=await n(`/api/admin/workspace-activity?${t.toString()}`);if(e!==_.current)return;c(a.data.activity||[])}catch(a){e===_.current&&R(a.message||"Unable to load workspace activity.")}finally{e===_.current&&S(!1)}},[h,n]);return e.useEffect(()=>{T()},[T]),e.useEffect(()=>{A()},[A]),e.useEffect(()=>{O()},[O]),e.useEffect(()=>()=>{E.current+=1,I.current+=1,_.current+=1},[]),t.jsxs("section",{className:"workspace-operations-panel",children:[t.jsx(vb,{overview:s,loading:f,error:x,onRetry:T}),t.jsxs("section",{className:"workspace-operations-section",children:[t.jsx("h3",{children:"Workload details"}),t.jsxs("div",{className:"workspace-operations-toolbar",children:[t.jsxs("label",{children:[t.jsx("span",{children:"Search people"}),t.jsx("input",{value:d.search,onChange:e=>u(t=>({...t,search:e.target.value}))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Department"}),t.jsx("input",{value:d.department,onChange:e=>u(t=>({...t,department:e.target.value}))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Personnel type"}),t.jsx("select",{value:d.personnelType,onChange:e=>u(t=>({...t,personnelType:e.target.value})),children:["","employee","intern","student","researcher","contractor"].map(e=>t.jsx("option",{children:e||"All types"},e))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Sort by"}),t.jsx("select",{value:d.sort,onChange:e=>u(t=>({...t,sort:e.target.value})),children:["name","openTasks","overdueTasks","blockedTasks","dueSoon","projectCount"].map(e=>t.jsx("option",{value:e,children:bb(e)},e))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Direction"}),t.jsxs("select",{value:d.direction,onChange:e=>u(t=>({...t,direction:e.target.value})),children:[t.jsx("option",{value:"asc",children:"Ascending"}),t.jsx("option",{value:"desc",children:"Descending"})]})]})]}),k?t.jsxs("p",{className:"admin-workspace-error",role:"alert",children:[k," ",t.jsx(Xu,{variant:"secondary",onClick:A,children:"Retry workload"})]}):null,j&&!i.length?t.jsx("p",{role:"status",children:"Loading workload details..."}):null,j||k||i.length?null:t.jsx(Hu,{children:"No workload records match these filters."}),i.length?t.jsxs(Bu,{minWidth:"900px",ariaLabel:"Workspace workload",className:j?"is-loading":"",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Person"}),t.jsx("th",{children:"Teams"}),t.jsx("th",{children:"Projects"}),t.jsx("th",{children:"Open"}),t.jsx("th",{children:"Overdue"}),t.jsx("th",{children:"Blocked"}),t.jsx("th",{children:"Due soon"}),t.jsx("th",{children:"Completed 30d"}),t.jsx("th",{children:"Action"})]})}),t.jsx("tbody",{children:i.map(e=>t.jsxs("tr",{children:[t.jsxs("td",{children:[e.name,t.jsxs("small",{children:[e.personnelType," · ",e.department||"No department"]})]}),t.jsx("td",{children:e.team_count}),t.jsx("td",{children:e.project_count}),t.jsx("td",{children:e.open_tasks}),t.jsx("td",{children:e.overdue_tasks}),t.jsx("td",{children:e.blocked_tasks}),t.jsx("td",{children:e.due_soon}),t.jsx("td",{children:e.completed_recently}),t.jsx("td",{children:t.jsx(Xu,{variant:"secondary",onClick:()=>a?.({tab:"people",personId:e.id}),"aria-label":`Open workload for ${e.name}`,children:"Open"})})]},e.id))})]}):null]}),t.jsxs("section",{className:"workspace-operations-section",children:[t.jsx("h3",{children:"Activity"}),t.jsxs("div",{className:"workspace-operations-toolbar",children:[t.jsxs("label",{children:[t.jsx("span",{children:"Event type"}),t.jsx("select",{value:h.eventType,onChange:e=>m(t=>({...t,eventType:e.target.value})),children:gb.map(e=>t.jsx("option",{value:e,children:e||"All events"},e))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"From date"}),t.jsx("input",{type:"date",value:h.dateFrom,onChange:e=>m(t=>({...t,dateFrom:e.target.value}))})]}),t.jsxs("label",{children:[t.jsx("span",{children:"To date"}),t.jsx("input",{type:"date",value:h.dateTo,onChange:e=>m(t=>({...t,dateTo:e.target.value}))})]}),t.jsx(Xu,{variant:"secondary",onClick:O,children:"Refresh"})]}),C?t.jsxs("p",{className:"admin-workspace-error",role:"alert",children:[C," ",t.jsx(Xu,{variant:"secondary",onClick:O,children:"Retry activity"})]}):null,t.jsxs("div",{className:"workspace-operations-activity",children:[N&&!o.length?t.jsx("p",{role:"status",children:"Loading activity..."}):null,N||C||o.length?null:t.jsx(Hu,{children:"No activity found."}),o.map(e=>t.jsxs("button",{type:"button",onClick:()=>a?.(e.urlState),children:[t.jsx("strong",{children:e.title}),t.jsx("span",{children:e.summary}
2),t.jsx("small",{children:new Date(e.createdAt).toLocaleString()})]},e.id))]})]})]})}function vb({overview:e,loading:a,error:n,onRetry:s}){if(a&&!e)return t.jsx("p",{role:"status",children:"Loading operational summary..."});if(n&&!e)return t.jsxs("p",{className:"admin-workspace-error",role:"alert",children:[n," ",t.jsx(Xu,{variant:"secondary",onClick:s,children:"Retry summary"})]});if(!e)return null;const r=[["Personnel",e.personnel],["Teams",e.teams],["Projects",e.projects],["Tasks",e.tasks],["Conversations",e.conversations],["Resources",e.resources]],i=r.flatMap(([e,t])=>Object.entries(t||{}).filter(([e,t])=>Number(t)>0&&/(overdue|blocked|failed|dead|infected|stale|mismatch)/i.test(e)).map(([t,a])=>({group:e,key:t,value:a})));return t.jsxs(t.Fragment,{children:[a?t.jsx("p",{role:"status",children:"Refreshing operational summaryâ¦"}):null,n?t.jsxs("p",{className:"admin-workspace-error",role:"alert",children:["Showing the last available operational summary. Refresh failed: ",n," ",t.jsx(Xu,{variant:"secondary",onClick:s,children:"Retry summary"})]}):null,t.jsxs("section",{className:"workspace-operations-attention","aria-labelledby":"operations-attention",children:[t.jsx("h3",{id:"operations-attention",children:"Needs attention"}),i.length?t.jsx("ul",{children:i.map(e=>t.jsxs("li",{children:[t.jsx("strong",{children:e.value})," ",e.group.toLowerCase()," ·"," ",bb(e.key)]},`${e.group}-${e.key}`))}):t.jsx("p",{children:"No reported exceptions."})]}),t.jsx("section",{className:"workspace-overview-grid","aria-label":"Operational summary",children:r.map(([e,a])=>t.jsxs("article",{children:[t.jsx("h3",{children:e}),Object.entries(a||{}).map(([e,a])=>t.jsxs("span",{children:[bb(e),": ",a]},e))]},e))})]})}const jb=new Set(["blocked","dead_lettered","quarantined","retry"]),yb=Object.freeze({dead_lettered:0,blocked:1,quarantined:2,retry:3,processing:4,pending:5,cancelled:6,completed:7});function kb(e){const t=Date.parse(e);return Number.isFinite(t)?t:null}function wb(e){const t=kb(e);return null===t?"Unavailable":new Date(t).toLocaleString(void 0,{timeZoneName:"short"})}function Nb(e){return!0===e.cancellable}function Sb(e){return!e.stages?.length&&e.cleanup?[["Storage",e.cleanup.storageCompleted],["Hub",e.cleanup.hubCompleted],["Home",e.cleanup.homeCompleted]].map(([e,t])=>`${e}: ${t?"done":"waiting"}`).join(" · "):e.stages?.length?e.stages.map(e=>`${e.key.replaceAll("_"," ")}: ${e.state}`).join(" · "):"No stage ledger"}function Cb(e,t){if(!t?.observed)return`${e}: never observed`;const a=Number.isFinite(t.ageSeconds)?`${t.ageSeconds}s ago`:"unknown age";return`${e}: ${t.state} · ${a}`}function Rb(e){if("quarantined"===e.status)return"No deadline; operator disposition required";if("cancelled"===e.status)return"Cancelled; retained for audit";const t=kb(e.deleteAfter);return null===t?"Deadline unavailable":t<=Date.now()?`${wb(e.deleteAfter)} · due`:`${wb(e.deleteAfter)} · ${Nb(e)?"grace period; cancellable":"scheduled"}`}function Eb(e){if(!e.leaseExpiresAt)return"Not leased";const t=kb(e.leaseExpiresAt);return null===t?"Lease timing unavailable":`Generation ${e.leaseGeneration} · ${t<=Date.now()?"stale":"current"} until ${wb(e.leaseExpiresAt)}`}function Ib(e){const t=String(e||"");return t.length>13?`${t.slice(0,8)}â¦${t.slice(-4)}`:t||"Unavailable"}function _b(e,t=!1){return"cancel"===e?t?"Cancelling deletionâ¦":"Cancel deletion":"reconfirm"===e?t?"Starting grace periodâ¦":"Start new grace period":t?"Replaying cleanupâ¦":"Replay cleanup"}function Tb(e,t){if("cancel"===t)return"Before cleanup starts, restore the captured account eligibility state and retain this operation for audit.";if("reconfirm"===t)return"Reconfirm this quarantined legacy request under the current contract. PostgreSQL will create a new 30-day grace deadline.";const a=kb(e.deleteAfter),n=null!==a&&a<=Date.now()?" Its deadline has passed, so a worker may resume irreversible cleanup immediately after replay.":" A worker may resume irreversible cleanup when its deadline passes.";return`Retry this reviewed failure without changing its deadline. The operation remains ${pm(e.status).toLowerCase()} until the worker records progress.${n}`}function Ab({request:a}){const n=e.useId(),[s,r]=e.useState(null),[i,l]=e.useState(!0),[o,c]=e.useState(null),[d,u]=e.useState(null),[h,m]=e.useState(""),[p,g]=e.useState(null),[f,b]=e.useState(null),[x,v]=e.useState("all"),j=e.useRef(0),y=e.useCallback(async()=>{const e=++j.current;l(!0),c(null);try{const t=await a("/api/admin/user-deletions?limit=25");e===j.current&&r(t.data)}catch(t){e===j.current&&(r(null),c(t.safeMessage||t.message||"Deletion operations could not be loaded."))}finally{e===j.current&&l(!1)}},[a]);e.useEffect(()=>(y(),()=>{j.current+=1}),[y]);const k=e.useMemo(()=>s?.operations||[],[s?.operations]),w=s?.queue||{},N=e.useMemo(()=>[...k].filter(e=>"attention"===x?jb.has(e.status):"grace"===x?"pending"===e.status:"history"!==x||["cancelled","completed"].includes(e.status)).sort((e,t)=>
2{const a=(yb[e.status]??99)-(yb[t.status]??99);return 0!==a?a:(kb(e.deleteAfter)??1/0)-(kb(t.deleteAfter)??1/0)}),[k,x]),S=k.reduce((e,t)=>(e[t.status]=(e[t.status]||0)+1,e),{}),C=Math.max(Number(w.quarantinedCount||0),Number(S.quarantined||0)),R=Math.max(Number(w.deadLetterCount||0),Number(S.dead_lettered||0)),E=Math.max(Number(w.blockedCount||0),Number(S.blocked||0)),I=Math.max(Number(w.retryCount||0),Number(S.retry||0)),_=Number(w.staleLeaseCount||0),T=Number(w.stageRetryCount||0),A=Number(w.hostRequiredOpenCount||0)>0&&"current"!==s?.dispatchers?.host?.state,O=[Number(w.dueUnclaimedCount||0)>0?`${w.dueUnclaimedCount} due operation${1===w.dueUnclaimedCount?"":"s"} unclaimed`:null,C>0?`${C} quarantined legacy request${1===C?"":"s"}`:null,R>0?`${R} dead letter${1===R?"":"s"}`:null,E>0?`${E} blocked operation${1===E?"":"s"}`:null,I>0?`${I} operation${1===I?"":"s"} awaiting retry`:null,_>0?`${_} stale execution lease${1===_?"":"s"}`:null,T>0?`${T} cleanup stage${1===T?"":"s"} blocked or retrying`:null,A?"reviewed-host work without a current dispatcher":null].filter(Boolean),D=(e,t)=>{m(""),g(null),u({operation:e,action:t})},P=()=>{f||(u(null),m(""),g(null))};return t.jsxs("section",{className:"admin-deletion-operations","aria-labelledby":"deletion-operations-title",children:[t.jsxs("div",{className:"admin-deletion-operations__heading",children:[t.jsxs("div",{children:[t.jsx("h2",{id:"deletion-operations-title",children:"Deletion operations"}),t.jsx("p",{children:"Recent permanent-cleanup requests and dispatcher health."})]}),t.jsx(ds,{size:"small",variant:"secondary",onClick:()=>{y()},disabled:i,children:i&&s?"Refreshingâ¦":"Refresh"})]}),i&&!s?t.jsx(Ku,{title:"Loading deletion operationsâ¦",children:"Reading the current cleanup queue and dispatcher state."}):null,o?t.jsx(Ku,{title:"Deletion operations could not be loaded",tone:"error",action:t.jsx(ds,{onClick:()=>{y()},children:"Retry"}),children:o}):null,s?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"admin-deletion-operations__attention "+(O.length?"is-warning":"is-clear"),role:"status",children:[t.jsx("strong",{children:O.length?"Attention required":"No queue exceptions detected"}),t.jsx("p",{children:O.length?`${O.join("; ")}. Review the exception rows before changing execution state.`:"No due-unclaimed, blocked, retrying, quarantined, dead-lettered, stale-lease, or blocked host work is visible."})]}),t.jsxs("dl",{className:"admin-deletion-operations__health",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Open"}),t.jsx("dd",{children:w.openCount??"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"In grace"}),t.jsx("dd",{children:w.graceCount??"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Due now"}),t.jsx("dd",{children:w.dueCount??"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Due, unclaimed"}),t.jsx("dd",{children:w.dueUnclaimedCount??"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Quarantined"}),t.jsx("dd",{children:w.quarantinedCount??"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Dead letters"}),t.jsx("dd",{children:w.deadLetterCount??"Unavailable"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Oldest open"}),t.jsx("dd",{children:Number.isFinite(w.oldestOpenAgeSeconds)?`${w.oldestOpenAgeSeconds}s`:"Unavailable"})]})]}),t.jsxs("div",{className:"admin-deletion-operations__dispatchers",children:[t.jsx("strong",{children:"Execution lanes"}),t.jsxs("span",{children:[Cb("Serverless",s.dispatchers?.serverless),s.dispatchers?.serverless?.executionMode?` · ${s.dispatchers.serverless.executionMode}`:""]}),t.jsxs("span",{children:[Cb("Reviewed host",s.dispatchers?.host),s.dispatchers?.host?.executionMode?` · ${s.dispatchers.host.executionMode}`:""]})]}),t.jsxs("div",{className:"admin-deletion-operations__filter",children:[t.jsx("label",{htmlFor:`${n}-filter`,children:"Show operations"}),t.jsxs("select",{id:`${n}-filter`,value:x,onChange:e=>v(e.target.value),children:[t.jsx("option",{value:"all",children:"All recent operations"}),t.jsx("option",{value:"attention",children:"Attention required"}
2),t.jsx("option",{value:"grace",children:"In grace period"}),t.jsx("option",{value:"history",children:"Completed or cancelled"})]})]}),k.length?N.length?t.jsxs(Bu,{minWidth:"1020px",ariaLabel:"Recent permanent deletion operations",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Status"}),t.jsx("th",{children:"Operation"}),t.jsx("th",{children:"Requested"}),t.jsx("th",{children:"Grace deadline"}),t.jsx("th",{children:"Attempts"}),t.jsx("th",{children:"Diagnostics"}),t.jsx("th",{children:"Completed"}),t.jsx("th",{children:"Controls"})]})}),t.jsx("tbody",{children:N.map(e=>{return t.jsxs("tr",{children:[t.jsx("td",{"data-label":"Status",children:t.jsx(li,{variant:(a=e.status,mm[a]||"default"),children:pm(e.status)})}),t.jsxs("td",{"data-label":"Operation",className:"admin-deletion-operations__id",children:[t.jsx("span",{title:e.id,children:Ib(e.id)}),t.jsx("small",{children:e.requiresHostCleanup?"Reviewed-host runner":"Serverless eligible"})]}),t.jsx("td",{"data-label":"Requested",children:wb(e.requestedAt)}),t.jsx("td",{"data-label":"Grace deadline",children:Rb(e)}),t.jsxs("td",{"data-label":"Attempts",children:[e.attempts," current / ",e.totalAttempts??e.attempts," ","total"]}),t.jsx("td",{"data-label":"Diagnostics",children:t.jsxs("details",{className:"admin-deletion-operations__diagnostics",children:[t.jsx("summary",{children:"View cleanup details"}),t.jsxs("span",{children:["Lease: ",Eb(e)]}),t.jsxs("span",{children:["Stages: ",Sb(e)]}),t.jsxs("span",{children:["Error: ",e.lastErrorCode||"None recorded"]})]})}),t.jsx("td",{"data-label":"Completed",children:wb(e.completedAt)}),t.jsx("td",{"data-label":"Controls",children:t.jsxs("div",{className:"admin-deletion-operations__controls",children:[Nb(e)?t.jsx(ds,{size:"small",variant:"secondary",disabled:Boolean(f),onClick:()=>D(e,"cancel"),children:"Cancel deletion"}):null,["blocked","dead_lettered"].includes(e.status)?t.jsx(ds,{size:"small",variant:"secondary",disabled:Boolean(f),onClick:()=>D(e,"replay"),children:"Replay cleanup"}):null,"quarantined"===e.status?t.jsx(ds,{size:"small",variant:"danger",disabled:Boolean(f),onClick:()=>D(e,"reconfirm"),children:"Start new grace period"}):null]})})]},e.id);var a})})]}):t.jsx(Ku,{title:"No operations match this view",children:"Choose another view to inspect the recent operation history."}):t.jsx(Ku,{title:"No deletion operations",children:"No permanent deletion requests are currently recorded."})]}):null,t.jsx(Ju,{isOpen:Boolean(d),onClose:P,title:d?_b(d.action):"Deletion control",className:"admin-deletion-control-modal",children:d?t.jsxs(t.Fragment,{children:[t.jsxs(Yu,{children:[t.jsx("p",{children:Tb(d.operation,d.action)}),t.jsxs("p",{className:"admin-deletion-control-modal__context",children:["Operation ",Ib(d.operation.id)," ·"," ",pm(d.operation.status)," ·"," ",Rb(d.operation)]}),"cancel"===d.action?t.jsx(Wu,{label:"Cancellation reason",htmlFor:n,hint:"Use at least 10 characters. This reason is retained in the deletion audit.",hintId:`${n}-hint`,children:t.jsx("textarea",{id:n,value:h,onChange:e=>m(e.target.value),"aria-describedby":`${n}-hint`,rows:3,disabled:Boolean(f)})}):null,p?t.jsx("p",{className:"admin-deletion-control-modal__error",role:"alert",children:p}):null,f?t.jsx("p",{role:"status",children:_b(d.action,!0)}):null]}),t.jsxs(Qu,{children:[t.jsx(ds,{variant:"secondary",onClick:P,disabled:Boolean(f),children:"Keep operation unchanged"}),t.jsx(ds,{variant:["reconfirm","replay"].includes(d.action)?"danger":"primary",onClick:()=>{(async()=>{if(!d)return;const{operation:e,action:t}=d,n=h.trim();if("cancel"===t&&n.length<10)return void g("Enter at least 10 characters so the cancellation remains auditable.");const s=`${e.id}:${t}`;b(s),g(null);try{await a("/api/admin/user-deletions",{method:"PATCH",body:JSON.stringify({action:t,operationId:e.id,...n?{reason:n}:{}})}),u(null),m(""),await y()}catch(r){g(r.safeMessage||r.message||"The deletion control action failed.")}finally{b(null)}})()},disabled:Boolean(f)||"cancel"===d.action&&h.trim().length<10,children:_b(d.action,Boolean(f))})]})]}):null})]})}const Ob=[".localhost",".localdomain",".local",".internal",".home",".lan"];function Db(e){const t=String(e||"");return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Pb(e){const t=Db(e).toLowerCase();
2return!(!t||"localhost"===t||"localhost.localdomain"===t||Ob.some(e=>t.endsWith(e)))&&(!xa.isValid(t)||function(e){let t;try{t=xa.parse(Db(e))}catch{return!1}return"ipv6"===t.kind()&&t.isIPv4MappedAddress()&&(t=t.toIPv4Address()),"unicast"===t.range()}(t))}function Lb(e){return"string"==typeof e?e.trim():"number"==typeof e&&Number.isFinite(e)?String(e):""}function $b(e){const t=Lb(e);return t||(!e||"object"!=typeof e||Array.isArray(e)?"":[e.firstName,e.middleName,e.lastName].map(Lb).filter(Boolean).join(" "))}function Mb(e,t=Date.now()){const a=Lb(e?.existing_reward_ends_at);if(!a)return"none";const n=Date.parse(a),s=t instanceof Date?t.getTime():Number(t);return Number.isFinite(n)&&Number.isFinite(s)?n>s?"active":"historical":"existing"}function Ub(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"â":`${(t/1048576).toFixed(2)} MB`}function Fb({label:e,children:a}){return t.jsxs("div",{children:[t.jsx("dt",{children:e}),t.jsx("dd",{children:a})]})}function zb({upload:e}){const a=Lb(e?.title)||"Not provided",n=Lb(e?.filename)||"Unavailable",s=Lb(e?.user_email)||"Unavailable";return t.jsxs("dl",{className:"upload-review-identity","aria-label":"Upload identity",children:[t.jsx(Fb,{label:"Title",children:a}),t.jsx(Fb,{label:"Filename",children:n}),t.jsx(Fb,{label:"Uploader",children:s})]})}function qb({upload:e,formatDate:a,id:n,className:s="",sourceAction:r,children:i}){const l=e.metadata&&"object"==typeof e.metadata?e.metadata:{},o=Lb(e.isbn),c=$b(e.author)||$b(l.author),d=Lb(e.year)||Lb(l.year),u=Lb(e.publisher)||Lb(l.publisherType),h=Lb(e.language),m=Lb(l.doi),p=Lb(l.url),g=function(e){const t="string"==typeof e&&Array.from(e).some(e=>{const t=e.codePointAt(0);return t<=31||127===t});if("string"!=typeof e||e.length>2048||t)return null;try{const t=new URL(e);return"https:"!==t.protocol||t.username||t.password||t.hostname.endsWith(".")||!Pb(t.hostname)?null:t.toString()}catch{return null}}(p),f=Lb(l.pages),b=Lb(l.seriesName),x=Lb(l.seriesNumber),v=Array.isArray(l.seriesEditors)?l.seriesEditors.map($b).filter(Boolean):[],j=Lb(e.notes),y=Mb(e),k=Number(e.existing_reward_months),w=Number.isFinite(k)?`${k} month${1===k?"":"s"}`:"an unspecified period",N=Array.isArray(e.tags)?e.tags.map(Lb).filter(Boolean):[],S=[o,c,d,u,h,m,p,f,b,v.length,j,N.length].some(Boolean);return t.jsxs("div",{id:n,className:"upload-detail-grid"+(s?` ${s}`:""),role:"group","aria-label":"Complete upload review evidence",children:[r?t.jsxs("section",{className:"upload-detail-section upload-review-source-panel",children:[t.jsx("h3",{className:"upload-detail-section__title",children:"Source document"}),r]}):null,S?t.jsxs("section",{className:"upload-detail-section",children:[t.jsx("h3",{className:"upload-detail-section__title",children:"Bibliographic details"}),t.jsxs("dl",{className:"upload-detail-list",children:[o?t.jsx(Fb,{label:"ISBN",children:o}):null,c?t.jsx(Fb,{label:"Author",children:c}):null,d?t.jsx(Fb,{label:"Year",children:d}):null,u?t.jsx(Fb,{label:"Publisher",children:u}):null,h?t.jsx(Fb,{label:"Language",children:h}):null,m?t.jsx(Fb,{label:"DOI",children:m}):null,p?t.jsx(Fb,{label:"URL",children:g?t.jsxs("a",{className:"upload-detail-url upload-detail-url--link",href:g,target:"_blank",rel:"noopener noreferrer",children:[g," ",t.jsx(Ue,{className:"upload-detail-external-icon",size:14,"aria-hidden":"true"}),t.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]}):t.jsxs("span",{className:"upload-detail-url upload-detail-url--blocked",children:[p," (not opened â unsafe saved URL)"]})}):null,f?t.jsx(Fb,{label:"Pages",children:f}):null,b?t.jsxs(Fb,{label:"Series",children:[b,x?` #${x}`:""]}):null,v.length>0?t.jsx(Fb,{label:"Series Editors",children:v.join(", ")}):null,j?t.jsx(Fb,{label:"Notes",children:j}):null,N.length>0?t.jsx(Fb,{label:"Tags",children:t.jsx("span",{className:"upload-tags",children:N.map(e=>t.jsx("span",{className:"upload-tag",children:e},e))})}):null]})]}):null,e.admin_message?t.jsxs("section",{className:"upload-detail-section upload-admin-message-display",children:[t.jsx("h3",{className:"upload-detail-section__title",children:"Reviewer communication"}),t.jsx("p",{children:e.admin_message}),t.jsxs("span",{className:"upload-message-date",children:["Sent ",a(e.admin_message_at)]})]}):null,"none"!==y?t.jsxs("section",{className:"upload-detail-section upload-existing-reward",children:[t.jsx("h3",{className:"upload-detail-section__title",children:"Reward status"}),"active"===y?t.jsxs("p",{children:["Active upload reward retained: ",w,", ending"," ",a(e.existing_reward_ends_at),". No additional reward will be granted."]}):"historical"===y?t.jsxs("p",{children:["Previous upload reward retained: ",w,", ended"," ",a(e.existing_reward_ends_at),". No additional reward will be granted."]}):t.jsx("p",{children:"An existing upload reward record will be retained. No additional reward will be granted."})]}):null,t.jsxs("section",{className:"upload-detail-section",children:[t.jsx("h3",{className:"upload-detail-section__title",children:"File integrity"}),t.jsxs("dl",{className:"upload-detail-file-info",children:[t.jsx(Fb,{label:"SHA-256",children:t.jsx(Lg,{value:e.sha256,mode:"identifier"})}),t.jsx(Fb,{label:"MIME",children:e.mime_type||"Unavailable"}),t.jsx(Fb,{label:"Provider",children:e.storage_provider||"Unavailable"})]})]}),i?t.jsxs("section",{className:"upload-detail-section upload-review-decision-panel",children:[t.jsx("h3",{className:"upload-detail-section__title",children:"Review decision"}),i]}):null]})}function Bb({isOpen:a,onClose:s,children:r,titleId:i="search-filter-drawer-title"}){const l=e.useRef(null),o=e.useRef(null),c=ys({isOpen:a,panelRef:o,initialFocusRef:l,onRequestClose:s});return a&&"undefined"!=typeof document?n.createPortal(t.jsx("div",{className:"search-filter-drawer-overlay",onClick:e=>{e.target===e.currentTarget&&c("backdrop")},children:t.jsxs("div",{ref:o,className:"search-filter-drawer",role:"dialog","aria-modal":"true","aria-labelledby":i,tabIndex:-1,
2children:[t.jsxs("div",{className:"search-filter-drawer-header",children:[t.jsx("h2",{id:i,children:"Filters"}),t.jsx("button",{type:"button",ref:l,onClick:()=>c("close-button"),className:"search-filter-drawer-close","aria-label":"Close filters",children:t.jsx(g,{size:18,"aria-hidden":"true"})})]}),t.jsx("div",{className:"search-filter-drawer-body",children:r})]})}),xs()):null}function Wb({label:e,segments:a,total:n}){const s=n>0?n:a.reduce((e,t)=>e+t.value,0)||1;return t.jsxs("div",{className:"coverage-bar",children:[t.jsx("div",{className:"coverage-bar__label",children:e}),t.jsx("div",{className:"coverage-bar__track","aria-hidden":"true",children:a.map(e=>{const a=Math.max(0,Math.min(100,e.value/s*100));return a<=0?null:t.jsx("div",{className:`coverage-bar__segment coverage-bar__segment--${e.tone}`,style:{width:`${a}%`}},e.key)})}),t.jsx("ul",{className:"coverage-bar__legend",children:a.map(e=>{const a=s>0?Math.round(e.value/s*100):0;return t.jsxs("li",{className:`coverage-bar__legend-item coverage-bar__legend-item--${e.tone}`,children:[t.jsx("span",{className:"coverage-bar__legend-dot","aria-hidden":"true"}),t.jsxs("span",{children:[e.label,": ",e.value.toLocaleString()," (",a,"%)"]})]},e.key)})})]})}const Vb=Object.freeze({LOADING:"loading",READY:"ready",ERROR:"error"});function Hb({status:e,summary:a,error:n,onRetry:s}){if(e===Vb.LOADING)return t.jsx(Mg,{title:"Wikibase & text coverage",className:"text-coverage-summary",children:t.jsx("div",{className:"text-coverage-summary__skeleton",role:"status","aria-live":"polite",children:t.jsx("span",{children:"Loading coverage summaryâ¦"})})});if(e===Vb.ERROR)return t.jsxs(Mg,{title:"Wikibase & text coverage",className:"text-coverage-summary",children:[t.jsx("p",{className:"text-coverage-summary__error",role:"alert",children:n?.message||"Coverage statistics are unavailable right now."}),t.jsx("button",{type:"button",className:"text-coverage-retry",onClick:s,children:"Retry"})]});if(!a||0===a.documents.total)return t.jsx(Mg,{title:"Wikibase & text coverage",className:"text-coverage-summary",children:t.jsx("p",{className:"text-coverage-summary__empty",children:"No extraction statistics available yet."})});const{documents:r,pages:i,sync:l}=a;return t.jsxs(Mg,{title:"Wikibase & text coverage",className:"text-coverage-summary",children:[t.jsxs("div",{className:"text-coverage-summary__tiles",children:[t.jsx(Ug,{label:"Documents",value:r.total.toLocaleString()}),t.jsx(Ug,{label:"Inspected",value:r.inspected.toLocaleString()}),t.jsx(Ug,{label:"Fully text-covered",value:r.fullyExtractable.toLocaleString()}),t.jsx(Ug,{label:"Partially text-covered",value:r.partiallyExtractable.toLocaleString()}),t.jsx(Ug,{label:"No embedded text",value:r.noEmbeddedText.toLocaleString()}),t.jsx(Ug,{label:"Needs attention",value:r.needsAttention.toLocaleString()})]}),t.jsx(Wb,{label:"Documents",total:r.total,segments:[{key:"full",label:"Full",value:r.fullyExtractable,tone:"positive"},{key:"partial",label:"Partial",value:r.partiallyExtractable,tone:"caution"},{key:"none",label:"No text",value:r.noEmbeddedText,tone:"neutral"},{key:"uninspected",label:"Uninspected",value:r.notInspected,tone:"muted"}]}),t.jsxs("div",{className:"text-coverage-summary__tiles",children:[t.jsx(Ug,{label:"Total pages",value:i.total.toLocaleString()}),t.jsx(Ug,{label:"Pages with source text",value:i.withSourceText.toLocaleString()}),t.jsx(Ug,{label:"No text available",value:i.noText.toLocaleString()}),t.jsx(Ug,{label:"Failed / attention",value:i.extractionFailed.toLocaleString()}),t.jsx(Ug,{label:"Human corrected",value:i.humanCorrected.toLocaleString()}),t.jsx(Ug,{label:"Human reviewed",value:i.humanReviewed.toLocaleString()})]}),t.jsx(Wb,{label:"Pages",total:i.total,segments:[{key:"text",label:"Text available",value:i.withSourceText,tone:"positive"},{key:"no-text",label:"No text",value:i.noText,tone:"neutral"},{key:"attention",label:"Attention",value:i.extractionFailed,tone:"negative"}]}),l?t.jsxs("div",{className:"text-coverage-summary__sync",children:[t.jsx("h4",{children:"Synchronization"}),t.jsxs("div",{className:"text-coverage-summary__tiles",children:[t.jsx(Ug,{label:"Mapped to Wikibase",value:l.mappedToWikibase.toLocaleStr
2ing()}),t.jsx(Ug,{label:"PageOCR synchronized",value:l.pageOcrSynchronized.toLocaleString()}),t.jsx(Ug,{label:"Projections current",value:l.projectionsCurrent.toLocaleString()}),t.jsx(Ug,{label:"Search-indexed",value:l.searchIndexed.toLocaleString()}),t.jsx(Ug,{label:"Stale / failed projections",value:l.staleOrFailedProjections.toLocaleString()})]})]}):null]})}const Kb=Object.freeze({FULLY_EXTRACTABLE:"fully_extractable",PARTIALLY_EXTRACTABLE:"partially_extractable",NO_USABLE_EXISTING_TEXT:"no_usable_existing_text",EXTRACTION_FAILED:"extraction_failed",PAGE_COUNT_MISMATCH:"page_count_mismatch"}),Gb=Object.freeze({USABLE_EXISTING_TEXT:"usable_existing_text",EMPTY_TEXT_LAYER:"empty_text_layer",BLANK_PAGE:"blank_page",SPARSE_TEXT_LAYER:"sparse_text_layer",LIKELY_GARBLED_TEXT:"likely_garbled_text",EXTRACTION_FAILED:"extraction_failed",REQUIRES_OCR:"requires_ocr",HUMAN_CURRENT_PRESERVED:"human_current_preserved",TEXT_SIZE_LIMIT_EXCEEDED:"text_size_limit_exceeded"}),Jb=Object.freeze({EMBEDDED_TEXT_LAYER:"existing_pdf_text_layer",TRUSTED_OCR_ARTIFACT:"preexisting_trusted_ocr_artifact"}),Yb=Object.freeze({CORRECTED:"corrected",REVIEWED:"reviewed"}),Qb=Object.freeze({FULL:"full",PARTIAL:"partial",NONE:"none",NOT_INSPECTED:"not_inspected",ATTENTION:"attention"}),Xb=Object.freeze({[Qb.FULL]:"Fully covered",[Qb.PARTIAL]:"Partially covered",[Qb.NONE]:"No embedded text",[Qb.NOT_INSPECTED]:"Not inspected",[Qb.ATTENTION]:"Needs attention"}),Zb=Object.freeze({AVAILABLE:"available",UNAVAILABLE:"unavailable",ATTENTION:"attention"}),ex=Object.freeze({[Zb.AVAILABLE]:"Text available",[Zb.UNAVAILABLE]:"No embedded text",[Zb.ATTENTION]:"Needs attention"}),tx=Object.freeze({PDF_TEXT_LAYER:"pdf_text_layer",PRE_EXISTING_SOURCE:"pre_existing_source",HUMAN_CORRECTED:"human_corrected",HUMAN_REVIEWED:"human_reviewed"}),ax=Object.freeze({[tx.PDF_TEXT_LAYER]:"PDF text layer",[tx.PRE_EXISTING_SOURCE]:"Pre-existing source text",[tx.HUMAN_CORRECTED]:"Human corrected",[tx.HUMAN_REVIEWED]:"Human reviewed"}),nx=Object.freeze({PDF_SIZE_LIMIT_EXCEEDED:"PDF exceeds size limit",PAGE_COUNT_LIMIT_EXCEEDED:"Page count exceeds limit",TEXT_SIZE_LIMIT_EXCEEDED:"Extracted text exceeds size limit",TOTAL_TEXT_SIZE_LIMIT_EXCEEDED:"Total extracted text exceeds size limit",EXTRACTION_TIMEOUT:"Extraction timed out",PDF_PASSWORD_REQUIRED:"PDF is password protected",PDF_EXTRACTION_FAILED:"Extraction failed",SOURCE_BINARY_CHANGED_DURING_EXTRACTION:"Source file changed during extraction",PAGE_COUNT_MISMATCH:"Page count mismatch",PAGE_MAPPING_CONFLICT:"Page mapping conflict",PAGEOCR_SYNC_CONFLICT:"PageOCR synchronization conflict",STALE_PROJECTION:"Projection is stale",SEARCH_INDEX_FAILURE:"Search indexing failed",UNKNOWN:"Extraction issue"}),sx=Object.freeze({SYNCED:"synced",PENDING:"pending",FAILED:"failed",STALE:"stale",CURRENT:"current",PARTIAL:"partial",MAPPED_NOT_PROJECTED:"mapped_not_projected",NOT_STARTED:"not_started",NOT_MAPPED:"not_mapped"}),rx=Object.freeze({[sx.SYNCED]:"Current",[sx.PENDING]:"Pending",[sx.FAILED]:"Failed",[sx.STALE]:"Stale",[sx.CURRENT]:"Current",[sx.PARTIAL]:"Partial",[sx.MAPPED_NOT_PROJECTED]:"Mapped, not projected",[sx.NOT_STARTED]:"Not started",[sx.NOT_MAPPED]:"Not mapped"}),ix=Object.freeze({INDEXED:"indexed",NOT_INDEXED:"not_indexed",STALE:"stale",FAILED:"failed",CURRENT:"current",UNAVAILABLE:"unavailable"}),lx=Object.freeze({[ix.INDEXED]:"Indexed",[ix.NOT_INDEXED]:"Not indexed",[ix.STALE]:"Stale",[ix.FAILED]:"Failed",[ix.CURRENT]:"Current",[ix.UNAVAILABLE]:"Unavailable"}),ox=Object.freeze({ALL:"all",FULL:"full",PARTIAL:"partial",NONE:"none",NOT_INSPECTED:"not_inspected",ATTENTION:"attention"}),cx=Object.freeze({ALL:"all",SYNCED:"synced",PENDING:"pending",FAILED:"failed",STALE:"stale"}),dx=Object.freeze({ALL:"all",PDF_TEXT_LAYER:"pdf_text_layer",HUMAN_CORRECTED_OR_REVIEWED:"human_corrected_or_reviewed"}),ux=Object.freeze({ALL:"all",YES:"yes",NO:"no"}),hx=25,mx=50,px=Object.freeze({ATTENTION_FIRST:"attention_first",RECENTLY_UPDATED:"recently_updated",TITLE:"title",MOST_NO_TEXT_PAGES:"most_no_text_pages",COVERAGE_PERCENTAGE:"coverage_percentage"}
2),gx=Object.freeze({NETWORK_ERROR:"NETWORK_ERROR",UNAUTHORIZED:"UNAUTHORIZED",FORBIDDEN:"FORBIDDEN",SERVER_ERROR:"SERVER_ERROR",NOT_FOUND:"NOT_FOUND",INVALID_RESPONSE:"INVALID_RESPONSE",REQUEST_CANCELLED:"REQUEST_CANCELLED",UNKNOWN:"TEXT_COVERAGE_REQUEST_FAILED"}),fx=[{value:ox.ALL,label:"All"},{value:ox.FULL,label:"Full"},{value:ox.PARTIAL,label:"Partial"},{value:ox.NONE,label:"No text"},{value:ox.NOT_INSPECTED,label:"Not inspected"},{value:ox.ATTENTION,label:"Needs attention"}],bx=[{value:cx.ALL,label:"All"},{value:cx.SYNCED,label:"Synced"},{value:cx.PENDING,label:"Pending"},{value:cx.FAILED,label:"Failed"},{value:cx.STALE,label:"Stale"}],xx=[{value:dx.ALL,label:"All"},{value:dx.PDF_TEXT_LAYER,label:"PDF text layer"},{value:dx.HUMAN_CORRECTED_OR_REVIEWED,label:"Human corrected/reviewed"}],vx=[{value:ux.ALL,label:"All"},{value:ux.YES,label:"Indexed"},{value:ux.NO,label:"Not indexed"}],jx=[{value:px.ATTENTION_FIRST,label:"Most attention needed"},{value:px.RECENTLY_UPDATED,label:"Recently updated"},{value:px.TITLE,label:"Title"},{value:px.MOST_NO_TEXT_PAGES,label:"Highest no-text page count"},{value:px.COVERAGE_PERCENTAGE,label:"Coverage percentage"}];function yx({queryState:a,onSubmitQuery:n,onSetCoverage:s,onSetSync:r,onSetTextSource:i,onSetIndexed:l,onSetSort:o,onClearFilters:c,idPrefix:d="text-coverage-filters"}){const[u,h]=e.useState(a.query);e.useEffect(()=>{h(a.query)},[a.query]);return t.jsxs("div",{className:"text-coverage-filters",children:[t.jsxs("form",{role:"search",onSubmit:e=>{e.preventDefault(),n(u)},className:"text-coverage-filters__search",children:[t.jsx(Wu,{label:"Search",htmlFor:`${d}-search`,children:t.jsx("input",{id:`${d}-search`,type:"search",value:u,onChange:e=>h(e.target.value),placeholder:"Title, document ID, or QIDâ¦"})}),t.jsx("button",{type:"submit",className:"text-coverage-filters__search-submit",children:"Search"})]}),t.jsx(Wu,{label:"Coverage",htmlFor:`${d}-coverage`,children:t.jsx("select",{id:`${d}-coverage`,value:a.coverage,onChange:e=>s(e.target.value),children:fx.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))})}),t.jsx(Wu,{label:"Synchronization",htmlFor:`${d}-sync`,children:t.jsx("select",{id:`${d}-sync`,value:a.sync,onChange:e=>r(e.target.value),children:bx.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))})}),t.jsx(Wu,{label:"Text source",htmlFor:`${d}-source`,children:t.jsx("select",{id:`${d}-source`,value:a.textSource,onChange:e=>i(e.target.value),children:xx.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))})}),t.jsx(Wu,{label:"Search indexed",htmlFor:`${d}-indexed`,children:t.jsx("select",{id:`${d}-indexed`,value:a.indexed,onChange:e=>l(e.target.value),children:vx.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))})}),t.jsx(Wu,{label:"Sort",htmlFor:`${d}-sort`,children:t.jsx("select",{id:`${d}-sort`,value:a.sort,onChange:e=>o(e.target.value),children:jx.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))})}),t.jsx("button",{type:"button",className:"text-coverage-filters__clear",onClick:c,children:"Clear filters"})]})}const kx={[Qb.FULL]:"positive",[Qb.PARTIAL]:"caution",[Qb.NONE]:"neutral",[Qb.NOT_INSPECTED]:"neutral",[Qb.ATTENTION]:"negative"},wx={[Zb.AVAILABLE]:"positive",[Zb.UNAVAILABLE]:"neutral",[Zb.ATTENTION]:"negative"},Nx={synced:"positive",pending:"caution",failed:"negative",stale:"caution"},Sx={indexed:"positive",not_indexed:"neutral",stale:"caution",failed:"negative"};function Cx({status:e}){return t.jsx(_x,{tone:kx[e]||"neutral",children:Xb[e]||"Unknown"})}function Rx({availability:e}){return t.jsx(_x,{tone:wx[e]||"neutral",children:ex[e]||"Unknown"})}function Ex({status:e}){return e?t.jsx(_x,{tone:Nx[e]||"neutral",children:rx[e]||e}):t.jsx(_x,{tone:"neutral",children:"â"})}function Ix({status:e}){return e?t.jsx(_x,{tone:Sx[e]||"neutral",children:lx[e]||e}):t.jsx(_x,{tone:"neutral",children:"â"})}function _x({tone:e="neutral",children:a}){return t.jsxs("span",{className:`coverage-status-pill coverage-status-pill--${e}`,children:[t.jsx("span",{className:"coverage-status-pill__dot","aria-hidden":"true"}),t.jsx("span",{children:a})]})}function Tx(e){if(!e)return"â";const t=new Date(e);return Number.isNaN(t.getTime())?"â":t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}function Ax({documents:e,onOpenDocument:a,emptyMessage:n}){return 0===e.length?t.jsx(Hu,{children:n||"No documents match these filters."}):t.jsxs(Bu,{className:"text-coverage-table",minWidth:"760px",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Document"}),t.jsx("th",{children:"Pages"}),t.jsx("th",{children:"Text"}),t.jsx("th",{children:"Status"}),t.jsx("th",{children:"Sync"}),t.jsx("th",{children:"Search index"}),t.jsx("th",{children:"Updated"})]})}),t.jsx("tbody",{children:e.map(e=>t.jsxs("tr",{className:"text-coverage-table__row",children:[t.jsxs("td",{"data-label":"Document",children:[t.jsx("button",{type:"button",className:"text-coverage-table__title-button",onClick:()=>a(e.documentId),children:e.displayName}),e.isCuratedTitle?t.jsx("div",{className:"text-coverage-table__subtitle",children:e.wikibaseEntityId?e.wikibaseEntityId:e.documentId}):t.jsx("div",{className:"text-coverage-table__subtitle",children:e.documentId}),e.hasHumanCorrections?t.jsx("span",{className:"text-coverage-table__human-flag",children:"Human corrected"}):null]}),t.jsx("td",{"data-label":"Pages",children:e.totalPages??"â"}),t.jsx("td",{"data-label":"Text",children:e.totalPages?`${e.pagesWithText}/${e.totalPages}`:`${e.pagesWithText}`}),t.jsxs("td",{"data-label":"Status",children:[t.jsx(Cx,{status:e.coverageStatus}),e.attentionReasons.length>0?t.jsx("div",{className:"text-coverage-table__attention-reasons",children:e.attentionReasons.join(", ")}):null]}),t.jsx("td",{"data-label":"Sync",children:t.jsx(Ex,{status:e.pageOcrSyncStatus})}),t.jsx("td",{"data-label":"Search index",children:t.jsx(Ix,{status:e.searchIndexStatus})}),t.jsx("td",{"data-label":"Updated",children:Tx(e.lastUpdatedAt)})]},e.documentId))})]})}const Ox=new Set([Gb.EXTRACTION_FAILED,Gb.TEXT_SIZE_LIMIT_EXCEEDED]),Dx=new Set([Gb.EMPTY_TEXT_LAYER,Gb.BLANK_PAGE,Gb.REQUIRES_OCR]),Px=new Set([Gb.USABLE_EXISTING_TEXT,Gb.SPARSE_TEXT_LAYER,Gb.HUMAN_CURRENT_PRESERVED]);const Lx=new Set([Kb.EXTRACTION_FAILED,Kb.PAGE_COUNT_MISMATCH]);function $x({rawHumanStatus:e,rawSourceType:t}={}){return e===Yb.CORRECTED?tx.HUMAN_CORRECTED:e===Yb.REVIEWED?tx.HUMAN_REVIEWED:t===Jb.TRUSTED_OCR_ARTIFACT?tx.PRE_EXISTING_SOURCE:t===Jb.EMBEDDED_TEXT_LAYER?tx.PDF_TEXT_LAYER:null}function Mx(e){return e===Yb.CORRECTED||e===Yb.REVIEWED}function Ux(e){return e&&nx[e]||nx.UNKNOWN}function Fx(e){if(null==e)return null;const t=String(e).trim();return t.length>0?t:null}function zx(e,t=""){return Fx(e)??t}function qx(e){const t=Number(e);return Number.isInteger(t)&&t>=0?t:0}function Bx(e){const t=Number(e);return Number.isInteger(t)&&t>0?t:null}function Wx(e){return!0===e}function Vx(e,t){const a=Fx(e);return a&&t.includes(a)?a:null}function Hx(e,{inspected:t,hasAttentionFlag:a}={}){const n=Fx(e);return a?Qb.ATTENTION:Object.values(Qb).includes(n)?n:"fully_extractable"===n?Qb.FULL:"partially_extractable"===n?Qb.PARTIAL:"no_embedded_text"===n||"no_usable_existing_text"===n?Qb.NONE:"needs_attention"===n||"extraction_failed"===n?Qb.ATTENTION:function({rawClassification:e,inspected:t,hasAttentionFlag:a=!1}={}){return t?a||Lx.has(e)?Qb.ATTENTION:e===Kb.FULLY_EXTRACTABLE?Qb.FULL:e===Kb.PARTIALLY_EXTRACTABLE?Qb.PARTIAL:e===Kb.NO_USABLE_EXISTING_TEXT?Qb.NONE:Qb.NOT_INSPECTED:Qb.NOT_INSPECTED}({rawClassification:n,inspected:t,hasAttentionFlag:a})}function Kx(e){const t=Fx(e);return Object.values(Zb).includes(t)?t:"with_source_text"===t?Zb.AVAILABLE:"extraction_failed"===t||"page_count_mismatch"===t?Zb.ATTENTION:"no_text"===t||"not_inspected"===t?Zb.UNAVAILABLE:(a=t,Px.has(a)?Zb.AVAILABLE:Ox.has(a)?Zb.ATTENTION:(Dx.has(a),Zb.UNAVAILABLE));var a}function Gx(e){const t=e||{},a=t.documents||{},n=t.pages||{},s=t.sync;return{documents:{total:qx(a.total),inspected:qx(a.inspected),notInspected:qx(a.notInspected??Math.max(0,qx(a.total)-qx(a.inspected))),fullyExtractable:qx(a.fullyExtractable),partiallyExtractable:qx(a.partiallyExtractable),noEmbeddedText:qx(a.noEmbeddedText??a.noUsableExistingText),needsAttention:qx(a.needsAttention)},pages:{total:qx(n.total),withSourceText:qx(n.withSourceText),humanCorrected:qx(n.humanCorrected),humanReviewed:qx(n.humanReviewed),noText:qx(n.noText),extractionFailed:qx(n.extractionFailed),pageCountMismatch:qx(n.pageCountMismatch)},sync:s?{mappedToWikibase:qx(s.mappedToWikibase),pageOcrSynchronized:qx(s.pageOcrSynchronized),projectionsCurrent:qx(s.projectionsCurrent),searchIndexed:qx(s.searchIndexed),staleOrFailedProjections:qx(s.staleOrFailedProjections)}:null,generatedAt:Fx(t.generatedAt)}}function Jx(e){const t=e||{},a=Fx(t.displayName),n=Fx(t.title??t.curatedTitle),s=Fx(t.fileName??t.filename),r=a??n??s??"Untitled document",i=Array.isArray(t.attentionReasonCodes)?t.attentionReasonCodes:[],l=Wx(t.sourceBinaryChanged)||Wx(t.pageMappingConflict)||Wx(t.pageOcrSyncConflict)||i.length>0;return{documentId:zx(t.documentId??t.id),wikibaseEntityId:Fx(t.wikibaseEntityId??t.qid),displayName:r,isCuratedTitle:Boolean(t.isCuratedTitle??n),totalPages:Bx(t.totalPages??t.page
2Count),pagesWithText:qx(t.pagesWithText),pagesWithoutText:qx(t.pagesWithoutText),correctedPages:qx(t.correctedPages),reviewedPages:qx(t.reviewedPages),coverageStatus:Hx(t.coverageStatus??t.classification,{inspected:Wx(t.inspected),hasAttentionFlag:l}),hasHumanCorrections:qx(t.correctedPages)+qx(t.reviewedPages)>0,attentionReasons:i.map(Ux),pageOcrSyncStatus:Vx(t.pageOcrSyncStatus,Object.values(sx)),searchIndexStatus:Vx(t.searchIndexStatus,Object.values(ix)),lastUpdatedAt:Fx(t.lastUpdatedAt??t.updatedAt)}}function Yx(e){const t=e||{},a=Array.isArray(t.documents)?t.documents:[],n=Fx(t.nextCursor);return{documents:a.map(Jx),nextCursor:n,hasMore:Boolean(n)}}function Qx(e){const t=e||{},a=Fx(t.humanStatus??t.correctionStatus),n=Fx(t.classification??t.textAvailability),s=Fx(t.attentionReasonCode),r=Kx(n);return{pageNumber:Bx(t.pageNumber),pageWikibaseEntityId:Fx(t.pageWikibaseEntityId??t.pageQid),textAvailability:r,textSource:$x({rawHumanStatus:a,rawSourceType:Fx(t.sourceType??t.textSource)}),correctionStatus:Mx(a)?a:null,pageOcrSyncStatus:Vx(t.pageOcrSyncStatus,Object.values(sx)),searchIndexStatus:Vx(t.searchIndexStatus,Object.values(ix)),lastUpdatedAt:Fx(t.lastUpdatedAt??t.updatedAt),attentionReason:r===Zb.ATTENTION?Ux(s):null}}function Xx(e){const t=e||{},a=Array.isArray(t.pages)?t.pages:[];return{document:Jx(t.document),pages:a.map(Qx),nextCursor:Fx(t.nextCursor)}}function Zx(e){if(!e)return"â";const t=new Date(e);return Number.isNaN(t.getTime())?"â":t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}function ev({documents:e,onOpenDocument:a}){const n=function(e){const t=Array.isArray(e)?e:[],a=[];for(const n of t){const e=n.attentionReasons.length>0?n.attentionReasons:["Needs attention"];for(const t of e)a.push({id:`${n.documentId}:${t}`,reasonLabel:t,documentId:n.documentId,documentDisplayName:n.displayName,pageNumber:null,lastOccurredAt:n.lastUpdatedAt})}return a}(e);return 0===n.length?t.jsx(Hu,{children:"No documents currently need attention."}):t.jsxs(Bu,{className:"text-coverage-attention-table",minWidth:"520px",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Reason"}),t.jsx("th",{children:"Document"}),t.jsx("th",{children:"Page"}),t.jsx("th",{children:"Last occurrence"})]})}),t.jsx("tbody",{children:n.map(e=>t.jsxs("tr",{children:[t.jsx("td",{"data-label":"Reason",children:e.reasonLabel}),t.jsx("td",{"data-label":"Document",children:t.jsx("button",{type:"button",className:"text-coverage-table__title-button",onClick:()=>a(e.documentId),children:e.documentDisplayName})}),t.jsx("td",{"data-label":"Page",children:e.pageNumber??"â"}),t.jsx("td",{"data-label":"Last occurrence",children:Zx(e.lastOccurredAt)})]},e.id))})]})}function tv(e){if(!e)return"â";const t=new Date(e);return Number.isNaN(t.getTime())?"â":t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}function av({documentId:e,pages:a,onNavigate:n}){return 0===a.length?t.jsx(Hu,{children:"No pages recorded for this document yet."}):t.jsxs(Bu,{className:"text-coverage-page-table",minWidth:"640px",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Page"}),t.jsx("th",{children:"Text"}),t.jsx("th",{children:"Source"}),t.jsx("th",{children:"Sync"}),t.jsx("th",{children:"Search index"}),t.jsx("th",{children:"Updated"}),t.jsx("th",{"aria-label":"Actions"})]})}),t.jsx("tbody",{children:a.map(a=>{const s=function(e,t){if(!e||!Number.isInteger(t)||t<1)return null;const a=new URLSearchParams({page:String(t)});return`/documents/${encodeURIComponent(e)}?${a.toString()}`}(e,a.pageNumber);return t.jsxs("tr",{className:"text-coverage-page-table__row",children:[t.jsxs("td",{"data-label":"Page",children:[a.pageNumber??"â",a.pageWikibaseEntityId?t.jsx("div",{className:"text-coverage-table__subtitle",children:a.pageWikibaseEntityId}):null]}),t.jsxs("td",{"data-label":"Text",children:[t.jsx(Rx,{availability:a.textAvailability}),a.attentionReason?t.jsx("div",{className:"text-coverage-table__attention-reasons",children:a.attentionReason}):null]}),t.jsx("td",{"data-label":"Source",children:a.textSource?ax[a.textSource]:"â"}),t.jsx("td",{"data-label":"Sync",children:t.jsx(Ex,{status:a.pageOcrSyncStatus})}),t.jsx("td",{"data-label":"Search index",children:t.jsx(Ix,{status:a.searchIndexStatus})}),t.jsx("td",{"data-label":"Updated",children:tv(a.lastUpdatedAt)}),t.jsx("td",{"data-label":"Actions",children:s?t.jsx("button",{type:"button",className:"text-coverage-page-table__open-button",onClick:()=>n(s),children:"Open page"}):null})]},a.pageNumber)})})]})}const nv=Object.freeze({IDLE:"idle",LOADING:"loading",LOADING_MORE_PAGES:"loading-more-pages",READY:"ready",ERROR:"error"});function sv({isOpen:e,onClose:a,status:n,document:s,pages:r,hasMorePages:l,onLoadMorePages:o,error:c,onRetry:d}){const u=i();return t.jsx(Ju,{isOpen:e,onClose:a,title:s?.displayName||"Document coverage",size:"large",children:t.jsxs(Yu,{className:"text-coverage-detail",children:[n===nv.LOADING?t.jsx($g,{message:"Loading document coverageâ¦"}):null,n===nv.ERROR?t.jsxs("div",{role:"alert",className:"text-coverage-detail__error",children:[t.jsx("p",{children:c?.message||"Failed to load this document."}),t.jsx("button",{type:"button",onClick:d,children:"Retry"})]}
2):null,s&&n!==nv.LOADING?t.jsxs(t.Fragment,{children:[t.jsxs("dl",{className:"text-coverage-detail__meta",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"TokenWorks ID"}),t.jsx("dd",{children:s.documentId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Wikibase QID"}),t.jsxs("dd",{children:[s.wikibaseEntityId||"â",s.wikibaseEntityId?t.jsx("button",{type:"button",className:"text-coverage-detail__link-button",onClick:()=>u(function(e){const t=String(e||"").trim().slice(0,256);return t?`/dashboard?${new URLSearchParams({tab:"documents",q:t}).toString()}`:null}(s.wikibaseEntityId)),children:"View in Documents"}):null]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Total pages"}),t.jsx("dd",{children:s.totalPages??"â"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Pages with text"}),t.jsx("dd",{children:s.pagesWithText})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Pages unavailable"}),t.jsx("dd",{children:s.pagesWithoutText})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Human corrected / reviewed"}),t.jsxs("dd",{children:[s.correctedPages," corrected, ",s.reviewedPages," reviewed"]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Status"}),t.jsx("dd",{children:t.jsx(Cx,{status:s.coverageStatus})})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"PageOCR sync"}),t.jsx("dd",{children:t.jsx(Ex,{status:s.pageOcrSyncStatus})})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Search index"}),t.jsx("dd",{children:t.jsx(Ix,{status:s.searchIndexStatus})})]})]}),s.attentionReasons.length>0?t.jsxs("p",{className:"text-coverage-detail__attention",role:"alert",children:["Needs attention: ",s.attentionReasons.join(", ")]}):null,t.jsx("h3",{className:"text-coverage-detail__pages-heading",children:"Pages"}),t.jsx(av,{documentId:s.documentId,pages:r,onNavigate:u}),l?t.jsx("button",{type:"button",className:"text-coverage-detail__load-more",onClick:o,children:"Load more pages"}):null]}):null]})})}const rv=Object.freeze({QUERY:"q",COVERAGE:"coverage",SYNC:"sync",TEXT_SOURCE:"source",INDEXED:"indexed",SORT:"sort",DOCUMENT_ID:"doc",CURSOR:"cursor"}),iv=Object.freeze({query:"",coverage:ox.ALL,sync:cx.ALL,textSource:dx.ALL,indexed:ux.ALL,sort:px.ATTENTION_FIRST,documentId:null,cursor:null});function lv(e,t,a,n){const s=e.get(t);return s&&a.includes(s)?s:n}function ov(){const[t,a]=c(),n=e.useMemo(()=>function(e){return{query:(e.get(rv.QUERY)||"").slice(0,256).trim(),coverage:lv(e,rv.COVERAGE,Object.values(ox),ox.ALL),sync:lv(e,rv.SYNC,Object.values(cx),cx.ALL),textSource:lv(e,rv.TEXT_SOURCE,Object.values(dx),dx.ALL),indexed:lv(e,rv.INDEXED,Object.values(ux),ux.ALL),sort:lv(e,rv.SORT,Object.values(px),px.ATTENTION_FIRST),documentId:e.get(rv.DOCUMENT_ID)||null,cursor:e.get(rv.CURSOR)||null}}(t),[t]),s=e.useCallback((e,{replace:n=!0}={})=>{a(function(e,t){const a=new URLSearchParams(t),n={...iv,...e},s=(e,t,n)=>{t&&t!==n?a.set(e,t):a.delete(e)};return s(rv.QUERY,n.query,""),s(rv.COVERAGE,n.coverage,ox.ALL),s(rv.SYNC,n.sync,cx.ALL),s(rv.TEXT_SOURCE,n.textSource,dx.ALL),s(rv.INDEXED,n.indexed,ux.ALL),s(rv.SORT,n.sort,px.ATTENTION_FIRST),s(rv.DOCUMENT_ID,n.documentId,null),s(rv.CURSOR,n.cursor,null),a}(e,t),{replace:n})},[t,a]),r=e.useCallback(e=>{s({...n,query:e,cursor:null},{replace:!1})},[s,n]),i=e.useCallback(e=>s({...n,coverage:e,cursor:null}),[s,n]),l=e.useCallback(e=>s({...n,sync:e,cursor:null}),[s,n]),o=e.useCallback(e=>s({...n,textSource:e,cursor:null}),[s,n]),d=e.useCallback(e=>s({...n,indexed:e,cursor:null}),[s,n]),u=e.useCallback(e=>s({...n,sort:e,cursor:null}),[s,n]),h=e.useCallback(()=>{s({...n,coverage:iv.coverage,sync:iv.sync,textSource:iv.textSource,indexed:iv.indexed,cursor:null})},[s,n]),m=e.useCallback(e=>s({...n,documentId:e}),[s,n]),p=e.useCallback(()=>s({...n,documentId:null}),[s,n]);return{state:n,submitQuery:r,setCoverage:i,setSync:l,setTextSource:o,setIndexed:d,setSort:u,clearFilters:h,openDocument:m,closeDocument:p}}const cv=Object.freeze({LOADING:"loading",LOADING_MORE:"loading-more",READY:"ready",ERROR:"error"});function dv(t){const{state:a,submitQuery:n,setCoverage:s,setSync:r,setTextSource:i,setIndexed:l,setSort:o,clearFilters:c,openDocument:d,closeDocument:u}=ov(),[h,m]=e.useState(cv.LOADING),[p,g]=e.useState([]),[f,b]=e.useState(null),[x,v]=e.useState(null),j=e.useRef(null),y=(k=a,JSON.stringify([k.query,k.coverage,k.sync,k.textSource,k.indexed,k.sort]));var k;const w=e.useRef(y);w.current=y;const N=e.useCallback(async({cursor:e,append:n})=>{j.current?.abort();const s=new AbortController;j.current=s;const r=y;m(n?cv.LOADING_MORE:cv.LOADING),n||v(null);try{const i=await t.listDocuments({...a,cursor:e},{signal:s.signal});if(w.current!==r)return;g(e=>n?[...e,...i.documents]:i.documents),b(i.nextCursor),m(cv.READY),v(null)}catch(i){if("REQUEST_CANCELLED"===i?.code)return;if(w.current!==r)return;m(cv.ERROR),v(i)}},[t,a,y]);e.useEffect(()=>(N({cursor:null,append:!1}),()=>j.current?.abort()),[y]);const S=e.useCallback(()=>{f&&h!==cv.LOADING_MORE&&h!==cv.LOADING&&N({cursor:f,append:!0})},[f,h,N]),C=e.useCallback(()=>
2{N({cursor:null,append:!1})},[N]);return{queryState:a,submitQuery:n,setCoverage:s,setSync:r,setTextSource:i,setIndexed:l,setSort:o,clearFilters:c,openDocument:d,closeDocument:u,status:h,documents:p,error:x,hasMore:Boolean(f),loadMore:S,retry:C}}function uv({repository:a}){const n=function(t){const[a,n]=e.useState(Vb.LOADING),[s,r]=e.useState(null),[i,l]=e.useState(null),o=e.useRef(null),c=e.useCallback(()=>{o.current?.abort();const e=new AbortController;o.current=e,n(Vb.LOADING),l(null),t.getSummary({signal:e.signal}).then(t=>{e.signal.aborted||(r(t),n(Vb.READY))}).catch(t=>{"REQUEST_CANCELLED"===t?.code||e.signal.aborted||(l(t),n(Vb.ERROR))})},[t]);return e.useEffect(()=>(c(),()=>o.current?.abort()),[c]),{status:a,summary:s,error:i,retry:c}}(a),{queryState:s,submitQuery:r,setCoverage:i,setSync:l,setTextSource:o,setIndexed:c,setSort:d,clearFilters:u,openDocument:h,closeDocument:m,status:p,documents:g,error:f,hasMore:b,loadMore:x,retry:v}=dv(a),j=function(t,a){const[n,s]=e.useState(nv.IDLE),[r,i]=e.useState(null),[l,o]=e.useState([]),[c,d]=e.useState(null),[u,h]=e.useState(null),m=e.useRef(null),p=e.useCallback(()=>{if(!a)return m.current?.abort(),s(nv.IDLE),i(null),o([]),d(null),void h(null);m.current?.abort();const e=new AbortController;m.current=e,s(nv.LOADING),h(null),t.getDocument(a,{signal:e.signal}).then(t=>{e.signal.aborted||(i(t.document),o(t.pages),d(t.nextCursor),s(nv.READY))}).catch(t=>{"REQUEST_CANCELLED"===t?.code||e.signal.aborted||(h(t),s(nv.ERROR))})},[t,a]);e.useEffect(()=>(p(),()=>m.current?.abort()),[p]);const g=e.useCallback(()=>{a&&c&&n!==nv.LOADING_MORE_PAGES&&(s(nv.LOADING_MORE_PAGES),t.getDocument(a,{pageCursor:c}).then(e=>{o(t=>[...t,...e.pages]),d(e.nextCursor),s(nv.READY)}).catch(e=>{h(e),s(nv.ERROR)}))},[t,a,c,n]);return{status:n,document:r,pages:l,hasMorePages:Boolean(c),loadMorePages:g,error:u,retry:p}}(a,s.documentId),[y,k]=e.useState(!1),[w,N]=e.useState("documents"),S=(C=s).coverage!==ox.ALL||C.sync!==cx.ALL||C.textSource!==dx.ALL||C.indexed!==ux.ALL;var C;const R=p===cv.LOADING,E=p===cv.LOADING_MORE,I=p===cv.ERROR,_={queryState:s,onSubmitQuery:r,onSetCoverage:i,onSetSync:l,onSetTextSource:o,onSetIndexed:c,onSetSort:d,onClearFilters:u};return t.jsxs("div",{className:"text-coverage-panel",children:[t.jsx(Hb,{status:n.status,summary:n.summary,error:n.error,onRetry:n.retry}),t.jsxs(Mg,{className:"text-coverage-panel__body",children:[t.jsxs("div",{className:"text-coverage-panel__toolbar",children:[t.jsxs("div",{className:"text-coverage-panel__view-toggle",role:"tablist","aria-label":"Wikibase status view",children:[t.jsx("button",{type:"button",role:"tab","aria-selected":"documents"===w,className:"text-coverage-panel__view-tab "+("documents"===w?"text-coverage-panel__view-tab--active":""),onClick:()=>N("documents"),children:"Documents"}),t.jsx("button",{type:"button",role:"tab","aria-selected":"attention"===w,className:"text-coverage-panel__view-tab "+("attention"===w?"text-coverage-panel__view-tab--active":""),onClick:()=>{N("attention"),i(ox.ATTENTION)},children:"Needs attention"})]}),t.jsxs("button",{type:"button",className:"text-coverage-panel__filter-toggle",onClick:()=>k(!0),"aria-label":"Open filters",children:[t.jsx(je,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:"Filters"}),S?t.jsx("span",{className:"text-coverage-panel__filter-dot","aria-hidden":"true"}):null]})]}),t.jsxs("div",{className:"text-coverage-panel__layout",children:[t.jsx("aside",{className:"text-coverage-panel__sidebar","aria-label":"Wikibase status filters",children:t.jsx(yx,{..._,idPrefix:"text-coverage-filters-desktop"})}),t.jsx(Bb,{isOpen:y,onClose:()=>k(!1),titleId:"text-coverage-filter-drawer-title",children:t.jsx(yx,{..._,idPrefix:"text-coverage-filters-mobile"})}),t.jsxs("div",{className:"text-coverage-panel__results",children:[t.jsx("p",{className:"text-coverage-panel__status-line","aria-live":"polite",children:E?"Loading more documentsâ¦":""}),R?t.jsx($g,{message:"Loading documentsâ¦"}):null,I?t.jsxs("div",{role:"alert",className:"text-coverage-panel__error",children:[t.jsx("p",{children:f?.message||"Failed to load documents."}),t.jsx("button",{type:"button",onClick:v,children:"Retry"})]}):null,R||I?null:"attention"===w?t.jsx(ev,{documents:g,onOpenDocument:h}):t.jsx(Ax,{documents:g,onOpenDocument:h,emptyMessage:S?"No documents match these filters.":"No extraction statistics available yet."}),R||I||!b?null:t.jsx("button",{type:"button",className:"text-coverage-panel__load-more",onClick:x,disabled:E,children:E?"Loading moreâ¦":"Load more"})]})]})]}),t.jsx(sv,{isOpen:Boolean(s.documentId),onClose:m,status:j.status,document:j.document,pages:j.pages,hasMorePages:j.hasMorePages,onLoadMorePages:j.loadMorePages,error:j.error,onRetry:j.retry})]})}const hv="Unavailable";function mv(e){return null!=e&&""!==e}function pv(e){return mv(e)&&Number.isFinite(Number(e))?Number(e).toLocaleStr
2ing():hv}function gv(e,t=""){const a=pv(e);return a===hv?a:`${a}${t?` ${t}`:""}`}function fv(e){return mv(e)?String(e).replaceAll("_"," "):hv}function bv(e){if(!e||"object"!=typeof e)return null;const t=Object.values(e);return t.length?t.some(e=>!Number.isFinite(Number(e)))?null:t.reduce((e,t)=>e+Number(t),0):0}function xv({label:e,value:a,tone:n="default"}){const s=a===hv;return t.jsxs("div",{className:`tools-admin-metric tools-admin-metric--${s?"unavailable":n}`,children:[t.jsx("span",{children:e}),t.jsx("strong",{children:a})]})}function vv({title:e,description:a,children:n,className:s=""}){return t.jsxs("section",{className:`tools-admin-section ${s}`.trim(),children:[t.jsxs("div",{className:"tools-admin-section__header",children:[t.jsx("h2",{children:e}),a?t.jsx("p",{children:a}):null]}),n]})}function jv(){const{makeAuthRequest:a}=Yn(),n=$s(),s=e.useRef(0),r=e.useRef(""),i=e.useRef(""),l=e.useRef(null),o=e.useRef(null);o.current||(o.current=crypto.randomUUID());const[c,d]=e.useState({status:"loading",data:null,sourceErrors:{}}),[u,h]=e.useState(""),[m,p]=e.useState(""),[g,f]=e.useState(""),[b,x]=e.useState(null),[v,j]=e.useState({ownerEmail:"",displayCredits:"",reason:""}),y=e.useCallback(async(e="",{background:t=!1}={})=>{const n=s.current+1;s.current=n,d(e=>({...e,status:t&&e.data?"refreshing":"loading",sourceErrors:{}}));const[r,i]=await Promise.allSettled([a("/api/admin/tools"+(e?`?job=${encodeURIComponent(e)}`:"")),a("/api/admin/tools/operations")]);if(n!==s.current)return!1;const o={};"rejected"===r.status&&(o.snapshot=r.reason?.message||"Tools health is unavailable."),"rejected"===i.status&&(o.operations=i.reason?.message||"Operations diagnostics are unavailable.");const c="fulfilled"===r.status?r.value?.data:null,u="fulfilled"===i.status?i.value?.data:null,h=t?l.current:null,m=c||u||h?{...c||h||{},operationsPanel:u||h?.operationsPanel||null}:null,p=Boolean(m);return l.current=m,d({status:p?"ready":"error",data:m,sourceErrors:o}),{hasData:p,complete:0===Object.keys(o).length}},[a]);e.useEffect(()=>(y(),()=>{s.current+=1}),[y]);const k=e.useCallback(async({key:e,request:t,successMessage:a,resolveOutcome:n=null})=>{if(i.current)return!1;i.current=e,f(e),x(null);try{const e=await t();if(!n&&!1===e?.ok)throw new Error(e.error?.message||"The operation could not be completed.");const s=n?n(e):{tone:"success",message:a};x(s);return(await y(m,{background:!0})).complete||x({tone:s.tone,message:`${s.message} Current Tools data could not be fully refreshed.`}),!0}catch(s){return x({tone:"error",message:s.message||"The operation could not be completed."}),!1}finally{i.current="",f("")}},[m,y]);async function w(e,t,s,l){if(r.current||i.current)return;r.current=`toggle:${e}:${t}`;const o=await n({title:`${l?"Enable":"Disable"} ${s}?`,message:l?`Enabling ${s} makes it available to every role in its current release gate. Existing authorization checks remain in force.`:`Disabling ${s} prevents new use. Existing jobs and audit history are retained.`,confirmLabel:`${l?"Enable":"Disable"} ${s}`,confirmVariant:l?"primary":"danger"});r.current="",o&&await k({key:`toggle:${e}:${t}`,request:()=>a("/api/admin/tools",{method:"PATCH",body:JSON.stringify({type:e,key:t,enabled:l})}),successMessage:`${s} was ${l?"enabled":"disabled"}.`})}const N=c.data,S=N?.health,C=N?.operationsPanel?.operations,R=S?.malwareScanner,E=S?.credits,I=R?.candidates?.find(e=>e.enabled),_=e.useMemo(()=>[{label:"Failed jobs",value:S?.jobs?.failed},{label:"Dead letters",value:S?.outbox?.dead_lettered},{label:"Infected files",value:R?.taskHealth?.infected},{label:"Scanner errors or timeouts",value:R?.taskHealth?.errors},{label:"Stale quarantined files",value:R?.staleQuarantinedCount},{label:"Stale queued operations",value:C?.stale?.queued},{label:"Stale running operations",value:C?.stale?.running},{label:"Credit reconciliation mismatches",value:E?.reconciliationMismatches},{label:"Pending credit expirations",value:E?.pendingExpirations},{label:"Stale cloud-worker tasks",value:S?.cloudWorker?.staleTasks},{label:"Degraded credit health",value:mv(E?.status)?"ok"===E.status?0:1:null}],[E,S,R,C]),T=_.filter(e=>Number.isFinite(Number(e.value))&&Number(e.value)>0),A=_.filter(e=>!mv(e.value)).length,O=Object.entries(c.sourceErrors);return"loading"===c.status?t.jsx($g,{message:"Loading Tools health and controlsâ¦"}):"error"===c.status?t.jsx("div",{className:"tools-admin-panel",children:t.jsxs(Ku,{tone:"error",title:"Tools data is unavailable",action:t.jsx(ds,{type:"button",variant:"secondary",onClick:()=>y(m),children:"Retry"}),children:[t.jsx("p",{children:"No operational totals are shown because neither source returned current data."}),O.map(([e,a])=>t.jsxs("p",{children:[t.jsxs("strong",{children:["snapshot"===e?"Health and catalog":"Diagnostics",":"]}
2)," ",a]},e))]})}):t.jsxs("div",{className:"tools-admin-panel","aria-busy":"refreshing"===c.status,children:[O.length?t.jsxs(Ku,{tone:"error",title:"Some Tools data is unavailable",action:t.jsx(ds,{type:"button",variant:"secondary",disabled:"refreshing"===c.status,onClick:()=>y(m,{background:!0}),children:"Retry unavailable data"}),children:[O.map(([e,a])=>t.jsxs("p",{children:[t.jsxs("strong",{children:["snapshot"===e?"Health and catalog":"Diagnostics",":"]})," ",a]},e)),t.jsx("p",{children:"Known values remain visible; missing values are marked unavailable."})]}):null,b?t.jsx("div",{className:`tools-admin-notice tools-admin-notice--${b.tone}`,role:"error"===b.tone?"alert":"status",children:b.message}):null,t.jsxs(vv,{title:"Needs attention",description:"Exceptions and stale work lead this view so operators can triage before scanning normal telemetry.",className:"tools-admin-section--attention",children:[T.length?t.jsx("div",{className:"tools-admin-attention-grid",children:T.map(e=>t.jsx(xv,{label:e.label,value:pv(e.value),tone:"danger"},e.label))}):A?t.jsxs(Ku,{title:"Attention status is incomplete",tone:"loading",children:[A," exception"," ",1===A?"check is":"checks are"," unavailable. Known checks have no recorded exceptions."]}):t.jsxs(Ku,{title:"No known exceptions",tone:"empty",children:["All ",_.length," attention checks returned known zero values."]}),T.length&&A?t.jsxs("p",{className:"tools-admin-unavailable-note",children:[A," additional exception"," ",1===A?"check is":"checks are"," unavailable."]}):null]}),t.jsx(vv,{title:"Health summary",description:"Current service and processing signals.",children:t.jsxs("div",{className:"tools-admin-metrics-grid",children:[t.jsx(xv,{label:"Jobs",value:pv(S?.jobs?.total)}),t.jsx(xv,{label:"Active jobs",value:pv(S?.jobs?.active)}),t.jsx(xv,{label:"Outbox pending",value:pv(S?.outbox?.pending)}),t.jsx(xv,{label:"Provider",value:fv(S?.provider?.status)}),t.jsx(xv,{label:"File scanner",value:fv(R?.status)}),t.jsx(xv,{label:"Job compute",value:"boolean"==typeof S?.persistentJobCompute?S.persistentJobCompute?"Persistent":"Scale to zero":hv})]})}),t.jsx(vv,{title:"Usage and cost",description:"Known consumption and credit ledger evidence.",children:t.jsxs("div",{className:"tools-admin-metrics-grid",children:[t.jsx(xv,{label:"Credit accounts",value:pv(E?.accounts)}),t.jsx(xv,{label:"Active reservations",value:pv(E?.activeReservations)}),t.jsx(xv,{label:"Measured jobs (24h)",value:pv(C?.runtime?.measured_jobs)}),t.jsx(xv,{label:"vCPU usage",value:gv(C?.costs?.vcpu_seconds,"vCPU-s")}),t.jsx(xv,{label:"Memory usage",value:gv(C?.costs?.memory_gb_seconds,"GB-s")}),t.jsx(xv,{label:"Estimated compute",value:gv(C?.costs?.estimated_compute_microusd,"micro-USD")})]})}),t.jsxs(vv,{title:"Catalog and models",description:"Release gates and availability for bounded Tools resources.",children:[N?.catalog?t.jsxs(Bu,{minWidth:"720px",ariaLabel:"Tools catalog",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Resource"}),t.jsx("th",{children:"Type"}),t.jsx("th",{children:"Release gate"}),t.jsx("th",{children:"Status"}),t.jsx("th",{className:"admin-ui-table__actions",children:"Action"})]})}),t.jsxs("tbody",{children:[N.catalog.tools?.map(e=>{const a=`toggle:tool:${e.key}`;return t.jsxs("tr",{children:[t.jsxs("td",{children:[t.jsx("strong",{children:e.name}),e.description?t.jsx("small",{children:e.description}):null]}),t.jsx("td",{children:"Tool"}),t.jsx("td",{children:e.releaseGate?.join(", ")||hv}),t.jsx("td",{children:t.jsx(Vu,{variant:e.enabled?"success":"default",children:e.enabled?"Enabled":"Disabled"})}),t.jsxs("td",{className:"admin-ui-table__actions",children:[t.jsx(Xu,{type:"button",variant:e.enabled?"danger":"secondary",size:"small",disabled:"ocr-studio"===e.key&&!e.enabled||Boolean(g),loading:g===a,"aria-describedby":"ocr-studio"!==e.key||e.enabled?void 0:`tools-${e.key}-enable-note`,onClick:()=>w("tool",e.key,e.name,!e.enabled),children:e.enabled?"Disable":"Enable"}),"ocr-studio"!==e.key||e.enabled?null:t.jsx("small",{id:`tools-${e.key}-enable-note`,children:"Enablement requires an approved provider. Disabling remains available if this resource is ever active."})]})]},e.key)}),N.catalog.workflows?.map(e=>{const a=`toggle:workflow:${e.key}`;return t.jsxs("tr",{children:[t.jsxs("td",{children:[t.jsx("strong",{children:e.name}),e.description?t.jsx("small",{children:e.description}):null]}),t.jsx("td",{children:"Workflow"}),t.jsx("td",{children:e.releaseGate?.join(", ")||hv}),t.jsx("td",{children:t.jsx(Vu,{variant:e.enabled?"success":"default",children:e.enabled?"Enabled":"Disabled"})}),t.jsx("td",{className:"admin-ui-table__actions",children:t.jsx(Xu,{type:"button",variant:e.enabled?"danger":"secondary",size:"small",disabled:Boolean(g),loading:g===a,onClick:()=>w("workflow",e.key,e.name,!e.enabled),children:e.enabled?"Disable":"Enable"})})]},e.key)})]})]}):t.jsx(Ku,{title:"Catalog unavailable",tone:"loading",children:"Tool, workflow, and model status could not be loaded."}),t.jsxs("details",{className:"tools-admin-disclosure",children:[t.jsxs("summary",{children:["Model registry (",pv(N?.catalog?.models?.length),")"]}),N?.catalog?.models?.length?t.jsx("ul",{className:"tools-admin-model-list",children:N.catalog.models.map(e=>t.jsxs("li",{children:[t.jsxs("span",{children:[t.jsx("strong",{children:e.key}),t.jsxs("small",{children:[e.provider||"Provider unavailable"," ·"," ",e.modelVersion||"Version unavailable"]})]}),t.jsx(Vu,{variant:e.enabled?"success":"default",children:e.enabled?"Enabled":"Disabled"})]},e.key))}):N?.catalog?.models?t.jsx("p",{children:"No models are registered. Model-based processing remains disabled."}):t.jsx("p",{children:"Model registry data is unavailable."})]})]}),t.jsx(vv,{title:"Diagnostics",description:"Deeper safe operational metadata. Input and output content are excluded.",children:t.jsxs("details",{className:"tools-admin-disclosure",children:[t.jsx("summary",{children:"Runtime, scanner, and recovery details"}),t.jsxs("dl",{className:"tools-admin-diagnostics",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Runtime p50"}),t.jsx("dd",{children:gv(C?.runtime?.p50_runtime_ms,"ms")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Runtime p95"}),t.jsx("dd",{children:gv(C?.runtime?.p95_runtime_ms,"ms")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Scanner active"}),t.jsx("dd",{children:pv(R?.taskHealth?.active)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Scanner clean"}),t.jsx("dd",{children:pv(R?.taskHealth?.clean)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Scanner recent exits"}),t.jsx("dd",{children:pv(R?.taskHealth?.recent_exits)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Definitions version"}),t.jsx("dd",{children:I?.definitionsVersion||hv})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Definitions age"}),t.jsx("dd",{children:gv(R?.definitionsAgeSeconds,"seconds")})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Definition update"}),t.jsx("dd",{children:I?.statusMessage||hv})]}
2),t.jsxs("div",{children:[t.jsx("dt",{children:"External uploads"}),t.jsx("dd",{children:"boolean"==typeof R?.externalUploadsAccepted?R.externalUploadsAccepted?"Accepted":"Quarantined":hv})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Cloud worker active"}),t.jsx("dd",{children:pv(S?.cloudWorker?.activeTasks)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Cloud worker recent exits"}),t.jsx("dd",{children:pv(S?.cloudWorker?.recentExits)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Cloud worker stale"}),t.jsx("dd",{children:pv(S?.cloudWorker?.staleTasks)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Retention backlog"}),t.jsx("dd",{children:pv(bv(C?.retentionBacklog))})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Maintenance runs"}),t.jsx("dd",{children:pv(C?.maintenance?.length)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Dead-letter records"}),t.jsx("dd",{children:pv(N?.operationsPanel?.deadLetters?.length)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Model/provider groups"}),t.jsx("dd",{children:pv(C?.modelProviders?.length)})]})]})]})}),t.jsx(vv,{title:"Manual operations",description:"Audited operator commands. Each mutating action explains its consequence before it runs.",children:t.jsxs("div",{className:"tools-admin-manual-grid",children:[t.jsxs("div",{className:"tools-admin-operation-card",children:[t.jsx("h3",{children:"Processing Credits preview"}),t.jsx("p",{children:"Adjustments are append-only and audited. Positive values grant preview credits; negative values may debit only currently available credits."}),t.jsxs("form",{className:"tools-admin-form",onSubmit:async function(e){if(e.preventDefault(),r.current||i.current)return;r.current="credits:adjust";const t={...v},s=await n({title:"Record credit adjustment?",message:`This creates an append-only audited ${t.displayCredits} credit adjustment for ${t.ownerEmail}. It does not edit prior ledger entries.`,confirmLabel:"Record adjustment"});if(r.current="",!s)return;await k({key:"credits:adjust",request:()=>a("/api/admin/tools/credits/adjust",{method:"POST",headers:{"Idempotency-Key":o.current},body:JSON.stringify(t)}),successMessage:`The audited credit adjustment for ${t.ownerEmail} was recorded.`})&&(o.current=crypto.randomUUID(),j({ownerEmail:"",displayCredits:"",reason:""}))},children:[t.jsxs("div",{className:"tools-admin-form-grid",children:[t.jsx(Wu,{label:"Exact owner email",htmlFor:"tools-credit-owner",children:t.jsx("input",{id:"tools-credit-owner",type:"email",required:!0,value:v.ownerEmail,onChange:e=>j(t=>(o.current=crypto.randomUUID(),{...t,ownerEmail:e.target.value}))})}),t.jsx(Wu,{label:"Displayed credits",htmlFor:"tools-credit-amount",hint:"Examples: 10 or -2.5",children:t.jsx("input",{id:"tools-credit-amount",inputMode:"decimal",required:!0,value:v.displayCredits,onChange:e=>j(t=>(o.current=crypto.randomUUID(),{...t,displayCredits:e.target.value}))})})]}),t.jsx(Wu,{label:"Audit reason",htmlFor:"tools-credit-reason",children:t.jsx("input",{id:"tools-credit-reason",required:!0,minLength:8,maxLength:500,value:v.reason,onChange:e=>j(t=>(o.current=crypto.randomUUID(),{...t,reason:e.target.value}))})}),t.jsxs("div",{className:"tools-admin-actions",children:[t.jsx(Xu,{type:"submit",loading:"credits:adjust"===g,disabled:Boolean(g),children:"Record adjustment"}),t.jsx(Xu,{type:"button",variant:"secondary",loading:"credits:reconcile"===g,disabled:Boolean(g),onClick:async function(){if(r.current||i.current)return;r.current="credits:reconcile";const e=await n({title:"Reconcile credit events?",message:"This scans up to 50 normalized Stripe events and records any safe reconciliation work. It does not modify Stripe resources.",confirmLabel:"Run reconciliation"});r.current="",e&&await k({key:"credits:reconcile",request:()=>a("/api/admin/tools/credits/reconcile",{method:"POST",body:JSON.stringify({limit:50})}),resolveOutcome:e=>{const t=e?.data?.reconciliation||{},a=e?.data?.health||{},n=`${pv(t.scanned)} scanned, ${pv(t.applied)} applied, ${pv(t.blocked)} blocked.`;return!1===e?.ok||"degraded"===a.status?{tone:"warning",message:`Reconciliation completed, but credit health remains degraded. ${n}`}:Number(t.blocked)>0?{tone:"warning",message:`Reconciliation completed with blocked events. ${n}`}:{tone:"success",message:`Credit event reconciliation completed. ${n}`}}})},children:"Reconcile credit events"})]})]})]}),t.jsxs("div",{className:"tools-admin-operation-card",children:[t.jsx("h3",{children:"Safe job lookup"}),t.jsx("p",{children:"Searches safe job metadata by exact job ID or exact owner email."}),t.jsxs("form",{className:"tools-admin-search",onSubmit:e=>{e.preventDefault();const t=u.trim();p(t),y(t)},children:[t.jsx(Wu,{label:"Job ID or exact owner email",htmlFor:"tools-job-search",children:t.jsx("input",{id:"tools-job-search",value:u,onChange:e=>h(e.target.value)})}),t.jsx(ds,{type:"submit",disabled:"refreshing"===c.status,children:"Search"})]}),Array.isArray(N?.jobs)?N.jobs.length?t.jsxs(Bu,{minWidth:"620px",ariaLabel:"Safe Tools job results",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Job"}),t.jsx("th",{children:"Owner"}),t.jsx("th",{children:"Workflow"}),t.jsx("th",{children:"Status"})]})}),t.jsx("tbody",{children:N.jobs.map(e=>t.jsxs("tr",{children:[t.jsx("td",{dir:"auto",children:e.id}),t.jsx("td",{dir:"auto",children:e.ownerEmail}),t.jsx("td",{children:e.workflowKey||e.toolKey||hv}),t.jsx("td",{children:fv(e.state)})]},e.id))})]}):t.jsx(Ku,{title:"No matching jobs",tone:"empty",children:m?"No safe job metadata matched this exact lookup.":"No recent jobs were returned."}):t.jsx(Ku,{title:"Job data unavailable",tone:"loading"})]})]})})]})}function yv({user:a,request:n,onDeleted:s,disabled:r=!1}){const i=e.useId(),l=`${i}-transfer`,o=`${i}-reason`,c=`${i}-confirmation`,d=`${i}-confirmation-hint`,[u,h]=e.useState(!1),[m,p]=e.useState(!1),[g,f]=e.useState(!1),[b,x]=e.useState(null),[v,j]=e.useState(null),[y,k]=e.useState(""),[w,N]=e.useState("administrative_request"),[S,C]=e.useState(""),R=e.useRef(null),E=`/api/admin/users/${encodeURIComponent(a.id)}/deletion`,I=a.name||a.email||a.id,_=b?.blockers||[],T=_.some(e=>String(e.key||"").startsWith("owned_")),A=_.some(e=>!String(e.key||"").startsWith("owned_")),O=Boolean(b&&y===b.confirmationText&&!A&&(!T||S)&&!g),D=e.useMemo(()=>Object.entries(b?.effectSummary||{}).filter(([,e])=>Number(e)>0),[b]),P=()=>{x(null),j(null),k(""),N("administrative_request"),C("")},L=()=>{g||(h(!1),P())};return t.jsxs(t.Fragment,{children:[t.jsx(ds,{size:"small",variant:"danger",className:"admin-user-deletion-trigger",onClick:async()=>{h(!0),P(),R.current=globalThis.crypto.randomUUID(),p(!0);try{const e=await n(E);x(e.data)}catch(e){j(bm(e,"Unable to check whether this user can be deleted."))}finally{p(!1)}},disabled:r||g,children:"Delete permanently"}),t.jsxs(Ju,{isOpen:u,onClose:L,title:`Permanently delete â${I}â?`,className:"admin-user-deletion-modal",children:[t.jsxs(Yu,{children:[t.jsx("p",{className:"admin-user-deletion-warning",children:"This request suspends access immediately and can be cancelled during the 30-day grace peri
2od. Once destructive execution starts after that deadline, it cannot be undone."}),m?t.jsx("p",{role:"status",children:"Checking deletion blockersâ¦"}):null,v?t.jsxs("p",{className:"admin-user-deletion-error",role:"alert",children:[v.message,v.code?t.jsxs("span",{className:"admin-user-deletion-code",children:[" (",v.code,")"]}):null]}):null,b?.canDelete?t.jsx("p",{className:"admin-user-deletion-status is-ready",children:"This account is eligible for permanent deletion."}):null,b&&_.length?t.jsxs("div",{className:"admin-user-deletion-status is-blocked",role:"status",children:[t.jsx("p",{children:A?"Deletion is blocked. Resolve these items before trying again.":"Owned records must be transferred as part of this request."}),t.jsx("ul",{children:_.map(e=>t.jsxs("li",{children:[e.label,": ",e.count,e.remediation?` â ${e.remediation}`:""]},e.key))})]}):null,b?t.jsxs(t.Fragment,{children:[T&&!A?t.jsx(Wu,{label:"Transfer all owned records to",htmlFor:l,children:t.jsxs("select",{id:l,value:S,onChange:e=>C(e.target.value),disabled:g,children:[t.jsx("option",{value:"",children:"Choose an active internal user"}),(b.ownershipSuccessors||[]).map(e=>t.jsx("option",{value:e.id,children:e.name||e.id},e.id))]})}):null,t.jsx(Wu,{label:"Reason",htmlFor:o,children:t.jsxs("select",{id:o,value:w,onChange:e=>N(e.target.value),disabled:g,children:[t.jsx("option",{value:"administrative_request",children:"Administrative request"}),t.jsx("option",{value:"privacy_request",children:"Privacy request"}),t.jsx("option",{value:"employment_ended",children:"Employment ended"}),t.jsx("option",{value:"test_cleanup",children:"Test cleanup"}),t.jsx("option",{value:"other",children:"Other approved reason"})]})}),t.jsx(Wu,{label:`Type ${b.confirmationText} to confirm`,hint:"The account is suspended immediately. A database-generated 30-day grace period follows; an administrator can cancel before execution is leased.",htmlFor:c,hintId:d,children:t.jsx("input",{id:c,"aria-describedby":d,value:y,onChange:e=>k(e.target.value),autoComplete:"off",spellCheck:"false",disabled:g||A})}),D.length?t.jsxs("details",{className:"admin-user-deletion-effects",children:[t.jsx("summary",{children:"Review affected records"}),t.jsx("ul",{children:D.map(([e,a])=>t.jsxs("li",{children:[e.replaceAll("_"," "),": ",a]},e))})]}):null]}):null]}),t.jsxs(Qu,{children:[t.jsx(ds,{variant:"secondary",onClick:L,disabled:g,children:"Cancel"}),t.jsx(ds,{variant:"danger",onClick:async()=>{f(!0),j(null);try{const e=await n(E,{method:"DELETE",body:JSON.stringify({confirmation:y,reasonCategory:w,idempotencyKey:R.current,...S?{transferToUserId:S}:{}})});h(!1),P(),await(s?.(e.data))}catch(e){const t=gm(e);Array.isArray(t)&&x(e=>({...e,canDelete:!1,blockers:t})),j(bm(e,"Unable to request permanent deletion."))}finally{f(!1)}},disabled:!O,children:g?"Requesting deletionâ¦":"Delete user permanently"})]})]})]})}const kv=[20,50,100],wv=["","new","reviewing","interviewing","hired","rejected"],Nv={title:"",slug:"",location:"",commitment:"",compensation:"",department:"",employmentType:"",summary:"",description:"",responsibilities:"",qualifications:"",niceToHave:"",benefits:"",is_active:!0};function Sv(e){return e?Array.isArray(e)?e.join("\n"):e:""}function Cv(e){return e?new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}):"N/A"}function Rv(){const{makeAuthRequest:a}=Yn(),n=s(),r=i(),l=Ds(),o=$s(),c=e.useMemo(()=>function(e){const t=new URLSearchParams(e),a=t.get("career_limit")||"20",n=t.get("career_offset")||"0",s=/^\d+$/u.test(a)?Number.parseInt(a,10):20,r=kv.includes(s)?s:20,i=/^\d+$/u.test(n)?Number.parseInt(n,10):0,l=Number.isFinite(i)&&i>=0?i:0,o=t.get("career_status")||"";return{positionId:t.get("career_position")||"",status:wv.includes(o)?o:"",limit:r,offset:Math.floor(l/r)*r}}(n.search),[n.search]),d=e.useMemo(()=>JSON.stringify(c),[c]),u=e.useRef(0),[h,m]=e.useState([]),[p,g]=e.useState(!0),[f,b]=e.useState(null),[x,v]=e.useState([]),[j,y]=e.useState(!0),[k,w]=e.useState(null),[N,S]=e.useState({total:0,limit:20,offset:0}),[C,R]=e.useState(null),[E,I]=e.useState(!1),[_,T]=e.useState(!1),[A,O]=e.useState(Nv),D=e.useCallback((e,{replace:t=!1}={})=>{const a={...c,...e},s=new URLSearchParams(n.search),i=(e,t,a="")=>{t===a||""===t?s.delete(e):s.set(e,String(t))};i("career_position",a.positionId),i("career_status",a.status),i("career_limit",a.limit,20),i("career_offset",a.offset,0),r({pathname:n.pathname,search:s.toString()},{replace:t})},[n.pathname,n.search,r,c]),P=e.useCallback(async()=>{g(!0),b(null);try{const e=await a("/api/admin/careers/positions");
2if(!e.ok)throw new Error(e.error?.message||"Failed to load roles");m(e.data||[])}catch(e){b(e.message||"Failed to load roles")}finally{g(!1)}},[a]),L=e.useCallback(async()=>{const e=u.current+1;u.current=e,y(!0),w(null);try{const t=new URLSearchParams({limit:String(c.limit),offset:String(c.offset)});c.positionId&&t.set("positionId",c.positionId),c.status&&t.set("status",c.status);const n=await a(`/api/admin/careers/applications?${t}`);if(e!==u.current)return;if(!n.ok)throw new Error(n.error?.message||"Failed to load applications");const s=n.data||[],r=n.pagination||{total:s.length,limit:c.limit,offset:c.offset};if(0===s.length&&r.total>0&&c.offset>0){const e=Math.floor((r.total-1)/c.limit)*c.limit;return void D({offset:e},{replace:!0})}v(s),S(r)}catch(t){if(e!==u.current)return;w(t.message||"Failed to load applications")}finally{e===u.current&&y(!1)}},[a,c.limit,c.offset,c.positionId,c.status,D]);e.useEffect(()=>{P()},[P]),e.useEffect(()=>{(function(e,t){const a=new URLSearchParams(e),n={career_position:t.positionId||null,career_status:t.status||null,career_limit:20===t.limit?null:String(t.limit),career_offset:0===t.offset?null:String(t.offset)};return Object.entries(n).every(([e,t])=>a.get(e)===t)})(n.search,c)||D({},{replace:!0})},[n.search,c,D]),e.useEffect(()=>{L()},[L,d]);const $=({close:e=!1}={})=>{R(null),O(Nv),e&&T(!1)},M=Boolean(c.positionId||c.status);return t.jsxs("div",{className:"careers-admin-panel",children:[t.jsxs(Js,{className:"careers-applications-card",children:[t.jsxs("div",{className:"metrics-card-header careers-applications-heading",children:[t.jsxs("div",{children:[t.jsx("h2",{children:"Applications"}),t.jsx("p",{className:"admin-subtitle",children:"Triage recent candidates before maintaining role copy."})]}),t.jsx(ds,{onClick:()=>{$(),T(!0)},children:"Create role"})]}),t.jsxs(zu,{ariaLabel:"Career application filters",children:[t.jsx(Wu,{label:"Position",htmlFor:"career-position-filter",children:t.jsxs("select",{id:"career-position-filter",value:c.positionId,onChange:e=>D({positionId:e.target.value,offset:0}),children:[t.jsx("option",{value:"",children:"All positions"}),h.map(e=>t.jsx("option",{value:e.id,children:e.title},e.id))]})}),t.jsx(Wu,{label:"Status",htmlFor:"career-status-filter",children:t.jsxs("select",{id:"career-status-filter",value:c.status,onChange:e=>D({status:e.target.value,offset:0}),children:[t.jsx("option",{value:"",children:"All statuses"}),t.jsx("option",{value:"new",children:"New"}),t.jsx("option",{value:"reviewing",children:"Reviewing"}),t.jsx("option",{value:"interviewing",children:"Interviewing"}),t.jsx("option",{value:"hired",children:"Hired"}),t.jsx("option",{value:"rejected",children:"Rejected"})]})}),t.jsx(ds,{type:"button",variant:"secondary",disabled:!M||j,onClick:()=>D({positionId:"",status:"",offset:0}),children:"Clear filters"})]}),j?t.jsx(Ku,{title:"Loading applications",tone:"loading",children:"Fetching the current candidate page."}):k?t.jsx(Ku,{title:"Applications unavailable",tone:"error",action:t.jsx(ds,{variant:"secondary",onClick:L,children:"Retry"}),children:k}):0===x.length?t.jsx(Ku,{title:M?"No applications match these filters":"No applications yet",action:M?t.jsx(ds,{variant:"secondary",onClick:()=>D({positionId:"",status:"",offset:0}),children:"Clear filters"}):null,children:M?"Try a different position or status.":"Submitted applications will appear here."}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"careers-applications-desktop",children:t.jsxs(Bu,{className:"careers-applications-table",minWidth:"720px",ariaLabel:"Career applications",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Applicant"}),t.jsx("th",{children:"Role"}),t.jsx("th",{children:"Status"}),t.jsx("th",{children:"Email"}),t.jsx("th",{children:"Submitted"}),t.jsx("th",{className:"admin-ui-table__actions-cell",children:"Resume"})]})}),t.jsx("tbody",{children:x.map(e=>t.jsxs("tr",{children:[t.jsxs("td",{children:[t.jsx("div",{className:"applicant-name",children:e.full_name}),t.jsx("div",{className:"applicant-meta",children:e.location||"Location unknown"})]}),t.jsx("td",{children:e.role_title||e.position_title||"N/A"}),t.jsx("td",{children:e.status||"Unknown"}),t.jsx("td",{children:e.email}),t.jsx("td",{children:Cv(e.created_at)}),t.jsx("td",{className:"admin-ui-table__actions-cell",children:e.resume_url?t.jsx("a",{href:e.resume_url,className:"btn btn-secondary btn-small",target:"_blank",rel:"noopener noreferrer",children:"View resume"}):"Unavailable"})]},e.id))})]})}),t.jsx("div",{className:"careers-applications-mobile","aria-label":"Career applications",children:x.map(e=>t.jsxs("article",{className:"career-application-card",children:[t.jsxs("div",{className:"career-application-card__heading",children:[t.jsx("h3",{children:e.full_name}),t.jsx(li,{variant:"default",children:e.status||"Unknown"})]}),t.jsxs("dl",{children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Role"}),t.jsx("dd",{children:e.role_title||e.position_title||"N/A"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Email"}),t.jsx("dd",{children:e.email})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Location"}),t.jsx("dd",{children:e.location||"Location unknown"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Submitted"}),t.jsx("dd",{children:Cv(e.created_at)})]})]}),e.resume_url?t.jsx("a",{href:e.resume_url,className:"btn btn-secondary btn-small",target:"_blank",rel:"noopener noreferrer",children:"View resume"}):t.jsx("p",{className:"admin-subtitle",children:"Resume unavailable"})]},e.id))}),t.jsx(Gu,{total:N.total,limit:c.limit,offset:c.offset,pageSizes:kv,label:"Applications",disabled:j,onOffsetChange:e=>D({offset:e}),onLimitChange:e=>D({limit:e,offset:0})})]})]}),t.jsxs("details",{className:"careers-editor",open:_,onToggle:e=>T(e.currentTarget.open),children:[t.jsx("summary",{children:C?`Editing ${A.title||"role"}`:"Role authoring"}),t.jsxs(Js,{className:"careers-form-card",children:[t.jsxs("div",{className:"metrics-card-header",children:[t.jsx("h2",{children:C?"Edit Role":"Create Role"}),t.jsx(ds,{variant:"secondary",onClick:()=>$({close:!0}),children:"Close editor"})]}),t.jsx("p",{className:"admin-subtitle",children:"Create and maintain the position cards shown on the public careers page."}),t.jsxs("form",{className:"careers-form",onSubmit:async e=>{e.preventDefault(),I(!0),b(null);try{const e=await a("/api/admin/careers/positions",{method:C?"PATCH":"POST",body:JSON.stringify({...A,id:C||void 0})});if(!e.ok)throw new Error(e.error?.message||"Failed to save role");
2l({type:"success",message:C?"Role updated.":"Role created."}),$({close:!0}),await P()}catch(t){b(t.message||"Failed to save role"),l({type:"error",message:t.message||"Failed to save role"})}finally{I(!1)}},children:[t.jsxs("div",{className:"careers-grid",children:[[["title","Role title","e.g. Machine Learning Engineer"],["slug","Slug (optional)","ml-engineer"],["location","Location","Remote, US-friendly"],["commitment","Commitment","Full-time, Part-time"],["compensation","Compensation","$80k-$110k"],["department","Department","Research & Engineering"],["employmentType","Employment type","Contract, Internship"]].map(([e,a,n])=>t.jsx(Wu,{label:a,htmlFor:`career-${e}`,children:t.jsx("input",{id:`career-${e}`,type:"text",value:A[e],onChange:t=>O(a=>({...a,[e]:t.target.value})),placeholder:n})},e)),[["summary","Summary",2,"Short teaser for the position card"],["description","Role description",4,"Describe the role in detail"],["responsibilities","Responsibilities (one per line)",4,"Own project delivery"],["qualifications","Qualifications (one per line)",4,"Strong research skills"],["niceToHave","Nice to have (one per line)",3,"Knowledge graphs"],["benefits","Benefits (one per line)",3,"Flexible schedule"]].map(([e,a,n,s])=>t.jsx(Wu,{label:a,htmlFor:`career-${e}`,className:"form-span",children:t.jsx("textarea",{id:`career-${e}`,rows:n,value:A[e],onChange:t=>O(a=>({...a,[e]:t.target.value})),placeholder:s})},e))]}),t.jsxs("div",{className:"careers-actions",children:[t.jsxs("label",{className:"checkbox",children:[t.jsx("input",{type:"checkbox",checked:A.is_active,onChange:e=>O(t=>({...t,is_active:e.target.checked}))}),"Visible on careers page"]}),t.jsxs("div",{className:"careers-buttons",children:[t.jsx(ds,{variant:"secondary",type:"button",onClick:()=>$(),children:"Reset"}),t.jsx(ds,{type:"submit",disabled:E,children:E?"Saving...":"Save role"})]})]})]}),t.jsxs("div",{className:"career-preview",children:[t.jsx("h3",{children:"Position card preview"}),t.jsx(Js,{title:A.title||"Role title",meta:`${A.location||"Remote"} ⢠${A.commitment||"Flexible"} ⢠${A.compensation||"Compensation varies"}`,body:A.summary||A.description||"Use the summary to pitch the role.",primary:{label:"View Role",href:"/careers"}})]})]})]}),t.jsxs(Js,{className:"careers-list-card",children:[t.jsxs("div",{className:"metrics-card-header",children:[t.jsxs("div",{children:[t.jsx("h2",{children:"Open Roles"}),t.jsx("p",{className:"admin-subtitle",children:"Publication state and role maintenance."})]}),t.jsx(ds,{variant:"secondary",onClick:P,children:"Refresh"})]}),p?t.jsx(Ku,{title:"Loading roles",tone:"loading"}):f?t.jsx(Ku,{title:"Roles unavailable",tone:"error",action:t.jsx(ds,{variant:"secondary",onClick:P,children:"Retry"}),children:f}):0===h.length?t.jsx(Ku,{title:"No roles created yet",children:"Create a role when a new position is approved."}):t.jsx("div",{className:"careers-role-grid",children:h.map(e=>t.jsxs(Js,{className:"career-role-card",children:[t.jsxs("div",{className:"career-role-header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:e.title}),t.jsxs("p",{children:[e.location||"Remote"," ⢠",e.commitment||"Flexible"," â¢"," ",e.compensation||"Compensation varies"]})]}),t.jsx(li,{variant:e.is_active?"success":"danger",children:e.is_active?"Active":"Closed"})]}),t.jsx("p",{className:"career-role-summary",children:e.summary||e.description||"No summary provided."}),t.jsxs("div",{className:"career-role-actions",children:[t.jsx(ds,{size:"small",variant:"secondary",onClick:()=>(e=>{R(e.id),O({title:e.title||"",slug:e.slug||"",location:e.location||"",commitment:e.commitment||"",compensation:e.compensation||"",department:e.department||"",employmentType:e.employment_type||"",summary:e.summary||"",description:e.description||"",responsibilities:Sv(e.responsibilities),qualifications:Sv(e.qualifications),niceToHave:Sv(e.nice_to_have),benefits:Sv(e.benefits),is_active:!1!==e.is_active}),T(!0)})(e),children:"Edit"}),t.jsx(ds,{size:"small",variant:e.is_active?"danger":"secondary",onClick:()=>(async e=>{const t=!e.is_active;if(await o({title:t?"Reopen role?":"Close role?",message:t?"This role will appear on the careers page.":"This role will no longer appear on the careers page.",confirmLabel:t?"Reopen":"Close",confirmVariant:t?"primary":"danger"}))try{const n=await a("/api/admin/careers/positions",{method:"PATCH",body:JSON.stringify({id:e.id,is_active:t})});if(!n.ok)throw new Error(n.error?.message||"Failed to update role");await P()}catch(n){l({type:"error",message:n.message||"Failed to update role"})}}
2)(e),children:e.is_active?"Close":"Reopen"}),t.jsx(ds,{size:"small",variant:"tertiary",onClick:()=>(async e=>{if(await o({title:"Archive role?",message:"This will hide the role from the careers page.",confirmLabel:"Archive role",confirmVariant:"danger"}))try{const t=await a(`/api/admin/careers/positions?id=${e.id}`,{method:"DELETE"});if(!t.ok)throw new Error(t.error?.message||"Failed to archive role");await P()}catch(t){l({type:"error",message:t.message||"Failed to archive role"})}})(e),children:"Archive"})]})]},e.id))})]})]})}const Ev={new:["in_review","resolved","dismissed"],in_review:["resolved","dismissed"],resolved:["in_review"],dismissed:["in_review"]};function Iv(e){return e?new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}):"N/A"}function _v(){const{makeAuthRequest:a}=Yn(),n=Ds(),[s,r]=e.useState([]),[i,l]=e.useState(!1),[o,c]=e.useState(null),[d,u]=e.useState({status:"",category:""}),[h,m]=e.useState({total:0,limit:50,offset:0}),p=e.useRef(0),[g,f]=e.useState(null),[b,x]=e.useState({}),[v,j]=e.useState(null),y=async({offset:e,limit:t,nextFilter:n}={})=>{const s=p.current+1;p.current=s;const i=n||d,o=Number.isFinite(e)?e:h.offset,u=Number.isFinite(t)?t:h.limit;l(!0),c(null);try{const e=new URLSearchParams;i.status&&e.set("status",i.status),i.category&&e.set("category",i.category),e.set("limit",String(u)),e.set("offset",String(o));const t=await a(`/api/admin/feedback?${e}`);if(s!==p.current)return;if(!t.ok)throw new Error(t.error?.message||"Failed to load feedback");const n=t.data.feedback||[];r(n),x(e=>{const t={...e};return n.forEach(e=>{t[e.id]||(t[e.id]={admin_notes:e.admin_notes||"",admin_response:e.admin_response||""})}),t}),m({total:t.data.pagination?.total||0,limit:t.data.pagination?.limit||u,offset:t.data.pagination?.offset||o})}catch(g){if(s!==p.current)return;c(g.message||"Failed to load feedback")}finally{s===p.current&&l(!1)}};e.useEffect(()=>{y({offset:0})},[]);const k=e=>{e&&(r(t=>t.map(t=>t.id===e.id?e:t)),x(t=>({...t,[e.id]:{admin_notes:e.admin_notes||"",admin_response:e.admin_response||""}})))},w=e=>{const t={...d,...e};u(t),f(null),y({nextFilter:t,offset:0})},N=Boolean(d.status||d.category);return t.jsxs("div",{className:"feedback-admin-section",children:[t.jsx("div",{className:"feedback-admin-header",children:t.jsxs("div",{children:[t.jsx("h2",{children:"User feedback triage"}),t.jsx("p",{className:"admin-subtitle",children:"Review reports, record internal context, and respond to submitters."})]})}),t.jsxs(zu,{ariaLabel:"Feedback filters",children:[t.jsx(Wu,{label:"Status",htmlFor:"admin-feedback-status",children:t.jsxs("select",{id:"admin-feedback-status",value:d.status,onChange:e=>w({status:e.target.value}),className:"form-input feedback-filter-select",children:[t.jsx("option",{value:"",children:"All statuses"}),t.jsx("option",{value:"new",children:"New"}),t.jsx("option",{value:"in_review",children:"In review"}),t.jsx("option",{value:"resolved",children:"Resolved"}),t.jsx("option",{value:"dismissed",children:"Dismissed"})]})}),t.jsx(Wu,{label:"Category",htmlFor:"admin-feedback-category",children:t.jsxs("select",{id:"admin-feedback-category",value:d.category,onChange:e=>w({category:e.target.value}),className:"form-input feedback-filter-select",children:[t.jsx("option",{value:"",children:"All categories"}),t.jsx("option",{value:"bug",children:"Bug reports"}),t.jsx("option",{value:"feature",children:"Feature requests"}),t.jsx("option",{value:"general",children:"General"})]})}),t.jsx(ds,{variant:"secondary",size:"small",onClick:()=>y(),children:"Refresh"})]}),i?t.jsx($g,{message:"Loading feedback..."}):o?t.jsx(Ku,{title:"Feedback could not be loaded",tone:"error",action:t.jsx(ds,{onClick:()=>y(),children:"Retry"}),children:o}):0===s.length?t.jsx(Ku,{title:N?"No feedback matches these filters":"No feedback submitted yet",action:N?t.jsx(ds,{variant:"secondary",onClick:()=>w({status:"",category:""}),children:"Clear filters"}):null,children:N?"Broaden the filters to see more feedback.":"New product feedback will appear here."}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"feedback-admin-list",children:s.map(e=>{const i=b[e.id]||{admin_notes:e.admin_notes||"",admin_response:e.admin_response||""},l=(o=e.status,Ev[o]||[]);var o;const c=g===e.id;return t.jsxs(Js,{className:"feedback-admin-card",children:[t.jsxs("button",{type:"button",className:"feedback-admin-card-header","aria-expanded":c,"aria-controls":`feedback-admin-card-body-${e.id}`,onClick:()=>{c?f(null):(f(e.id),x(t=>
2({...t,[e.id]:{admin_notes:e.admin_notes||"",admin_response:e.admin_response||""}})))},children:[t.jsxs("div",{className:"feedback-admin-card-info",children:[t.jsxs("div",{className:"feedback-admin-card-badges",children:[t.jsx(li,{variant:"bug"===e.category?"danger":"feature"===e.category?"info":"default",children:e.category}),t.jsx(li,{variant:"new"===e.status?"warning":"in_review"===e.status?"info":"resolved"===e.status?"success":"default",children:e.status.replace("_"," ")})]}),t.jsx("h3",{className:"feedback-admin-card-title",children:e.title}),t.jsxs("div",{className:"feedback-admin-card-meta",children:[t.jsx("span",{children:e.user_name||e.user_email}),t.jsx("span",{"aria-hidden":"true",children:"·"}),t.jsx("span",{children:Iv(e.created_at)}),e.resolved_at?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",children:"·"}),t.jsxs("span",{children:["Resolved ",Iv(e.resolved_at)]})]}):null]})]}),t.jsx("span",{className:"feedback-expand-icon","aria-hidden":"true",children:c?"â²":"â¼"})]}),c?t.jsxs("div",{className:"feedback-admin-card-body",id:`feedback-admin-card-body-${e.id}`,children:[t.jsxs("div",{className:"feedback-admin-description",children:[t.jsx("h4",{children:"Description"}),t.jsx("p",{children:e.description})]}),e.error_context?t.jsxs("div",{className:"feedback-admin-error-context",children:[t.jsx("h4",{children:"Error Context"}),t.jsx("pre",{children:JSON.stringify(e.error_context,null,2)})]}):null,e.client_context||e.page_path||e.related_document?t.jsxs("div",{className:"feedback-admin-error-context",children:[t.jsx("h4",{children:"Client Context"}),t.jsx("pre",{children:JSON.stringify({page_path:e.page_path,related_document:e.related_document,client_context:e.client_context},null,2)})]}):null,t.jsxs("div",{className:"feedback-admin-notes",children:[t.jsx("label",{htmlFor:`feedback-admin-notes-${e.id}`,children:"Internal Notes"}),t.jsx("textarea",{id:`feedback-admin-notes-${e.id}`,value:i.admin_notes,onChange:t=>x(a=>({...a,[e.id]:{admin_notes:t.target.value,admin_response:a[e.id]?.admin_response||""}})),className:"form-input",rows:3,placeholder:"Add internal notes..."}),t.jsx("label",{htmlFor:`feedback-admin-response-${e.id}`,children:"Response to User"}),t.jsx("textarea",{id:`feedback-admin-response-${e.id}`,value:i.admin_response,onChange:t=>x(a=>({...a,[e.id]:{admin_notes:a[e.id]?.admin_notes||"",admin_response:t.target.value}})),className:"form-input",rows:3,placeholder:"Write a response the submitter can see..."}),t.jsx(ds,{variant:"secondary",size:"small",onClick:()=>(async e=>{const t=s.find(t=>t.id===e);if(!t)return;const i=b[e]||{};j(e);try{const s=await a(`/api/admin/feedback/${e}`,{method:"PATCH",body:JSON.stringify({admin_notes:i.admin_notes||null,admin_response:i.admin_response||null,expectedUpdatedAt:t.updated_at})});if(!s.ok)throw"FEEDBACK_UPDATE_CONFLICT"===s.error?.code&&k(s.data?.feedback),new Error(s.error?.message||"Failed to save feedback response");n({type:"success",message:"Feedback response saved"}),r(t=>t.map(t=>t.id===e?s.data.feedback:t)),x(t=>({...t,[e]:{admin_notes:s.data.feedback.admin_notes||"",admin_response:s.data.feedback.admin_response||""}}))}catch(l){n({type:"error",message:l.message})}finally{j(null)}})(e.id),disabled:v===e.id,children:v===e.id?"Saving...":"Save Response"})]}),t.jsxs("div",{className:"feedback-admin-status-actions",children:[t.jsx("span",{children:"Set status:"}),0===l.length?t.jsx("span",{children:"No status actions available"}):null,l.map(i=>t.jsx(ds,{variant:"resolved"===i?"primary":"ghost",size:"small",onClick:()=>(async(e,t)=>{const i=s.find(t=>t.id===e);if(i){j(e);try{const s=await a(`/api/admin/feedback/${e}`,{method:"PATCH",body:JSON.stringify({status:t,expectedUpdatedAt:i.updated_at})});if(!s.ok)throw"FEEDBACK_UPDATE_CONFLICT"===s.error?.code&&k(s.data?.feedback),new Error(s.error?.message||"Failed to update");n({type:"success",message:`Feedback marked as ${t.replace("_"," ")}`}),r(t=>t.map(t=>t.id===e?s.data.feedback:t))}catch(l){n({type:"error",message:l.message})}finally{j(null)}}})(e.id,i),disabled:v===e.id,children:i.replace("_"," ")},i))]})]}):null]},e.id)})}),t.jsx(Gu,{total:h.total,limit:h.limit,offset:h.offset,onOffsetChange:e=>y({offset:e}),onLimitChange:e=>y({limit:e,offset:0}),pageSizes:[25,50,100],label:"Feedback",disabled:i})]})]})}const Tv=[20,50,100],Av={status:"idle",loadedDocumentId:null,entries:[],error:null};const Ov=Object.freeze(Object.defineProperty({__proto__:null,default:()=>{const{makeAuthRequest:a}=Yn(),n=s(),r=i(),l=e.useMemo(()=>function(e){const t=new URLSearchParams(e),a=Number.parseInt(t.get("limit")||"50",10),n=Number.parseInt(t.get("offset")||"0",10);return{org_id:t.get("org_id")||"",user_email:t.get("user_email")||"",filename:t.get("filename")||"",limit:Tv.includes(a)?a:50,offset:Number.isFinite(n)&&n>=0?n:0}}(n.search),[n.search]),o=e.useMemo(()=>JSON.stringify(l),[l]),[c,d]=e.useState("list"),[u,h]=e.useState([]),[m,p]=e.useState(null),[g,f]=e.useState(Av),[b,x]=e.useState(null),[v,j]=e.useState(!1),[y,k]=e.useState(null),[w,N]=e.useState(!1),[S,C]=e.useState(null),[R,E]=e.useState(""),[I,_]=e.useState("viewer"),[T,A]=e.useState(null),[O,D]=e.useState(!1),[P,L]=e.useState({total:0,limit:50,offset:0}),$=e.useRef(0),M=Ds(),U=$s(),F=e.useCallback(async e=>("documents"===e||r(`/admin?tab=${e}`),!0),[r]),z=e.useCallback(async e=>(r(e),!0),[r]),q=e.useRef(!0),B=e.useRef(null),W=e.useRef(Av),V=e.useRef(0),H=e.useRef(null),K=e.useRef(null),[G,J]=e.useState({org_id:l.org_id,user_email:l.user_email,filename:l.filename}),Y=e.useCallback((e,{replace:t=!1}={})=>{const a={...l,...e},s=new URLSearchParams;a.org_id&&s.set("org_id",a.org_id),a.user_email&&s.set("user_email",a.user_email),a.filename&&s.set("filename",a.filename),50!==a.limit&&s.set("limit",String(a.limit)),0!==a.offset&&s.set("offset",String(a.offset)),r({pathname:n.pathname,search:s.toString()},{replace:t})},[l,n.pathname,r]);e.useEffect(()=>{J({org_id:l.org_id,user_email:l.user_email,filename:l.filename})},[l.filename,l.org_id,l.user_email]),e.useEffect(()=>{"list"===c&&Q()},[c,o]);const Q=async()=>{const e=$.current+1;$.current=e,j(!0),k(null);try{const t=function(e){const t=new URLSearchParams({limit:String(e.limit),offset:String(e.offset)});for(const a of["org_id","user_email","filename"]){const n=e[a].trim();n&&t.set(a,n)}return t}(l),n=await a(`/api/admin/documents/list?${t}`);if(e!==$.current)return;if(!n.ok)throw new Error(n.error?.message||"Failed to fetch documents");{const e=n.data.documents||[],t=n.data.pagination||{total:e.length,limit:l.limit,offset:l.offset};if(0===e.length&&t.total>0&&l.offset>0){const e=Math.floor((t.total-1)/l.limit)*l.limit;return void Y({offset:e},{replace:!0})}h(e),L(t),D(!0===n.data.publicationCapability?.available)}}catch(t){if(e!==$.current)return;k(t.message)}finally{e===$.current&&j(!1)}},X=()=>{const e={org_id:"",user_email:"",filename:""};J(e),Y({...e,offset:0})},Z=e.useCallback(e=>{W.current=e,q.current&&f(e)},[]),ee=e.useCallback(e=>{const t=W.current;return B.current===e&&t.loadedDocumentId===e&&["success","empty"].includes(t.status)},[]),te=e.useCallback(async e=>{if(!e||B.current!==e)return;H.current?.abort();const t=new AbortController,n=V.current+1;V.current=n,H.current=t,Z({status:"loading",loadedDocumentId:null,entries:[],error:null});const s=()=>q.current&&!t.signal.aborted&&V.current===n&&B.current===e;try{const n=await a(`/api/admin/documents/acl?document_id=${encodeURIComponent(e)}`,{signal:t.signal});if(!s())return;if(!n.ok)throw new Error(n.error?.message||"Failed to load document access");const r=Array.isArray(n.data?.acl_entries)?n.data.acl_entries:[];Z({status:r.length>0?"success":"empty",loadedDocumentId:e,entries:r,error:null})}catch(r){if(!s()||(e=>"AbortError"===e?.name)(r))return;Z({status:"error",loadedDocumentId:null,entries:[],error:r.message||"Failed to load document access"})}finally{H.current===t&&(H.current=null)}},[a,Z]),ae=e.useCallback(()=>{B.current=null,V.current+=1,H.current?.abort(),H.current=null,Z(Av),p(null),N(!1),C(null),E(""),_("viewer")},[Z]);e.useEffect(()=>(q.current=!0,()=>{q.current=!1,B.current=null,V.current+=1,H.current?.abort(),H.current=null}),[]);const ne=e=>{if(["confirming","pending"].includes(K.current?.status))return null;const t={...e,token:Symbol("acl-mutation"),status:e.status||"pending",error:null};return K.current=t,x(t),t},se=(e,t)=>{if(K.current?.token!==e.token||!q.current)return;const a={...e,...t};K.current=a,x(a)},re=e=>{K.current?.token===e.token&&(K.current=null,q.current&&x(null))},ie=e=>{e?.id&&(B.current=e.id,V.current+=1,H.current?.abort(),H.current=null,Z({status:"loading",loadedDocumentId:null,entries:[],error:null}),p(e),N(!1),C(null),d("acl"),te(e.id))},le=()=>{ae(),d("list")},oe=()=>{"add"===K.current?.type&&"pending"===K.current.status||(N(!1),C(null))},ce=async(e,t)=>{if(T)return;if(await U({title:`${t[0].toUpperCase()}${t.slice(1)} public metadata`,message:`${t[0].toUpperCase()}${t.slice(1)} metadata for this document? PDF access remains protected.`,confirmLabel:`${t[0].toUpperCase()}${t.slice(1)}`,confirmVariant:"publish"===t?"primary":"danger"})){A(e.id);try{const n=await a("/api/admin/documents/publication",{method:"PATCH",body:JSON.stringify({documentId:e.id,action:t})});if(!n.ok)throw new Error(n.error?.message||"Failed to update publication state");M({type:"success",message:`Metadata is now ${n.data.status}.`}),await Q()}catch(n){M({type:"error",message:n.message||"Failed to update publication state"})}finally{A(null)}}},de=e=>{if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]},ue=e=>e?new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}):"N/A",he=["confirming","pending"].includes(b?.status),me=Boolean(m&&g.loadedDocumentId===m.id&&["success","empty"].includes(g.status)),pe=!me||he,ge=b?.documentId===m?.id?b:null;return t.jsx(ri,{contextLabel:"Admin Panel",sectionLabel:"Documents",children:t.jsxs(Uu,{className:"admin-dashboard document-manager-shell",children:[t.jsx(Wg,{activeTab:"documents",onChange:F,onExit:z}),t.jsx(Fu,{title:"Documents",description:"Browse the complete catalog and manage access or public metadata state.",badge:t.jsx(li,{variant:"info",children:"Admin Access"})}),t.jsxs("div",{className:"document-manager",children:[t.jsxs("div",{className:"manager-header",children:[t.jsx("h2",{children:"Document Manager"}),t.jsxs("div",{className:"view-toggles",children:[t.jsx(ds,{variant:"list"===c?"primary":"secondary",onClick:le,children:"Document List"}),t.jsx(ds,{variant:"secondary",disabled:!0,"aria-describedby":"bulk-upload-unavailable-message",ariaLabel:"Bulk Upload unavailable",children:"Bulk Upload"})]})]}),t.jsxs("p",{id:"bulk-upload-unavailable-message",className:"bulk-upload-unavailable",children:[t.jsx("strong",{children:"Bulk upload is temporarily unavailable."})," This page cannot yet safely assign uploaded PDFs to another organization or owner. No files can be submitted here."]}),"list"===c&&t.jsxs(Js,{children:[t.jsx("form",{onSubmit:e=>{e.preventDefault(),Y({org_id:G.org_id.trim(),user_email:G.user_email.trim(),filename:G.filename.trim(),offset:0})}
2,children:t.jsxs(zu,{ariaLabel:"Document search filters",children:[t.jsx(Wu,{label:"Organization ID",htmlFor:"document-filter-organization",children:t.jsx("input",{id:"document-filter-organization",type:"text",value:G.org_id,onChange:e=>J({...G,org_id:e.target.value})})}),t.jsx(Wu,{label:"Owner email",htmlFor:"document-filter-owner",children:t.jsx("input",{id:"document-filter-owner",type:"email",value:G.user_email,onChange:e=>J({...G,user_email:e.target.value})})}),t.jsx(Wu,{label:"Filename",htmlFor:"document-filter-filename",children:t.jsx("input",{id:"document-filter-filename",type:"search",value:G.filename,onChange:e=>J({...G,filename:e.target.value})})}),t.jsx(ds,{type:"submit",children:"Search"}),l.org_id||l.user_email||l.filename?t.jsx(ds,{type:"button",variant:"ghost",onClick:X,children:"Clear filters"}):null]})}),v?t.jsx($g,{message:"Loading documents..."}):y?t.jsx(Ku,{title:"Documents could not be loaded",tone:"error",action:t.jsx(ds,{onClick:Q,children:"Retry"}),children:y}):0===u.length?t.jsx(Ku,{title:l.org_id||l.user_email||l.filename?"No documents match these filters":"No documents found",action:l.org_id||l.user_email||l.filename?t.jsx(ds,{variant:"secondary",onClick:X,children:"Clear filters"}):null,children:l.org_id||l.user_email||l.filename?"Broaden the search to see more of the catalog.":"Documents will appear after they are added to the library."}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"documents-desktop-table",children:t.jsxs(Bu,{className:"documents-table",minWidth:"720px",ariaLabel:"Admin document catalog",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Filename"}),t.jsx("th",{children:"Owner"}),t.jsx("th",{children:"Organization"}),t.jsx("th",{children:"Size"}),t.jsx("th",{children:"Created"}),O?t.jsx("th",{children:"Publication"}):null,t.jsx("th",{className:"admin-ui-table__actions",children:"Actions"})]})}),t.jsx("tbody",{children:u.map(e=>t.jsxs("tr",{children:[t.jsx("td",{children:e.filename}),t.jsx("td",{children:e.owner_email||"N/A"}),t.jsx("td",{children:e.org_name||e.org_id}),t.jsx("td",{children:de(e.size_bytes)}),t.jsx("td",{children:ue(e.created_at)}),O?t.jsxs("td",{children:[t.jsx(li,{variant:"published"===e.publication_status?"success":"default",children:e.publication_status||"unpublished"}),e.publication_updated_at?t.jsxs("small",{children:["Updated ",ue(e.publication_updated_at),e.publication_updated_by_email?` by ${e.publication_updated_by_email}`:""]}):null]}):null,t.jsx("td",{className:"admin-ui-table__actions",children:t.jsxs(qu,{children:[t.jsx(ds,{size:"small",variant:"secondary",onClick:()=>ie(e),children:"Manage ACL"}),O&&("published"!==e.publication_status?t.jsx(ds,{size:"small",onClick:()=>ce(e,"publish"),disabled:T===e.id,children:"Record publication"}):t.jsx(ds,{size:"small",variant:"danger",onClick:()=>ce(e,"withdraw"),disabled:T===e.id,children:"Withdraw"}))]})})]},e.id))})]})}),t.jsx("div",{className:"documents-mobile-list","aria-label":"Admin document catalog",children:u.map(e=>t.jsxs("article",{className:"document-mobile-card",children:[t.jsxs("div",{children:[t.jsx("h3",{children:e.filename}),t.jsx("p",{children:e.owner_email||"No owner email"})]}),t.jsxs("dl",{children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Organization"}),t.jsx("dd",{children:e.org_name||e.org_id||"N/A"})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Size"}),t.jsx("dd",{children:de(e.size_bytes)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Created"}),t.jsx("dd",{children:ue(e.created_at)})]}),O?t.jsxs("div",{children:[t.jsx("dt",{children:"Publication"}),t.jsx("dd",{children:t.jsx(li,{variant:"published"===e.publication_status?"success":"default",children:e.publication_status||"unpublished"})})]}):null]}),t.jsxs(qu,{className:"document-mobile-card__actions",align:"stack",children:[t.jsx(ds,{size:"small",variant:"secondary",onClick:()=>ie(e),children:"Manage ACL"}),O&&"published"!==e.publication_status?t.jsx(ds,{size:"small",onClick:()=>ce(e,"publish"),disabled:T===e.id,children:"Record publication"}):null,O&&"published"===e.publication_status?t.jsx(ds,{size:"small",variant:"danger",onClick:()=>ce(e,"withdraw"),disabled:T===e.id,children:"Withdraw"}):null]})]},e.id))}),t.jsx(Gu,{total:P.total,limit:P.limit,offset:P.offset,onOffsetChange:e=>Y({offset:e}),onLimitChange:e=>Y({limit:e,offset:0}),pageSizes:Tv,label:"Documents",disabled:v})]})]}),t.jsxs(Ju,{isOpen:w,onClose:oe,title:"Grant document access",children:[t.jsxs(Yu,{children:[t.jsxs("p",{className:"acl-modal-target",children:["Access will be granted only for"," ",t.jsx("strong",{children:m?.filename||"the selected document"}),"."]}),t.jsx(Wu,{label:"User ID",htmlFor:"acl-user-id",children:t.jsx("input",{id:"acl-user-id",type:"text",value:R,onChange:e=>E(e.target.value),placeholder:"User UUID"})}),t.jsx(Wu,{label:"Access level",htmlFor:"acl-access-level",children:t.jsxs("select",{id:"acl-access-level",value:I,onChange:e=>_(e.target.value),children:[t.jsx("option",{value:"viewer",children:"viewer"}),t.jsx("option",{value:"editor",children:"editor"}),t.jsx("option",{value:"owner",children:"owner"})]})}),"add"===ge?.type&&"error"===ge.status?t.jsxs("div",{className:"acl-inline-state acl-inline-state--error",role:"alert",children:[t.jsx("strong",{children:"Access was not granted."}),t.jsxs("span",{children:[ge.error," Review the details and try again."]})]}):null,"add"===ge?.type&&"pending"===ge.status?t.jsxs("p",{className:"acl-mutation-status",role:"status","aria-live":"polite",children:["Granting access for ",m?.filename||"the selected document","â¦"]}):null]}),t.jsxs(Qu,{children:[t.jsx(ds,{variant:"secondary",onClick:oe,disabled:he,children:"Cancel"}),t.jsx(ds,{onClick:async()=>{const e=S,t=m?.filename||"the selected document";if(!e||!ee(e)||"pending"===K.current?.status)return void M({type:"error",message:"Document access changed before this request was submitted. Reload and try again."});
2if(!R.trim()||!I)return void M({type:"warning",message:"User ID and access level are required"});const n=ne({type:"add",documentId:e,documentLabel:t});if(n)try{const s=await a("/api/admin/documents/acl",{method:"POST",body:JSON.stringify({document_id:e,user_id:R.trim(),access_level:I})});if(!s.ok)throw new Error(s.error?.message||"Failed to add ACL entry");if(!q.current)return;M({type:"success",message:`Access was granted for ${t}.`}),B.current===e&&(N(!1),C(null)),re(n),B.current===e&&await te(e)}catch(s){if(!q.current)return;const e=s.message||"Failed to add ACL entry";se(n,{status:"error",error:e}),M({type:"error",message:`Access was not granted for ${t}. ${e}`})}},disabled:pe||!R.trim(),children:"add"===ge?.type&&"pending"===ge.status?"Granting accessâ¦":"Grant access"})]})]}),"acl"===c&&m&&t.jsx(Js,{children:t.jsxs("section",{className:"acl-management","aria-labelledby":"acl-management-heading","aria-busy":"loading"===g.status||he,children:[t.jsxs("div",{className:"acl-header",children:[t.jsxs("h3",{id:"acl-management-heading",children:[t.jsx("span",{children:"Access Control"}),t.jsx("span",{className:"acl-document-title",children:m.filename})]}),t.jsx(ds,{onClick:le,children:"Back to Document List"})]}),t.jsx(ds,{variant:"primary",onClick:()=>{const e=B.current;ee(e)&&!["confirming","pending"].includes(K.current?.status)&&(E(""),_("viewer"),C(e),N(!0))},disabled:pe,"aria-describedby":me?void 0:"acl-action-availability",children:"Add User Access"}),me?null:t.jsx("p",{id:"acl-action-availability",className:"acl-action-availability",children:"Access changes stay disabled until this document's access list loads successfully."}),"remove"===ge?.type&&"pending"===ge.status?t.jsxs("p",{className:"acl-mutation-status",role:"status","aria-live":"polite",children:["Removing access from ",m.filename,"â¦"]}):null,"error"===ge?.status?t.jsxs("div",{className:"acl-inline-state acl-inline-state--error",role:"alert",children:[t.jsx("strong",{children:"The access change failed."}),t.jsxs("span",{children:[ge.error," The current document remains selected."]})]}):null,"loading"===g.status?t.jsxs("div",{className:"acl-inline-state",role:"status","aria-live":"polite",children:[t.jsx("div",{className:"spinner","aria-hidden":"true"}),t.jsxs("span",{children:["Loading access for ",m.filename,"â¦"]})]}):null,"error"===g.status?t.jsxs("div",{className:"acl-inline-state acl-inline-state--error",role:"alert",children:[t.jsxs("strong",{children:["Access could not be loaded for ",m.filename,"."]}),t.jsx("span",{children:g.error}),t.jsx(ds,{variant:"secondary",onClick:()=>{te(m.id)},children:"Retry access load"})]}):null,"empty"===g.status&&g.loadedDocumentId===m.id?t.jsxs("div",{className:"acl-inline-state",role:"status",children:["No access entries are currently assigned to ",m.filename,"."]}):null,"success"===g.status&&g.loadedDocumentId===m.id?t.jsxs(Bu,{className:"acl-table",minWidth:"520px",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"User"}),t.jsx("th",{children:"Access Level"}),t.jsx("th",{children:"Granted"}),t.jsx("th",{children:"Actions"})]})}),t.jsx("tbody",{children:g.entries.map(e=>t.jsxs("tr",{children:[t.jsx("td",{children:e.user_email||"N/A"}),t.jsx("td",{children:t.jsx(li,{children:e.access_level})}),t.jsx("td",{children:ue(e.created_at)}),t.jsx("td",{children:t.jsx(qu,{children:t.jsx(ds,{size:"small",variant:"danger",onClick:()=>(async e=>{const t=B.current,n=m?.filename||"the selected document",s=W.current.entries.some(t=>t.id===e?.id);if(!ee(t)||!s)return void M({type:"error",message:"This access entry is no longer current. Reload the document access list."});const r=ne({type:"remove",status:"confirming",documentId:t,documentLabel:n,entryId:e.id});if(!r)return;if(!(await U({title:"Remove access",message:`Remove ${e.user_email||"this user"} from ${n}?`,confirmLabel:"Remove",confirmVariant:"danger"})))return void re(r);const i=W.current.entries.some(t=>t.id===e.id);if(!ee(t)||!i)return re(r),void M({type:"error",message:"Document access changed before removal. Reload and try again."});se(r,{status:"pending"});try{const s=await a("/api/admin/documents/acl",{method:"DELETE",body:JSON.stringify({acl_id:e.id,document_id:t})});if(!s.ok)throw new Error(s.error?.message||"Failed to remove ACL entry");if(!q.current)return;M({type:"success",message:`Access was removed from ${n}.`}),re(r),B.current===t&&await te(t)}catch(l){if(!q.current)return;const e=l.message||"Failed to remove ACL entry";se(r,{status:"error",error:e}),M({type:"error",message:`Access was not removed from ${n}. ${e}`})}})(e),disabled:pe,ariaLabel:`Remove access for ${e.user_email||"this user"} from ${m.filename}`,children:"Remove"})})})]},e.id))})]}):null]})})]})]})})}},Symbol.toStringTag,{value:"Module"}));const Dv={status:"idle",detail:null,error:null,summary:null,integrityConflict:null},Pv=Object.freeze({unsettled:5e3,active:15e3,stable:6e4,maxFailure:12e4});function Lv(e){return e?[e.documentId||"",e.pageNumber??"",e.sourceBinaryIdentity||"",e.sourceRevision??"",e.ocrChecksum||"",e.ocrStatus||"",e.sourceKind||"",!0===e.authoritative?"authoritative":"",!0===e.synchronizedToWikibase?"claims-synced":"",e.operationalClaimSyncStatus||"",e.searchIndexStatus||"",e.searchIndexedRevision??"",!0===e.requiresReconciliation?"re
2conciliation":"",e.syncRequest?.state||"",e.syncRequest?.classification||"",!0===e.syncRequest?.reviewRequired?"review-required":""].join("|"):null}function $v(e,t){return e?.hasOcr||e?.editable?{status:"ready",detail:e,error:null,summary:t,integrityConflict:null}:{status:"unavailable",detail:e,error:null,summary:t,integrityConflict:null}}function Mv(e){return"PAGE_OCR_CACHE_EVIDENCE_CONFLICT"===e?.code}function Uv(e,t,a=e.summary){return e.detail?{...$v(e.detail,a),integrityConflict:t}:{status:"error",detail:null,error:t,summary:a,integrityConflict:t}}function Fv(e,t,a=e.summary){return n=e.detail,!((s=t)&&"pageocr_projection"===s.sourceKind&&!0===s.authoritative&&!0!==s.requiresReconciliation&&s.sourceBinaryIdentity&&Number.isInteger(s.sourceRevision))||s.sourceRevision<=0||!s.ocrChecksum||n&&(n.documentId&&s.documentId&&n.documentId!==s.documentId||Number.isInteger(n.pageNumber)&&Number.isInteger(s.pageNumber)&&n.pageNumber!==s.pageNumber||!(n.sourceBinaryIdentity!==s.sourceBinaryIdentity||!Number.isInteger(n.sourceRevision)||n.sourceRevision<=0||s.sourceRevision>n.sourceRevision||s.sourceRevision===n.sourceRevision&&s.ocrChecksum===n.ocrChecksum))?e:$v(t,a);var n,s}async function zv({documentId:e,pageNumber:t,previewRepository:a,previewSummary:n,controller:s,requestIdRef:r,requestId:i,summary:l,setState:o}){if(!a)return void o({status:"unavailable",detail:null,error:null,summary:l});if(n?.pageCount&&t>n.pageCount)return void o({status:"unavailable",detail:null,error:null,summary:n});const c=a.peekCachedPageDetail?.(e,t);if(c)o($v(c,l));else{o({status:"loading",detail:null,error:null,summary:l});try{const n=await a.getPageDetail(e,t,{signal:s?.signal});if(r.current!==i)return;o($v(n,l))}catch(d){if(r.current!==i)return;if("AbortError"===d?.name)return;if("PAGE_NOT_FOUND"===d?.code)return void o({status:"unavailable",detail:null,error:null,summary:l});o({status:"error",detail:null,error:d,summary:l})}}}function qv({documentId:t,pageNumber:a,repository:n,getSummary:s,previewRepository:r,previewSummary:i,prefetchEnabled:l=!0,pollingEnabled:o=!0}){const[c,d]=e.useState(Dv),u=e.useRef(Dv),h=e.useRef(0),m=e.useRef(null),p=e.useRef(null),g=e.useRef({documentId:t,pageNumber:a});g.current={documentId:t,pageNumber:a};const[f,b]=e.useState(0);e.useEffect(()=>{u.current=c},[c]),e.useEffect(()=>{if(!t||!a||!n)return void d(Dv);const e=s?s(a):null,l=++h.current,o="undefined"!=typeof AbortController?new AbortController:null;m.current={requestId:l,controller:o};const c=()=>{m.current?.requestId===l&&(m.current=null)};if(e&&!1===e.hasOcr&&!e.editable)return zv({documentId:t,pageNumber:a,previewRepository:r,previewSummary:i,controller:o,requestIdRef:h,requestId:l,summary:e,setState:d}).finally(c),()=>{c(),o?.abort()};const p=f>0,g=p?null:n.peekCachedPageDetail?.(t,a);return d(g?$v(g,e):n=>{const s=!p||n.detail?.pageNumber!==a||n.detail?.documentId&&n.detail.documentId!==t?null:n.detail;return s&&n.integrityConflict?Uv(n,n.integrityConflict,e):{status:"loading",detail:s,error:null,summary:e}}),n.getPageDetail(t,a,{signal:o?.signal,bypassCache:p}).then(n=>{if(h.current===l)if(n?.hasOcr||n?.editable)d(t=>t.integrityConflict?Fv(t,n,e):$v(n,e));else{if(!u.current.integrityConflict||!u.current.detail)return zv({documentId:t,pageNumber:a,previewRepository:r,previewSummary:i,controller:o,requestIdRef:h,requestId:l,summary:e,setState:d});d(t=>Uv(t,t.integrityConflict,e))}}).catch(n=>{if(h.current===l&&"AbortError"!==n?.name){if(!Mv(n))return"PAGE_NOT_FOUND"===n?.code?u.current.integrityConflict&&u.current.detail?void d(t=>Uv(t,t.integrityConflict,e)):zv({documentId:t,pageNumber:a,previewRepository:r,previewSummary:i,controller:o,requestIdRef:h,requestId:l,summary:e,setState:d}):void d(s=>{const r=!p||s.detail?.pageNumber!==a||s.detail?.documentId&&s.detail.documentId!==t?null:s.detail;return r&&s.integrityConflict?Uv(s,s.integrityConflict,e):{status:"error",detail:r,error:n,summary:e,integrityConflict:null}});d(t=>Uv(t,n,e))}}).finally(c),()=>{c(),o?.abort()}},[t,a,n,s,r,i,f]),e.useEffect(()=>{if(l&&t&&a&&n&&(n.prefetchPageDetail?.(t,a-1),n.prefetchPageDetail?.(t,a+1),i)){const e=e=>{e<1||i.pageCount&&e>i.pageCount||r?.prefetchPageDetail?.(t,e,{pageCount:i.pageCount})};e(a-1),e(a+1)}},[t,a,n,r,i,l]),e.useEffect(()=>{if(!(o&&t&&a&&n))return;let e=!1,s=null,r=0,i=0;const l=()=>
2"undefined"==typeof document||"hidden"!==document.visibilityState,c=()=>{null!==s&&window.clearTimeout(s),s=null},g=()=>{c(),!e&&l()&&(s=window.setTimeout(f,(()=>{if(i>0)return Math.min(Pv.active*2**i,Pv.maxFailure);const e=u.current.detail;return!(t=e)||!0!==t.syncRequest?.reviewRequired&&("pageocr_projection"!==t.sourceKind||!0!==t.authoritative||!0!==t.synchronizedToWikibase||["pending","queued","processing","updating"].includes(t.searchIndexStatus))?Pv.unsettled:r>=2?Pv.stable:Pv.active;var t})()))},f=async()=>{if(c(),e||!l())return;if(m.current)return void g();p.current?.abort();const s="undefined"!=typeof AbortController?new AbortController:null;p.current=s;const o=++h.current,f=Lv(u.current.detail);try{const l=await n.getPageDetail(t,a,{signal:s?.signal,bypassCache:!0});if(e||h.current!==o)return;i=0;const c=Lv(l);r=f&&f===c?r+1:0,d(e=>Lv(e.detail)!==c||e.integrityConflict?e.integrityConflict?Fv(e,l):$v(l,e.summary):e)}catch(b){if(e||h.current!==o)return;Mv(b)?(i=0,r=0,d(e=>Uv(e,b))):"AbortError"!==b?.name&&(i+=1)}finally{p.current===s&&(p.current=null),e||g()}},b=()=>{if(!l())return c(),void p.current?.abort();f()};return document.addEventListener("visibilitychange",b),g(),()=>{e=!0,c(),document.removeEventListener("visibilitychange",b),p.current?.abort(),p.current=null}},[t,a,o,n]);const x=e.useCallback(()=>{m.current?.controller?.abort(),m.current=null,p.current?.abort(),h.current+=1,b(e=>e+1)},[]),v=e.useCallback(async()=>{if(!t||!a||!n)return!1;p.current?.abort();const e="undefined"!=typeof AbortController?new AbortController:null;p.current=e;const s=++h.current;try{const r=await n.getPageDetail(t,a,{signal:e?.signal,bypassCache:!0});return h.current===s&&g.current.documentId===t&&g.current.pageNumber===a&&(d(e=>Fv(e,r)),!0)}catch(r){return h.current!==s||"AbortError"===r?.name||Mv(r)&&d(e=>Uv(e,r)),!1}finally{p.current===e&&(p.current=null)}},[t,a,n]),j=e.useCallback((e,t=null)=>(!t||g.current.documentId===t.documentId&&g.current.pageNumber===t.pageNumber)&&(m.current?.controller?.abort(),m.current=null,p.current?.abort(),h.current+=1,d(t=>$v(e,t.summary)),!0),[]);return{...c,reload:x,refresh:v,acceptDetail:j}}function Bv(e){if(null==e||""===e)return null;const t=Number(e);return!Number.isInteger(t)||t<1?null:t}function Wv(e,t){const a=Number.isInteger(e)&&e>0?e:1;return!Number.isInteger(t)||t<1?a:Math.min(Math.max(a,1),t)}function Vv(t){const[a,n]=e.useState(()=>function(e){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia(e).matches}(t));return e.useEffect(()=>{if("undefined"==typeof window||"function"!=typeof window.matchMedia)return;const e=window.matchMedia(t),a=e=>n(e.matches);return n(e.matches),"function"==typeof e.addEventListener?(e.addEventListener("change",a),()=>e.removeEventListener("change",a)):(e.addListener?.(a),()=>e.removeListener?.(a))},[t]),a}function Hv({metadata:e}){if(!e)return null;const{title:a,authors:n,publicationDate:s,language:r,qid:i}=e,l=n?.length>0||s||r;return t.jsxs("header",{className:"research-viewer-header",children:[t.jsx("h2",{className:"research-viewer-header-title",children:a}),l?t.jsxs("div",{className:"research-viewer-header-byline",children:[n?.length>0?t.jsx("span",{children:n.join(", ")}):null,s?t.jsx("span",{children:s}):null,r?t.jsx("span",{children:r.toUpperCase()}):null]}):null,i?t.jsx("span",{className:"research-viewer-header-qid",children:i}):null]})}function Kv({paneMode:e,onSetPaneMode:a,paneModeDisabled:n=!1,hasDirtyDraft:s=!1,annotationsAvailable:r=!1,annotationsOpen:i=!1,onToggleAnnotations:l,qaAvailable:o=!1,qaOpen:c=!1,onToggleQa:d,ariaLabel:u="Research viewer layout"}){return t.jsxs("div",{className:"research-viewer-toolbar",role:"toolbar","aria-label":u,children:[t.jsxs(ds,{variant:"pdf-only"===e?"primary":"ghost",size:"small",onClick:()=>a("pdf-only"),disabled:n,title:n?"Layout is locked while page text is saving":void 0,ariaLabel:"Show PDF only","aria-pressed":"pdf-only"===e,children:[t.jsx(wt,{size:15}),t.jsx("span",{className:"research-viewer-toolbar-label",children:"PDF only"})]}),t.jsxs(ds,{variant:"split"===e?"primary":"ghost",size:"small",onClick:()=>a("split"),disabled:n,title:n?"Layout is locked while page text is saving":void 0,ariaLabel:"Show split view","aria-pressed":"split"===e,children:[t.jsx(Nt,{size:15}),t.jsx("span",{className:"research-viewer-toolbar-label",children:"Split"})]}),t.jsxs(ds,{variant:"ocr-only"===e?"primary":"ghost",size:"small",onClick:()=>a("ocr-only"),disabled:n,title:n?"Layout is locked while page text is saving":void 0,ariaLabel:"Show text only","aria-pressed":"ocr-only"===e,children:[t.jsx(W,{size:15}),t.jsx("span",{className:"research-viewer-toolbar-label",children:"Text only"})]}),s&&"pdf-only"===e?t.jsxs(ds,{variant:"ghost",size:"small",className:"research-viewer-toolbar-dirty",onClick:()=>a("split"),ariaLabel:"Unsaved page text changes. Show text editor",children:[t.jsx(fe,{size:15}),t.jsx("span",{className:"research-viewer-toolbar-label",children:"Unsaved"})]}):null,r?t.jsxs(ds,{variant:i?"primary":"ghost",size:"small",onClick:l,ariaLabel:i?"Hide entities and annotations":"Show entities and annotations","aria-pressed":i,children:[t.jsx(St,{size:15}),t.jsx("span",{className:"research-viewer-toolbar-label",children:"Entities"})]}):null,o?t.jsxs(ds,{variant:c?"primary":"ghost",size:"small",onClick:d,ariaLabel:c?"Hide PDF text preview QA":"Review all page text","aria-pressed":c,children:[t.jsx(Ct,{size:15}),t.jsx("span",{className:"research-viewer-toolbar-label",children:"Text QA"})]}):null]})}const Gv=[{id:"pdf",label:"PDF"},{id:"ocr",label:"Text"},{id:"info",label:"Info"}];function Jv({activeTab:a,onChangeTab:n,includeInfo:s=!0,hasDirtyDraft:r=!1,hasNewerVersion:i=!1,hasIntegrityConflict:l=!1}){const o=e.useRef([]),c=e.useId(),d=s?Gv:Gv.filter(e=>"info"!==e.id),u=r||i||l,h=l?"Needs review":r?"Unsaved":"New version",m=[r?"
2Unsaved page text changes.":null,l?"Conflicting page text evidence needs review.":null,i?"A newer page text version is available.":null].filter(Boolean).join(" ");return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"research-viewer-mobile-tabs",role:"tablist","aria-label":"Viewer pane",children:d.map((e,s)=>t.jsxs("button",{id:`research-viewer-${e.id}-tab`,type:"button",role:"tab","aria-selected":a===e.id,"aria-controls":`research-viewer-${e.id}-panel`,"aria-describedby":"ocr"===e.id&&u?c:void 0,tabIndex:a===e.id?0:-1,ref:e=>{o.current[s]=e},className:"research-viewer-mobile-tab "+(a===e.id?"is-active":""),onClick:()=>n(e.id),onKeyDown:e=>((e,t)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;e.preventDefault();const a="Home"===e.key?0:"End"===e.key?d.length-1:(t+("ArrowRight"===e.key?1:-1)+d.length)%d.length;n(d[a].id),o.current[a]?.focus()})(e,s),children:[t.jsx("span",{children:e.label}),"ocr"===e.id&&u?t.jsx("span",{className:"research-viewer-mobile-tab-dirty","aria-hidden":"true",children:h}):null]},e.id))}),t.jsx("span",{id:c,className:"sr-only",children:m})]})}const Yv=Object.freeze({FIT_WIDTH:"fit-width",FIT_PAGE:"fit-page",ACTUAL_SIZE:"actual-size",CUSTOM:"custom"}),Qv=Object.freeze({min:.5,max:3,buttonStep:.25,wheelMultiplier:1.1,maxFitWidth:1400});function Xv(e){const t=Number(e);return Number.isFinite(t)?Math.min(Qv.max,Math.max(Qv.min,t)):1}function Zv({pageWidth:t,pageHeight:a,containerWidth:n,containerHeight:s,resetKey:r,defaultMode:i=Yv.FIT_WIDTH}={}){const[l,o]=e.useState(i),[c,d]=e.useState(1);e.useEffect(()=>{o(i),d(1)},[i,r]);const u=e.useMemo(()=>function({mode:e,customScale:t=1,pageWidth:a,pageHeight:n,containerWidth:s,containerHeight:r}){const i=Number(a)||0,l=Number(n)||0,o=Number(s)||0,c=Number(r)||0;return e===Yv.ACTUAL_SIZE?1:i&&l&&o?e===Yv.FIT_PAGE?Xv(c?Math.min(o/i,c/l):Math.min(Qv.maxFitWidth,o)/i):e===Yv.CUSTOM?Xv(t):Xv(Math.min(Qv.maxFitWidth,o)/i):e===Yv.CUSTOM?Xv(t):1}({mode:l,customScale:c,pageWidth:t,pageHeight:a,containerWidth:n,containerHeight:s}),[s,n,c,l,a,t]),h=e.useCallback(()=>o(Yv.FIT_WIDTH),[]),m=e.useCallback(()=>o(Yv.FIT_PAGE),[]),p=e.useCallback(()=>{d(1),o(Yv.ACTUAL_SIZE)},[]),g=e.useCallback(e=>{const t=Xv(e);return d(t),o(Yv.CUSTOM),t},[]),f=e.useCallback(e=>{const t=Xv(u+e);return d(t),o(Yv.CUSTOM),t},[u]),b=e.useCallback(()=>f(Qv.buttonStep),[f]),x=e.useCallback(()=>f(-Qv.buttonStep),[f]),v=e.useCallback(e=>{const t=e<0?Qv.wheelMultiplier:1/Qv.wheelMultiplier,a=Xv(u*t);return d(a),o(Yv.CUSTOM),a},[u]);return{mode:l,scale:u,scalePercent:Math.round(100*u),minScale:Qv.min,maxScale:Qv.max,canZoomIn:u<Qv.max-.001,canZoomOut:u>Qv.min+.001,setFitWidth:h,setFitPage:m,setActualSize:p,setCustomScale:g,zoomIn:b,zoomOut:x,zoomByWheel:v}}ya.workerSrc=new URL("/assets/pdf.worker.min-qwK7q_zL.mjs",import.meta.url).toString();const ej=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function tj(e){const t=Number(e);return Number.isFinite(t)?`${(100*t).toFixed(1)}%`:"unknown"}function aj(e,t,a){const n=Math.max(1,Number(t)||1),s=Math.max(1,Number(a)||1),r=Number(e.x)||0,i=Number(e.y)||0,l=Number(e.width)||0,o=Number(e.height)||0,c=Math.min(r,r+l),d=Math.min(i,i+o),u=Math.max(r,r+l,c+1),h=Math.max(i,i+o,d+1),m=Math.min(Math.max(0,c),n-1),p=Math.min(Math.max(0,d),s-1);return{left:m,top:p,width:Math.min(n,Math.max(m+1,u))-m,height:Math.min(s,Math.max(p+1,h))-p}}function nj(e,t,a){const n=t.map(t=>{const a=function(e,t){const a=t.left+t.width,n=t.top+t.height,s=Math.max(t.left-e.x,0,e.x-a),r=Math.max(t.top-e.y,0,e.y-n),i=t.left+t.width/2,l=t.top+t.height/2,o=e.x-i,c=e.y-l;return{contains:0===s&&0===r,distanceSquared:s*s+r*r,centerDistanceSquared:o*o+c*c,area:t.width*t.height,withinPointerRadius:e.x>=t.left-22&&e.x<=a+22&&e.y>=t.top-22&&e.y<=n+22}}(e,t.geometry);return{...t,...a}}).filter(e=>e.withinPointerRadius).sort((e,t)=>Number(t.contains)-Number(e.contains)||e.distanceSquared-t.distanceSquared||(e.contains?e.area-t.area:0)||e.centerDistanceSquared-t.centerDistanceSquared||e.area-t.area||e.index-t.index);if(!n.length)return null;const s=n[0],r=n.filter(e=>e.contains===s.contains&&e.distanceSquared===s.distanceSquared&&e.area===s.area&&e.centerDistanceSquared===s.centerDistanceSquared);return r.length<2?s.index:r.find(e=>e.index>a)?.index??r[0].index}function sj({documentUrl:a,documentData:n,requestHeaders:s,ocrOverlayUrl:r,ocrOverlayData:i,page:l,onPageChange:o,onDocumentInfo:c,onLoadError:d,showInternalErrors:u=!0,fitToViewport:h=!1,showPageControls:m=!0,ocrOverlayIsOriginalSnapshot:p=!1,textSourceKind:g=null,className:f=""}){const[b,x]=e.useState(null),[v,j]=e.useState(()=>Number.isInteger(l)&&l>0?l:1),[y,k]=e.useState(()=>String(Number.isInteger(l)&&l>0?l:1)),[w,N]=e.useState(null),[S,C]=e.useState(null),[R,E]=e.useState(i||null),[I,_]=e.useState(()=>i?"ready":r?"loading":"absent"),[T,A]=e.useState(0),[O,D]=e.useState(!p),[P,L]=e.useState(!0),[$,M]=e.useState(null),[U,F]=e.useState(null),[z,q]=e.useState(null),[B,W]=e.useState(0),[V,H]=e.useState(null),[K,G]=e.useState(!1),[Y,Q]=e.useState(null),[X,ee]=e.useState(null),[te,ae]=e.useState(!1),[ne,se]=e.useState(null),[re,ie]=e.useState(null),[le,oe]=e.useState(""),ce=e.useRef(null),de=e.useRef(null),ue=e.useRef(null),he=e.useRef(!1),me=e.useRef(null),pe=e.useRef(1),ge=e.useRef(null),fe=e.useRef(null),be=e.useRef(null),xe=e.useRef(null),ve=e.useRef(null),je=e.useRef([]),ye=e.useId(),ke=e.useId(),we=e.useMemo(()=>n||(a?s&&0!==Object.keys(s).length?{url:a,httpHeaders:s,withCredentials:!0}:{url:a}:null),[n,a,s]),Ne=e.useCallback(()=>
2{if(!de.current)return;const e=de.current,t=window.getComputedStyle(e),a=Number.parseFloat(t.paddingLeft||"0")+Number.parseFloat(t.paddingRight||"0"),n=Number.parseFloat(t.paddingTop||"0")+Number.parseFloat(t.paddingBottom||"0"),s=Math.max(0,Math.floor(e.clientWidth-a)),r=Math.max(0,Math.floor(e.clientHeight-n));Q(e=>null!==e&&Math.abs((e||0)-s)<8?e:s),ee(e=>null!==e&&Math.abs((e||0)-r)<8?e:r)},[]),Se=e.useCallback(()=>{if(!de.current)return;const e=de.current.querySelector(".react-pdf__Page__canvas");if(!e)return;const t=Math.max(0,Math.floor(e.getBoundingClientRect().width)),a=Math.max(0,Math.floor(e.getBoundingClientRect().height));se(e=>Math.abs((e||0)-t)<=1?e:t),ie(e=>Math.abs((e||0)-a)<=1?e:a)},[]);e.useEffect(()=>{const e=()=>{me.current&&cancelAnimationFrame(me.current),me.current=requestAnimationFrame(()=>{me.current=null,Ne()})};e();const t=new ResizeObserver(e);return de.current&&t.observe(de.current),()=>{t.disconnect(),me.current&&(cancelAnimationFrame(me.current),me.current=null)}},[Ne]),e.useEffect(()=>{Ne()},[K,h,Ne]);const Ce=Zv({pageWidth:w,pageHeight:S,containerWidth:Y,containerHeight:X,resetKey:`${a||"data"}:${n?"buffer":"url"}:${r||""}`,defaultMode:Yv.FIT_WIDTH});e.useEffect(()=>{pe.current=Ce.scale},[Ce.scale]);const Re=e.useMemo(()=>w&&S&&ne&&re?{x:ne/w,y:re/S}:{x:1,y:1},[w,S,ne,re]);e.useEffect(()=>{const e=Number.isInteger(l)&&l>0?l:1;x(null),j(e),k(String(e)),N(null),C(null),E(i||null),_(i?"ready":r?"loading":"absent"),D(!p),L(!0),M(null),F(null),q(null),W(0),H(null),ae(!1),se(null),ie(null),oe("")},[n,a,i,p,r]),e.useEffect(()=>{if(te&&r&&!i){const e=new AbortController;let t=!0;return _(e=>"retrying"===e?e:"loading"),fetch(r,{headers:s||void 0,credentials:"include",cache:"no-store",signal:e.signal}).then(e=>{if(!e.ok)throw new Error(`OCR overlay request failed with status ${e.status}`);return e.json()}).then(e=>{t&&(E(e),_("ready"))}).catch(e=>{t&&"AbortError"!==e?.name&&(E(null),_("error"))}),()=>{t=!1,e.abort()}}},[te,r,i,s,T]);const Ee=e.useRef(o),_e=e.useRef(null);e.useEffect(()=>{Ee.current=o},[o]),e.useEffect(()=>{_e.current!==v?Ee.current?.(v):_e.current=null},[v]),e.useEffect(()=>{if(null==l)return;const e=b?Math.min(Math.max(1,l),b):Math.max(1,l);j(t=>t===e?t:e),k(t=>Number(t)===e?t:String(e))},[l,b]);const Te=e=>{const t=Math.min(Math.max(1,e),b||1);if(null!=l){const e=Ee.current?.(t);if(!1===e){const e=b?Math.min(Math.max(1,l),b):Math.max(1,l);return j(e),k(String(e)),oe(""),!1}return t!==v&&(_e.current=t),oe(""),!0}return j(t),k(String(t)),oe(""),!0},Ae=e=>{const t=String(e).trim(),a=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isInteger(a)||a<1||a>(b||1))return oe(`Enter a page number between 1 and ${b||1}.`),void k(String(v));Te(a)},Oe=e.useCallback(()=>{ue.current?.focus(),requestAnimationFrame(()=>ue.current?.focus())},[]),De=e.useCallback(()=>{const e=ce.current;if(G(!1),Oe(),document.fullscreenElement===e&&"function"==typeof document.exitFullscreen)try{const t=document.exitFullscreen();t?.catch?.(()=>{document.fullscreenElement===e&&G(!0)})}catch{document.fullscreenElement===e&&G(!0)}},[Oe]);e.useEffect(()=>{const e=()=>{if(document.fullscreenElement===ce.current)return he.current=!0,void G(!0);he.current&&(he.current=!1,G(!1),Oe())};return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[Oe]),e.useEffect(()=>{if(!K)return;const e=ce.current;if(!e)return;const t=[];let a=e;for(;a.parentElement;){const e=a.parentElement;if(Array.from(e.children).forEach(e=>{e!==a&&(t.push({element:e,inert:e.inert,inertAttribute:e.getAttribute("inert"),ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}),e===document.body)break;a=e}const n=t=>{e.contains(t.target)||(ue.current||e).focus()},s=t=>{if("Escape"===t.key)return t.preventDefault(),t.stopPropagation(),void De();if("Tab"!==t.key)return;const a=Array.from(e.querySelectorAll(ej)).filter(e=>!e.hidden&&"true"!==e.getAttribute("aria-hidden")&&!e.closest("[inert]"));if(!a.length)return t.preventDefault(),void e.focus();const n=a[0],s=a[a.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),s.focus()):t.shiftKey||document.activeElement!==s?e.contains(document.activeElement)||(t.preventDefault(),(t.shiftKey?s:n).focus()):(t.preventDefault(),n.focus())};return document.addEventListener("focusin",n,!0),document.addEventListener("keydown",s,!0),()=>{document.removeEventListener("focusin",n,!0),document.removeEventListener("keydown",s,!0),t.forEach(({element:e,inert:t,inertAttribute:a,ariaHidden:n})=>{e.inert=t,null===a?e.removeAttribute("inert"):e.setAttribute("inert",a),null===n?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",n)})}}
2,[K,De]);const Pe=e.useCallback(e=>{if(!e.ctrlKey&&!e.metaKey)return;if(e.preventDefault(),ge.current)return;const t=de.current;if(!t)return;const a=t.getBoundingClientRect(),n=t.querySelector(".pdf-viewer-page-wrapper"),s=n?.getBoundingClientRect(),r=e.clientX-a.left,i=e.clientY-a.top,l=pe.current||1,o=s?s.left-a.left+t.scrollLeft:0,c=s?s.top-a.top+t.scrollTop:0,d=(t.scrollLeft+r-o)/l,u=(t.scrollTop+i-c)/l,h=Ce.zoomByWheel(e.deltaY);fe.current={localX:r,localY:i,contentX:d,contentY:u,nextScale:h}},[Ce]);e.useEffect(()=>{const e=de.current;if(e)return e.addEventListener("wheel",Pe,{passive:!1}),()=>{e.removeEventListener("wheel",Pe)}},[Pe]),e.useEffect(()=>()=>{ge.current&&(cancelAnimationFrame(ge.current),ge.current=null)},[]),e.useEffect(()=>{const e=fe.current,t=de.current;if(e&&t&&!(Math.abs(Ce.scale-e.nextScale)>.001))return ge.current=requestAnimationFrame(()=>{ge.current=null;const a=t.getBoundingClientRect(),n=t.querySelector(".pdf-viewer-page-wrapper"),s=n?.getBoundingClientRect(),r=s?s.left-a.left+t.scrollLeft:0,i=s?s.top-a.top+t.scrollTop:0;t.scrollLeft=Math.max(0,r+e.contentX*Ce.scale-e.localX),t.scrollTop=Math.max(0,i+e.contentY*Ce.scale-e.localY),fe.current=null}),()=>{ge.current&&(cancelAnimationFrame(ge.current),ge.current=null)}},[re,ne,Ce.scale]);const Le=(()=>{if(!R||!O)return[];if(R.pages){const e=R.pages.find(e=>e.pageNumber===v);return e?.boxes||[]}return R[v]?R[v].boxes||[]:Array.isArray(R)?R.filter(e=>e.pageNumber===v):[]})(),$e=Le.length?Math.min(B,Le.length-1):0,Ue=Number.isInteger(V)&&Le[V]||null,Fe=p?"Original OCR region":"Text region",ze=p?"original OCR region":"text region",qe=p?"Original OCR regions":"Text regions",Be=p?"original OCR regions":"text regions",We="tokenworks_correction"===g,Ve=We?"Original OCR snapshot for reference. The earlier TokenWorks correction requires reconciliation and may differ.":"embedded_pdf_text"===g||"pdf_text_preview"===g?"Original OCR snapshot for reference. The Text pane currently shows embedded PDF text.":"pageocr_projection"===g?"Original OCR snapshot for reference. The Text pane currently shows TokenWorks OCR text.":"empty_pdf_text"===g?"Original OCR snapshot for reference. The Text pane has no stored text yet.":"Original OCR snapshot for reference. Check the Text pane for the current page text.",He="loading"===I?`Loading ${Be}.`:"retrying"===I?`Retrying ${Be}.`:"error"===I?`${qe} are unavailable. The PDF remains available.`:"ready"!==I?"":O?Le.length?`${Le.length} ${1===Le.length?ze:Be} on this page.`:`No ${Be} on this page.`:`${qe} are hidden.`,Ke=ne&&re?Le.flatMap((e,t)=>{const a=(e=>{if(!w||!S)return null;const t=Re.x,a=Re.y;let n=e.x,s=e.y,r=e.width,i=e.height;return e.x<=1&&e.y<=1&&(n=e.x*w,s=e.y*S,r=e.width*w,i=e.height*S),{...e,x:n*t,y:s*a,width:r*t,height:i*a}})(e);return a?[{index:t,pixelBox:a,geometry:aj(a,ne,re)}]:[]}):[];e.useEffect(()=>{F(null),q(null),W(0),H(null)},[v]);const Ge=(e,{keepDetailsOpen:t=!1,moveFocus:a=!1}={})=>{if(!Le.length)return;const n=(e+Le.length)%Le.length;W(n),F(n),H(t?n:null),a&&je.current[n]?.focus()},Je=()=>{ve.current=null,xe.current&&(cancelAnimationFrame(xe.current),xe.current=null),q(null)};e.useEffect(()=>()=>{xe.current&&cancelAnimationFrame(xe.current)},[]);const Ye=()=>{const e=$e;H(null),F(null),requestAnimationFrame(()=>je.current[e]?.focus())};return a||n?t.jsxs("div",{ref:ce,className:`pdf-viewer ${f}${K?" pdf-viewer--fullscreen":""}`,onKeyDown:e=>{const t=e.target;"INPUT"===t?.tagName||"TEXTAREA"===t?.tagName||"SELECT"===t?.tagName||t?.isContentEditable||("+"===e.key||"="===e.key?(e.preventDefault(),Ce.zoomIn()):"-"===e.key?(e.preventDefault(),Ce.zoomOut()):"0"===e.key&&(e.preventDefault(),Ce.setFitWidth()))},tabIndex:K?-1:void 0,children:[t.jsxs("div",{className:"pdf-viewer-controls",role:"toolbar","aria-label":"PDF controls",children:[m||K?t.jsxs("div",{className:"pdf-viewer-toolbar-group pdf-viewer-pagination",role:"group","aria-label":"Page",children:[t.jsxs(ds,{variant:"secondary",size:"small",onClick:()=>{Te(v-1)},disabled:v<=1,ariaLabel:"Previous page",children:[t.jsx(Rt,{size:16}),t.jsx("span",{className:"pdf-viewer-wide-label",children:"Previous"})]}),t.jsxs("div",{className:"pdf-viewer-page-info",children:[t.jsx("span",{children:"Page"}),t.jsx("form",{onSubmit:e=>{e.preventDefault(),Ae(y)},className:"pdf-viewer-page-form",children:t.jsx("input",{type:"text",inputMode:"numeric",enterKeyHint:"go",autoComplete:"off",className:"pdf-viewer-page-input",value:y,onChange:e=>{k(e.target.value),oe("")},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),Ae(y))},onBlur:()=>{Ae(y)},"aria-label":"Go to page number","aria-invalid":le?"true":void 0,"aria-describedby":le?"pdf-page-validation":void 0})}),t.jsxs("span",{children:["of ",b||"?"]})]}),t.jsxs(ds,{variant:"secondary",size:"small",onClick:()=>{Te(v+1)},disabled:v>=(b||1),ariaLabel:"Next page",children:[t.jsx("span",{className:"pdf-viewer-wide-label",children:"Next"}),t.jsx(J,{size:16})]})]}):null,t.jsxs("div",{className:"pdf-viewer-toolbar-group pdf-viewer-zoom-modes",role:"group","aria-label":"Zoom mode",children:[t.jsxs("div",{className:"pdf-viewer-zoom-mode-buttons",children:[t.jsx(ds,{variant:Ce.mode===Yv.FIT_WIDTH?"primary":"secondary",size:"small",onClick:Ce.setFitWidth,ariaLabel:"Fit width","aria-pressed":Ce.mode===Yv.FIT_WIDTH,children:"Fit Width"}),t.jsx(ds,{variant:Ce.mode===Yv.FIT_PAGE?"primary":"secondary",size:"small",onClick:Ce.setFitPage,ariaLabel:"Fit page","aria-pressed":Ce.mode===Yv.FIT_PAGE,children:"Fit Page"}),t.jsxs(ds,{variant:Ce.mode===Yv.ACTUAL_SIZE?"primary":"secondary",size:"small",onClick:Ce.setActualSize,ariaLabel:"Actual size","aria-pressed":Ce.mode===Yv.ACTUAL_SIZE,
2children:[t.jsx(Me,{size:15}),"100%"]})]}),t.jsxs("label",{className:"pdf-viewer-compact-zoom-mode",children:[t.jsx("span",{children:"Zoom"}),t.jsxs("select",{"aria-label":"Zoom mode for narrow screens",value:Ce.mode,onChange:e=>{const t=e.target.value;t===Yv.FIT_WIDTH&&Ce.setFitWidth(),t===Yv.FIT_PAGE&&Ce.setFitPage(),t===Yv.ACTUAL_SIZE&&Ce.setActualSize()},children:[t.jsx("option",{value:Yv.FIT_WIDTH,"aria-label":"Fit PDF to width",children:"Width"}),t.jsx("option",{value:Yv.FIT_PAGE,"aria-label":"Fit whole PDF page",children:"Page"}),t.jsx("option",{value:Yv.ACTUAL_SIZE,"aria-label":"Show PDF at actual size",children:"100%"}),t.jsx("option",{value:Yv.CUSTOM,"aria-label":"Custom PDF zoom",disabled:!0,children:"Custom"})]})]})]}),t.jsxs("div",{className:"pdf-viewer-toolbar-group pdf-viewer-zoom-controls",role:"group","aria-label":"Zoom",children:[t.jsx(ds,{variant:"secondary",size:"small",onClick:Ce.zoomOut,disabled:!Ce.canZoomOut,ariaLabel:"Zoom out",children:t.jsx(Ie,{size:16})}),t.jsxs("output",{className:"pdf-viewer-zoom-value","aria-label":"Zoom level",children:[Ce.scalePercent,"%"]}),t.jsx(ds,{variant:"secondary",size:"small",onClick:Ce.zoomIn,disabled:!Ce.canZoomIn,ariaLabel:"Zoom in",children:t.jsx(Z,{size:16})})]}),t.jsxs("div",{className:"pdf-viewer-toolbar-group pdf-viewer-controls-right",role:"group","aria-label":"Tools",children:[t.jsx("span",{className:"pdf-viewer-zoom-hint",title:"Ctrl/Cmd + scroll to zoom",children:"Ctrl/Cmd + scroll to zoom"}),"absent"!==I?t.jsx("span",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:He}):null,"loading"===I||"retrying"===I?t.jsx("span",{className:"pdf-viewer-overlay-request","aria-hidden":"true",children:"retrying"===I?`Retrying ${Be}â¦`:`Loading ${Be}â¦`}):null,"error"===I?t.jsxs("div",{className:"pdf-viewer-overlay-request pdf-viewer-overlay-request--error",children:[t.jsxs("span",{children:[qe," unavailable. PDF viewing is unaffected."]}),t.jsx(ds,{variant:"ghost",size:"small",onClick:()=>{_("retrying"),A(e=>e+1)},ariaLabel:`Retry loading ${Be}`,children:"Retry"})]}):null,"ready"===I&&t.jsx("div",{className:"pdf-viewer-overlay-toggle",children:t.jsxs("label",{children:[t.jsx("input",{type:"checkbox",checked:O,onChange:()=>{O&&(F(null),q(null),W(0),H(null)),D(e=>!e)}}),t.jsx("span",{children:qe})]})}),"ready"===I&&p?t.jsx("span",{className:"pdf-viewer-overlay-hint pdf-viewer-overlay-hint--authority",children:We?"Correction requires reconciliation":"Original OCR reference"}):"ready"===I&&O&&Le.length?t.jsx("span",{className:"pdf-viewer-overlay-hint",children:"Select a highlight"}):null]}),t.jsx("button",{type:"button",ref:ue,className:"pdf-viewer-fullscreen-btn",onClick:()=>{if(K)return void De();const e=ce.current;if(G(!0),"function"==typeof e?.requestFullscreen)try{const t=e.requestFullscreen();t?.catch?.(()=>{he.current=!1})}catch{he.current=!1}},"aria-label":K?"Exit full screen":"Enter full screen","aria-pressed":K,children:K?t.jsx(Et,{size:18}):t.jsx(It,{size:18})})]}),le&&t.jsx("div",{className:"pdf-viewer-page-validation",id:"pdf-page-validation",role:"status",children:le}),P&&t.jsx("div",{className:"pdf-viewer-loading",role:"status","aria-live":"polite","aria-atomic":"true",children:"Loading PDFâ¦"}),$&&u&&t.jsx("div",{className:"pdf-viewer-error",children:$}),t.jsx("div",{className:"pdf-viewer-container",ref:de,role:"region",tabIndex:0,"aria-label":"PDF page canvas","aria-busy":P,children:t.jsx(va,{file:we,onLoadSuccess:({numPages:e})=>{x(e),ae(!0),L(!1),c&&c({numPages:e})},onLoadError:e=>{M(u||!d?"Failed to load PDF document":null),ae(!1),L(!1),d&&d(e)},loading:null,children:t.jsxs("div",{className:"pdf-viewer-page-wrapper"+(null!==z?" is-over-text-region":""),onPointerDownCapture:e=>{!1!==e.isPrimary&&0===e.button&&(be.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,moved:!1})},onPointerMoveCapture:e=>{const t=be.current;if(t?.pointerId===e.pointerId){const a=e.clientX-t.startX,n=e.clientY-t.startY;Math.hypot(a,n)>6&&(t.moved=!0)}if("touch"===e.pointerType||!O||!Ke.length)return;const a=e.target;if(a?.closest?.('a, button, input, select, textarea, [role="link"], [role="button"], [contenteditable="true"]'))return void q(null);const n=e.currentTarget.getBoundingClientRect();ve.current={x:e.clientX-n.left,y:e.clientY-n.top},xe.current||(xe.current=requestAnimationFrame(()=>{xe.current=null;const e=ve.current;q(e?nj(e,Ke,-1):null)}))},onPointerLeave:Je,onPointerCancel:()=>
2{be.current=null,Je()},onClickCapture:e=>{if(!O||!Ke.length||e.defaultPrevented)return;const t=be.current;if(be.current=null,t?.moved)return;const a=window.getSelection?.();if(a&&!a.isCollapsed)return;const n=e.target;if(n?.closest?.('a, button, input, select, textarea, [role="link"], [role="button"], [contenteditable="true"]'))return;const s=e.currentTarget.getBoundingClientRect(),r=nj({x:e.clientX-s.left,y:e.clientY-s.top},Ke,$e);null!==r&&Ge(r,{keepDetailsOpen:!0,moveFocus:!0})},children:[t.jsx(ja,{pageNumber:v,onLoadSuccess:e=>{const t=e.getViewport({scale:1});N(t.width),C(t.height)},onRenderSuccess:Se,renderTextLayer:!0,renderAnnotationLayer:!0,scale:Ce.scale}),O&&Le.length>0&&ne&&re&&t.jsxs("div",{className:"pdf-viewer-ocr-overlay",style:{width:ne,height:re},children:[t.jsxs("span",{id:ye,className:"sr-only",children:["Use arrow keys to move between ",Be,". Press Enter or Space for details and Escape to close them."]}),Ke.map(({index:e,pixelBox:a,geometry:n})=>{const s=tj(a.confidence),r=`${Fe} ${e+1} of ${Le.length}, confidence ${s}`,i=V===e;return t.jsx("button",{type:"button",ref:t=>{je.current[e]=t},className:`ocr-box ${U===e?"highlighted":""} ${z===e?"hovered":""}`,style:n,tabIndex:$e===e?0:-1,onFocus:()=>{W(e),F(e)},onBlur:()=>{i||F(null)},onKeyDown:t=>((e,t)=>{let a=null;if("ArrowRight"===e.key||"ArrowDown"===e.key?a=t+1:"ArrowLeft"===e.key||"ArrowUp"===e.key?a=t-1:"Home"===e.key?a=0:"End"===e.key&&(a=Le.length-1),null!==a)return e.preventDefault(),e.stopPropagation(),void Ge(a,{keepDetailsOpen:null!==V,moveFocus:!0});"Enter"===e.key||" "===e.key?(e.preventDefault(),e.stopPropagation(),W(t),F(t),H(t)):"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),H(null),F(null))})(t,e),onClick:()=>Ge(e,{keepDetailsOpen:!0,moveFocus:!0}),"aria-label":r,"aria-describedby":ye,"aria-expanded":i,"aria-controls":i?ke:void 0,children:t.jsx("span",{className:`ocr-box-visual ${a.type||""}`,"aria-hidden":"true"})},e)})]})]})})}),O&&Ue?t.jsxs("div",{id:ke,className:"pdf-viewer-ocr-details",role:"region","aria-label":p?"Original OCR snapshot details":"Text region details","aria-live":"polite",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),Ye())},children:[t.jsxs("div",{className:"pdf-viewer-ocr-details-copy",children:[t.jsxs("p",{className:"pdf-viewer-ocr-details-meta",children:[Fe," ",V+1," of ",Le.length," · Confidence"," ",tj(Ue.confidence)]}),p?t.jsx("p",{className:"pdf-viewer-ocr-details-note",children:Ve}):null,t.jsx("p",{className:"pdf-viewer-ocr-details-text",children:String(Ue.text||"").trim()||`No text is stored for this ${ze}.`})]}),t.jsxs("div",{className:"pdf-viewer-ocr-details-actions",children:[t.jsxs(ds,{variant:"secondary",size:"small",onClick:()=>Ge(V-1,{keepDetailsOpen:!0}),disabled:Le.length<2,ariaLabel:`Previous ${ze}`,children:[t.jsx(Rt,{size:16}),"Previous"]}),t.jsxs(ds,{variant:"secondary",size:"small",onClick:()=>Ge(V+1,{keepDetailsOpen:!0}),disabled:Le.length<2,ariaLabel:`Next ${ze}`,children:["Next",t.jsx(J,{size:16})]}),t.jsx(ds,{variant:"ghost",size:"small",onClick:Ye,ariaLabel:`Close ${ze} details`,children:"Close"})]})]}):null,"ready"===I&&O&&t.jsx("div",{className:"pdf-viewer-stats",children:Le.length?`${Le.length} ${1===Le.length?ze:Be} on this page. ${p?We?"The earlier correction requires reconciliation.":"Original OCR is shown for reference.":"Select a highlighted region for details."}`:`No ${Be} on this page`})]}):t.jsx("div",{className:`pdf-viewer ${f}`,children:t.jsx("div",{className:"pdf-viewer-error",children:"No document URL provided"})})}const rj=Object.freeze(Object.defineProperty({__proto__:null,default:sj},Symbol.toStringTag,{value:"Module"}));function ij({page:e,onPageChange:a,onDocumentInfo:n,pdfProps:s,className:r="",isTabbedLayout:i=!1,isActive:l=!0}){return t.jsx("div",{id:"research-viewer-pdf-panel",className:`pdf-research-pane ${r}`.trim(),role:i?"tabpanel":"region","aria-label":i?void 0:"PDF","aria-labelledby":i?"research-viewer-pdf-tab":void 0,hidden:i&&!l,children:t.jsx(sj,{...s,page:e,onPageChange:a,onDocumentInfo:n})})}function lj(e,t){if(!e||!t||!t.trim())return[];const a=new RegExp(t.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");const n=[];let s;for(;null!==(s=a.exec(e));)n.push({start:s.index,end:s.index+s[0].length}),0===s[0].length&&(a.lastIndex+=1);return n}function oj(e,t,a=-1){if(!e)return[];if(!t||0===t.length)return[{text:e,isMatch:!1,isActive:!1}];const n=[];let s=0;return t.forEach((t,r)=>{t.start>s&&n.push({text:e.slice(s,t.start),isMatch:!1,isActive:!1}),n.push({text:e.slice(t.start,t.end),isMatch:!0,isActive:r===a}),s=t.end}),s<e.length&&n.push({text:e.slice(s),isMatch:!1,isActive:!1}),n}function cj(e,t){if(!e)return null;const a=Math.max(0,Math.min(e.start,t)),n=Math.max(0,Math.min(e.end,t));return!Number.isInteger(a)||!Number.isInteger(n)||n<=a?null:{start:a,end:n}}const dj=Object.freeze({NOT_STARTED:"not_started",QUEUED:"queued",PROCESSING:"processing",MACHINE:"machine_generated",CORRECTED:"corrected",REVIEWED:"reviewed",PREVIEW:"pdf_text_preview",TOKENWORKS_CORRECTION:"tokenworks_correction",FAILED:"failed",SUPERSEDED:"superseded",UNKNOWN:"unknown"}),uj=new Set(Object.values(dj));function hj(e){const t="string"==typeof e?e.trim().toLowerCase():"";return uj.has(t)?t:dj.UNKNOWN}const mj={[dj.NOT_STARTED]:{label:"No page text",description:"This page does not have available page text.",tone
2:"neutral"},[dj.QUEUED]:{label:"Pending",description:"Page text processing has not completed for this page.",tone:"neutral"},[dj.PROCESSING]:{label:"Processing",description:"Page text processing is currently running for this page.",tone:"info"},[dj.MACHINE]:{label:"Page text",description:"Extracted automatically. Not yet reviewed by a person.",tone:"neutral"},[dj.CORRECTED]:{label:"Corrected",description:"A person has corrected this page text.",tone:"positive"},[dj.REVIEWED]:{label:"Reviewed",description:"A person has reviewed and confirmed this page text.",tone:"positive"},[dj.PREVIEW]:{label:"PDF text preview",description:"Extracted from the existing PDF text layer. Not yet synchronized to Wikibase.",tone:"info"},[dj.TOKENWORKS_CORRECTION]:{label:"Saved correction",description:"Saved in TokenWorks as the displayed page text.",tone:"positive"},[dj.FAILED]:{label:"Text unavailable",description:"Page text could not be produced for this page.",tone:"negative"},[dj.SUPERSEDED]:{label:"Superseded",description:"This page text has been replaced by a newer version.",tone:"neutral"},[dj.UNKNOWN]:{label:"Status unknown",description:"The page text status could not be determined.",tone:"neutral"}};function pj({status:e,className:a=""}){const{label:n,description:s,tone:r}=function(e){return mj[hj(e)]||mj[dj.UNKNOWN]}(e);return t.jsx("span",{className:`ocr-status-badge ocr-status-badge--${r} ${a}`.trim(),title:s,children:n})}function gj({query:e,onQueryChange:a,matchCount:n,activeIndex:s,onNext:r,onPrevious:i,disabled:l}){return t.jsxs("div",{className:"ocr-search-box",role:"search","aria-label":"Search this page text",children:[t.jsx(ue,{size:14,"aria-hidden":"true"}),t.jsx("input",{type:"text",value:e,onChange:e=>a(e.target.value),placeholder:"Search this page...","aria-label":"Search this page text",disabled:l,onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.shiftKey?i():r())}}),e?t.jsx("span",{className:"ocr-search-box-count",role:"status",children:n>0?`${s+1} of ${n}`:"No matches"}):null,t.jsx(ds,{variant:"ghost",size:"small",onClick:i,disabled:0===n,ariaLabel:"Previous match",children:t.jsx(_t,{size:14})}),t.jsx(ds,{variant:"ghost",size:"small",onClick:r,disabled:0===n,ariaLabel:"Next match",children:t.jsx(u,{size:14})})]})}function fj(){return t.jsxs("div",{className:"ocr-pane-skeleton",role:"status","aria-label":"Loading page text",children:[t.jsx("span",{className:"ocr-pane-skeleton-line"}),t.jsx("span",{className:"ocr-pane-skeleton-line"}),t.jsx("span",{className:"ocr-pane-skeleton-line ocr-pane-skeleton-line--short"}),t.jsx("span",{className:"ocr-pane-skeleton-line"})]})}function bj({pageNumber:e,ocrStatus:a}){return t.jsxs("div",{className:"ocr-pane-empty-state",role:"status",children:[t.jsx("p",{className:"ocr-pane-empty-state-message",children:"Page text is not available."}),e?t.jsxs("p",{className:"ocr-pane-empty-state-detail",children:["Page ",e,a?t.jsxs(t.Fragment,{children:[" ","· ",t.jsx(pj,{status:a})]}):null]}):null]})}function xj({pageNumber:e,error:a,onRetry:n}){const s=[401,402,403].includes(a?.status)||["SUBSCRIPTION_REQUIRED","DOCUMENT_FORBIDDEN","UNAUTHORIZED"].includes(a?.code),r="DOCUMENT_TEXT_PERSISTENCE_UNAVAILABLE"===a?.code;return t.jsxs("div",{className:"ocr-pane-error-state",role:"alert",children:[t.jsx("p",{children:s?"Your account does not currently have access to page text.":r?"Saved page text is temporarily unavailable.":`Couldn't load the page text for this page${e?` (page ${e})`:""}.`}),t.jsxs("p",{className:"ocr-pane-error-state-detail",children:[r?"Try again in a few minutes. If the problem continues, contact support. ":"","The PDF page is still available."]}),n&&!s?t.jsx(ds,{variant:"secondary",size:"small",onClick:n,children:"Retry page text"}):null]})}function vj(e){return{currentRevisionId:e?.currentRevisionId??e?.revision??null,currentChecksum:e?.currentChecksum??e?.checksum??null,remoteRevision:e?.remoteRevision??e?.observedRevisionId??null,remoteChecksum:e?.remoteChecksum??e?.observedChecksum??null,reconciliationRequired:!0===e?.reconciliationRequired}}function jj(e){return["indexed","current","synced"].includes(e)?"updated":["failed","dead_lettered","terminal_failed"].includes(e)?"update needs retry":["pending","queued","processing","updating"].includes(e)?"updating":"update status pending confirmation"}function yj(e){return!0===e?.synchronizedToWikibase||"synced"===e?.operationalClaimSyncStatus?"synced":["failed","dead_lettered","terminal_failed"].includes(e?.operationalClaimSyncStatus)?"failed":"updating"}function kj(e,t,a=320){const n=String(e??""),s=String(t??"");if(!n)return"No text";if(n.length<=a)return n;let r=0;const i=Math.min(n.length,s.length);for(;r<i&&n[r]===s[r];)r+=1;const l=Math.max(0,r-80),o=Math.min(n.length,l+a);return`${l>0?"â¦":""}${n.slice(l,o)}${o<n.length?"â¦":""}`}function wj({status:n,detail:s,integrityConflict:r=null,pageNumber:i,className:l="",initialHighlight:o=null,annotationSpans:c=[],selectedAnnotationId:d=null,onSelectAnnotation:u,canEditResearchData:h=!1,onSaveOcrText:m,onReload:p,onDirtyChange:f,onEditingChange:b,onNewerVersionChange:x,onIntegrityConflictChange:v,customerMode:j=!1,pageTextSyncStatus:y=null,error:k=null,isTabbedLayout:w=!1,isActive:N=!0}){const S=Ds(),[C,R]=e.useState(!1),[E,I]=e.useState(Boolean(o)),[_,T]=e.useState(!1),[A,O]=e.useState(""),[D,P]=e.useState(""),[L,$]=e.useState("idle"),[M,U]=e.useState(null),[F,z]=e.useState(null),[q,B]=e.useState(null),[W,V]=e.useState(null),[H,K]=e.useState(null),[G,J]=e.useState(""),Y=s?.ocrText||"",Q=Y.trim()?Y:"",X="pdf_text_preview"===s?.sourceKind,Z=["embedded_pdf_text","empty_pdf_text"].includes(s?.sourceKind),ee="tokenworks_correction"===s?.sourceKind,te="pageocr_projection"===s?.sourceKind,ae=!0===s?.requiresReconciliation,se=String(s?.syncRequest?.classification||y?.classification||"").toUpperCase(),re=j&&(!0===s?.syncRequest?.reviewRequired||!0===y?.reviewRequired||"REVIEW_REQUIRED"===se),ie=te&&!0===s?.authoritative&&!
2ae&&Number.isInteger(s?.sourceRevision)&&s.sourceRevision>0&&Boolean(s?.ocrChecksum),le=re&&!ie,oe=h&&"ready"===n&&!0===s?.editable&&!r&&!le&&(!j||!0===s?.authoritative&&!ae)&&Number.isInteger(s?.sourceRevision)&&s?.ocrChecksum&&"function"==typeof m,ce=te&&"pageocr_content_sync_required"===s?.editabilityReason,de=!j&&h&&te&&"parent_wikibase_mapping_reconciliation_required"===s?.editabilityReason,he=!j&&h&&!oe&&(Z||X||ce),me=j&&h,pe=s?.syncRequest?.state||y?.requestState||null,ge=function({classification:e,selectedPageReady:t}){return t?"Ready to edit":"FULLY_SYNCED"===e?"Publishing transcript":"MISSING_PAGE_DISCOVERY"===e?"Creating page records":["MISSING_PAGE_ENTITY","MISSING_PARENT_EDGE","MISSING_REVERSE_EDGE"].includes(e)?"Synchronizing page identity":["MISSING_PAGE_TEXT","MISSING_TEXT_READBACK"].includes(e)?"Publishing transcript":["MISSING_PROJECTION","MISSING_SEARCH"].includes(e)?"Finalizing search":"REVIEW_REQUIRED"===e?"Synchronizing page identity":"Creating page records"}({classification:se,selectedPageReady:oe}),fe="NOT_ACTIVATED"===pe?"Automatic transcript preparation is not active yet.":"DURABLY_QUEUED"===pe?"Transcript preparation is queued and will continue automatically.":"RETRY_DEFERRED"===pe?"Transcript preparation is waiting for its next automatic retry.":"RETRYING"===pe?"A temporary scheduling issue occurred. Retrying automatically.":"The saved transcript is being verified.",be=_&&"ready"===n&&!oe&&!r,xe=_&&(A!==(q?.text??Q)||D.trim().length>0),ve=function(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}(s?.updatedAt),je=vj(F),ye=vj(r?.conflict||r),ke=s?.sourceRevision??null,we=s?.ocrChecksum??null,Ne=s?.documentId??null,Se=s?.pageNumber??i??null,Ce=s?.sourceBinaryIdentity??null,Re=yj(s),Ee=s?.searchIndexStatus||null,Ie=function(t,{initialQuery:a=""}={}){const[n,s]=e.useState(a),[r,i]=e.useState(0),l=e.useMemo(()=>lj(t,n),[t,n]);return e.useEffect(()=>{i(0)},[n,t]),{query:n,setQuery:s,matches:l,matchCount:l.length,activeIndex:l.length>0?r:-1,goToNext:()=>{0!==l.length&&i(e=>(e+1)%l.length)},goToPrevious:()=>{0!==l.length&&i(e=>(e-1+l.length)%l.length)}}}(Q,{initialQuery:o||""}),_e=e.useRef(null),Te=e.useRef(null),Ae=e.useRef(null),Oe=e.useRef(_);Oe.current=_;const De=e.useRef({requested:!1,sawLoading:!1,sourceBinaryIdentity:null}),Pe=e.useRef(s?.sourceBinaryIdentity||null),Le=e.useRef({key:null,sawPreparing:!1,announced:!1});e.useEffect(()=>{if(!h)return Le.current={key:null,sawPreparing:!1,announced:!1},void J("");const e=`${i||""}:${s?.sourceBinaryIdentity||""}`;if(Le.current.key!==e&&(Le.current={key:e,sawPreparing:!1,announced:!1},J("")),!oe)return Le.current.sawPreparing=!0,Le.current.announced=!1,void J("");Le.current.sawPreparing&&!Le.current.announced&&(Le.current.announced=!0,J("Editable transcript ready. Edit page text is now available."))},[oe,h,s?.sourceBinaryIdentity,i]),e.useEffect(()=>(f?.(xe),()=>f?.(!1)),[xe,f]),e.useLayoutEffect(()=>(b?.(_),()=>b?.(!1)),[_,b]),e.useEffect(()=>{x?.(Boolean(W))},[W,x]),e.useEffect(()=>{v?.(Boolean(r))},[r,v]),e.useEffect(()=>{r&&K(null)},[r]),e.useEffect(()=>()=>{x?.(!1),v?.(!1)},[v,x]),e.useEffect(()=>{const e=s?.sourceBinaryIdentity||null,t=Pe.current;if(e&&t!==e){if(Pe.current=e,Oe.current&&t&&e&&t!==e)return $("conflict"),z({currentRevisionId:s?.sourceRevision??null}),void U("The source PDF changed while this draft was open. Your draft is still here for comparison.");Oe.current||($("idle"),U(null),z(null))}},[s?.sourceBinaryIdentity,s?.sourceRevision]),e.useEffect(()=>{_||(O(Q),P(""),U(null),B(null),V(null),"saved"!==L&&$("idle"))},[_,Q,L]),e.useEffect(()=>{if(!_||!q)return;const e=s?.sourceRevision!==q.sourceRevision,t=s?.ocrChecksum!==q.ocrChecksum,a=s?.sourceBinaryIdentity!==q.sourceBinaryIdentity;(e||t||a)&&V({revision:s?.sourceRevision??null,checksum:s?.ocrChecksum??null,sourceChanged:a})},[s?.ocrChecksum,s?.sourceBinaryIdentity,s?.sourceRevision,q,_]),e.useEffect(()=>{K(e=>{if(!e)return e;if(!(e.documentId===Ne&&e.pageNumber===Se&&e.sourceBinaryIdentity===Ce)||!Number.isInteger(ke)||ke<=0||ke!==e.revision||!we||we!==e.checksum)return null;const t=Ee||e.searchStatus;return e.claimsStatus===Re&&e.searchStatus===t?e:{...e,claimsStatus:Re,searchStatus:t}})},[Re,Ne,Se,we,ke,Ee,Ce]),e.useEffect(()=>{_&&Ae.current?.focus()},[_]),e.useEffect(()=>{const e=De.current;if(!e.requested)return;if("loading"===n)return void(e.sawLoading=!0);if(!e.sawLoading)return;if("ready"!==n)return De.current={requested:!1,sawLoading:!1,sourceBinaryIdentity:null},$("reconciliation"),void U(j?"The saved page text could not be confirmed yet. Your draft is still here; do not save it again.":"Synchronization could not be confirmed yet. Your draft is still here; do not save it again.");if(De.current={requested:!1,sawLoading:!1,sourceBinaryIdentity:null},e.sourceBinaryIdentity&&s?.sourceBinaryIdentity&&e.sourceBinaryIdentity!==s.sourceBinaryIdentity)return $("conflict"),z({currentRevisionId:s?.sourceRevision??null}),void U(j?"The source PDF changed while the saved page text was checked. Your draft is still here for comparison.":"The source PDF changed while synchronization was checked. Your draft is still here for comparison.");return"pageocr_projection"===s?.sourceKind&&!0===s?.authoritative&&!0===s?.synchronizedToWikibase&&!0!==s?.requiresReconciliation?Q===A?($("saved"),U(null),z(null),T(!1),S?.({type:"success",message:j?"S
2aved page text confirmed.":"Page text synchronization confirmed."}),void window.setTimeout(()=>Te.current?.focus(),0)):($("conflict"),z({currentRevisionId:s?.sourceRevision??null,currentChecksum:s?.ocrChecksum??null}),void U(j?"The saved page text is different from your draft. Your draft is still here for comparison.":"Synchronization completed with different page text. Your draft is still here for comparison.")):($("reconciliation"),void U(j?"The saved page text is still being checked. Your draft is still here; do not save it again.":"Synchronization is still pending. Your draft is still here; do not save it again."))},[j,s,A,S,Q,n]),e.useEffect(()=>{if(!xe)return;const e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[xe]);const $e=async()=>{if(_)try{if(!navigator?.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(A),S?.({type:"success",message:"Draft copied to clipboard."})}catch{S?.({type:"error",message:"Could not copy the draft."})}},Me=()=>{!xe||window.confirm("Discard your unsaved draft and reload the latest saved page text?")?(T(!1),$("idle"),U(null),z(null),V(null),p?.()):window.setTimeout(()=>Ae.current?.focus(),0)},Ue=e.useMemo(()=>"ready"===n?function(e,{searchMatches:t=[],activeSearchIndex:a=-1,annotationSpans:n=[],selectedAnnotationId:s=null}={}){if("string"!=typeof e||0===e.length)return[];const r=e.length,i=[];t.forEach((e,t)=>{const n=cj(e,r);n&&i.push({...n,isActive:t===a})});const l=[];if(n.forEach(e=>{const t=cj(e,r);t&&e.id&&l.push({...t,id:e.id})}),0===i.length&&0===l.length)return[{text:e,isSearchMatch:!1,isActiveSearchMatch:!1,isAnnotation:!1,isSelectedAnnotation:!1,annotationIds:[]}];const o=new Set([0,r]);for(const u of i)o.add(u.start),o.add(u.end);for(const u of l)o.add(u.start),o.add(u.end);const c=Array.from(o).sort((e,t)=>e-t),d=[];for(let u=0;u<c.length-1;u++){const t=c[u],a=c[u+1];if(a<=t)continue;let n=!1,r=!1;for(const e of i)e.start<=t&&e.end>=a&&(n=!0,e.isActive&&(r=!0));const o=[];let h=!1;for(const e of l)e.start<=t&&e.end>=a&&(o.push(e.id),s&&e.id===s&&(h=!0));d.push({text:e.slice(t,a),isSearchMatch:n,isActiveSearchMatch:r,isAnnotation:o.length>0,isSelectedAnnotation:h,annotationIds:o})}return d}(Q,{searchMatches:Ie.matches,activeSearchIndex:Ie.activeIndex,annotationSpans:c,selectedAnnotationId:d}):[],[n,Q,Ie.matches,Ie.activeIndex,c,d]),Fe=e.useMemo(()=>{const e=new Map;for(const t of c)e.set(t.id,t);return e},[c]);e.useEffect(()=>{d&&_e.current&&_e.current.scrollIntoView?.({block:"nearest",inline:"nearest"})},[d,Ue]);let ze=!1;return t.jsxs("div",{id:"research-viewer-ocr-panel",className:`ocr-research-pane ${l}`.trim(),role:w?"tabpanel":"region","aria-label":w?void 0:"Page text","aria-labelledby":w?"research-viewer-ocr-tab":void 0,hidden:w&&!N,children:[t.jsxs("div",{className:"ocr-research-pane-toolbar",role:"toolbar","aria-label":"Page text tools",children:[s?.ocrStatus?t.jsx(pj,{status:s.ocrStatus}):null,t.jsxs("div",{className:"ocr-research-pane-toolbar-actions",children:[t.jsx(ds,{variant:"ghost",size:"small",onClick:()=>I(e=>!e),ariaLabel:E?"Hide page search":"Search this page","aria-pressed":E,disabled:"ready"!==n,children:t.jsx(ue,{size:14})}),t.jsxs(ds,{variant:"ghost",size:"small",onClick:async()=>{if(Q)try{if(!navigator?.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),R(!0),S?.({type:"success",message:"Page text copied to clipboard."}),window.setTimeout(()=>R(!1),2e3)}catch{S?.({type:"error",message:"Could not copy page text."})}},disabled:"ready"!==n||!Q||_,ariaLabel:"Copy page text",children:[C?t.jsx(Ve,{size:14}):t.jsx(Ge,{size:14}),t.jsx("span",{className:"ocr-research-pane-copy-label",children:C?"Copied":"Copy text"})]}),oe&&!_?t.jsxs(ds,{ref:Te,variant:"ghost",size:"small",onClick:()=>{oe&&(O(Q),B({text:Q,sourceRevision:s.sourceRevision,ocrChecksum:s.ocrChecksum,sourceBinaryIdentity:s.sourceBinaryIdentity}),P(""),U(null),z(null),V(null),$("idle"),T(!0))},ariaLabel:j?Q?"Edit page text":"Add page text":"Edit PageOCR text",children:[t.jsx(Tt,{size:14}),t.jsx("span",{className:"ocr-research-pane-edit-label"+(Q?"":" ocr-research-pane-edit-label--add"),children:Q?"Edit text":"Add text"})]}):null]})]}),t.jsx("span",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:G}),j?null:t.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:"saving"===L?"Saving page text.":""}),E&&"ready"===n?t.jsx(gj,{query:Ie.query,onQueryChange:Ie.setQuery,matchCount:Ie.matchCount,activeIndex:Ie.activeIndex,onNext:Ie.goToNext,onPrevious:Ie.goToPrevious}):null,t.jsxs("div",{className:"ocr-research-pane-content",children:[r?t.jsxs("div",{className:"ocr-edit-ne
2wer-version",role:"alert","aria-live":"assertive","aria-atomic":"true",children:[t.jsx("strong",{children:j?"Saved page text needs review.":"Conflicting page-text evidence needs review."}),j?t.jsx("span",{children:"The latest check returned different text. The last verified page text is still shown."}):t.jsxs("span",{children:["Revision ",ye.currentRevisionId??"unknown"," was returned with inconsistent content. The last verified page text is still shown."]}),_?t.jsx("span",{children:"Your draft has not been replaced."}):null,t.jsxs("div",{className:"ocr-edit-newer-version-actions",children:[_?t.jsxs(ds,{variant:"secondary",size:"small",onClick:$e,children:[t.jsx(Ge,{size:14}),t.jsx("span",{children:"Copy draft"})]}):null,t.jsx(ds,{variant:"secondary",size:"small",onClick:p,children:"Check latest page text"})]})]}):null,r||!H||_?null:t.jsxs("div",{className:"ocr-research-pane-source-note ocr-research-pane-source-note--saved",role:"status","aria-live":"polite",children:[t.jsxs("strong",{children:["Page text saved",!j&&H.revision?` · Revision ${H.revision}`:""]}),t.jsxs("span",{children:[j?"Library update: ":"Wikibase claims: ","synced"===H.claimsStatus?j?"complete":"synced":"failed"===H.claimsStatus?j?"needs attention":"repair required":j?"in progress":"updating"]}),t.jsxs("span",{children:["Search: ",jj(H.searchStatus)]}),t.jsx("span",{children:"The PDF file itself is unchanged."})]}),!r&&le?t.jsxs("div",{className:"ocr-research-pane-source-note ocr-research-pane-source-note--warning",role:"status","aria-live":"polite","aria-atomic":"true",children:[t.jsx("strong",{children:"Saved page text needs review."}),t.jsx("span",{children:"TokenWorks staff must resolve the page identity or source conflict before editing can continue."}),t.jsx("span",{children:"The last verified transcript remains readable, and this status refreshes automatically."}),t.jsx("span",{children:"Return later, or contact support with this document reference if the status persists."}),t.jsx("span",{children:"The PDF file itself is unchanged."})]}):!r&&de?t.jsxs("div",{className:"ocr-research-pane-source-note ocr-research-pane-source-note--warning",role:"status","aria-live":"polite","aria-atomic":"true",children:[t.jsx("strong",{children:"Page mapping needs review · Read-only"}),t.jsx("span",{children:"The transcript remains readable while TokenWorks verifies this page and its source document."}),t.jsx("span",{children:"This status refreshes automatically. Contact support with the document reference if it persists."}),t.jsx("span",{children:"The PDF file itself is unchanged."})]}):!r&&ee?t.jsxs("div",{className:"ocr-research-pane-source-note ocr-research-pane-source-note--warning",children:[t.jsx("strong",{children:j?"Saved page text needs review · Read-only":"Reconciliation required · Read-only"}),t.jsx("span",{children:j?"This earlier correction remains visible while the saved page text is being checked.":"This earlier correction remains visible, but it has not been synchronized with the canonical page text."}),j&&ve?t.jsxs("span",{children:["Last saved ",t.jsx("time",{dateTime:s.updatedAt,children:ve})]}):null,t.jsx("span",{children:"The PDF file itself is unchanged."})]}):!r&&me&&oe?t.jsxs("div",{className:"ocr-research-pane-source-note ocr-research-pane-source-note--synced",children:[t.jsx("strong",{children:"Editable transcript ready"}),t.jsx("span",{children:"Edit page text is now available."}),t.jsx("span",{children:"The PDF file itself is unchanged."})]}):!r&&!H&&te&&j&&s?.synchronizedToWikibase?t.jsxs("div",{className:"ocr-research-pane-source-note ocr-research-pane-source-note--synced",children:[t.jsx("strong",{children:"Saved page text"}),t.jsx("span",{children:"Library update: complete"}),t.jsxs("span",{children:["Search: ",jj(s?.searchIndexStatus)]}),t.jsx("span",{children:"The PDF file itself is unchanged."})]}):!r&&!H&&te&&j&&s?.authoritative?t.jsxs("div",{className:"ocr-research-pane-source-note ocr-research-pane-source-note--warning",children:[t.jsx("strong",{children:"Saved page text"}),t.jsx("span",{children:"failed"===s?.operationalClaimSyncStatus?"Library update: needs attention":"Library update: in progress"}),t.jsxs("span",{children:["Search: ",jj(s?.searchIndexStatus)]}),t.jsx("span",{children:"The PDF file itself is unchanged."})]}):!r&&(Z||X&&h||ce&&h||X&&j||!H&&te&&j)?t.jsxs("div",{className:"ocr-research-pane-source-note ocr-research-pane-source-note--warning",role:he?"status":void 0,"aria-live":he?"polite":void 0,"aria-atomic":he?"true":void 0,children:[t.jsx("strong",{children:he?"Preparing editable transcriptâ¦":te?j?me?"NOT_ACTIVATED"===pe?"Editable transcript unavailable":ge:"Saved page text":"Canonical page text needs reconciliation":j&&me?"NOT_ACTIVATED"===pe?"Editable transcript unavailable":ge:Q?"Embedded PDF text":"No embedded text detected"}),t.jsx("span",{children:he?Q?"This readable PDF text stays read-only until the authoritative PageOCR transcript is ready.":"No embedded text was detected. Editing will become available after the authoritative PageOCR transcript is ready.":j?me?fe:Q?"This page text is read-only for your access.":"No embedded text was detected. Page text editing is not included with your access.":"Read-only until canonical page text synchronization is complete."}),he?t.jsx("span",{children:"This status refreshes automatically."}):null,t.jsx("span",{children:"The PDF file itself is unchanged."})]}):!r&&X?t.jsxs("div",{className:"ocr-research-pane-source-note",children:[t.jsx("strong",{children:"PDF text preview"}),t.jsx("span",{children:"Extracted from the existing PDF text layer"}),t.jsx("span",{children:"Not yet synchronized to Wikibase"})]}):null,!j&&!X&&"ready"===n&&s?.sourceRevision>0?t.jsxs("div",{className:"ocr-research-pane-revision","aria-label":"Page text revision",children:[t.jsxs("span",{children:["Revision ",s.sourceRevision]}),s.editHistory?.length?t.jsxs("details",{children:[t.jsx("summary",{children:"History"}),t.jsx("ol",{children:s.editHistory.map(e=>t.jsxs("li",{children:[t.jsxs("span",{children:["Revision ",e.resultingRevisionId||"unknown"]}),e.createdAt?t.jsx("time",{dateTime:e.createdAt,children:new Date(e.createdAt).toLocaleStr
2ing()}):null,e.tokenworksUserRole?t.jsx("span",{children:e.tokenworksUserRole}):null,e.editSummary?t.jsx("span",{children:e.editSummary}):null]},e.id||`${e.resultingRevisionId}-${e.createdAt}`))})]}):null]}):null,"loading"===n&&t.jsx(fj,{}),"unavailable"===n&&t.jsx(bj,{pageNumber:i,ocrStatus:s?.ocrStatus}),"error"===n&&t.jsx(xj,{pageNumber:i,error:k,onRetry:p}),"idle"===n&&t.jsx(bj,{pageNumber:i}),!_||"ready"!==n&&"reconciliation"!==L?null:t.jsxs("div",{className:"ocr-edit-form","aria-busy":"saving"===L,children:[be?t.jsxs("div",{className:"ocr-edit-newer-version",role:"alert",children:[t.jsx("strong",{children:"Page text editing is no longer available."}),t.jsx("span",{children:j?"Your draft has not been replaced. Copy it before checking whether editing access or the saved page text has changed again.":"Your draft has not been replaced. Copy it before checking whether editing access or the authoritative page state has changed again."})]}):null,W&&!["conflict","reconciliation"].includes(L)?t.jsxs("div",{className:"ocr-edit-ne
2wer-version",children:[t.jsxs("div",{role:"status","aria-live":"polite","aria-atomic":"true",children:[t.jsx("strong",{children:"A newer version is available."}),t.jsx("span",{children:"Your draft has not been replaced. Reload to review the saved version, or keep editing and Save will check for a conflict."})]}),t.jsxs("div",{className:"ocr-edit-version-comparison",role:"region","aria-label":"Draft and latest saved text comparison",children:[t.jsxs("div",{className:"ocr-edit-version-comparison-item",children:[t.jsx("strong",{children:"Your draft"}),t.jsx("p",{children:kj(A,Q)})]}),t.jsxs("div",{className:"ocr-edit-version-comparison-item",children:[t.jsx("strong",{children:"Latest saved text"}),t.jsx("p",{children:kj(Q,A)})]})]}),t.jsxs("div",{className:"ocr-edit-newer-version-actions",children:[t.jsxs(ds,{variant:"secondary",size:"small",onClick:$e,children:[t.jsx(Ge,{size:14}),t.jsx("span",{children:"Copy draft"})]}),t.jsx(ds,{variant:"secondary",size:"small",onClick:Me,children:"Reload newer version"})]})]}):null,xe?t.jsx("p",{className:"ocr-edit-dirty",role:"status",children:"Unsaved changes"}):null,t.jsxs("label",{className:"ocr-edit-field",children:[t.jsx("span",{children:"Page text"}),t.jsx("textarea",{ref:Ae,value:A,onChange:e=>O(e.target.value),spellCheck:!1,disabled:"saving"===L,"aria-label":j?"Editable page text":"Editable PageOCR text"})]}),j?null:t.jsxs("label",{className:"ocr-edit-field",children:[t.jsx("span",{children:"Summary"}),t.jsx("input",{value:D,onChange:e=>P(e.target.value),maxLength:240,disabled:"saving"===L,"aria-label":"PageOCR edit summary"})]}),M?t.jsx("p",{className:"ocr-edit-error",role:"alert",children:M}):null,"conflict"===L?t.jsx("p",{className:"ocr-edit-conflict-detail",children:j?"A newer saved version is available.":t.jsxs(t.Fragment,{children:["Latest revision ",je.currentRevisionId??"unknown",je.currentChecksum?` · checksum ${je.currentChecksum}`:""]})}):null,"reconciliation"===L?t.jsx("p",{className:"ocr-edit-conflict-detail",children:j?"Saved page check awaiting confirmation":t.jsxs(t.Fragment,{children:["Remote revision ",je.remoteRevision??"awaiting confirmation",je.remoteChecksum?` · checksum ${je.remoteChecksum}`:""]})}):null,t.jsxs("div",{className:"ocr-edit-actions",children:["reconciliation"===L?t.jsxs(t.Fragment,{children:[t.jsxs(ds,{variant:"secondary",size:"small",onClick:$e,children:[t.jsx(Ge,{size:14}),t.jsx("span",{children:"Copy draft"})]}),t.jsx(ds,{variant:"secondary",size:"small",onClick:()=>{De.current={requested:!0,sawLoading:!1,sourceBinaryIdentity:s?.sourceBinaryIdentity||null},U(j?"Checking the latest saved page text. Your draft will be retained.":"Checking the authoritative page revision. Your draft will be retained."),p?.()},children:j?"Check saved page text":"Check synchronization"})]}):"conflict"===L?t.jsxs(t.Fragment,{children:[t.jsxs(ds,{variant:"secondary",size:"small",onClick:$e,children:[t.jsx(Ge,{size:14}),t.jsx("span",{children:"Copy draft"})]}),t.jsx(ds,{variant:"danger",size:"small",onClick:Me,children:"Discard draft and reload"})]}):r?null:be?t.jsxs(t.Fragment,{children:[t.jsxs(ds,{variant:"secondary",size:"small",onClick:$e,children:[t.jsx(Ge,{size:14}),t.jsx("span",{children:"Copy draft"})]}),t.jsx(ds,{variant:"secondary",size:"small",onClick:p,children:"Check latest page text"})]}):t.jsxs(ds,{variant:"primary",size:"small",onClick:async()=>{if(oe&&!r&&"saving"!==L){$("saving"),U(null),z(null);try{const e=await m({ocrText:A,baseRevisionId:q?.sourceRevision??s.sourceRevision,baseChecksum:q?.ocrChecksum??s.ocrChecksum,sourceBinaryIdentity:q?.sourceBinaryIdentity??s.sourceBinaryIdentity,editSummary:D});K({documentId:e?.documentId??s?.documentId??null,pageNumber:e?.pageNumber??s?.pageNumber??i??null,sourceBinaryIdentity:e?.sourceBinaryIdentity??q?.sourceBinaryIdentity??s?.sourceBinaryIdentity??null,revision:e?.sourceRevision??null,checksum:e?.ocrChecksum??null,claimsStatus:yj(e),searchStatus:e?.searchIndexStatus||null}),$("saved"),V(null),T(!1),window.setTimeout(()=>Te.current?.focus(),0)}catch(e){const t="PAGE_OCR_READBACK_MISMATCH"===e?.code||"PAGE_OCR_REMOTE_COMMITTED_REPAIR_REQUIRED"===e?.code||"DOCUMENT_TEXT_SOURCE_CHANGED_AFTER_REMOTE_WRITE"===e?.code||!0===e?.conflict?.reconciliationRequired,a=409===e?.status||["PAGE_OCR_REVISION_CONFLICT","DOCUMENT_TEXT_REVISION_CONFLICT"].includes(e?.code);
2if($(t?"reconciliation":a?"conflict":"error"),z((t||a)&&(e?.conflict||e?.details?.conflict)||null),t)U(j?"The saved page may already contain this edit, but the result could not be confirmed. Your draft is still here; do not save it again while the saved version is being checked.":"The remote page may already contain this edit, but synchronization could not be verified. Your draft is still here; do not save it again while reconciliation is pending.");else if(a)U("This page changed after editing started. Your draft is still here.");else{const t=e?.safeMessage||e?.message||"Could not save page text.",a=/[.!?]$/.test(t)?t:`${t}.`;U(/your draft is still here/i.test(a)?a:`${a} Your draft is still here. Try saving again.`)}window.setTimeout(()=>Ae.current?.focus(),0)}}},disabled:"saving"===L||!xe,ariaLabel:j?"Save page text":"Save PageOCR edit",children:[t.jsx(ne,{size:14}),t.jsx("span",{children:"saving"===L?"Saving":"Save"})]}),["conflict","reconciliation"].includes(L)?null:t.jsxs(ds,{variant:"ghost",size:"small",onClick:()=>{xe&&!window.confirm("Discard unsaved page text changes?")||(T(!1),window.setTimeout(()=>Te.current?.focus(),0))},disabled:"saving"===L,ariaLabel:j?"Cancel page text edit":"Cancel PageOCR edit",children:[t.jsx(g,{size:14}),t.jsx("span",{children:"Cancel"})]})]})]}),"ready"===n&&!_&&(Q?t.jsx("p",{className:"ocr-research-pane-text","data-testid":"ocr-page-text",children:Ue.map((e,n)=>{if(!e.isSearchMatch&&!e.isAnnotation)return t.jsx(a.Fragment,{children:e.text},n);const s=function(e){if(!e.isAnnotation&&!e.isSearchMatch)return"";const t=[];return e.isAnnotation&&t.push("annotation-span"),e.isSelectedAnnotation&&t.push("annotation-span--selected"),e.isSearchMatch&&t.push("ocr-search-match"),e.isActiveSearchMatch&&t.push("ocr-search-match--active"),t.join(" ")}(e);if(!e.isAnnotation)return t.jsx("mark",{className:s,children:e.text},n);const r=function(e,t){if(!e||0===e.length)return null;if(1===e.length)return e[0];let a=null,n=1/0;for(const s of e){const e=t?.get(s),r=e?e.end-e.start:1/0;(r<n||r===n&&null!==a&&s<a)&&(a=s,n=r)}return a??e[0]}(e.annotationIds,Fe),i=e.isSelectedAnnotation&&!ze;return i&&(ze=!0),t.jsx("mark",{ref:i?_e:void 0,className:s,role:u?"button":void 0,tabIndex:u?0:void 0,"aria-pressed":u?e.isSelectedAnnotation:void 0,onClick:u&&r?()=>u(r):void 0,onKeyDown:u&&r?e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),u(r))}:void 0,children:e.text},n)})}):t.jsxs("div",{className:"ocr-pane-empty-state",role:"status",children:[t.jsx("p",{className:"ocr-pane-empty-state-message",children:"No text is stored for this page yet."}),t.jsx("p",{className:"ocr-pane-empty-state-detail",children:oe?"Use Add text to create the canonical page text.":ae?j?"Text will become editable after the saved page text is ready.":"Text will become editable after canonical synchronization is complete.":j?"Page text cannot be edited right now.":"No editable canonical text is available for this page."})]}))]})]})}function Nj({ratio:a,onChangeRatio:n,min:s=.3,max:r=.7}){const i=e.useRef(!1),l=e=>Math.min(r,Math.max(s,e)),o=e=>{i.current=!1,e.currentTarget.hasPointerCapture?.(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)};return t.jsx("div",{className:"research-pane-resizer",role:"separator","aria-orientation":"vertical","aria-label":"Resize PDF and text panes","aria-valuemin":Math.round(100*s),"aria-valuemax":Math.round(100*r),"aria-valuenow":Math.round(100*a),tabIndex:0,onPointerDown:e=>{i.current=!0,e.currentTarget.setPointerCapture?.(e.pointerId)},onPointerMove:e=>{if(!i.current)return;const t=e.currentTarget.parentElement;if(!t)return;const a=t.getBoundingClientRect();0!==a.width&&n(l((e.clientX-a.left)/a.width))},onPointerUp:o,onPointerCancel:o,onLostPointerCapture:()=>{i.current=!1},onKeyDown:e=>{"ArrowLeft"===e.key?(e.preventDefault(),n(l(a-.02))):"ArrowRight"===e.key?(e.preventDefault(),n(l(a+.02))):"Home"===e.key?(e.preventDefault(),n(s)):"End"===e.key&&(e.preventDefault(),n(r))},children:t.jsx("span",{className:"research-pane-resizer-handle","aria-hidden":"true"})})}function Sj({currentPage:a,totalPages:n,onPrevious:s,onNext:r,onGoToPage:i,pageQid:l,ocrStatus:o,onOpenDetails:c,detailsOpen:d,detailsPanelId:u,detailsTriggerId:h,showDetail
2s:m=!0,disabled:p=!1,statusMessage:g=null}){const[f,b]=e.useState(String(a||1)),[x,v]=e.useState(""),j=e.useId();e.useEffect(()=>{b(String(a||1)),v("")},[a]);const y=()=>{const e=f.trim(),t=Number(e),s=Number(n),r=Number.isInteger(s)&&s>=1;if(!(/^\d+$/.test(e)&&Number.isSafeInteger(t)&&t>=1&&(!r||t<=s)))return b(String(a||1)),void v(r?`Enter a page number between 1 and ${s}.`:"Enter a page number of 1 or greater.");const l=i(t);b(String(!1===l?a||1:t)),v("")};return t.jsxs("div",{className:"research-page-navigator"+(g?" research-page-navigator--with-status":""),role:"group","aria-label":"Page navigation",children:[g?t.jsx("span",{className:"research-page-navigator-status",children:g}):null,t.jsx(ds,{variant:"secondary",size:"small",onClick:s,disabled:p||a<=1,ariaLabel:"Previous page",children:t.jsx(Rt,{size:16})}),t.jsxs("span",{className:"research-page-navigator-info",children:[t.jsx("span",{children:"Page"}),t.jsx("form",{onSubmit:e=>{e.preventDefault(),y()},children:t.jsx("input",{type:"text",inputMode:"numeric",className:"research-page-navigator-input",value:f,onChange:e=>{b(e.target.value),x&&v("")},onBlur:y,"aria-label":"Go to page number","aria-invalid":x?"true":void 0,"aria-describedby":x?j:void 0,disabled:p})}),t.jsxs("span",{children:["of ",n||"?"]})]}),t.jsx(ds,{variant:"secondary",size:"small",onClick:r,disabled:p||Boolean(n)&&a>=n,ariaLabel:"Next page",children:t.jsx(J,{size:16})}),m||o||l?t.jsx("span",{className:"research-page-navigator-divider","aria-hidden":"true"}):null,o?t.jsx(pj,{status:o}):null,l?t.jsx("span",{className:"research-page-navigator-qid",children:l}):null,m?t.jsxs(ds,{variant:d?"primary":"ghost",size:"small",onClick:c,ariaLabel:d?"Hide page details":"Show page details","aria-expanded":d,"aria-controls":u,id:h,children:[t.jsx(Y,{size:16}),t.jsx("span",{className:"research-page-navigator-details-label",children:"Details"})]}):null,x?t.jsx("span",{id:j,className:"research-page-navigator-validation",role:"status","aria-live":"polite","aria-atomic":"true",children:x}):null]})}function Cj({entities:e}){return e&&0!==e.length?t.jsxs("section",{className:"provenance-drawer-section","aria-label":"Entities & Annotations",children:[t.jsx("h4",{children:"Entities & Annotations"}),t.jsx("ul",{className:"entities-placeholder-list",children:e.map((e,a)=>t.jsxs("li",{children:[t.jsx("span",{className:"entities-placeholder-label",children:e.label}),e.type?t.jsx("span",{className:"entities-placeholder-type",children:e.type}):null]},e.qid||`${e.label}-${a}`))})]}):null}function Rj(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Ej({label:e,value:a}){return null==a||""===a?null:t.jsxs("div",{className:"provenance-drawer-field",children:[t.jsx("dt",{children:e}),t.jsx("dd",{children:a})]})}function Ij({isOpen:a,onClose:n,documentMeta:s,pageDetail:r,entities:i,id:l,titleId:o,focusOnOpen:c=!1,className:d="",children:u}){const h=e.useRef(null);if(e.useEffect(()=>{a&&c&&h.current?.focus()},[c,a]),!a)return null;const m=r?.provenance||{},p="pdf_text_preview"===r?.sourceKind;return t.jsxs("aside",{id:l,className:`provenance-drawer ${d}`.trim(),role:"region","aria-labelledby":o||"provenance-drawer-title",children:[t.jsxs("div",{className:"provenance-drawer-header",children:[t.jsx("h3",{ref:h,id:o||"provenance-drawer-title",tabIndex:c?-1:void 0,children:"Page details"}),t.jsx(ds,{variant:"ghost",size:"small",onClick:n,ariaLabel:"Close details panel",children:t.jsx(g,{size:16})})]}),t.jsxs("section",{className:"provenance-drawer-section","aria-label":"Document",children:[t.jsx("h4",{children:"Document"}),t.jsxs("dl",{children:[t.jsx(Ej,{label:"Title",value:s?.title}),t.jsx(Ej,{label:"QID",value:s?.qid||r?.parentQid})]})]}),t.jsxs("section",{className:"provenance-drawer-section","aria-label":"Page",children:[t.jsx("h4",{children:"Page"}),t.jsxs("dl",{children:[t.jsx(Ej,{label:"Page number",value:r?.pageNumber}),p?null:t.jsx(Ej,{label:"Page QID",value:r?.pageQid})]})]}),t.jsxs("section",{className:"provenance-drawer-section","aria-label":"Page text",children:[t.jsx("h4",{children:"Page text"}),t.jsxs("dl",{children:[r?.ocrStatus?t.jsxs("div",{className:"provenance-drawer-field",children:[t.jsx("dt",{children:"Status"}),t.jsx("dd",{children:t.jsx(pj,{status:r.ocrStatus})})]}):null,p?t.jsxs(t.Fragment,{children:[t.jsx(Ej,{label:"Source",value:"PDF text layer"}),t.jsx(Ej,{label:"Synchronization",value:"Not yet synchronized to Wikibase"}),t.jsx(Ej,{label:"Classification",value:r?.classification}),t.jsx(Ej,{label:"Extractor",value:m.engine}),t.jsx(Ej,{label:"Extractor version",value:m.engineVersion}),t.jsx(Ej,{label:"Source binary identity",value:r?.sourceBinaryIdentity})]}):t.jsxs(t.Fragment,{children:[t.jsx(Ej,{label:"Correction state",value:r?.correctionState}),t.jsx(Ej,{label:"Source revision",value:r?.sourceRevision}),t.jsx(Ej,{label:"Engine",value:m.engine}),t.jsx(Ej,{label:"Engine version",value:m.engineVersion}),t.jsx(Ej,{label:"Model",value:m.model})]}),t.jsx(Ej,{label:"Text checksum",value:r?.ocrChecksum}),t.jsx(Ej,{label:"Source page checksum",value:r?.sourcePageChecksum}),p?null:t.jsxs(t.Fragment,{children:[t.jsx(Ej,{label:"Produced at",value:Rj(m.producedAt)}),t.jsx(Ej,{label:"Projected at",value:Rj(r?.projectedAt)})]})]})]}),t.jsx(Cj,{entities:i}),u]})}const _j=Object.freeze({ENTITY_MENTION:"entity_mention",PERSONAL_NAME:"personal_name",PERSON:"person",PLACE:"place",RULER:"ruler",PERIOD:"period",LEMMA:"lemma",LANGUAGE_FEATURE:"language_feature"}),Tj=Object.freeze({[_j.ENTITY_MENTION]:"Entity",[_j.PERSONAL_NAME]:"Personal name",[_j.PERSON]:"Person",[_j.PLACE]:"Place",[_j.RULER]:"Ruler",[_j.PERIOD]:"Period",[_j.LEMMA]:"Lemma",[_j.LANGUAGE_FEATURE]:"Language feature"}),Aj=Object.freeze({PEOPLE:"people",PLACES:"places",OTHER_ENTITIES:"other_entities",LINGUISTIC:"linguistic"}),Oj=Object.freeze({[Aj.PEOPLE]:"People & personal names",[Aj.PLACES]:"Places",[Aj.OTHER_ENTITIES]:"Other entities",[Aj.LINGUISTIC]:"Linguistic annotations"}),Dj=Object.freeze({[_j.PERSONAL_NAME]:Aj.PEOPLE,[_j.PERSON]:Aj.PEOPLE,[_j.RULER]:Aj.PEOPLE,[_j.PLACE]:Aj.PLACES,[_j.LEMMA]:Aj.LINGUISTIC,[_j.LANGUAGE_FEATURE]:Aj.LINGUISTIC});function Pj(e){return Dj[e]||Aj.OTHER_ENTITIES}const Lj=Object.freeze({MACHINE:"machine",HUMAN:"human",UNKNOWN:"unknown"}),$j=Object.freeze({UNREVIEWED:"unreviewed",ACCEPTED:"accepted",CORRECTED:"corrected",REJECTED:"rejected",SUPERSEDED:"superseded"}),Mj=Object.freeze({MACHINE_UNREVIEWED:"Machine suggested",MACHINE_ACCEPTED:"Human confirmed",MACHINE_CORRECTED:"Human corrected",MACHINE_REJECTED:"Rejected",MACHINE_SUPERSEDED:"Superseded",HUMAN:"Human reviewed",UNKNOWN_SOURCE:"Source unavailable"}),Uj=Object.freeze({[$j.UNREVIEWED]:"Unreviewed",[$j.ACCEPTED]:"Human confirmed",[$j.CORRECTED]:"Human corrected",[$j.REJECTED]:"Rejected",[$j.SUPERSEDED]:"Superseded"}),Fj=Object.freeze({UTF16:"utf16",UNICODE_CODEPOINT:"unicode_codepoint"}),zj=Fj.UNICODE_CODEPOINT,qj=Object.freeze({STALE_TEXT:"stale_text",INVALID_RANGE:"invalid_range",OUT_OF_BOUNDS:"out_of_bounds",MISSING_SPAN:"missing_span"}),Bj=Object.freeze({ALL:"all",PEOPLE:"people",PLACES:"places",LINGUISTIC:"linguistic",REVIEWED:"reviewed",MACHINE:"machine"}),Wj=Object.freeze({[Bj.ALL]:"All",[Bj.PEOPLE]:"People",[Bj.PLACES]:"Places",[Bj.LINGUISTIC]:"Linguistic",[Bj.REVIEWED]:"Reviewed",[Bj.MACHINE]:"Machine suggestions"}),Vj=Object.freeze({MISSING_DOCUMENT_ID:"MISSING_DOCUMENT_ID",INVALID_PAGE_
2NUMBER:"INVALID_PAGE_NUMBER",NOT_FOUND:"NOT_FOUND",UNAUTHORIZED:"UNAUTHORIZED",NETWORK_ERROR:"NETWORK_ERROR",SERVER_ERROR:"SERVER_ERROR",INVALID_RESPONSE:"INVALID_RESPONSE",REQUEST_CANCELLED:"REQUEST_CANCELLED",UNKNOWN:"ANNOTATION_REQUEST_FAILED"});function Hj(e){const t=[];if("string"!=typeof e)return[0];for(let a=0;a<e.length;){t.push(a);a+=e.codePointAt(a)>65535?2:1}return t.push(e.length),t}function Kj(e,t,{text:a,table:n}={}){if(!Number.isInteger(e)||e<0)return null;if("string"!=typeof a)return null;if(t===Fj.UTF16)return e<=a.length?e:null;const s=n||Hj(a);return e<s.length?s[e]:null}function Gj(e,{text:t,table:a}={}){if(!e||!Number.isInteger(e.start)||!Number.isInteger(e.end))return{ok:!1,reason:qj.MISSING_SPAN};if(e.start<0||e.end<=e.start)return{ok:!1,reason:qj.INVALID_RANGE};if("string"!=typeof t||0===t.length)return{ok:!1,reason:qj.OUT_OF_BOUNDS};const n=e.offsetEncoding||zj,s=n===Fj.UTF16?null:a||Hj(t),r=Kj(e.start,n,{text:t,table:s}),i=Kj(e.end,n,{text:t,table:s});return null===r||null===i?{ok:!1,reason:qj.OUT_OF_BOUNDS}:i<=r?{ok:!1,reason:qj.INVALID_RANGE}:{ok:!0,start:r,end:i}}const Jj=Object.freeze({IDLE:"idle",LOADING:"loading",READY:"ready",ERROR:"error"}),Yj=Object.freeze({status:Jj.IDLE,set:null,error:null});function Qj({documentId:t,pageNumber:a,repository:n,pageText:s="",currentTextChecksum:r=null,enabled:i=!0}){const[l,o]=e.useState(Yj),c=e.useRef(0);e.useEffect(()=>{if(!(i&&t&&a&&n))return void o(Yj);const e=++c.current,s="undefined"!=typeof AbortController?new AbortController:null,r=n.peekCachedAnnotations?.(t,a);return o(r?{status:Jj.READY,set:r,error:null}:{status:Jj.LOADING,set:null,error:null}),n.getPageAnnotations(t,a,{signal:s?.signal}).then(t=>{c.current===e&&o({status:Jj.READY,set:t,error:null})}).catch(t=>{c.current===e&&"AbortError"!==t?.name&&"REQUEST_CANCELLED"!==t?.code&&o("NOT_FOUND"!==t?.code?{status:Jj.ERROR,set:null,error:t}:{status:Jj.READY,set:null,error:null})}),()=>{s?.abort()}},[t,a,n,i]);const d=e.useMemo(()=>function(e,{pageText:t="",currentTextChecksum:a=null}={}){const n=e?.annotations||[];if(0===n.length)return{isStale:!1,annotations:[],highlightSpans:[]};const s=function({sourceTextChecksum:e,currentTextChecksum:t}={}){return!(!e||!t)&&e!==t}({sourceTextChecksum:e?.sourceTextChecksum,currentTextChecksum:a}),r="string"==typeof t&&t.length>0?Hj(t):null,i=[],l=[];for(const o of n){if(s){i.push({...o,resolvedSpan:null,spanUnavailableReason:qj.STALE_TEXT});continue}const e=Gj(o.span,{text:t,table:r});e.ok?(i.push({...o,resolvedSpan:{start:e.start,end:e.end},spanUnavailableReason:null}),l.push({id:o.id,start:e.start,end:e.end})):i.push({...o,resolvedSpan:null,spanUnavailableReason:e.reason})}return{isStale:s,annotations:i,highlightSpans:l}}(l.set,{pageText:s,currentTextChecksum:r}),[l.set,s,r]);return{status:l.status,error:l.error,annotationSet:l.set,annotations:d.annotations,highlightSpans:d.highlightSpans,isStale:d.isStale}}function Xj(e){return e.sourceType===Lj.HUMAN||e.reviewStatus===$j.ACCEPTED||e.reviewStatus===$j.CORRECTED?"human":e.reviewStatus===$j.REJECTED||e.reviewStatus===$j.SUPERSEDED||e.sourceType===Lj.UNKNOWN?"muted":"machine"}function Zj({provenance:e}){return e?t.jsx("span",{className:`annotation-provenance annotation-provenance--${Xj(e)}`,children:e.label}):null}function ey({annotation:e,isSelected:a,onSelect:n,id:s}){const{entity:r,linguistic:i,provenance:l}=e,o="number"==typeof l?.confidence;return t.jsx("li",{className:"annotation-list-item",children:t.jsxs("button",{type:"button",id:s,className:"annotation-item "+(a?"annotation-item--selected":""),"aria-pressed":a,onClick:()=>n(e.id),children:[t.jsxs("span",{className:"annotation-item-main",children:[t.jsx("span",{className:"annotation-item-label",children:e.displayLabel}),t.jsx("span",{className:"annotation-item-kind",children:e.kindLabel})]}),t.jsxs("span",{className:"annotation-item-meta",children:[t.jsx(Zj,{provenance:l}),r?.qid?t.jsx("span",{className:"annotation-item-qid",title:r.qid,children:r.qid}):t.jsx("span",{className:"annotation-item-unlinked",children:"No linked entity"}),i?.lemma?t.jsxs("span",{className:"annotation-item-lemma",children:["Lemma: ",i.lemma,i.partOfSpeech?` · ${i.partOfSpeech}`:""]}):null,o?t.jsxs("span",{className:"annotation-item-confidence",children:["Model confidence ",Math.round(100*l.confidence),"%"]}):null,e.spanUnavailableReason?t.jsx("span",{className:"annotation-item-span-warning",children:"Text location unavailable"}):null]})]})})}function ty({annotation:e,mentionCount:a,onClose:n}){if(!e)return null;const{entity:s,linguistic:r,provenance:i}=e,l=s&&!s.linkConfirmedByHuman;return t.jsxs("section",{className:"annotation-detail","aria-label":"Selected annotation details",children:[t.jsxs("div",{className:"annotation-detail-header",children:[t.jsx("h4",{className:"annotation-detail-title",children:e.displayLabel}),t.jsx("button",{type:"button",className:"annotation-detail-close",onClick:n,"aria-label":"Clear annotation selection",children:"Ã"})]}),t.jsxs("dl",{className:"annotation-detail-fields",children:[t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Type"}),t.jsx("dd",{children:e.kindLabel})]}),e.surface?t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Surface form"}),t.jsx("dd",{className:"annotation-detail-surface",children:e.surface})]}
2):null,s?.qid?t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Wikibase QID"}),t.jsxs("dd",{children:[t.jsx("span",{className:"annotation-detail-qid",children:s.qid}),t.jsx("span",{className:"annotation-detail-link-provenance",children:l?"Machine-proposed link":"Human-confirmed link"})]})]}):t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Wikibase QID"}),t.jsx("dd",{className:"annotation-detail-unlinked",children:"Not linked to a Wikibase entity"})]}),s?.description?t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Description"}),t.jsx("dd",{children:s.description})]}):null,r?t.jsxs(t.Fragment,{children:[r.lemma?t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Lemma"}),t.jsx("dd",{children:r.lemma})]}):null,r.partOfSpeech?t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Part of speech"}),t.jsx("dd",{children:r.partOfSpeech})]}):null,r.language?t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Language"}),t.jsxs("dd",{children:[r.language,r.dialect?` · ${r.dialect}`:""]})]}):null]}):null,t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Mentions on this page"}),t.jsx("dd",{children:a})]}),t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Source"}),t.jsx("dd",{children:t.jsx(Zj,{provenance:i})})]}),i?.sourceType===Lj.MACHINE&&i.modelId?t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Model"}),t.jsxs("dd",{children:[i.modelId,i.modelVersion?` · ${i.modelVersion}`:""]})]}):null,"number"==typeof i?.confidence?t.jsxs("div",{className:"annotation-detail-field",children:[t.jsx("dt",{children:"Model confidence"}),t.jsxs("dd",{children:[Math.round(100*i.confidence),"%",t.jsx("span",{className:"annotation-detail-confidence-note",children:"Model confidence only â not an assessment of historical accuracy."})]})]}):null]})]})}const ay=[Aj.PEOPLE,Aj.PLACES,Aj.OTHER_ENTITIES,Aj.LINGUISTIC],ny=[Bj.ALL,Bj.PEOPLE,Bj.PLACES,Bj.LINGUISTIC,Bj.REVIEWED,Bj.MACHINE];function sy(e){return"UNAUTHORIZED"===e?.code?"Your session has expired. Please sign in again.":"NETWORK_ERROR"===e?.code?"Could not reach the annotation service.":"Entities and annotations could not be loaded for this page."}function ry({status:a,error:n,annotations:s,isStale:r,selectedId:i,onSelectAnnotation:l,onClearSelection:o,selectedAnnotation:c,headingId:d="annotations-panel-title"}){const[u,h]=e.useState(Bj.ALL),m=e.useMemo(()=>s.filter(e=>function(e,t){switch(t){case Bj.PEOPLE:return e.group===Aj.PEOPLE;case Bj.PLACES:return e.group===Aj.PLACES;case Bj.LINGUISTIC:return e.group===Aj.LINGUISTIC;case Bj.REVIEWED:return e.provenance.sourceType===Lj.HUMAN||e.provenance.reviewStatus===$j.ACCEPTED||e.provenance.reviewStatus===$j.CORRECTED;case Bj.MACHINE:return e.provenance.sourceType===Lj.MACHINE;case Bj.ALL:default:return!0}}(e,u)),[s,u]),p=e.useMemo(()=>{const e=new Map;for(const t of m)e.has(t.group)||e.set(t.group,[]),e.get(t.group).push(t);return e},[m]),g=e.useMemo(()=>{if(!c)return 0;const e=c.entity?.qid;return e?s.filter(t=>t.entity?.qid===e).length:1},[c,s]),f=m.length>=3;return t.jsxs("section",{className:"annotations-panel","aria-labelledby":d,"data-testid":"annotations-panel",children:[t.jsxs("div",{className:"annotations-panel-header",children:[t.jsx("h4",{id:d,children:"Entities & Annotations"}),s.length>0?t.jsx("span",{className:"annotations-panel-count",children:s.length}):null]}),t.jsx("p",{className:"annotations-panel-disclaimer",children:"Machine-generated annotations are research suggestions, not curated scholarly claims."}),r?t.jsx("p",{className:"annotations-panel-stale",role:"status",children:"This page's text has changed since these annotations were generated, so their positions in the text are no longer reliable. Details remain available below, but nothing is highlighted."}):null,a===Jj.LOADING?t.jsx("p",{className:"annotations-panel-loading",role:"status",children:"Loading entities and annotationsâ¦"}):null,a===Jj.ERROR?t.jsx("p",{className:"annotations-panel-error",role:"alert",children:sy(n)}):null,a===Jj.READY&&0===s.length?t.jsx("p",{className:"annotations-panel-empty",children:"No entities or annotations available for this page."}):null,s.length>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"annotations-panel-filters",role:"group","aria-label":"Filter annotations on this page",children:ny.map(e=>t.jsx("button",{type:"button",className:"annotations-filter "+(u===e?"annotations-filter--active":""),"aria-pressed":u===e,onClick:()=>h(e),children:Wj[e]},e))}),0===m.length?t.jsx("p",{className:"annotations-panel-empty",children:"No annotations match this filter."}):f?ay.filter(e=>p.has(e)).map(e=>t.jsxs("div",{className:"annotations-panel-group",children:[t.jsx("h5",{className:"annotations-panel-group-title",children:Oj[e]}),t.jsx("ul",{className:"annotation-list",children:p.get(e).map(e=>t.jsx(ey,{id:`annotation-item-${e.id}`,annotation:e,isSelected:e.id===i,onSelect:l},e.id))})]},e)):t.jsx("ul",{className:"annotation-list",children:m.map(e=>t.jsx(ey,{id:`annotation-item-${e.id}`,annotation:e,isSelected:e.id===i,onSelect:l},e.id))}),t.jsx("p",{className:"annotations-panel-live","aria-live":"polite",children:c?`Selected ${c.kindLabel}: ${c.displayLabel}. ${c.provenance.label}.`:""}),t.jsx(ty,{annotation:c,mentionCount:g,onClose:o})]}):null]})}const iy=[["harassment","Harassment"],["spam","Spam"],["impersonation","Impersonation"],["privacy","Privacy concern"],["abusive_content","Abusive content"],["unsafe_contact","Unsafe contact"],["other","Other"]];function ly({isOpen:a,onClose:n,repository:s,targetType:r,targetId:i}){const[l,o]=e.useState("harassment"),[c,d]=e.useState(""),[u,h]=e.useState("idle"),[m,p]=e.useState("");e.useEffect(()=>{a&&(o("harassment"),d(""),h("idle"),p(""))},[a,i]);return t.jsx(Ss,{isOpen:a,onClose:n,title:"Report safety concern",size:"small",children:"saved"===u?t.jsxs("div",{className:"social-report-confirmation",role:"status",children:[t.jsx("p",{children:"Your report was submitted privately for moderation review."}),t.jsx("button",{type:"button",onClick:n,children:"Done"})]}):t.jsxs("form",{className:"social-report-form",onSubmit:async e=>{e.preventDefault(),h("saving"),p("");try{await s.reportSocialTarget(r,i,l,c),h("saved")}catch(t){p(t.message||"The report could not be submitted."),h("error")}},children:[t.jsx("p",{children:"Reports are private. The reported person is not notified and cannot see who submitted the report."}),t.jsxs("label",{children:["Reason",t.jsx("select",{value:l,onCh
2ange:e=>o(e.target.value),children:iy.map(([e,a])=>t.jsx("option",{value:e,children:a},e))})]}),t.jsxs("label",{children:["Details (optional)",t.jsx("textarea",{value:c,maxLength:2e3,rows:5,onChange:e=>d(e.target.value),"aria-describedby":"social-report-details-help"})]}),t.jsxs("div",{id:"social-report-details-help",className:"social-form-help",children:["Add only information needed to understand the concern. ",c.length,"/2000"]}),m?t.jsx("div",{className:"social-form-error",children:m}):null,t.jsxs("div",{className:"social-form-actions",children:[t.jsx("button",{type:"button",onClick:n,children:"Cancel"}),t.jsx("button",{type:"submit",disabled:"saving"===u,children:"saving"===u?"Submittingâ¦":"Submit private report"})]})]})})}function oy({repository:a,targetType:n,targetKey:s,label:r}){const[i,l]=e.useState(!1),[o,c]=e.useState([]),[d,u]=e.useState(""),[h,m]=e.useState("idle"),[p,f]=e.useState("");e.useEffect(()=>{if(!i||!a)return;const e=new AbortController;return m("loading"),a.list({status:"active",limit:100,signal:e.signal}).then(e=>{const t=(e.items||[]).filter(e=>e.permissions?.canAddItems);c(t),u(e=>e||t[0]?.id||""),m("ready")}).catch(e=>{"REQUEST_CANCELLED"!==e.code&&(f(e.message||"Workspaces are unavailable"),m("error"))}),()=>e.abort()},[i,a]);return a&&s?t.jsxs("div",{className:"add-to-workspace-control",children:[t.jsxs(ds,{variant:"secondary",size:"small",onClick:()=>{l(e=>!e),f("")},"aria-expanded":i,children:[t.jsx(K,{size:15}),r||"Add to Workspace"]}),i?t.jsxs("div",{className:"add-to-workspace-popover",role:"group","aria-label":"Choose workspace",children:[t.jsxs("select",{value:d,onChange:e=>u(e.target.value),disabled:"loading"===h||"saving"===h,"aria-label":"Research workspace",children:[0===o.length?t.jsx("option",{value:"",children:"No writable workspaces"}):null,o.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]}),t.jsx("button",{type:"button",onClick:async()=>{if(d&&s&&"saving"!==h){m("saving"),f("");try{await a.addItem(d,n,s),f("Added"),m("saved")}catch(e){f(e.message||"Could not add item"),m("error")}}},disabled:!d||"saving"===h,"aria-label":"Add research item",children:t.jsx(Ve,{size:16})}),t.jsx("button",{type:"button",onClick:()=>l(!1),"aria-label":"Close workspace picker",children:t.jsx(g,{size:16})}),p?t.jsx("span",{role:"status",children:p}):null]}):null]}):null}function cy(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(t)}function dy(e){return"undefined"!=typeof crypto&&crypto.randomUUID?`${e}:${crypto.randomUUID()}`:`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function uy({repository:a,targetType:n,targetKey:s,targetLabel:r,initialDiscussionId:i,readOnly:l=!1,workspaceRepository:o}){const{user:c}=Yn(),[d,u]=e.useState([]),[h,m]=e.useState(i||null),[p,f]=e.useState(null),[b,x]=e.useState("loading"),[v,j]=e.useState("idle"),[y,k]=e.useState(""),[w,N]=e.useState(""),[S,C]=e.useState(""),[R,E]=e.useState(""),[I,_]=e.useState(!1),[T,A]=e.useState(null),[O,D]=e.useState(!1),P=e.useMemo(()=>({targetType:n,targetKey:s,limit:20}),[n,s]),L=e.useCallback(async e=>{if(!a||!n||!s)return u([]),void x("idle");x("loading"),k("");try{const t=(await a.listDiscussions({...P,signal:e})).items||[];u(t),m(e=>e||t[0]?.id||null),x("ready")}catch(t){if("REQUEST_CANCELLED"===t.code)return;k(t.message||"Failed to load discussions"),x("error")}},[a,s,P,n]),$=e.useCallback(async(e,t)=>{if(!a||!e)return f(null),void j("idle");j("loading");try{const n=await a.getDiscussion(e,{signal:t});f(n),j("ready")}catch(n){if("REQUEST_CANCELLED"===n.code)return;f(null),j("error")}},[a]);e.useEffect(()=>{m(i||null)},[i,s,n]),e.useEffect(()=>{const e=new AbortController;return L(e.signal),()=>e.abort()},[L]),e.useEffect(()=>{const e=new AbortController;return $(h,e.signal),()=>e.abort()},[$,h]);const M=async e=>{if(e.preventDefault(),S.trim()&&!I){_(!0),k("");try{const e=await a.createDiscussion({targetType:n,targetKey:s,title:w,body:S,operationId:dy("discussion-create")});N(""),C(""),D(!1),m(e.discussion.id),await L(),f(e)}catch(t){k(t.message||"Failed to create discussion")}finally{_(!1)}}},U=p?.discussion||d.find(e=>e.id===h),F=p?.messages||[],z="resolved"===U?.status;return t.jsxs("section",{className:"research-discussion-panel","aria-label":"Scholarly discussions","aria-busy":"loading"===b||"loading"===v||I,children:[t.jsxs("div",{className:"research-discussion-panel-header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Discussions"}),t.jsx("p",{children:r})]}),!l&&d.length>0?t.jsxs(ds,{variant:"secondary",size:"small",type:"button",onClick:()=>D(e=>!e),"aria-expanded":O,children:[O?t.jsx(g,{size:15}):t.jsx(Z,{size:15}),O?"Cancel":"New thread"]}):t.jsx(le,{size:20,"aria-hidden":"true"})]}),y?t.jsx("div",{className:"research-discussion-error",role:"alert",children:y}):null,"loading"===b?t.jsx("div",{className:"research-discussion-state",children:"Loading..."}):null,"error"===b?t.jsx("div",{className:"research-discussion-state",children:"Discussions are unavailable."}):null,t.jsxs("div",{className:"research-discussion-grid",children:[t.jsxs("div",{className:"research-discussion-list","aria-label":"Discussion threads",children:[0===d.length&&"ready"===b?t.jsx("div",{className:"research-discussion-state",children:"No discussions yet."}):null,d.map(e=>t.jsxs("button",{type:"button",className:e.id===h?"is-active":"",onClick:()=>m(e.id),children:[t.jsx("strong",{children:e.title||"Untitled discussion"}),t.jsxs("span",{children:[e.status," · ",e.messageCount," messages"]})]},e.id))]}),t.jsxs("div",{className:"research-discussion-detail",children:["loading"===v?t.jsx("div",{className:"research-discussion-state",children:"Loading thread..."}):null,U?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"research-discussion-detail-header",children:[t.jsxs("div",{children:[t.jsx("h4",{children:U.title||"Untitled discussion"}),t.jsxs("span",{children:[U.createdBy?.displayName||"Researcher"," ·"," ",cy(U.createdAt)]})]}),t.jsxs("div",{className:"research-discussion-detail-actions",children:[t.jsx(oy,{repository:o,targetType:"discussion",targetKey:U.id,label:"Add to Workspace"}),l?null:t.jsxs(ds,{variant:"secondary",size:"small",disabled:I,onClick:()=>(async e=>{if(h&&!I){_(!0),k("");try{const t=await a.updateDiscussionStatus(h,e,{operationId:dy(`discussion-${e}`)});f(t),await L()}catch(t){k(t.message||"Failed to update discussion")}finally{_(!1)}}})(z?"open":"resolved"),children:[z?t.jsx(Me,{size:15}):t.jsx(pe,{size:15}),z?"Reopen":"Resolve"]})]})]}),t.jsx("div",{className:"research-discussion-messages",children:F.map(e=>t.jsxs("article",{className:"research-discussion-message",children:[t.jsxs("div",{children:[t.jsxs("span",{children:[t.jsx("strong",{children:e.author?.displayName||"Researcher"}),t.jsx("span",{children:cy(e.createdAt)})]}),e.author?.userId&&e.author.userId!==c?.id?t.jsxs("button",{type:"button",className:"research-discussion-report",onClick:()=>A(e.id),children:[t.jsx(At,{size:13}),"Report"]}):null]}),t.jsx("p",{children:e.body}),e.mentions?.length?t.jsx("div",{className:"research-discussion-mentions",children:e.mentions.map(e=>t.jsxs("span",{children:["@",e.slug||e.displayName]}
2,e.userId))}):null]},e.id))}),l?null:t.jsxs("form",{className:"research-discussion-form",onSubmit:async e=>{if(e.preventDefault(),h&&R.trim()&&!I){_(!0),k("");try{const e=await a.replyToDiscussion(h,{body:R,operationId:dy("discussion-reply")});E(""),f(e),await L()}catch(t){k(t.message||"Failed to reply")}finally{_(!1)}}},children:[t.jsx("textarea",{value:R,onChange:e=>E(e.target.value),maxLength:12e3,rows:3,disabled:z,placeholder:z?"Reopen to reply":"Reply with scholarly context","aria-label":"Discussion reply"}),t.jsxs(ds,{variant:"primary",size:"small",type:"submit",disabled:I||z||!R.trim(),children:[t.jsx(oe,{size:15}),"Reply"]})]})]}):l?null:t.jsxs("form",{className:"research-discussion-form",onSubmit:M,children:[t.jsx("input",{value:w,onChange:e=>N(e.target.value),maxLength:240,placeholder:"Discussion title","aria-label":"Discussion title"}),t.jsx("textarea",{value:S,onChange:e=>C(e.target.value),maxLength:12e3,rows:4,placeholder:"Start a target-bound scholarly discussion","aria-label":"Opening discussion message"}),t.jsxs(ds,{variant:"primary",size:"small",type:"submit",disabled:I||!S.trim(),children:[t.jsx(oe,{size:15}),"Start discussion"]})]})]})]}),U&&!l&&O?t.jsxs("form",{className:"research-discussion-form research-discussion-new",onSubmit:M,"aria-label":"Create another discussion thread",children:[t.jsx("input",{value:w,onChange:e=>N(e.target.value),maxLength:240,placeholder:"New thread title","aria-label":"New thread title"}),t.jsx("textarea",{value:S,onChange:e=>C(e.target.value),maxLength:12e3,rows:3,placeholder:"Open another discussion on this target","aria-label":"Opening message for new thread"}),t.jsxs(ds,{variant:"secondary",size:"small",type:"submit",disabled:I||!S.trim(),children:[t.jsx(oe,{size:15}),"New thread"]})]}):null,t.jsx(ly,{isOpen:Boolean(T),onClose:()=>A(null),repository:a,targetType:"research_discussion_message",targetId:T})]})}function hy({targetType:a,targetKey:n,canonicalPath:s,label:r="Share",onAddToWorkspace:i=null}){const o=Yn({required:!1}),[c,d]=e.useState(!1),[u,h]=e.useState(!1),m=e.useRef(null),p=e.useRef(null),g=e.useRef(null);e.useEffect(()=>{if(!c)return;const e=e=>{m.current?.contains(e.target)||d(!1)},t=e=>{const t=[...g.current?.querySelectorAll('[role="menuitem"]')||[]],a=t.indexOf(document.activeElement);"Escape"===e.key?(e.preventDefault(),d(!1),p.current?.focus()):"ArrowDown"===e.key&&t.length?(e.preventDefault(),t[(a+1+t.length)%t.length].focus()):"ArrowUp"===e.key&&t.length&&(e.preventDefault(),t[(a-1+t.length)%t.length].focus())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),g.current?.querySelector('[role="menuitem"]')?.focus(),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[c]);return t.jsxs("div",{className:"community-share-menu",ref:m,children:[t.jsxs("button",{ref:p,className:"community-share-trigger",type:"button","aria-haspopup":"menu","aria-expanded":c,onClick:()=>d(e=>!e),children:[t.jsx(Ot,{size:17,"aria-hidden":"true"}),u?"Link copied":r]}),c?t.jsxs("div",{className:"community-share-menu-popover",role:"menu",ref:g,children:[t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{(async()=>{const e=new URL(s,window.location.origin).toString();if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(e);else{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),t.remove()}h(!0),d(!1),window.setTimeout(()=>h(!1),1800)})()},children:[t.jsx(Ge,{size:16,"aria-hidden":"true"})," Copy Link"]}),o?.canAccessCommunityMessagingPreview?.()?t.jsxs(l,{role:"menuitem",to:`/community/messages?shareType=${encodeURIComponent(a)}&shareKey=${encodeURIComponent(n)}`,onClick:()=>d(!1),children:[t.jsx($e,{size:16,"aria-hidden":"true"})," Send in Message"]}):null,i?t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{d(!1),i()},children:[t.jsx(K,{size:16,"aria-hidden":"true"})," Add to Workspace"]}):null]}):null]})}const my="annotation",py="entity",gy=/^[A-Za-z0-9][A-Za-z0-9._:-]*$/;function fy(e){if("string"!=typeof e)return null;const t=e.trim();return 0===t.length||t.length>64?null:gy.test(t)?t:null}function by(e,{annotationId:t,entityQid:a=null}){const n=new URLSearchParams(e);return t?n.set(my,t):n.delete(my),a&&!t?n.set(py,a):n.delete(py),n}function xy({annotations:t,pageNumber:a}){const[n,s]=c(),r=fy(n.get(my));const i=function(e){return fy(e)}(n.get(py)),l=e.useMemo(()=>function({annotationParam:e,entityParam:t},a){const n=Array.isArray(a)?a:[];if(0===n.length)return null;if(e){const t=n.find(t=>
2t.id===e);if(t)return t.id}if(t){const e=n.find(e=>e.entity?.qid===t);if(e)return e.id}return null}({annotationParam:r,entityParam:i},t),[r,i,t]),o=e.useRef(a);e.useEffect(()=>{o.current!==a&&(o.current=a,(r||i)&&s(e=>by(e,{annotationId:null,entityQid:null}),{replace:!0}))},[a,s]);const d=e.useCallback(e=>{s(t=>by(t,{annotationId:e===l?null:e}),{replace:!0})},[l,s]),u=e.useCallback(()=>{s(e=>by(e,{annotationId:null,entityQid:null}),{replace:!0})},[s]),h=e.useMemo(()=>l&&t.find(e=>e.id===l)||null,[l,t]);return{selectedId:l,selectedAnnotation:h,selectAnnotation:d,clearSelection:u}}function vy({documentId:a,metadata:n,summary:s,currentPage:r,onOpenPage:i,onClose:l}){const o=Ds(),[c,d]=e.useState(!1),[u,h]=e.useState(0),m=s?.pages||[],p=Math.max(1,Math.ceil(m.length/25)),g=Math.min(u,p-1),f=m.slice(25*g,25*(g+1));if(e.useEffect(()=>{h(0)},[s?.sourceBinaryIdentity,s?.pageCount]),!s)return null;const b=()=>JSON.stringify(function({documentId:e,metadata:t,summary:a}){return{generatedAt:(new Date).toISOString(),documentId:e,title:t?.title||null,source:"PDF text preview",sourceType:a.sourceType,authoritative:!1,synchronizedToWikibase:!1,extractor:a.extractor,extractorVersion:a.extractorVersion,sourceBinaryIdentity:a.sourceBinaryIdentity,pageCount:a.pageCount,counts:{pagesWithText:a.pagesWithText,pagesWithoutText:a.pagesWithoutText,sparsePages:a.sparsePages,likelyGarbledPages:a.likelyGarbledPages,extractionFailures:a.extractionFailures,totalExtractedCharacters:a.totalExtractedCharacters},pages:a.pages.map(e=>({pageNumber:e.pageNumber,hasText:e.hasText,characterCount:e.characterCount,classification:e.classification,textChecksum:e.textChecksum,pageChecksum:e.pageChecksum,previewCharacterCount:e.preview.length,fullTextOmitted:!0}))}}({documentId:a,metadata:n,summary:s}),null,2);return t.jsxs("section",{className:"pdf-text-preview-qa","aria-label":"PDF text preview QA",children:[t.jsxs("div",{className:"pdf-text-preview-qa-header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"PDF text preview"}),t.jsx("p",{children:"Extracted from the existing PDF text layer. Not yet synchronized to Wikibase."})]}),t.jsxs("div",{className:"pdf-text-preview-qa-actions",children:[t.jsxs(ds,{variant:"ghost",size:"small",onClick:async()=>{try{if(!navigator?.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(b()),d(!0),o?.({type:"success",message:"QA report copied."}),window.setTimeout(()=>d(!1),2e3)}catch{o?.({type:"error",message:"Could not copy QA report."})}},ariaLabel:"Copy PDF text preview QA report",children:[c?t.jsx(Ve,{size:14}):t.jsx(Ge,{size:14}),t.jsx("span",{className:"research-viewer-toolbar-label",children:c?"Copied":"Copy report"})]}),t.jsxs(ds,{variant:"ghost",size:"small",onClick:()=>{const e=new Blob([b()],{type:"application/json"}),t=URL.createObjectURL(e),n=document.createElement("a");n.href=t,n.download=`pdf-text-preview-${a||"document"}.json`,n.rel="noopener",n.style.display="none",document.body.appendChild(n),n.click(),n.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),0)},ariaLabel:"Download PDF text preview QA report",children:[t.jsx(Je,{size:14}),t.jsx("span",{className:"research-viewer-toolbar-label",children:"Download report"})]}),t.jsx(ds,{variant:"ghost",size:"small",onClick:l,ariaLabel:"Close text QA",children:"Close"})]})]}),t.jsxs("div",{className:"pdf-text-preview-qa-stats","aria-label":"PDF text preview counts",children:[t.jsxs("span",{children:[s.pageCount," pages"]}),t.jsxs("span",{children:[s.pagesWithText," with text"]}),t.jsxs("span",{children:[s.pagesWithoutText," without text"]}),t.jsxs("span",{children:[s.sparsePages," sparse"]}),t.jsxs("span",{children:[s.likelyGarbledPages," garbled"]})]}),t.jsx("div",{className:"pdf-text-preview-qa-pages",children:f.map(e=>{return t.jsxs("div",{className:"pdf-text-preview-qa-row"+(e.pageNumber===r?" is-current":""),children:[t.jsxs("div",{className:"pdf-text-preview-qa-page-main",children:[t.jsxs("span",{className:"pdf-text-preview-qa-page-number",children:["Page ",e.pageNumber]}),t.jsx("span",{className:"pdf-text-preview-qa-classification",children:(a=e.classification,String(a||"unknown").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))}),t.jsxs("span",{children:[e.characterCount," chars"]})]}),t.jsx("p",{className:"pdf-text-preview-qa-preview",children:e.preview||"No embedded text detected."}),t.jsxs("div",{className:"pdf-text-preview-qa-page-meta",children:[e.textChecksum?t.jsxs("span",{children:["Text checksum ",e.textChecksum]}):null,t.jsx(ds,{variant:e.pageNumber===r?"secondary":"ghost",size:"small",onClick:()=>i(e.pageNumber),ariaLabel:`Open page ${e.pageNumber}`,children:"Open page"}),e.pageNumber===r?t.jsx("span",{className:"pdf-text-preview-qa-current-page",children:"Current page"}):null]})]},e.pageNumber);var a})}),p>1?t.jsxs("div",{className:"pdf-text-preview-qa-pagination",children:[t.jsx(ds,{variant:"ghost",size:"small",disabled:0===g,onClick:()=>h(e=>Math.max(0,e-1)),children:"Previous"}),t.jsxs("span",{children:["Pages ",25*g+1,"-",25*g+f.length," of ",m.length]}),t.jsx(ds,{variant:"ghost",size:"small",disabled:g>=p-1,onClick:()=>h(e=>Math.min(p-1,e+1)),children:"Next"})]}):null]})}function jy({documentId:a,metadata:n,totalPagesHint:s,onPageChange:r,repository:i,annotationRepository:l,discussionRepository:o,workspaceRepository:d,entities:u,documentUrl:h,documentData:m,requestHeaders:p,ocrOverlayUrl:g,onLoadError:f,onDownload:b,downloadBusy:x,downloadDisabled:v,showInternalErrors:j,fitToViewport:y,pdfClassName:k,previewRepository:w,canEditResearchData:N=!1,customerMode:S=!1,pageTextSyncStatus:C=null,onDirtyChange:R,onSavePendingChange:E}){const I={className:k,documentUrl:h,documentData:m,requestHeaders:p,ocrOverlayUrl:g,onLoadError:f,onDownload:b,downloadBusy:x,downloadDisabled:v,showInternalErrors:j,fitToViewport:y,showPageControls:!S,ocrOverlayIsOriginalSnapshot:S},{summaries:_,getSummary:T}=function(t,a){const[n,s]=e.useState([]),[r,i]=e.useState("idle"),l=e.useRef(0);e.useEffect(()=>{if(!t||!a)return s([]),void i("idle");const e=++l.current,n="undefined"!=typeof AbortController?new AbortController:null;return i("loading"),a.listPages(t,{signal:n?.signal}).then(t=>{l.current===e&&(s(t),i("ready"))}).catch(t=>{l.current===e&&"AbortError"!==t?.name&&i("error")}),()=>{n?.abort()}},[t,a]);const o=e.useRef(new Map);
2return o.current=new Map(n.map(e=>[e.pageNumber,e])),{summaries:n,status:r,getSummary:e.useCallback(e=>o.current.get(e)||null,[])}}(a,S?null:i),[A,O]=e.useState(null),[D,P]=e.useState("idle"),[L,$]=e.useState(!1),[M,U]=e.useState(null),F=M||s||_.length||A?.pageCount||null,[z,q]=function({paramName:t="page",totalPages:a}={}){const[n,s]=c(),r=n.get(t),i=e.useRef(a);i.current=a;const[l,o]=e.useState(()=>Wv(Bv(r)||1,a)),d=e.useRef(l);e.useEffect(()=>{d.current=l},[l]);const u=e.useCallback(e=>{s(a=>{const n=new URLSearchParams(a);return n.set(t,String(e)),n},{replace:!0})},[t,s]);e.useEffect(()=>{const e=Bv(r),t=Wv(e||1,i.current);t!==d.current&&o(t),null!=r&&""!==r&&e!==t&&u(t)},[r,u]),e.useEffect(()=>{if(!a)return;const e=Wv(d.current,a);e!==d.current&&(o(e),u(e))},[a]);const h=e.useCallback(e=>{const t=d.current,a=Wv("function"==typeof e?e(t):e,i.current);a!==t&&(o(a),u(a))},[u]);return[l,h]}({totalPages:F}),[B]=c(),[W,V]=e.useState("split"),[H,K]=e.useState(.5),[G,J]=e.useState("pdf"),Y=Vv("(max-width: 768px)"),[Q,X]=e.useState(!1),[Z,ee]=e.useState(!1),te=Y?"ocr"===G:"pdf-only"!==W,ae=e.useMemo(()=>function(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}(B.get("highlight")),[B]),ne=qv({documentId:a,pageNumber:z,repository:i,getSummary:T,previewRepository:w,previewSummary:A,prefetchEnabled:!S,pollingEnabled:te}),{acceptDetail:se,refresh:re}=ne,[ie,oe]=e.useState(!1),ce=e.useId(),de=e.useId(),ue=e.useId(),[he,me]=e.useState(!1),[pe,ge]=e.useState(Boolean(B.get("discussion"))),[fe,be]=e.useState(!1),[xe,ve]=e.useState(!1),[je,ye]=e.useState(!1),ke=e.useCallback(()=>{oe(!1),window.setTimeout(()=>document.getElementById(ue)?.focus(),0)},[ue]);e.useEffect(()=>(R?.(fe),()=>R?.(!1)),[fe,R]),e.useEffect(()=>(E?.(je),()=>E?.(!1)),[E,je]);const we=e.useCallback(e=>{if(je)return!1;let t=!1;return q(a=>{const n="function"==typeof e?e(a):e,s=Math.max(1,F?Math.min(F,Number(n)||a):Number(n)||a);return s===a?(t=!0,a):fe&&!window.confirm("Discard unsaved page text changes and open another page?")?a:(t=!0,be(!1),s)}),t},[fe,je,q,F]),Ne=e.useCallback(async({ocrText:e,baseRevisionId:t,baseChecksum:n,sourceBinaryIdentity:s,editSummary:r})=>{if(!i?.savePageText)throw new Error("PageOCR editing is unavailable.");const l=a,o=z;ye(!0);try{const a=await i.savePageText(l,o,{ocrText:e,baseRevisionId:t,baseChecksum:n,sourceBinaryIdentity:s,editSummary:r}),c=se?.(a,{documentId:l,pageNumber:o});return c&&re?.(),a}catch(c){throw S&&(J("ocr"),V("split")),c}finally{ye(!1)}},[i,a,z,S,se,re]);e.useEffect(()=>{if(!a||!w)return O(null),P("idle"),void $(!1);const e="undefined"!=typeof AbortController?new AbortController:null;let t=!1;return P("loading"),w.listPages(a,{signal:e?.signal}).then(e=>{t||(O(e),P("ready"))}).catch(e=>{t||"AbortError"===e?.name||(O(null),P("error"))}),()=>{t=!0,e?.abort()}},[a,w]);const Se=Qj({documentId:a,pageNumber:z,repository:l,pageText:ne.detail?.ocrText||"",currentTextChecksum:ne.detail?.ocrChecksum||null,enabled:Boolean(l)}),{selectedId:Ce,selectedAnnotation:Re,selectAnnotation:Ee,clearSelection:Ie}=xy({annotations:Se.annotations,pageNumber:z});e.useEffect(()=>{Ce&&me(!0)},[Ce]);const _e={status:Se.status,error:Se.error,annotations:Se.annotations,isStale:Se.isStale,selectedId:Ce,selectedAnnotation:Re,onSelectAnnotation:Ee,onClearSelection:Ie};e.useEffect(()=>{r&&r(z)},[z,r]),e.useEffect(()=>{const e=e=>{var t;(t=e.target,"INPUT"===t?.tagName||"TEXTAREA"===t?.tagName||"SELECT"===t?.tagName||Boolean(t?.isContentEditable)||Boolean(t?.closest?.('button, a, [role="tab"], [role="separator"], .pdf-viewer-container')))||("ArrowLeft"===e.key?(e.preventDefault(),we(e=>Math.max(1,e-1))):"ArrowRight"===e.key&&(e.preventDefault(),we(e=>F?Math.min(F,e+1):e+1)))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[we,F]);const Te=e.useCallback(({numPages:e})=>{U(e||null)},[]),Ae=e.useCallback(()=>{we(e=>Math.max(1,e-1))},[we]),Oe=e.useCallback(()=>{we(e=>F?Math.min(F,e+1):e+1)},[we,F]),De=he?" minmax(260px, 22rem)":"",Pe="split"===W?{"--research-viewer-grid-columns":`minmax(320px, ${100*H}%) auto 1fr${De}`}:he?{"--research-viewer-grid-columns":`1fr${De}`}:void 0,Le=ne.detail?.pageQid||ne.summary?.qid||null,$e=ne.detail?.ocrStatus??ne.summary?.ocrStatus,Me=ne.detail?.documentPageId||ne.summary?.id||null,Ue=Me?{targetType:"document_page",targetKey:Me,targetLabel:`Page ${z}${Le?` · ${Le}`:""}`}:{targetType:"document",targetKey:a,targetLabel:n?.title||n?.filename||"Document"};return t.jsxs("div",{className:`document-research-viewer document-research-viewer--${W} document-research-viewer--mobile-${G}${S?" document-research-viewer--customer":""}${he?" document-research-viewer--annotations-open":""}`,"data-testid":"document-research-viewer",children:[S?null:t.jsx(Hv,{metadata:n}),t.jsx(Kv,{ariaLabel:S?"Document layout":"Research viewer layout",paneMode:W,onSetPaneMode:V,paneModeDisabled:je,hasDirtyDraft:fe,annotationsAvailable:Boolean(l),annotationsOpen:he,onToggleAnnotations:()=>me(e=>!e),qaAvailable:Boolean(A),qaOpen:L,onToggleQa:()=>$(e=>!e)}),t.jsx(Jv,{activeTab:G,onChangeTab:J,includeInfo:!S,hasDirtyDraft:fe,hasNewerVersion:Q,hasIntegrityConflict:Z}),L&&A?t.jsx(vy,{documentId:a,metadata:n,summary:A,currentPage:z,onOpenPage:we,onClose:()=>$(!1)}):"error"===D?t.jsx("div",{className:"pdf-text-preview-qa-unavailable",role:"status",children:"PDF text preview is unavailable. The PDF remains available."}):null,t.jsxs("div",{className:"document-research-viewer-split",style:Pe,children:[t.jsx(ij,{className:"document-research-viewer-pane document-research-viewer-pane--pdf",page:z,onPageChange:we,onDocumentInfo:Te,pdfProps:{...I,textSourceKind:ne.detail?.sourceKind||null},isTabbedLayout:Y,isActive:"pdf"===G}),"split"===W?t.jsx(Nj,{ratio:H,onChangeRatio:K}):t.jsx("span",{className:"document-research-viewer-split-gap","aria-hidden":"true"}),t.jsx(wj,{className:"document-research-viewer-pane document-research-viewer-pane--ocr",status:ne.status,error:ne.error,detail
2:ne.detail,integrityConflict:ne.integrityConflict,pageNumber:z,initialHighlight:ae,annotationSpans:Se.highlightSpans,selectedAnnotationId:Ce,onSelectAnnotation:Ee,canEditResearchData:N,onSaveOcrText:Ne,onReload:ne.reload,onDirtyChange:be,onEditingChange:ve,onNewerVersionChange:X,onIntegrityConflictChange:ee,customerMode:S,pageTextSyncStatus:C,isTabbedLayout:Y,isActive:"ocr"===G},z),he?t.jsx("aside",{className:"document-research-viewer-annotations","aria-label":"Entities and annotations",children:t.jsx(ry,{..._e})}):null]}),S&&Y&&"ocr"===G&&xe?null:t.jsx(Sj,{currentPage:z,totalPages:F,onPrevious:Ae,onNext:Oe,onGoToPage:we,disabled:je,pageQid:S?null:Le,ocrStatus:S&&Y?null:$e,onOpenDetails:()=>oe(e=>!e),detailsOpen:ie,detailsPanelId:ce,detailsTriggerId:ue,showDetails:!S&&!Y,statusMessage:S&&Y&&"pdf"===G&&je?"Saving page text. Page navigation is paused.":null}),S||Y||!ie?null:t.jsx(Ij,{id:ce,titleId:de,isOpen:ie,onClose:ke,documentMeta:n,pageDetail:ne.detail,entities:u,focusOnOpen:!0,className:"document-research-viewer-details-overlay",children:l?t.jsx(ry,{..._e,headingId:"annotations-panel-title-details"}):null}),d?t.jsxs("section",{className:"document-research-viewer-workspace-actions","aria-label":"Workspace actions",children:[t.jsx(oy,{repository:d,targetType:"document",targetKey:a,label:"Add document to Workspace"}),t.jsx(hy,{targetType:"document",targetKey:a,canonicalPath:`/documents/${a}`,label:"Share document"}),Me?t.jsxs(t.Fragment,{children:[t.jsx(oy,{repository:d,targetType:"document_page",targetKey:Me,label:"Add page to Workspace"}),t.jsx(hy,{targetType:"document_page",targetKey:Me,canonicalPath:`/documents/${a}?page=${z}`,label:"Share page"})]}):null]}):null,o&&Ue.targetKey?t.jsxs("section",{className:"document-research-viewer-discussions",children:[t.jsxs(ds,{variant:"secondary",size:"small",onClick:()=>ge(e=>!e),"aria-expanded":pe,ariaLabel:"Toggle scholarly discussions",children:[t.jsx(le,{size:15}),"Discussions"]}),pe?t.jsx(uy,{repository:o,targetType:Ue.targetType,targetKey:Ue.targetKey,targetLabel:Ue.targetLabel,initialDiscussionId:B.get("discussion"),workspaceRepository:d}):null]}):null,!S&&Y&&"info"===G?t.jsx("div",{id:"research-viewer-info-panel",className:"document-research-viewer-mobile-info",role:"tabpanel","aria-labelledby":"research-viewer-info-tab",children:t.jsx(Ij,{isOpen:!0,onClose:()=>J("pdf"),documentMeta:n,pageDetail:ne.detail,entities:u,children:l?t.jsx(ry,{..._e,headingId:"annotations-panel-title-mobile"}):null})}):null]})}const yy=[{value:Hi.ALL,label:"All"},{value:Hi.DOCUMENTS,label:"Documents"},{value:Hi.PAGES,label:"Pages"}];function ky(t,a){const[n,s]=e.useState(t||""),r=e.useRef(null);e.useEffect(()=>{s(t||"")},[t]),e.useEffect(()=>()=>window.clearTimeout(r.current),[]);return[n,e=>{s(e),window.clearTimeout(r.current),r.current=window.setTimeout(()=>{a(e.trim()||null)},400)}]}function wy({queryState:e,onSetResultType:a,onSetFilters:n,onClearFilters:s,idPrefix:r="search-filters"}){const{resultType:i,filters:l}=e,[o,c]=ky(l.language,e=>n({language:e})),[d,u]=ky(l.author,e=>n({author:e})),[h,m]=ky(l.classification,e=>n({classification:e})),p=Boolean(l.language||l.author||l.classification||l.hasPageText);return t.jsxs("div",{className:"search-filters",children:[t.jsxs("fieldset",{className:"search-filters-group",children:[t.jsx("legend",{children:"Result type"}),t.jsx("div",{className:"search-filters-segmented",role:"radiogroup","aria-label":"Result type",children:yy.map(e=>t.jsxs("label",{className:"search-filters-segmented-option",children:[t.jsx("input",{type:"radio",name:`${r}-result-type`,value:e.value,checked:i===e.value,onChange:()=>a(e.value)}),t.jsx("span",{children:e.label})]},e.value))})]}),t.jsxs("div",{className:"search-filters-field",children:[t.jsx("label",{htmlFor:`${r}-language`,children:"Language"}),t.jsx("input",{id:`${r}-language`,type:"text",value:o,onChange:e=>c(e.target.value),placeholder:"e.g. en, akk-Latn",autoComplete:"off"})]}),t.jsxs("div",{className:"search-filters-field",children:[t.jsx("label",{htmlFor:`${r}-author`,children:"Author"}),t.jsx("input",{id:`${r}-author`,type:"text",value:d,onChange:e=>u(e.target.value),placeholder:"Author name",autoComplete:"off"})]}),t.jsxs("div",{className:"search-filters-field",children:[t.jsx("label",{htmlFor:`${r}-classification`,children:"Classification"}),t.jsx("input",{id:`${r}-classification`,type:"text",value:h,onChange:e=>m(e.target.value),placeholder:"e.g. royal-inscriptions",autoComplete:"off"})]}),t.jsxs("label",{className:"search-filters-checkbox",children:[t.jsx("input",{type:"checkbox",checked:Boolean(l.hasPageText),onChange:e=>n({hasPageText:e.target.checked})}),t.jsx("span",{children:"Has page text"})]}),t.jsx("button",{type:"button",className:"search-filters-clear",onClick:s,disabled:!p,children:"Clear filters"})]})}function Ny({label:e="Exact identifier match"}){return t.jsx("span",{className:"search-badge search-badge--exact-id",children:e})}function Sy({matchedFields:e}){return e&&0!==e.length?t.jsx("span",{className:"search-matched-field-chips","aria-label":"Matched fields",children:e.map(e=>t.jsx("span",{className:"search-matched-field-chip",children:e.label},e.key))}):null}function Cy(e,{ranges:t,query:a}={}){const n=String(e||"");return n?Array.isArray(t)&&t.length>0?function(e,t){const a=String(e||"");if(!a)return[];const n=Array.isArray(t)?t.filter(e=>Number.isInteger(e?.start)&&Number.isInteger(e?.end)&&e.start>=0&&e.end>e.start&&e.end<=a.length):[];if(0===n.length)return[{text:a,isMatch:!1,isActive:!1}];const s=[...n].sort((e,t)=>
2e.start-t.start);return oj(a,s,-1)}(n,t):a&&String(a).trim()?function(e,t){const a=String(e||"");if(!a)return[];const n=String(t||"").trim();return n?oj(a,lj(a,n),-1):[{text:a,isMatch:!1,isActive:!1}]}(n,a):[{text:n,isMatch:!1,isActive:!1}]:[]}function Ry({text:e,ranges:n,query:s,className:r=""}){const i=Cy(e,{ranges:n,query:s});return 0===i.length?null:t.jsx("span",{className:r,children:i.map((e,n)=>e.isMatch?t.jsx("mark",{className:"search-highlight-mark",children:e.text},n):t.jsx(a.Fragment,{children:e.text},n))})}function Ey(e){return e?`/documents/${encodeURIComponent(e)}`:null}function Iy({result:e,query:a}){const n=Ey(e.documentId),s=e.authors&&e.authors.length>0?e.authors.join(", "):null;return t.jsxs("li",{className:"search-result-row search-result-row--document","data-result-type":"document",children:[t.jsx("div",{className:"search-result-row-icon","aria-hidden":"true",children:t.jsx(he,{size:18})}),t.jsxs("div",{className:"search-result-row-body",children:[t.jsxs("div",{className:"search-result-row-heading",children:[t.jsx("span",{className:"search-result-kind-label search-result-kind-label--document",children:"Document"}),e.isExactIdentifierMatch?t.jsx(Ny,{}):null]}),t.jsx("h3",{className:"search-result-row-title",children:t.jsx(l,{to:n||"#",children:t.jsx(Ry,{text:e.displayName,query:a})})}),t.jsxs("div",{className:"search-result-row-meta",children:[s?t.jsx("span",{className:"search-result-meta-item search-result-meta-item--authors",children:s}):null,e.publicationDate?t.jsx("span",{className:"search-result-meta-item",children:e.publicationDate}):null,e.language?t.jsx("span",{className:"search-result-meta-item search-result-meta-item--language",children:e.language}):null,e.wikibaseEntityId?t.jsx("span",{className:"search-result-meta-item search-result-meta-item--qid",children:e.wikibaseEntityId}):null]}),t.jsx(Sy,{matchedFields:e.matchedFields})]})]})}function _y({result:e,query:a}){const n=function(e,t){const a=e?.matchRanges?.[0];if(a&&"string"==typeof e?.snippet){const t=e.snippet.slice(a.start,a.end).trim();if(t)return t}return String(t||"").trim().split(/\s+/)[0]||null}(e,a),s=function(e,t,{highlight:a}={}){if(!e)return null;const n=new URLSearchParams;Number.isInteger(t)&&t>0&&n.set("page",String(t));const s="string"==typeof a?a.trim():"";s&&n.set("highlight",s.slice(0,64));const r=n.toString();return`/documents/${encodeURIComponent(e)}${r?`?${r}`:""}`}(e.documentId,e.pageNumber,{highlight:n}),r=Ey(e.documentId),i=[e.authors?.join(", ")||null,e.publicationDate,e.language].filter(Boolean).join(" · ");return t.jsxs("li",{className:"search-result-row search-result-row--page","data-result-type":"page",children:[t.jsx("div",{className:"search-result-row-icon","aria-hidden":"true",children:t.jsx(j,{size:18})}),t.jsxs("div",{className:"search-result-row-body",children:[t.jsxs("div",{className:"search-result-row-heading",children:[t.jsx("span",{className:"search-result-kind-label search-result-kind-label--page",children:e.pageNumber?`Page ${e.pageNumber}`:"Page result"}),e.isExactIdentifierMatch?t.jsx(Ny,{}):null]}),t.jsx("p",{className:"search-result-parent-title",children:t.jsx(l,{to:r||"#",children:e.documentDisplayName})}),i?t.jsx("div",{className:"search-result-row-meta",children:i}):null,e.snippet?t.jsx("p",{className:"search-result-snippet",lang:e.language||void 0,children:t.jsx(Ry,{text:e.snippet,ranges:e.matchRanges,query:a})}):null,t.jsxs("div",{className:"search-result-row-footer",children:[e.pageWikibaseEntityId?t.jsx("span",{className:"search-result-meta-item search-result-meta-item--qid",children:e.pageWikibaseEntityId}):null,t.jsx(Sy,{matchedFields:e.matchedFields}),t.jsxs(l,{to:s||"#",className:"search-result-open-page","aria-label":`Open page ${e.pageNumber||""} of ${e.documentDisplayName}`.trim(),children:["Open page",t.jsx(de,{size:14,"aria-hidden":"true"})]})]})]})]})}function Ty({results:e,query:a}){return t.jsx("ul",{className:"search-results-list","aria-label":"Search results",children:e.map(e=>"page"===e.resultType?t.jsx(_y,{result:e,query:a},`page-${e.documentPageId}`):t.jsx(Iy,{result:e,query:a},`document-${e.documentId}`))})}const Ay=Object.freeze({language:null,author:null,classification:null,hasPageText:!1});function Oy(){const[t,a]=c(),n=e.useMemo(()=>function(e){const t=Xi(e,"type"),a=Qi.has(t)?t:Hi.ALL;return{query:Zi(Xi(e,"q")||""),resultType:a,filters:{language:Xi(e,"language")||null,author:Xi(e,"author")||null,classification:Xi(e,"classification")||null,hasPageText:"1"===Xi(e,"hasText")},cursor:Xi(e,"cursor")||null}}(t),[t]),s=e.useCallback((e,{replace:t=!0}={})=>{a(el(e),{replace:t})},[a]),r=e.useCallback(e=>{s({...n,query:e,cursor:null},{replace:!1})},[s,n]),i=e.useCallback(e=>{s({...n,resultType:e},{replace:!0})},[s,n]),l=e.useCallback(e=>{s({...n,filters:{...n.filters,...e}},{replace:!0})},[s,n]),o=e.useCallback(()=>{s({...n,filters:{...Ay}},{replace:!0})},[s,n]);return{state:n,submitQuery:r,setResultType:i,setFilters:l,clearFilters:o}}function Dy(e){return`researchSearch:v1:${e}`}const Py=Object.freeze({IDLE:"idle",LOADING:"loading",LOADING_MORE:"loading-more",READY:"ready",ERROR:"error"});function Ly(t){const{state:a,submitQuery:n,setResultType:s,setFilters:r,clearFilters:i}=Oy(),[l,o]=e.useState(Py.IDLE),[c,d]=e.useState([]),[u,h]=e.useState([]),[m,p]=e.useState(null),[g,f]=e.useState(null),b=e.useRef(null),x=function(e){const t=e?.filters||{};return JSON.stringify([e?.query||"",e?.resultType||"all",t.language||"",t.author||"",t.classification||"",Boolean(t.hasPageText)])}(a),v=e.useRef(x);v.current=x;const j=e.useCallback(async({cursor:e,append:n})=>{b.current?.abort();const s=new AbortController;b.current=s;const r=x;o(n?Py.LOADING_MORE:Py.LOADING),n||f(null);try{const i=await t.search({...a,cursor:e},{signal:s.signal});if(v.current!==r)return;d(e=>{const t=n?[...e,...i.results]:i.results;return function(e,t){if("undefined"!=typeof window&&e)try{window.sessionStorage.setItem(Dy(e),JSON.stringify({savedAt:Date.now(),payload:t}))}catch{}}(r,{results:t,exactIdentifiers:i.exactIdentifiers,nextCursor:i.nextCursor}),t}),h(i.exactIdentifiers),p(i.nextCursor),o(Py.READY),f(null)}catch(i){if("REQUEST_CANCELLED"===i?.code)return;if(v.current!==r)return;o(Py.ERROR),f(i)}},[t,a,x]);e.useEffect(()=>{if(!a.query.trim())return b.current?.abort(),o(Py.IDLE),d([]),h([]),p(null),void f(null);const e=function(e){if("undefined"==typeof window||!e)return null;try{const t=window.sessionStorage.getItem(Dy(e));if(!t)return null;const a=JSON.parse(t);return!a?.savedAt||Date.now()-a.savedAt>6e5?(window.sessionStorage.removeItem(Dy(e)),null):a.payload||null}catch{return null}}(x);return e?(d(e.results||[]),h(e.exactIdentifiers||[]),p(e.nextCursor||null),o(Py.READY),void f(null)):(j({cursor:null,append:!1}),()=>{b.current?.abort()})},[x]);const y=e.useCallback(()=>{m&&l!==Py.LOADING_MORE&&l!==Py.LOADING&&j({cursor:m,append:!0})},[m,l,j]),k=e.useCallback(()=>
2{j({cursor:null,append:!1})},[j]);return{queryState:a,submitQuery:n,setResultType:s,setFilters:r,clearFilters:i,status:l,results:c,exactIdentifiers:u,error:g,hasMore:Boolean(m),loadMore:y,retry:k}}function $y(e){return"SUBSCRIPTION_REQUIRED"===e?.code?"An active subscription is required to search the research corpus.":"UNAUTHORIZED"===e?.code?"Your session has expired. Please sign in again.":"NETWORK_ERROR"===e?.code?"Could not reach the search service. Check your connection and try again.":"Something went wrong while searching. Please try again."}function My({repository:a}){const{queryState:n,submitQuery:s,setResultType:r,setFilters:i,clearFilters:l,status:o,results:c,error:d,hasMore:u,loadMore:h,retry:m}=Ly(a),[p,g]=e.useState(n.query),[f,b]=e.useState(!1),x=e.useRef(null);e.useEffect(()=>{g(n.query)},[n.query]),e.useEffect(()=>{function e(e){if("/"!==e.key||e.metaKey||e.ctrlKey||e.altKey)return;const t=e.target;"INPUT"===t?.tagName||"TEXTAREA"===t?.tagName||t?.isContentEditable||(e.preventDefault(),x.current?.focus())}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]);const v=o===Py.LOADING,j=o===Py.LOADING_MORE,y=o===Py.ERROR,k=n.query.trim().length>0,w=!!(N=n.filters)&&Boolean(N.language||N.author||N.classification||N.hasPageText);var N;const S=c.length>0,C=function({hasQuery:e,status:t,results:a,hasMore:n}){if(!e||t===Py.ERROR)return"";const s=t===Py.LOADING,r=t===Py.LOADING_MORE;return s&&0===a.length?"":s&&a.length>0?"Updating resultsâ¦":r?"Loading more resultsâ¦":0===a.length?"":function(e,t){return 0===e?null:`${e}${t?"+":""} result${1!==e||t?"s":""}`}(a.length,n)||""}({hasQuery:k,status:o,results:c,hasMore:u});return t.jsxs("div",{className:"research-search-view",children:[t.jsxs("form",{className:"research-search-bar",role:"search",onSubmit:e=>{e.preventDefault(),s(p)},children:[t.jsx("label",{htmlFor:"research-search-input",className:"research-search-input-label",children:"Search the research corpus"}),t.jsxs("div",{className:"research-search-input-row",children:[t.jsx(oi,{id:"research-search-input",ref:x,value:p,onChange:g,placeholder:"Title, author, identifier, or page textâ¦",className:"research-search-input"}),t.jsx("button",{type:"submit",className:"research-search-submit",children:"Search"}),t.jsxs("button",{type:"button",className:"research-search-filter-toggle",onClick:()=>b(!0),"aria-label":"Open filters",children:[t.jsx(je,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:"Filters"}),w?t.jsx("span",{className:"research-search-filter-dot","aria-hidden":"true"}):null]})]})]}),t.jsxs("div",{className:"research-search-body",children:[t.jsx("aside",{className:"research-search-sidebar","aria-label":"Search filters",children:t.jsx(wy,{queryState:n,onSetResultType:r,onSetFilters:i,onClearFilters:l})}),t.jsx(Bb,{isOpen:f,onClose:()=>b(!1),children:t.jsx(wy,{queryState:n,onSetResultType:r,onSetFilters:i,onClearFilters:l,idPrefix:"search-filters-mobile"})}),t.jsxs("div",{className:"research-search-results",children:[t.jsx("p",{className:"research-search-status-line","aria-live":"polite",children:C}),k?null:t.jsxs("div",{className:"research-search-state research-search-state--prompt",children:[t.jsx(ue,{size:26,"aria-hidden":"true"}),t.jsx("p",{children:"Search the research corpus by title, author, identifier, or page text."})]}),k&&y?t.jsxs("div",{className:"research-search-state research-search-state--error",role:"alert",children:[t.jsx(be,{size:24,"aria-hidden":"true"}),t.jsx("p",{children:$y(d)}),t.jsx("button",{type:"button",onClick:m,className:"research-search-retry",children:"Try again"})]}):null,k&&!y&&!S&&v?t.jsxs("div",{className:"research-search-state research-search-state--loading",role:"status",children:[t.jsx(Dt,{className:"research-search-spinner",size:22,"aria-hidden":"true"}),t.jsx("p",{children:"Searchingâ¦"})]}):null,!k||y||S||v?null:t.jsxs("div",{className:"research-search-state research-search-state--empty",children:[t.jsx(me,{size:26,"aria-hidden":"true"}),t.jsx("p",{children:"No matching results found."}),t.jsxs("p",{className:"research-search-state-hint",children:["Try different terms",w?" or remove filters":"","."]})]}),S?t.jsxs(t.Fragment,{children:[t.jsx(Ty,{results:c,query:n.query}),u?t.jsx("button",{type:"button",className:"research-search-load-more",onClick:h,disabled:j,children:j?"Loading moreâ¦":"Load more"}):null]}):null]})]})]})}function Uy({title:e="Subscription Required",message:a="This feature requires an active subscription to access.",ctaText:n="View Plans & Subscribe",onUpgradeClick:s,showFeatures:r=!1,documentCount:l,headingLevel:o=3,compact:c=!1}){const d=i(),u=2===o?"h2":"h3",h=[{icon:he,text:"Extracted text and research tools"},{icon:ue,text:"Bookmarks and personal folders"},{icon:Pt,text:"Eligible upload actions"},{icon:ce,text:"New materials added regularly"}
2],m=t.jsx("ul",{className:"subscription-features-list",children:h.map(e=>t.jsxs("li",{children:[t.jsx(e.icon,{size:16}),t.jsx("span",{children:e.text})]},e.text))});return t.jsxs(Js,{className:"subscription-required"+(c?" subscription-required--compact":""),children:[t.jsx("div",{className:"subscription-required-icon",children:t.jsx(Lt,{size:c?24:48})}),t.jsx(u,{className:"subscription-required-title",children:e}),t.jsx("p",{className:"subscription-required-message",children:a}),l>0&&t.jsxs("div",{className:"subscription-doc-count",children:[t.jsx("span",{className:"subscription-doc-number",children:l.toLocaleString()}),t.jsx("span",{className:"subscription-doc-label",children:"documents available"})]}),r&&!c&&t.jsxs("div",{className:"subscription-features",children:[t.jsx("p",{className:"subscription-features-title",children:"What you get with a subscription:"}),m]}),t.jsx(ds,{variant:"primary",size:"large",onClick:()=>{s?s():d("/dashboard?tab=settings§ion=subscription")},className:"subscription-upgrade-btn",children:n}),t.jsx("p",{className:"subscription-required-subtext",children:"Cancel anytime. Access begins after your subscription is confirmed."}),r&&c?t.jsxs("details",{className:"subscription-features-disclosure",children:[t.jsx("summary",{children:"What a subscription includes"}),m]}):null]})}const Fy=Object.freeze([{path:"/research-feed",label:"Activity",icon:xt},{path:"/community/messages",label:"Messages",icon:$e,messagingPreview:!0},{path:"/researchers",label:"People",icon:S},{path:"/following",label:"Following",icon:$t},{path:"/research-workspaces",label:"Workspaces",icon:A}]);function zy({title:e,message:a,tone:n="neutral",action:s=null}){return t.jsxs("div",{className:`research-product-state research-product-state--${n}`,role:"error"===n?"alert":"status",children:[t.jsx("strong",{children:e}),a?t.jsx("span",{children:a}):null,s?t.jsx("div",{className:"research-product-state-action",children:s}):null]})}function qy({children:a,title:n,description:s,eyebrow:r=null,actions:i=null,leading:o=null,details:c=null,backLink:u=null,width:h="standard"}){const{canAccessCommunityMessagingPreview:m}=Yn(),p=function(){const{canAccessCommunityMessagingPreview:t,makeAuthRequest:a}=Yn(),n=Boolean(t?.()),[s,r]=e.useState(0),i=e.useCallback(async()=>{if(n&&"visible"===document.visibilityState)try{const e=await a("/api/community/messages/conversations",{method:"GET"});r(Number(e?.data?.unreadCount||0)+Number(e?.data?.requestCount||0))}catch{}},[n,a]);return e.useEffect(()=>{if(!n)return void r(0);i();const e=window.setInterval(i,75e3);return document.addEventListener("visibilitychange",i),window.addEventListener("focus",i),()=>{window.clearInterval(e),document.removeEventListener("visibilitychange",i),window.removeEventListener("focus",i)}},[n,i]),n?s:0}(),g=Boolean(m?.());return e.useEffect(()=>(document.body.classList.add("research-product-route"),()=>{document.body.classList.remove("research-product-route")}),[]),t.jsx(ri,{variant:"research",children:t.jsxs("div",{className:`research-product-shell research-product-shell--${h}`,children:[t.jsxs("header",{className:"research-product-context",children:[t.jsxs("div",{className:"research-product-context-title",children:[t.jsxs("div",{className:"research-product-context-name",children:[t.jsx("span",{children:"Community"}),t.jsx("span",{className:"research-product-preview-badge",children:"Admin preview"})]}),t.jsx("small",{children:"Scholarly collaboration for internal review"})]}),t.jsx("nav",{className:"research-product-nav","aria-label":"Community sections",children:Fy.filter(e=>!e.messagingPreview||g).map(e=>t.jsxs(d,{to:e.path,className:({isActive:e})=>"research-product-nav-item "+(e?"is-active":""),end:"/researchers"!==e.path&&"/research-workspaces"!==e.path,children:[t.jsx(e.icon,{size:17,"aria-hidden":"true"}),t.jsx("span",{children:e.label}),e.messagingPreview&&p?t.jsx("span",{className:"research-product-nav-badge","aria-label":`${p} unread`,children:p>99?"99+":p}):null]},e.path))})]}),t.jsxs("div",{className:"research-product-preview-notice",role:"note",children:[t.jsx(ot,{size:17,"aria-hidden":"true"}),t.jsxs("span",{children:[t.jsx("strong",{children:"Internal preview."})," Community profiles, workspaces, discussions, and messages are currently available only to admins and cofounders."]})]}),t.jsxs("div",{className:"research-product-content",children:[u?t.jsxs(l,{className:"research-product-back",to:u.to,children:[t.jsx(G,{size:16,"aria-hidden":"true"}),u.label]}):null,n?t.jsxs("header",{className:"research-product-page-header",children:[o?t.jsx("div",{className:"research-product-page-leading",children:o}):null,t.jsxs("div",{className:"research-product-page-heading",children:[r?t.jsx("p",{children:r}):null,t.jsx("h1",{children:n}),s?t.jsx("span",{children:s}):null,c?t.jsx("div",{className:"research-product-page-details",children:c}):null]}),i?t.jsx("div",{className:"research-product-page-actions",children:i}):null]}):null,a]})]})})}function By({person:a,size:n="medium"}){const[s,r]=e.useState(!1);return a?.avatarUrl&&!s?t.jsx("img",{className:`community-avatar community-avatar--${n}`,src:a.avatarUrl,alt:"",onError:()=>r(!0)}):t.jsx("span",{className:`community-avatar community-avatar--${n} community-avatar--fallback`,"aria-hidden":"true",children:(i=a?.displayName,String(i||"Community member").split(/\s+/).slice(0,2).map(e=>e[0]).join("").toUpperCase())});var i}function Wy({person:e,meta:a=null,link:n=!0,size:s="medium"}){const r=e?.profileSlug?`/researchers/${e.profileSlug}`:e?.userId?`/researchers/user/${e.userId}`:null,i=t.jsxs(t.Fragment,{children:[t.jsx(By,{person:e,size:s}),t.jsxs("span",{className:"community-identity-copy",children:[t.jsx("strong",{children:e?.displayName||"Community member"}),a||e?.headline||e?.affiliation?t.jsx("small",{children:a||e.headline||e.affiliation}):null]})]});return n&&r?t.jsx(l,{className:"community-identity",to:r,children:i}):t.jsx("span",{className:"community-identity",children:i})}const Vy=[{path:"/studio",label:"Overview",icon:Mt,exact:!0},{path:"/studio/ocr",label:"OCR Studio",icon:jt},{path:"/studio/workflows",label:"Workflows",icon:Ut},{path:"/studio/jobs",label:"Jobs",icon:Ft},{path:"/studio/credits",label:"Credits",icon:zt}];function Hy({title:e,message:a,tone:n="default",action:s=null}){return t.jsxs("section",{className:`studio-state studio-state--${n}`,role:"error"===n?"alert":"status",children:[t.jsx("h2",{children:e}),t.jsx("p",{children:a}),s]})}function Ky({title:e,description:a,children:n,actions:r=null}){const i=s();return t.jsx(ri,{children:t.jsxs("div",{className:"studio-page",children:[t.jsxs("header",{className:"studio-header",children:[t.jsxs("div",{children:[t.jsx(l,{className:"studio-kicker",to:"/studio",children:"TokenWorks Tools"}),t.jsx("h1",{children:e}),a?t.jsx("p",{children:a}):null]}),r?t.jsx("div",{className:"studio-header__actions",children:r}):null]}),t.jsx("nav",{className:"studio-section-nav","aria-label":"Tools sections",children:Vy.map(e=>{const a=i.pathname===e.path||!e.exact&&i.pathname.startsWith(`${e.path}/`);return t.jsxs(l,{to:e.path,"aria-current":a?"page":void 0,className:a?"active":"",children:[t.jsx(e.icon,{size:17,"aria-hidden":"true"}),e.label]},e.path)})}),t.jsx("div",{className:"studio-content",children:n})]})})}const Gy={"engineering-reviewed":"Engineering reviewed","review-in-progress":"Review in progress","domain-review-required":"Domain review required","operations-review-required":"Operations review required"};function Jy(t){return e.Children.map(t,t=>{if(!e.isValidElement(t))return t;const n=t.props?.children?Jy(t.props.children):t.props?.children;if("string"==typeof t.type){if("h1"===t.type)return a.createElement("h2",t.props,n);if(["h4","h5","h6"].includes(t.type))return a.createElement("h3",t.props,n)}return e.cloneElement(t,t.props,n)})}function Yy({title:n,description:r,meta:i,metaTitle:o,metaDescription:c,canonicalPath:d,robots:u="index,follow",children:h,breadcrumbs:m=[],showToc:p=!0,tocItems:g=[],sidebar:f=null}){const b=s(),x=$a(b.pathname),v=x?.title||n,j=x?.summary||r,y=x?Ma(x.taskGroup):null,k=x?Ua(x.id):null,w=x?Fa.filter(e=>e.taskGroup===x.taskGroup&&!1!==e.discoverable):[],N=(x?.relatedGuideIds||[]).map(za).filter(
2Boolean).slice(0,3),S=(x?.prerequisites||[]).map(za).filter(Boolean),C=Jy(h);e.useEffect(()=>{x&&es("guide_open",{guide_id:x.id,source:"guide_page"})},[x]);const R=o||(v&&!["Loading...","Error","Not Found"].includes(v)?v:null),E=c||j||"TokenWorks documentation for setup, integration, troubleshooting, and research workflows.",I=e=>t.jsx("nav",{className:"docs-nav","aria-label":e,children:f||t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"docs-nav-section",children:[t.jsx("h2",{children:y?.title||"Browse guides"}),t.jsx("ul",{children:w.length>0?w.map(e=>t.jsx("li",{children:t.jsx(l,{to:e.route,"aria-current":e.route===b.pathname?"page":void 0,children:e.title})},e.id)):t.jsx("li",{children:t.jsx(l,{to:"/guides",children:"All guides"})})})]}),t.jsxs("div",{className:"docs-nav-footer",children:[t.jsx(l,{to:"/resources",children:"Learning paths"}),t.jsx(l,{to:"/guides",children:"All guides"})]})]})});return t.jsxs("div",{className:"docs-layout",children:[t.jsx(zs,{title:R,description:E,canonicalPath:x?.route||d,robots:u}),t.jsx("div",{className:"docs-shell",id:"guide-content",children:t.jsxs("div",{className:"docs-grid",children:[t.jsxs("article",{className:"docs-article",children:[m.length>0&&t.jsx("nav",{className:"docs-breadcrumbs","aria-label":"Breadcrumb",children:t.jsx("ol",{children:m.map((e,a)=>t.jsx("li",{children:e.href?t.jsx(l,{to:e.href,children:e.label}):t.jsx("span",{children:e.label})},`${e.label}-${a}`))})}),t.jsxs("header",{className:"docs-header",children:[y&&t.jsx("p",{className:"docs-kicker",children:y.title}),t.jsx("h1",{children:v}),j&&t.jsx("p",{className:"docs-description",children:j}),x?t.jsxs("dl",{className:"docs-identity",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Audience"}),t.jsx("dd",{children:x.audience})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Level"}),t.jsx("dd",{children:x.level})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Outcome"}),t.jsx("dd",{children:x.outcome})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Review status"}),t.jsx("dd",{children:Gy[x.reviewStatus]||x.reviewStatus})]}),x.lastReviewed&&t.jsxs("div",{children:[t.jsx("dt",{children:"Last reviewed"}),t.jsx("dd",{children:x.lastReviewed})]}),x.reviewedAgainst&&t.jsxs("div",{children:[t.jsx("dt",{children:"Reviewed against"}),t.jsx("dd",{children:x.reviewedAgainst})]})]}):i?t.jsx("div",{className:"docs-meta",children:i.map(e=>t.jsx("span",{children:e},e))}):null,S.length>0&&t.jsxs("p",{className:"docs-prerequisites",children:[t.jsx("strong",{children:"Start first:"})," ",S.map((e,n)=>t.jsxs(a.Fragment,{children:[n>0?", ":"",t.jsx(l,{to:e.route,children:e.title})]},e.id))]})]}),t.jsxs("details",{className:"docs-mobile-navigation",children:[t.jsx("summary",{children:"Browse this learning path"}),I("Guide navigation")]}),p&&g.length>0&&t.jsx("div",{className:"docs-toc-wrapper",children:t.jsxs("details",{className:"docs-toc",open:!0,children:[t.jsx("summary",{children:"In this guide"}),t.jsx("nav",{className:"docs-toc-nav","aria-label":"Table of contents",children:t.jsx("ul",{children:g.map(e=>t.jsx("li",{className:`toc-level-${e.level}`,children:t.jsx("a",{href:`#${e.id}`,children:e.text})},e.id))})})]})}),t.jsx("div",{className:"docs-content prose",children:C}),k&&t.jsxs("aside",{className:"docs-evidence","aria-labelledby":"docs-evidence-title",children:[t.jsxs("div",{className:"docs-evidence__heading",children:[t.jsxs("div",{children:[t.jsx("p",{className:"docs-kicker",children:"Factual review"}),t.jsx("h2",{id:"docs-evidence-title",children:"Evidence and limits"})]}),t.jsx("span",{children:k.classification.replaceAll("-"," ")})]}),t.jsx("p",{children:k.reviewNote}),t.jsxs("ol",{className:"docs-evidence__flow","aria-label":"How to use this guide safely",children:[t.jsxs("li",{children:[t.jsx("strong",{children:"Check the source"}),t.jsx("span",{children:"Confirm the current upstream contract."})]}),t.jsxs("li",{children:[t.jsx("strong",{children:"Adapt the example"}),t.jsx("span",{children:"Replace sample URLs, IDs, versions, and topology."})]}),t.jsxs("li",{children:[t.jsx("strong",{children:"Verify the result"}),t.jsx("span",{children:"Test safely before consequential use."})]})]}),t.jsx("h3",{children:"Authoritative sources"}),t.jsx("ul",{className:"docs-evidence__sources",children:k.sources.map(e=>t.jsxs("li",{children:[e.href?t.jsx("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",children:e.title}):t.jsx("span",{children:e.title}),t.jsx("small",{children:e.publisher})]},`${e.publisher}-${e.title}`))})]}),N.length>0&&t.jsxs("aside",{className:"docs-related","aria-labelledby":"docs-related-title",children:[t.jsx("p",{className:"docs-kicker",children:"Continue learning"}),t.jsx("h2",{id:"docs-related-title",children:"Recommended next guides"}),t.jsx("ul",{children:N.map(e=>t.jsx("li",{children:t.jsxs(l,{to:e.route,children:[t.jsx("strong",{children:e.title}),t.jsx("span",{children:e.summary})]})},e.id))})]}),t.jsx("footer",{className:"docs-footer",children:x?.lastReviewed?t.jsxs("p",{children:["Editorial review recorded ",x.lastReviewed,"."]}):t.jsx("p",{children:"This guide does not yet have a completed editorial review date."})})]}),t.jsx("aside",{className:"docs-desktop-sidebar",children:I("Guide navigation")})]})})]})}function Qy({variant:e="info",title:a=null,children:n,className:s=""}){const r=`callout callout-${e}${s?` ${s}`:""}`;return t.jsxs("div",{className:r,children:[a?t.jsx("h3",{children:a}):null,n]})}function Xy({text:a,label:n="Copy",copiedLabel:s="Copied",className:r=""}){const[i,l]=e.useState(!1),o=e.useRef(null);e.useEffect(()=>()=>{o.current&&window.clearTimeout(o.current)},[]);const c=`copy-btn${i?" is-copied":""}${r?` ${r}`:""}`;return t.jsx("button",{type:"button",className:c,onClick:async()=>{const e="function"==typeof a?a():a;if("string"==typeof e&&0!==e.length)try{await navigator.clipboard.writeText(e),l(!0),o.current&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>{l(!1)},1600)}catch(t){}},children:i?s:n})}function Zy({id:e,title:a=null,children:n,className:s=""}){const r="step-by-step"+(s?` ${s}`:"");return t.jsxs("div",{id:e,className:r,children:[a?t.jsx("h3",{children:a}):null,n]})}function ek({number:e,title:a=null,headingLevel:n="h3",children:s}){const r=n;return t.jsxs("div",{className:"step",children:[t.jsx("div",{className:"step-number",children:e}),t.jsxs("div",{className:"step-content",children:[a?t.jsx(r,{children:a}
2):null,s]})]})}function tk({resourceId:e}){const a=qa(e);if(!a)return null;const n="unavailable"===a.status||!a.action,s="external"===a.action?.kind,r=s?Ue:Bt;return t.jsxs("aside",{id:`tool-${a.id}`,className:`guide-tool-panel guide-tool-panel--${a.status}`,"aria-labelledby":`tool-${a.id}-title`,children:[t.jsxs("div",{className:"guide-tool-panel__header",children:[t.jsxs("div",{children:[t.jsx("p",{className:"guide-tool-panel__eyebrow",children:"Contextual resource"}),t.jsx("h3",{id:`tool-${a.id}-title`,children:a.name})]}),t.jsx("span",{className:"guide-tool-panel__status",children:a.statusLabel||("available"===a.status?"Available":"Review required")})]}),t.jsx("p",{children:a.purpose}),t.jsxs("dl",{className:"guide-tool-panel__details",children:[a.prerequisites&&t.jsxs("div",{children:[t.jsx("dt",{children:"Before you use it"}),t.jsx("dd",{children:a.prerequisites})]}),a.input&&t.jsxs("div",{children:[t.jsx("dt",{children:"Input"}),t.jsx("dd",{children:a.input})]}),a.expectedOutput&&t.jsxs("div",{children:[t.jsx("dt",{children:"Expected output"}),t.jsx("dd",{children:a.expectedOutput})]}),a.fileType&&t.jsxs("div",{children:[t.jsx("dt",{children:"Format"}),t.jsx("dd",{children:a.fileType})]})]}),(a.provenance||a.help)&&t.jsxs("div",{className:"guide-tool-panel__notice",children:[t.jsx(qt,{"aria-hidden":"true"}),t.jsx("p",{children:a.provenance||a.help})]}),!n&&t.jsxs("a",{className:"guide-tool-panel__action",href:a.action.href,download:"download"===a.action.kind?a.action.filename:void 0,target:s?"_blank":void 0,rel:s?"noopener noreferrer":void 0,onClick:()=>{es("download"===a.action.kind?"resource_download":"contextual_resource_launch",{resource_id:a.id})},children:[t.jsx(r,{"aria-hidden":"true"}),a.action.label,s&&t.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}const ak=({codes:a,defaultLanguage:n=null,title:s=null})=>{const[r,i]=e.useState(n);if(!a)return t.jsx("div",{className:"code-block-container",children:t.jsx("div",{className:"code-block",children:t.jsx("pre",{children:t.jsx("code",{children:"No code provided"})})})});"string"==typeof a&&(a={[n||"code"]:a});const l=Object.keys(a);return!r&&l.length>0&&i(l[0]),1===l.length?t.jsxs("div",{className:"code-block-container",children:[s&&t.jsx("h3",{className:"code-block-title",children:s}),t.jsx("pre",{children:t.jsx("code",{children:a[l[0]]})})]}):t.jsxs("div",{className:"code-block-container",children:[s&&t.jsx("h3",{className:"code-block-title",children:s}),t.jsx("div",{className:"code-block-tabs",children:l.map(e=>t.jsx("button",{className:"code-tab "+(r===e?"active":""),onClick:()=>i(e),children:e},e))}),t.jsx("pre",{children:t.jsx("code",{children:a[r]})})]})},nk=Object.freeze([12e4,3e5]);function sk(){return"undefined"==typeof document||"hidden"!==document.visibilityState}function rk(){return"undefined"==typeof navigator||!1!==navigator.onLine}const ik=Object.freeze({"application-delivery":"Application & Delivery",schedulers:"Schedulers",database:"Database",storage:"Storage",wikibase:"Wikibase","workers-queues":"Workers & Queues",jupyter:"Jupyter","external-integrations":"External Integrations",observability:"Observability","backups-alerting":"Backups & Alerting"}),lk=Object.freeze({down:0,unknown:1,degraded:2,maintenance:3,healthy:4,disabled:5}),ok=Object.freeze({critical:0,high:1,medium:2,low:3});function ck(e){return Number.isFinite(e)?e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h`:`${Math.round(e/86400)}d`:"Not available"}function dk(e,t){if(!Number.isFinite(e))return"Not available";const a=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}).format(e);return t?`${a} ${t}`:a}function uk(e){const t="number"==typeof e?e:Date.parse(e);return e&&Number.isFinite(t)?new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",timeZoneName:"short"}):"Not observed"}function hk(e,t=Date.now()){const a="number"==typeof e?e:Date.parse(e);if(!e||!Number.isFinite(a))return"Never";const n=Math.max(0,Math.floor((t-a)/1e3));return n<10?"Just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:n<86400?`${Math.floor(n/3600)}h ago`:`${Math.floor(n/86400)}d ago`}const mk=Object.freeze({healthy:"Healthy",degraded:"Degraded",down:"Down",maintenance:"Maintenance",disabled:"Disabled",unknown:"Unknown"});function pk({transitions:e,className:a=""}){return t.jsx("ol",{className:a,children:e.map(e=>t.jsxs("li",{children:[t.jsx("span",{children:"Changed"}),t.jsx("time",{dateTime:e.at,children:uk(e.at)}),t.jsx("strong",{children:mk[e.status]||e.status})]},e.at))})}function gk({history:e}){const a=e?.points||[];if(!a.length)return t.jsxs("div",{className:"ih-history-empty",children:[t.jsx("h3",{children:"History"}),t.jsx("p",{children:"No trustworthy samples exist for this range yet."})]});const n=a.reduce((e,t)=>
2(e[t.status]=(e[t.status]||0)+1,e),{}),s=Object.entries(n).map(([e,t])=>`${t} ${mk[e]||e}`).join(" · "),r=a.filter(e=>Number.isFinite(e.latencyMs)).map(e=>e.latencyMs),i=r.length?`${Math.round(Math.min(...r))}â${Math.round(Math.max(...r))} ms across ${r.length} buckets.`:"No latency samples are available for this range.",l=a.map(e=>e.value).filter(e=>Number.isFinite(e)),o=l.length?`${Math.min(...l)}â${Math.max(...l)}${e.metricUnit?` ${e.metricUnit}`:""} across ${l.length} buckets.`:null,c=a.filter((e,t)=>0===t||e.status!==a[t-1].status).slice(1),d=c.slice(-10),u=c.length,h=`${u} status ${1===u?"change":"changes"}`,m=a[0],p=a.at(-1);return t.jsxs("section",{className:"ih-history","aria-labelledby":"ih-history-heading",children:[t.jsxs("div",{className:"ih-history__heading",children:[t.jsxs("div",{children:[t.jsx("h3",{id:"ih-history-heading",children:"History"}),t.jsxs("p",{children:[e.sampleCount," of ",e.expectedSamples," expected samples ·"," ",Math.round(e.coveragePercent),"% coverage"]})]}),t.jsx("span",{children:"raw"===e.source?"Raw samples":"Hourly rollup"})]}),t.jsx("div",{className:"ih-history-strip ih-history-strip--large",role:"img","aria-label":`Status history: ${s.replaceAll(" · ",", ")}.`,children:a.map(e=>t.jsx("span",{className:`ih-history-strip__segment ih-status-fill--${e.status}`,title:`${new Date(e.at).toLocaleString()} â ${mk[e.status]||e.status}, ${Math.round(e.coveragePercent)}% coverage`},e.at))}),t.jsx("p",{className:"ih-history-state-summary",children:s}),t.jsxs("div",{className:"ih-history-range","aria-label":"History range endpoints",children:[t.jsxs("span",{children:[t.jsx("span",{children:"Oldest"}),t.jsx("time",{dateTime:m.at,children:uk(m.at)}),t.jsx("strong",{children:mk[m.status]||m.status})]}),t.jsx("span",{"aria-hidden":"true",children:"â"}),t.jsxs("span",{children:[t.jsx("span",{children:"Latest"}),t.jsx("time",{dateTime:p.at,children:uk(p.at)}),t.jsx("strong",{children:mk[p.status]||p.status})]})]}),t.jsxs("div",{className:"ih-history-chronology",children:[t.jsx("h4",{children:"Status chronology"}),t.jsxs("p",{children:[h,u>10?" · latest 10 shown":""]}),d.length?t.jsx(pk,{transitions:d}):t.jsx("p",{className:"ih-history-chronology__empty",children:"No status changes in this range."}),u>10?t.jsxs("details",{className:"ih-history-all-changes",children:[t.jsxs("summary",{children:["Show all ",u," changes"]}),t.jsx("div",{className:"ih-history-all-changes__scroll",tabIndex:0,children:t.jsx(pk,{transitions:c})})]}):null]}),t.jsxs("dl",{className:"ih-history-summary",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Coverage"}),t.jsxs("dd",{children:[Math.round(e.coveragePercent),"%"]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Latency range"}),t.jsx("dd",{children:i})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Missing samples"}),t.jsx("dd",{children:Math.max(0,e.expectedSamples-e.sampleCount)})]}),o?t.jsxs("div",{children:[t.jsx("dt",{children:"Metric range"}),t.jsx("dd",{children:o})]}):null]})]})}const fk=Object.freeze({healthy:{label:"Healthy",icon:pe},degraded:{label:"Degraded",icon:be},down:{label:"Down",icon:Vt},maintenance:{label:"Maintenance",icon:ge},disabled:{label:"Disabled",icon:Wt},unknown:{label:"Unknown",icon:R},current:{label:"Current",icon:pe},stale:{label:"Stale",icon:ge},error:{label:"Error",icon:qt},never_run:{label:"Never run",icon:R}});function bk({status:e,monitor:a=!1,labelPrefix:n,label:s}){const r=fk[e]||fk.unknown,i=r.icon,l=s||r.label;return t.jsxs("span",{className:`ih-status ih-status--${e}`,"aria-label":`${n||(a?"Monitor":"Status")}: ${l}`,children:[t.jsx(i,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:l})]})}const xk=Object.freeze([{range:"24h",resolution:"5m",label:"24 hours"},{range:"7d",resolution:"1h",label:"7 days"},{range:"30d",resolution:"1d",label:"30 days"},{range:"90d",resolution:"1d",label:"90 days"}]);function vk(e){return String(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]/g," ").replace(/^./,e=>e.toUpperCase())}function jk(e){return Array.isArray(e)?e.length?e.join(", "):"None":"boolean"==typeof e?e?"Yes":"No":String(e)}function yk({service:a,request:n,onClose:s}){const[r,i]=e.useState({serviceKey:null,data:null}),[l,o]=e.useState({serviceKey:null,data:null}),[c,d]=e.useState(xk[0]),[u,h]=e.useState(!0),[m,p]=e.useState(null),[g,f]=e.useState(0);if(e.useEffect(()=>{if(!a)return;const e=new AbortController;return i({serviceKey:a.key,data:null}),o({serviceKey:a.key,data:null}
2),h(!0),p(null),Promise.all([n(`/api/admin/infrastructure-health/services/${encodeURIComponent(a.key)}`,{signal:e.signal,cache:"no-store"}),n(`/api/admin/infrastructure-health/history?serviceKey=${encodeURIComponent(a.key)}&range=${c.range}&resolution=${c.resolution}`,{signal:e.signal,cache:"no-store"})]).then(([t,n])=>{e.signal.aborted||(i({serviceKey:a.key,data:t?.data||null}),o({serviceKey:a.key,data:n?.data||null}))}).catch(e=>{"AbortError"!==e?.name&&p(e)}).finally(()=>{e.signal.aborted||h(!1)}),()=>e.abort()},[c,n,g,a]),!a)return null;const b=r.serviceKey===a.key?r.data:null,x=l.serviceKey===a.key?l.data:null,v=b?.check||a.check,j=b?.dependencies||[],y=Object.entries(a.details||{});return t.jsx(Ju,{isOpen:!0,onClose:s,title:a.name,size:"large",className:"ih-detail-modal",children:t.jsxs(Yu,{className:"ih-detail",children:[t.jsxs("div",{className:"ih-detail__status-line",children:[t.jsx(bk,{status:a.status,labelPrefix:"Service"}),t.jsx(bk,{status:a.monitorStatus,monitor:!0,labelPrefix:"Monitor"}),t.jsxs("span",{children:[a.criticality," criticality"]}),t.jsxs("span",{children:[a.expectedMode.replace("_"," ")," mode"]}),t.jsx("span",{children:a.environment}),t.jsxs("span",{children:[a.provider," · ",a.region]})]}),t.jsx("p",{className:"ih-detail__diagnosis",children:a.summary}),t.jsxs("section",{className:"ih-detail__guidance","aria-labelledby":"ih-detail-limitations-title",children:[t.jsx("h3",{id:"ih-detail-limitations-title",children:"Limitations"}),t.jsx("ul",{children:(b?.limitations||["The persisted snapshot does not replace provider-native alerts."]).map(e=>t.jsx("li",{children:e},e))}),b?.links?.includes("infrastructure-health-runbook")?t.jsxs("div",{className:"ih-detail__next-step","aria-labelledby":"ih-detail-next-step-title",children:[t.jsx("h3",{id:"ih-detail-next-step-title",children:"Recovery guidance"}),t.jsx("p",{children:"Use the approved runbook to investigate degraded or unavailable evidence and choose the next authorized action."}),t.jsxs("a",{href:"https://github.com/TokenWorks-LLC/TokenWorks-Site/blob/main/docs/operations/infrastructure-health.md",className:"ih-runbook-link",target:"_blank",rel:"noreferrer",children:["Open approved runbook ",t.jsx(Ue,{size:15,"aria-hidden":"true"})]})]}):null]}),t.jsxs("div",{className:"ih-detail__range",children:[t.jsx("label",{htmlFor:"ih-history-range",children:"History range"}),t.jsx("select",{id:"ih-history-range",value:c.range,onChange:e=>d(xk.find(t=>t.range===e.target.value)||xk[0]),children:xk.map(e=>t.jsx("option",{value:e.range,children:e.label},e.range))})]}),u?t.jsx("div",{className:"ih-detail__loading","aria-live":"polite",children:"Loading persisted detail and historyâ¦"}):m?t.jsxs("div",{className:"ih-callout ih-callout--error",role:"alert",children:[t.jsx("p",{children:"Detail is unavailable. The current snapshot above remains authoritative."}),t.jsx(ds,{variant:"secondary",onClick:()=>f(e=>e+1),children:"Retry detail"})]}):t.jsx(gk,{history:x}),t.jsxs("details",{className:"ih-detail__disclosure",children:[t.jsx("summary",{children:"Observation details"}),t.jsxs("dl",{className:"ih-detail__facts",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Checked"}),t.jsx("dd",{children:uk(a.checkedAt)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Observed"}),t.jsx("dd",{children:uk(a.observedAt)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Cadence"}),t.jsx("dd",{children:ck(v.intervalSeconds)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Stale after"}),t.jsx("dd",{children:ck(v.staleAfterSeconds)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Timeout"}),t.jsx("dd",{children:ck(v.timeoutMs/1e3)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Poller"}),t.jsx("dd",{children:v.source})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Last success"}),t.jsx("dd",{children:uk(a.lastSuccessAt)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Last failure"}),t.jsx("dd",{children:uk(a.lastFailureAt)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Last transition"}),t.jsx("dd",{children:uk(a.lastTransitionAt)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Current metric"}),t.jsx("dd",{children:dk(a.value,a.unit)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Collector"}),t.jsx("dd",{children:v.collector})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Check version"}),t.jsx("dd",{children:v.version})]})]})]}),t.jsxs("details",{className:"ih-detail__disclosure",children:[t.jsx("summary",{children:"Check and proof"}),t.jsxs("div",{className:"ih-detail__disclosure-body",children:[t.jsxs("p",{children:[v.type," via ",v.source,". This check is version ",v.version," and runs through ",v.collector,"."]}),t.jsxs("p",{children:[t.jsx("strong",{children:"What it proves:"})," ",v.proves]}),t.jsxs("p",{children:[t.jsx("strong",{children:"What it does not prove:"})," ",v.doesNotProve]}),t.jsxs("p",{children:["Reason: ",(k=a.reasonCode,k?String(k).toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"Reason unavailable")," (",t.jsx("code",{children:a.reasonCode}),")"]})]})]}),t.jsxs("details",{className:"ih-detail__disclosure",children:[t.jsx("summary",{children:"Dependencies"}),t.jsx("div",{className:"ih-detail__disclosure-body",children:j.length?t.jsx("ul",{children:j.map(e=>t.jsx("li",{children:e.name},e.key))}):t.jsx("p",{children:"No catalog dependencies are declared."})})]}),t.jsxs("details",{className:"ih-detail__disclosure",children:[t.jsx("summary",{children:"Safe diagnostics"}),t.jsx("div",{className:"ih-detail__disclosure-body",children:y.length?t.jsx("dl",{className:"ih-detail__diagnostics",children:y.map(([e,a])=>t.jsxs("div",{children:[t.jsx("dt",{children:vk(e)}),t.jsx("dd",{children:jk(a)})]},e))}):t.jsx("p",{children:"No allowlisted diagnostic aggregate is available."})})]}),t.jsxs("details",{className:"ih-detail__disclosure",children:[t.jsx("summary",{children:"Recent transitions"}),t.jsx("div",{className:"ih-detail__disclosure-body",children:b?.transitions?.length?t.jsx("ol",{className:"ih-transition-list",children:b.transitions.map(e=>t.jsxs("li",{children:[t.jsx("span",{children:uk(e.at)}),t.jsx("strong",{children:e.status}),t.jsx("p",{children:e.summary})]},`${e.at}-${e.reasonCode}`))}):t.jsx("p",{children:"No status transition is recorded in bounded history."})})]})]})});var k}const kk=Object.freeze({search:"",status:"all",category:"all",expectedMode:"all",criticality:"all",provider:"all",region:"all",staleOnly:!1,includeInactive:!1}),wk="wikibase-health";function Nk(){return"undefined"==typeof window?new URLSearchParams:new URLSearchParams(window.location.search)}function Sk(){const e=Nk().get("category");return"wikibase"!==e?kk:{...kk,category:e}}function Ck(){const e=Nk().get("returnTo");return e===wk?e:null}const Rk=new Set(["disabled","dormant","absent"]),Ek=new Set(["degraded","down","unknown"]),Ik=new Set(["stale","error","never_run"]),_k=Object.freeze(["category","staleOnly","expectedMode","criticality","provider","region","includeInactive"]);function Tk(e){return Ek.has(e.status)||Ik.has(e.monitorStatus)}function Ak(e,t=" · "){if(!e?.length)return"No 24-hour history";const a=e.reduce((e,t)=>
2(e[t.status]=(e[t.status]||0)+1,e),{});return Object.entries(a).map(([e,t])=>`${t} ${e}`).join(t)}function Ok(e){const t=e?.[0],a=e?.at(-1),n=e?.reduce((t,a,n)=>t+(n>0&&a.status!==e[n-1].status),0)||0;return[`24-hour status: ${Ak(e,", ")}.`,`Oldest ${uk(t?.at)}, ${t?.status}.`,`Latest ${uk(a?.at)}, ${a?.status}.`,`${n} status ${1===n?"change":"changes"}.`].join(" ")}function Dk(e){const t=Date.parse(e);return e&&Number.isFinite(t)?new Date(t).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}):"not observed"}function Pk({history:e}){if(!e?.length)return t.jsx("span",{className:"ih-history-none",children:"No history"});const a=e[0],n=e.at(-1),s=e.reduce((t,a,n)=>t+(n>0&&a.status!==e[n-1].status),0),r=`${s} status ${1===s?"change":"changes"}`;return t.jsxs("span",{className:"ih-history-overview",children:[t.jsx("span",{className:"ih-history-strip",role:"img","aria-label":Ok(e),children:e.map(e=>t.jsx("span",{className:`ih-history-strip__segment ih-status-fill--${e.status}`,title:`${uk(e.at)} â ${e.status}`},e.at))}),t.jsx("span",{className:"ih-history-state-summary",children:Ak(e)}),t.jsx("span",{className:"ih-history-endpoints",children:t.jsxs("span",{children:[t.jsx("span",{className:"sr-only",children:"Oldest "}),t.jsx("time",{dateTime:a.at,title:uk(a.at),children:Dk(a.at)}),t.jsx("span",{children:a.status}),t.jsx("span",{"aria-hidden":"true",children:"â"}),t.jsx("span",{className:"sr-only",children:"Latest "}),t.jsx("time",{dateTime:n.at,title:uk(n.at),children:Dk(n.at)}),t.jsx("span",{children:n.status}),t.jsx("span",{"aria-hidden":"true",children:"·"}),t.jsx("span",{children:r})]})})]})}const Lk=Object.freeze({ready:"Ready",draining:"Draining",constrained:"Constrained",stalled:"Stalled",blocked:"Blocked",telemetry_degraded:"Telemetry degraded"});function $k(e,t,a,n="Not observed"){return!0===e?t:!1===e?a:n}function Mk(e){return!0===e.releaseReady?"Release gate ready":!1!==e.releaseReady?"Release gate not observed":Number.isFinite(e.releaseThreshold)?`Release gate blocked until below ${dk(e.releaseThreshold,null)}`:"Release gate not ready; threshold not observed"}function Uk({service:e}){const a=e.details||{};return"wikibase-job-queue"===e.key?t.jsxs("ul",{className:"ih-service-facts","aria-label":"MediaWiki job queue facts",children:[t.jsxs("li",{children:["Runner ",a.runnerHealthy?"healthy":"unavailable"]}),t.jsxs("li",{children:["Governor ",a.governorState||"unknown"]}),t.jsx("li",{children:$k(a.telemetryHealthy,"Queue telemetry current","Queue telemetry degraded","Queue telemetry not observed")}),t.jsx("li",{children:$k(a.runnerResultTelemetryHealthy,"Runner result telemetry current","Runner result telemetry degraded","Runner result telemetry not observed")}),t.jsx("li",{children:Number.isFinite(a.completedPerMinute)?`${dk(a.completedPerMinute,null)} completed/min`:"Completed: Not observed"}),t.jsx("li",{children:Number.isFinite(a.arrivalPerMinute)?`${dk(a.arrivalPerMinute,null)} arrived/min`:"Arrived: Not observed"}),t.jsx("li",{children:Number.isFinite(a.netDrainPerMinute)?`${dk(a.netDrainPerMinute,null)} net drain/min`:"Net drain: Not observed"}),t.jsx("li",{children:Number.isFinite(a.quarantinedNotificationJobs)?`${dk(a.quarantinedNotificationJobs,null)} notifications quarantined`:"Quarantined notification count unavailable"}),t.jsx("li",{children:Number.isFinite(a.unsupportedJobCount)?`${dk(a.unsupportedJobCount,null)} unsupported jobs quarantined`:"Unsupported job count unavailable"}),t.jsx("li",{children:$k(a.backupRecoveryPending,"Post-backup recovery pending","No post-backup recovery pending","Post-backup recovery not observed")}),t.jsx("li",{children:Mk(a)})]}):"wikibase-root-ebs"===e.key?t.jsxs("ul",{className:"ih-service-facts","aria-label":"Wikibase root EBS facts",children:[t.jsx("li",{children:a.encryptionEnabled?"Encrypted":"Unencrypted"}),t.jsx("li",{children:"attached"===a.attachmentState?"Attached":"Attachment unavailable"}),Number.isFinite(a.volumeSizeGiB)?t.jsxs("li",{children:[a.volumeSizeGiB," GiB"]}):null,a.currentRoot?t.jsx("li",{children:"Current production root"}):null]}):null}function Fk({service:a,now:n}){const[s,r]=e.useState(!1);return t.jsxs("details",{className:"ih-service-mobile-evidence",onToggle:e=>r(e.currentTarget.open),children:[t.jsx("summary",{children:"Supporting evidence"}),s?t.jsxs("dl",{children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Diagnosis"}),t.jsxs("dd",{children:[t.jsx("p",{className:"ih-service-summary",children:a.summary}),t.jsx(Uk,{service:a}),a.lastObservedStatus?t.jsxs("span",{className:"ih-last-observed",children:["Last observed: ",a.lastObservedStatus]}):null]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Last success"}),t.jsx("dd",{children:hk(a.lastSuccessAt,n)})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"24-hour history"}),t.jsxs("dd",{children:[t.jsx(Pk,{history:a.statusHistory}),t.jsx("span",{className:"ih-cell-subtext",children:null==a.historyCoverage24h?"Coverage unavailable":`${Math.round(a.historyCoverage24h)}% coverage`})]})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Polled by"}),t.jsxs("dd",{children:[t.jsx("span",{children:a.check.source}),t.jsxs("span",{className:"ih-cell-subtext",children:["Every ",ck(a.check.intervalSeconds)," · stale after"," ",ck(a.check.staleAfterSeconds)]})]})]})]}):null]})}function zk({snapshot:e}){const a=[["Healthy",e.summary.healthy],["Degraded",e.summary.degraded],["Down",e.summary.down],["Unknown",e.summary.unknown],["Maintenance",e.summary.maintenance],["Inactive",e.summary.disabled]],n=e.services.filter(e=>!Rk.has(e.expectedMode)&&Tk(e)).length,s=[["Overall",e.overallStatus,!0,"ih-summary__item--overall"],["Actionable exceptions",n,!1,"ih-summary__item--actionable"],["Collector",e.collector.status,!0,"ih-summary__item--collector"]],r=([e,a,n,s=""])=>t.jsxs("div",{className:`ih-summary__item ${s}`.trim(),children:[t.jsx("dt",{children:e}
2),t.jsx("dd",{children:n?t.jsx(bk,{status:a,labelPrefix:e}):a})]},e);return t.jsxs("div",{className:"ih-summary-block",children:[t.jsxs("div",{className:"ih-summary-block__heading",children:[t.jsx("h3",{children:"All-infrastructure snapshot"}),t.jsx("p",{children:"Counts cover the full catalog, even when the service list is filtered."})]}),t.jsx("dl",{className:"ih-summary","aria-label":"All-infrastructure snapshot summary",children:s.map(r)}),t.jsxs("details",{className:"ih-summary-details",children:[t.jsx("summary",{children:"All status counts"}),t.jsx("dl",{className:"ih-summary ih-summary--status-counts",children:a.map(r)})]})]})}function qk({label:e,value:a,onChange:n,children:s}){return t.jsxs("label",{className:"ih-filter-field",children:[t.jsx("span",{children:e}),t.jsx("select",{value:a,onChange:e=>n(e.target.value),children:s})]})}function Bk(e){return`ih-service-row ih-service-row--${e.status}${Tk(e)?" ih-service-row--exception":""}`}function Wk({label:e,services:a,now:n,onOpen:s,tableFocusable:r}){return t.jsxs("section",{className:"ih-service-group","aria-labelledby":`ih-group-${a[0].category}`,children:[t.jsxs("div",{className:"ih-service-group__heading",children:[t.jsx("h3",{id:`ih-group-${a[0].category}`,children:e}),t.jsx("span",{children:a.length})]}),t.jsxs(Bu,{className:"ih-service-table",minWidth:"960px",ariaLabel:`${e} services`,focusable:r,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{scope:"col",children:"Service"}),t.jsx("th",{scope:"col",children:"State"}),t.jsx("th",{scope:"col",children:"Diagnosis"}),t.jsx("th",{scope:"col",children:"Checked"}),t.jsx("th",{scope:"col",children:"24h"}),t.jsx("th",{scope:"col",children:"Polled by"}),t.jsx("th",{scope:"col",children:"Details"})]})}),t.jsx("tbody",{children:a.map(e=>t.jsxs("tr",{className:Bk(e),children:[t.jsxs("td",{"data-label":"Service",children:[t.jsxs("div",{className:"ih-service-identity",children:[t.jsx("strong",{children:e.name}),t.jsxs("span",{children:[e.criticality," · ",e.provider," · ",e.region]})]}),t.jsx(Fk,{service:e,now:n})]}),t.jsx("td",{"data-label":"State",children:t.jsxs("div",{className:"ih-service-state",children:[t.jsx(bk,{status:e.status,labelPrefix:"Service",label:Lk[e.details?.operationalState]}),t.jsx(bk,{status:e.monitorStatus,monitor:!0,labelPrefix:"Monitor"})]})}),t.jsxs("td",{"data-label":"Metric",className:"ih-service-metric-cell"+(Number.isFinite(e.value)?"":" ih-service-metric-cell--empty"),children:[Number.isFinite(e.value)?t.jsx("strong",{className:"ih-primary-metric",children:dk(e.value,e.unit)}):null,t.jsx("p",{className:"ih-service-summary",children:e.summary}),t.jsx(Uk,{service:e}),e.lastObservedStatus?t.jsxs("span",{className:"ih-last-observed",children:["Last observed: ",e.lastObservedStatus]}):null]}),t.jsx("td",{"data-label":"Checked",children:t.jsxs("div",{className:"ih-cell-stack",children:[t.jsx("time",{dateTime:e.checkedAt||void 0,title:uk(e.checkedAt),children:hk(e.checkedAt,n)}),t.jsxs("span",{className:"ih-cell-subtext",children:["Last success ",hk(e.lastSuccessAt,n)]})]})}),t.jsx("td",{"data-label":"24-hour history",className:"ih-service-history-cell",children:t.jsxs("div",{className:"ih-cell-stack",children:[t.jsx(Pk,{history:e.statusHistory}),t.jsx("span",{className:"ih-cell-subtext",children:null==e.historyCoverage24h?"Coverage unavailable":`${Math.round(e.historyCoverage24h)}% coverage`})]})}),t.jsx("td",{"data-label":"Polled by",className:"ih-service-poller-cell",children:t.jsxs("div",{className:"ih-cell-stack",children:[t.jsx("span",{children:e.check.source}),t.jsxs("span",{className:"ih-cell-subtext",children:["Every ",ck(e.check.intervalSeconds)," · stale after"," ",ck(e.check.staleAfterSeconds)]})]})}),t.jsx("td",{className:"ih-service-action",children:t.jsxs("button",{type:"button",onClick:t=>s(e,t.currentTarget),"aria-label":`Open ${e.name} health detail`,children:[t.jsx("span",{className:"ih-service-action__label",children:"Details"}),t.jsx(J,{size:18,"aria-hidden":"true"})]})})]},e.key))})]})]})}const Vk=Object.freeze(Object.defineProperty({__proto__:null,default:function({request:n}){const s=function({enabled:t=!0,request:a}={}){const{makeAuthRequest:n}=Yn(),s=a||n,[r,i]=e.useState(null),[l,o]=e.useState(t),[c,d]=e.useState(!1),[u,h]=e.useState(null),[m,p]=e.useState(!rk()),[g,f]=e.useState(0),[b,x]=e.useState(null),[v,j]=e.useState(()=>Date.now()),[y,k]=e.useState(""),w=e.useRef(!1),N=e.useRef(null),S=e.useRef(null),C=e.useRef(0),R=e.useRef(0),E=e.useRef(0),I=e.useRef(null),_=e.useRef(0),T=e.useRef(null),A=e.useCallback(async({eventDriven:e=!1}={})=>
2{if(!t||!rk())return null;if(e&&!sk())return null;if(e&&Date.now()-E.current<5e3)return null;if(N.current&&!S.current?.signal.aborted)return N.current;const a=++C.current,n=new AbortController;let r;return S.current=n,T.current?d(!0):o(!0),r=(async()=>{try{const e=await s("/api/admin/infrastructure-health",{method:"GET",cache:"no-store",signal:n.signal});if(!w.current||a<R.current)return null;const t=e?.data||null;if(!t?.services||!Array.isArray(t.services)){const e=new Error("Infrastructure Health returned an invalid snapshot.");throw e.code="INFRASTRUCTURE_SNAPSHOT_INVALID",e}R.current=a;const r=I.current;r&&r!==t.overallStatus&&k(`Infrastructure Health changed from ${r} to ${t.overallStatus}.`),I.current=t.overallStatus,T.current=t,i(t),h(null),_.current=0,f(0);const l=Date.now();return E.current=l,x(l),t}catch(e){if("AbortError"===e?.name||"AUTH_SESSION_STALE"===e?.code)return null;if(!w.current||a<R.current)return null;R.current=a;const t=_.current+1;return _.current=t,f(t),h(e),k("Infrastructure Health snapshot refresh failed. Previous data is retained."),E.current=Date.now(),null}finally{w.current&&(o(!1),d(!1)),S.current===n&&(S.current=null),N.current===r&&(N.current=null)}})(),N.current=r,r},[t,s]);return e.useEffect(()=>(w.current=!0,()=>{w.current=!1,S.current?.abort()}),[]),e.useEffect(()=>{t&&A()},[t,A]),e.useEffect(()=>{if(!t||"undefined"==typeof window)return;const e=()=>{A({eventDriven:!0})},a=()=>{sk()&&A({eventDriven:!0})},n=()=>{p(!1),A({eventDriven:!0})},s=()=>{p(!0),S.current?.abort()};return window.addEventListener("focus",e),window.addEventListener("online",n),window.addEventListener("offline",s),document.addEventListener("visibilitychange",a),()=>{window.removeEventListener("focus",e),window.removeEventListener("online",n),window.removeEventListener("offline",s),document.removeEventListener("visibilitychange",a)}},[t,A]),e.useEffect(()=>{if(!t)return;const e=0===g?6e4:nk[Math.min(g-1,1)],a=setInterval(()=>{sk()&&rk()&&A({eventDriven:!0})},e);return()=>clearInterval(a)},[t,g,A]),e.useEffect(()=>{const e=setInterval(()=>j(Date.now()),3e4);return()=>clearInterval(e)},[]),{request:s,snapshot:r,loading:l,refreshing:c,error:u,offline:m,paused:!sk()||m,failureCount:g,lastFetchedAt:b,now:v,announcement:y,pollIntervalMs:0===g?6e4:nk[Math.min(g-1,1)],refresh:A}}({request:n}),r=Vv("(max-width: 900px)"),[i,l]=e.useState(Sk),[o]=e.useState(Ck),[c,d]=e.useState(null),u=s.snapshot,h=e.useMemo(()=>{if(!u)return[];const e=i.search.trim().toLowerCase();return u.services.filter(e=>i.includeInactive||!1!==e.visibleByDefault).filter(e=>"all"===i.status||("exceptions"===i.status?Tk(e):e.status===i.status)).filter(e=>"all"===i.category||e.category===i.category).filter(e=>"all"===i.expectedMode||e.expectedMode===i.expectedMode).filter(e=>"all"===i.criticality||e.criticality===i.criticality).filter(e=>"all"===i.provider||e.provider===i.provider).filter(e=>"all"===i.region||e.region===i.region).filter(e=>!i.staleOnly||Ik.has(e.monitorStatus)).filter(t=>!e||`${t.name} ${t.summary} ${t.owner} ${t.category}`.toLowerCase().includes(e)).sort((e,t)=>lk[e.status]-lk[t.status]||ok[e.criticality]-ok[t.criticality]||e.name.localeCompare(t.name))},[i,u]),m=e.useMemo(()=>{const e=new Map;for(const t of h)e.has(t.category)||e.set(t.category,[]),e.get(t.category).push(t);return[...e.entries()]},[h]),p=(e,t)=>l(a=>({...a,[e]:t})),g=Object.entries(kk).some(([e,t])=>i[e]!==t),f=_k.filter(e=>i[e]!==kk[e]).length,b="wikibase"===i.category,[x,v]=e.useState(null);a.useEffect(()=>{const e=i.search?350:0,t=window.setTimeout(()=>v(h.length),e);return()=>window.clearTimeout(t)},[h.length,i.search]);const j=u?.services.filter(e=>"critical"===e.criticality&&!Rk.has(e.expectedMode)&&Ik.has(e.monitorStatus))||[];if(s.loading&&!u)return t.jsxs("section",{className:"ih-panel","aria-labelledby":"infrastructure-health-title",children:[t.jsx("h2",{id:"infrastru
2cture-health-title",className:"sr-only",children:"Persisted infrastructure snapshot"}),t.jsx("div",{className:"ih-skeleton ih-skeleton--header"}),t.jsx("div",{className:"ih-skeleton ih-skeleton--summary"}),t.jsx("div",{className:"ih-skeleton ih-skeleton--table"}),t.jsx("span",{className:"sr-only",role:"status",children:"Loading persisted Infrastructure Health snapshot"})]});if(!u)return t.jsx("section",{className:"ih-panel","aria-labelledby":"infrastructure-health-title",children:t.jsxs("div",{className:"ih-empty-state ih-empty-state--error",role:"alert",children:[t.jsx(be,{size:24,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("h2",{id:"infrastructure-health-title",children:"Persisted infrastructure snapshot"}),t.jsx("p",{children:"The protected persisted snapshot is unavailable. No provider checks were started by this page."})]}),t.jsx(ds,{variant:"secondary",onClick:()=>s.refresh(),children:"Retry snapshot"})]})});const y=function(e,t){const a=Date.parse(e?.lastCompletedAt||""),n=Date.parse(e?.nextExpectedAt||""),s=Number(t);if(!Number.isFinite(a)||!Number.isFinite(s))return!1;const r=a+(Number.isFinite(e?.staleAfterSeconds)?1e3*e.staleAfterSeconds:72e4),i=!e?.nextExpectedAt||Number.isFinite(n)&&n>=a&&n<=r;return a<=s+3e5&&s<=r&&i}(u.collector,s.now),k="current"!==u.collector.status||"partial"===u.collector.runStatus||!y,w=s.offline?"offline":s.paused?"paused":k?"stale":"current",N={current:"Current persisted snapshot",stale:"Stale persisted snapshot",paused:"Last persisted snapshot",offline:"Last persisted snapshot"}[w],S=u.collector.lastCompletedAt;return t.jsxs("section",{className:"ih-panel","aria-labelledby":"infrastructure-health-title",children:[t.jsx("p",{className:"sr-only","aria-live":"polite","aria-atomic":"true",children:s.announcement}),t.jsxs("header",{className:"ih-header",children:[t.jsxs("div",{className:"ih-header__identity",children:[t.jsx("span",{className:"ih-header__icon","aria-hidden":"true",children:t.jsx(Ht,{size:22})}
2),t.jsxs("div",{children:[t.jsx("h2",{id:"infrastructure-health-title",className:"sr-only",children:"Persisted infrastructure snapshot"}),t.jsxs("span",{className:`ih-live-state ih-live-state--${w}`,children:[s.offline?t.jsx(Kt,{size:15,"aria-hidden":"true"}):null,N]}),t.jsxs("p",{className:"ih-snapshot-evidence-time",children:["Collected"," ",t.jsxs("time",{dateTime:S||void 0,children:[hk(S,s.now)," ·"," ",uk(S)]}),t.jsx("span",{"aria-hidden":"true",children:" · "}),t.jsxs("span",{children:["Next expected ",uk(u.collector.nextExpectedAt)]})]}),o===wk?t.jsx("a",{className:"ih-context-return",href:"/dashboard/employee?tab=wikibase&view=health",children:"Back to Wikibase query & import health"}):null]})]}),t.jsx("div",{className:"ih-header__actions",children:t.jsxs(ds,{variant:"secondary",onClick:()=>s.refresh(),disabled:s.refreshing||s.offline,className:"ih-refresh-button",children:[t.jsx(ce,{size:16,className:s.refreshing?"ih-refresh-icon--active":"","aria-hidden":"true"}),s.refreshing?"Refreshingâ¦":"Refresh snapshot"]})})]}),j.length||k||s.offline?t.jsxs("div",{className:"ih-callout ih-callout--warning",role:"status",children:[t.jsx(be,{size:19,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("strong",{children:"Freshness needs attention."}),t.jsxs("p",{children:["current"!==u.collector.status?`Collector is ${u.collector.status}. `:"","partial"===u.collector.runStatus?"The latest collector run was partial; successful prior evidence remains visible. ":"",y||"current"!==u.collector.status?"":"Collector evidence is outside its freshness window. ",s.offline?"The browser is offline; the last persisted snapshot remains visible. ":"",j.length?`${j.length} critical service monitor${1===j.length?" is":"s are"} stale, errored, or unobserved.`:"No critical service monitor is currently stale."]})]})]}):null,b?t.jsxs("div",{className:"ih-scope-banner","aria-label":"Active service scope",children:[t.jsxs("span",{children:[t.jsx("strong",{children:"Scoped to Wikibase"}),t.jsx("span",{children:"Only Wikibase services are listed below."})]}),t.jsx("button",{type:"button",onClick:()=>p("category","all"),children:"Show all services"})]}):null,t.jsx(zk,{snapshot:u}),s.error?t.jsxs("div",{className:"ih-callout ih-callout--error",role:"alert",children:[t.jsx(be,{size:19,"aria-hidden":"true"}),t.jsx("p",{children:"Snapshot refresh failed. Previous data remains visible and polling has backed off."})]}):null,t.jsxs("section",{className:"ih-filters","aria-labelledby":"ih-filters-title",children:[t.jsx("div",{className:"ih-filters__heading",children:t.jsxs("div",{children:[t.jsx("h3",{id:"ih-filters-title",children:"Services"}),t.jsxs("p",{id:"ih-filter-result-count",children:[h.length," shown · ",u.summary.disabled," inactive hidden by default"]}),t.jsx("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:Number.isFinite(x)?`${x} service${1===x?"":"s"} shown.`:""})]})}),t.jsxs("div",{className:"ih-filter-controls ih-filter-controls--primary",children:[t.jsxs("label",{className:"ih-filter-field ih-filter-field--search",children:[t.jsx("span",{children:"Search"}),t.jsxs("span",{className:"ih-search-input",children:[t.jsx(ue,{size:16,"aria-hidden":"true"}),t.jsx("input",{type:"search",value:i.search,onChange:e=>p("search",e.target.value),placeholder:"Service, owner, or diagnosis"})]})]}),t.jsxs(qk,{label:"Status",value:i.status,onChange:e=>p("status",e),children:[t.jsx("option",{value:"all",children:"All statuses"}),t.jsx("option",{value:"exceptions",children:"Exceptions only"}),["down","degraded","unknown","healthy","maintenance","disabled"].map(e=>t.jsx("option",{value:e,children:e},e))]}),t.jsx("button",{type:"button",className:"ih-clear-filters",disabled:!g,onClick:()=>l(kk),children:"Clear filters"})]}),t.jsxs("details",{className:"ih-more-filters",children:[t.jsxs("summary",{children:[t.jsx(Gt,{size:16,"aria-hidden":"true"})," More filters",f?` · ${f} active`:""]}),t.jsxs("div",{className:"ih-filter-controls ih-filter-controls--diagnostic",children:[t.jsxs(qk,{label:"Category",value:i.category,onChange:e=>p("category",e),children:[t.jsx("option",{value:"all",children:"All categories"}),u.filters.categories.map(e=>t.jsx("option",{value:e,children:ik[e]||e},e))]}),t.jsxs("label",{className:"ih-check-filter",children:[t.jsx("input",{type:"checkbox",checked:i.staleOnly,onChange:e=>p("staleOnly",e.target.checked)}),"Stale only"]}),t.jsxs(qk,{label:"Mode",value:i.expectedMode,onChange:e=>p("expectedMode",e),children:[t.jsx("option",{value:"all",children:"All modes"}),["active","on_demand","maintenance","dormant","disabled"].map(e=>t.jsx("option",{value:e,children:e.replace("_"," ")},e))]}),t.jsxs(qk,{label:"Criticality",value:i.criticality,onChange:e=>p("criticality",e),children:[t.jsx("option",{value:"all",children:"All criticalities"}),["critical","high","medium","low"].map(e=>t.jsx("option",{value:e,children:e},e))]}
2),t.jsxs(qk,{label:"Provider",value:i.provider,onChange:e=>p("provider",e),children:[t.jsx("option",{value:"all",children:"All providers"}),u.filters.providers.map(e=>t.jsx("option",{value:e,children:e},e))]}),t.jsxs(qk,{label:"Region",value:i.region,onChange:e=>p("region",e),children:[t.jsx("option",{value:"all",children:"All regions"}),u.filters.regions.map(e=>t.jsx("option",{value:e,children:e},e))]}),t.jsxs("label",{className:"ih-check-filter",children:[t.jsx("input",{type:"checkbox",checked:i.includeInactive,onChange:e=>p("includeInactive",e.target.checked)}),"Include inactive"]})]}),t.jsx("div",{className:"ih-more-filters__actions",children:t.jsx("button",{type:"button",className:"ih-clear-filters",disabled:!f,onClick:()=>l(e=>({...e,...Object.fromEntries(_k.map(e=>[e,kk[e]]))})),children:"Clear more filters"})})]})]}),t.jsx("div",{className:"ih-results","aria-describedby":"ih-filter-result-count",children:m.length?m.map(([e,a])=>t.jsx(Wk,{label:ik[e]||e,services:a,now:s.now,tableFocusable:!r,onOpen:e=>d(e)},e)):t.jsxs("div",{className:"ih-empty-state",children:[t.jsx(Ht,{size:24,"aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("h3",{children:"No services match these filters"}),t.jsx("p",{children:"Clear one or more filters to return to the current catalog."}),t.jsx("button",{type:"button",className:"ih-clear-filters",onClick:()=>l(kk),children:"Clear filters"})]})]})}),t.jsxs("footer",{className:"ih-disclaimer",children:[t.jsx("p",{children:u.disclaimer}),t.jsx("p",{children:"Browser refreshes only this protected snapshot. They never call AWS, Vercel, GitHub, Neon, Stripe, Resend, Wikibase, or Jupyter providers."})]}),t.jsx(yk,{service:c,request:n||s.request,onClose:()=>d(null)})]})}},Symbol.toStringTag,{value:"Module"}));export{Vl as $,Vs as A,Cs as B,Js as C,Yy as D,Is as E,Ns as F,Qy as G,ws as H,oc as I,Fn as J,Cl as K,Ts as L,Rl as M,Tn as N,To as O,zs as P,ri as Q,ls as R,Ws as S,Bs as T,gr as U,Po as V,Yo as W,uo as X,Io as Y,fo as Z,Wa as _,Zy as a,jv as a$,zo as a0,li as a1,si as a2,kc as a3,qr as a4,Wr as a5,fc as a6,Ir as a7,Wm as a8,Og as a9,Uu as aA,Wg as aB,Fu as aC,ab as aD,lf as aE,zu as aF,Wu as aG,ds as aH,$g as aI,Ku as aJ,Bu as aK,qu as aL,Gu as aM,Ab as aN,Ju as aO,Mg as aP,yv as aQ,Ug as aR,$b as aS,Ub as aT,Lg as aU,qb as aV,Rv as aW,_v as aX,mb as aY,pb as aZ,xb as a_,ad as aa,md as ab,Bc as ac,Km as ad,Xm as ae,Ap as af,Sp as ag,Hp as ah,ju as ai,$d as aj,qd as ak,wh as al,pg as am,kg as an,Op as ao,Dg as ap,bp as aq,Gx as ar,Yx as as,hx as at,gx as au,mx as av,Xx as aw,$s as ax,qg as ay,zg as az,ek as b,rj as b$,uv as b0,Yu as b1,zb as b2,Qu as b3,tf as b4,xm as b5,Mb as b6,rn as b7,dj as b8,jy as b9,Vv as bA,Ui as bB,Bi as bC,qi as bD,Fi as bE,Lo as bF,Za as bG,yl as bH,kl as bI,Uy as bJ,eo as bK,Ss as bL,jl as bM,vl as bN,qy as bO,zy as bP,By as bQ,hy as bR,ly as bS,Wy as bT,uy as bU,Zr as bV,ai as bW,ti as bX,Ky as bY,Hy as bZ,Ov as b_,Fj as ba,zj as bb,Tj as bc,Pj as bd,_j as be,Lj as bf,$j as bg,Uj as bh,Mj as bi,Vj as bj,ml as bk,Hi as bl,Yi as bm,ul as bn,My as bo,hj as bp,iv as bq,Kb as br,Gb as bs,Yb as bt,ox as bu,cx as bv,ux as bw,dx as bx,px as by,Jb as bz,Xy as c,Vk as c0,tk as d,ak as e,Yn as f,ec as g,Xo as h,tc as i,bc as j,Qo as k,Zo as l,cc as m,Us as n,qs as o,Hs as p,Ks as q,Jn as r,Os as s,es as t,Ds as u,Ls as v,os as w,Ys as x,Xs as y,Rs as z};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.