forge-openclaw-plugin 0.2.66 → 0.2.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -55,7 +55,7 @@ Take a ten-minute reset walk`})})]})},{id:"links",eyebrow:"Placement",title:"Pla
55
55
  `)}function Kg(t,s){return[t,"- Open Forge from a local browser on the host running Forge.",`- Use one of these local addresses: ${s.join(", ")}.`].join(`
56
56
  `)}function Sv(t){return{clientId:(t.clientId??"").trim(),clientSecret:(t.clientSecret??"").trim()}}function _6(t,s){return t.clientId.trim()===s.clientId.trim()&&t.clientSecret.trim()===s.clientSecret.trim()}function F6(t){const s=Sv(t),a={},i=s.clientId.length>0,r=s.clientSecret.length>0;if(i!==r){const n="When overriding Google OAuth credentials, save the client ID and client secret together, or clear both to use the bundled defaults.";i||(a.clientId=n),r||(a.clientSecret=n)}return{normalized:s,issues:a,isValid:Object.keys(a).length===0}}function Ju(t){return{clientId:t.clientId.trim(),tenantId:t.tenantId.trim()||"common",redirectUri:t.redirectUri.trim()}}function R6(t){const s=Ju(t),a={};if(s.clientId?E6.test(s.clientId)||(a.clientId="Use the Microsoft app registration client ID GUID."):a.clientId="Microsoft client ID is required.",!s.redirectUri)a.redirectUri="Redirect URI is required.";else try{const i=new URL(s.redirectUri);i.protocol!=="http:"&&i.protocol!=="https:"?a.redirectUri="Redirect URI must use http or https.":i.pathname!==$g&&(a.redirectUri=`Redirect URI must end with ${$g}.`)}catch{a.redirectUri="Redirect URI must be a full URL."}return{normalized:s,issues:a,isValid:Object.keys(a).length===0}}function D6(t,s){return t.clientId.trim()===s.clientId.trim()&&t.tenantId.trim()===s.tenantId.trim()&&t.redirectUri.trim()===s.redirectUri.trim()}function Zu(t){return t==="127.0.0.1"||t==="localhost"}function $6(t){return t.endsWith(".ts.net")}function O6(t){t.allowedOrigins.filter(i=>{try{return Zu(new URL(i).hostname)}catch{return!1}});const s=(()=>{try{return new URL(t.redirectUri).hostname}catch{return""}})();let a="";try{a=new URL(t.currentOrigin).hostname}catch{a=""}return $6(a)&&Zu(s)?`Google sign-in has to start from a local browser on the host running Forge. Forge is currently open through Tailscale at ${t.currentOrigin}, but Google sends the callback to localhost on the device that opens the popup. On a phone or another computer, that callback goes to that device instead of the Forge host.`:t.isLocalOnly?"Google sign-in has to start from a local browser on the host running Forge. Google sends the callback to localhost, so if Forge is opened remotely, the callback goes to the other device instead of the Forge host.":`Google sign-in is only enabled from the configured Forge host for this deployment. Open Forge on ${t.appBaseUrl}. Current browser origin: ${t.currentOrigin}.`}function z6({open:t,onOpenChange:s,initialProvider:a="google",initialStepId:i,googleSetup:r,microsoftSetup:n,onCalendarSettingsChanged:l,existingConnections:o=[],onSubmit:d,pending:m=!1}){const h=pt(),[c,p]=u.useState(()=>tu(a)),[g,x]=u.useState(null),[f,b]=u.useState(null),[A,T]=u.useState("not_determined"),[I,y]=u.useState(null),[N,k]=u.useState(null),[w,P]=u.useState(null),[j,R]=u.useState(r),[v,D]=u.useState(()=>Kn(r)),[L,Q]=u.useState(()=>Kn(r)),[Z,V]=u.useState(!1),[B,$]=u.useState(null),[E,X]=u.useState(n),[W,q]=u.useState(()=>To(n)),[G,z]=u.useState(()=>To(n)),[ge,ke]=u.useState(null),me=u.useRef(null),se=(Y=[])=>{const ee=new Set(Y);return o.find(xe=>{var ye;return ee.has(xe.id)?!1:typeof((ye=xe.config)==null?void 0:ye.forgeCalendarUrl)=="string"&&xe.config.forgeCalendarUrl.trim().length>0})??null},we=u.useMemo(()=>c.provider==="microsoft"?null:se(c.replaceConnectionIds),[c.provider,c.replaceConnectionIds,o]),ve=we?we.accountLabel&&we.accountLabel.trim().length>0?`${we.label} · ${we.accountLabel}`:we.label:null,_=Y=>(h.setQueryData(["forge-settings"],Y),Y.settings),F=()=>{k(null),me.current=null},O=()=>{P(null),me.current=null},ce=Y=>{b(Y);const ee=Y.calendars.filter(ye=>ye.selectedByDefault).map(ye=>ye.url),xe=Y.calendars.find(ye=>ye.isForgeCandidate);p(ye=>{const ue=se(ye.replaceConnectionIds);return{...ye,selectedCalendarUrls:ye.selectedCalendarUrls.length>0?ye.selectedCalendarUrls.filter($e=>Y.calendars.some(Xe=>Xe.url===$e)):ee,forgeCalendarUrl:ye.provider==="microsoft"||ue?null:(xe==null?void 0:xe.url)??ye.forgeCalendarUrl??null,createForgeCalendar:ye.provider==="microsoft"||ue?!1:ye.createForgeCalendar&&!xe}}),x(null)};u.useEffect(()=>{var Y;if(!t){(Y=me.current)==null||Y.close(),me.current=null;return}x(null),b(null),p(tu(a)),F(),O(),y(null),T("not_determined"),V(!1),$(null),ke(null)},[a,t]),u.useEffect(()=>{!t||c.provider!=="macos_local"||je.mutateAsync()},[c.provider,t]),u.useEffect(()=>{if(!t||!f||c.provider==="microsoft"||we||c.forgeCalendarUrl||c.createForgeCalendar)return;const Y=f.calendars.find(ee=>ee.isForgeCandidate);Y&&p(ee=>ee.provider==="microsoft"||ee.forgeCalendarUrl||ee.createForgeCalendar||se(ee.replaceConnectionIds)?ee:{...ee,forgeCalendarUrl:Y.url})},[f,c.createForgeCalendar,c.forgeCalendarUrl,c.provider,t,we]),u.useEffect(()=>{if(!t)return;R(r);const Y=Kn(r);D(Y),Q(Y),V(!1),$(null)},[r,t]),u.useEffect(()=>{if(!t)return;X(n);const Y=To(n);q(Y),z(Y),ke(null)},[n,t]),u.useEffect(()=>{if(!t||!N||N.status!=="pending")return;const Y=new URL(j.redirectUri).origin;let ee=!1;const xe=()=>{ee||(ee=!0,ae(N.sessionId).finally(()=>{ee=!1}))},ye=Ge=>{var re,Ae;Ge.origin===Y&&(((re=Ge.data)==null?void 0:re.type)!=="forge:google-calendar-auth"||((Ae=Ge.data)==null?void 0:Ae.sessionId)!==N.sessionId||xe())},ue=()=>{xe()},$e=()=>{document.visibilityState==="visible"&&xe()},Xe=window.setInterval(xe,Og);return window.addEventListener("message",ye),window.addEventListener("focus",ue),document.addEventListener("visibilitychange",$e),()=>{window.removeEventListener("message",ye),window.removeEventListener("focus",ue),document.removeEventListener("visibilitychange",$e),window.clearInterval(Xe)}},[j.redirectUri,N,t]),u.useEffect(()=>{if(!t||!w||w.status!=="pending")return;const Y=new URL(E.redirectUri).origin;let ee=!1;const xe=()=>{ee||(ee=!0,Fe(w.sessionId).finally(()=>{ee=!1}))},ye=Ge=>{var re,Ae;Ge.origin===Y&&(((re=Ge.data)==null?void 0:re.type)!=="forge:microsoft-calendar-auth"||((Ae=Ge.data)==null?void 0:Ae.sessionId)!==w.sessionId||xe())},ue=()=>{xe()},$e=()=>{document.visibilityState==="visible"&&xe()},Xe=window.setInterval(xe,Og);return window.addEventListener("message",ye),window.addEventListener("focus",ue),document.addEventListener("visibilitychange",$e),()=>{window.removeEventListener("message",ye),window.removeEventListener("focus",ue),document.removeEventListener("visibilitychange",$e),window.clearInterval(Xe)}},[E.redirectUri,w,t]);const J=De({mutationFn:()=>c.provider==="macos_local"?zN().then(({discovery:Y})=>{y(Y),T(Y.status);const ee=Y.sources.find(xe=>xe.sourceId===c.sourceId)??Y.sources[0]??null;return ee&&(ce({provider:"macos_local",accountLabel:ee.accountLabel,serverUrl:c.serverUrl,principalUrl:null,homeUrl:null,calendars:ee.calendars}),p(xe=>({...xe,sourceId:ee.sourceId}))),{discovery:null}}):c.provider==="apple"?xp({provider:"apple",username:c.username,password:c.password}):xp({provider:"caldav",serverUrl:c.serverUrl,username:c.username,password:c.password}),onSuccess:({discovery:Y})=>{Y&&ce(Y)},onError:Y=>{b(null),x(Y instanceof Error?Y.message:"Forge could not discover calendars with these credentials.")}}),je=De({mutationFn:$N,onSuccess:({status:Y})=>{T(Y),Y!=="full_access"&&(y(null),b(null))}}),Ee=De({mutationFn:ON,onSuccess:({granted:Y,status:ee,message:xe})=>{if(T(ee),Y){x(null);return}x(xe??"Forge could not obtain Calendar access from macOS yet. Open System Settings > Privacy & Security > Calendars, allow Forge, then return here and click Check access.")},onError:Y=>{x(Y instanceof Error?Y.message:"Forge could not request Calendar access from macOS.")}});u.useEffect(()=>{!t||c.provider!=="macos_local"||A!=="full_access"||I!==null||J.isPending||J.mutateAsync()},[J,c.provider,I,A,t]);const Ce=De({mutationFn:async Y=>{const ee=Ju(Y),xe=await gi({calendarProviders:{microsoft:ee}});return{normalized:ee,settings:_(xe)}},onSuccess:async({settings:Y})=>{X(Y.calendarProviders.microsoft);const ee=To(Y.calendarProviders.microsoft);z(ee),q(ee),ke("Microsoft settings saved. Start the guided Microsoft sign-in when you are ready."),l==null||l()},onError:Y=>{ke(Y instanceof Error?Y.message:"Forge could not save the Microsoft settings.")}}),Ke=De({mutationFn:async Y=>{const ee=Sv(Y),xe=await gi({calendarProviders:{google:ee}});return{normalized:ee,settings:_(xe)}},onSuccess:async({normalized:Y,settings:ee})=>{R(ee.calendarProviders.google);const xe=Kn(ee.calendarProviders.google);Q(xe),D(xe),V(!1),$(Y.clientId||Y.clientSecret?"Google OAuth credentials saved on the Forge server for this install.":"Google OAuth override cleared. Forge will use the packaged or environment default again."),l==null||l()},onError:Y=>{$(Y instanceof Error?Y.message:"Forge could not save the Google OAuth credentials.")}}),Pe=De({mutationFn:Y=>{const ee=Ju(Y);return UN(ee)},onSuccess:({result:Y})=>{ke(Y.message)},onError:Y=>{ke(Y instanceof Error?Y.message:"Forge could not validate the Microsoft configuration.")}}),M=u.useMemo(()=>R6(W),[W]),U=u.useMemo(()=>F6(v),[v]),he=!_6(v,L),Ne=!D6(W,G),fe=typeof window>"u"?"":window.location.origin,Se=u.useMemo(()=>{try{return new URL(j.redirectUri).origin}catch{return""}},[j.redirectUri]),Je=fe.length>0&&j.allowedOrigins.includes(fe)&&(!j.isLocalOnly||Zu(new URL(fe).hostname)),nt=fe&&!Je?O6({currentOrigin:fe,appBaseUrl:j.appBaseUrl,redirectUri:j.redirectUri,allowedOrigins:j.allowedOrigins,isLocalOnly:j.isLocalOnly}):null,K=j.isReadyForPairing?null:L6(j.setupMessage)||zg(),Ie=nt?Kg(nt,j.allowedOrigins):null,_e=Y=>{if(g)return g;if(c.provider==="google"&&(Y==="credentials"||Y==="discovery")){if(he)return"Save the Google OAuth credential change before starting sign-in.";const ee=[Ie,K].filter(xe=>!!xe);if(ee.length>0)return ee.join(`
57
57
 
58
- `)}if(c.provider==="microsoft"&&Y==="credentials"){if(Ne)return"Save these Microsoft settings before starting sign-in.";if(!Ne&&!G.clientId&&!ge)return E.setupMessage}if(c.provider==="macos_local"&&(Y==="credentials"||Y==="discovery")&&A!=="full_access")return A==="unavailable"?"This provider is only available on macOS, because Forge uses EventKit to access the host machine's calendar store.":"Grant Calendar full access for Forge on this Mac before discovering host calendars."},ae=async(Y,ee)=>{try{const{session:xe}=await qN(Y);if(k(xe),xe.status==="authorized"&&xe.discovery){ce(xe.discovery),x(null);return}if(xe.status==="error"||xe.status==="expired"){x(xe.error??"Google sign-in did not complete. Start the guided sign-in again.");return}ee!=null&&ee.afterPopupClose}catch(xe){x(xe instanceof Error?xe.message:"Forge could not confirm the Google sign-in session.")}},Fe=async(Y,ee)=>{try{const{session:xe}=await WN(Y);if(P(xe),xe.status==="authorized"&&xe.discovery){ce(xe.discovery),x(null);return}if(xe.status==="error"||xe.status==="expired"){x(xe.error??"Microsoft sign-in did not complete. Start the guided sign-in again.");return}ee!=null&&ee.afterPopupClose}catch(xe){x(xe instanceof Error?xe.message:"Forge could not confirm the Microsoft sign-in session.")}},ie=async()=>{var Y;try{if(nt)throw new Error(Kg(nt,j.allowedOrigins));if(!j.isReadyForPairing)throw new Error(zg());x(null),b(null);const{session:ee}=await KN({label:ci("google",c.label),browserOrigin:fe||void 0});if(!ee.authUrl)throw new Error("Forge could not prepare the Google sign-in URL.");if(k(ee),(Y=me.current)==null||Y.close(),me.current=window.open(ee.authUrl,"forge-google-calendar-auth","popup=yes,width=520,height=720,resizable=yes,scrollbars=yes"),!me.current)throw new Error("The Google sign-in popup was blocked. Allow popups for Forge and try again.");me.current.focus()}catch(ee){F(),x(ee instanceof Error?ee.message:"Forge could not start the Google sign-in flow.")}},Be=async()=>{var Y;try{if(!M.isValid)throw new Error("Enter a valid Microsoft client ID and redirect URI before starting sign-in.");if(Ne)throw new Error("Save the Microsoft settings in this guided flow before starting sign-in.");if(Ce.isPending)throw new Error("Wait for Forge to finish saving the Microsoft settings before starting sign-in.");x(null),ke(null),b(null);const{session:ee}=await BN({label:ci("microsoft",c.label)});if(!ee.authUrl)throw new Error("Forge could not prepare the Microsoft sign-in URL.");if(P(ee),(Y=me.current)==null||Y.close(),me.current=window.open(ee.authUrl,"forge-microsoft-calendar-auth","popup=yes,width=520,height=720,resizable=yes,scrollbars=yes"),!me.current)throw new Error("The Microsoft sign-in popup was blocked. Allow popups for Forge and try again.");me.current.focus()}catch(ee){O(),x(ee instanceof Error?ee.message:"Forge could not start the Microsoft sign-in flow.")}},at=u.useMemo(()=>[{id:"provider",eyebrow:"Connection",title:"Choose the calendar provider Forge should connect to",description:"macOS local uses EventKit to access the calendars already configured on this Mac, Apple uses autodiscovery from caldav.icloud.com, Google uses a localhost Authorization Code + PKCE flow, Exchange Online uses guided Microsoft sign-in in read-only mode, and custom CalDAV stays available for everything else.",render:(Y,ee)=>e.jsxs("div",{className:"grid gap-5",children:[e.jsx(oe,{label:"Provider",description:"Each setup path is guided. Forge discovers calendars before anything is saved.",children:e.jsx(St,{value:Y.provider,onChange:xe=>{b(null),y(null),x(null),ke(null),F(),O(),ee(tu(xe))},options:[{value:"google",label:"Google Calendar",description:"Use Google sign-in with Authorization Code + PKCE, let Forge exchange the code on the backend, and store a per-user refresh token server-side."},{value:"apple",label:"Apple Calendar",description:"Start from https://caldav.icloud.com and autodiscover calendars with your app password."},{value:"microsoft",label:"Exchange Online",description:"Save the Microsoft app registration fields in Settings, then sign in with Microsoft and mirror selected Exchange Online calendars in read-only mode."},{value:"macos_local",label:"Calendars On This Mac",description:"Use EventKit to access the calendars already configured in Calendar.app on this host machine and avoid reconnecting those same accounts manually."},{value:"caldav",label:"Custom CalDAV",description:"Use a CalDAV base URL for Nextcloud, Fastmail, Baikal, and other compatible providers."}]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 text-white",children:[e.jsx(Df,{className:"size-4 text-[var(--primary)]"}),e.jsx("div",{className:"font-medium",children:"Dedicated write calendar"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:Y.provider==="microsoft"?"Exchange Online is read-only for now. Forge mirrors selected calendars into Forge, but it does not publish work blocks or owned timeboxes back to Microsoft.":e.jsxs(e.Fragment,{children:["Forge writes work blocks and owned timeboxes into a dedicated calendar named"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"}),"."]})})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 text-white",children:[e.jsx(rr,{className:"size-4 text-[var(--primary)]"}),e.jsx("div",{className:"font-medium",children:"Discovery first"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:Y.provider==="google"?"Forge opens a Google sign-in popup, exchanges the authorization code on the backend, stores a per-user refresh token, and then discovers the writable calendars for that account.":Y.provider==="macos_local"?"Forge asks macOS for Calendar access, discovers the host calendars grouped by account source, and replaces overlapping remote connections instead of keeping two copies.":Y.provider==="microsoft"?"Forge starts a Microsoft sign-in popup, then discovers the calendars available to that account before you choose what to mirror.":"Forge discovers the actual calendar collections before you choose which ones to mirror and which one should receive owned timeboxes."})]})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Setup guide"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"These are the exact setup steps for the selected provider. They stay inside this guided flow so Settings can stay focused on connection health and actions."}),e.jsx("div",{className:"mt-4",children:e.jsx(M6,{provider:Y.provider,compact:!0})})]})]})},{id:"credentials",eyebrow:"Credentials",title:c.provider==="google"?"Sign in with Google":c.provider==="macos_local"?"Use the calendars already configured on this Mac":c.provider==="apple"?"Provide the Apple account email and app-specific password":c.provider==="microsoft"?"Sign in with Microsoft":"Provide the custom CalDAV base URL and credentials",description:c.provider==="google"?"Review the Google desktop OAuth client, save a local override only if you need one, then start the popup and let Forge finish the PKCE exchange on the backend.":c.provider==="macos_local"?"Forge requests Calendar access through EventKit, discovers sources from Calendar.app, then lets you choose which host calendars to mirror and where Forge should write.":c.provider==="apple"?"Apple discovery starts from https://caldav.icloud.com, so you only need the Apple ID email and app password here.":c.provider==="microsoft"?"Forge uses the Microsoft client ID, tenant, and redirect URI saved in Settings -> Calendar, then runs a guided popup sign-in.":"Forge stores the secrets securely, then discovers the available calendars before anything is saved.",render:(Y,ee)=>{var xe;return e.jsxs("div",{className:"grid gap-4",children:[e.jsx(oe,{label:"Connection label",description:"This is the readable label Forge shows in settings and the calendar health cards.",children:e.jsx(be,{value:Y.label,onChange:ye=>ee({label:ye.target.value}),placeholder:yd[Y.provider].label})}),Y.provider==="macos_local"?e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,32,48,0.98),rgba(11,18,30,0.98))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"macOS Calendar access"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Forge uses EventKit to read and write the calendars already configured in Calendar.app on this Mac. Grant Calendar full access, then discover the available account sources."})]}),e.jsx(S,{className:A==="full_access"?"bg-emerald-500/16 text-emerald-100":"bg-white/[0.08] text-white/72",children:A==="full_access"?"Full access":A.replaceAll("_"," ")})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs(H,{type:"button",onClick:()=>void Ee.mutateAsync(),pending:Ee.isPending,pendingLabel:"Waiting for macOS",children:[e.jsx(rr,{className:"size-4"}),"Request Calendar access"]}),e.jsxs(H,{type:"button",variant:"secondary",onClick:()=>void je.mutateAsync(),pending:je.isPending,pendingLabel:"Checking",children:[e.jsx(sa,{className:"size-4"}),"Check access"]}),e.jsxs(H,{type:"button",onClick:()=>void J.mutateAsync(),disabled:A!=="full_access",pending:J.isPending,pendingLabel:"Discovering",children:[e.jsx(sa,{className:"size-4"}),"Discover host calendars"]})]}),(xe=I==null?void 0:I.sources)!=null&&xe.length?e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Host calendar sources"}),I.sources.map(ye=>{const ue=Y.sourceId===ye.sourceId;return e.jsxs("button",{type:"button",className:`rounded-[20px] border px-4 py-3 text-left transition ${ue?"border-[var(--primary)]/40 bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,onClick:()=>{ee({sourceId:ye.sourceId}),ce({provider:"macos_local",accountLabel:ye.accountLabel,serverUrl:Y.serverUrl,principalUrl:null,homeUrl:null,calendars:ye.calendars})},children:[e.jsx("div",{className:"font-medium",children:ye.accountLabel||ye.sourceTitle}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[ye.sourceType," · ",ye.calendars.length," ","calendars"]})]},ye.sourceId)})]}):null]})}):Y.provider==="google"?e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,32,48,0.98),rgba(11,18,30,0.98))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"How Google sign-in works"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Start the popup from the host running Forge. Google returns to Forge on localhost, Forge completes the PKCE exchange on the backend, then Forge discovers the calendars for that account."})]}),e.jsx(S,{className:"bg-emerald-500/16 text-emerald-100",children:"Auth code + PKCE"})]}),e.jsxs("div",{className:"mt-4 rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:[e.jsxs("div",{children:["Forge runtime:"," ",e.jsx("span",{className:"font-medium text-white",children:j.appBaseUrl})]}),e.jsxs("div",{className:"break-all",children:["Redirect URI:"," ",e.jsx("span",{className:"font-medium text-white",children:j.redirectUri})]}),e.jsxs("div",{className:"break-all",children:["Redirect origin:"," ",e.jsx("span",{className:"font-medium text-white",children:Se||"Unavailable"})]}),e.jsxs("div",{children:["Allowed local browser origins:"," ",e.jsx("span",{className:"font-medium text-white",children:j.allowedOrigins.join(", ")})]}),e.jsxs("div",{className:"break-all",children:["Detected browser origin:"," ",e.jsx("span",{className:"font-medium text-white",children:fe||"Unavailable"})]})]}),e.jsx("div",{className:"mt-4 rounded-[18px] bg-white/[0.04] p-4",children:Z?e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Google OAuth override"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Save both the client ID and client secret only when this Forge install should use a different Google desktop OAuth app than the packaged default."})]}),e.jsx("button",{type:"button","aria-label":"Done editing Google OAuth client",className:"inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.06] text-white/72 transition hover:bg-white/[0.12] hover:text-white",onClick:()=>{$(null);const ye=Kn(j);D(ye),V(!1)},children:e.jsx(_o,{className:"size-4"})})]}),e.jsxs(oe,{label:"Client ID",description:"Override the packaged Google desktop-app client ID for this Forge install.",children:[e.jsx(be,{"aria-label":"Client ID",value:v.clientId,onChange:ye=>{$(null),D({...v,clientId:ye.target.value})},placeholder:"1234567890-abcdef.apps.googleusercontent.com"}),U.issues.clientId?e.jsx("p",{className:"mt-2 text-sm text-rose-200",children:U.issues.clientId}):null]}),e.jsxs(oe,{label:"Client secret",description:"Override the packaged Google desktop-app client secret for this Forge install.",children:[e.jsx(be,{"aria-label":"Client secret",value:v.clientSecret,onChange:ye=>{$(null),D({...v,clientSecret:ye.target.value})},placeholder:"GOCSPX-..."}),U.issues.clientSecret?e.jsx("p",{className:"mt-2 text-sm text-rose-200",children:U.issues.clientSecret}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(H,{type:"button",onClick:()=>void Ke.mutateAsync(v),disabled:!he||!U.isValid,pending:Ke.isPending,pendingLabel:"Saving",children:"Save Google OAuth override"}),e.jsx(H,{type:"button",variant:"secondary",onClick:()=>{$(null),D({clientId:"",clientSecret:""})},disabled:Ke.isPending||!L.clientId&&!L.clientSecret&&v.clientId.length===0&&v.clientSecret.length===0,children:L.clientId||L.clientSecret?"Clear override":"Use packaged default"})]})]}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"grid min-w-0 gap-3",children:e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate font-medium text-white",children:"Google OAuth client"}),e.jsx(S,{className:j.storedClientId||j.storedClientSecret?"bg-emerald-500/16 text-emerald-100":"bg-white/[0.08] text-white/72",children:j.storedClientId||j.storedClientSecret?"Stored on server":"Using packaged default"}),e.jsx(Tt,{content:"Forge ships with a packaged Google desktop OAuth client by default. Save both fields only when this Forge install should use a different client ID and client secret pair.",label:"Explain Google OAuth client",className:"shrink-0"})]})}),e.jsx("button",{type:"button","aria-label":"Edit Google OAuth client",className:"inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.06] text-white/72 transition hover:bg-white/[0.12] hover:text-white",onClick:()=>{$(null),V(!0)},children:e.jsx(Pi,{className:"size-4"})})]})}),e.jsx(oe,{label:"Effective client ID",description:"This is the Google desktop-app client ID Forge will use right now.",children:e.jsx("div",{className:"flex min-h-11 min-w-0 items-center overflow-hidden rounded-[18px] border border-white/8 bg-black/20 px-4 text-sm text-white/38",children:e.jsx("span",{className:"block min-w-0 truncate",title:j.clientId,children:j.clientId})})}),e.jsx(oe,{label:"Effective client secret",description:"Forge uses this value on the local backend when exchanging and refreshing Google tokens.",children:e.jsx("div",{className:"flex min-h-11 min-w-0 items-center overflow-hidden rounded-[18px] border border-white/8 bg-black/20 px-4 text-sm text-white/38",children:e.jsx("span",{className:"block min-w-0 truncate",title:j.clientSecret||"",children:j.clientSecret||""})})})]})}),B?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/72",children:B}):null,e.jsx("div",{className:"mt-4 rounded-[18px] border border-sky-400/20 bg-sky-400/10 px-4 py-3 text-sm leading-6 text-sky-50",children:"If you open Forge on a phone or another remote route, Google redirects to localhost on that other device instead of back to Forge."}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs(H,{type:"button",onClick:()=>void ie(),disabled:!j.isReadyForPairing||!Je||he||Ke.isPending,pending:(N==null?void 0:N.status)==="pending",pendingLabel:"Waiting for Google",children:[e.jsx(Ra,{className:"size-4"}),(N==null?void 0:N.status)==="authorized"?"Sign in again":"Sign in with Google"]}),N!=null&&N.accountLabel?e.jsxs(S,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(_o,{className:"mr-1 size-3.5"}),N.accountLabel]}):null]})]})}):Y.provider==="microsoft"?e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,32,48,0.98),rgba(11,18,30,0.98))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Guided Microsoft setup"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Save the Microsoft app registration details for this Forge instance here, optionally test them, then continue into the Microsoft sign-in popup. Exchange Online stays read-only for now."})]}),e.jsx(S,{className:"bg-sky-400/12 text-sky-100",children:"Read only"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsxs(oe,{label:"Microsoft client ID",description:"Use the Application (client) ID from the Microsoft Entra app registration for this Forge instance.",children:[e.jsx(be,{value:W.clientId,onChange:ye=>{ke(null),q(ue=>({...ue,clientId:ye.target.value}))},placeholder:"00000000-0000-0000-0000-000000000000"}),M.issues.clientId?e.jsx("div",{className:"text-sm text-rose-300",children:M.issues.clientId}):null]}),e.jsx(oe,{label:"Tenant / authority",description:"Use common unless you need a tenant-specific authority.",children:e.jsx(be,{value:W.tenantId,onChange:ye=>{ke(null),q(ue=>({...ue,tenantId:ye.target.value}))},placeholder:"common"})})]}),e.jsxs(oe,{label:"Redirect URI",description:"Register this exact Forge callback URI in the Microsoft app registration.",children:[e.jsx(be,{value:W.redirectUri,onChange:ye=>{ke(null),q(ue=>({...ue,redirectUri:ye.target.value}))},placeholder:"http://127.0.0.1:4317/api/v1/calendar/oauth/microsoft/callback"}),M.issues.redirectUri?e.jsx("div",{className:"text-sm text-rose-300",children:M.issues.redirectUri}):null]}),e.jsx("div",{className:"mt-4 rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"Forge saves the client ID, tenant, and redirect URI for this local instance, then handles Microsoft sign-in in a popup."}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsx(H,{type:"button",onClick:()=>void Ce.mutateAsync(W),disabled:!M.isValid,pending:Ce.isPending,pendingLabel:"Saving",children:"Save Microsoft settings"}),e.jsx(H,{type:"button",variant:"secondary",onClick:()=>void Pe.mutateAsync(W),disabled:!M.isValid,pending:Pe.isPending,pendingLabel:"Testing",children:"Test Microsoft configuration"}),e.jsxs(H,{type:"button",onClick:()=>void Be(),disabled:!M.isValid||Ne||Ce.isPending,pending:(w==null?void 0:w.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(Ra,{className:"size-4"}),(w==null?void 0:w.status)==="authorized"?"Sign in again":"Sign in with Microsoft"]}),w!=null&&w.accountLabel?e.jsxs(S,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(_o,{className:"mr-1 size-3.5"}),w.accountLabel]}):null]}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"Save before sign-in. The Microsoft popup always uses the latest saved client ID, tenant, and redirect URI."}),e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"After sign-in, Forge will let you choose which Exchange Online calendars to mirror into the Calendar page."})]}),ge?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/72",children:ge}):null]})}):e.jsxs(e.Fragment,{children:[Y.provider==="caldav"?e.jsx(oe,{label:"CalDAV base URL",description:"Use the account-level CalDAV server URL, not an individual calendar collection URL.",children:e.jsx(be,{value:Y.serverUrl,onChange:ye=>ee({serverUrl:ye.target.value}),placeholder:"https://caldav.example.com"})}):null,Y.provider==="apple"?e.jsx(oe,{label:"Apple CalDAV base URL",children:e.jsx(be,{value:"https://caldav.icloud.com",disabled:!0})}):null,e.jsx(oe,{label:"Account email or username",children:e.jsx(be,{value:Y.username,onChange:ye=>ee({username:ye.target.value}),placeholder:"operator@example.com"})}),e.jsx(oe,{label:Y.provider==="apple"?"App-specific password":"Password or app password",children:e.jsx(be,{type:"password",value:Y.password,onChange:ye=>ee({password:ye.target.value}),placeholder:"Password"})})]})]})}},{id:"discovery",eyebrow:"Discovery",title:"Discover the calendars and choose what Forge should sync",description:c.provider==="microsoft"?"Select the Exchange Online calendars Forge should mirror into the Calendar page. This connection stays read-only for now.":c.provider==="macos_local"?ve?`Select the host-machine calendars Forge should mirror into the Calendar page. Forge already writes work blocks and timeboxes through ${ve}.`:"Select the host-machine calendars Forge should mirror into the Calendar page, then choose the host calendar Forge should write into for work blocks and timeboxes.":ve?`Select the calendars Forge should mirror into the Calendar page. Forge already writes work blocks and timeboxes through ${ve}.`:"Select the calendars Forge should mirror into the Calendar page, then choose the calendar Forge should write into for work blocks and timeboxes.",render:(Y,ee)=>e.jsxs("div",{className:"grid gap-4",children:[Y.provider==="google"?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(H,{type:"button",onClick:()=>void ie(),disabled:!j.isReadyForPairing||!Je,pending:(N==null?void 0:N.status)==="pending",pendingLabel:"Waiting for Google",children:[e.jsx(Ra,{className:"size-4"}),(N==null?void 0:N.status)==="authorized"?"Reconnect Google":"Sign in with Google"]}),f?e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[f.calendars.length," discovered"]}):null]}):Y.provider==="microsoft"?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(H,{type:"button",onClick:()=>void Be(),disabled:!M.isValid||Ne||Ce.isPending,pending:(w==null?void 0:w.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(Ra,{className:"size-4"}),(w==null?void 0:w.status)==="authorized"?"Reconnect Microsoft":"Sign in with Microsoft"]}),f?e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[f.calendars.length," discovered"]}):null]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(H,{pending:J.isPending,pendingLabel:"Discovering",onClick:()=>void J.mutateAsync(),disabled:Y.provider==="macos_local"&&A!=="full_access",children:[e.jsx(sa,{className:"size-4"}),Y.provider==="macos_local"?"Discover host calendars":"Discover calendars"]}),f?e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[f.calendars.length," discovered"]}):null]}),f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4 text-sm leading-6 text-white/64",children:[Y.provider==="macos_local"?"Discovered through the host calendar store":"Discovered through"," ",e.jsx("span",{className:"font-medium text-white",children:f.serverUrl}),f.homeUrl?e.jsxs(e.Fragment,{children:[" ","· home set"," ",e.jsx("span",{className:"font-medium text-white",children:f.homeUrl})]}):null]}),Y.provider!=="microsoft"&&ve?e.jsxs("div",{className:"rounded-[24px] border border-emerald-400/20 bg-emerald-400/10 p-4 text-sm leading-6 text-emerald-50",children:["Forge already writes work blocks and owned timeboxes through"," ",e.jsx("span",{className:"font-medium text-white",children:ve}),". This connection only needs a mirror selection."]}):null,e.jsx("div",{className:"grid gap-3",children:f.calendars.map(xe=>{const ye=Y.selectedCalendarUrls.includes(xe.url),ue=Y.forgeCalendarUrl===xe.url;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:Jr(xe)}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[xe.timezone||"No timezone exposed"," ·"," ",xe.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[xe.isForgeCandidate?e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge match"}):null,xe.isPrimary?e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:"Primary"}):null]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>ee({selectedCalendarUrls:ye?Y.selectedCalendarUrls.filter($e=>$e!==xe.url):[...Y.selectedCalendarUrls,xe.url]}),className:`rounded-full px-3 py-2 text-sm transition ${ye?"bg-[var(--primary)]/18 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.24)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:ye?"Mirrored":"Mirror into Forge"}),Y.provider!=="microsoft"&&!ve?e.jsx("button",{type:"button",onClick:()=>ee({forgeCalendarUrl:xe.url,createForgeCalendar:!1}),className:`rounded-full px-3 py-2 text-sm transition ${ue?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:ue?"Forge writes here":"Use for Forge writes"}):e.jsx(S,{className:Y.provider==="microsoft"?"bg-sky-400/12 text-sky-100":"bg-white/[0.08] text-white/74",children:Y.provider==="microsoft"?"Read only":"Shared target elsewhere"})]})]},xe.url)})}),Y.provider!=="microsoft"&&!ve?e.jsxs("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"No Forge calendar yet?"}),e.jsxs("p",{className:"mt-2 text-sm leading-6 text-white/60",children:["If none of the discovered calendars should receive Forge-owned work blocks and timeboxes, let Forge create a dedicated calendar named"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"}),"."]}),e.jsx("div",{className:"mt-4",children:e.jsx("button",{type:"button",onClick:()=>ee({forgeCalendarUrl:null,createForgeCalendar:!Y.createForgeCalendar}),className:`rounded-full px-3 py-2 text-sm transition ${Y.createForgeCalendar?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:Y.createForgeCalendar?"Forge will create one":"Create a new Forge calendar"})})]}):Y.provider==="microsoft"?e.jsx("div",{className:"rounded-[24px] border border-sky-400/20 bg-sky-400/10 p-4 text-sm leading-6 text-sky-50",children:"Exchange Online is connected through Microsoft Graph in read-only mode. Forge will mirror the calendars you select here, but it will keep work blocks and owned timeboxes local or publish them through another writable provider."}):e.jsxs("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] p-4 text-sm leading-6 text-white/60",children:["Forge will keep"," ",e.jsx("span",{className:"font-medium text-white",children:ve})," ","as the canonical write target instead of creating another Forge calendar on this connection."]})]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-4 py-6 text-sm leading-6 text-white/58",children:Y.provider==="google"?e.jsx(e.Fragment,{children:"Start the guided Google sign-in first. Forge will bring the discovered Google calendars back here as soon as the popup completes."}):Y.provider==="microsoft"?e.jsx(e.Fragment,{children:"Start the guided Microsoft sign-in first. Forge will bring the discovered Exchange Online calendars back here as soon as the popup completes."}):e.jsx(e.Fragment,{children:Y.provider==="macos_local"?"Grant macOS Calendar access and discover the host calendars first. If Calendar.app already aggregates Google, Exchange, or iCloud for this Mac, Forge will pick them up here without reconnecting those accounts.":e.jsxs(e.Fragment,{children:["Discover calendars after entering the credentials. For Apple, Forge starts from"," ",e.jsx("span",{className:"font-medium text-white",children:"https://caldav.icloud.com"})," ","and resolves the principal plus calendar home automatically."]})})})]})},{id:"review",eyebrow:"Review",title:"Confirm what Forge will mirror and where it will write",description:"This keeps the sync model explicit before the provider connection is saved.",render:Y=>{var ee,xe;return e.jsxs("div",{className:"grid gap-4",children:[Y.provider==="macos_local"&&Y.sourceId?e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/70",children:["Selected host source:"," ",e.jsx("span",{className:"font-medium text-white",children:((ee=I==null?void 0:I.sources.find(ye=>ye.sourceId===Y.sourceId))==null?void 0:ee.accountLabel)??((xe=I==null?void 0:I.sources.find(ye=>ye.sourceId===Y.sourceId))==null?void 0:xe.sourceTitle)??Y.sourceId})]}):null,e.jsxs("div",{className:"rounded-[26px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,31,42,0.96),rgba(10,16,26,0.96))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(Hs,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-xl text-white",children:ci(Y.provider,Y.label)}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:Y.provider==="google"?"Google Calendar":Y.provider==="macos_local"?"Calendars On This Mac":Y.provider==="apple"?"Apple Calendar":Y.provider==="microsoft"?"Exchange Online":"Custom CalDAV"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:["Mirrored calendars:"," ",e.jsx("span",{className:"font-medium text-white",children:Y.selectedCalendarUrls.length})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:["Forge writes:"," ",e.jsx("span",{className:"font-medium text-white",children:Y.provider==="microsoft"?"read only":Y.forgeCalendarUrl?"existing calendar":Y.createForgeCalendar?"new Forge calendar":ve?`shared target via ${ve}`:"not selected"})]})]}),Y.replaceConnectionIds.length>0?e.jsxs("div",{className:"mt-4 rounded-[20px] border border-amber-400/20 bg-amber-400/10 px-4 py-3 text-sm leading-6 text-amber-50",children:["Forge will replace ",Y.replaceConnectionIds.length," older overlapping connection",Y.replaceConnectionIds.length===1?"":"s"," for this same calendar account so only one visible copy remains.",o.filter(ye=>Y.replaceConnectionIds.includes(ye.id)).map(ye=>ye.label).join(", ")?` ${o.filter(ye=>Y.replaceConnectionIds.includes(ye.id)).map(ye=>ye.label).join(", ")}.`:""]}):null]})]})}}],[f,J.isPending,c.provider,Z,v,N,j.clientId,B,j.allowedOrigins,j.appBaseUrl,j.isLocalOnly,j.isReadyForPairing,j.redirectUri,Se,he,Je,nt,Ne,W,E.setupMessage,ge,M,Ke.isPending,Ce.isPending,G,Pe.isPending,E.isReadyForSignIn,E.redirectUri,I,w,we,ve]),Le=c.provider==="macos_local"&&c.replaceConnectionIds.length>0?"Replace and connect":"Connect provider";return e.jsx(Kt,{open:t,onOpenChange:s,eyebrow:"Calendar settings",title:"Connect a calendar provider",description:"Discover provider calendars first, choose which calendars Forge should mirror, and only choose a Forge write target when the runtime does not already have one.",value:c,onChange:Y=>{p(Y),f&&Y.provider!==f.provider&&b(null),Y.provider!=="macos_local"&&y(null)},draftPersistenceKey:"calendar.connection.new",steps:at,submitLabel:Le,pending:m,pendingLabel:"Connecting",error:g,resolveError:_e,initialStepId:i,onSubmit:async()=>{try{if(x(null),!f){x("Discover the available calendars before saving the connection.");return}if(c.selectedCalendarUrls.length===0){x("Select at least one calendar to mirror into Forge.");return}if(c.provider!=="microsoft"&&!c.forgeCalendarUrl&&!c.createForgeCalendar&&!we){x("Choose the calendar Forge should write into, ask Forge to create one, or keep using the existing shared Forge write target.");return}if(c.provider==="google"){if(!(N!=null&&N.sessionId)||N.status!=="authorized"){x("Complete the Google sign-in flow before saving this connection.");return}await d({provider:"google",label:ci("google",c.label),authSessionId:N.sessionId,selectedCalendarUrls:c.selectedCalendarUrls,forgeCalendarUrl:c.forgeCalendarUrl,createForgeCalendar:c.createForgeCalendar})}else if(c.provider==="apple")await d({provider:"apple",label:ci("apple",c.label),username:c.username.trim(),password:c.password.trim(),selectedCalendarUrls:c.selectedCalendarUrls,forgeCalendarUrl:c.forgeCalendarUrl,createForgeCalendar:c.createForgeCalendar});else if(c.provider==="microsoft"){if(!(w!=null&&w.sessionId)||w.status!=="authorized"){x("Complete the Microsoft sign-in flow before saving this connection.");return}await d({provider:"microsoft",label:ci("microsoft",c.label),authSessionId:w.sessionId,selectedCalendarUrls:c.selectedCalendarUrls})}else if(c.provider==="macos_local"){if(!c.sourceId){x("Choose which host calendar source Forge should connect before saving.");return}await d({provider:"macos_local",label:ci("macos_local",c.label),sourceId:c.sourceId,selectedCalendarUrls:c.selectedCalendarUrls,forgeCalendarUrl:c.forgeCalendarUrl,createForgeCalendar:c.createForgeCalendar,replaceConnectionIds:c.replaceConnectionIds})}else await d({provider:"caldav",label:ci("caldav",c.label),serverUrl:c.serverUrl.trim(),username:c.username.trim(),password:c.password.trim(),selectedCalendarUrls:c.selectedCalendarUrls,forgeCalendarUrl:c.forgeCalendarUrl,createForgeCalendar:c.createForgeCalendar});s(!1)}catch(Y){if(Y instanceof Ya&&Y.code==="calendar_connection_overlap"){const ee=Y.response,xe=Array.isArray(ee==null?void 0:ee.overlappingConnectionIds)?ee==null?void 0:ee.overlappingConnectionIds.filter(ye=>typeof ye=="string"):[];p(ye=>({...ye,replaceConnectionIds:xe})),x(`${Y.message} Submit again to replace the older overlapping connection${xe.length===1?"":"s"}.`);return}x(Y instanceof Error?Y.message:"Forge could not create this calendar connection.")}}})}function Lr(t){try{const s=new URL(t);return s.pathname.endsWith("/")||(s.pathname=`${s.pathname}/`),s.toString()}catch{return t}}function qg(t){switch(t){case"google":return"Google Calendar";case"apple":return"Apple Calendar";case"microsoft":return"Exchange Online";case"macos_local":return"Calendars On This Mac";case"caldav":default:return"Custom CalDAV"}}function K6(t){switch(t){case"google":return"Open Google guided flow";case"microsoft":return"Open Microsoft guided flow";case"macos_local":return"Open Mac calendar flow";default:return"Open guided setup"}}function q6(t){switch(t){case"google":case"microsoft":return rr;case"macos_local":return bs;case"apple":return bs;case"caldav":default:return Hs}}function B6(t){switch(t){case"microsoft":return"Read only";case"macos_local":return"Read + write";default:return"Read + write"}}function U6(t){switch(t){case"google":return"Local PKCE";case"microsoft":return"Guided sign-in";case"macos_local":return"Host machine";case"apple":return"App password";case"caldav":default:return"CalDAV credentials"}}function W6(t){switch(t){case"google":return"Sign in from the same machine running Forge. After connection, Forge can mirror the calendars you choose and reuse the current shared Forge write target, creating one only when the runtime does not already have one.";case"apple":return"Use your Apple ID email and app-specific password. Forge discovers your iCloud calendars before you choose what to mirror.";case"microsoft":return"Use the guided Microsoft sign-in flow. Forge mirrors the Exchange calendars you choose and keeps this provider read only.";case"macos_local":return"Use the calendars already configured in Calendar.app on this Mac. Forge requests Calendar access through macOS, discovers host calendars by account source, and replaces overlapping remote account connections instead of duplicating them.";case"caldav":default:return"Enter a CalDAV server URL and account credentials. Forge discovers the calendars on that account before you choose what to mirror."}}function Bg(t){return`${t} connection${t===1?"":"s"}`}function H6(){var me,se,we,ve,_;const t=pt(),[s,a]=ws(),[i,r]=u.useState(!1),[n,l]=u.useState("google"),[o,d]=u.useState(void 0),[m,h]=u.useState(null),[c,p]=u.useState([]),[g,x]=u.useState(!1),[f,b]=u.useState(null),[A,T]=u.useState(()=>aw()),I=Me({queryKey:["forge-operator-session"],queryFn:mr}),y=I.isSuccess,N=Me({queryKey:["forge-settings"],queryFn:pr,enabled:y}),k=Me({queryKey:["forge-calendar-connections"],queryFn:DN,enabled:y}),w=Me({queryKey:["forge-calendar-resources"],queryFn:YN,enabled:y}),P=async()=>{await Promise.all([t.invalidateQueries({queryKey:["forge-settings"]}),t.invalidateQueries({queryKey:["forge-calendar-connections"]}),t.invalidateQueries({queryKey:["forge-calendar-resources"]}),t.invalidateQueries({queryKey:["forge-calendar-overview"]}),Zt(t)])},j=De({mutationFn:GN,onSuccess:P}),R=De({mutationFn:F=>QN(F),onSuccess:P}),v=De({mutationFn:({connectionId:F,patch:O})=>VN(F,O),onSuccess:P}),D=De({mutationFn:F=>XN(F),onSuccess:P});u.useEffect(()=>{if(!y)return;const F=s.get("intent"),O=s.get("provider");if(F!=="connect")return;l(O==="apple"||O==="caldav"||O==="google"||O==="microsoft"||O==="macos_local"?O:"google"),d(O==="microsoft"?"credentials":void 0),r(!0);const ce=new URLSearchParams(s);ce.delete("intent"),ce.delete("provider"),a(ce,{replace:!0})},[y,s,a]);const L=u.useMemo(()=>{var F,O;return Vf(((F=w.data)==null?void 0:F.calendars)??[],((O=k.data)==null?void 0:O.connections)??[])},[(me=w.data)==null?void 0:me.calendars,(se=k.data)==null?void 0:se.connections]),Q=u.useMemo(()=>{const F=new Map;for(const O of L){const ce=F.get(O.connectionId)??[];ce.push(O),F.set(O.connectionId,ce)}return F},[L]),Z=u.useMemo(()=>{var O;const F={};for(const ce of((O=k.data)==null?void 0:O.connections)??[])F[ce.provider]=(F[ce.provider]??0)+1;return F},[(we=k.data)==null?void 0:we.connections]),V=u.useMemo(()=>rw(L,A.calendarColors),[L,A.calendarColors]),B=u.useMemo(()=>{var F;return(((F=k.data)==null?void 0:F.connections)??[]).find(O=>{var ce;return typeof((ce=O.config)==null?void 0:ce.forgeCalendarUrl)=="string"&&O.config.forgeCalendarUrl.trim().length>0})??null},[(ve=k.data)==null?void 0:ve.connections]),$=u.useMemo(()=>{var F;return((F=k.data)==null?void 0:F.connections.find(O=>O.id===m))??null},[k.data,m]),E=u.useMemo(()=>{var F;return((F=k.data)==null?void 0:F.connections.find(O=>O.id===f))??null},[k.data,f]),X=u.useMemo(()=>m?Q.get(m)??[]:[],[Q,m]),W=Me({queryKey:["forge-calendar-connection-discovery",m],queryFn:()=>HN(m),enabled:y&&m!==null});u.useEffect(()=>{if(!m){p([]),x(!1);return}const F=X.filter(O=>O.selectedForSync).map(O=>Lr(O.remoteId));p(F),x(!0)},[m,X]),u.useEffect(()=>{Q3(A)},[A]);const q=u.useMemo(()=>[{id:"mirrors",eyebrow:"Mirroring",title:"Choose which calendars Forge should mirror",description:"Unselected calendars stop showing up in Forge’s mirrored calendar views. The Forge write calendar stays available for work blocks and timeboxes.",render:(F,O)=>{var Ee,Ce;if(W.isLoading)return e.jsx("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-6 text-sm leading-6 text-white/58",children:"Rediscovering calendars for this connection."});if(W.isError||!((Ee=W.data)!=null&&Ee.discovery))return e.jsx("div",{className:"rounded-[24px] border border-rose-400/20 bg-rose-400/10 px-4 py-6 text-sm leading-6 text-rose-100",children:W.error instanceof Error?W.error.message:"Forge could not rediscover calendars for this connection."});const ce=W.data.discovery,J=($==null?void 0:$.provider)==="microsoft",je=typeof((Ce=$==null?void 0:$.config)==null?void 0:Ce.forgeCalendarUrl)=="string"?Lr($.config.forgeCalendarUrl):null;return e.jsx("div",{className:"grid gap-3",children:ce.calendars.map(Ke=>{const Pe=Lr(Ke.url),M=g?F.selectedCalendarUrls.includes(Pe):X.some(he=>he.selectedForSync&&Lr(he.remoteId)===Pe),U=je===Pe;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:Jr(Ke)}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[Ke.timezone||"No timezone exposed"," ·"," ",Ke.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[U&&!J?e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge writes here"}):null,J?e.jsx(S,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,Ke.isPrimary?e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:"Primary"}):null]})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:e.jsx("button",{type:"button",disabled:U&&!J,onClick:()=>O({selectedCalendarUrls:M?F.selectedCalendarUrls.filter(he=>he!==Pe):[...F.selectedCalendarUrls,Pe]}),className:`rounded-full px-3 py-2 text-sm transition ${U&&!J?"cursor-not-allowed bg-white/[0.05] text-white/35":M?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:U&&!J?"Always available for Forge writes":M?"Mirrored into Forge":"Do not mirror"})})]},Ke.url)})})}}],[$,W]);if(I.isLoading||N.isLoading||k.isLoading||w.isLoading)return e.jsx(gs,{eyebrow:"Settings · Calendar",title:"Loading calendar settings",description:"Checking the operator session and loading provider connections.",columns:2,blocks:6});if(I.isError)return e.jsx(ct,{eyebrow:"Settings · Calendar",error:I.error,onRetry:()=>void I.refetch()});if(N.isError||k.isError||w.isError||!((_=N.data)!=null&&_.settings)||!k.data||!w.data)return e.jsx(ct,{eyebrow:"Settings · Calendar",error:N.error??k.error??w.error??new Error("Calendar settings are unavailable."),onRetry:()=>{N.refetch(),k.refetch(),w.refetch()}});const{providers:G,connections:z}=k.data,ge=N.data.settings.calendarProviders.google,ke=N.data.settings.calendarProviders.microsoft;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(mt,{title:"Calendar settings",description:"Manage provider connections, review the shared Forge write target, and open guided setup only when you need to connect or reconfigure a provider.",badge:`${z.length} connection${z.length===1?"":"s"}`}),e.jsx(Aa,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(le,{className:"surface-section-panel grid gap-5 rounded-[30px] border",children:[e.jsxs("div",{className:"max-w-3xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Provider connections"}),e.jsxs("p",{className:"mt-2 text-sm leading-6 text-white/60",children:["Connect a provider here, then choose which calendars Forge should mirror. Writable providers publish work blocks and owned timeboxes through one shared"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"})," write target, creating it only when the runtime does not already have one."]})]}),e.jsx("div",{className:"grid gap-4 lg:grid-cols-2",children:G.map(F=>{const O=q6(F.provider),ce=Z[F.provider]??0,J=ce>0;return e.jsxs("div",{className:`flex min-h-[248px] flex-col rounded-[26px] border p-5 shadow-[inset_0_1px_0_var(--ui-border-subtle)] ${J?"border-emerald-400/24 bg-[linear-gradient(180deg,color-mix(in_srgb,#10b981_18%,var(--surface-panel)_82%),var(--ui-surface-2))]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]"}`,children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`rounded-[18px] p-3 ${J?"bg-emerald-400/16 text-emerald-100":"bg-[var(--primary)]/14 text-[var(--primary)]"}`,children:e.jsx(O,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"font-medium text-[var(--ui-ink-strong)]",children:F.label}),J?e.jsxs(e.Fragment,{children:[e.jsx(S,{className:"bg-emerald-400/16 text-emerald-50",children:"Connected"}),e.jsx(S,{className:"bg-white/[0.08] text-white/82",children:Bg(ce)})]}):null]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:W6(F.provider)}),J?e.jsxs("div",{className:"mt-3 text-sm text-emerald-100/88",children:["Forge already has"," ",Bg(ce)," for this provider. Open the guided flow again to add another account or reconfigure one."]}):null]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsx(S,{tone:"signal",className:"bg-[var(--primary)]/14 text-white/86",children:U6(F.provider)}),e.jsx(S,{className:F.supportsDedicatedForgeCalendar?"bg-emerald-500/16 text-emerald-100":"bg-sky-400/14 text-sky-100",children:B6(F.provider)})]}),e.jsx("div",{className:"mt-auto pt-5",children:e.jsxs(H,{variant:"secondary",className:"w-full justify-center",onClick:()=>{l(F.provider),d(F.provider==="google"||F.provider==="microsoft"?"credentials":void 0),r(!0)},children:[e.jsx(Ra,{className:"size-4"}),K6(F.provider)]})})]},F.provider)})})]}),e.jsxs(le,{className:"surface-section-panel grid gap-4 rounded-[30px] border",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar colors"}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:"Calendar colors are on by default so each mirrored calendar stays legible in the week view. Adjust any display color here without changing the provider itself."})]}),e.jsx("button",{type:"button",onClick:()=>T(F=>({...F,useCalendarColors:!F.useCalendarColors})),className:`rounded-full px-4 py-2 text-sm transition ${A.useCalendarColors?"bg-[var(--ui-accent-soft)] text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] text-[var(--ui-ink-soft)] hover:bg-[var(--ui-surface-hover)]"}`,children:A.useCalendarColors?"Colors on":"Colors off"})]}),L.length>0?e.jsx("div",{className:"grid gap-3",children:L.map(F=>{const O=Jr(F);return e.jsxs("div",{className:"grid gap-3 rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-4 md:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{"aria-hidden":"true",className:"size-3 shrink-0 rounded-full",style:{backgroundColor:V[F.id]}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-[var(--ui-ink-strong)]",children:O}),e.jsxs("div",{className:"mt-1 text-sm text-[var(--ui-ink-soft)]",children:[F.canWrite?"Writable":"Read only"," ·"," ",F.timezone]})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{"aria-label":`Choose display color for ${O}`,type:"color",value:V[F.id],onChange:ce=>T(J=>({...J,calendarColors:{...J.calendarColors,[F.id]:ce.target.value}})),className:"h-10 w-12 cursor-pointer rounded-[14px] border border-[var(--ui-border-subtle)] bg-transparent p-1"}),e.jsx(H,{size:"sm",variant:"secondary",onClick:()=>T(ce=>{const J={...ce.calendarColors};return delete J[F.id],{...ce,calendarColors:J}}),children:"Reset palette"})]})]},F.id)})}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-4 py-5 text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Connect a provider first, then Forge will let you tune the display color of each mirrored calendar here."})]}),e.jsxs(le,{className:"surface-section-panel grid gap-4 rounded-[30px] border",children:[e.jsx("div",{className:"flex items-center justify-between gap-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Connected providers"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Review connection health, confirm which provider calendars Forge can read or mirror, and see which connection currently owns the shared Forge write target."})]})}),z.length>0?e.jsx("div",{className:"grid gap-3",children:z.map(F=>{var J;const O=Q.get(F.id)??[],ce=F.provider!=="microsoft"&&B!==null&&B.id!==F.id;return e.jsxs("div",{className:"rounded-[24px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-[var(--ui-ink-strong)]",children:F.label}),e.jsxs("div",{className:"mt-1 text-sm text-[var(--ui-ink-soft)]",children:[qg(F.provider)," ·"," ",F.accountLabel||"No account label yet"]}),F.lastSyncedAt?e.jsxs("div",{className:"mt-2 text-sm text-[var(--ui-ink-faint)]",children:["Last synced"," ",new Date(F.lastSyncedAt).toLocaleString()]}):null,F.lastSyncError?e.jsx("div",{className:"mt-2 text-sm text-rose-200",children:F.lastSyncError}):null,ce?e.jsxs("div",{className:"mt-2 text-sm text-[var(--ui-ink-soft)]",children:["Forge writes through"," ",e.jsx("span",{className:"font-medium text-[var(--ui-ink-strong)]",children:B.label}),B.accountLabel?` · ${B.accountLabel}`:"","."]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:F.status}),((J=F.config)==null?void 0:J.readOnly)===!0?e.jsx(S,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,e.jsxs(H,{size:"sm",variant:"secondary",pending:R.isPending&&R.variables===F.id,pendingLabel:"Syncing",onClick:()=>void R.mutateAsync(F.id),children:[e.jsx(sa,{className:"size-4"}),"Sync"]}),e.jsxs(H,{size:"sm",variant:"secondary",onClick:()=>{const je=(Q.get(F.id)??[]).filter(Ee=>Ee.selectedForSync).map(Ee=>Lr(Ee.remoteId));p(je),x(!0),h(F.id)},children:[e.jsx(Ff,{className:"size-4"}),"Manage mirrored calendars"]}),e.jsxs(H,{size:"sm",variant:"secondary",onClick:()=>b(F.id),children:[e.jsx(Wt,{className:"size-4"}),"Remove"]})]})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:O.map(je=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-[var(--ui-ink-strong)]",children:Jr(je)}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:[je.canWrite?"Writable":"Read only"," ·"," ",je.timezone]})]}),je.forgeManaged?e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge"}):e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[e.jsx(bs,{className:"mr-1 size-3.5"}),"Mirrored"]})]},je.id))})]},F.id)})}):e.jsxs("div",{className:"rounded-[26px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-6 text-sm leading-6 text-white/60",children:["No provider is connected yet. Open a guided setup flow above when you are ready. Forge will reuse one shared"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"})," write target across writable providers when it already exists, create one only when none exists yet, and mirror selected calendars in read-only mode for providers like Exchange Online."]})]})]}),e.jsx(z6,{open:i,onOpenChange:F=>{r(F),F||d(void 0)},initialProvider:n,initialStepId:o,googleSetup:ge,microsoftSetup:ke,existingConnections:z.map(F=>({id:F.id,label:F.label,provider:F.provider,status:F.status,accountLabel:F.accountLabel,forgeCalendarId:F.forgeCalendarId,config:F.config})),onCalendarSettingsChanged:P,pending:j.isPending,onSubmit:async F=>{await j.mutateAsync(F)}}),e.jsx(Kt,{open:m!==null,onOpenChange:F=>{F||h(null)},eyebrow:"Calendar settings",title:"Manage mirrored calendars",description:"Choose which calendars this connection should mirror into Forge.",value:{selectedCalendarUrls:c},onChange:F=>p(F.selectedCalendarUrls),draftPersistenceKey:m?`settings.calendar.manage.${m}`:"settings.calendar.manage",steps:q,pending:v.isPending,pendingLabel:"Saving",submitLabel:"Save mirror selection",error:v.error instanceof Error?v.error.message:null,onSubmit:async()=>{m&&(await v.mutateAsync({connectionId:m,patch:{selectedCalendarUrls:c.map(Lr)}}),x(!1),h(null))}}),e.jsx(Kt,{open:f!==null,onOpenChange:F=>{F||b(null)},eyebrow:"Calendar settings",title:"Remove calendar connection",description:"This removes the provider connection, stops syncing its calendars, removes mirrored external events from Forge, and keeps Forge-native events local.",value:{acknowledgement:!1},onChange:()=>{},draftPersistenceKey:f?`settings.calendar.remove.${f}`:"settings.calendar.remove",steps:[{id:"confirm",eyebrow:"Disconnect",title:E?`Remove ${E.label}?`:"Remove this connection?",description:"Use this when you want to disconnect the account entirely. You can reconnect later with the guided setup flow.",render:()=>e.jsx("div",{className:"rounded-[24px] border border-rose-400/20 bg-rose-400/10 p-4 text-sm leading-6 text-rose-100",children:E?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"font-medium text-white",children:[qg(E.provider)," ·"," ",E.accountLabel||"No account label"]}),e.jsx("div",{className:"mt-2",children:"Mirrored provider calendars and external mirrored events from this connection will be removed. Forge-owned events, work blocks, and timeboxes remain in Forge."})]}):"This connection will be removed from Forge."})}],pending:D.isPending,pendingLabel:"Removing",submitLabel:"Remove connection",error:D.error instanceof Error?D.error.message:null,onSubmit:async()=>{f&&(await D.mutateAsync(f),b(null))}})]})}function G6(t){return t.replaceAll("."," ")}function Q6(t){const s=typeof t.sleepNights=="number"?t.sleepNights:typeof t.sleepSessions=="number"?t.sleepSessions:0,a=typeof t.sleepSegments=="number"?t.sleepSegments:0,i=typeof t.sleepRawRecords=="number"?t.sleepRawRecords:0,r=typeof t.sleepSessions=="number"?t.sleepSessions:0,n=typeof t.workouts=="number"?t.workouts:0,l=t.vitals&&typeof t.vitals=="object"&&!Array.isArray(t.vitals)&&typeof t.vitals.metricEntries=="number"?t.vitals.metricEntries:0;return`${s||r} nights · ${a} segments · ${i} raw records · ${n} workouts · ${l} vitals`}function Ug(t){return t?"signal":"meta"}function V6(t){return t.replaceAll("_"," ")}function X6(t){return t?new Date(t).toLocaleString():"Waiting for device update"}function Y6(t,s){return t?s?"signal":"default":"meta"}function J6(t){return t.transportMode==="iroh"?"Iroh":"Manual HTTP"}function Z6(t){return t.transportMode==="iroh"?"signal":"meta"}function eE(){const t=Ct(),s=pt(),a=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],i=Is(a),[r,n]=u.useState(null),[l,o]=u.useState(!1),[d,m]=u.useState(!1),[h,c]=u.useState(!1),[p,g]=u.useState(null),x=Me({queryKey:["forge-companion-overview",...a],queryFn:async()=>(await xb(a)).overview}),f=De({mutationFn:async(R="iroh")=>J1({userId:i??null,transportMode:R}),onSuccess:async R=>{g({qrPayload:R.qrPayload}),o(!0),await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),b=De({mutationFn:async R=>Z1(R),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),A=De({mutationFn:async()=>t2({userIds:a,includeRevoked:!1}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),T=De({mutationFn:async R=>e2(R.pairingSessionId,R.source,R.desiredEnabled),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}});if(u.useEffect(()=>{if(!p){n(null);return}vj.toDataURL(JSON.stringify(p.qrPayload),{width:320,margin:1}).then(n)},[p]),u.useEffect(()=>{m(!1),c(!1)},[p]),x.isLoading)return e.jsx(gs,{eyebrow:"Companion",title:"Loading mobile companion",description:"Checking pairing state and recent sync status.",columns:2,blocks:5});if(x.isError||!x.data)return e.jsx(ct,{eyebrow:"Companion",error:x.error??new Error("Companion overview unavailable"),onRetry:()=>void x.refetch()});const I=x.data,y=I.pairings.filter(R=>R.status!=="revoked"),N=I.pairings.length-y.length,k=p?JSON.stringify(p.qrPayload,null,2):"",w=async()=>{if(p&&l){o(!1);return}if(p&&!l){o(!0);return}await f.mutateAsync("iroh")},P=async()=>{await f.mutateAsync("manual-http")},j=async()=>{if(k){if(!navigator.clipboard){m(!0);return}try{await navigator.clipboard.writeText(k),c(!0),window.setTimeout(()=>c(!1),1800)}catch{m(!0)}}};return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(mt,{title:"Mobile companion",description:"Pair the native iPhone companion, sync Apple Health, and keep the bridge open for watch and location signals.",badge:I.healthState.replaceAll("_"," ")}),e.jsx(Aa,{}),e.jsxs("section",{className:"grid gap-4",children:[null,e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pair iPhone"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Pair your iPhone privately"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Forge uses its own Iroh/QUIC companion route by default. Scan once from the iPhone app; manual HTTP stays as the advanced LAN or Tailscale path."})]}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsxs(H,{variant:"secondary",onClick:()=>void P(),pending:f.isPending&&f.variables==="manual-http",pendingLabel:"Generating",children:[e.jsx(jj,{className:"size-4"}),"Advanced HTTP"]}),e.jsxs(H,{onClick:()=>void w(),pending:f.isPending&&f.variables!=="manual-http",pendingLabel:"Generating",children:[e.jsx(kj,{className:"size-4"}),p?l?"Hide QR":"Show QR":"Generate Forge QR",p?l?e.jsx(en,{className:"size-4"}):e.jsx(Ta,{className:"size-4"}):null]})]})]}),l?e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] p-4 sm:p-5",children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(260px,360px)_1fr]",children:[r?e.jsxs("div",{className:"grid justify-items-center gap-4 rounded-[24px] bg-white px-6 py-6 text-slate-950",children:[e.jsx("img",{src:r,alt:"Forge Companion pairing QR code",className:"w-full max-w-[320px]"}),e.jsx("div",{className:"max-w-[320px] text-center text-sm text-slate-600",children:"Scan this code from Forge Companion on iPhone."})]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-8 text-center text-sm text-white/55",children:"Generating the QR code now."}),e.jsxs("div",{className:"grid content-start gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p?e.jsxs(S,{tone:Z6(p.qrPayload),children:[e.jsx(Df,{className:"size-3"}),J6(p.qrPayload)]}):null,e.jsxs(S,{tone:"meta",children:[e.jsx(ap,{className:"size-3"}),"One-time token"]})]}),e.jsxs("div",{className:"grid gap-3 text-sm leading-6 text-white/66",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Nj,{className:"mt-1 size-4 shrink-0 text-white/45"}),e.jsx("span",{children:"Open Forge Companion and choose Scan Forge QR."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ap,{className:"mt-1 size-4 shrink-0 text-white/45"}),e.jsx("span",{children:"The iPhone receives the desktop node, relay hint, and pairing token for the Forge Iroh route."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ia,{className:"mt-1 size-4 shrink-0 text-white/45"}),e.jsx("span",{children:"After verification, the app moves straight into native permissions and first sync."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/62",children:p?e.jsxs("span",{children:["Expires"," ",new Date(p.qrPayload.expiresAt).toLocaleString(),"."]}):"Generate the one-time QR and scan it from the iPhone app."}),p?e.jsxs(H,{variant:"secondary",pending:f.isPending,pendingLabel:"Generating",onClick:()=>void f.mutateAsync("iroh"),children:[e.jsx(sa,{className:"size-4"}),"Regenerate QR"]}):null]})]})]}),p?e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/62",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("div",{className:"text-white/78",children:"Fallback pairing payload"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/45",children:"Use this only when the iPhone camera cannot scan the QR. The payload contains the same Forge Iroh connection recipe."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(H,{variant:"secondary",onClick:()=>void j(),children:[h?e.jsx(Ia,{className:"size-4"}):e.jsx(Sj,{className:"size-4"}),h?"Copied":"Copy payload"]}),e.jsxs(H,{variant:"secondary",onClick:()=>m(R=>!R),children:[d?"Hide payload":"Show payload",d?e.jsx(en,{className:"size-4"}):e.jsx(Ta,{className:"size-4"})]})]})]}),d?e.jsx("pre",{className:"max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-[16px] bg-slate-950/60 p-3 font-mono text-[11px] leading-5 text-white/70",children:k}):null]}):null]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-6 text-sm leading-6 text-white/55",children:"Generate a one-time Forge QR when the iPhone is in your hand. The code expires automatically and can be regenerated anytime."})]}),e.jsxs(le,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Companion state"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Pairings"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:y.length}),N>0?e.jsxs("div",{className:"mt-2 text-xs text-white/42",children:[N," revoked hidden"]}):null]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Sleep sessions"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.sleepSessions})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Raw sleep records"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.sleepRawRecords})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workouts"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.workouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Vitals days"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.vitalsDaySummaries??0})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Vital entries"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.vitalsMetricEntries??0})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Reflected sleep"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.reflectiveSleepSessions})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked workouts"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.linkedWorkouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Habit-generated"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.habitGeneratedWorkouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Reconciled"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.reconciledWorkouts})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{children:I.healthState.replaceAll("_"," ")}),I.lastSyncAt?e.jsxs(S,{tone:"meta",children:["Last sync ",new Date(I.lastSyncAt).toLocaleString()]}):null,e.jsxs(S,{tone:Ug(I.permissions.healthKitAuthorized),children:["HealthKit ",I.permissions.healthKitAuthorized?"ready":"needed"]}),e.jsxs(S,{tone:Ug(I.permissions.backgroundRefreshEnabled),children:["Background refresh"," ",I.permissions.backgroundRefreshEnabled?"ready":"not yet"]}),e.jsxs(S,{tone:"meta",children:["Location ",I.permissions.locationReady?"ready":"later"]}),e.jsxs(S,{tone:"meta",children:["Motion ",I.permissions.motionReady?"ready":"later"]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pairing path"}),e.jsxs("div",{className:"grid gap-2 text-sm text-white/62",children:[e.jsx("div",{children:"1. Generate the Forge QR from this page."}),e.jsx("div",{children:"2. Scan it in Forge Companion to pass the desktop node and pairing token."}),e.jsx("div",{children:"3. Approve Health access on iPhone, then run the first sync."}),e.jsx("div",{children:"4. Use Advanced HTTP only for a local, Tailscale, or direct TCP route."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[y.length>0?e.jsx("div",{className:"flex justify-end",children:e.jsxs(H,{variant:"secondary",pending:A.isPending,pendingLabel:"Revoking all",onClick:()=>void A.mutateAsync(),children:[e.jsx(ip,{className:"size-4"}),"Revoke all"]})}):null,y.map(R=>e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-base text-white",children:R.deviceName??R.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[R.platform??"ios"," · ",R.status]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{tone:R.status==="healthy"?"signal":"meta",children:R.status.replaceAll("_"," ")}),R.lastSyncAt?e.jsxs(S,{tone:"meta",children:["Synced ",new Date(R.lastSyncAt).toLocaleString()]}):null]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:R.capabilities.map(v=>e.jsx(S,{tone:"meta",size:"sm",wrap:!0,children:G6(v)},v))}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-sm text-white/55",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{children:R.apiBaseUrl}),e.jsxs("div",{children:["Expires ",new Date(R.expiresAt).toLocaleString()]}),R.lastSyncError?e.jsx("div",{className:"text-rose-200/80",children:R.lastSyncError}):null]}),e.jsxs(H,{variant:"secondary",pending:b.isPending&&b.variables===R.id,pendingLabel:"Revoking",disabled:R.status==="revoked",onClick:()=>void b.mutateAsync(R.id),children:[e.jsx(ip,{className:"size-4"}),R.status==="revoked"?"Revoked":"Revoke"]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[16px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Device sync sources"}),[["health","Health"],["movement","Movement"],["screenTime","Screen Time"]].map(([v,D])=>{var V,B;const L=R.sourceStates[v],Q=L.desiredEnabled!==L.appliedEnabled,Z=T.isPending&&((V=T.variables)==null?void 0:V.pairingSessionId)===R.id&&((B=T.variables)==null?void 0:B.source)===v;return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[14px] border border-white/6 bg-white/[0.03] px-3 py-3",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-sm text-white",children:D}),e.jsx(S,{tone:Y6(L.desiredEnabled,L.syncEligible),size:"sm",children:L.desiredEnabled?"Enabled":"Off"}),Q?e.jsx(S,{tone:"meta",size:"sm",children:"Pending on phone"}):e.jsx(S,{tone:"meta",size:"sm",children:"Applied"})]}),e.jsxs("div",{className:"text-xs text-white/55",children:["Authorization ",V6(L.authorizationStatus)," · ","Last seen ",X6(L.lastObservedAt)]})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":L.desiredEnabled,"aria-label":`${D} sync source`,disabled:Z,onClick:()=>void T.mutateAsync({pairingSessionId:R.id,source:v,desiredEnabled:!L.desiredEnabled}),className:`relative inline-flex h-7 w-12 items-center rounded-full border transition ${L.desiredEnabled?"border-[rgba(171,232,255,0.4)] bg-[rgba(111,133,232,0.36)]":"border-white/10 bg-white/[0.06]"} ${Z?"opacity-60":""}`,children:e.jsx("span",{className:`inline-block size-5 rounded-full bg-white shadow transition ${L.desiredEnabled?"translate-x-6":"translate-x-1"}`})})]},v)})]})]},R.id)),y.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-6 text-sm text-white/55",children:"No companion paired yet. Generate a QR code, then open the iOS companion and scan it."}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(H,{variant:"secondary",onClick:()=>void x.refetch(),children:[e.jsx(sa,{className:"size-4"}),"Refresh status"]}),e.jsxs(et,{to:"/sleep",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(Hs,{className:"size-4"}),"Open sleep view"]}),e.jsxs(et,{to:"/sports",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(Hs,{className:"size-4"}),"Open sports view"]}),e.jsxs(et,{to:"/vitals",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(Hs,{className:"size-4"}),"Open vitals view"]})]})]})]}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Sync history"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Recent HealthKit import runs"})]}),e.jsxs(S,{tone:"meta",children:[I.importRuns.length," recent runs"]})]}),e.jsxs("div",{className:"grid gap-3",children:[I.importRuns.map(R=>e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4 lg:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Cj,{className:"size-4 text-white/55"}),e.jsxs("div",{className:"text-base text-white",children:[R.sourceDevice||"iPhone"," import"]}),e.jsx(S,{tone:R.status==="completed"?"signal":"meta",children:R.status})]}),e.jsxs("div",{className:"text-sm text-white/60",children:[new Date(R.importedAt).toLocaleString()," ·"," ",Q6(R.payloadSummary)]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs(S,{tone:"meta",children:["Imported ",R.importedCount]}),e.jsxs(S,{tone:"meta",children:["Created ",R.createdCount]}),e.jsxs(S,{tone:"meta",children:["Updated ",R.updatedCount]}),e.jsxs(S,{tone:"meta",children:["Merged ",R.mergedCount]})]}),R.errorMessage?e.jsx("div",{className:"text-sm text-rose-200/80",children:R.errorMessage}):null]}),R.pairingSessionId?e.jsxs("div",{className:"text-sm text-white/45 lg:text-right",children:["Pairing ",R.pairingSessionId]}):null]},R.id)),I.importRuns.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-6 text-sm text-white/55",children:"No sync runs yet. Pair the iPhone companion and run the first HealthKit import."}):null]})]})]})}function su(t="openai-api"){return{label:t==="openai-codex"?"OpenAI Codex":t==="openai-compatible"?"Local compatible endpoint":t==="mock"?"Workbench mock runtime":"OpenAI API",provider:t,baseUrl:t==="openai-codex"?"https://chatgpt.com/backend-api":t==="openai-compatible"?"http://127.0.0.1:11434/v1":t==="mock"?"mock://workbench":"https://api.openai.com/v1",model:t==="mock"?"mock-echo":"gpt-5.4-mini",apiKey:""}}function tE(t){return{id:t.id,label:t.label,provider:t.provider,baseUrl:t.baseUrl,model:t.model,apiKey:""}}function sE(){var Q,Z,V;const t=pt(),[s,a]=u.useState(()=>su()),[i,r]=u.useState(""),[n,l]=u.useState("gpt-5.4-mini"),[o,d]=u.useState(""),[m,h]=u.useState("gpt-5.4-mini"),[c,p]=u.useState(""),[g,x]=u.useState(null),[f,b]=u.useState(null),A=Me({queryKey:["forge-settings"],queryFn:pr}),T=Me({queryKey:["forge-openai-codex-oauth",g],queryFn:async()=>{if(!g)throw new Error("Missing OAuth session id");return await w1(g)},enabled:!!g,refetchInterval:B=>{var E;const $=(E=B.state.data)==null?void 0:E.session.status;return $&&["authorized","error","consumed","expired"].includes($)?!1:1500}}),I=async()=>{await t.invalidateQueries({queryKey:["forge-settings"]}),await t.invalidateQueries({queryKey:["forge-openai-codex-oauth",g]})},y=De({mutationFn:()=>gi({modelSettings:{forgeAgent:{basicChat:{connectionId:i||null,model:n},wiki:{connectionId:o||null,model:m}}}}),onSuccess:I}),N=De({mutationFn:()=>g1({id:s.id,label:s.label,provider:s.provider,authMode:s.provider==="openai-codex"?"oauth":"api_key",baseUrl:s.baseUrl,model:s.model,apiKey:s.provider==="openai-codex"?void 0:s.apiKey||void 0,oauthSessionId:s.provider==="openai-codex"?g??void 0:void 0}),onSuccess:async()=>{b("Connection saved."),s.provider==="openai-codex"&&(x(null),p("")),a(su(s.provider)),await I()}}),k=De({mutationFn:f1,onSuccess:I}),w=De({mutationFn:async()=>b1({connectionId:s.id,provider:s.provider,baseUrl:s.baseUrl,model:s.model,apiKey:s.provider==="openai-codex"?void 0:s.apiKey||void 0}),onSuccess:({result:B})=>{b(`Connection test succeeded: ${B.outputPreview}`)},onError:B=>{b(B instanceof Error?B.message:"Connection test failed.")}}),P=De({mutationFn:y1,onSuccess:({session:B})=>{x(B.id),b("OpenAI Codex OAuth started."),B.authUrl&&window.open(B.authUrl,"_blank","noopener,noreferrer")}}),j=De({mutationFn:async()=>{if(!g)throw new Error("No OAuth session started yet.");return await v1(g,c)},onSuccess:({session:B})=>{b(B.status==="authorized"?"OpenAI Codex OAuth authorized.":"Manual OAuth code submitted.")}});u.useEffect(()=>{var $;const B=($=A.data)==null?void 0:$.settings;B&&(r(B.modelSettings.forgeAgent.basicChat.connectionId??""),l(B.modelSettings.forgeAgent.basicChat.model),d(B.modelSettings.forgeAgent.wiki.connectionId??""),h(B.modelSettings.forgeAgent.wiki.model))},[A.data]);const R=((Q=A.data)==null?void 0:Q.settings.modelSettings.connections)??[],v=((Z=T.data)==null?void 0:Z.session)??null,D=u.useMemo(()=>!s.label.trim()||!s.model.trim()?!1:s.provider==="openai-codex"?!!(s.id||(v==null?void 0:v.status)==="authorized"):s.provider==="mock"?!0:s.apiKey.trim().length>0||!!s.id,[s,v==null?void 0:v.status]);if(A.isLoading)return e.jsx(zt,{eyebrow:"Models",title:"Loading model settings",description:"Fetching Forge agent defaults and configured AI connections."});if(A.isError||!((V=A.data)!=null&&V.settings))return e.jsx(ct,{eyebrow:"Models",error:A.error??new Error("Forge returned an empty model settings payload."),onRetry:()=>void A.refetch()});const L=A.data.settings;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(mt,{eyebrow:"AI runtime",title:"Model Settings",description:"Manage Forge Agent defaults, OpenAI OAuth/API connections, and local OpenAI-compatible endpoints as first-class chat agents.",badge:`${R.length} model connection${R.length===1?"":"s"}`}),e.jsx(Aa,{}),e.jsxs(le,{className:"grid gap-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sa,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Forge Agent defaults"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Forge Agent stays the default system agent. Choose which model connection powers basic chat and the managed wiki workflow."})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Basic chat connection"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:i,onChange:B=>r(B.target.value),children:[e.jsx("option",{value:"",children:"No external connection"}),R.map(B=>e.jsxs("option",{value:B.id,children:[B.label," (",B.agentLabel,")"]},B.id))]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:n,onChange:B=>l(B.target.value),placeholder:"Model"})]}),e.jsxs("label",{className:"grid gap-2 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("span",{className:"text-sm text-white/72",children:"KarpaWiki model connection"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:o,onChange:B=>d(B.target.value),children:[e.jsx("option",{value:"",children:"No external connection"}),R.map(B=>e.jsxs("option",{value:B.id,children:[B.label," (",B.agentLabel,")"]},B.id))]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:m,onChange:B=>h(B.target.value),placeholder:"Model"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(H,{pending:y.isPending,pendingLabel:"Saving defaults",onClick:()=>void y.mutateAsync(),children:"Save Forge Agent defaults"}),e.jsxs(S,{className:"bg-white/[0.06] text-white/78",children:["Forge Agent",L.modelSettings.forgeAgent.basicChat.connectionLabel?` basic chat: ${L.modelSettings.forgeAgent.basicChat.connectionLabel}`:" basic chat stays local"]}),e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:L.modelSettings.forgeAgent.wiki.connectionLabel?`KarpaWiki: ${L.modelSettings.forgeAgent.wiki.connectionLabel}`:"KarpaWiki: no external model selected"})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ij,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Connection editor"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Every saved connection becomes a first-class agent layered on top of Forge Agent."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Provider"}),e.jsx("div",{className:"grid gap-2 md:grid-cols-3",children:[["openai-api","OpenAI API"],["openai-codex","OpenAI Codex OAuth"],["openai-compatible","OpenAI-compatible"]].map(([B,$])=>e.jsx("button",{type:"button",className:`rounded-[18px] px-4 py-3 text-left text-sm transition ${s.provider===B?"bg-[var(--primary)]/[0.18] text-white":"bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"}`,onClick:()=>{a(su(B)),x(null),p("")},children:$},B))})]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.label,onChange:B=>a($=>({...$,label:B.target.value})),placeholder:"Connection label"}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.model,onChange:B=>a($=>({...$,model:B.target.value})),placeholder:"Model"}),s.provider==="mock"?e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white",children:"The Workbench mock runtime is only meant for local development and test workflows."}),e.jsxs("div",{className:"text-xs leading-5 text-white/52",children:["Use mock models like ",e.jsx("code",{children:"mock-echo"}),", ",e.jsx("code",{children:"mock-json"}),",",e.jsx("code",{children:"mock-tool-search"}),", ",e.jsx("code",{children:"mock-tool-note"}),", or",e.jsx("code",{children:"mock-chat-memory"})," to exercise deterministic flow behavior without a real external model."]})]}):s.provider!=="openai-codex"?e.jsxs(e.Fragment,{children:[e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.baseUrl,onChange:B=>a($=>({...$,baseUrl:B.target.value})),placeholder:"Base URL"}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.apiKey,onChange:B=>a($=>({...$,apiKey:B.target.value})),placeholder:s.id?"Leave blank to keep the stored key":"API key",type:"password"})]}):e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"text-sm text-white",children:["OpenAI Codex uses the documented PKCE flow with the local callback at ",L.modelSettings.oauth.openAiCodex.callbackUrl,"."]}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Start OAuth, finish the browser sign-in, then save the resulting connection as a chat agent backed by the ChatGPT Codex runtime."}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(H,{variant:"secondary",pending:P.isPending,pendingLabel:"Starting OAuth",onClick:()=>void P.mutateAsync(),children:[e.jsx(Ut,{className:"size-4"}),"Start OAuth"]}),v!=null&&v.authUrl?e.jsxs(H,{variant:"secondary",onClick:()=>window.open(v.authUrl??"","_blank","noopener,noreferrer"),children:["Open sign-in",e.jsx(Ra,{className:"size-4"})]}):null]}),v?e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-black/20 p-3 text-sm text-white/72",children:[e.jsxs("div",{children:["Status: ",v.status]}),v.accountLabel?e.jsxs("div",{children:["Account: ",v.accountLabel]}):null,v.error?e.jsx("div",{className:"text-rose-200",children:v.error}):null]}):null,e.jsxs("div",{className:"grid gap-2",children:[e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:c,onChange:B=>p(B.target.value),placeholder:"Paste the authorization code or full redirect URL"}),e.jsx(H,{variant:"secondary",disabled:!c.trim()||!g,pending:j.isPending,pendingLabel:"Submitting",onClick:()=>void j.mutateAsync(),children:"Submit manual code"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(H,{pending:N.isPending,pendingLabel:"Saving connection",disabled:!D,onClick:()=>void N.mutateAsync(),children:"Save connection"}),e.jsxs(H,{variant:"secondary",pending:w.isPending,pendingLabel:"Testing",disabled:s.provider==="openai-codex"?!s.id:s.provider==="mock"?!1:!s.id&&!s.apiKey.trim(),onClick:()=>void w.mutateAsync(),children:[e.jsx(rr,{className:"size-4"}),"Test connection"]})]}),f?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:f}):null]})]}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sa,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Connected agents"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Each connection registers its own chat-facing agent identity."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[R.length===0?e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-5 text-sm leading-6 text-white/58",children:"No external model connection yet. Add one with OAuth or API credentials and Forge will expose it as a first-class agent."}):null,R.map(B=>e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-white",children:B.label}),e.jsxs("div",{className:"mt-1 text-xs text-white/46",children:[B.agentLabel," · ",B.provider," ·"," ",B.model]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"secondary",onClick:()=>{a(tE(B)),x(null),p("")},children:"Edit"}),e.jsx(H,{variant:"secondary",pending:k.isPending,pendingLabel:"Deleting",onClick:()=>void k.mutateAsync(B.id),children:e.jsx(Wt,{className:"size-4"})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:B.authMode==="oauth"?"OAuth":"API key"}),e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:B.status}),e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:B.baseUrl}),B.accountLabel?e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:B.accountLabel}):null]})]},B.id))]})]})]})]})}const aE=["error","warning","info","debug"],iE=["server","ui","system","agent","openclaw"],rE=60;function vl(t){return t.trim().toLowerCase()}function Ur(t){return Array.from(new Set(t.map(s=>(s==null?void 0:s.trim())??"").filter(Boolean)))}function _r(t,s){const a=Ur(t.getAll(s));if(a.length>0)return a;const i=t.get(s);return i!=null&&i.trim()?[i.trim()]:[]}function nE(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}).format(new Date(t))}function Cv(t){return t==="error"?"border-rose-400/20 bg-rose-500/[0.08] text-rose-100":t==="warning"?"border-amber-400/20 bg-amber-500/[0.08] text-amber-100":t==="info"?"border-sky-400/20 bg-sky-500/[0.08] text-sky-100":"border-white/10 bg-white/[0.04] text-white/68"}function au(t){return t==="error"?"Errors":t==="warning"?"Warnings":t==="info"?"Info":"Debug"}function iu(t){return t==="openclaw"?"OpenClaw":t.charAt(0).toUpperCase()+t.slice(1)}function lE(t){return[t.scope?`scope: ${t.scope}`:null,t.eventKey?`event: ${t.eventKey}`:null,t.route?`route: ${t.route}`:null,t.functionName?`function: ${t.functionName}`:null,t.jobId?`job: ${t.jobId}`:null,t.entityType&&t.entityId?`entity: ${t.entityType}:${t.entityId}`:null,t.requestId?`request: ${t.requestId}`:null].filter(s=>!!s)}function oE(t){return vl([t.message,t.scope,t.eventKey,t.route,t.functionName,t.requestId,t.entityType,t.entityId,t.jobId,JSON.stringify(t.details)].filter(Boolean).join(" "))}function zi(t,s){return e.jsx(S,{size:"sm",className:te("bg-white/[0.08] text-white/74",s),children:t})}function Wg(t,s){return nS(t)?e.jsx(Qe,{kind:t,label:s,compact:!0,gradient:!1}):zi(s,"bg-[rgba(192,193,255,0.12)] text-white/84")}function Fr({label:t,placeholder:s,options:a,selectedIds:i,onChange:r,emptyMessage:n="No matches yet."}){const[l,o]=u.useState(!1),[d,m]=u.useState(""),[h,c]=u.useState(0),p=u.useRef(null),g=u.useRef(null),x=Eb(p,l,{offset:8,preferredMaxHeight:320,minHeight:160}),f=u.useMemo(()=>i.map(y=>a.find(N=>N.id===y)??null).filter(y=>y!==null),[a,i]),b=vl(d),A=u.useMemo(()=>{const y=a.filter(N=>!i.includes(N.id));return b?y.filter(N=>vl(`${N.label} ${N.description??""} ${N.searchText??""}`).includes(b)).slice(0,10):y.slice(0,10)},[b,a,i]),T=y=>{i.includes(y)||(r([...i,y]),m(""),c(0),o(!1))},I=y=>{r(i.filter(N=>N!==y))};return u.useEffect(()=>{if(!l)return;const y=k=>{var P,j;const w=k.target;(P=p.current)!=null&&P.contains(w)||(j=g.current)!=null&&j.contains(w)||o(!1)},N=k=>{k.key==="Escape"&&o(!1)};return document.addEventListener("pointerdown",y),document.addEventListener("keydown",N),()=>{document.removeEventListener("pointerdown",y),document.removeEventListener("keydown",N)}},[l]),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.18em] text-white/45",children:t}),e.jsxs("div",{ref:p,className:"relative rounded-[20px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[f.length>0?e.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:f.map(y=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/8 bg-white/[0.05] px-1.5 py-1",children:[y.badge,e.jsx("button",{type:"button",className:"rounded-full p-0.5 text-white/46 transition hover:text-white",onClick:()=>I(y.id),"aria-label":`Remove ${y.label}`,children:e.jsx(Lt,{className:"size-3"})})]},y.id))}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"size-3.5 text-white/34"}),e.jsx("input",{value:d,onChange:y=>{m(y.target.value),c(0),o(!0)},onFocus:()=>o(!0),onKeyDown:y=>{if(y.key==="Backspace"&&!d&&i.length>0){I(i[i.length-1]);return}if(y.key==="ArrowDown"){y.preventDefault(),o(!0),c(N=>A.length===0?0:Math.min(A.length-1,N+1));return}if(y.key==="ArrowUp"){y.preventDefault(),c(N=>Math.max(0,N-1));return}if(y.key==="Escape"){o(!1);return}y.key==="Enter"&&A[h]&&(y.preventDefault(),T(A[h].id))},placeholder:s,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),l&&x&&typeof document<"u"?Ti.createPortal(e.jsx("div",{ref:g,role:"listbox","aria-multiselectable":"true",className:"z-[80] overflow-y-auto overscroll-contain rounded-[20px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl [webkit-overflow-scrolling:touch]",style:x,children:A.length>0?A.map((y,N)=>e.jsx("button",{type:"button",role:"option","aria-selected":!1,className:te("flex w-full items-start justify-between gap-3 rounded-[16px] px-3 py-2 text-left transition",N===h?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>c(N),onMouseDown:k=>k.preventDefault(),onClick:()=>T(y.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:y.menuBadge??y.badge}),y.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:y.description}):null]})},y.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-white/42",children:n})}),document.body):null]})]})}function dE(t,s){const a=`${s.entityType}:${s.entityId}`;t.has(a)||t.set(a,{id:a,label:s.label,description:s.description,searchText:s.searchText,badge:s.badge,menuBadge:s.menuBadge})}function cE(t){const s=new Map;for(const a of t){if(!a.entityType||!a.entityId)continue;const i=`${a.entityType}:${a.entityId}`;if(s.has(i))continue;const r=a.entityType==="wiki_ingest_job"?`Ingest ${a.entityId}`:`${a.entityType} ${a.entityId}`;dE(s,{entityType:a.entityType,entityId:a.entityId,label:r,description:"Seen in diagnostics logs",searchText:vl(`${r} ${a.scope} ${a.message} ${a.eventKey}`),badge:Wg(a.entityType,r),menuBadge:Wg(a.entityType,r)})}return Array.from(s.values()).sort((a,i)=>a.label.localeCompare(i.label))}const uE=u.memo(function({entry:s}){const[a,i]=u.useState(!1),r=u.useMemo(()=>a&&Object.keys(s.details).length>0?JSON.stringify(s.details,null,2):"",[a,s.details]);return e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:te("rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em]",Cv(s.level)),children:s.level}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/60",children:s.source}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/60",children:s.scope}),s.eventKey?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/46",children:s.eventKey}):null]}),e.jsx("div",{className:"text-base font-medium text-white",children:s.message}),e.jsx("div",{className:"flex flex-wrap gap-3 text-xs text-white/45",children:lE(s).map(n=>e.jsx("span",{children:n},n))})]}),e.jsxs("div",{className:"shrink-0 text-right text-xs text-white/40",children:[e.jsx("div",{children:nE(s.createdAt)}),e.jsx("div",{className:"mt-1 font-mono text-[11px]",children:s.id})]})]}),Object.keys(s.details).length>0?e.jsxs("details",{className:"rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",onToggle:n=>i(n.currentTarget.open),children:[e.jsx("summary",{className:"cursor-pointer text-sm text-white/70",children:"View structured details"}),a?e.jsx("pre",{className:"mt-3 overflow-x-auto whitespace-pre-wrap text-xs leading-6 text-white/58",children:r}):null]}):null]})});function mE(){const[t,s]=ws(),a=u.useMemo(()=>{var j,R;const k=((j=t.get("entityType"))==null?void 0:j.trim())||"",w=((R=t.get("entityId"))==null?void 0:R.trim())||"",P=_r(t,"entity");return P.length===0&&k&&w&&P.push(`${k}:${w}`),{search:t.get("search")||"",levels:_r(t,"level"),sources:_r(t,"source"),scopes:_r(t,"scope"),routes:_r(t,"route"),jobs:_r(t,"jobId"),entities:Ur(P)}},[t]),i=pu({queryKey:["forge-diagnostic-logs","settings-filters"],initialPageParam:null,queryFn:({pageParam:k})=>R2({limit:rE,beforeCreatedAt:k==null?void 0:k.beforeCreatedAt,beforeId:k==null?void 0:k.beforeId}),getNextPageParam:k=>k.nextCursor,retry:!1,refetchOnWindowFocus:!1}),r=(k,w)=>{const P=new URLSearchParams(t);w.trim()?P.set(k,w.trim()):P.delete(k),s(P,{replace:!0})},n=(k,w,P=[])=>{const j=new URLSearchParams(t);j.delete(k);for(const R of P)j.delete(R);for(const R of Ur(w))j.append(k,R);s(j,{replace:!0})},l=()=>{const k=new URLSearchParams(t);["search","level","source","scope","route","jobId","entity","entityType","entityId"].forEach(w=>k.delete(w)),s(k,{replace:!0})},o=u.useMemo(()=>{var k;return((k=i.data)==null?void 0:k.pages.flatMap(w=>w.logs))??[]},[i.data]),d=vl(a.search),m=u.useRef(null),h=u.useMemo(()=>aE.map(k=>({id:k,label:au(k),searchText:`${k} ${au(k)}`,badge:e.jsx(S,{size:"sm",className:Cv(k),children:au(k)})})),[]),c=u.useMemo(()=>iE.map(k=>({id:k,label:iu(k),searchText:`${k} ${iu(k)}`,badge:zi(iu(k))})),[]),p=u.useMemo(()=>Ur(o.map(k=>k.scope)).map(k=>({id:k,label:k,searchText:k,badge:zi(k)})),[o]),g=u.useMemo(()=>Ur(o.map(k=>k.route)).map(k=>({id:k,label:k,description:"Filter logs to one or more exact routes.",searchText:k,badge:zi(k,"max-w-[16rem]"),menuBadge:zi(k)})),[o]),x=u.useMemo(()=>Ur(o.map(k=>k.jobId)).map(k=>({id:k,label:k,description:"Background job or ingest run id.",searchText:k,badge:zi(k,"max-w-[14rem]"),menuBadge:zi(k)})),[o]),f=u.useMemo(()=>cE(o),[o]),b=u.useMemo(()=>o.filter(k=>{if(d&&!oE(k).includes(d)||a.levels.length>0&&!a.levels.includes(k.level)||a.sources.length>0&&!a.sources.includes(k.source)||a.scopes.length>0&&!a.scopes.includes(k.scope)||a.routes.length>0&&!a.routes.includes(k.route??"")||a.jobs.length>0&&!a.jobs.includes(k.jobId??""))return!1;if(a.entities.length>0){const w=k.entityType&&k.entityId?`${k.entityType}:${k.entityId}`:"";if(!w||!a.entities.includes(w))return!1}return!0}),[a,d,o]),A=[a.search,a.levels.join("|"),a.sources.join("|"),a.scopes.join("|"),a.routes.join("|"),a.jobs.join("|"),a.entities.join("|")].join("::");u.useEffect(()=>{var k;(k=m.current)==null||k.scrollTo({top:0})},[A]);const T=Ad({count:b.length,getScrollElement:()=>m.current,estimateSize:()=>260,overscan:8}),I=T.getVirtualItems(),y=()=>{const k=m.current;if(!k||!i.hasNextPage||i.isFetchingNextPage)return;k.scrollHeight-k.scrollTop-k.clientHeight<=800&&i.fetchNextPage()},N=a.levels.length+a.sources.length+a.scopes.length+a.routes.length+a.jobs.length+a.entities.length+(a.search.trim()?1:0);return i.isPending?e.jsx(gs,{eyebrow:"Settings",title:"Loading diagnostics",description:"Collecting the latest frontend, backend, and runtime traces.",columns:1,blocks:6}):i.isError?e.jsx(ct,{eyebrow:"Settings",error:i.error,onRetry:()=>void i.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(mt,{title:"Logs",description:"Inspect shared diagnostics from the UI, backend routes, background jobs, and LLM flows.",badge:`${b.length} matching${b.length!==o.length?` · ${o.length} loaded`:""}${i.hasNextPage?" · more available":""}`}),e.jsx(Aa,{}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Filters"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Use token filters with OR-style badge selections for levels, sources, routes, jobs, scopes, and linked entities. Search still matches the message body and structured details."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[N>0?e.jsxs(H,{variant:"ghost",size:"sm",onClick:l,children:["Clear ",N]}):null,e.jsx(H,{variant:"secondary",size:"sm",onClick:()=>void i.refetch(),pending:i.isRefetching&&!i.isFetchingNextPage,pendingLabel:"Refreshing",children:"Refresh"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.18em] text-white/45",children:"Search message or details"}),e.jsx(be,{value:a.search,onChange:k=>r("search",k.target.value),placeholder:"LLM compilation failed, wiki_ingest, request_failed…",className:"h-11 rounded-[20px]"})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsx(Fr,{label:"Levels",placeholder:"Add one or more levels",options:h,selectedIds:a.levels,onChange:k=>n("level",k),emptyMessage:"No additional log levels."}),e.jsx(Fr,{label:"Sources",placeholder:"Add one or more sources",options:c,selectedIds:a.sources,onChange:k=>n("source",k),emptyMessage:"No additional log sources."}),e.jsx(Fr,{label:"Scopes",placeholder:"Search scopes",options:p,selectedIds:a.scopes,onChange:k=>n("scope",k),emptyMessage:"No scopes match the current logs."}),e.jsx(Fr,{label:"Routes",placeholder:"Search exact routes",options:g,selectedIds:a.routes,onChange:k=>n("route",k),emptyMessage:"No routes match the current logs."}),e.jsx(Fr,{label:"Jobs",placeholder:"Search job ids",options:x,selectedIds:a.jobs,onChange:k=>n("jobId",k),emptyMessage:"No job ids match the current logs."}),e.jsx(Fr,{label:"Entities",placeholder:"Search Forge entities or logged ids",options:f,selectedIds:a.entities,onChange:k=>n("entity",k,["entityType","entityId"]),emptyMessage:"No logged entities match yet."})]})]}),e.jsx("div",{className:"grid gap-3",children:b.length===0?e.jsx(le,{className:"text-sm text-white/58",children:"No diagnostic entries match the current filters yet."}):e.jsx(le,{className:"p-0",children:e.jsxs("div",{ref:m,onScroll:y,className:"h-[72vh] overflow-y-auto px-3 py-3",children:[e.jsx("div",{className:"relative",style:{height:`${T.getTotalSize()}px`},children:I.map(k=>{const w=b[k.index];return w?e.jsx("div",{"data-index":k.index,ref:T.measureElement,className:"absolute left-0 top-0 w-full pb-3",style:{transform:`translateY(${k.start}px)`},children:e.jsx(uE,{entry:w})},w.id):null})}),e.jsx("div",{className:"border-t border-white/6 px-1 py-3 text-center text-xs text-white/46",children:i.isFetchingNextPage?"Loading older logs…":i.hasNextPage?"Scroll to load older logs.":`Showing all ${o.length} loaded logs.`})]})})})]})}function hE(t){switch(t){case"platinum":return"text-cyan-200";case"gold":return"text-amber-200";case"silver":return"text-slate-200";default:return"text-orange-200"}}function pE(t){switch(t){case"surging":return"from-[rgba(192,193,255,0.3)] via-[rgba(78,222,163,0.22)] to-[rgba(255,185,95,0.22)]";case"steady":return"from-[rgba(192,193,255,0.24)] via-[rgba(192,193,255,0.14)] to-[rgba(78,222,163,0.18)]";default:return"from-[rgba(255,185,95,0.2)] via-[rgba(255,185,95,0.12)] to-[rgba(192,193,255,0.16)]"}}function xE({profile:t,achievements:s,milestoneRewards:a,momentumPulse:i,recentLedger:r=[],className:n,tone:l="core"}){const o=s.filter(p=>p.unlocked),d=(o.length>0?o:s).slice(0,3),m=a.slice(0,3),h=r.slice(0,3),c=Math.min(100,Math.round(t.currentLevelXp/t.nextLevelXp*100));return e.jsxs("section",{className:te("min-w-0 overflow-hidden rounded-[30px] border border-white/6 bg-[linear-gradient(180deg,rgba(18,24,40,0.96),rgba(11,16,28,0.94))] shadow-[0_24px_70px_rgba(4,8,18,0.3)]",l==="psyche"&&"bg-[linear-gradient(180deg,rgba(18,27,35,0.96),rgba(12,20,26,0.94))]",n),children:[e.jsx("div",{className:te("bg-gradient-to-r px-5 py-5",pE(i.status)),children:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/55",children:"Weekly progress"}),e.jsx("h2",{className:"mt-3 font-display text-3xl leading-none text-white lg:text-4xl",children:i.headline}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/68",children:i.detail})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap gap-2",children:[e.jsxs(S,{wrap:!0,className:"bg-black/20 text-white/84",children:["Level ",t.level]}),e.jsxs(S,{wrap:!0,className:"bg-black/20 text-white/84",children:[t.streakDays," day streak"]}),e.jsxs(S,{wrap:!0,className:"bg-black/20 text-white/84",children:[t.weeklyXp," weekly XP"]})]})]})}),e.jsxs("div",{className:"grid gap-5 px-5 py-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(Ms.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.24,ease:"easeOut"},className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-white",children:"Next reward"}),e.jsx("div",{className:"mt-2 text-sm text-white/60",children:i.nextMilestoneLabel})]}),e.jsx(S,{wrap:!0,className:"max-w-[12rem] shrink-0 self-start text-[var(--tertiary)]",children:i.celebrationLabel})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Gs,{value:c})}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-xs uppercase tracking-[0.16em] text-white/38",children:[e.jsxs("span",{children:[t.currentLevelXp,"/",t.nextLevelXp," XP"]}),e.jsxs("span",{children:[t.comboMultiplier.toFixed(2),"x combo"]})]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:d.map((p,g)=>e.jsxs(Ms.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.24,delay:.04*g,ease:"easeOut"},className:"overflow-hidden rounded-[22px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:p.title}),e.jsx(S,{wrap:!0,className:te("max-w-[8rem] shrink-0 self-start",hE(p.tier)),children:p.tier})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:p.summary}),e.jsx("div",{className:"mt-4 text-xs uppercase tracking-[0.16em] text-white/40",children:p.progressLabel})]},p.id))})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Rewards in progress"}),e.jsx("div",{className:"mt-4 grid gap-3",children:m.map(p=>{const g=Math.min(100,Math.round(p.current/p.target*100));return e.jsxs("div",{className:"overflow-hidden rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:p.title}),e.jsx(S,{wrap:!0,className:te("max-w-[10.5rem] shrink-0 self-start",p.completed?"text-emerald-300":"text-white/68"),children:p.rewardLabel})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:p.summary}),e.jsx("div",{className:"mt-4",children:e.jsx(Gs,{value:g})}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:p.progressLabel})]},p.id)})})]}),h.length>0?e.jsxs("div",{className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recent XP changes"}),e.jsx("div",{className:"mt-4 grid gap-3",children:h.map(p=>e.jsxs("div",{className:"overflow-hidden rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:p.reasonTitle}),e.jsxs(S,{wrap:!0,className:te("max-w-[8rem] shrink-0 self-start",p.deltaXp>=0?"text-emerald-300":"text-amber-300"),children:[p.deltaXp>0?"+":"",p.deltaXp," XP"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:p.reasonSummary}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:Ml(p.createdAt)})]},p.id))})]}):null]})]})]})}function gE(t){return JSON.stringify(t,null,2)}function Hg(t){const s=t.trim();if(!s)return{};const a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Expected a JSON object.");return a}function fE(){var j,R,v;const t=Ct(),s=pt(),[a,i]=u.useState(""),[r,n]=u.useState(null),[l,o]=u.useState(null),d=Me({queryKey:["forge-operator-session"],queryFn:mr}),m=d.isSuccess,h=Me({queryKey:["forge-xp-metrics"],queryFn:_m}),c=Me({queryKey:["forge-reward-rules"],queryFn:S2,enabled:m}),p=Me({queryKey:["forge-reward-ledger"],queryFn:()=>T2(30),enabled:m}),g=Me({queryKey:["forge-psyche-overview"],queryFn:async()=>(await Dd()).overview}),x=Yo({defaultValues:{title:"",description:"",active:!0,configJson:"{}"}}),f=Yo({defaultValues:{entityType:"task",entityId:"",deltaXp:15,reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"}}),b=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-xp-metrics"]}),s.invalidateQueries({queryKey:["forge-reward-rules"]}),s.invalidateQueries({queryKey:["forge-reward-ledger"]})])},A=De({mutationFn:D=>C2(D.ruleId,{title:D.title,description:D.description,active:D.active,config:D.config}),onSuccess:b}),T=De({mutationFn:I2,onSuccess:b}),I=((j=c.data)==null?void 0:j.rules)??[],y=u.useMemo(()=>{var D,L,Q,Z,V,B;return{system:[{id:"operator_manual_reward",label:"Operator reward ledger"}],goal:t.snapshot.goals.map($=>({id:$.id,label:$.title})),project:t.snapshot.dashboard.projects.map($=>({id:$.id,label:$.title})),task:t.snapshot.tasks.map($=>({id:$.id,label:$.title})),habit:t.snapshot.habits.map($=>({id:$.id,label:$.title})),tag:t.snapshot.tags.map($=>({id:$.id,label:$.name})),note:[],insight:[],psyche_value:(((D=g.data)==null?void 0:D.values)??[]).map($=>({id:$.id,label:$.title})),behavior_pattern:(((L=g.data)==null?void 0:L.patterns)??[]).map($=>({id:$.id,label:$.title})),behavior:(((Q=g.data)==null?void 0:Q.behaviors)??[]).map($=>({id:$.id,label:$.title})),belief_entry:(((Z=g.data)==null?void 0:Z.beliefs)??[]).map($=>({id:$.id,label:$.statement})),mode_profile:(((V=g.data)==null?void 0:V.modes)??[]).map($=>({id:$.id,label:$.title})),trigger_report:(((B=g.data)==null?void 0:B.reports)??[]).map($=>({id:$.id,label:$.title}))}},[g.data,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits,t.snapshot.tags,t.snapshot.tasks]);u.useEffect(()=>{var Z;const D=f.getValues("entityType"),L=f.getValues("entityId"),Q=y[D]??[];L&&Q.some(V=>V.id===L)||f.setValue("entityId",((Z=Q[0])==null?void 0:Z.id)??"")},[f,y]),u.useEffect(()=>{I.length&&(!a||!I.some(D=>D.id===a))&&i(I[0].id)},[I,a]);const N=I.find(D=>D.id===a)??I[0]??null;u.useEffect(()=>{N&&(x.reset({title:N.title,description:N.description,active:N.active,configJson:gE(N.config)}),n(null))},[N,x]);const k=(R=h.data)==null?void 0:R.metrics,P=(((v=p.data)==null?void 0:v.ledger)??[]).filter(D=>D.metadata.manual===!0).slice(0,8);return d.isLoading?e.jsx(gs,{eyebrow:"Settings · Rewards",title:"Loading reward controls",description:"Establishing the operator session and fetching reward configuration.",columns:2,blocks:6}):d.isError?e.jsx(ct,{eyebrow:"Settings · Rewards",error:d.error,onRetry:()=>void d.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(mt,{title:"Rewards",description:"XP command deck, reward rule editor, manual bonus grants, and ledger history."}),e.jsx(Aa,{}),e.jsx("div",{className:"grid gap-5",children:e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Reward operations"}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[k?e.jsx(xE,{profile:k.profile,achievements:k.achievements,milestoneRewards:k.milestoneRewards,momentumPulse:k.momentumPulse,recentLedger:k.recentLedger}):null,k?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Os,{label:"Total XP",value:k.profile.totalXp,tone:"core"}),e.jsx(Os,{label:"Daily ambient",value:`${k.dailyAmbientXp} / ${k.dailyAmbientCap}`,tone:"core"})]}):null,e.jsxs("div",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Reward rule editor"}),I.length>0?e.jsxs("form",{className:"mt-4 grid gap-4",onSubmit:x.handleSubmit(async D=>{try{n(null);const L=Hg(D.configJson);if(!N)return;await A.mutateAsync({ruleId:N.id,title:D.title,description:D.description,active:D.active,config:L})}catch(L){n(L instanceof Error?L.message:"Invalid reward rule config.")}}),children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Rule"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:a,onChange:D=>i(D.target.value),children:I.map(D=>e.jsx("option",{value:D.id,children:D.title},D.id))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Title"}),e.jsx(be,{...x.register("title")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Description"}),e.jsx(st,{className:"min-h-24",...x.register("description")})]}),e.jsxs("label",{className:"flex items-center justify-between rounded-[18px] bg-[rgba(8,13,28,0.68)] px-4 py-3",children:[e.jsx("span",{className:"text-white/72",children:"Rule is active"}),e.jsx("input",{type:"checkbox",...x.register("active")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Config JSON"}),e.jsx(st,{className:"min-h-28 font-mono text-xs",...x.register("configJson")})]}),r?e.jsx("div",{className:"text-sm text-amber-300",children:r}):null,e.jsx(H,{type:"submit",pending:A.isPending,pendingLabel:"Saving rule",children:"Save reward rule"})]}):e.jsx("div",{className:"mt-4 text-sm text-white/58",children:"Loading reward rules…"})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Manual bonus XP"}),e.jsxs("form",{className:"mt-4 grid gap-4",onSubmit:f.handleSubmit(async D=>{try{o(null);const L=Hg(D.metadataJson);await T.mutateAsync({entityType:D.entityType,entityId:D.entityId,deltaXp:D.deltaXp,reasonTitle:D.reasonTitle,reasonSummary:D.reasonSummary,metadata:L}),f.reset({...D,entityId:"",reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"})}catch(L){o(L instanceof Error?L.message:"Invalid metadata payload.")}}),children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Entity type"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",...f.register("entityType"),children:Object.keys(y).map(D=>e.jsx("option",{value:D,children:D.replaceAll("_"," ")},D))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Entity id"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",...f.register("entityId"),children:(y[f.watch("entityType")]??[]).map(D=>e.jsx("option",{value:D.id,children:D.label},D.id))})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Delta XP"}),e.jsx(be,{type:"number",...f.register("deltaXp",{valueAsNumber:!0})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Reason title"}),e.jsx(be,{...f.register("reasonTitle")})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Reason summary"}),e.jsx(st,{className:"min-h-24",...f.register("reasonSummary")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Metadata JSON"}),e.jsx(st,{className:"min-h-24 font-mono text-xs",...f.register("metadataJson")})]}),l?e.jsx("div",{className:"text-sm text-amber-300",children:l}):null,e.jsx(H,{type:"submit",pending:T.isPending,pendingLabel:"Issuing bonus",children:"Issue bonus XP"})]}),T.data?e.jsxs("div",{className:"mt-4 rounded-[18px] bg-[rgba(192,193,255,0.12)] p-4 text-sm text-white",children:["Granted ",T.data.reward.deltaXp>0?"+":"",T.data.reward.deltaXp," XP for ",e.jsx("strong",{children:T.data.reward.reasonTitle}),"."]}):null]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Manual bonus history"}),e.jsx("div",{className:"mt-4 grid gap-3",children:P.length===0?e.jsx("div",{className:"rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4 text-sm text-white/58",children:"No manual bonus grants yet."}):P.map(D=>e.jsxs("div",{className:"rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:D.reasonTitle}),e.jsxs(S,{className:D.deltaXp>=0?"text-emerald-300":"text-amber-300",children:[D.deltaXp>0?"+":"",D.deltaXp," XP"]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:D.reasonSummary||"No summary supplied."}),e.jsxs("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/38",children:[D.entityType," · ",D.entityId," · ",new Date(D.createdAt).toLocaleString()]})]},D.id))})]})]})]})})]})}const Iv=[{id:"visibility",label:"Discovery and visibility",description:"What the source user can discover, inspect, and pull into read flows on the target side.",rights:[{key:"discoverable",label:"Discoverable",description:"The target appears as a reachable collaborator in the source user's graph and pickers."},{key:"canListUsers",label:"List users",description:"The source user can include the target in directory, comparison, and routing surfaces."},{key:"canReadProfile",label:"Read profile",description:"The source user can inspect the target's identity card, handle, type, and description."},{key:"canReadEntities",label:"Read entities",description:"The source user can read the target's goals, projects, tasks, notes, strategies, and related records."},{key:"canSearchEntities",label:"Search entities",description:"The source user can find the target's work through Forge search and entity pickers."}]},{id:"coordination",label:"Messaging, context, and handoff",description:"What the source user can message, connect, and coordinate on the target side before changing execution.",rights:[{key:"canLinkEntities",label:"Share context",description:"The source user can attach the target's records into shared notes, strategies, calendar context, and cross-owner plans."},{key:"canCoordinate",label:"Message and coordinate",description:"The source user can communicate with the target through Forge, hand off work, and coordinate execution."},{key:"canViewMetrics",label:"View metrics",description:"The source user can inspect the target's XP, alignment, and progress metrics."},{key:"canViewActivity",label:"View activity",description:"The source user can inspect the target's activity stream, evidence, and execution trail."}]},{id:"execution",label:"Plan and execution control",description:"What the source user can actually change on the target side once collaboration is trusted.",rights:[{key:"canManageStrategies",label:"Manage strategies",description:"The source user can draft and update strategies that belong to the target."},{key:"canCreateOnBehalf",label:"Create on behalf",description:"The source user can intentionally create new target-owned entities."},{key:"canAffectEntities",label:"Affect entities",description:"The source user can mutate work that belongs to the target."}]}],bE=[{id:"full_collab",label:"Full collaboration",description:"Use when two humans or agents can see, coordinate, plan, and change each other's work.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!0,canCoordinate:!0,canAffectEntities:!0,canManageStrategies:!0,canCreateOnBehalf:!0,canViewMetrics:!0,canViewActivity:!0}},{id:"coordination_only",label:"Coordinate only",description:"Use when the source user may see and coordinate with the target but should not directly mutate target-owned work.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!0,canCoordinate:!0,canAffectEntities:!1,canManageStrategies:!0,canCreateOnBehalf:!1,canViewMetrics:!0,canViewActivity:!0}},{id:"observe_only",label:"Observe only",description:"Use when the source user should keep visibility into the target without planning or execution control.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!1,canCoordinate:!1,canAffectEntities:!1,canManageStrategies:!1,canCreateOnBehalf:!1,canViewMetrics:!0,canViewActivity:!0}},{id:"hidden",label:"Hidden edge",description:"Use when this direction should stop discovering, reading, or acting on the target.",rights:{discoverable:!1,canListUsers:!1,canReadProfile:!1,canReadEntities:!1,canSearchEntities:!1,canLinkEntities:!1,canCoordinate:!1,canAffectEntities:!1,canManageStrategies:!1,canCreateOnBehalf:!1,canViewMetrics:!1,canViewActivity:!1}}],Zr=Iv.reduce((t,s)=>t+s.rights.length,0);function sc(t){return Object.values(t.config.rights).filter(Boolean).length}function Tv(t){const s=[];return t.config.rights.canReadEntities&&s.push("See"),t.config.rights.canCoordinate&&s.push("Message"),t.config.rights.canManageStrategies&&s.push("Plan"),t.config.rights.canAffectEntities&&s.push("Affect"),s.join(" · ")||"Hidden"}function yE(t){return!t.config.rights.discoverable&&!t.config.rights.canReadEntities?"Hidden":t.config.rights.canAffectEntities&&t.config.rights.canManageStrategies?"Trusted":t.config.rights.canCoordinate||t.config.rights.canLinkEntities?"Coordinated":"Observed"}function Pv(t){return[{id:"see",label:"See",enabled:t.config.rights.discoverable&&t.config.rights.canReadEntities&&t.config.rights.canSearchEntities},{id:"message",label:"Message",enabled:t.config.rights.canCoordinate},{id:"share",label:"Share context",enabled:t.config.rights.canLinkEntities},{id:"plan",label:"Plan",enabled:t.config.rights.canManageStrategies},{id:"affect",label:"Affect",enabled:t.config.rights.canAffectEntities||t.config.rights.canCreateOnBehalf}]}function wE(t,s){return Object.entries(s.rights).every(([a,i])=>t.config.rights[a]===i)}function vE(t,s){const a=t.filter(p=>p.kind==="human"),i=t.filter(p=>p.kind==="bot"),r={x:560,y:360},n={width:226,height:132},l=a[0]??null,d=[...a.slice(l?1:0).map(p=>({user:p,radius:245,offset:-90})),...i.map(p=>({user:p,radius:390,offset:-90}))],m=d.length,h=[...l?[{user:l,position:{x:r.x-n.width/2,y:r.y-n.height/2}}]:[],...d.map((p,g)=>{const x=(p.offset+360/Math.max(m,1)*g)*Math.PI/180;return{user:p.user,position:{x:r.x+Math.cos(x)*p.radius-n.width/2,y:r.y+Math.sin(x)*p.radius-n.height/2}}})],c=new Set(s.selectedGrant?[s.selectedGrant.subjectUserId,s.selectedGrant.targetUserId]:s.selectedUserId?[s.selectedUserId]:[]);return h.map(({user:p,position:g})=>{const x=c.has(p.id),f=p.id===s.selectedUserId;return{id:p.id,position:g,draggable:!1,selectable:!1,data:{label:e.jsxs("div",{className:`min-w-[206px] rounded-[22px] border px-4 py-4 shadow-[0_24px_60px_rgba(0,0,0,0.28)] transition ${f?"border-[rgba(244,185,122,0.45)] bg-[rgba(27,16,10,0.92)]":x?"border-white/18 bg-[rgba(14,20,34,0.94)]":"border-white/10 bg-[rgba(9,15,28,0.92)]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ht,{user:p}),e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:p.kind})]}),e.jsxs("div",{className:"mt-3 text-xs text-white/52",children:["@",p.handle]}),e.jsx("div",{className:"mt-2 line-clamp-2 text-xs leading-5 text-white/46",children:p.description||"No user description yet."})]})},style:{background:"transparent",border:"none",padding:0}}})}function jE(t,s,a){return t.filter(i=>i.subjectUserId!==i.targetUserId).map(i=>{const r=s===i.id,n=a!==null&&(i.subjectUserId===a||i.targetUserId===a),l=sc(i),o=r?"#f4b97a":!i.config.rights.discoverable&&!i.config.rights.canReadEntities?"rgba(248,113,113,0.55)":n?"rgba(192,193,255,0.78)":"rgba(255,255,255,0.32)";return{id:i.id,source:i.subjectUserId,target:i.targetUserId,label:`${Tv(i)} · ${l}/${Zr}`,markerEnd:{type:bm.ArrowClosed,color:o},labelStyle:{fill:r?"#f4b97a":"rgba(255,255,255,0.68)",fontSize:11,fontWeight:600},labelBgStyle:{fill:r?"rgba(34,23,16,0.96)":"rgba(8,13,24,0.94)",stroke:r?"rgba(244,185,122,0.36)":"rgba(255,255,255,0.14)",strokeWidth:1},labelBgPadding:[7,5],labelBgBorderRadius:8,style:{stroke:o,strokeWidth:r?2.5:n?1.8:1.25},animated:r}})}function kE({users:t,grants:s,selectedGrantId:a=null,selectedUserId:i=null,onOpenGrant:r,onOpenUser:n}){const l=s.find(g=>g.id===a)??null,o=u.useMemo(()=>vE(t,{selectedUserId:i,selectedGrant:l}),[l,i,t]),d=u.useMemo(()=>jE(s,a,i),[s,a,i]),m=u.useMemo(()=>s.filter(g=>g.subjectUserId!==g.targetUserId),[s]),h=m.filter(g=>sc(g)===Zr).length,c=m.filter(g=>g.config.rights.canCoordinate).length,p=m.filter(g=>g.config.rights.canAffectEntities||g.config.rights.canCreateOnBehalf).length;return e.jsxs(le,{className:"overflow-hidden p-0",children:[e.jsxs("div",{className:"grid gap-4 border-b border-white/8 px-5 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Directed relationship graph"}),e.jsx(Tt,{content:"Keep Forge, OpenClaw, Hermes, and the browser on the same runtime and storage root when these arrows should describe one shared human and bot system.",label:"Explain the shared runtime rule"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Click a user card to open that user's settings. Click any arrow to open the exact directional relationship flow for that lane."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[m.length," edges"]}),e.jsxs(S,{className:"bg-emerald-500/12 text-emerald-200",children:[h," fully open"]})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Full collaboration"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:h}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions still running with the default fully open posture."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Coordination lanes"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:c}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions allowed to coordinate directly through Forge."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Execution control"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:p}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions allowed to create or mutate target-owned work."})]})]})]}),e.jsx("div",{className:"h-[min(72vh,54rem)] min-h-[34rem] bg-[radial-gradient(circle_at_top,rgba(244,185,122,0.08),transparent_34%),linear-gradient(180deg,rgba(6,10,20,0.97),rgba(8,14,26,0.94))]",children:e.jsxs(Td,{className:"user-relationship-flow",nodes:o,edges:d,fitView:!0,fitViewOptions:{padding:.18,maxZoom:.95},nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,onNodeClick:(g,x)=>{n(x.id)},onEdgeClick:(g,x)=>{r(x.id)},attributionPosition:"bottom-left",children:[e.jsx(fm,{showInteractive:!1}),e.jsx(Pd,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})]})}const NE={kind:"human",handle:"",displayName:"",description:"",accentColor:"#c0c1ff"};function Gg(t){return t?{kind:t.kind,handle:t.handle,displayName:t.displayName,description:t.description,accentColor:t.accentColor}:NE}function SE({open:t,onOpenChange:s,user:a,grants:i,ownership:r,xp:n,pending:l=!1,onSubmit:o,onOpenRelationship:d}){const[m,h]=u.useState(()=>Gg(a)),[c,p]=u.useState(null);u.useEffect(()=>{t&&(h(Gg(a)),p(null))},[t,a]);const g=u.useMemo(()=>i.filter(A=>A.subjectUserId!==A.targetUserId),[i]),x=u.useMemo(()=>a?g.filter(A=>A.subjectUserId===a.id):[],[g,a]),f=u.useMemo(()=>a?g.filter(A=>A.targetUserId===a.id):[],[g,a]),b=[{id:"identity",eyebrow:a?"Edit user":"Create user",title:a?"Update the user identity":"Add a human or bot user",description:"Set the owner type and the public identity Forge will use across ownership, routing, and collaboration surfaces.",render:(A,T)=>e.jsxs(e.Fragment,{children:[e.jsx(oe,{label:"Kind",description:"Humans represent real people. Bots represent agents or automations with their own ownership lane.",children:e.jsx(St,{columns:2,value:A.kind,onChange:I=>T({kind:I}),options:[{value:"human",label:"Human",description:"Use for a real person in the Forge runtime."},{value:"bot",label:"Bot",description:"Use for an agent, assistant, or automation actor."}]})}),e.jsx(oe,{label:"Handle",description:"This becomes the stable short id shown as @handle.",hint:"Use lowercase and a durable label, for example forge-operator or planner-bot.",children:e.jsx(be,{value:A.handle,onChange:I=>T({handle:I.target.value}),placeholder:"forge-operator"})}),e.jsx(oe,{label:"Display name",description:"This is the human-readable label used across the UI.",children:e.jsx(be,{value:A.displayName,onChange:I=>T({displayName:I.target.value}),placeholder:"Forge Operator"})})]})},{id:"profile",eyebrow:"Profile",title:"Describe the user lane",description:"Capture what this user represents in the shared Forge runtime and pick the accent color that helps the lane stay recognizable.",render:(A,T)=>e.jsxs(e.Fragment,{children:[e.jsx(oe,{label:"Description",description:"Explain what this user is responsible for and what side of the system it represents.",children:e.jsx(st,{value:A.description,onChange:I=>T({description:I.target.value}),className:"min-h-36",placeholder:"Primary human operator for strategy, execution, and review."})}),e.jsx(oe,{label:"Accent color",description:"Forge uses this accent to help the user stand out in ownership and collaboration surfaces.",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(be,{value:A.accentColor,onChange:I=>T({accentColor:I.target.value}),placeholder:"#c0c1ff"}),e.jsx("div",{className:"size-10 shrink-0 rounded-full border border-white/10",style:{backgroundColor:A.accentColor||"#c0c1ff"}})]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Owned records"}),e.jsx("div",{className:"mt-2 text-white",children:(r==null?void 0:r.totalOwnedEntities)??0})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Total XP"}),e.jsx("div",{className:"mt-2 text-white",children:(n==null?void 0:n.totalXp)??0})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Weekly XP"}),e.jsx("div",{className:"mt-2 text-white",children:(n==null?void 0:n.weeklyXp)??0})]})]})]})},{id:"relationships",eyebrow:"Relationships",title:"Open directional relationship settings",description:"Each arrow is a separate contract. Open the exact lane you want to adjust and Forge will take you into the relationship flow.",render:()=>a?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx(ht,{user:a}),e.jsxs("div",{className:"mt-3 text-sm leading-6 text-white/56",children:["@",a.handle," · ",a.description||"No description yet."]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Outbound lanes"}),x.length>0?x.map(A=>e.jsxs("button",{type:"button",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-left transition hover:bg-white/[0.05]",onClick:()=>d(A.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ht,{user:A.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(ht,{user:A.targetUser})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:Tv(A)}),e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[sc(A),"/",Zr," rights"]})]})]},A.id)):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm text-white/52",children:"No outbound relationship lanes yet."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Inbound lanes"}),f.length>0?f.map(A=>e.jsxs("button",{type:"button",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-left transition hover:bg-white/[0.05]",onClick:()=>d(A.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ht,{user:A.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(ht,{user:A.targetUser})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Pv(A).map(T=>e.jsx(S,{className:T.enabled?"bg-white/[0.08] text-white/74":"bg-white/[0.04] text-white/38",children:T.label},`${A.id}-${T.id}`))})]},A.id)):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm text-white/52",children:"No inbound relationship lanes yet."})]})]})]}):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm leading-6 text-white/52",children:"Create the user first, then Forge will generate the directional relationship lanes you can tune from here."})}];return e.jsx(Kt,{open:t,onOpenChange:s,eyebrow:a?"User settings":"Create user",title:a?"User settings":"Create user",description:"Edit the user identity, clarify what this lane represents, and jump into relationship settings without crowding the page.",value:m,onChange:h,draftPersistenceKey:a?`users.settings.${a.id}`:"users.settings.new",steps:b,submitLabel:a?"Save user":"Create user",pending:l,pendingLabel:a?"Saving user":"Creating user",error:c,contentClassName:"lg:w-[min(58rem,calc(100vw-1.5rem))]",onSubmit:async()=>{const A=m.handle.trim(),T=m.displayName.trim();if(A.length===0){p("Add a handle before saving this user.");return}if(T.length===0){p("Add a display name before saving this user.");return}await o({userId:a==null?void 0:a.id,input:{kind:m.kind,handle:A,displayName:T,description:m.description.trim(),accentColor:m.accentColor.trim()||"#c0c1ff"}}),s(!1)}})}function Qg(t,s){return{accessLevel:(t==null?void 0:t.accessLevel)??"manage",applyScope:"this_arrow",rights:{discoverable:(t==null?void 0:t.config.rights.discoverable)??!0,canListUsers:(t==null?void 0:t.config.rights.canListUsers)??!0,canReadProfile:(t==null?void 0:t.config.rights.canReadProfile)??!0,canReadEntities:(t==null?void 0:t.config.rights.canReadEntities)??!0,canSearchEntities:(t==null?void 0:t.config.rights.canSearchEntities)??!0,canLinkEntities:(t==null?void 0:t.config.rights.canLinkEntities)??!0,canCoordinate:(t==null?void 0:t.config.rights.canCoordinate)??!0,canAffectEntities:(t==null?void 0:t.config.rights.canAffectEntities)??!0,canManageStrategies:(t==null?void 0:t.config.rights.canManageStrategies)??!0,canCreateOnBehalf:(t==null?void 0:t.config.rights.canCreateOnBehalf)??!0,canViewMetrics:(t==null?void 0:t.config.rights.canViewMetrics)??!0,canViewActivity:(t==null?void 0:t.config.rights.canViewActivity)??!0}}}function CE({open:t,onOpenChange:s,grant:a,grants:i,pending:r=!1,onSubmit:n}){const l=u.useMemo(()=>a?i.find(p=>p.subjectUserId===a.targetUserId&&p.targetUserId===a.subjectUserId)??null:null,[a,i]),[o,d]=u.useState(()=>Qg(a,!!l));u.useEffect(()=>{t&&d(Qg(a,!!l))},[a,t,l]);const m=u.useMemo(()=>Object.values(o.rights).filter(Boolean).length,[o.rights]),h=Math.round(m/Zr*100),c=[{id:"posture",eyebrow:"Relationship posture",title:"Set the trust mode for this arrow",description:"Each arrow is directional. Decide whether you want to tune only this lane or mirror the same contract onto both directions.",render:(p,g)=>e.jsxs(e.Fragment,{children:[a?e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ht,{user:a.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(ht,{user:a.targetUser})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:yE(a)}),e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[sc(a),"/",Zr," rights"]})]})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Access level"}),e.jsx(St,{columns:2,value:p.accessLevel,onChange:x=>g({accessLevel:x}),options:[{value:"view",label:"View",description:"Use when this lane should stay mostly observational."},{value:"manage",label:"Manage",description:"Use when the source side can actively collaborate or act."}]})]}),l?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Apply scope"}),e.jsx(St,{columns:2,value:p.applyScope,onChange:x=>g({applyScope:x}),options:[{value:"this_arrow",label:"This arrow",description:"Only change the exact direction you opened."},{value:"both_arrows",label:"Both arrows",description:"Mirror the same contract onto the reverse direction too."}]})]}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Quick preset"}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:bE.map(x=>e.jsxs("button",{type:"button",className:`rounded-[22px] border p-4 text-left transition ${a&&wE(a,x)?"border-[rgba(244,185,122,0.35)] bg-[rgba(244,185,122,0.08)]":"border-white/8 bg-white/[0.03] hover:bg-white/[0.05]"}`,onClick:()=>g({rights:{...p.rights,...x.rights}}),children:[e.jsx("div",{className:"text-sm font-medium text-white",children:x.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:x.description})]},x.id))})]})]})},{id:"rights",eyebrow:"Rights",title:"Tune the individual permissions",description:"Use the preset as the starting point, then sharpen the exact boundaries only where this relationship needs them.",render:(p,g)=>e.jsx(e.Fragment,{children:Iv.map(x=>e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:x.label}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/54",children:x.description})]}),e.jsx("div",{className:"grid gap-2",children:x.rights.map(f=>e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:f.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:f.description})]}),e.jsx("input",{type:"checkbox",checked:p.rights[f.key],onChange:b=>g({rights:{...p.rights,[f.key]:b.target.checked}})})]},f.key))})]},x.id))})},{id:"review",eyebrow:"Review",title:"Review the final relationship contract",description:"Check the enabled capabilities, confirm whether both directions should match, and then save the relationship.",render:p=>{var g,x;return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Capability coverage"}),e.jsx("div",{className:"mt-4",children:e.jsx(Gs,{value:h})}),e.jsxs("div",{className:"mt-3 text-sm text-white/62",children:[m,"/",Zr," rights enabled"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Pv({...a??{id:"draft",subjectUserId:"",targetUserId:"",accessLevel:p.accessLevel,config:{self:!1,mutable:!0,linkedEntities:!0,rights:p.rights},createdAt:"",updatedAt:"",subjectUser:null,targetUser:null},accessLevel:p.accessLevel,config:{...(a==null?void 0:a.config)??{self:!1,mutable:!0,linkedEntities:!0},rights:p.rights}}).map(f=>e.jsx(S,{className:f.enabled?"bg-white/[0.08] text-white/74":"bg-white/[0.04] text-white/38",children:f.label},f.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Save scope"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:p.applyScope==="both_arrows"&&l?"Forge will apply the same access level and rights to both directions of this pair.":"Forge will only update the exact arrow you opened."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:["access ",p.accessLevel]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:["scope"," ",p.applyScope==="both_arrows"&&l?"both arrows":"this arrow"]})]}),l?e.jsxs("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/54",children:["Reverse arrow available:"," ",((g=l.subjectUser)==null?void 0:g.displayName)??l.subjectUserId," ","→"," ",((x=l.targetUser)==null?void 0:x.displayName)??l.targetUserId]}):null]})]})})}}];return e.jsx(Kt,{open:t,onOpenChange:s,eyebrow:"Relationship settings",title:"Relationship settings",description:"Edit the exact directional contract between two users without keeping the full rights editor pinned on the page.",value:o,onChange:d,draftPersistenceKey:a?`users.relationship.${a.id}`:"users.relationship.new",steps:c,submitLabel:"Save relationship",pending:r,pendingLabel:"Saving relationship",contentClassName:"lg:w-[min(62rem,calc(100vw-1.5rem))]",onSubmit:async()=>{a&&(await n({grantId:a.id,patch:{accessLevel:o.accessLevel,rights:o.rights},reverseGrantId:(l==null?void 0:l.id)??null,applyToReverse:o.applyScope==="both_arrows"&&l!==null}),s(!1))}})}function IE(){var j;const t=Ct(),[s,a]=u.useState(null),[i,r]=u.useState(null),[n,l]=u.useState(!1),[o,d]=u.useState(!1),[m,h]=u.useState(""),c=Me({queryKey:["forge-user-directory"],queryFn:a2}),p=async()=>{await Promise.all([t.refresh(),c.refetch()])},g=De({mutationFn:async({input:R,userId:v})=>v?(await n2(v,R)).user:(await r2(R)).user,onSuccess:async()=>{a(null),l(!1),await p()}}),x=De({mutationFn:async({grantId:R,patch:v})=>(await i2(R,v)).grant,onSuccess:p}),f=(j=c.data)==null?void 0:j.directory,b=(f==null?void 0:f.grants.find(R=>R.id===i))??null,A=u.useMemo(()=>new Map(((f==null?void 0:f.ownership)??[]).map(R=>[R.userId,R])),[f==null?void 0:f.ownership]),T=u.useMemo(()=>new Map(((f==null?void 0:f.xp)??[]).map(R=>[R.userId,R])),[f==null?void 0:f.xp]),I=u.useMemo(()=>{const R=new Map;for(const v of(f==null?void 0:f.grants)??[]){if(!v.targetUser||v.subjectUserId===v.targetUserId)continue;const D=R.get(v.subjectUserId)??[];D.push(v.targetUser),R.set(v.subjectUserId,D)}return R},[f==null?void 0:f.grants]),y=u.useMemo(()=>{const R=((f==null?void 0:f.grants)??[]).filter(v=>v.subjectUserId!==v.targetUserId);return{totalEdges:R.length,fullyOpenEdges:R.filter(v=>Object.values(v.config.rights).every(Boolean)).length,coordinationEdges:R.filter(v=>v.config.rights.canCoordinate).length,executionEdges:R.filter(v=>v.config.rights.canAffectEntities||v.config.rights.canCreateOnBehalf).length}},[f==null?void 0:f.grants]),N=m.trim().toLowerCase(),k=u.useMemo(()=>{const v=((f==null?void 0:f.users)??t.snapshot.users).filter(D=>N?[D.displayName,D.handle,D.kind,D.description].join(" ").toLowerCase().includes(N):!0);return{humans:v.filter(D=>D.kind==="human"),bots:v.filter(D=>D.kind==="bot")}},[f==null?void 0:f.users,N,t.snapshot.users]),w=(b==null?void 0:b.subjectUserId)??(s==null?void 0:s.id)??null,P=(b==null?void 0:b.id)??null;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(mt,{title:"Users",description:"Forge users can be human or bot. Ownership, search, and routing are prepared so work can move across both sides of the system.",badge:`${t.snapshot.users.length} users`}),e.jsx(Aa,{}),e.jsx(SE,{open:n,onOpenChange:l,user:s,grants:(f==null?void 0:f.grants)??[],ownership:s?A.get(s.id)??null:null,xp:s?T.get(s.id)??null:null,pending:g.isPending,onSubmit:async R=>{await g.mutateAsync(R)},onOpenRelationship:R=>{l(!1),r(R),d(!0)}}),e.jsx(CE,{open:o,onOpenChange:d,grant:b,grants:(f==null?void 0:f.grants)??[],pending:x.isPending,onSubmit:async R=>{await x.mutateAsync({grantId:R.grantId,patch:R.patch}),R.applyToReverse&&R.reverseGrantId&&await x.mutateAsync({grantId:R.reverseGrantId,patch:R.patch})}}),e.jsxs(le,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Multi-user posture"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:(f==null?void 0:f.posture.summary)??"Forge is preparing modular user access while keeping the current posture permissive."})]}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:(f==null?void 0:f.posture.accessModel)??"permissive"})]}),e.jsx("div",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:e.jsx(be,{value:m,onChange:R=>h(R.target.value),placeholder:"Search human, bot, @handle, or description"})})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Multi-agent onboarding"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:"Forge now treats the users graph as the collaboration control plane. Create each human or bot here, keep the runtime shared, then narrow only the specific arrows that should stop seeing, coordinating, planning, or affecting another user."})]}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:"default open"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Directional edges"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y.totalEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Fully open"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y.fullyOpenEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Coordination"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y.coordinationEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Execution control"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y.executionEdges})]})]}),e.jsxs("div",{className:"grid gap-2 text-sm leading-6 text-white/56",children:[e.jsx("div",{children:"1. Create the human and bot users that should exist in the shared Forge system."}),e.jsx("div",{children:"2. Point OpenClaw, Hermes, and the browser at the same Forge runtime and storage root."}),e.jsx("div",{children:"3. Use the graph below to decide what each direction can see, message, plan, or change."}),e.jsx("div",{children:"4. Keep strategy drafting open while the plan is negotiated, then lock the strategy once it becomes the contract."})]})]}),e.jsx(kE,{users:(f==null?void 0:f.users)??t.snapshot.users,grants:(f==null?void 0:f.grants)??[],selectedGrantId:P,selectedUserId:w,onOpenUser:R=>{const v=((f==null?void 0:f.users)??t.snapshot.users).find(D=>D.id===R)??null;r(null),a(v),l(!0)},onOpenGrant:R=>{a(null),r(R),d(!0)}}),e.jsxs(le,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Agent onboarding"}),e.jsx("div",{className:"text-sm leading-6 text-white/60",children:"OpenClaw, Hermes, and the Forge UI all read this same multi-user graph. Keep the defaults open while you are still wiring collaboration, then narrow specific arrows when one user or agent should stop seeing, messaging, planning, or changing another user's work."}),e.jsx("div",{className:"text-sm leading-6 text-white/52",children:"Forge now treats every owner as either human or bot, keeps search cross-user by default, and allows cross-owner links plus explicit coordination lanes between projects, tasks, notes, and strategies."}),e.jsx("div",{children:e.jsx(et,{to:"/settings/agents",className:"inline-flex min-h-10 items-center justify-center rounded-[var(--radius-control)] bg-white/8 px-3 py-2 text-[13px] font-medium text-white transition hover:bg-white/12",children:"Open agent onboarding"})})]})]}),e.jsx(le,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"User directory"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:"Open any user to edit its identity and jump into the exact directional relationship lanes from the user settings flow."})]}),e.jsx(H,{onClick:()=>{r(null),a(null),l(!0)},children:"Create user"})]})}),e.jsx("div",{className:"grid gap-5",children:[{title:"Human users",users:k.humans},{title:"Bot users",users:k.bots}].map(R=>e.jsxs(le,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:R.title}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:R.users.length})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:R.users.map(v=>{var D,L,Q,Z,V,B;return e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(ht,{user:v}),e.jsxs("div",{className:"mt-3 text-sm text-white/58",children:["@",v.handle]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:v.description||"No description yet."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[((D=T.get(v.id))==null?void 0:D.totalXp)??0," XP"]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[((L=T.get(v.id))==null?void 0:L.weeklyXp)??0," weekly"]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[((Q=T.get(v.id))==null?void 0:Q.rewardEventCount)??0," ","rewards"]}),Object.entries(((Z=A.get(v.id))==null?void 0:Z.entityCounts)??{}).sort(($,E)=>E[1]-$[1]).slice(0,4).map(([$,E])=>e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[E," ",$]},`${v.id}-${$}`)),e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[((V=A.get(v.id))==null?void 0:V.totalOwnedEntities)??0," ","owned"]})]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/50",children:["Can currently read:"," ",(I.get(v.id)??[]).map($=>`${$.displayName} (${$.kind})`).join(", ")||"no other users"]}),(B=T.get(v.id))!=null&&B.lastRewardAt?e.jsxs("div",{className:"mt-2 text-xs leading-5 text-white/45",children:["Last XP movement:"," ",new Date(T.get(v.id).lastRewardAt).toLocaleString()]}):null]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(H,{variant:"secondary",onClick:()=>{r(null),a(v),l(!0)},children:"Open settings"})})]})},v.id)})})]},R.title))})]})]})}const Eh=[{id:"xp_levels",label:"XP and level",trophyCount:8,unlockCount:4},{id:"streaks",label:"Streak and comeback",trophyCount:14,unlockCount:10},{id:"tasks",label:"Tasks and focus runs",trophyCount:14,unlockCount:4},{id:"projects",label:"Projects, goals, and strategy",trophyCount:14,unlockCount:4},{id:"wiki",label:"Wiki, notes, and knowledge graph",trophyCount:16,unlockCount:6},{id:"psyche",label:"Psyche",trophyCount:18,unlockCount:10},{id:"habits",label:"Habits, Life Force, and health",trophyCount:8,unlockCount:8},{id:"agents",label:"Agents and collaboration",trophyCount:4,unlockCount:2}],TE=[1,2,3,5,7,14,21,30,45,60,90,180,365,730],PE=[1,2,3,5,7,10,14,21,30,60];function Te(t,s){return{metric:t,threshold:s}}function At(...t){return{allOf:t}}function wd(t){return t.toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function AE(t,s){const a=(t+1)/s;return a>.82?"platinum":a>.55?"gold":a>.25?"silver":"bronze"}function ME(t){return t==="platinum"?"legendary":t==="gold"?"hard":t==="silver"?"standard":"intro"}function EE(t){return t==="platinum"?"legendary":t==="gold"?"epic":t==="silver"?"rare":"common"}function LE(t){return`item-${t.kind}-${wd(t.category)}-${wd(t.title)}`}function Ze(t,s,a,i,r,n){return{category:t,kind:"trophy",title:s,summary:r,requirement:a,requirementText:i,reward:`${s} trophy on the Forge shelf`}}function gt(t,s,a,i,r,n,l){return{category:t,kind:"unlock",title:s,summary:n,requirement:i,requirementText:r,reward:`${s} cosmetic`,unlockType:a,rewardPayload:l}}const _E=[Ze("xp_levels","The First Heat",Te("nonManualXp",5e3),"Earn 5,000 non-manual XP.","The first real furnace of work is hot enough to be noticed."),Ze("xp_levels","Bellows Graduate",Te("nonManualXp",1e4),"Earn 10,000 non-manual XP.","Your reward ledger is no longer a spark; it is a system."),Ze("xp_levels","Iron Apprentice",Te("nonManualXp",2e4),"Earn 20,000 non-manual XP.","You have repeated the work enough that the anvil knows your hand."),Ze("xp_levels","Steel Temper",Te("nonManualXp",5e4),"Earn 50,000 non-manual XP.","Pressure has started to make the metal cleaner instead of louder."),Ze("xp_levels","Crown of Coals",Te("nonManualXp",1e5),"Earn 100,000 non-manual XP.","A visible crown for an invisible mountain of completed work."),Ze("xp_levels","Obsidian Master",Te("nonManualXp",25e4),"Earn 250,000 non-manual XP.","The Forge Smith stops testing your seriousness and starts respecting it."),Ze("xp_levels","Star-Forge Adept",Te("nonManualXp",5e5),"Earn 500,000 non-manual XP.","Your XP trail burns like a constellation across the operating system."),Ze("xp_levels","Mythic Smith",Te("nonManualXp",1e6),"Earn 1,000,000 non-manual XP.","A ridiculous trophy for a ridiculous amount of lived execution.")],FE=[gt("xp_levels","Obsidian Smith","mascot_skin",Te("nonManualXp",8e3),"Earn 8,000 non-manual XP.","A dramatic black-iron Forge Smith skin.",{mascotSkin:"obsidian-smith"}),gt("xp_levels","Molten Progress Bar","hud_treatment",Te("nonManualXp",25e3),"Earn 25,000 non-manual XP.","A bright molten XP fill for the level ring.",{hudTreatment:"molten-progress"}),gt("xp_levels","Apex Level Frame","icon_frame",Te("nonManualXp",1e5),"Earn 100,000 non-manual XP.","A high-tier frame for level and trophy icons.",{iconFrame:"apex-level"}),gt("xp_levels","Masterwork Glow","celebration_variant",Te("nonManualXp",25e4),"Earn 250,000 non-manual XP.","A stronger forge-bell reveal for major unlocks.",{celebrationVariant:"masterwork-glow"})],RE=[Ze("streaks","Spark Kept",Te("longestStreakDays",1),"Play one qualifying day.","The first day is small, but the forge heard it."),Ze("streaks","Three-Day Furnace",Te("longestStreakDays",3),"Reach a 3-day streak.","Three returns make the first shape of discipline."),Ze("streaks","Week-Fire",Te("longestStreakDays",7),"Reach a 7-day streak.","Seven days changes the temperature of your life."),Ze("streaks","Twin-Week Bellows",Te("longestStreakDays",14),"Reach a 14-day streak.","Two weeks of showing up makes the room expect you."),Ze("streaks","Cinder Discipline",Te("longestStreakDays",21),"Reach a 21-day streak.","The fire is not accidental anymore."),Ze("streaks","Monthly Forge",Te("longestStreakDays",30),"Reach a 30-day streak.","A full month of returns becomes a personal weather system."),Ze("streaks","Sixty-Day Flame",Te("longestStreakDays",60),"Reach a 60-day streak.","The Smith grows stronger because you stopped disappearing."),Ze("streaks","Quarter-Anvil",Te("longestStreakDays",90),"Reach a 90-day streak.","Ninety days is not motivation. It is architecture."),Ze("streaks","Half-Year Inferno",Te("longestStreakDays",180),"Reach a 180-day streak.","The forge is now a season of your life."),Ze("streaks","Year of Steel",Te("longestStreakDays",365),"Reach a 365-day streak.","A year of returns. The anvil has become a witness."),Ze("streaks","Comeback Hammer",Te("comebackAfter7Count",1),"Return after 7+ missed days and complete a qualifying action.","You came back after the room went cold."),Ze("streaks","Repair Artist",Te("comebackAfter7Count",3),"Complete 3 major comebacks.","Breaking the chain did not become breaking the story."),Ze("streaks","Rust Refuser",At(Te("comebackAfter7Count",5),Te("longestStreakDays",30)),"Complete 5 major comebacks and reach a 30-day streak.","You repeatedly turned absence into a new strike."),Ze("streaks","Relentless Return",At(Te("comebackAfter7Count",8),Te("longestStreakDays",90)),"Complete 8 major comebacks and reach a 90-day streak.","This trophy is for the part of you that keeps coming back.")],DE=[gt("streaks","Bronze Ember Flame","streak_effect",Te("longestStreakDays",3),"Reach a 3-day streak.","A small ember around the streak HUD.",{streakEffect:"bronze-ember"}),gt("streaks","Blue Forge-Fire","streak_effect",Te("longestStreakDays",7),"Reach a 7-day streak.","A cool blue streak flame.",{streakEffect:"blue-forge-fire"}),gt("streaks","Violet Arc Flame","streak_effect",Te("longestStreakDays",21),"Reach a 21-day streak.","A sharper violet flame effect.",{streakEffect:"violet-arc"}),gt("streaks","Molten Crown Fire","streak_effect",Te("longestStreakDays",60),"Reach a 60-day streak.","A crown-like fire treatment for streaks.",{streakEffect:"molten-crown"}),gt("streaks","Stern Pressure Pose","mascot_pose",Te("comebackAfter7Count",1),"Complete a major comeback.","Unlocks the Smith's stern pressure pose.",{mascotPose:"stern-pressure"}),gt("streaks","Comeback Pose","mascot_pose",Te("comebackAfter7Count",2),"Complete 2 major comebacks.","Unlocks the Smith's comeback repair pose.",{mascotPose:"comeback"}),gt("streaks","Awakening Forge Pose","mascot_pose",Te("longestStreakDays",30),"Reach a 30-day streak.","Unlocks the forge awakening mascot pose.",{mascotPose:"awakening-forge"}),gt("streaks","Yearfire Aura","streak_effect",Te("longestStreakDays",365),"Reach a 365-day streak.","A huge aura for year-scale presence.",{streakEffect:"yearfire-aura"}),gt("streaks","Old Foundry Shelf","trophy_shelf",Te("longestStreakDays",90),"Reach a 90-day streak.","A warmer trophy shelf skin.",{trophyShelf:"old-foundry"}),gt("streaks","Relentless Bell","celebration_variant",Te("longestStreakDays",180),"Reach a 180-day streak.","A heavier celebration sound-and-spark treatment.",{celebrationVariant:"relentless-bell"})],$E=[Ze("tasks","First Strike",Te("taskCompletionCount",25),"Complete 25 tasks.","A real task trail begins."),Ze("tasks","Clean Swing",At(Te("taskCompletionCount",50),Te("focusRunCount",10)),"Complete 50 tasks and 10 task runs.","Tasks and time-tracked execution start to converge."),Ze("tasks","Five Rivets",At(Te("taskCompletionCount",75),Te("taskCloseoutReportCount",5)),"Complete 75 tasks and 5 completion reports.","You are leaving proof behind, not just checkmarks."),Ze("tasks","Task Blade",At(Te("taskCompletionCount",120),Te("focusRunCount",25)),"Complete 120 tasks and 25 task runs.","A sharp blade forged out of repeated finishes."),Ze("tasks","Anvil Marathon",At(Te("taskCompletionCount",300),Te("focusRunCount",75)),"Complete 300 tasks and 75 task runs.","The long road achievement for serious execution."),Ze("tasks","Deep-Work Maul",Te("creditedFocusMinutes",3e3),"Log 3,000 credited focus minutes.","The heavy hammer of deliberate time."),Ze("tasks","Planned Heat",Te("plannedFocusRunCount",25),"Complete 25 planned task runs.","You planned the heat before striking the metal."),Ze("tasks","Closeout Scribe",Te("taskCloseoutReportCount",25),"Write 25 task completion reports.","The Forge remembers what changed because you wrote it down."),Ze("tasks","Hundred-Hammer Road",Te("taskCompletionCount",500),"Complete 500 tasks.","A road paved with finished work."),Ze("tasks","Timebox Knight",At(Te("plannedFocusRunCount",75),Te("creditedFocusMinutes",7500)),"Complete 75 planned runs and 7,500 focus minutes.","A trophy for time that obeyed the mission."),Ze("tasks","Backlog Breaker",Te("taskCompletionCount",750),"Complete 750 tasks.","The backlog learned to fear your return."),Ze("tasks","Execution Monarch",At(Te("taskCompletionCount",1e3),Te("focusRunCount",200)),"Complete 1,000 tasks and 200 task runs.","A crown for turning vague intention into finished artifacts."),Ze("tasks","Forge Ledger Exact",Te("taskCloseoutReportCount",100),"Write 100 task completion reports.","The most boring discipline becomes the most useful history."),Ze("tasks","The Hammer Does Not Blink",At(Te("taskCompletionCount",1500),Te("creditedFocusMinutes",15e3)),"Complete 1,500 tasks and 15,000 focus minutes.","For absurd consistency under real load.")],OE=[gt("tasks","Hammer Cursor","icon_frame",Te("taskCompletionCount",75),"Complete 75 tasks.","A hammer-shaped action accent.",{iconFrame:"hammer-cursor"}),gt("tasks","Focus Rail Glow","hud_treatment",Te("focusRunCount",25),"Complete 25 task runs.","A task-run glow for compact HUDs.",{hudTreatment:"focus-rail-glow"}),gt("tasks","Completion Burst","celebration_variant",Te("taskCloseoutReportCount",25),"Write 25 completion reports.","A sharper task-completion burst.",{celebrationVariant:"completion-burst"}),gt("tasks","Ember Knight","mascot_skin",Te("taskCompletionCount",500),"Complete 500 tasks.","A molten-armored Forge Smith skin for execution mastery.",{mascotSkin:"ember-knight"})],zE=[Ze("projects","Aligned Spark",Te("goalLinkedTaskCompletionCount",25),"Complete 25 goal-linked tasks.","Work starts pointing at something bigger."),Ze("projects","Goal Rivet",At(Te("goalLinkedTaskCompletionCount",50),Te("distinctGoalsWithCompletions",3)),"Complete 50 goal-linked tasks across 3 goals.","Several goals now have real rivets, not just titles."),Ze("projects","Strategist's Seal",At(Te("goalLinkedTaskCompletionCount",50),Te("distinctGoalsWithCompletions",5)),"Complete 50 goal-linked tasks across 5 goals.","A seal for strategy that survived contact with execution."),Ze("projects","Project Spine",At(Te("projectLinkedTaskCompletionCount",100),Te("activeProjectCount",5)),"Complete 100 project-linked tasks while maintaining 5 active projects.","The work has a spine across multiple initiatives."),Ze("projects","Strategy Weld",Te("strategyCount",10),"Create 10 strategies.","You forged planning layers instead of improvising every day."),Ze("projects","Purpose Hammer",Te("goalLinkedTaskCompletionCount",150),"Complete 150 goal-linked tasks.","The hammer keeps landing where your stated life points."),Ze("projects","Arc Builder",At(Te("projectLinkedTaskCompletionCount",250),Te("distinctGoalsWithCompletions",8)),"Complete 250 project-linked tasks across 8 goals.","Multiple arcs moved because you kept building."),Ze("projects","North-Star Foundry",At(Te("goalLinkedTaskCompletionCount",300),Te("strategyCount",20)),"Complete 300 goal-linked tasks and create 20 strategies.","The north star is no longer decorative."),Ze("projects","Project Finisher",Te("projectCompletionCount",5),"Complete 5 projects.","Finished projects leave heavier evidence than active dreams."),Ze("projects","Life-Work Crown",At(Te("projectCompletionCount",10),Te("goalLinkedTaskCompletionCount",500)),"Complete 10 projects and 500 goal-linked tasks.","A crown for long arcs that actually closed."),Ze("projects","Portfolio Anvil",Te("activeProjectCount",12),"Maintain 12 active projects.","A large operating portfolio, held without flattening."),Ze("projects","Tracer Bullet Guild",At(Te("projectCompletionCount",15),Te("strategyCount",35)),"Complete 15 projects and create 35 strategies.","Strategy and delivery joined hands repeatedly."),Ze("projects","Mountain Moved",Te("goalLinkedTaskCompletionCount",1e3),"Complete 1,000 goal-linked tasks.","The trophy for moving a mountain one task at a time."),Ze("projects","The Work Had A Spine",At(Te("projectCompletionCount",25),Te("distinctGoalsWithCompletions",12)),"Complete 25 projects across 12 goals.","Your life map became execution history.")],KE=[gt("projects","Goal Compass Frame","icon_frame",Te("goalLinkedTaskCompletionCount",50),"Complete 50 goal-linked tasks.","A compass frame for aligned-work trophies.",{iconFrame:"goal-compass"}),gt("projects","War-Room Iron Shelf","trophy_shelf",Te("projectLinkedTaskCompletionCount",150),"Complete 150 project-linked tasks.","A darker tactical trophy shelf.",{trophyShelf:"war-room-iron"}),gt("projects","North-Star HUD","hud_treatment",Te("strategyCount",20),"Create 20 strategies.","A strategy-forward HUD treatment.",{hudTreatment:"north-star"}),gt("projects","Foundry Compass Burst","celebration_variant",Te("projectCompletionCount",10),"Complete 10 projects.","A compass-shaped major reveal.",{celebrationVariant:"foundry-compass"})],qE=[Ze("wiki","First Inscription",Te("wikiPageCount",50),"Create 50 wiki pages.","Knowledge has started to become an archive."),Ze("wiki","Memory Rivet",Te("noteCount",100),"Create 100 notes.","The system remembers because you gave it material."),Ze("wiki","Archive Ember",At(Te("wikiPageCount",150),Te("wikiLinkCount",50)),"Create 150 wiki pages and 50 wiki links.","The archive starts connecting to itself."),Ze("wiki","Knowledge Anvil",At(Te("wikiPageCount",250),Te("wikiLinkCount",150)),"Create 250 wiki pages and 150 wiki links.","A serious anvil of memory and links."),Ze("wiki","Living Index",At(Te("wikiPageWithSummaryCount",100),Te("linkedWikiPageCount",100)),"Maintain 100 wiki pages with summaries and linked entities.","Pages now carry shape, summary, and relationships."),Ze("wiki","Black Library",At(Te("wikiPageCount",500),Te("wikiLinkCount",300)),"Create 500 wiki pages and 300 wiki links.","The great hard knowledge trophy."),Ze("wiki","Obsidian Index",At(Te("wikiPageWithSummaryCount",250),Te("wikiLinkCount",500)),"Maintain 250 summarized pages and 500 links.","The archive is no longer just big; it is navigable."),Ze("wiki","Graph Lantern",Te("knowledgeGraphNodeCount",500),"Reach 500 Knowledge Graph nodes.","The graph has enough stars to navigate by."),Ze("wiki","Entity Weaver",Te("linkedWikiPageCount",200),"Link 200 wiki pages to other pages or entities.","Your memory connects to the operating system."),Ze("wiki","Codex Temper",At(Te("wikiPageCount",750),Te("wikiLinkCount",750)),"Create 750 wiki pages and 750 wiki links.","A codex tempered by breadth and connection."),Ze("wiki","Note Furnace",Te("noteCount",500),"Create 500 notes.","Raw notes became a real furnace of evidence."),Ze("wiki","Archive Cartographer",At(Te("wikiPageWithSummaryCount",400),Te("linkedWikiPageCount",300)),"Maintain 400 summarized pages and 300 linked pages.","You mapped the archive enough that it can map you back."),Ze("wiki","The Shelf Breathes",Te("knowledgeGraphNodeCount",1e3),"Reach 1,000 Knowledge Graph nodes.","The knowledge system feels alive at a glance."),Ze("wiki","Librarian of Coals",At(Te("noteCount",1e3),Te("wikiLinkCount",1e3)),"Create 1,000 notes and 1,000 wiki links.","A trophy for the long, quiet archive discipline."),Ze("wiki","Living Codex",At(Te("wikiPageCount",1500),Te("wikiPageWithSummaryCount",750),Te("wikiLinkCount",1500)),"Create 1,500 pages, 750 summarized pages, and 1,500 links.","The living memory crown."),Ze("wiki","Memory Starfield",Te("knowledgeGraphNodeCount",2e3),"Reach 2,000 Knowledge Graph nodes.","The graph becomes a sky.")],BE=[gt("wiki","Quiet Library Shelf","trophy_shelf",Te("wikiPageCount",150),"Create 150 wiki pages.","A quiet library shelf skin.",{trophyShelf:"quiet-library"}),gt("wiki","Rune Page Frame","icon_frame",Te("wikiLinkCount",150),"Create 150 wiki links.","A runic frame for knowledge trophies.",{iconFrame:"rune-page"}),gt("wiki","Scholar Glass HUD","hud_treatment",Te("wikiPageWithSummaryCount",100),"Maintain 100 summarized wiki pages.","A glassy scholar HUD treatment.",{hudTreatment:"scholar-glass"}),gt("wiki","Archive Sparks","celebration_variant",Te("linkedWikiPageCount",200),"Link 200 wiki pages to other pages or entities.","A page-flare reveal variant.",{celebrationVariant:"archive-sparks"}),gt("wiki","Astral Archive Shelf","trophy_shelf",Te("knowledgeGraphNodeCount",1e3),"Reach 1,000 Knowledge Graph nodes.","A cosmic trophy shelf for memory work.",{trophyShelf:"astral-archive"}),gt("wiki","Reading Smith Pose","mascot_pose",Te("wikiPageWithSummaryCount",250),"Maintain 250 summarized wiki pages.","Unlocks the Forge Smith reading pose.",{mascotPose:"reading"})],UE=[Ze("psyche","Named Spark",Te("psycheValueCount",5),"Create 5 Psyche values.","You named the values the forge should obey."),Ze("psyche","Pattern Tongs",Te("behaviorPatternCount",5),"Create 5 behavior patterns.","The recurring loops are now held with tongs."),Ze("psyche","Belief Crucible",Te("beliefEntryCount",5),"Create 5 belief entries.","Beliefs entered the fire where they can be worked."),Ze("psyche","Mode Lantern",Te("modeProfileCount",3),"Create 3 mode profiles.","The inner cast has names and lantern light."),Ze("psyche","Trigger Witness",Te("triggerReportCount",3),"Create 3 trigger reports.","You turned moments of activation into evidence."),Ze("psyche","Mode Cartographer",At(Te("modeProfileCount",8),Te("linkedModeProfileCount",8)),"Create 8 mode profiles, each linked to a value, behavior, or pattern.","A map of modes, not a pile of labels."),Ze("psyche","Trigger Alchemist",At(Te("triggerReportRichCount",30),Te("triggerReportCompletedCount",20)),"Complete 30 rich trigger reports and mark 20 reports beyond draft.","Activation was turned into material for change."),Ze("psyche","Pattern Breaker",At(Te("behaviorPatternCount",20),Te("behaviorPatternWithReplacementCount",10)),"Create 20 patterns and link 10 to replacement responses.","The old loops now have counter-moves."),Ze("psyche","Belief Temperer",At(Te("beliefEntryCount",25),Te("beliefFlexibleAlternativeCount",25)),"Create 25 beliefs with flexible alternatives.","Rigid beliefs were heated until they could bend."),Ze("psyche","Value Blade",At(Te("psycheValueCount",10),Te("goalLinkedTaskCompletionCount",100)),"Create 10 values and complete 100 goal-linked tasks.","Values and work started cutting in the same direction."),Ze("psyche","Shadow Temper",At(Te("modeProfileCount",12),Te("triggerReportRichCount",50)),"Create 12 modes and 50 rich trigger reports.","Shadow material became usable steel."),Ze("psyche","Inner Forge",At(Te("psycheValueCount",12),Te("behaviorPatternCount",25),Te("beliefFlexibleAlternativeCount",30)),"Create 12 values, 25 patterns, and 30 flexible beliefs.","A full inner forge takes shape."),Ze("psyche","Schema Bell",Te("questionnaireRunCount",40),"Complete 40 questionnaire runs.","Structured self-observation rang the bell repeatedly."),Ze("psyche","Mode Guide",Te("modeGuideSessionCount",5),"Complete 5 mode guide sessions.","Guided mode work became an actual practice."),Ze("psyche","Repair Script",Te("behaviorCount",10),"Create 10 Psyche behaviors.","Behaviors now carry repair plans, not just names."),Ze("psyche","Flexible Self",Te("beliefFlexibleAlternativeCount",50),"Create 50 beliefs with flexible alternatives.","A trophy for not letting old beliefs remain iron cages."),Ze("psyche","Trigger Cartography",Te("triggerReportRichCount",100),"Create 100 rich trigger reports.","The map of activation became detailed enough to steer by."),Ze("psyche","The Inner Council",At(Te("modeProfileCount",20),Te("behaviorCount",20),Te("beliefFlexibleAlternativeCount",75)),"Create 20 modes, 20 behaviors, and 75 flexible beliefs.","The inner system became a council instead of noise.")],WE=[gt("psyche","Scholar Smith","mascot_skin",Te("psycheValueCount",7),"Create 7 Psyche values.","A wise, bookish Forge Smith skin.",{mascotSkin:"scholar-smith"}),gt("psyche","Wise Smith Pose","mascot_pose",Te("modeProfileCount",3),"Create 3 mode profiles.","Unlocks the wise mentor pose.",{mascotPose:"wise"}),gt("psyche","Reflection Frame","icon_frame",Te("beliefEntryCount",10),"Create 10 belief entries.","A reflective frame for Psyche trophies.",{iconFrame:"reflection"}),gt("psyche","Mode Lens HUD","hud_treatment",Te("modeProfileCount",8),"Create 8 mode profiles.","A HUD tuned to Psyche work.",{hudTreatment:"mode-lens"}),gt("psyche","Shadow Smith","mascot_skin",Te("triggerReportRichCount",25),"Create 25 rich trigger reports.","A darker Smith skin for shadow work.",{mascotSkin:"shadow-smith"}),gt("psyche","Arcane Metallurgist","mascot_skin",Te("beliefFlexibleAlternativeCount",25),"Create 25 beliefs with flexible alternatives.","A rune-lit Smith skin for deep reflection.",{mascotSkin:"arcane-metallurgist"}),gt("psyche","Inner-Fire Halo","streak_effect",Te("psycheValueCount",10),"Create 10 Psyche values.","A halo-like flame for reflective momentum.",{streakEffect:"inner-fire-halo"}),gt("psyche","Mode Lantern Reveal","celebration_variant",Te("modeProfileCount",12),"Create 12 mode profiles.","A lantern reveal for Psyche unlocks.",{celebrationVariant:"mode-lantern"}),gt("psyche","Therapist's Shelf","trophy_shelf",Te("triggerReportRichCount",50),"Create 50 rich trigger reports.","A quiet shelf for inner-work trophies.",{trophyShelf:"therapist-shelf"}),gt("psyche","Prismatic Crucible","celebration_variant",Te("beliefFlexibleAlternativeCount",50),"Create 50 flexible belief alternatives.","A prismatic reveal for belief work.",{celebrationVariant:"prismatic-crucible"})],HE=[Ze("habits","Ritual Spark",Te("habitAlignedCount",25),"Record 25 aligned habit check-ins.","Your recurring commitments have started to leave marks."),Ze("habits","Routine Rivet",Te("habitAlignedCount",75),"Record 75 aligned habit check-ins.","The habit rail is no longer decorative."),Ze("habits","Habit Heat",At(Te("habitAlignedCount",150),Te("habitStreakMax",14)),"Record 150 aligned check-ins and a 14-day habit streak.","One behavior got hot enough to shape you."),Ze("habits","Ritual Iron",Te("habitAlignedCount",365),"Record 365 aligned habit check-ins.","The hard habit trophy."),Ze("habits","Recovery Shield",Te("recoveryEventCount",50),"Earn 50 recovery rewards.","Recovery was treated as part of the work."),Ze("habits","Life-Force Alloy",Te("lifeForceSnapshotCount",100),"Record 100 Life Force day snapshots.","Energy accounting became a usable alloy."),Ze("habits","Sleep Temper",Te("healthSleepSessionCount",120),"Import 120 sleep sessions.","Sleep became evidence, not a guess."),Ze("habits","Vitality Forge",At(Te("workoutSessionCount",100),Te("healthSleepSessionCount",200)),"Import 100 workouts and 200 sleep sessions.","Body data and execution entered the same forge.")],GE=[gt("habits","Recovery Blue Flame","streak_effect",Te("recoveryEventCount",20),"Earn 20 recovery rewards.","A cooler recovery flame.",{streakEffect:"recovery-blue"}),gt("habits","Ritual Check Glow","hud_treatment",Te("habitAlignedCount",75),"Record 75 aligned habit check-ins.","A habit-check glow for the HUD.",{hudTreatment:"ritual-check"}),gt("habits","Storm Forger","mascot_skin",Te("workoutSessionCount",50),"Import 50 workouts.","A storm-lit Smith skin for movement arcs.",{mascotSkin:"storm-forger"}),gt("habits","Clockwork Smith","mascot_skin",Te("habitAlignedCount",150),"Record 150 aligned habit check-ins.","A clockwork skin for ritual precision.",{mascotSkin:"clockwork-smith"}),gt("habits","Vital Flame","streak_effect",Te("healthSleepSessionCount",90),"Import 90 sleep sessions.","A vital-sign flame around streak indicators.",{streakEffect:"vital-flame"}),gt("habits","Life-Force Frame","icon_frame",Te("lifeForceSnapshotCount",100),"Record 100 Life Force snapshots.","An AP-inspired frame for body trophies.",{iconFrame:"life-force"}),gt("habits","Steady-State Aura","streak_effect",Te("habitStreakMax",60),"Reach a 60-day habit streak.","An aura for long stable rituals.",{streakEffect:"steady-state"}),gt("habits","Celestial Smith","mascot_skin",At(Te("workoutSessionCount",100),Te("healthSleepSessionCount",200)),"Import 100 workouts and 200 sleep sessions.","A celestial skin for body stewardship.",{mascotSkin:"celestial-smith"})],QE=[Ze("agents","Companion Spark",Te("agentActionCount",5),"Record 5 agent actions.","The first sign of a working human-agent council."),Ze("agents","Bot Bellows",Te("agentCompletedActionCount",20),"Complete 20 agent actions.","Agents are not just present; they are moving work."),Ze("agents","Council Spark",Te("collaborationRewardCount",50),"Earn 50 collaboration rewards.","The collaboration trophy for meaningful assisted work."),Ze("agents","Guild Forge",At(Te("agentCompletedActionCount",100),Te("collaborationRewardCount",100)),"Complete 100 agent actions and earn 100 collaboration rewards.","The Forge has become a small guild.")],VE=[gt("agents","Guild Badge Frame","icon_frame",Te("agentCompletedActionCount",20),"Complete 20 agent actions.","A guild frame for agent trophies.",{iconFrame:"guild-badge"}),gt("agents","Council Sparks Reveal","celebration_variant",Te("collaborationRewardCount",50),"Earn 50 collaboration rewards.","A council-sparks reveal for collaboration.",{celebrationVariant:"council-sparks"})],XE=[..._E,...FE,...RE,...DE,...$E,...OE,...zE,...KE,...qE,...BE,...UE,...WE,...HE,...GE,...QE,...VE];function YE(){let t=0,s=0,a=0;const i=new Map;return XE.map(r=>{const n=Eh.find(p=>p.id===r.category);if(!n)throw new Error(`Unknown gamification category ${r.category}`);const l=i.get(r.category)??{trophy:0,unlock:0},o=l[r.kind];l[r.kind]+=1,i.set(r.category,l);const d=r.kind==="trophy"?n.trophyCount:n.unlockCount,m=AE(o,d),h=`${r.kind}-${wd(r.category)}-${wd(r.title)}`,c=r.kind==="trophy"?s++:a++;return{id:h,kind:r.kind,category:r.category,tier:m,difficulty:ME(m),hidden:r.hidden??!1,title:r.title,summary:r.summary,requirement:r.requirement,requirementText:r.requirementText,reward:r.reward,unlockType:r.kind==="unlock"?r.unlockType??"icon_frame":null,rewardPayload:r.kind==="unlock"?r.rewardPayload??{}:{trophyId:h},assetKey:LE(r),sheetKey:`${r.kind==="trophy"?"trophies":"unlocks"}-r${Math.floor(c/10)+1}-c${c%10+1}`,rarity:EE(m),sortOrder:t++}})}const Ba=YE();function JE(){if(Ba.length!==144)throw new Error(`GAMIFICATION_CATALOG must contain exactly 144 items; found ${Ba.length}.`);const t=Ba.filter(i=>i.kind==="trophy").length,s=Ba.filter(i=>i.kind==="unlock").length;if(t!==96||s!==48)throw new Error(`GAMIFICATION_CATALOG must contain 96 trophies and 48 unlocks; found ${t}/${s}.`);for(const i of Eh){const r=Ba.filter(l=>l.category===i.id&&l.kind==="trophy").length,n=Ba.filter(l=>l.category===i.id&&l.kind==="unlock").length;if(r!==i.trophyCount||n!==i.unlockCount)throw new Error(`${i.id} expected ${i.trophyCount}/${i.unlockCount}, found ${r}/${n}.`)}if(new Set(Ba.map(i=>i.assetKey)).size!==Ba.length)throw new Error("Every trophy and unlock must have a unique asset key.")}JE();const Vg=Eh.map(t=>({id:t.id,label:t.label})),ZE=Array.from({length:30},(t,s)=>`mascot-state-${String(s+1).padStart(3,"0")}`),eL=TE.map((t,s)=>[t,`mascot-state-${String(17+s).padStart(3,"0")}`]),tL=PE.map((t,s)=>[t,`mascot-state-${String(10-s).padStart(3,"0")}`]),em=ZE;if(em.length!==30)throw new Error(`GAMIFICATION_MASCOT_KEYS must contain exactly 30 mascot/state keys; found ${em.length}.`);function sL(t){switch(t.category){case"xp_levels":return"#f59e0b";case"streaks":return"#fb923c";case"tasks":return"#f97316";case"projects":return"#38bdf8";case"wiki":return"#a78bfa";case"psyche":return"#8b5cf6";case"habits":return"#4ade80";case"agents":return"#22d3ee";default:return"#f59e0b"}}function aL(t){return["cinematic stylized blacksmith game icon",t.category.replace(/_/g," "),t.kind,t.title,"obsidian iron, ember gold, cool violet and cyan steel highlights, no text"].join(", ")}const iL=Object.fromEntries(Ba.map(t=>[t.assetKey,{key:t.assetKey,role:"item",itemKind:t.kind,alt:`${t.title} ${t.kind} icon.`,dominantColor:sL(t),tierFrame:t.tier,sourcePath:`gamification/source/themes/dark-fantasy/items/${t.assetKey}.png`,spritePath:`gamification/sprites/themes/dark-fantasy/items/${t.assetKey}-{size}.webp`,sheetKey:t.sheetKey,prompt:aL(t)}])),rL=Object.fromEntries(em.map(t=>{const s=Number(t.replace("mascot-state-","")),a=s<=10,i=s>=17;return[t,{key:t,role:i||a?"streak":"mascot",alt:a?"The Forge Smith in a safe cold-forge absence state.":"The Forge Smith mascot in a dramatic blacksmith game-art pose.",dominantColor:a?"#64748b":i?"#fb923c":"#38bdf8",tierFrame:"none",sourcePath:`gamification/source/themes/dark-fantasy/mascots/${t}.png`,spritePath:`gamification/sprites/themes/dark-fantasy/mascots/${t}-{size}.webp`,sheetKey:null,prompt:"dramatic Forge Smith blacksmith mascot, premium game art, no text, no watermark"}]}));({...iL,...rL});function Ki(t){t.currentTarget.hidden=!0}const nL=["all","bronze","silver","gold","platinum"],lL=[{id:"trophies",label:"Trophies"},{id:"unlocks",label:"Unlocks"},{id:"armory",label:"Mascot Armory"},{id:"streak",label:"Streak Forge"}],tm={mascot_skin:{field:"selectedMascotSkin",payloadKey:"mascotSkin",label:"Mascot skin"},hud_treatment:{field:"selectedHudTreatment",payloadKey:"hudTreatment",label:"HUD treatment"},streak_effect:{field:"selectedStreakEffect",payloadKey:"streakEffect",label:"Streak flame"},trophy_shelf:{field:"selectedTrophyShelf",payloadKey:"trophyShelf",label:"Trophy shelf"},celebration_variant:{field:"selectedCelebrationVariant",payloadKey:"celebrationVariant",label:"Celebration"}};function Av(t){switch(t){case"platinum":return"border-cyan-200/35 text-cyan-100";case"gold":return"border-amber-200/35 text-amber-100";case"silver":return"border-slate-200/35 text-slate-100";default:return"border-orange-300/35 text-orange-100"}}function oL(t){const s=t.unlockType?tm[t.unlockType]:null,a=s?t.rewardPayload[s.payloadKey]:null;return typeof a=="string"?a:null}function dL({item:t,gamificationTheme:s,onSelect:a}){return e.jsxs("button",{type:"button",onClick:()=>a(t),className:te("group relative min-h-[19rem] overflow-hidden rounded-[18px] border border-white/8 bg-white/[0.045] p-4 text-left transition hover:-translate-y-0.5 hover:border-white/16 hover:bg-white/[0.07]",!t.unlocked&&"opacity-78"),children:[e.jsx("div",{className:"absolute inset-0 -z-10 bg-[radial-gradient(circle_at_50%_0%,rgba(249,115,22,0.16),transparent_38%)]"}),e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx(S,{className:te("border bg-black/18",Av(t.tier)),children:t.tier}),e.jsx(S,{className:"bg-white/[0.06] text-white/58",children:t.unlocked?"earned":"locked"})]}),e.jsx("div",{className:"mt-3 grid place-items-center",children:e.jsx("img",{src:ja(t.assetKey,512,s),alt:"",onError:Ki,className:te("size-36 object-contain drop-shadow-[0_22px_34px_rgba(0,0,0,0.44)] transition group-hover:scale-[1.03]",!t.unlocked&&"grayscale")})}),e.jsxs("div",{className:"mt-3 min-w-0",children:[e.jsx("div",{className:"font-display text-lg text-white",children:t.title}),e.jsx("p",{className:"mt-2 line-clamp-2 text-sm leading-6 text-white/58",children:t.unlocked?t.summary:t.requirementText})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Gs,{value:t.progressPercent}),e.jsxs("div",{className:"mt-2 flex justify-between gap-3 text-[11px] uppercase tracking-[0.16em] text-white/38",children:[e.jsxs("span",{children:[t.progressCurrent,"/",t.progressTarget]}),e.jsxs("span",{children:[t.progressPercent,"%"]})]})]})]})}function cL(){var j,R,v,D;const t=Ct(),s=Bm(),a=pt(),i=gr(),r=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[n,l]=u.useState("trophies"),[o,d]=u.useState("all"),[m,h]=u.useState("all"),[c,p]=u.useState("all"),[g,x]=u.useState(""),[f,b]=u.useState(null),A=Me({queryKey:["forge-gamification-catalog",...r],queryFn:()=>P2(r)}),T=Vm(r),I=De({mutationFn:L=>A2(L,r),onSuccess:async()=>{await Promise.all([a.invalidateQueries({queryKey:["forge-gamification-catalog"]}),a.invalidateQueries({queryKey:["forge-xp-metrics"]})]),i(Ja.util.invalidateTags(["Gamification"]))}}),y=(j=A.data)==null?void 0:j.catalog,N=(y==null?void 0:y.items)??[],k=u.useMemo(()=>{const L=g.trim().toLowerCase();return N.filter(Q=>n==="trophies"&&Q.kind!=="trophy"||n==="unlocks"&&Q.kind!=="unlock"||(n==="armory"||n==="streak")&&Q.kind!=="unlock"||n==="armory"&&!Q.unlockType||n==="streak"&&Q.unlockType!=="streak_effect"||o!=="all"&&Q.category!==o||m!=="all"&&Q.tier!==m||c==="unlocked"&&!Q.unlocked||c==="locked"&&Q.unlocked?!1:L?`${Q.title} ${Q.summary} ${Q.requirementText} ${Q.reward}`.toLowerCase().includes(L):!0)},[o,N,g,c,n,m]),w=(y==null?void 0:y.equipment)??((R=T.data)==null?void 0:R.metrics.equipment)??null,P=N.filter(L=>L.kind==="unlock"&&L.unlockType&&tm[L.unlockType]);return A.isError?e.jsx(ct,{eyebrow:"Rewards",error:A.error,onRetry:()=>void A.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1320px] gap-5",children:[e.jsx(mt,{title:"Trophy Hall",description:"Achievements are earned from real Forge behavior: tasks, runs, goals, wiki links, Psyche work, habits, Life Force, health, and collaboration.",badge:y?`${y.unlockedCount}/${y.totalCount} earned`:"Loading",actions:(v=T.data)!=null&&v.metrics?e.jsx(Mi,{metrics:T.data.metrics.profile}):null}),e.jsxs("section",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(20rem,0.42fr)]",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.045] p-4",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:lL.map(L=>e.jsxs(H,{type:"button",variant:n===L.id?"primary":"secondary",size:"sm",onClick:()=>l(L.id),children:[L.id==="trophies"?e.jsx(ll,{className:"size-4"}):null,L.id==="armory"?e.jsx(Tj,{className:"size-4"}):null,L.id==="streak"?e.jsx(nl,{className:"size-4"}):null,L.id==="unlocks"?e.jsx(Ut,{className:"size-4"}):null,L.label]},L.id))}),e.jsxs("div",{className:"mt-4 flex min-w-0 flex-wrap items-center gap-2",children:[["all","unlocked","locked"].map(L=>e.jsxs(H,{type:"button",variant:c===L?"primary":"secondary",size:"sm",onClick:()=>p(L),children:[L==="locked"?e.jsx(rp,{className:"size-4"}):null,L]},L)),e.jsxs("label",{className:"ml-auto flex min-h-10 min-w-[16rem] max-w-full items-center gap-2 rounded-full border border-white/8 bg-black/18 px-3 text-sm text-white/70",children:[e.jsx(Bt,{className:"size-4 shrink-0 text-white/38"}),e.jsx("input",{value:g,onChange:L=>x(L.target.value),placeholder:"Search rewards",className:"min-w-0 flex-1 bg-transparent text-white outline-none placeholder:text-white/34"})]})]}),e.jsxs("div",{className:"mt-4 flex min-w-0 flex-wrap gap-2",children:[e.jsx(H,{type:"button",variant:o==="all"?"primary":"secondary",size:"sm",onClick:()=>d("all"),children:"all categories"}),Vg.map(L=>e.jsx(H,{type:"button",variant:o===L.id?"primary":"secondary",size:"sm",onClick:()=>d(L.id),children:L.label},L.id))]}),e.jsx("div",{className:"mt-4 flex min-w-0 flex-wrap gap-2",children:nL.map(L=>e.jsx(H,{type:"button",variant:m===L?"primary":"secondary",size:"sm",onClick:()=>h(L),children:L},L))})]}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] border border-white/8 bg-black/18 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-white",children:[e.jsx(Ut,{className:"size-4 text-[var(--tertiary)]"}),"Near completion"]}),((y==null?void 0:y.nextTargets)??[]).map(L=>e.jsxs("button",{type:"button",onClick:()=>b(L),className:"grid grid-cols-[2.75rem_minmax(0,1fr)_3rem] items-center gap-3 rounded-2xl bg-white/[0.045] p-2 text-left",children:[e.jsx("img",{src:ja(L.assetKey,256,s),alt:"",onError:Ki,className:"size-11 object-contain"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm text-white/82",children:L.title}),e.jsx("span",{className:"block truncate text-[11px] text-white/42",children:L.requirementText})]}),e.jsxs("span",{className:"text-right text-xs text-white/50",children:[L.progressPercent,"%"]})]},L.id))]})]}),n==="armory"?e.jsxs("section",{className:"grid gap-3 lg:grid-cols-[minmax(18rem,0.42fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative min-h-[24rem] overflow-hidden rounded-[24px] border border-white/8 bg-[linear-gradient(145deg,rgba(15,23,42,0.92),rgba(24,24,36,0.88))] p-4",children:[e.jsx("img",{src:ja(((D=T.data)==null?void 0:D.metrics.mascot.spriteKey)??"mascot-state-014",512,s),alt:"Forge Smith mascot",onError:Ki,className:"absolute inset-x-0 bottom-0 mx-auto h-[23rem] object-contain"}),e.jsxs("div",{className:"relative z-10",children:[e.jsx(S,{className:"bg-black/30 text-[var(--tertiary)]",children:"Equipped"}),e.jsxs("div",{className:"mt-3 grid gap-1 text-sm text-white/68",children:[e.jsxs("span",{children:["Skin: ",(w==null?void 0:w.selectedMascotSkin)??"default"]}),e.jsxs("span",{children:["HUD: ",(w==null?void 0:w.selectedHudTreatment)??"default"]}),e.jsxs("span",{children:["Flame: ",(w==null?void 0:w.selectedStreakEffect)??"default"]}),e.jsxs("span",{children:["Shelf: ",(w==null?void 0:w.selectedTrophyShelf)??"default"]})]})]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:P.map(L=>{const Q=L.unlockType?tm[L.unlockType]:null,Z=oL(L),V=!!(Q&&Z&&(w==null?void 0:w[Q.field])===Z);return e.jsxs(le,{className:te("p-4",!L.unlocked&&"opacity-70"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx(S,{className:"bg-white/[0.06] text-white/58",children:(Q==null?void 0:Q.label)??"Cosmetic"}),V?e.jsx(Ia,{className:"size-4 text-emerald-200"}):null]}),e.jsx("img",{src:ja(L.assetKey,256,s),alt:"",onError:Ki,className:te("mx-auto mt-3 size-28 object-contain",!L.unlocked&&"grayscale")}),e.jsx("div",{className:"mt-3 font-display text-lg text-white",children:L.title}),e.jsx("p",{className:"mt-2 line-clamp-2 text-sm leading-6 text-white/56",children:L.unlocked?L.summary:L.requirementText}),e.jsx(H,{type:"button",variant:V?"secondary":"primary",size:"sm",disabled:!L.unlocked||!Q||!Z||I.isPending,className:"mt-4 w-full",onClick:()=>{!Q||!Z||I.mutate({[Q.field]:V?null:Z})},children:V?"Unequip":L.unlocked?"Equip":"Locked"})]},L.id)})})]}):n==="streak"?e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 font-display text-xl text-white",children:[e.jsx(nl,{className:"size-5 text-[var(--tertiary)]"}),"Streak power states"]}),e.jsx("div",{className:"mt-4 grid gap-3 sm:grid-cols-2 md:grid-cols-4 xl:grid-cols-5",children:eL.map(([L,Q])=>e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("img",{src:ja(Q,256,s),alt:"",onError:Ki,className:"mx-auto size-28 object-contain"}),e.jsxs("div",{className:"mt-2 text-center text-sm text-white/74",children:[L," day power"]})]},Q))})]}),e.jsxs(le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 font-display text-xl text-white",children:[e.jsx(rp,{className:"size-5 text-slate-300"}),"Absence pressure states"]}),e.jsx("div",{className:"mt-4 grid gap-3 sm:grid-cols-2 md:grid-cols-4 xl:grid-cols-5",children:tL.map(([L,Q])=>e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("img",{src:ja(Q,256,s),alt:"",onError:Ki,className:"mx-auto size-28 object-contain"}),e.jsxs("div",{className:"mt-2 text-center text-sm text-white/74",children:[L," days away"]})]},Q))})]})]}):e.jsx("section",{className:"grid gap-5",children:Vg.map(L=>{const Q=k.filter(Z=>Z.category===L.id);return Q.length===0?null:e.jsxs("section",{className:"grid gap-3",children:[e.jsx("div",{className:"flex items-end justify-between gap-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-xl text-white",children:L.label}),e.jsxs("div",{className:"text-sm text-white/44",children:[Q.length," visible rewards"]})]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:Q.map(Z=>e.jsx(dL,{item:Z,gamificationTheme:s,onSelect:b},Z.id))})]},L.id)})}),f?e.jsx("div",{className:"fixed inset-0 z-50 grid place-items-center bg-black/72 p-4 backdrop-blur-sm",onClick:()=>b(null),children:e.jsxs("div",{className:"w-full max-w-[34rem] rounded-[26px] border border-white/10 bg-[rgb(12,17,30)] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.6)]",onClick:L=>L.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("img",{src:ja(f.assetKey,512,s),alt:"",onError:Ki,className:"size-32 object-contain"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{className:te("border bg-black/18",Av(f.tier)),children:f.tier}),e.jsx(S,{className:"bg-white/[0.06] text-white/58",children:f.kind})]}),e.jsx("div",{className:"mt-3 font-display text-2xl text-white",children:f.title}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/62",children:f.summary})]})]}),e.jsxs("div",{className:"mt-5 rounded-[18px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:"Requirement"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:f.requirementText}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Gs,{value:f.progressPercent}),e.jsxs("div",{className:"mt-2 flex justify-between text-[11px] uppercase tracking-[0.16em] text-white/40",children:[e.jsxs("span",{children:[f.progressCurrent,"/",f.progressTarget]}),e.jsx("span",{children:f.unlocked?"earned":"locked"})]})]})]}),e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx(H,{type:"button",variant:"secondary",onClick:()=>b(null),children:"Close"})})]})}):null]})}function qa(t,s,a,i){return{value:t,label:s,description:a,searchText:`${s} ${a}`,kind:i}}function Mv(t){const s=t.goals??[],a=t.projects??[],i=t.tasks??[],r=t.habits??[],n=t.values??[],l=t.patterns??[],o=t.behaviors??[],d=t.beliefs??[],m=t.reports??[];return[...s.map(h=>qa(`goal:${h.id}`,h.title,"Goal","goal")),...a.map(h=>qa(`project:${h.id}`,h.title,"Project","project")),...i.map(h=>qa(`task:${h.id}`,h.title,"Task","task")),...r.map(h=>qa(`habit:${h.id}`,h.title,"Habit","habit")),...n.map(h=>qa(`psyche_value:${h.id}`,h.title,"Value","value")),...l.map(h=>qa(`behavior_pattern:${h.id}`,h.title,"Pattern","pattern")),...o.map(h=>qa(`behavior:${h.id}`,h.title,"Behavior","behavior")),...d.map(h=>qa(`belief_entry:${h.id}`,h.statement,"Belief","belief")),...m.map(h=>qa(`trigger_report:${h.id}`,h.title,"Report","report"))]}function Ev(t){return t.map(s=>{const a=s.indexOf(":");if(a===-1)return null;const i=s.slice(0,a),r=s.slice(a+1);return!i||!r?null:{entityType:i,entityId:r,relationshipType:"context"}}).filter(s=>s!==null)}const uL=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Xg={awake:{label:"Awake",strong:"rgba(251, 191, 36, 0.95)",soft:"rgba(251, 191, 36, 0.16)",text:"text-amber-200"},core:{label:"Core",strong:"rgba(165, 180, 252, 0.96)",soft:"rgba(165, 180, 252, 0.18)",text:"text-indigo-100"},deep:{label:"Deep",strong:"rgba(45, 212, 191, 0.96)",soft:"rgba(45, 212, 191, 0.18)",text:"text-teal-100"},rem:{label:"REM",strong:"rgba(96, 165, 250, 0.96)",soft:"rgba(96, 165, 250, 0.18)",text:"text-sky-100"},in_bed:{label:"In bed",strong:"rgba(255, 255, 255, 0.4)",soft:"rgba(255, 255, 255, 0.1)",text:"text-white/72"},asleep_unspecified:{label:"Asleep",strong:"rgba(196, 181, 253, 0.96)",soft:"rgba(196, 181, 253, 0.16)",text:"text-violet-100"}};function jl(t){return Xg[t]??Xg.asleep_unspecified}function zs(t){if(t<=0)return"0m";const s=Math.floor(t/3600),a=Math.round(t%3600/60);return s===0?`${a}m`:a===0?`${s}h`:`${s}h ${a}m`}function mL(t){const s=Math.round(t/60);return s===0?"on baseline":`${s>0?"+":"-"}${Math.abs(s)}m`}function xn(t){return`${Math.round(t*100)}%`}function Vr(t,s){return t?new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",timeZone:s}).format(new Date(t)):"n/a"}function Lv(t,s){return new Intl.DateTimeFormat(void 0,{weekday:"long",day:"numeric",month:"long",timeZone:s}).format(new Date(t))}function Wo(t,s,a){return`${Vr(t,a)} - ${Vr(s,a)}`}function hL(t){const[s,a]=t.split("-").map(Number);return new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(s,(a??1)-1,1))}function _v(t){const s=new Date(t),a=(t.getDay()+6)%7;return s.setDate(t.getDate()-a),s}function pL(t){const s=_v(t);return s.setDate(s.getDate()+6),s}function xL(t){const s=t.getFullYear(),a=`${t.getMonth()+1}`.padStart(2,"0"),i=`${t.getDate()}`.padStart(2,"0");return`${s}-${a}-${i}`}function Po(t){return{qualitySummary:typeof t.annotations.qualitySummary=="string"?t.annotations.qualitySummary:"",notes:typeof t.annotations.notes=="string"?t.annotations.notes:"",tagsText:Array.isArray(t.annotations.tags)?t.annotations.tags.join(", "):"",linkValues:Array.isArray(t.links)?t.links.map(s=>`${s.entityType}:${s.entityId}`):[]}}function gL(t,s){if(!t)return[];const[a,i]=t.split("-").map(Number),r=new Date(a,(i??1)-1,1),n=new Date(a,i??1,0),l=_v(r),o=pL(n),d=new Map(s.map(h=>[h.dateKey,h])),m=[];for(const h=new Date(l);h<=o;h.setDate(h.getDate()+1)){const c=xL(h);m.push({dateKey:c,dayNumber:h.getDate(),outsideMonth:h.getMonth()!==r.getMonth(),sleep:d.get(c)??null})}return m}function fL(t){return t>0?"text-emerald-200":t<0?"text-rose-200":"text-white/70"}function Fv(t){return t==="recharged"||t==="recovered"?"bg-emerald-400/16 text-emerald-100":t==="steady"||t==="stable"?"bg-sky-400/16 text-sky-100":t==="fragile"||t==="strained"?"bg-amber-400/16 text-amber-100":t==="depleted"?"bg-rose-400/16 text-rose-100":"bg-white/10 text-white/76"}function bL(t){return t==="provider_raw"?"bg-emerald-400/16 text-emerald-100":t==="historical_raw"?"bg-amber-400/16 text-amber-100":"bg-white/10 text-white/70"}function yL(t){return t==="provider_raw"?"Provider raw data":t==="historical_raw"?"Historical raw data":"Raw data unavailable"}function wL(t){return t.qualityKind==="provider_native"?"bg-emerald-400/16 text-emerald-100":"bg-amber-400/16 text-amber-100"}function vL(t,s){const a=t.stage;if(typeof a=="string"&&a.trim().length>0)return a;const i=t.sourceType;if(typeof i=="string"&&i.trim().length>0)return i;const r=t.stageBreakdown;if(Array.isArray(r)&&r.length>0){const n=r[0];if(n&&typeof n=="object"&&typeof n.stage=="string")return(n.stage||"asleep_unspecified").trim()}return s.includes("awake")?"awake":"asleep_unspecified"}function jL(t){const s=t,a=(s==null?void 0:s.segments)??(s==null?void 0:s.rawSegments)??[],i=(s==null?void 0:s.auditLogs)??(s==null?void 0:s.rawLogs)??[],r=s!=null&&s.sourceRecords&&s.sourceRecords.length>0?s.sourceRecords:i.filter(l=>typeof l.startedAt=="string"&&typeof l.endedAt=="string").map(l=>({id:l.id,importRunId:l.importRunId,pairingSessionId:l.pairingSessionId,sleepSessionId:l.sleepSessionId,userId:l.userId,provider:l.source,providerRecordType:l.logType,providerRecordUid:l.externalUid??l.id,sourceDevice:"",sourceTimezone:l.sourceTimezone,localDateKey:l.localDateKey,startedAt:l.startedAt,endedAt:l.endedAt,rawStage:vL(l.payload,l.logType),rawValue:null,qualityKind:"historical_import",payload:l.payload,metadata:l.metadata,ingestedAt:l.createdAt})),n=(s==null?void 0:s.rawDataStatus)??(r.length>0?"historical_raw":"raw_unavailable");return{sourceRecords:r,segments:a,auditLogs:i,rawDataStatus:n}}function Rv({stages:t}){const s=t.reduce((a,i)=>a+i.seconds,0);return t.length===0||s===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No stage composition was stored for this night yet."}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"flex h-3 overflow-hidden rounded-full bg-white/[0.08]",children:t.map(a=>{const i=jl(a.stage);return e.jsx("div",{className:"h-full",style:{width:`${Math.max(4,a.seconds/s*100)}%`,background:i.strong},title:`${i.label} · ${zs(a.seconds)}`},a.stage)})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-4",children:t.map(a=>{const i=jl(a.stage),r="percentage"in a&&typeof a.percentage=="number"?a.percentage:s>0?a.seconds/s:0;return e.jsxs("div",{className:"rounded-[16px] border border-white/8 px-3 py-3",style:{background:i.soft},children:[e.jsx("div",{className:te("text-sm font-medium",i.text),children:i.label}),e.jsx("div",{className:"mt-1 text-lg text-white",children:zs(a.seconds)}),e.jsx("div",{className:"text-xs text-white/54",children:xn(r)})]},a.stage)})})]})}function Yg({blocks:t,selectedBlockId:s,onSelect:a}){return e.jsxs("div",{className:"relative h-12 overflow-hidden rounded-[18px] border border-white/8 bg-black/20",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(255,255,255,0.06)_1px,transparent_1px)] bg-[length:25%_100%]"}),t.map(i=>{const r=jl(i.stage),n=s===i.id;return e.jsx("button",{type:"button",onClick:()=>a(i.id),className:te("absolute inset-y-[5px] rounded-[12px] border transition",n?"border-white/60 shadow-[0_0_0_1px_rgba(255,255,255,0.18)]":"border-white/10"),style:{left:`${i.offsetRatio*100}%`,width:`${Math.max(i.widthRatio*100,1.8)}%`,background:r.strong},title:`${i.label} · ${zs(i.durationSeconds)} · ${i.startedAt} - ${i.endedAt}`,children:i.widthRatio>.13?e.jsx("span",{className:"truncate px-2 text-[10px] font-medium text-slate-950/85",children:i.label}):null},i.id)})]})}function kL({timeline:t,timeZone:s}){var d,m;const a=t.blocks.filter(h=>h.lane==="in_bed"),i=t.blocks.filter(h=>h.lane==="sleep"),r=((d=i[0])==null?void 0:d.id)??((m=a[0])==null?void 0:m.id)??null,[n,l]=u.useState(r);u.useEffect(()=>{l(r)},[r,t.startedAt,t.endedAt,t.totalSeconds]);const o=t.blocks.find(h=>h.id===n)??null;return t.hasRawSegments?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[a.length>0?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed window"}),e.jsx(Yg,{blocks:a,selectedBlockId:n,onSelect:l})]}):null,e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:t.hasSleepStageData?"Sleep phases":"Recorded sleep coverage"}),e.jsx(Yg,{blocks:i.length>0?i:a,selectedBlockId:n,onSelect:l})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-white/48",children:[e.jsx("span",{children:Vr(t.startedAt,s)}),e.jsx("span",{children:zs(t.totalSeconds)}),e.jsx("span",{children:Vr(t.endedAt,s)})]}),o?e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:te("text-sm font-medium",jl(o.stage).text),children:o.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[Vr(o.startedAt,s)," -"," ",Vr(o.endedAt,s)]})]}),e.jsx(S,{tone:"meta",children:zs(o.durationSeconds)})]})}):null]}):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-black/10 px-4 py-5 text-sm text-white/56",children:"Phase timing is unavailable for this night. Forge still keeps the canonical overnight summary, but the companion did not store segment-level timing."})}function NL({latestNight:t}){return t?e.jsx(le,{className:"overflow-hidden border-white/8 bg-[linear-gradient(135deg,rgba(7,17,40,0.96),rgba(16,24,54,0.94))] p-0",children:e.jsxs("div",{className:"relative overflow-hidden px-6 py-6 sm:px-7 sm:py-7",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(96,165,250,0.22),transparent_36%),radial-gradient(circle_at_bottom_left,rgba(45,212,191,0.14),transparent_34%)]"}),e.jsxs("div",{className:"relative grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(S,{className:te("border-white/0",Fv(t.recoveryState)),children:t.qualitativeState}),e.jsx(S,{tone:"meta",children:t.sourceTimezone}),t.hasReflection?e.jsx(S,{tone:"meta",children:"Has reflection"}):null,t.hasRawSegments?e.jsxs(S,{tone:"meta",children:[t.rawSegmentCount," raw segments"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Last night"}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end gap-x-4 gap-y-2",children:[e.jsx("div",{className:"text-[clamp(2.5rem,6vw,5rem)] font-medium leading-none text-white",children:zs(t.asleepSeconds)}),e.jsxs("div",{className:"pb-2 text-sm text-white/58",children:["asleep across ",Wo(t.startedAt,t.endedAt,t.sourceTimezone)]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/64",children:Lv(t.endedAt,t.sourceTimezone)}),t.qualitySummary?e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-white/72",children:t.qualitySummary}):e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-white/56",children:"Canonical overnight summary computed from synced sleep segments, with raw evidence still available underneath."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:zs(t.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Score"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:t.score??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Regularity"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:t.regularity??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:xn(t.efficiency)})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/20 px-5 py-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Baseline"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Compared with recent nights"})]}),e.jsx(ym,{className:"size-5 text-[var(--primary)]"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"7-night average"}),e.jsx("span",{className:"text-sm text-white",children:zs(t.weeklyAverageSleepSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Versus baseline"}),e.jsx("span",{className:te("text-sm",fL(t.deltaFromWeeklyAverageSeconds)),children:mL(t.deltaFromWeeklyAverageSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Bedtime drift"}),e.jsxs("span",{className:"text-sm text-white",children:[t.bedtimeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Wake drift"}),e.jsxs("span",{className:"text-sm text-white",children:[t.wakeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Restorative share"}),e.jsx("span",{className:"text-sm text-white",children:xn(t.restorativeShare)})]})]})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/20 px-5 py-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(Rv,{stages:t.stageBreakdown})})]})]})]})]})}):e.jsxs(le,{className:"overflow-hidden p-6",children:[e.jsx("div",{className:"text-sm uppercase tracking-[0.18em] text-white/42",children:"Sleep"}),e.jsx("div",{className:"mt-4 text-2xl text-white",children:"No overnight sleep yet"}),e.jsx("div",{className:"mt-3 max-w-2xl text-sm leading-6 text-white/58",children:"The sleep page will switch to a night-first summary once the companion syncs a canonical overnight session."})]})}function ru({title:t,value:s,description:a}){return e.jsxs(le,{className:"h-full border-white/8 bg-white/[0.03]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsx("div",{className:"mt-3 text-3xl text-white",children:s}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/56",children:a})]})}function SL({days:t,selectedSleepId:s,onSelect:a}){const i=u.useMemo(()=>Array.from(new Set(t.map(d=>d.dateKey.slice(0,7)))).sort((d,m)=>d.localeCompare(m)),[t]),[r,n]=u.useState(i[i.length-1]??"");u.useEffect(()=>{if(i.length===0){n("");return}i.includes(r)||n(i[i.length-1]??"")},[r,i]);const l=i.indexOf(r),o=u.useMemo(()=>gL(r,t),[t,r]);return r?e.jsx(le,{className:"overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(10,17,33,0.98),rgba(12,20,40,0.96))] p-0",children:e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sleep calendar"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:hL(r)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:l<=0,onClick:()=>n(i[Math.max(0,l-1)]??r),children:"Previous"}),e.jsx(H,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:l===-1||l>=i.length-1,onClick:()=>n(i[Math.min(i.length-1,l+1)]??r),children:"Next"})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-2 text-center text-[11px] uppercase tracking-[0.16em] text-white/38",children:uL.map(d=>e.jsx("div",{children:d},d))}),e.jsx("div",{className:"grid grid-cols-7 gap-2",children:o.map(d=>{const m=d.sleep,h=(m==null?void 0:m.sleepId)===s,c=m&&typeof m.score=="number"?m.score>=80?"rgba(45,212,191,0.22)":m.score>=65?"rgba(96,165,250,0.22)":"rgba(251,191,36,0.18)":"rgba(255,255,255,0.04)";return e.jsxs("button",{type:"button",disabled:!m,"aria-pressed":h,"aria-label":`Select sleep for ${d.dateKey}`,onClick:()=>{m&&(n(m.dateKey.slice(0,7)),a(m.sleepId,m.dateKey.slice(0,7)))},className:te("min-h-[90px] rounded-[18px] border px-2 py-2 text-left transition",m?"border-white/10 hover:border-white/22 hover:bg-white/[0.05]":"border-white/6 bg-white/[0.02]",h&&"border-[var(--primary)] bg-[var(--primary)]/12",d.outsideMonth&&!m&&"opacity-35"),style:m?{background:`linear-gradient(180deg, ${c}, rgba(255,255,255,0.03))`}:void 0,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:te("text-sm",d.outsideMonth?"text-white/40":"text-white/82"),children:d.dayNumber}),m!=null&&m.hasReflection?e.jsx("span",{className:"size-2 rounded-full bg-emerald-300"}):null]}),m?e.jsxs("div",{className:"mt-4 grid gap-1",children:[e.jsxs("div",{className:"text-lg text-white",children:[m.sleepHours.toFixed(1),"h"]}),e.jsxs("div",{className:"text-xs text-white/52",children:[m.score??"n/a"," score"]}),e.jsx("div",{className:"text-xs text-white/40",children:m.hasRawSegments?"phases available":"summary only"})]}):null]},d.dateKey)})})]})}):e.jsx(le,{className:"border-white/8 bg-white/[0.03] px-5 py-8 text-sm leading-6 text-white/56",children:"No canonical nights are available for the calendar yet."})}function nu({active:t,children:s,onClick:a}){return e.jsx("button",{type:"button",onClick:a,className:te("rounded-full border px-4 py-2 text-sm transition",t?"border-[var(--primary)] bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.03] text-white/60 hover:text-white"),children:s})}function CL({session:t,draft:s,rawDetail:a,rawDetailLoading:i,pending:r,tab:n,linkOptions:l,onTabChange:o,onDraftChange:d,onSave:m}){const[h,c]=u.useState(null),p=u.useMemo(()=>jL(a),[a]),g=typeof t.derived.efficiency=="number"?t.derived.efficiency:t.timeInBedSeconds>0?t.asleepSeconds/t.timeInBedSeconds:0,x=typeof t.derived.restorativeShare=="number"?t.derived.restorativeShare:0,f=typeof t.derived.recoveryState=="string"?t.derived.recoveryState:null;return e.jsx(le,{className:"overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(10,17,33,0.98),rgba(13,20,38,0.96))] p-0",children:e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{className:te("border-white/0",Fv(f)),children:f?f.replaceAll("_"," "):"Canonical night"}),e.jsxs(S,{tone:"meta",children:[t.rawSegmentCount," raw segments"]}),e.jsx(S,{tone:"meta",children:t.sourceTimezone})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected night"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Lv(t.endedAt,t.sourceTimezone)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:Wo(t.startedAt,t.endedAt,t.sourceTimezone)})]}),e.jsxs("div",{className:"grid gap-2 text-right",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Summary"}),e.jsx("div",{className:"text-3xl text-white",children:zs(t.asleepSeconds)}),e.jsx("div",{className:"text-sm text-white/54",children:"asleep"})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:zs(t.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Awake"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:zs(t.awakeSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:xn(g)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Restorative"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:xn(x)})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(nu,{active:n==="summary",onClick:()=>o("summary"),children:"Summary"}),e.jsx(nu,{active:n==="reflection",onClick:()=>o("reflection"),children:"Reflection"}),e.jsx(nu,{active:n==="raw",onClick:()=>o("raw"),children:"Show raw data"})]}),n==="summary"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/18 px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Phase timeline"}),e.jsx("div",{className:"mt-4",children:i?e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-6 text-sm text-white/56",children:"Loading phase timing from raw sleep segments…"}):e.jsx(kL,{timeline:(a==null?void 0:a.phaseTimeline)??{startedAt:t.startedAt,endedAt:t.endedAt,totalSeconds:Math.max(0,Math.round((new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime())/1e3)),hasRawSegments:!1,hasSleepStageData:!1,blocks:[]},timeZone:t.sourceTimezone})})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/18 px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(Rv,{stages:t.stageBreakdown})})]})]}):null,n==="reflection"?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Quality summary"}),e.jsx(be,{value:s.qualitySummary,onChange:b=>d({qualitySummary:b.target.value}),placeholder:"Recovered after a late evening, but sleep onset drifted."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Night notes"}),e.jsx(st,{className:"min-h-[200px]",value:s.notes,onChange:b=>d({notes:b.target.value}),placeholder:"What shaped this night, and what should we remember about it?"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(be,{value:s.tagsText,onChange:b=>d({tagsText:b.target.value}),placeholder:"travel, stress, good-routine, late-caffeine"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Linked context"}),e.jsx(bt,{options:l,selectedValues:s.linkValues,onChange:b=>d({linkValues:b}),placeholder:"Search goals, tasks, habits, beliefs, reports, or patterns…"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(H,{type:"button",pending:r,pendingLabel:"Saving",onClick:m,children:[e.jsx(Ni,{className:"size-4"}),"Save reflection"]})})]}):null,n==="raw"?e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm leading-6 text-white/56",children:"Forge shows the canonical overnight session by default. This view reveals the evidence stack underneath it: raw provider or historical imported records first, then Forge-normalized sleep segments."}),i?e.jsx("div",{className:"text-sm text-white/56",children:"Loading raw sleep evidence…"}):null,i?null:e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{className:te("border-white/0",bL(p.rawDataStatus)),children:yL(p.rawDataStatus)}),p.rawDataStatus==="historical_raw"?e.jsx(S,{tone:"meta",children:"Partial evidence"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Raw data"}),p.sourceRecords.length?p.sourceRecords.map(b=>e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-black/18 px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{className:te("border-white/0",wL(b)),children:b.qualityKind==="provider_native"?"Provider raw":"Historical raw"}),e.jsx(S,{tone:"meta",className:"capitalize",children:b.rawStage.replaceAll("_"," ")}),e.jsx("span",{className:"text-sm text-white/64",children:Wo(b.startedAt,b.endedAt,b.sourceTimezone)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-white/42",children:b.providerRecordType.replaceAll("_"," ")}),e.jsx(H,{type:"button",variant:"secondary",className:"h-8 rounded-full px-3",onClick:()=>c(A=>A===b.id?null:b.id),children:h===b.id?"Hide JSON":"See JSON"})]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/50",children:zs(Math.max(0,Math.round((new Date(b.endedAt).getTime()-new Date(b.startedAt).getTime())/1e3)))}),h===b.id?e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[14px] border border-white/8 bg-slate-950/70 p-3 text-xs leading-6 text-white/72",children:JSON.stringify({payload:b.payload,metadata:b.metadata},null,2)}):null]},b.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No raw data was stored for this night."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sleep segments"}),p.segments.length?p.segments.map(b=>e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-black/18 px-4 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{tone:"meta",className:"capitalize",children:b.stage.replaceAll("_"," ")}),e.jsx(S,{tone:"meta",children:b.qualityKind==="provider_native"?"provider-backed":"historical"}),e.jsx("span",{className:"text-sm text-white/64",children:Wo(b.startedAt,b.endedAt,b.sourceTimezone)})]}),e.jsx("span",{className:"text-sm text-white/50",children:zs(Math.max(0,Math.round((new Date(b.endedAt).getTime()-new Date(b.startedAt).getTime())/1e3)))})]})},b.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No normalized sleep segments were stored for this night."})]})]})]}):null]})})}function IL(){var R;const t=Ct(),s=pt(),[a,i]=u.useState({}),[r,n]=u.useState(null),[l,o]=u.useState("summary"),d=Array.isArray(t==null?void 0:t.selectedUserIds)?t.selectedUserIds:[],m=t==null?void 0:t.snapshot,h=Me({queryKey:["forge-sleep",...d],queryFn:async()=>(await Lm(d)).sleep}),c=Me({queryKey:["forge-sleep-raw",r],enabled:!!r,queryFn:async()=>F1(r)}),p=Me({queryKey:["forge-sleep-values",...d],queryFn:async()=>(await ia(d)).values}),g=Me({queryKey:["forge-sleep-patterns",...d],queryFn:async()=>(await si(d)).patterns}),x=Me({queryKey:["forge-sleep-behaviors",...d],queryFn:async()=>(await ra(d)).behaviors}),f=Me({queryKey:["forge-sleep-beliefs",...d],queryFn:async()=>(await Oa(d)).beliefs}),b=Me({queryKey:["forge-sleep-reports",...d],queryFn:async()=>(await Ai(d)).reports});u.useEffect(()=>{h.data&&i(Object.fromEntries(h.data.sessions.map(v=>[v.id,Po(v)])))},[h.data]),u.useEffect(()=>{var D,L,Q;if(!((D=h.data)!=null&&D.sessions.length)){n(null);return}h.data.sessions.some(Z=>Z.id===r)||n(((L=h.data.latestNight)==null?void 0:L.sleepId)??((Q=h.data.sessions[0])==null?void 0:Q.id)??null)},[r,h.data]),u.useEffect(()=>{o("summary")},[r]);const A=De({mutationFn:async v=>vb(v.sleepId,{qualitySummary:v.qualitySummary,notes:v.notes,tags:v.tagsText.split(",").map(D=>D.trim()).filter(Boolean),links:Ev(v.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-sleep"]}),await s.invalidateQueries({queryKey:["forge-sleep-raw"]})}});if(h.isLoading)return e.jsx(gs,{eyebrow:"Sleep",title:"Loading sleep surface",description:"Reading canonical nights, calendar summaries, and sleep phase detail.",columns:2,blocks:6});if(h.isError||!h.data)return e.jsx(ct,{eyebrow:"Sleep",error:h.error??new Error("Sleep data unavailable"),onRetry:()=>void h.refetch()});const T=h.data,I=T.sessions,y=new Map(I.map(v=>[v.id,v])),N=(r?y.get(r):null)??(T.latestNight?y.get(T.latestNight.sleepId):null)??I[0]??null,k=N?a[N.id]??Po(N):null,w=Mv({goals:(m==null?void 0:m.dashboard.goals)??[],projects:(m==null?void 0:m.dashboard.projects)??[],tasks:(m==null?void 0:m.dashboard.tasks)??[],habits:(m==null?void 0:m.dashboard.habits)??[],values:p.data??[],patterns:g.data??[],behaviors:x.data??[],beliefs:f.data??[],reports:b.data??[]});function P(v,D){i(L=>{const Q=I.find(V=>V.id===v),Z=L[v]??(Q?Po(Q):{qualitySummary:"",notes:"",tagsText:"",linkValues:[]});return{...L,[v]:{...Z,...D}}})}async function j(v){const D=I.find(Q=>Q.id===v);if(!D)return;const L=a[v]??Po(D);await A.mutateAsync({sleepId:v,qualitySummary:L.qualitySummary,notes:L.notes,tagsText:L.tagsText,linkValues:L.linkValues})}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(mt,{eyebrow:"Health",title:"Sleep",description:"Canonical overnight sessions first, with last-night recovery, a clickable night calendar, and raw segment evidence only when you ask for it.",badge:`${I.length} nights`}),e.jsx(Es,{}),e.jsx(vy,{children:e.jsx(NL,{latestNight:T.latestNight})}),e.jsx(jy,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]",children:[e.jsx(ru,{title:"Weekly average",value:zs(T.summary.averageSleepSeconds),description:"Average overnight sleep duration across the recent week, used as the baseline for the latest-night comparison."}),e.jsx(ru,{title:"Regularity",value:`${T.summary.averageRegularityScore}`,description:`Average bedtime drift ${T.summary.averageBedtimeConsistencyMinutes}m and wake drift ${T.summary.averageWakeConsistencyMinutes}m.`}),e.jsx(ru,{title:"Restorative share",value:xn(T.summary.averageRestorativeShare),description:`Deep + REM share across recent nights, with ${T.summary.reflectiveNightCount} nights already carrying context.`}),e.jsxs(le,{className:"border-white/8 bg-white/[0.03]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Recent stage mix"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:"Average nightly phases"})]}),e.jsx(bs,{className:"size-5 text-[var(--primary)]"})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:T.stageAverages.length>0?T.stageAverages.slice(0,5).map(v=>e.jsxs(S,{tone:"meta",children:[jl(v.stage).label," ",zs(v.averageSeconds)]},v.stage)):e.jsx("div",{className:"text-sm text-white/52",children:"Stage averages will appear once nights include phase data."})})]})]})}),e.jsx(ky,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(SL,{days:T.calendarDays,selectedSleepId:(N==null?void 0:N.id)??null,onSelect:v=>n(v)}),N&&k?e.jsx(CL,{session:N,draft:k,rawDetail:c.data??null,rawDetailLoading:c.isLoading,pending:A.isPending&&((R=A.variables)==null?void 0:R.sleepId)===N.id,tab:l,linkOptions:w,onTabChange:o,onDraftChange:v=>P(N.id,v),onSave:()=>void j(N.id)}):e.jsx(le,{className:"border-white/8 bg-white/[0.03] px-6 py-8 text-sm leading-6 text-white/58",children:"Pick a night from the calendar to inspect its phase timing, stage summary, and reflection context."})]})})]})}function cr(t){return t?t.replace(/^activity_/i,"").replaceAll("_"," ").replace(/\s+/g," ").replace(/\b\w/g,s=>s.toUpperCase()):"Unknown"}function al(t){return`${Math.round(t/60)}m`}function sm(t){return t?`${(t/1e3).toFixed(1)} km`:"n/a"}function il(t,s){const a=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}),i=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${a.format(new Date(t))} · ${i.format(new Date(t))} - ${i.format(new Date(s))}`}function qn(t){return{subjectiveEffort:t.subjectiveEffort!==null?String(t.subjectiveEffort):"",moodBefore:t.moodBefore??"",moodAfter:t.moodAfter??"",meaningText:t.meaningText??"",plannedContext:t.plannedContext??"",socialContext:t.socialContext??"",tagsText:Array.isArray(t.tags)?t.tags.join(", "):"",linkValues:Array.isArray(t.links)?t.links.map(s=>`${s.entityType}:${s.entityId}`):[]}}function Dv(t){return t.trim().toLowerCase()}function ar(t){var s;return((s=t.workoutTypeLabel)==null?void 0:s.trim())||cr(t.workoutType)}function kl(t){var s;return((s=t.activityFamilyLabel)==null?void 0:s.trim())||cr(t.activityFamily)}function $v(t){return cr(t.sourceSystem??t.source)}function TL(t){return t==null?"n/a":typeof t=="boolean"?t?"Yes":"No":typeof t=="number"?Number.isInteger(t)?String(t):t.toFixed(1):t}function PL(t){const s=TL(t.value);return!t.unit||t.unit==="count"?s:`${s} ${t.unit}`}function AL(t,s){return Dv([t.workoutType,ar(t),t.activityFamily,kl(t),t.sourceSystem,$v(t),t.sourceType,t.sourceDevice,t.reconciliationStatus,t.moodBefore,t.moodAfter,t.meaningText,t.plannedContext,t.socialContext,t.tags.join(" "),s.moodBefore,s.moodAfter,s.meaningText,s.plannedContext,s.socialContext,s.tagsText,il(t.startedAt,t.endedAt)].join(" "))}function ML(t){const s=new Map;for(const a of t)s.set(`workout:${a.workoutType}`,{id:`workout:${a.workoutType}`,label:ar(a),description:"Workout type",searchText:`${ar(a)} workout`,badge:e.jsx(S,{tone:"meta",children:ar(a)})}),s.set(`source:${a.sourceType}`,{id:`source:${a.sourceType}`,label:a.sourceType.replaceAll("_"," "),description:"Source type",searchText:`${a.sourceType} source`,badge:e.jsx(S,{tone:"meta",className:"capitalize",children:a.sourceType.replaceAll("_"," ")})}),s.set(`status:${a.reconciliationStatus}`,{id:`status:${a.reconciliationStatus}`,label:a.reconciliationStatus.replaceAll("_"," "),description:"Reconciliation status",searchText:`${a.reconciliationStatus} status`,badge:e.jsx(S,{tone:"meta",className:"capitalize",children:a.reconciliationStatus.replaceAll("_"," ")})});return s.set("linked:yes",{id:"linked:yes",label:"Linked",description:"Already tied to Forge or Psyche context",badge:e.jsx(S,{tone:"meta",children:"Linked"})}),s.set("linked:no",{id:"linked:no",label:"Needs links",description:"No Forge or Psyche links yet",badge:e.jsx(S,{tone:"meta",children:"Needs links"})}),s.set("habit:yes",{id:"habit:yes",label:"Habit-generated",description:"Created from a habit completion",badge:e.jsx(S,{tone:"meta",children:"Habit-generated"})}),s.set("effort:rated",{id:"effort:rated",label:"Effort rated",description:"Already has a subjective effort score",badge:e.jsx(S,{tone:"meta",children:"Effort rated"})}),Array.from(s.values())}function EL(t,s){return s.every(a=>a.startsWith("workout:")?t.workoutType===a.slice(8):a.startsWith("source:")?t.sourceType===a.slice(7):a.startsWith("status:")?t.reconciliationStatus===a.slice(7):a==="linked:yes"?t.links.length>0:a==="linked:no"?t.links.length===0:a==="habit:yes"?!!t.generatedFromHabitId:a==="effort:rated"?t.subjectiveEffort!==null:!0)}function LL({session:t,draft:s,linkOptions:a,pending:i,step:r,onStepChange:n,onDraftChange:l,onSave:o}){var m,h,c,p,g,x,f,b,A;const d=[{id:"context",title:"Session context",description:"Quick facts, effort, and how this session happened."},{id:"reflection",title:"Reflection",description:"Mood, meaning, and what the session actually did for you."},{id:"links",title:"Links",description:"Tie the session back to Forge and Psyche context."}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] p-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-lg text-white",children:[e.jsx(pm,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:ar(t)})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:il(t.startedAt,t.endedAt)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{children:al(t.durationSeconds)}),t.totalEnergyKcal?e.jsxs(S,{tone:"meta",children:[Math.round(t.totalEnergyKcal)," kcal"]}):null,t.distanceMeters?e.jsx(S,{tone:"meta",children:sm(t.distanceMeters)}):null,e.jsx(S,{tone:"meta",children:kl(t)}),e.jsx(S,{tone:"meta",className:"capitalize",children:t.reconciliationStatus.replaceAll("_"," ")})]})]})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:d.map((T,I)=>e.jsxs("button",{type:"button",onClick:()=>n(I),className:`rounded-[20px] border px-4 py-3 text-left transition ${r===I?"border-[var(--primary)] bg-[var(--primary)]/10 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.06] hover:text-white"}`,children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:["Step ",I+1]}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:T.title})]},T.id))}),e.jsxs("div",{className:"rounded-[24px] bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:d[r].title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:d[r].description}),r===0?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Activity family"}),e.jsx("div",{className:"mt-2 text-lg text-white capitalize",children:kl(t)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source system"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:$v(t)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source device"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.sourceDevice||"n/a"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Steps"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.stepCount??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Avg HR"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.averageHeartRate?Math.round(t.averageHeartRate):"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Max HR"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.maxHeartRate?Math.round(t.maxHeartRate):"n/a"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Effort"}),e.jsx(be,{type:"number",min:1,max:10,value:s.subjectiveEffort,onChange:T=>l({subjectiveEffort:T.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Planned vs spontaneous"}),e.jsx(be,{value:s.plannedContext,onChange:T=>l({plannedContext:T.target.value}),placeholder:"Planned recovery block"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Social context"}),e.jsx(be,{value:s.socialContext,onChange:T=>l({socialContext:T.target.value}),placeholder:"Solo, coach, group class, partner"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(be,{value:s.tagsText,onChange:T=>l({tagsText:T.target.value}),placeholder:"recovery, interval-block, stress-release"})]})]}):null,r===1?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood before"}),e.jsx(be,{value:s.moodBefore,onChange:T=>l({moodBefore:T.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood after"}),e.jsx(be,{value:s.moodAfter,onChange:T=>l({moodAfter:T.target.value})})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Meaning, impact, and why this session mattered"}),e.jsx(st,{className:"min-h-[160px]",value:s.meaningText,onChange:T=>l({meaningText:T.target.value}),placeholder:"This session was planned as active recovery after a heavy work block and helped reset stress before sleep."})]})]}):null,r===2?e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Search goals, projects, habits, values, beliefs, patterns, or reports and attach the ones that explain this session."}),e.jsx(bt,{options:a,selectedValues:s.linkValues,onChange:T=>l({linkValues:T}),placeholder:"Search Forge and Psyche records…"})]}):null,e.jsxs("div",{className:"mt-5 grid gap-4 border-t border-white/8 pt-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Captured data"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Source-native workout metrics, events, and phases exposed through the adapter layer."})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:[(((m=t.details)==null?void 0:m.metrics)??[]).slice(0,12).map(T=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:T.label}),e.jsx("div",{className:"mt-2 text-lg text-white",children:PL(T)}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.14em] text-white/38",children:[cr(T.category)," · ",cr(T.statistic)]})]},`${T.category}:${T.key}:${T.statistic}`)),(((c=(h=t.details)==null?void 0:h.metrics)==null?void 0:c.length)??0)===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/50",children:"No provider metrics were captured for this session yet."}):null]}),(((g=(p=t.details)==null?void 0:p.events)==null?void 0:g.length)??0)>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workout events"}),e.jsx("div",{className:"grid gap-2",children:(x=t.details)==null?void 0:x.events.map(T=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-white",children:T.label}),e.jsx(S,{tone:"meta",children:al(T.durationSeconds)})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:il(T.startedAt,T.endedAt??T.startedAt)})]},`${T.type}:${T.startedAt}`))})]}):null,(((b=(f=t.details)==null?void 0:f.components)==null?void 0:b.length)??0)>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workout phases"}),e.jsx("div",{className:"grid gap-2",children:(A=t.details)==null?void 0:A.components.map(T=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-white",children:T.activity.canonicalLabel}),e.jsx(S,{tone:"meta",children:al(T.durationSeconds)})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:il(T.startedAt,T.endedAt??T.startedAt)})]},T.externalUid))})]}):null]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm text-white/48",children:r<d.length-1?"Move through the session one step at a time, then save when the context is clean.":"Everything is in place. Save the session metadata back into Forge."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(H,{type:"button",variant:"secondary",onClick:()=>n(Math.max(0,r-1)),disabled:r===0,children:"Back"}),r<d.length-1?e.jsxs(H,{type:"button",onClick:()=>n(r+1),children:["Next",e.jsx(Ca,{className:"size-4"})]}):null,e.jsxs(H,{type:"button",pending:i,pendingLabel:"Saving",onClick:o,children:[e.jsx(Ni,{className:"size-4"}),"Save session"]})]})]})]})}function _L(){var E;const t=Ct(),s=pt(),a=u.useRef(null),i=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[r,n]=u.useState({}),[l,o]=u.useState(""),[d,m]=u.useState([]),[h,c]=u.useState(null),[p,g]=u.useState(0),x=Me({queryKey:["forge-fitness",...i],queryFn:async()=>(await gb(i)).fitness}),f=Me({queryKey:["forge-health-values",...i],queryFn:async()=>(await ia(i)).values}),b=Me({queryKey:["forge-health-patterns",...i],queryFn:async()=>(await si(i)).patterns}),A=Me({queryKey:["forge-health-behaviors",...i],queryFn:async()=>(await ra(i)).behaviors}),T=Me({queryKey:["forge-health-beliefs",...i],queryFn:async()=>(await Oa(i)).beliefs}),I=Me({queryKey:["forge-health-reports",...i],queryFn:async()=>(await Ai(i)).reports});u.useEffect(()=>{x.data&&n(Object.fromEntries(x.data.sessions.map(X=>[X.id,qn(X)])))},[x.data]);const y=De({mutationFn:async X=>s2(X.workoutId,{subjectiveEffort:X.subjectiveEffort.trim().length>0?Number(X.subjectiveEffort):null,moodBefore:X.moodBefore,moodAfter:X.moodAfter,meaningText:X.meaningText,plannedContext:X.plannedContext,socialContext:X.socialContext,tags:X.tagsText.split(",").map(W=>W.trim()).filter(Boolean),links:Ev(X.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-fitness"]})}}),N=x.data,k=(N==null?void 0:N.sessions)??[],w=Mv({goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.dashboard.tasks,habits:t.snapshot.dashboard.habits,values:f.data??[],patterns:b.data??[],behaviors:A.data??[],beliefs:T.data??[],reports:I.data??[]}),P=u.useMemo(()=>ML(k),[k]),j=u.useMemo(()=>{const X=Dv(l);return[...k].sort((W,q)=>new Date(q.startedAt).getTime()-new Date(W.startedAt).getTime()).filter(W=>{const q=r[W.id]??qn(W);return(X.length===0||AL(W,q).includes(X))&&EL(W,d)})},[r,l,d,k]),R=j.length===k.length&&l.trim().length===0&&d.length===0?`${k.length} workout sessions visible`:`${j.length} of ${k.length} workout sessions visible`,v=j.find(X=>X.id===h)??k.find(X=>X.id===h)??null,D=v?r[v.id]??qn(v):null,L=Ad({count:j.length,getScrollElement:()=>a.current,estimateSize:()=>108,overscan:8});if(x.isLoading)return e.jsx(gs,{eyebrow:"Sports",title:"Loading sports view",description:"Reading synced workouts and local reflection metadata.",columns:2,blocks:6});if(x.isError||!N)return e.jsx(ct,{eyebrow:"Sports",error:x.error??new Error("Sports data unavailable"),onRetry:()=>void x.refetch()});const{summary:Q,weeklyTrend:Z,typeBreakdown:V}=N;function B(X,W){n(q=>{const G=q[X]??qn(k.find(z=>z.id===X));return{...q,[X]:{...G,...W}}})}async function $(X){const W=k.find(G=>G.id===X);if(!W)return;const q=r[X]??qn(W);await y.mutateAsync({workoutId:X,subjectiveEffort:q.subjectiveEffort,moodBefore:q.moodBefore,moodAfter:q.moodAfter,meaningText:q.meaningText,plannedContext:q.plannedContext,socialContext:q.socialContext,tagsText:q.tagsText,linkValues:q.linkValues}),c(null),g(0)}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(mt,{entityKind:"project",title:"Sports",description:"A session-first training surface for workout data, subjective meaning, and links back into Forge execution and Psyche.",badge:`${k.length} sessions`}),e.jsx(Ny,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Weekly volume"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:al(Q.weeklyVolumeSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Total training time in the recent week."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Exercise minutes"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.exerciseMinutes}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Aggregate exercise minutes from synced sessions."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Energy burned"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.energyBurnedKcal}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Recent weekly kcal."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training streak"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.streakDays}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Distinct workout days in the recent week."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average session"}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[Q.averageSessionMinutes,"m"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean duration across recent sessions."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average effort"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.averageEffort||"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Subjective effort across sessions that carry a rating."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked sessions"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.linkedSessionCount}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Sessions already tied to Forge or Psyche entities."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Top block"}),e.jsx("div",{className:"mt-3 text-xl text-white",children:Q.topWorkoutTypeLabel??Q.topWorkoutType??"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Dominant workout type across the recent window."})]})]})}),e.jsx(Sy,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[1.05fr_0.95fr]",children:[e.jsxs(le,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recent volume"}),e.jsx("div",{className:"grid gap-3",children:Z.map(X=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[110px_150px_minmax(0,1fr)_90px]",children:[e.jsx("div",{className:"text-sm text-white/62",children:X.dateKey}),e.jsx("div",{className:"text-sm text-white",children:X.workoutTypeLabel??cr(X.workoutType)}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--primary)]",style:{width:`${Math.min(100,X.durationMinutes/120*100)}%`}})}),e.jsxs("div",{className:"text-sm text-white",children:[X.durationMinutes,"m"]})]}),e.jsxs("div",{className:"text-sm text-white/62",children:[X.energyKcal," kcal"]})]},X.id))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Distance"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:sm(Q.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Planned sessions"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Q.plannedSessionCount})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Imported / merged"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[Q.importedSessionCount," / ",Q.reconciledSessionCount]})]})]})]}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training composition"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Workout type and provenance mix"})]}),e.jsx("div",{className:"grid gap-3",children:V.slice(0,6).map(X=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[minmax(0,1fr)_90px_90px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white",children:X.workoutTypeLabel??cr(X.workoutType)}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[X.sessionCount," sessions · ",X.activityFamilyLabel??"Other"]})]}),e.jsxs("div",{className:"text-sm text-white/72",children:[X.totalMinutes,"m"]}),e.jsxs("div",{className:"text-sm text-white/72",children:[X.energyKcal," kcal"]})]},X.workoutType))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Habit-generated"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Q.habitGeneratedSessionCount})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Forge-linked"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Q.linkedSessionCount})]})]})]})]})}),e.jsx(Cy,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(Ii,{title:"Session browser",description:"Search past activities by workout type, source, reconciliation state, or whether they still need context.",query:l,onQueryChange:o,options:P,selectedOptionIds:d,onSelectedOptionIdsChange:m,resultSummary:R,placeholder:"Search workouts, devices, notes, moods, or filter chips",emptyStateMessage:"Keep typing or pick a filter chip to narrow the activity history."}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Activity history"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a workout to add reflection and links in a guided modal."})]}),e.jsx(S,{tone:"meta",children:R})]}),e.jsx("div",{ref:a,className:"h-[34rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:j.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No workout matches the current search yet. Clear some filters or search by workout type, device, or reflection text."}):e.jsx("div",{className:"relative w-full",style:{height:`${L.getTotalSize()}px`},children:L.getVirtualItems().map(X=>{const W=j[X.index],q=W.meaningText.trim().length>0||W.moodBefore.trim().length>0||W.moodAfter.trim().length>0||W.tags.length>0||W.links.length>0;return e.jsx("div",{className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${X.start}px)`},children:e.jsxs("button",{type:"button",className:"grid w-full gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>{c(W.id),g(0)},children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(pm,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:ar(W)})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-sm text-white/56",children:[e.jsx(bs,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:il(W.startedAt,W.endedAt)})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/46",children:[kl(W)," · ",W.sourceDevice]})]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.05] px-3 py-1.5 text-xs text-white/70",children:[e.jsx("span",{children:q?"Reflected":"Needs reflection"}),e.jsx(Ca,{className:"size-3.5"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{children:al(W.durationSeconds)}),W.totalEnergyKcal?e.jsxs(S,{tone:"meta",children:[Math.round(W.totalEnergyKcal)," kcal"]}):null,W.distanceMeters?e.jsx(S,{tone:"meta",children:sm(W.distanceMeters)}):null,W.averageHeartRate?e.jsxs(S,{tone:"meta",children:[e.jsx(Sf,{className:"mr-1 size-3.5"}),Math.round(W.averageHeartRate)," bpm"]}):null,e.jsx(S,{tone:"meta",children:kl(W)}),e.jsx(S,{tone:"meta",className:"capitalize",children:W.sourceType.replaceAll("_"," ")}),e.jsx(S,{tone:"meta",className:"capitalize",children:W.reconciliationStatus.replaceAll("_"," ")})]})]})},W.id)})})})]})]})}),v&&D?e.jsx(Pa,{open:!!v,onOpenChange:X=>{X||(c(null),g(0))},eyebrow:"Sports session",title:ar(v),description:"Add contextual meaning without crowding the main training surface.",children:e.jsx(LL,{session:v,draft:D,linkOptions:w,pending:y.isPending&&((E=y.variables)==null?void 0:E.workoutId)===v.id,step:p,onStepChange:g,onDraftChange:X=>B(v.id,X),onSave:()=>void $(v.id)})}):null]})}function Fs({label:t,help:s}){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/58",children:[e.jsx("span",{children:t}),s?e.jsx(Tt,{content:s,label:`Explain ${t}`}):null]})}const Ao=[{status:"backlog",label:"Backlog",description:"Not started yet.",icon:Va},{status:"focus",label:"Focus",description:"Ready to start soon.",icon:Sl},{status:"in_progress",label:"In progress",description:"Work is active now.",icon:ta},{status:"blocked",label:"Blocked",description:"Something is stopping progress.",icon:Pf},{status:"done",label:"Done",description:"The task is completed.",icon:ml}],FL={issue:{label:"Issue",noun:"issue",descriptor:"Vertical slice issue",heroDescription:"Track the vertical slice, keep the acceptance bar explicit, and surface the execution context without losing the product-level story."},task:{label:"Task",noun:"task",descriptor:"AI session task",heroDescription:"Drive one focused AI execution session, keep the work contract crisp, and show the concrete evidence of what changed."},subtask:{label:"Subtask",noun:"subtask",descriptor:"Granular child step",heroDescription:"Keep the child step sharply scoped, trace its parent chain, and make the work evidence visible without opening the editor."}},RL={commit:{label:"Commit",className:"bg-emerald-500/12 text-emerald-100"},branch:{label:"Branch",className:"bg-sky-500/12 text-sky-100"},pull_request:{label:"Pull request",className:"bg-fuchsia-500/12 text-fuchsia-100"}};function lu(t){return t==="issue"?"issue":"task"}function DL(t,s){switch(t){case"goal":return`/goals/${s}`;case"project":return`/projects/${s}`;case"task":return`/tasks/${s}`;case"strategy":return`/strategies/${s}`;case"habit":return"/habits";default:return null}}function Di(t){if(!t||t<=0)return"0 min";if(t<3600)return`${Math.max(1,Math.round(t/60))} min`;const s=Math.floor(t/3600),a=Math.round(t%3600/60);return a===0?`${s} h`:`${s} h ${a} min`}function $i({eyebrow:t,title:s,description:a,children:i,className:r}){return e.jsxs("div",{className:te("rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.025))] p-4 sm:p-5",r),children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsx("div",{className:"mt-2 text-lg font-medium text-white",children:s}),a?e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/56",children:a}):null,e.jsx("div",{className:"mt-4",children:i})]})}function Bs({label:t,value:s,hint:a,className:i}){return e.jsxs("div",{className:te("rounded-[18px] border border-white/8 bg-white/[0.035] px-4 py-3",i),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:t}),e.jsx("div",{className:"mt-2 text-base font-medium text-white",children:s}),a?e.jsx("div",{className:"mt-1 text-sm leading-5 text-white/52",children:a}):null]})}function $L(){var Be,at,Le,Y,ee,xe,ye;const{t,formatDate:s,formatDateTime:a}=Gt(),i=Ct(),r=Array.isArray(i.selectedUserIds)?i.selectedUserIds:[],n=aa(),l=Ht(),o=pt(),d=Is(r),[m,h]=u.useState(!1),[c,p]=u.useState(!1),[g,x]=u.useState(!1),[f,b]=u.useState(!1),[A,T]=u.useState(!1),[I,y]=u.useState(null),[N,k]=u.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 1023px)").matches:!1),[w]=u.useState(()=>{const ue=new Date,$e=new Date(ue);$e.setHours(0,0,0,0);const Xe=new Date(ue);return Xe.setHours(23,59,59,999),{from:$e.toISOString(),to:Xe.toISOString()}}),[P]=u.useState(()=>{const ue=new Date,$e=new Date(ue);$e.setHours(0,0,0,0);const Xe=new Date($e);return Xe.setDate(Xe.getDate()+7),Xe.setHours(23,59,59,999),{from:$e.toISOString(),to:Xe.toISOString()}});u.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const ue=window.matchMedia("(max-width: 1023px)"),$e=Xe=>k(Xe?Xe.matches:ue.matches);return $e(),typeof ue.addEventListener=="function"?(ue.addEventListener("change",$e),()=>ue.removeEventListener("change",$e)):(ue.addListener($e),()=>ue.removeListener($e))},[]);const j=Me({queryKey:["task-context",n.taskId],queryFn:()=>q2(n.taskId),enabled:!!n.taskId}),R=Me({queryKey:["task-calendar-overview",n.taskId,w.from,w.to,...r],queryFn:()=>nn({...w,userIds:r}),enabled:!!n.taskId}),v=Me({queryKey:["forge-life-force",...r],queryFn:async()=>(await hr(r)).lifeForce}),D=Me({queryKey:["task-calendar-overview",n.taskId,P.from,P.to,...r],queryFn:()=>nn({...P,userIds:r}),enabled:!!n.taskId}),L=async()=>{await Promise.all([Zt(o),o.invalidateQueries({queryKey:["task-context",n.taskId]}),o.invalidateQueries({queryKey:["activity-archive"]}),o.invalidateQueries({queryKey:["project-board"]}),o.invalidateQueries({queryKey:["forge-xp-metrics"]}),o.invalidateQueries({queryKey:["forge-reward-ledger"]}),o.invalidateQueries({queryKey:["forge-operator-context"]}),o.invalidateQueries({queryKey:["task-calendar-overview",n.taskId]}),o.invalidateQueries({queryKey:["forge-calendar-overview"]})])},Q=De({mutationFn:({taskId:ue,patch:$e})=>i.patchTask(ue,$e),onSuccess:L}),Z=De({mutationFn:ue=>Km(ue),onSuccess:L}),V=De({mutationFn:ue=>Sb(ue),onSuccess:L}),B=De({mutationFn:({runId:ue,actor:$e,note:Xe})=>Ib(ue,{actor:$e,note:Xe??""}),onSuccess:L}),$=De({mutationFn:({runId:ue,actor:$e,note:Xe})=>Cb(ue,{actor:$e,note:Xe??""}),onSuccess:L}),E=De({mutationFn:qm,onSuccess:L}),X=De({mutationFn:ue=>zm(ue),onSuccess:L}),W=De({mutationFn:mb,onSuccess:L}),q=De({mutationFn:({timeboxId:ue,patch:$e})=>vu(ue,$e),onSuccess:L}),G=De({mutationFn:hb,onSuccess:L}),z=j.data;if(j.isLoading)return e.jsx(gs,{});if(j.isError)return e.jsx(ct,{eyebrow:t("common.taskDetail.errorEyebrow"),error:j.error,onRetry:()=>void j.refetch()});if(!z)return e.jsx(ct,{eyebrow:t("common.taskDetail.errorEyebrow"),error:new Error(t("common.taskDetail.emptyPayload")),onRetry:()=>void j.refetch()});const ge=z.activeTaskRun??null,ke=z.task.actionPointSummary??null,me=Ao.find(ue=>ue.status===z.task.status)??Ao[0],se=z.task.level??"task",we=z.task.aiInstructions??"",ve=IP(z.task,(Be=z.project)==null?void 0:Be.schedulingRules),_=Xw({rules:ve,overview:(at=R.data)==null?void 0:at.calendar}),F=(((Le=D.data)==null?void 0:Le.calendar.timeboxes)??[]).filter(ue=>ue.taskId===z.task.id).sort((ue,$e)=>Date.parse(ue.startsAt)-Date.parse($e.startsAt)),O=F[0]??null,ce=FL[se],J=lu(se),je=i.snapshot.workItems??i.snapshot.tasks??[],Ee=z.task.parentWorkItemId?je.find(ue=>ue.id===z.task.parentWorkItemId)??null:null,Ce=je.filter(ue=>ue.parentWorkItemId===z.task.id).sort((ue,$e)=>ue.sortOrder-$e.sortOrder),Ke=i.snapshot.tags??[],Pe=(z.task.tagIds??[]).map(ue=>Ke.find($e=>$e.id===ue)??null).filter(ue=>!!ue),M=z.task.acceptanceCriteria??[],U=z.task.blockerLinks??[],he=z.task.gitRefs??[],Ne=z.task.completionReport,fe=new Set((Ne==null?void 0:Ne.linkedGitRefIds)??[]),Se=he.filter(ue=>fe.has(ue.id)),Je=he.filter(ue=>!fe.has(ue.id)),nt=((Y=z.task.user)==null?void 0:Y.kind)==="bot"||((ee=z.task.ownerUser)==null?void 0:ee.kind)==="bot",K=(z.task.assignees??[]).filter(ue=>ue.kind==="bot"),Ie=we.trim().length>0,_e=N?"w-full justify-start":"",ae=ue=>{switch(ue){case"active":return"Active";case"completed":return"Completed";case"released":return"Paused";case"timed_out":return"Timed out";default:return ue}},Fe=async ue=>{await i.patchTaskStatus(z.task.id,ue),await L(),T(!1)},ie=async()=>{window.confirm(`Delete ${ce.noun} "${z.task.title}"?`)&&(await X.mutateAsync(z.task.id),l(z.project?`/projects/${z.project.id}`:z.goal?`/goals/${z.goal.id}`:"/kanban"))};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(mt,{entityKind:J,title:e.jsx(It,{kind:J,label:z.task.title,variant:"heading",size:"lg",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),titleText:z.task.title,description:z.task.description?e.jsx(Ws,{markdown:z.task.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):ce.heroDescription,badge:ke?`${z.task.points} xp · ${Math.round(ke.totalCostAp)} AP`:`${z.task.points} xp`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Mi,{metrics:i.snapshot.metrics}),e.jsx(Qd,{userId:d,domain:"tasks",entityType:"task",entityId:z.task.id,label:z.task.title,description:z.task.description}),e.jsx(fr,{entityType:"task",entityId:z.task.id})]})}),e.jsxs(le,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:ce.label}),e.jsx("div",{className:"mt-2",children:e.jsx(It,{kind:J,label:z.task.title,variant:"heading",size:"xl",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"})}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:z.task.description?e.jsx(Ws,{markdown:z.task.description,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):`This page shows the ${ce.noun}, where it belongs, what is driving it, and the concrete evidence of what has happened on it so far.`})]}),e.jsx("div",{className:te("shrink-0",N?"w-full":""),children:e.jsxs("div",{className:te("flex flex-wrap items-center gap-2",N&&"grid w-full grid-cols-1"),children:[e.jsxs(H,{className:_e,pending:j.isFetching,pendingLabel:ge?"Opening":"Starting",onClick:async()=>{await i.startTaskNow(z.task.id),await L()},children:[e.jsx(ta,{className:"size-4 fill-current"}),ge?"Focus work":"Start work"]}),ge?e.jsxs(e.Fragment,{children:[e.jsx(H,{className:_e,variant:"secondary",pending:B.isPending,pendingLabel:"Pausing",onClick:async()=>{await B.mutateAsync({runId:ge.id,actor:ge.actor,note:ge.note})},children:"Pause"}),e.jsx(H,{className:_e,variant:"secondary",pending:$.isPending,pendingLabel:"Completing",onClick:async()=>{await $.mutateAsync({runId:ge.id,actor:ge.actor,note:ge.note})},children:"Complete"})]}):null,e.jsxs(H,{className:_e,variant:"secondary",onClick:()=>T(!0),children:[e.jsx(me.icon,{className:"size-4"}),"Change status"]}),e.jsxs(H,{className:_e,variant:"secondary",onClick:()=>h(!0),children:[e.jsx(Pi,{className:"size-4"}),"Edit ",ce.noun]}),e.jsxs(H,{className:_e,variant:"secondary",onClick:()=>p(!0),children:[e.jsx(Va,{className:"size-4"}),"Adjust work"]}),e.jsxs(H,{className:_e,variant:"secondary",pending:W.isPending,pendingLabel:"Planning",onClick:()=>x(!0),children:[e.jsx(bs,{className:"size-4"}),"Time Box"]}),z.task.status==="done"?e.jsx(H,{className:_e,variant:"secondary",onClick:async()=>{await Z.mutateAsync(z.task.id)},children:"Mark as not done"}):null,e.jsxs(H,{className:te(_e,"text-rose-200 hover:bg-rose-500/10"),variant:"ghost",pending:X.isPending,pendingLabel:t("common.taskDetail.deleting"),onClick:()=>void ie(),children:["Delete ",ce.noun]})]})})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:ce.label}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ce.descriptor}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:me.label}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.priority.${z.task.priority}`)}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.effort.${z.task.effort}`)}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.energy.${z.task.energy}`)}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:[z.task.points," xp"]}),z.task.time.totalCreditedSeconds>0?e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(z.task.time.totalCreditedSeconds/60)," min tracked"]}):null,ge?e.jsx(S,{className:"bg-emerald-500/12 text-emerald-200",children:"Timer active"}):null,z.task.executionMode?e.jsx(S,{className:z.task.executionMode==="afk"?"bg-emerald-500/12 text-emerald-100":"bg-amber-500/12 text-amber-100",children:z.task.executionMode.toUpperCase()}):null,Ie?e.jsx(S,{className:"bg-sky-500/12 text-sky-100",children:"AI brief ready"}):null,nt||K.length>0?e.jsx(S,{className:"bg-fuchsia-500/12 text-fuchsia-100",children:"Bot collaboration live"}):null,O?e.jsx(et,{to:`/calendar?timeboxId=${encodeURIComponent(O.id)}`,className:"inline-flex",children:e.jsxs(S,{className:"cursor-pointer bg-[var(--primary)]/16 text-[var(--primary)] transition hover:bg-[var(--primary)]/24",children:["Timeboxed · ",a(O.startsAt)]})}):null]}),N?null:e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Status"}),e.jsx("div",{className:"mt-3 grid gap-2 md:grid-cols-2 xl:grid-cols-5",children:Ao.map(ue=>{const $e=ue.icon,Xe=ue.status===z.task.status;return e.jsxs("button",{type:"button",disabled:Xe||Q.isPending,className:`rounded-[18px] border px-3.5 py-3 text-left transition ${Xe?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.08]"}`,onClick:()=>void Fe(ue.status),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"font-medium",children:ue.label})]}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/54",children:ue.description})]},ue.status)})})]}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsx($i,{eyebrow:"Hierarchy",title:"Context map",description:`See where this ${ce.noun} sits in the larger planning ladder without opening the board.`,children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx(Fs,{label:"Project",help:`The project is the main work stream this ${ce.noun} belongs to.`}),e.jsx("div",{className:"mt-2",children:z.project?e.jsx(et,{to:`/projects/${z.project.id}`,className:"inline-flex max-w-full",children:e.jsx(Qe,{kind:"project",label:z.project.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No project linked"})})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Goal",help:"The goal shows the longer-term result this work supports."}),e.jsx("div",{className:"mt-2",children:z.goal?e.jsx(et,{to:`/goals/${z.goal.id}`,className:"inline-flex max-w-full",children:e.jsx(Qe,{kind:"goal",label:z.goal.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No goal linked"})})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Parent item",help:"Issues parent tasks, tasks parent subtasks, and split child items stay legible here."}),e.jsx("div",{className:"mt-2",children:Ee?e.jsx(et,{to:`/tasks/${Ee.id}`,className:"inline-flex max-w-full",children:e.jsx(Qe,{kind:lu(Ee.level),label:Ee.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No parent work item"})})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Child items",help:"Child work items let you scan the next layer down without leaving the detail view."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Ce.length>0?Ce.map(ue=>e.jsx(et,{to:`/tasks/${ue.id}`,className:"inline-flex max-w-full",children:e.jsx(Qe,{kind:lu(ue.level),label:ue.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})},ue.id)):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No child work items"})})]})]})}),e.jsx($i,{eyebrow:"Execution",title:"Execution profile",description:"Surface the operating mode, AI posture, tags, and blockers as a single readable brief.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Bs,{label:"Work-item type",value:ce.descriptor,hint:se==="task"?"Tasks are meant to fit one focused AI session.":se==="issue"?"Issues hold the vertical slice and its delivery contract.":"Subtasks stay intentionally small and concrete."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{label:"Execution mode",value:z.task.executionMode?z.task.executionMode.toUpperCase():"Not set"}),e.jsx(Bs,{label:"AI posture",value:Ie?"AI brief ready":se==="issue"?"Issue narrative only":"Needs AI brief"})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Tags",help:"Tags shape filtering and fast scanning across the board and hierarchy views."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Pe.length>0?Pe.map(ue=>e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue.name},ue.id)):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No tags"})})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Blockers",help:"Blockers tie this work item to the entities that currently constrain it."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:U.length>0?U.map(ue=>{const $e=DL(ue.entityType,ue.entityId),Xe=e.jsx(S,{wrap:!0,className:"bg-amber-500/12 text-amber-100",children:ue.label??`${ue.entityType} · ${ue.entityId}`},`${ue.entityType}:${ue.entityId}`);return $e?e.jsx(et,{to:$e,className:"inline-flex max-w-full",children:Xe},`${ue.entityType}:${ue.entityId}`):Xe}):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No blockers linked"})})]})]})}),e.jsx($i,{eyebrow:"People and timing",title:"Accountability surface",description:"Show who owns the work, who is helping, and when the record moved.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Bs,{label:"Owner",value:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[z.task.user?e.jsx(ht,{user:z.task.user,compact:!0}):null,e.jsx("span",{children:z.task.owner}),nt?e.jsxs(S,{className:"bg-fuchsia-500/12 text-fuchsia-100",children:[e.jsx(Sa,{className:"mr-1 size-3.5"}),"Bot owner"]}):null]})}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Assignees"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:z.task.assignees&&z.task.assignees.length>0?z.task.assignees.map(ue=>e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.05] px-3 py-1.5 text-sm text-white/72",children:[e.jsx(ht,{user:ue,compact:!0}),e.jsx("span",{children:ue.displayName}),ue.kind==="bot"?e.jsx(Sa,{className:"size-3.5 text-fuchsia-200"}):null]},ue.id)):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No assignees"})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{label:"Due date",value:s(z.task.dueDate),hint:`Use due dates only when timing materially matters for this ${ce.noun}.`}),e.jsx(Bs,{label:"Completed",value:z.task.completedAt?a(z.task.completedAt):"Not completed"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{label:"Created",value:a(z.task.createdAt)}),e.jsx(Bs,{label:"Updated",value:a(z.task.updatedAt)})]})]})})]}),Ie||M.length>0||Ne||he.length>0?e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1.05fr)_minmax(0,1fr)]",children:[e.jsx($i,{eyebrow:"Execution brief",title:"AI and delivery instructions",description:"The narrative, criteria, and execution intent live together so the detail view can stand on its own.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(Ut,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:"AI instructions"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/72",children:Ie?e.jsx(Ws,{markdown:we,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):`No AI instructions have been written for this ${ce.noun} yet.`})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(Sl,{className:"size-4 text-emerald-200"}),e.jsx("span",{children:"Acceptance criteria"})]}),M.length>0?e.jsx("div",{className:"mt-3 grid gap-2",children:M.map((ue,$e)=>e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/72",children:ue},`${z.task.id}-criterion-${$e}`))}):e.jsx("div",{className:"mt-3 rounded-[16px] border border-dashed border-white/10 px-4 py-3 text-sm text-white/52",children:"No acceptance criteria captured yet."})]})]})}),e.jsx($i,{eyebrow:"Evidence",title:"Work done, changed files, and git traceability",description:"Show the work summary, file footprint, and linked refs directly in the detail view.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(cm,{className:"size-4 text-sky-200"}),e.jsx("span",{children:"Work summary"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/72",children:Ne!=null&&Ne.workSummary?e.jsx(Ws,{markdown:Ne.workSummary,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):"No work summary yet."})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(Af,{className:"size-4 text-amber-200"}),e.jsx("span",{children:"Changed files"})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Ne!=null&&Ne.modifiedFiles&&Ne.modifiedFiles.length>0?Ne.modifiedFiles.map(ue=>e.jsx(S,{wrap:!0,className:"bg-white/[0.08] font-mono text-[11px] text-white/74",children:ue},ue)):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No changed files listed"})})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(Na,{className:"size-4 text-fuchsia-200"}),e.jsx("span",{children:"Git refs"})]}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[[Se,Je].filter(ue=>ue.length>0).map((ue,$e)=>e.jsxs("div",{className:"grid gap-2",children:[Se.length>0&&Je.length>0?e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:$e===0?"Linked in completion report":"Other recorded refs"}):null,ue.map(Xe=>{const Ge=RL[Xe.refType],re=e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{className:Ge.className,children:Ge.label}),e.jsx("div",{className:"font-mono text-sm text-white/84",children:Xe.refValue})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Xe.displayTitle||Xe.repository||Xe.provider})]});return Xe.url?e.jsxs("a",{href:Xe.url,target:"_blank",rel:"noreferrer",className:"group block",children:[re,e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1 text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:["Open ref",e.jsx(Ks,{className:"size-3.5 transition group-hover:translate-x-0.5 group-hover:-translate-y-0.5"})]})]},Xe.id):e.jsx("div",{children:re},Xe.id)})]},`git-group-${$e}`)),he.length===0?e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No git refs recorded"}):null]})]})]})})]}):null,e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs($i,{eyebrow:"Work done",title:"Execution ledger",description:"Surface tracked work, credited work, and manual adjustments without opening the timer history.",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Bs,{label:"Tracked total",value:Di(z.task.time.totalTrackedSeconds)}),e.jsx(Bs,{label:"Credited total",value:Di(z.task.time.totalCreditedSeconds)}),e.jsx(Bs,{label:"Live work",value:Di(z.task.time.liveCreditedSeconds)}),e.jsx(Bs,{label:"Manual adjustments",value:Di(z.task.time.manualAdjustedSeconds)})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Today credited ",Di(z.task.time.todayCreditedSeconds??0)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Live tracked ",Di(z.task.time.liveTrackedSeconds)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Active runs ",z.task.time.activeRunCount]})]})]}),e.jsxs($i,{eyebrow:"Workflow health",title:"Signal scan",description:"A fast read on how ready this work item is for execution and closeout.",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{label:"Closeout readiness",value:Ne!=null&&Ne.workSummary||Se.length>0?"Evidence present":"Needs closeout evidence",hint:(xe=Ne==null?void 0:Ne.modifiedFiles)!=null&&xe.length?`${Ne.modifiedFiles.length} changed file${Ne.modifiedFiles.length===1?"":"s"} listed`:"No changed-file evidence captured yet."}),e.jsx(Bs,{label:"Collaboration model",value:nt||K.length>0?"Human + bot":z.task.assignees&&z.task.assignees.length>0?"Shared human work":"Single owner",hint:K.length>0?`${K.length} bot assignee${K.length===1?"":"s"} attached`:"No bot assignee attached."})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Priority ",t(`common.enums.priority.${z.task.priority}`)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Effort ",t(`common.enums.effort.${z.task.effort}`)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Energy ",t(`common.enums.energy.${z.task.energy}`)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Duration ",Di(z.task.plannedDurationSeconds)]})]})]})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Action Point load"}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Total cost"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ke?Et(ke.totalCostAp):"Not calibrated"})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Today debit"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ke?Et(ke.spentTodayAp):"0 AP"})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Sustain rate"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ke?Xt(ke.sustainRateApPerHour):"0 AP/h"})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Expected duration"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ke?`${Math.round(ke.expectedDurationSeconds/3600)} h`:"No target"})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[(ye=z.task.splitSuggestion)!=null&&ye.shouldSplit?e.jsx(S,{className:"bg-amber-400/12 text-amber-100",children:"Split it"}):null,ke?e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Remaining ",Et(ke.remainingAp)]}):null,ke?e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Spent total ",Et(ke.spentTotalAp)]}):null,ke?e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ke.costBand}):null]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"This task only debits the Action Points you actually worked today. Marking it done does not consume the full estimate by itself."})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Today's Life Force context"}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Daily AP"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:v.data?`${Et(v.data.spentTodayAp)} / ${Et(v.data.dailyBudgetAp)}`:"Loading..."})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Instant headroom"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:v.data?Xt(v.data.instantFreeApPerHour):"Loading..."})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Forecast"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:v.data?`${Et(v.data.forecastAp)} / ${Et(v.data.dailyBudgetAp)}`:"Loading..."})]})]})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/58",children:[e.jsx("span",{children:"Current timer"}),e.jsx(Tt,{content:"This shows whether work is running on the task right now and how much time has been credited.",label:"Explain current timer"})]}),e.jsx("div",{className:"mt-3 text-white",children:ge?`${ge.timerMode==="planned"?"Planned":"Unlimited"} timer active with ${Math.floor(ge.creditedSeconds/60)} credited minutes.`:"No timer is running on this task right now."})]}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Task scheduling"}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Rule source"}),e.jsx("div",{className:"mt-2 text-white",children:z.task.schedulingRules?"Task-specific override":"Uses project defaults"})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Planned duration"}),e.jsx("div",{className:"mt-2 text-white",children:z.task.plannedDurationSeconds?`${Math.round(z.task.plannedDurationSeconds/60)} min`:"No duration target"})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/58",children:"Scheduling rules now live behind the guided modal flow instead of an inline editor. Use it to change eligible blocks, blocked contexts, and the planning duration without overcrowding the task page."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(H,{onClick:()=>b(!0),children:[e.jsx(bs,{className:"size-4"}),"Edit task scheduling"]}),e.jsx(et,{to:"/calendar",children:e.jsx(H,{variant:"secondary",children:"Open calendar workspace"})})]})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar status"}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(S,{className:_.tone==="blocked"?"bg-rose-500/14 text-rose-100":_.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:_.label}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:z.task.schedulingRules?"Task override":"Using project defaults"}),z.task.plannedDurationSeconds?e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:[Math.round(z.task.plannedDurationSeconds/60)," min target"]}):null]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"Forge checks these rules before a live run starts. If the current calendar context is blocked, you can still override with an explicit reason."}),_.context.length>0?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Current context"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:_.context.map(ue=>e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue},ue))})]}):null,_.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:_.conflicts.map(ue=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:ue},ue))}):null,e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:e.jsxs(H,{pending:W.isPending||q.isPending,pendingLabel:"Planning",onClick:()=>{y(null),x(!0)},children:[e.jsx(bs,{className:"size-4"}),"Time Box"]})})]})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Scheduled blocks"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:"Open a scheduled block to edit the day, the hour range, or the AP profile tied to this task."})]}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:F.length})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[F.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.03] px-4 py-4 text-sm text-white/55",children:"No future timeboxes are attached to this task yet."}):null,F.map(ue=>e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{y(ue),x(!0)},onKeyDown:$e=>{($e.key==="Enter"||$e.key===" ")&&($e.preventDefault(),y(ue),x(!0))},className:"rounded-[18px] border border-white/8 bg-[linear-gradient(180deg,rgba(26,32,49,0.86),rgba(16,21,34,0.86))] p-4 text-left transition hover:bg-[linear-gradient(180deg,rgba(30,36,54,0.92),rgba(18,23,37,0.92))]",children:[e.jsx("div",{className:"flex flex-wrap items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-2 font-medium leading-6 text-white",children:ue.title}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-sm text-white/58",children:[e.jsx(Va,{className:"size-3.5 shrink-0"}),a(ue.startsAt)," to ",a(ue.endsAt)]})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue.source}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue.status}),e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:Xt(on(ue).rateApPerHour)}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:Et(on(ue).totalAp)}),ue.overrideReason?e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue.overrideReason}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx("span",{className:"rounded-[999px] bg-white/[0.08] px-3 py-1 text-xs text-white/72",children:"Edit in guide"}),e.jsx(et,{to:`/calendar?timeboxId=${encodeURIComponent(ue.id)}`,onClick:$e=>$e.stopPropagation(),className:"rounded-[999px] bg-white/[0.08] px-3 py-1 text-xs text-white/72 transition hover:bg-white/[0.12]",children:"Open in calendar"})]})]},ue.id))]})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Gd,{entityType:"task",entityId:z.task.id,title:`${ce.label} notes`,description:`Capture real progress, blockers, and context in Markdown so the ${ce.noun} keeps a durable work log.`,invalidateQueryKeys:[["task-context",n.taskId],...z.task.projectId?[["project-board",z.task.projectId]]:[]]})}),e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Activity"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[z.activity.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/55",children:"No activity has been recorded for this task yet."}):null,z.activity.map(ue=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:Vd(ue)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:Xd(ue)}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:a(ue.createdAt)})]}),e.jsx(H,{variant:"ghost",className:"shrink-0",onClick:async()=>{await V.mutateAsync(ue.id)},children:"Remove"})]}),Za(ue)&&bl(ue)?e.jsx(et,{to:Za(ue),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:bl(ue)}):null]},ue.id))]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Timer sessions"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[z.taskRuns.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/55",children:"No timer sessions have been recorded for this task yet."}):null,z.taskRuns.map(ue=>{var $e,Xe,Ge,re,Ae;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:ue.actor}),e.jsx(S,{children:ae(ue.status)})]}),($e=ue.gitContext)!=null&&$e.branch||(Xe=ue.gitContext)!=null&&Xe.pullRequestNumber?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[(Ge=ue.gitContext)!=null&&Ge.branch?e.jsxs(S,{className:"bg-sky-500/12 text-sky-100",children:[e.jsx(Na,{className:"mr-1 size-3"}),ue.gitContext.branch]}):null,(re=ue.gitContext)!=null&&re.pullRequestNumber?e.jsxs(S,{className:"bg-fuchsia-500/12 text-fuchsia-100",children:[e.jsx(ul,{className:"mr-1 size-3"}),"PR #",ue.gitContext.pullRequestNumber]}):null,(Ae=ue.gitContext)!=null&&Ae.repository?e.jsx(S,{className:"bg-white/[0.08] text-white/68",children:ue.gitContext.repository}):null]}):null,e.jsx("div",{className:"mt-2 text-sm text-white/58",children:ue.note||t("common.labels.noRunNote")}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:a(ue.updatedAt)})]},ue.id)})]})]})]}),e.jsx(Bd,{open:m,goals:i.snapshot.goals,projects:i.snapshot.dashboard.projects,workItems:i.snapshot.workItems,tags:i.snapshot.tags,users:i.snapshot.users,editingTask:z.task,defaultUserId:z.task.userId??d,onRefreshEntities:i.refresh,currentCreditedSeconds:z.task.time.totalCreditedSeconds,onOpenChange:h,onAdjustTrackedTime:async ue=>{await E.mutateAsync(ue)},onSubmit:async(ue,$e)=>{$e&&await Q.mutateAsync({taskId:$e,patch:ue})}}),e.jsx(Qw,{open:c,onOpenChange:p,entityType:"task",entityId:z.task.id,targetLabel:z.task.title,currentCreditedSeconds:z.task.time.totalCreditedSeconds,pending:E.isPending,onSubmit:async ue=>{await E.mutateAsync(ue)}}),e.jsx(ew,{open:g,onOpenChange:ue=>{x(ue),ue||y(null)},tasks:[z.task],initialTaskId:z.task.id,lockedTaskId:z.task.id,editingTimebox:I,from:P.from,to:P.to,userIds:r,onCreateTimebox:async ue=>{await W.mutateAsync({...ue,userId:d??void 0})},onUpdateTimebox:async(ue,$e)=>{await q.mutateAsync({timeboxId:ue,patch:{...$e,userId:d??void 0}})},onDeleteTimebox:async ue=>{await G.mutateAsync(ue)}}),e.jsx(Jy,{open:f,onOpenChange:b,tasks:[z.task],onSave:async({taskId:ue,schedulingRules:$e,plannedDurationSeconds:Xe})=>{await Q.mutateAsync({taskId:ue,patch:{schedulingRules:$e,plannedDurationSeconds:Xe}}),await o.invalidateQueries({queryKey:["task-calendar-overview",n.taskId]})}}),e.jsx(Pa,{open:A,onOpenChange:T,eyebrow:`${ce.label} status`,title:"Change status",description:`Pick the state that best matches where this ${ce.noun} is right now.`,children:e.jsx("div",{className:"grid gap-3",children:Ao.map(ue=>{const $e=ue.icon,Xe=ue.status===z.task.status;return e.jsx("button",{type:"button",disabled:Xe||Q.isPending,className:`rounded-[22px] border px-4 py-4 text-left transition ${Xe?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.08]"}`,onClick:()=>void Fe(ue.status),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($e,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ue.label}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:ue.description})]})]})},ue.status)})})})]})}function Jg(t,s,a){var i;return((i=s.find(r=>r.id===t.goalId))==null?void 0:i.title)??a}function OL(t,s){return t.tagIds.map(a=>s.find(i=>i.id===a)).filter(Boolean)}function zL(t,s){(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),s())}function KL(t,s){switch(t.status){case"backlog":return{label:s.backlog,action:"start",icon:ta};case"focus":return{label:s.focus,action:"start",icon:ta};case"in_progress":return{label:s.in_progress,nextStatus:"done",action:"move",icon:ml};case"blocked":return{label:s.blocked,action:"start",icon:ta};default:return null}}function qL({tasks:t,timeline:s,goals:a,tags:i,notesSummaryByEntity:r,selectedTaskId:n,onSelectTask:l,onMove:o,onStartTask:d}){const{t:m,formatDate:h}=Gt(),c={backlog:m("common.dailyRunway.actionBacklog"),focus:m("common.dailyRunway.actionFocus"),in_progress:m("common.dailyRunway.actionProgress"),blocked:m("common.dailyRunway.actionBlocked")};return e.jsxs("div",{className:"grid min-w-0 gap-4 2xl:grid-cols-[minmax(0,1.3fr)_minmax(17rem,0.9fr)]",children:[e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:m("common.dailyRunway.runwayEyebrow")}),e.jsx(Tt,{content:"These are the tasks that matter most for today. Click a card to open the task details. Use Start to begin work immediately."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-white",children:m("common.dailyRunway.runwayTitle")})]}),e.jsx(S,{className:"shrink-0 text-[var(--primary)]",children:m(t.length===1?"common.dailyRunway.prioritiesOne":"common.dailyRunway.prioritiesOther",{count:t.length})})]}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:t.map((p,g)=>{const x=KL(p,c),f=OL(p,i).slice(0,2),b=n===p.id,A=la(r,"task",p.id).count;return e.jsxs("article",{role:"button",tabIndex:0,"aria-pressed":b,className:`grid w-full gap-3 rounded-[22px] px-4 py-4 text-left transition ${b?"bg-[linear-gradient(180deg,rgba(192,193,255,0.16),rgba(192,193,255,0.05))] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"bg-white/[0.03] hover:bg-white/[0.06]"}`,onClick:()=>l(p.id),onKeyDown:T=>zL(T,()=>l(p.id)),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:m("common.dailyRunway.runwayItem",{index:g+1})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(Qe,{kind:"goal",label:Jg(p,a,m("common.dailyRunway.unassigned")),compact:!0,gradient:!1}),p.time.activeRunCount>0?e.jsx(S,{className:"bg-emerald-500/12 text-emerald-200",children:"Live"}):null]}),e.jsx("div",{className:"mt-2",children:e.jsx(It,{kind:"task",label:p.title,variant:"heading",size:"md"})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:p.description||m("common.dailyRunway.noNote")})]}),e.jsx(S,{className:"shrink-0 self-start",children:p.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[p.points," xp"]}),e.jsx(Vs,{entityType:"task",entityId:p.id,count:A}),p.time.totalCreditedSeconds>0?e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[Math.floor(p.time.totalCreditedSeconds/60)," min tracked"]}):null,e.jsx(S,{className:"bg-white/[0.08] text-white/70",children:p.effort}),e.jsx(S,{className:"bg-white/[0.08] text-white/70",children:h(p.dueDate)}),f.map(T=>e.jsx(S,{className:"bg-white/[0.08]",style:{color:T.color},children:T.name},T.id))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:p.owner}),x?e.jsxs(H,{variant:x.action==="start"?"primary":"secondary",className:"px-3 py-2 text-[11px] uppercase tracking-[0.16em]",onClick:async T=>{if(T.stopPropagation(),x.action==="start"){await d(p.id);return}x.nextStatus&&await o(p.id,x.nextStatus)},children:[e.jsx(x.icon,{className:"mr-2 size-3.5"}),x.label]}):null]})]},p.id)})})]}),e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:m("common.dailyRunway.timelineEyebrow")}),e.jsx(Tt,{content:"This groups today's tasks by status, so you can see what is already moving, what is ready to start, what is blocked, and what is done."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-white",children:m("common.dailyRunway.timelineTitle")}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:s.map(p=>e.jsxs("div",{className:"min-w-0 overflow-hidden rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:p.label}),e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:p.tasks.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[p.tasks.slice(0,3).map(g=>e.jsxs("button",{type:"button",className:"flex min-w-0 items-center justify-between gap-3 overflow-hidden rounded-[16px] bg-white/[0.03] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>l(g.id),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(It,{kind:"task",label:g.title,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("div",{className:"mt-2",children:e.jsx(Qe,{kind:"goal",label:Jg(g,a,m("common.dailyRunway.unassigned")),compact:!0,gradient:!1})})]}),e.jsx(Ca,{className:"size-4 shrink-0 text-white/35"})]},g.id)),p.tasks.length===0?e.jsx("div",{className:"text-sm text-white/42",children:m("common.dailyRunway.emptyBucket")}):null]})]},p.id))})]})]})}const BL=5;function UL(){const t=new Date;t.setHours(0,0,0,0);const s=new Date(t);return s.setDate(s.getDate()+1),{start:t,end:s,from:t.toISOString(),to:s.toISOString()}}function WL(t,s){const a=new Date(t.startAt),i=new Date(t.endAt);return a<s.end&&i>s.start}function HL(t){if(t.isAllDay)return"All day";const s=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});return`${s.format(new Date(t.startAt))} - ${s.format(new Date(t.endAt))}`}function GL(){var x;const{t}=Gt(),s=Ct(),a=Ht(),i=u.useMemo(()=>UL(),[]),r=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],n=Me({queryKey:["forge-calendar-overview",i.from,i.to,...r],queryFn:()=>nn({from:i.from,to:i.to,userIds:r})}),l=s.snapshot.today.directive.task,o=s.snapshot.today.milestoneRewards.find(f=>!f.completed)??s.snapshot.today.milestoneRewards[0]??null,d=s.snapshot.risk.blockedTasks[0]??s.snapshot.risk.overdueTasks[0]??null,m=Math.max(0,s.snapshot.metrics.nextLevelXp-s.snapshot.metrics.currentLevelXp),h=u.useMemo(()=>{var f;return(((f=n.data)==null?void 0:f.calendar.events)??[]).filter(b=>!b.deletedAt&&b.status!=="cancelled"&&WL(b,i)).sort((b,A)=>new Date(b.startAt).getTime()-new Date(A.startAt).getTime())},[(x=n.data)==null?void 0:x.calendar.events,i]),c=h.slice(0,BL);if(!(s.snapshot.lifeForce!==void 0||l!==null||s.snapshot.overview.topTasks.length>0||s.snapshot.today.dueHabits.length>0||s.snapshot.today.dailyQuests.length>0||s.snapshot.today.milestoneRewards.length>0||h.length>0)&&!n.isLoading)return e.jsxs("div",{className:"grid gap-4",children:[e.jsx(mt,{title:"Today",titleText:"Today",description:"Start a task, earn XP, and keep today's work clear.",badge:`${s.snapshot.metrics.weeklyXp} weekly xp`}),e.jsx(rs,{eyebrow:t("common.todayPage.heroEyebrow"),title:t("common.todayPage.emptyTitle"),description:t("common.todayPage.emptyDescription"),action:e.jsx(et,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium whitespace-nowrap text-slate-950 transition hover:opacity-90",children:t("common.todayPage.emptyAction")})})]});const g=[{id:"hero",title:"Today",description:"Compact page header.",defaultWidth:12,defaultHeight:2,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(Oy,{children:e.jsx(mt,{title:"Today",titleText:"Today",description:(l==null?void 0:l.description)??"Start one real task, collect XP, and keep today's work moving.",badge:`${s.snapshot.metrics.weeklyXp} weekly xp`})})},{id:"life-force",title:"Life Force",description:"Instant headroom, AP use today, and tiredness signals.",defaultWidth:12,defaultHeight:3,minWidth:5,render:()=>e.jsx(sT,{selectedUserIds:s.selectedUserIds,fallbackLifeForce:s.snapshot.lifeForce,onRefresh:s.refresh})},{id:"metrics",title:"Live metrics",description:"XP, level, and momentum stay visible but lighter than before.",defaultWidth:5,defaultHeight:4,minWidth:4,render:({compact:f})=>e.jsx(zy,{children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs(le,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Weekly XP"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-[var(--primary)]",children:s.snapshot.metrics.weeklyXp}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[s.snapshot.metrics.totalXp," total XP"]})]}),e.jsxs(le,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Level"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:s.snapshot.metrics.level}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[m," xp to the next level"]}),f?null:e.jsx("div",{className:"mt-3",children:e.jsx(Gs,{value:s.snapshot.metrics.currentLevelXp/s.snapshot.metrics.nextLevelXp*100,tone:"tertiary"})})]}),e.jsxs(le,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Momentum"}),e.jsxs("div",{className:"mt-2 font-display text-4xl text-white",children:[s.snapshot.metrics.momentumScore,"%"]}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[s.snapshot.metrics.streakDays," day streak"]})]}),e.jsxs(le,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Next reward"}),e.jsx("div",{className:"mt-2 text-base font-semibold text-white",children:(o==null?void 0:o.title)??"Keep showing up"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:(o==null?void 0:o.progressLabel)??"The next visible win comes from a task completion or aligned habit check-in."})]})]})})},{id:"runway",title:"Runway",description:"The execution lane itself can be widened or narrowed.",defaultWidth:7,defaultHeight:6,minWidth:5,render:()=>e.jsx(Ky,{children:e.jsx(qL,{tasks:s.snapshot.overview.topTasks,timeline:s.snapshot.today.timeline,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:(l==null?void 0:l.id)??null,onSelectTask:f=>a(`/tasks/${f}`),onStartTask:async f=>{await s.startTaskNow(f)},onMove:async(f,b)=>{await s.patchTaskStatus(f,b)}})})},{id:"calendar",title:"Calendar",description:"Today's events stay grouped with their results instead of splitting search from outcome.",defaultWidth:5,defaultHeight:5,minWidth:4,render:({compact:f})=>e.jsx(qy,{children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"inline-flex size-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--primary)]/14 text-[var(--primary)]",children:e.jsx(bs,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Today's calendar"}),e.jsx("div",{className:"text-sm font-semibold text-white",children:new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(i.start)}),e.jsxs("div",{className:"text-sm text-white/58",children:[h.length," event",h.length===1?"":"s"]})]})]}),e.jsxs(et,{to:"/calendar",className:"inline-flex shrink-0 items-center gap-2 rounded-full bg-white/[0.06] px-3 py-2 text-xs font-medium text-white/72 transition hover:bg-white/[0.1] hover:text-white",children:["Open calendar",e.jsx(wm,{className:"size-3.5"})]})]}),h.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:"Nothing is scheduled yet for today."}):c.map(b=>e.jsxs("button",{type:"button",className:"grid min-w-0 gap-2 rounded-[18px] bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>a("/calendar"),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:b.title}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:HL(b)})]}),e.jsx(S,{className:"shrink-0 bg-white/[0.08] text-white/72",children:b.originType==="native"?"Forge":b.originType})]}),!f&&b.description?e.jsx("div",{className:"line-clamp-2 text-sm leading-6 text-white/52",children:b.description}):null]},b.id))]})})},{id:"focus",title:"Current focus",description:"Current task, comeback task, and due habits stay in one movable stack.",defaultWidth:12,defaultHeight:4,minWidth:6,render:({compact:f})=>{var b;return e.jsx(By,{children:e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Current task"}),l?e.jsx(Vs,{entityType:"task",entityId:l.id,count:((b=s.snapshot.dashboard.notesSummaryByEntity[`task:${l.id}`])==null?void 0:b.count)??0}):null]}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:(l==null?void 0:l.title)??"Pick a task from the runway"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(l==null?void 0:l.description)??"Once a task is active, the timer rail and this panel stay aligned."}),l?e.jsx("button",{type:"button",className:"mt-4 inline-flex min-h-10 items-center justify-center rounded-2xl bg-[rgba(192,193,255,0.16)] px-3.5 py-2 text-sm font-medium text-[var(--primary)] transition hover:bg-[rgba(192,193,255,0.24)]",onClick:async()=>{await s.startTaskNow(l.id)},children:"Start work"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Recovery task"}),e.jsx("div",{className:"mt-3 text-sm font-semibold text-white",children:(d==null?void 0:d.title)??"No blocked or overdue task is dominating today"}),f?null:e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:(d==null?void 0:d.description)??"If something slips, it will surface here as the clean comeback move."})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Due habits"}),e.jsx("div",{className:"mt-3 grid gap-2",children:s.snapshot.today.dueHabits.slice(0,f?2:3).map(A=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:A.title}),f?null:e.jsx("div",{className:"text-sm text-white/52",children:A.frequency})]}),e.jsxs(S,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[A.rewardXp," xp"]})]},A.id))})]})]})]})})}},{id:"time",title:"Clock",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:f})=>e.jsx(Ol,{compact:f})},{id:"weather",title:"Weather",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:f})=>e.jsx(ql,{compact:f})},{id:"mini-calendar",title:"Mini calendar",description:"Optional utility widget.",defaultWidth:4,defaultHeight:3,defaultHidden:!0,render:({compact:f})=>e.jsx(zl,{compact:f})},{id:"spotify",title:"Spotify",description:"Optional utility widget.",defaultWidth:4,defaultHeight:2,defaultHidden:!0,render:()=>e.jsx(Kl,{surfaceId:"today"})},{id:"quick-capture",title:"Quick capture",description:"Save a note or wiki draft without leaving Today.",defaultWidth:5,defaultHeight:3,defaultHidden:!0,render:({compact:f})=>{var b;return e.jsx(Bl,{compact:f,defaultUserId:s.selectedUserIds[0]??((b=s.snapshot.users[0])==null?void 0:b.id)??null})}}];return e.jsx(Zd,{surfaceId:"today",baseWidgets:g})}const QL=["restingHeartRate","heartRateVariabilitySDNN","vo2Max","oxygenSaturation","bodyMass","stepCount"];function am(t){return t?new Date(`${t}T12:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}):"No date yet"}function Zg(t,s){return s==="cumulative"?t.total??t.latest??t.maximum??t.average:t.latest??t.average??t.maximum??t.minimum}function hi(t,s){if(s==null)return"No reading";const a=t.unit==="steps"||t.unit==="flights"||t.unit==="kcal"||t.unit==="min"?0:(t.unit==="%",1);return`${s.toLocaleString(void 0,{maximumFractionDigits:a,minimumFractionDigits:a===0||s>=100?0:1})} ${t.unit}`}function Ov(t){return t.deltaValue==null?"No baseline yet":`${t.deltaValue>0?"+":""}${hi(t,t.deltaValue)}`}function VL(t){return t.deltaValue==null||t.deltaValue===0?"steady":t.deltaValue>0?"up":"down"}function rl(t){switch(t){case"recovery":return{ring:"border-[rgba(255,122,167,0.18)]",badge:"bg-[rgba(255,122,167,0.16)] text-[rgb(255,179,205)]",glow:"from-[rgba(255,122,167,0.2)] via-[rgba(109,76,255,0.06)] to-transparent"};case"cardio":return{ring:"border-[rgba(109,173,255,0.22)]",badge:"bg-[rgba(109,173,255,0.16)] text-[rgb(186,220,255)]",glow:"from-[rgba(109,173,255,0.22)] via-[rgba(64,108,255,0.08)] to-transparent"};case"breathing":return{ring:"border-[rgba(111,232,195,0.2)]",badge:"bg-[rgba(111,232,195,0.15)] text-[rgb(195,255,237)]",glow:"from-[rgba(111,232,195,0.2)] via-[rgba(29,154,123,0.08)] to-transparent"};case"composition":return{ring:"border-[rgba(247,211,110,0.18)]",badge:"bg-[rgba(247,211,110,0.15)] text-[rgb(255,235,176)]",glow:"from-[rgba(247,211,110,0.18)] via-[rgba(184,128,24,0.08)] to-transparent"};case"temperature":return{ring:"border-[rgba(255,153,102,0.18)]",badge:"bg-[rgba(255,153,102,0.16)] text-[rgb(255,214,190)]",glow:"from-[rgba(255,153,102,0.2)] via-[rgba(255,91,46,0.06)] to-transparent"};default:return{ring:"border-[rgba(163,174,208,0.16)]",badge:"bg-[rgba(163,174,208,0.14)] text-[rgb(220,228,255)]",glow:"from-[rgba(163,174,208,0.14)] via-[rgba(112,120,167,0.06)] to-transparent"}}}function zv(t){switch(t){case"restingHeartRate":case"walkingHeartRateAverage":case"heartRateRecoveryOneMinute":return cu;case"heartRateVariabilitySDNN":case"vo2Max":return Ut;case"oxygenSaturation":case"respiratoryRate":return Mj;case"bodyMass":case"bodyFatPercentage":case"leanBodyMass":return Aj;case"stepCount":case"flightsClimbed":case"appleExerciseTime":return Pj;case"basalEnergyBurned":return nl;default:return Cd}}function XL({metric:t,className:s}){const a=t.days.slice(-14).map(o=>Zg(o,t.aggregation)).filter(o=>o!=null);if(a.length===0)return e.jsx("div",{className:te("flex h-16 items-center justify-center rounded-[18px] border border-dashed border-white/8 bg-white/[0.025] text-xs text-white/36",s),children:"Waiting for daily points"});const i=Math.min(...a),r=Math.max(...a),n=Math.max(r-i,1),l=t.days.slice(-14);return e.jsx("div",{className:te("flex h-16 items-end gap-1 rounded-[18px] border border-white/8 bg-white/[0.025] px-3 py-2",s),children:l.map((o,d)=>{const m=Zg(o,t.aggregation),h=m==null?12:18+Math.round((m-i)/n*34),c=d===l.length-1;return e.jsx("div",{className:"flex min-w-0 flex-1 flex-col items-center justify-end gap-1",children:e.jsx("div",{className:te("w-full rounded-full bg-gradient-to-t from-white/28 to-white/60 transition",c&&"from-[var(--primary)] to-[rgba(171,232,255,0.9)]"),style:{height:h},title:`${o.dateKey}: ${m==null?"No reading":hi(t,m)}`})},`${t.metric}-${o.dateKey}`)})})}function Mo({title:t,description:s,metric:a}){const i=a?zv(a.metric):Cd,r=rl(a?a.category:"default"),n=a?VL(a):"steady";return e.jsxs(le,{className:te("relative overflow-hidden rounded-[28px] border bg-[rgba(12,18,36,0.82)] p-5 shadow-[0_18px_60px_rgba(4,8,18,0.3)]",r.ring),children:[e.jsx("div",{className:te("pointer-events-none absolute inset-0 bg-gradient-to-br opacity-90",r.glow)}),e.jsxs("div",{className:"relative grid gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:t}),e.jsx("div",{className:"text-sm leading-6 text-white/56",children:s})]}),e.jsx("div",{className:"rounded-[18px] border border-white/10 bg-white/[0.05] p-3 text-white/80",children:e.jsx(i,{className:"size-5"})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xl font-semibold text-white",children:a?hi(a,a.latestValue):"No signal yet"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-white/56",children:[a?e.jsx(S,{className:r.badge,children:a.label}):null,a?e.jsx(S,{className:te("border-none",n==="up"?"bg-[rgba(111,232,195,0.14)] text-[rgb(190,255,231)]":n==="down"?"bg-[rgba(255,122,167,0.14)] text-[rgb(255,193,215)]":"bg-white/[0.08] text-white/72"),children:Ov(a)}):null,a?e.jsxs(S,{tone:"meta",children:[a.coverageDays," days tracked"]}):null]}),e.jsx("div",{className:"text-xs text-white/48",children:a?`Latest reading on ${am(a.latestDateKey)}`:"Forge will populate this card as soon as HealthKit has recent readings."})]})]})]})}function YL(){const t=Ct(),s=Me({queryKey:["forge-vitals-view",...t.selectedUserIds],queryFn:async()=>(await fb(t.selectedUserIds)).vitals});if(s.isLoading)return e.jsx(zt,{title:"Loading body signals",description:"Reading recent HealthKit body metrics, recovery signals, and daily aggregates."});if(s.isError||!s.data)return e.jsx(ct,{error:s.error??new Error("Vitals data unavailable"),onRetry:()=>void s.refetch()});const a=s.data,i=QL.map(l=>a.metrics.find(o=>o.metric===l)??null),r=a.summary.categoryBreakdown,n=r.map(l=>({...l,metrics:a.metrics.filter(o=>o.category===l.category)}));return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1380px] gap-5",children:[e.jsx(mt,{title:"Vitals",description:"Forge now keeps a daily body-signals layer across recovery, cardio fitness, breathing, composition, temperature, and activity. Use this surface to spot drift early, not just admire numbers late.",badge:`${a.summary.metricCount} live metrics`}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[e.jsx(Mo,{title:"Recovery pulse",description:"Resting heart rate and HRV are the fastest read on load, stress, and whether today needs a gentler edge.",metric:i[0]??i[1]}),e.jsx(Mo,{title:"Cardio engine",description:"VO2 max and walking heart rate show whether baseline fitness is improving or whether your effort is costing more than usual.",metric:i[2]}),e.jsx(Mo,{title:"Breath and oxygen",description:"Respiratory rate and oxygen saturation help catch nights or stretches where recovery quality starts to slip.",metric:i[3]}),e.jsx(Mo,{title:"Body composition",description:"Mass and composition stay close to the daily story so progress is visible without flattening everything into weight alone.",metric:i[4]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(340px,0.9fr)]",children:[e.jsxs(le,{className:"overflow-hidden rounded-[30px] border-white/8 bg-[radial-gradient(circle_at_top_left,rgba(108,99,255,0.16),transparent_36%),linear-gradient(180deg,rgba(15,19,38,0.98),rgba(9,13,28,0.98))] p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Coverage"}),e.jsxs("div",{className:"text-2xl font-semibold text-white",children:[a.summary.trackedDays," tracked days across ",a.summary.metricCount," metrics"]}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/58",children:"The companion is compressing HealthKit into daily signal bands, so what you see here is designed for decisions: how your recovery is trending, where your physiology is changing, and which body systems are actually being observed consistently."})]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Latest snapshot ",am(a.summary.latestDateKey)]})]}),e.jsx("div",{className:"mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:r.map(l=>{const o=rl(l.category);return e.jsxs("div",{className:te("rounded-[22px] border bg-white/[0.03] p-4",o.ring),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(S,{className:o.badge,children:l.category}),e.jsxs("div",{className:"text-xs text-white/44",children:[l.coverageDays," days"]})]}),e.jsx("div",{className:"mt-3 text-2xl font-semibold text-white",children:l.metricCount}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:["active metric",l.metricCount===1?"":"s"]})]},l.category)})})]}),e.jsx(le,{className:"rounded-[30px] border-white/8 bg-[linear-gradient(180deg,rgba(13,19,37,0.96),rgba(10,14,30,0.96))] p-6",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Daily interpretation"}),e.jsx("div",{className:"text-lg font-semibold text-white",children:"Body signals should feel operational, not medical-chart dead."}),e.jsxs("div",{className:"grid gap-3 text-sm leading-6 text-white/58",children:[e.jsx("div",{children:"Lower resting heart rate paired with stable or rising HRV usually means recovery is holding."}),e.jsx("div",{children:"Rising walking heart rate, falling HRV, or a jump in respiratory rate usually means you are carrying more load than the calendar admits."}),e.jsx("div",{children:"Composition and temperature metrics move slower, but they make the fast signals easier to trust because you can see the surrounding body context."})]}),e.jsxs("div",{className:"mt-2 rounded-[22px] border border-white/8 bg-white/[0.035] p-4 text-sm text-white/70",children:[a.summary.latestMetricCount," metrics updated on the latest tracked day."]})]})})]}),e.jsx("section",{className:"grid gap-5",children:n.map(l=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:l.category}),e.jsxs("div",{className:"mt-1 text-2xl font-semibold text-white",children:[l.metrics.length," signals in this lane"]})]}),e.jsxs(S,{className:rl(l.category).badge,children:[l.coverageDays," days of coverage"]})]}),e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:l.metrics.map(o=>{const d=zv(o.metric),m=rl(o.category),h=o.days.at(-1);return e.jsxs(le,{className:te("overflow-hidden rounded-[28px] border bg-[linear-gradient(180deg,rgba(12,18,36,0.94),rgba(8,12,24,0.98))] p-5",m.ring),children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-[18px] border border-white/10 bg-white/[0.04] p-3 text-white/84",children:e.jsx(d,{className:"size-5"})}),e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:o.category}),e.jsx("div",{className:"text-xl font-semibold text-white",children:o.label}),e.jsxs("div",{className:"text-sm text-white/52",children:[o.coverageDays," tracked day",o.coverageDays===1?"":"s"]})]})]}),e.jsx(S,{className:m.badge,children:o.aggregation})]}),e.jsxs("div",{className:"mt-5 grid gap-4 md:grid-cols-[minmax(0,0.95fr)_minmax(220px,1.05fr)]",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Latest"}),e.jsx("div",{className:"mt-1 text-3xl font-semibold text-white",children:hi(o,o.latestValue)}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:o.latestDateKey?`Latest reading on ${am(o.latestDateKey)}`:"Waiting for the first successful reading"})]}),e.jsxs("div",{className:"grid gap-2 rounded-[22px] border border-white/8 bg-white/[0.03] p-4 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Baseline"}),e.jsx("span",{className:"font-medium text-white",children:hi(o,o.baselineValue)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Delta"}),e.jsx("span",{className:te("font-medium",o.deltaValue==null?"text-white/58":o.deltaValue>0?"text-[rgb(190,255,231)]":o.deltaValue<0?"text-[rgb(255,198,219)]":"text-white"),children:Ov(o)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Latest samples"}),e.jsx("span",{className:"font-medium text-white",children:(h==null?void 0:h.sampleCount)??0})]})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx(XL,{metric:o}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-white/48",children:[e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.025] px-3 py-2",children:[e.jsx("div",{children:"Min"}),e.jsx("div",{className:"mt-1 font-medium text-white/78",children:hi(o,(h==null?void 0:h.minimum)??null)})]}),e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.025] px-3 py-2",children:[e.jsx("div",{children:"Average"}),e.jsx("div",{className:"mt-1 font-medium text-white/78",children:hi(o,(h==null?void 0:h.average)??null)})]}),e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.025] px-3 py-2",children:[e.jsx("div",{children:"Max"}),e.jsx("div",{className:"mt-1 font-medium text-white/78",children:hi(o,(h==null?void 0:h.maximum)??null)})]})]})]})]})]},o.metric)})})]},l.category))})]})}function JL(t){const s=[];let a,i;for(const r of t){const n=r.trim();if(!n)continue;const l=n.indexOf(":");if(l<=0){s.push({label:"Note",value:n});continue}const o=n.slice(0,l).trim(),d=n.slice(l+1).trim();if(!d)continue;const m=o.toLowerCase();if(m==="title"){a=d;continue}if(m==="summary"){i=d;continue}s.push({label:o,value:d})}return{title:a,summary:i,rows:s}}function ZL(t){const s=[],a=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let i=0,r=null;for(;(r=a.exec(t))!==null;){if(r.index>i&&s.push({type:"text",value:t.slice(i,r.index)}),r[1]&&r[2]){const n=r[2].trim(),l=r[1].startsWith("!"),o=n.indexOf("|"),d=o>=0?n.slice(0,o).trim():n,m=o>=0?n.slice(o+1).trim():d;if(d.toLowerCase().startsWith("forge:")){const[,h,...c]=d.split(":");s.push({type:"forge-link",entityType:h??"",entityId:c.join(":").trim(),label:m})}else s.push({type:"wiki-link",target:d,label:m,embed:l})}else r[3]&&r[4]?s.push({type:"link",label:r[3],href:r[4].trim()}):r[5]?s.push({type:"code",value:r[5]}):r[6]?s.push({type:"strong",value:r[6]}):r[7]&&s.push({type:"em",value:r[7]});i=a.lastIndex}return i<t.length&&s.push({type:"text",value:t.slice(i)}),s}function e_(t){const s=t.replace(/\r/g,"").split(`
58
+ `)}if(c.provider==="microsoft"&&Y==="credentials"){if(Ne)return"Save these Microsoft settings before starting sign-in.";if(!Ne&&!G.clientId&&!ge)return E.setupMessage}if(c.provider==="macos_local"&&(Y==="credentials"||Y==="discovery")&&A!=="full_access")return A==="unavailable"?"This provider is only available on macOS, because Forge uses EventKit to access the host machine's calendar store.":"Grant Calendar full access for Forge on this Mac before discovering host calendars."},ae=async(Y,ee)=>{try{const{session:xe}=await qN(Y);if(k(xe),xe.status==="authorized"&&xe.discovery){ce(xe.discovery),x(null);return}if(xe.status==="error"||xe.status==="expired"){x(xe.error??"Google sign-in did not complete. Start the guided sign-in again.");return}ee!=null&&ee.afterPopupClose}catch(xe){x(xe instanceof Error?xe.message:"Forge could not confirm the Google sign-in session.")}},Fe=async(Y,ee)=>{try{const{session:xe}=await WN(Y);if(P(xe),xe.status==="authorized"&&xe.discovery){ce(xe.discovery),x(null);return}if(xe.status==="error"||xe.status==="expired"){x(xe.error??"Microsoft sign-in did not complete. Start the guided sign-in again.");return}ee!=null&&ee.afterPopupClose}catch(xe){x(xe instanceof Error?xe.message:"Forge could not confirm the Microsoft sign-in session.")}},ie=async()=>{var Y;try{if(nt)throw new Error(Kg(nt,j.allowedOrigins));if(!j.isReadyForPairing)throw new Error(zg());x(null),b(null);const{session:ee}=await KN({label:ci("google",c.label),browserOrigin:fe||void 0});if(!ee.authUrl)throw new Error("Forge could not prepare the Google sign-in URL.");if(k(ee),(Y=me.current)==null||Y.close(),me.current=window.open(ee.authUrl,"forge-google-calendar-auth","popup=yes,width=520,height=720,resizable=yes,scrollbars=yes"),!me.current)throw new Error("The Google sign-in popup was blocked. Allow popups for Forge and try again.");me.current.focus()}catch(ee){F(),x(ee instanceof Error?ee.message:"Forge could not start the Google sign-in flow.")}},Be=async()=>{var Y;try{if(!M.isValid)throw new Error("Enter a valid Microsoft client ID and redirect URI before starting sign-in.");if(Ne)throw new Error("Save the Microsoft settings in this guided flow before starting sign-in.");if(Ce.isPending)throw new Error("Wait for Forge to finish saving the Microsoft settings before starting sign-in.");x(null),ke(null),b(null);const{session:ee}=await BN({label:ci("microsoft",c.label)});if(!ee.authUrl)throw new Error("Forge could not prepare the Microsoft sign-in URL.");if(P(ee),(Y=me.current)==null||Y.close(),me.current=window.open(ee.authUrl,"forge-microsoft-calendar-auth","popup=yes,width=520,height=720,resizable=yes,scrollbars=yes"),!me.current)throw new Error("The Microsoft sign-in popup was blocked. Allow popups for Forge and try again.");me.current.focus()}catch(ee){O(),x(ee instanceof Error?ee.message:"Forge could not start the Microsoft sign-in flow.")}},at=u.useMemo(()=>[{id:"provider",eyebrow:"Connection",title:"Choose the calendar provider Forge should connect to",description:"macOS local uses EventKit to access the calendars already configured on this Mac, Apple uses autodiscovery from caldav.icloud.com, Google uses a localhost Authorization Code + PKCE flow, Exchange Online uses guided Microsoft sign-in in read-only mode, and custom CalDAV stays available for everything else.",render:(Y,ee)=>e.jsxs("div",{className:"grid gap-5",children:[e.jsx(oe,{label:"Provider",description:"Each setup path is guided. Forge discovers calendars before anything is saved.",children:e.jsx(St,{value:Y.provider,onChange:xe=>{b(null),y(null),x(null),ke(null),F(),O(),ee(tu(xe))},options:[{value:"google",label:"Google Calendar",description:"Use Google sign-in with Authorization Code + PKCE, let Forge exchange the code on the backend, and store a per-user refresh token server-side."},{value:"apple",label:"Apple Calendar",description:"Start from https://caldav.icloud.com and autodiscover calendars with your app password."},{value:"microsoft",label:"Exchange Online",description:"Save the Microsoft app registration fields in Settings, then sign in with Microsoft and mirror selected Exchange Online calendars in read-only mode."},{value:"macos_local",label:"Calendars On This Mac",description:"Use EventKit to access the calendars already configured in Calendar.app on this host machine and avoid reconnecting those same accounts manually."},{value:"caldav",label:"Custom CalDAV",description:"Use a CalDAV base URL for Nextcloud, Fastmail, Baikal, and other compatible providers."}]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 text-white",children:[e.jsx(Df,{className:"size-4 text-[var(--primary)]"}),e.jsx("div",{className:"font-medium",children:"Dedicated write calendar"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:Y.provider==="microsoft"?"Exchange Online is read-only for now. Forge mirrors selected calendars into Forge, but it does not publish work blocks or owned timeboxes back to Microsoft.":e.jsxs(e.Fragment,{children:["Forge writes work blocks and owned timeboxes into a dedicated calendar named"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"}),"."]})})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 text-white",children:[e.jsx(rr,{className:"size-4 text-[var(--primary)]"}),e.jsx("div",{className:"font-medium",children:"Discovery first"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:Y.provider==="google"?"Forge opens a Google sign-in popup, exchanges the authorization code on the backend, stores a per-user refresh token, and then discovers the writable calendars for that account.":Y.provider==="macos_local"?"Forge asks macOS for Calendar access, discovers the host calendars grouped by account source, and replaces overlapping remote connections instead of keeping two copies.":Y.provider==="microsoft"?"Forge starts a Microsoft sign-in popup, then discovers the calendars available to that account before you choose what to mirror.":"Forge discovers the actual calendar collections before you choose which ones to mirror and which one should receive owned timeboxes."})]})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Setup guide"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"These are the exact setup steps for the selected provider. They stay inside this guided flow so Settings can stay focused on connection health and actions."}),e.jsx("div",{className:"mt-4",children:e.jsx(M6,{provider:Y.provider,compact:!0})})]})]})},{id:"credentials",eyebrow:"Credentials",title:c.provider==="google"?"Sign in with Google":c.provider==="macos_local"?"Use the calendars already configured on this Mac":c.provider==="apple"?"Provide the Apple account email and app-specific password":c.provider==="microsoft"?"Sign in with Microsoft":"Provide the custom CalDAV base URL and credentials",description:c.provider==="google"?"Review the Google desktop OAuth client, save a local override only if you need one, then start the popup and let Forge finish the PKCE exchange on the backend.":c.provider==="macos_local"?"Forge requests Calendar access through EventKit, discovers sources from Calendar.app, then lets you choose which host calendars to mirror and where Forge should write.":c.provider==="apple"?"Apple discovery starts from https://caldav.icloud.com, so you only need the Apple ID email and app password here.":c.provider==="microsoft"?"Forge uses the Microsoft client ID, tenant, and redirect URI saved in Settings -> Calendar, then runs a guided popup sign-in.":"Forge stores the secrets securely, then discovers the available calendars before anything is saved.",render:(Y,ee)=>{var xe;return e.jsxs("div",{className:"grid gap-4",children:[e.jsx(oe,{label:"Connection label",description:"This is the readable label Forge shows in settings and the calendar health cards.",children:e.jsx(be,{value:Y.label,onChange:ye=>ee({label:ye.target.value}),placeholder:yd[Y.provider].label})}),Y.provider==="macos_local"?e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,32,48,0.98),rgba(11,18,30,0.98))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"macOS Calendar access"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Forge uses EventKit to read and write the calendars already configured in Calendar.app on this Mac. Grant Calendar full access, then discover the available account sources."})]}),e.jsx(S,{className:A==="full_access"?"bg-emerald-500/16 text-emerald-100":"bg-white/[0.08] text-white/72",children:A==="full_access"?"Full access":A.replaceAll("_"," ")})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs(H,{type:"button",onClick:()=>void Ee.mutateAsync(),pending:Ee.isPending,pendingLabel:"Waiting for macOS",children:[e.jsx(rr,{className:"size-4"}),"Request Calendar access"]}),e.jsxs(H,{type:"button",variant:"secondary",onClick:()=>void je.mutateAsync(),pending:je.isPending,pendingLabel:"Checking",children:[e.jsx(sa,{className:"size-4"}),"Check access"]}),e.jsxs(H,{type:"button",onClick:()=>void J.mutateAsync(),disabled:A!=="full_access",pending:J.isPending,pendingLabel:"Discovering",children:[e.jsx(sa,{className:"size-4"}),"Discover host calendars"]})]}),(xe=I==null?void 0:I.sources)!=null&&xe.length?e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Host calendar sources"}),I.sources.map(ye=>{const ue=Y.sourceId===ye.sourceId;return e.jsxs("button",{type:"button",className:`rounded-[20px] border px-4 py-3 text-left transition ${ue?"border-[var(--primary)]/40 bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,onClick:()=>{ee({sourceId:ye.sourceId}),ce({provider:"macos_local",accountLabel:ye.accountLabel,serverUrl:Y.serverUrl,principalUrl:null,homeUrl:null,calendars:ye.calendars})},children:[e.jsx("div",{className:"font-medium",children:ye.accountLabel||ye.sourceTitle}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[ye.sourceType," · ",ye.calendars.length," ","calendars"]})]},ye.sourceId)})]}):null]})}):Y.provider==="google"?e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,32,48,0.98),rgba(11,18,30,0.98))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"How Google sign-in works"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Start the popup from the host running Forge. Google returns to Forge on localhost, Forge completes the PKCE exchange on the backend, then Forge discovers the calendars for that account."})]}),e.jsx(S,{className:"bg-emerald-500/16 text-emerald-100",children:"Auth code + PKCE"})]}),e.jsxs("div",{className:"mt-4 rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:[e.jsxs("div",{children:["Forge runtime:"," ",e.jsx("span",{className:"font-medium text-white",children:j.appBaseUrl})]}),e.jsxs("div",{className:"break-all",children:["Redirect URI:"," ",e.jsx("span",{className:"font-medium text-white",children:j.redirectUri})]}),e.jsxs("div",{className:"break-all",children:["Redirect origin:"," ",e.jsx("span",{className:"font-medium text-white",children:Se||"Unavailable"})]}),e.jsxs("div",{children:["Allowed local browser origins:"," ",e.jsx("span",{className:"font-medium text-white",children:j.allowedOrigins.join(", ")})]}),e.jsxs("div",{className:"break-all",children:["Detected browser origin:"," ",e.jsx("span",{className:"font-medium text-white",children:fe||"Unavailable"})]})]}),e.jsx("div",{className:"mt-4 rounded-[18px] bg-white/[0.04] p-4",children:Z?e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Google OAuth override"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Save both the client ID and client secret only when this Forge install should use a different Google desktop OAuth app than the packaged default."})]}),e.jsx("button",{type:"button","aria-label":"Done editing Google OAuth client",className:"inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.06] text-white/72 transition hover:bg-white/[0.12] hover:text-white",onClick:()=>{$(null);const ye=Kn(j);D(ye),V(!1)},children:e.jsx(_o,{className:"size-4"})})]}),e.jsxs(oe,{label:"Client ID",description:"Override the packaged Google desktop-app client ID for this Forge install.",children:[e.jsx(be,{"aria-label":"Client ID",value:v.clientId,onChange:ye=>{$(null),D({...v,clientId:ye.target.value})},placeholder:"1234567890-abcdef.apps.googleusercontent.com"}),U.issues.clientId?e.jsx("p",{className:"mt-2 text-sm text-rose-200",children:U.issues.clientId}):null]}),e.jsxs(oe,{label:"Client secret",description:"Override the packaged Google desktop-app client secret for this Forge install.",children:[e.jsx(be,{"aria-label":"Client secret",value:v.clientSecret,onChange:ye=>{$(null),D({...v,clientSecret:ye.target.value})},placeholder:"GOCSPX-..."}),U.issues.clientSecret?e.jsx("p",{className:"mt-2 text-sm text-rose-200",children:U.issues.clientSecret}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(H,{type:"button",onClick:()=>void Ke.mutateAsync(v),disabled:!he||!U.isValid,pending:Ke.isPending,pendingLabel:"Saving",children:"Save Google OAuth override"}),e.jsx(H,{type:"button",variant:"secondary",onClick:()=>{$(null),D({clientId:"",clientSecret:""})},disabled:Ke.isPending||!L.clientId&&!L.clientSecret&&v.clientId.length===0&&v.clientSecret.length===0,children:L.clientId||L.clientSecret?"Clear override":"Use packaged default"})]})]}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"grid min-w-0 gap-3",children:e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate font-medium text-white",children:"Google OAuth client"}),e.jsx(S,{className:j.storedClientId||j.storedClientSecret?"bg-emerald-500/16 text-emerald-100":"bg-white/[0.08] text-white/72",children:j.storedClientId||j.storedClientSecret?"Stored on server":"Using packaged default"}),e.jsx(Tt,{content:"Forge ships with a packaged Google desktop OAuth client by default. Save both fields only when this Forge install should use a different client ID and client secret pair.",label:"Explain Google OAuth client",className:"shrink-0"})]})}),e.jsx("button",{type:"button","aria-label":"Edit Google OAuth client",className:"inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.06] text-white/72 transition hover:bg-white/[0.12] hover:text-white",onClick:()=>{$(null),V(!0)},children:e.jsx(Pi,{className:"size-4"})})]})}),e.jsx(oe,{label:"Effective client ID",description:"This is the Google desktop-app client ID Forge will use right now.",children:e.jsx("div",{className:"flex min-h-11 min-w-0 items-center overflow-hidden rounded-[18px] border border-white/8 bg-black/20 px-4 text-sm text-white/38",children:e.jsx("span",{className:"block min-w-0 truncate",title:j.clientId,children:j.clientId})})}),e.jsx(oe,{label:"Effective client secret",description:"Forge uses this value on the local backend when exchanging and refreshing Google tokens.",children:e.jsx("div",{className:"flex min-h-11 min-w-0 items-center overflow-hidden rounded-[18px] border border-white/8 bg-black/20 px-4 text-sm text-white/38",children:e.jsx("span",{className:"block min-w-0 truncate",title:j.clientSecret||"",children:j.clientSecret||""})})})]})}),B?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/72",children:B}):null,e.jsx("div",{className:"mt-4 rounded-[18px] border border-sky-400/20 bg-sky-400/10 px-4 py-3 text-sm leading-6 text-sky-50",children:"If you open Forge on a phone or another remote route, Google redirects to localhost on that other device instead of back to Forge."}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs(H,{type:"button",onClick:()=>void ie(),disabled:!j.isReadyForPairing||!Je||he||Ke.isPending,pending:(N==null?void 0:N.status)==="pending",pendingLabel:"Waiting for Google",children:[e.jsx(Ra,{className:"size-4"}),(N==null?void 0:N.status)==="authorized"?"Sign in again":"Sign in with Google"]}),N!=null&&N.accountLabel?e.jsxs(S,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(_o,{className:"mr-1 size-3.5"}),N.accountLabel]}):null]})]})}):Y.provider==="microsoft"?e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,32,48,0.98),rgba(11,18,30,0.98))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Guided Microsoft setup"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Save the Microsoft app registration details for this Forge instance here, optionally test them, then continue into the Microsoft sign-in popup. Exchange Online stays read-only for now."})]}),e.jsx(S,{className:"bg-sky-400/12 text-sky-100",children:"Read only"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsxs(oe,{label:"Microsoft client ID",description:"Use the Application (client) ID from the Microsoft Entra app registration for this Forge instance.",children:[e.jsx(be,{value:W.clientId,onChange:ye=>{ke(null),q(ue=>({...ue,clientId:ye.target.value}))},placeholder:"00000000-0000-0000-0000-000000000000"}),M.issues.clientId?e.jsx("div",{className:"text-sm text-rose-300",children:M.issues.clientId}):null]}),e.jsx(oe,{label:"Tenant / authority",description:"Use common unless you need a tenant-specific authority.",children:e.jsx(be,{value:W.tenantId,onChange:ye=>{ke(null),q(ue=>({...ue,tenantId:ye.target.value}))},placeholder:"common"})})]}),e.jsxs(oe,{label:"Redirect URI",description:"Register this exact Forge callback URI in the Microsoft app registration.",children:[e.jsx(be,{value:W.redirectUri,onChange:ye=>{ke(null),q(ue=>({...ue,redirectUri:ye.target.value}))},placeholder:"http://127.0.0.1:4317/api/v1/calendar/oauth/microsoft/callback"}),M.issues.redirectUri?e.jsx("div",{className:"text-sm text-rose-300",children:M.issues.redirectUri}):null]}),e.jsx("div",{className:"mt-4 rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"Forge saves the client ID, tenant, and redirect URI for this local instance, then handles Microsoft sign-in in a popup."}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsx(H,{type:"button",onClick:()=>void Ce.mutateAsync(W),disabled:!M.isValid,pending:Ce.isPending,pendingLabel:"Saving",children:"Save Microsoft settings"}),e.jsx(H,{type:"button",variant:"secondary",onClick:()=>void Pe.mutateAsync(W),disabled:!M.isValid,pending:Pe.isPending,pendingLabel:"Testing",children:"Test Microsoft configuration"}),e.jsxs(H,{type:"button",onClick:()=>void Be(),disabled:!M.isValid||Ne||Ce.isPending,pending:(w==null?void 0:w.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(Ra,{className:"size-4"}),(w==null?void 0:w.status)==="authorized"?"Sign in again":"Sign in with Microsoft"]}),w!=null&&w.accountLabel?e.jsxs(S,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(_o,{className:"mr-1 size-3.5"}),w.accountLabel]}):null]}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"Save before sign-in. The Microsoft popup always uses the latest saved client ID, tenant, and redirect URI."}),e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"After sign-in, Forge will let you choose which Exchange Online calendars to mirror into the Calendar page."})]}),ge?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/72",children:ge}):null]})}):e.jsxs(e.Fragment,{children:[Y.provider==="caldav"?e.jsx(oe,{label:"CalDAV base URL",description:"Use the account-level CalDAV server URL, not an individual calendar collection URL.",children:e.jsx(be,{value:Y.serverUrl,onChange:ye=>ee({serverUrl:ye.target.value}),placeholder:"https://caldav.example.com"})}):null,Y.provider==="apple"?e.jsx(oe,{label:"Apple CalDAV base URL",children:e.jsx(be,{value:"https://caldav.icloud.com",disabled:!0})}):null,e.jsx(oe,{label:"Account email or username",children:e.jsx(be,{value:Y.username,onChange:ye=>ee({username:ye.target.value}),placeholder:"operator@example.com"})}),e.jsx(oe,{label:Y.provider==="apple"?"App-specific password":"Password or app password",children:e.jsx(be,{type:"password",value:Y.password,onChange:ye=>ee({password:ye.target.value}),placeholder:"Password"})})]})]})}},{id:"discovery",eyebrow:"Discovery",title:"Discover the calendars and choose what Forge should sync",description:c.provider==="microsoft"?"Select the Exchange Online calendars Forge should mirror into the Calendar page. This connection stays read-only for now.":c.provider==="macos_local"?ve?`Select the host-machine calendars Forge should mirror into the Calendar page. Forge already writes work blocks and timeboxes through ${ve}.`:"Select the host-machine calendars Forge should mirror into the Calendar page, then choose the host calendar Forge should write into for work blocks and timeboxes.":ve?`Select the calendars Forge should mirror into the Calendar page. Forge already writes work blocks and timeboxes through ${ve}.`:"Select the calendars Forge should mirror into the Calendar page, then choose the calendar Forge should write into for work blocks and timeboxes.",render:(Y,ee)=>e.jsxs("div",{className:"grid gap-4",children:[Y.provider==="google"?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(H,{type:"button",onClick:()=>void ie(),disabled:!j.isReadyForPairing||!Je,pending:(N==null?void 0:N.status)==="pending",pendingLabel:"Waiting for Google",children:[e.jsx(Ra,{className:"size-4"}),(N==null?void 0:N.status)==="authorized"?"Reconnect Google":"Sign in with Google"]}),f?e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[f.calendars.length," discovered"]}):null]}):Y.provider==="microsoft"?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(H,{type:"button",onClick:()=>void Be(),disabled:!M.isValid||Ne||Ce.isPending,pending:(w==null?void 0:w.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(Ra,{className:"size-4"}),(w==null?void 0:w.status)==="authorized"?"Reconnect Microsoft":"Sign in with Microsoft"]}),f?e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[f.calendars.length," discovered"]}):null]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(H,{pending:J.isPending,pendingLabel:"Discovering",onClick:()=>void J.mutateAsync(),disabled:Y.provider==="macos_local"&&A!=="full_access",children:[e.jsx(sa,{className:"size-4"}),Y.provider==="macos_local"?"Discover host calendars":"Discover calendars"]}),f?e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[f.calendars.length," discovered"]}):null]}),f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4 text-sm leading-6 text-white/64",children:[Y.provider==="macos_local"?"Discovered through the host calendar store":"Discovered through"," ",e.jsx("span",{className:"font-medium text-white",children:f.serverUrl}),f.homeUrl?e.jsxs(e.Fragment,{children:[" ","· home set"," ",e.jsx("span",{className:"font-medium text-white",children:f.homeUrl})]}):null]}),Y.provider!=="microsoft"&&ve?e.jsxs("div",{className:"rounded-[24px] border border-emerald-400/20 bg-emerald-400/10 p-4 text-sm leading-6 text-emerald-50",children:["Forge already writes work blocks and owned timeboxes through"," ",e.jsx("span",{className:"font-medium text-white",children:ve}),". This connection only needs a mirror selection."]}):null,e.jsx("div",{className:"grid gap-3",children:f.calendars.map(xe=>{const ye=Y.selectedCalendarUrls.includes(xe.url),ue=Y.forgeCalendarUrl===xe.url;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:Jr(xe)}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[xe.timezone||"No timezone exposed"," ·"," ",xe.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[xe.isForgeCandidate?e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge match"}):null,xe.isPrimary?e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:"Primary"}):null]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>ee({selectedCalendarUrls:ye?Y.selectedCalendarUrls.filter($e=>$e!==xe.url):[...Y.selectedCalendarUrls,xe.url]}),className:`rounded-full px-3 py-2 text-sm transition ${ye?"bg-[var(--primary)]/18 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.24)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:ye?"Mirrored":"Mirror into Forge"}),Y.provider!=="microsoft"&&!ve?e.jsx("button",{type:"button",onClick:()=>ee({forgeCalendarUrl:xe.url,createForgeCalendar:!1}),className:`rounded-full px-3 py-2 text-sm transition ${ue?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:ue?"Forge writes here":"Use for Forge writes"}):e.jsx(S,{className:Y.provider==="microsoft"?"bg-sky-400/12 text-sky-100":"bg-white/[0.08] text-white/74",children:Y.provider==="microsoft"?"Read only":"Shared target elsewhere"})]})]},xe.url)})}),Y.provider!=="microsoft"&&!ve?e.jsxs("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"No Forge calendar yet?"}),e.jsxs("p",{className:"mt-2 text-sm leading-6 text-white/60",children:["If none of the discovered calendars should receive Forge-owned work blocks and timeboxes, let Forge create a dedicated calendar named"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"}),"."]}),e.jsx("div",{className:"mt-4",children:e.jsx("button",{type:"button",onClick:()=>ee({forgeCalendarUrl:null,createForgeCalendar:!Y.createForgeCalendar}),className:`rounded-full px-3 py-2 text-sm transition ${Y.createForgeCalendar?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:Y.createForgeCalendar?"Forge will create one":"Create a new Forge calendar"})})]}):Y.provider==="microsoft"?e.jsx("div",{className:"rounded-[24px] border border-sky-400/20 bg-sky-400/10 p-4 text-sm leading-6 text-sky-50",children:"Exchange Online is connected through Microsoft Graph in read-only mode. Forge will mirror the calendars you select here, but it will keep work blocks and owned timeboxes local or publish them through another writable provider."}):e.jsxs("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] p-4 text-sm leading-6 text-white/60",children:["Forge will keep"," ",e.jsx("span",{className:"font-medium text-white",children:ve})," ","as the canonical write target instead of creating another Forge calendar on this connection."]})]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-4 py-6 text-sm leading-6 text-white/58",children:Y.provider==="google"?e.jsx(e.Fragment,{children:"Start the guided Google sign-in first. Forge will bring the discovered Google calendars back here as soon as the popup completes."}):Y.provider==="microsoft"?e.jsx(e.Fragment,{children:"Start the guided Microsoft sign-in first. Forge will bring the discovered Exchange Online calendars back here as soon as the popup completes."}):e.jsx(e.Fragment,{children:Y.provider==="macos_local"?"Grant macOS Calendar access and discover the host calendars first. If Calendar.app already aggregates Google, Exchange, or iCloud for this Mac, Forge will pick them up here without reconnecting those accounts.":e.jsxs(e.Fragment,{children:["Discover calendars after entering the credentials. For Apple, Forge starts from"," ",e.jsx("span",{className:"font-medium text-white",children:"https://caldav.icloud.com"})," ","and resolves the principal plus calendar home automatically."]})})})]})},{id:"review",eyebrow:"Review",title:"Confirm what Forge will mirror and where it will write",description:"This keeps the sync model explicit before the provider connection is saved.",render:Y=>{var ee,xe;return e.jsxs("div",{className:"grid gap-4",children:[Y.provider==="macos_local"&&Y.sourceId?e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/70",children:["Selected host source:"," ",e.jsx("span",{className:"font-medium text-white",children:((ee=I==null?void 0:I.sources.find(ye=>ye.sourceId===Y.sourceId))==null?void 0:ee.accountLabel)??((xe=I==null?void 0:I.sources.find(ye=>ye.sourceId===Y.sourceId))==null?void 0:xe.sourceTitle)??Y.sourceId})]}):null,e.jsxs("div",{className:"rounded-[26px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,31,42,0.96),rgba(10,16,26,0.96))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(Hs,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-xl text-white",children:ci(Y.provider,Y.label)}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:Y.provider==="google"?"Google Calendar":Y.provider==="macos_local"?"Calendars On This Mac":Y.provider==="apple"?"Apple Calendar":Y.provider==="microsoft"?"Exchange Online":"Custom CalDAV"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:["Mirrored calendars:"," ",e.jsx("span",{className:"font-medium text-white",children:Y.selectedCalendarUrls.length})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:["Forge writes:"," ",e.jsx("span",{className:"font-medium text-white",children:Y.provider==="microsoft"?"read only":Y.forgeCalendarUrl?"existing calendar":Y.createForgeCalendar?"new Forge calendar":ve?`shared target via ${ve}`:"not selected"})]})]}),Y.replaceConnectionIds.length>0?e.jsxs("div",{className:"mt-4 rounded-[20px] border border-amber-400/20 bg-amber-400/10 px-4 py-3 text-sm leading-6 text-amber-50",children:["Forge will replace ",Y.replaceConnectionIds.length," older overlapping connection",Y.replaceConnectionIds.length===1?"":"s"," for this same calendar account so only one visible copy remains.",o.filter(ye=>Y.replaceConnectionIds.includes(ye.id)).map(ye=>ye.label).join(", ")?` ${o.filter(ye=>Y.replaceConnectionIds.includes(ye.id)).map(ye=>ye.label).join(", ")}.`:""]}):null]})]})}}],[f,J.isPending,c.provider,Z,v,N,j.clientId,B,j.allowedOrigins,j.appBaseUrl,j.isLocalOnly,j.isReadyForPairing,j.redirectUri,Se,he,Je,nt,Ne,W,E.setupMessage,ge,M,Ke.isPending,Ce.isPending,G,Pe.isPending,E.isReadyForSignIn,E.redirectUri,I,w,we,ve]),Le=c.provider==="macos_local"&&c.replaceConnectionIds.length>0?"Replace and connect":"Connect provider";return e.jsx(Kt,{open:t,onOpenChange:s,eyebrow:"Calendar settings",title:"Connect a calendar provider",description:"Discover provider calendars first, choose which calendars Forge should mirror, and only choose a Forge write target when the runtime does not already have one.",value:c,onChange:Y=>{p(Y),f&&Y.provider!==f.provider&&b(null),Y.provider!=="macos_local"&&y(null)},draftPersistenceKey:"calendar.connection.new",steps:at,submitLabel:Le,pending:m,pendingLabel:"Connecting",error:g,resolveError:_e,initialStepId:i,onSubmit:async()=>{try{if(x(null),!f){x("Discover the available calendars before saving the connection.");return}if(c.selectedCalendarUrls.length===0){x("Select at least one calendar to mirror into Forge.");return}if(c.provider!=="microsoft"&&!c.forgeCalendarUrl&&!c.createForgeCalendar&&!we){x("Choose the calendar Forge should write into, ask Forge to create one, or keep using the existing shared Forge write target.");return}if(c.provider==="google"){if(!(N!=null&&N.sessionId)||N.status!=="authorized"){x("Complete the Google sign-in flow before saving this connection.");return}await d({provider:"google",label:ci("google",c.label),authSessionId:N.sessionId,selectedCalendarUrls:c.selectedCalendarUrls,forgeCalendarUrl:c.forgeCalendarUrl,createForgeCalendar:c.createForgeCalendar})}else if(c.provider==="apple")await d({provider:"apple",label:ci("apple",c.label),username:c.username.trim(),password:c.password.trim(),selectedCalendarUrls:c.selectedCalendarUrls,forgeCalendarUrl:c.forgeCalendarUrl,createForgeCalendar:c.createForgeCalendar});else if(c.provider==="microsoft"){if(!(w!=null&&w.sessionId)||w.status!=="authorized"){x("Complete the Microsoft sign-in flow before saving this connection.");return}await d({provider:"microsoft",label:ci("microsoft",c.label),authSessionId:w.sessionId,selectedCalendarUrls:c.selectedCalendarUrls})}else if(c.provider==="macos_local"){if(!c.sourceId){x("Choose which host calendar source Forge should connect before saving.");return}await d({provider:"macos_local",label:ci("macos_local",c.label),sourceId:c.sourceId,selectedCalendarUrls:c.selectedCalendarUrls,forgeCalendarUrl:c.forgeCalendarUrl,createForgeCalendar:c.createForgeCalendar,replaceConnectionIds:c.replaceConnectionIds})}else await d({provider:"caldav",label:ci("caldav",c.label),serverUrl:c.serverUrl.trim(),username:c.username.trim(),password:c.password.trim(),selectedCalendarUrls:c.selectedCalendarUrls,forgeCalendarUrl:c.forgeCalendarUrl,createForgeCalendar:c.createForgeCalendar});s(!1)}catch(Y){if(Y instanceof Ya&&Y.code==="calendar_connection_overlap"){const ee=Y.response,xe=Array.isArray(ee==null?void 0:ee.overlappingConnectionIds)?ee==null?void 0:ee.overlappingConnectionIds.filter(ye=>typeof ye=="string"):[];p(ye=>({...ye,replaceConnectionIds:xe})),x(`${Y.message} Submit again to replace the older overlapping connection${xe.length===1?"":"s"}.`);return}x(Y instanceof Error?Y.message:"Forge could not create this calendar connection.")}}})}function Lr(t){try{const s=new URL(t);return s.pathname.endsWith("/")||(s.pathname=`${s.pathname}/`),s.toString()}catch{return t}}function qg(t){switch(t){case"google":return"Google Calendar";case"apple":return"Apple Calendar";case"microsoft":return"Exchange Online";case"macos_local":return"Calendars On This Mac";case"caldav":default:return"Custom CalDAV"}}function K6(t){switch(t){case"google":return"Open Google guided flow";case"microsoft":return"Open Microsoft guided flow";case"macos_local":return"Open Mac calendar flow";default:return"Open guided setup"}}function q6(t){switch(t){case"google":case"microsoft":return rr;case"macos_local":return bs;case"apple":return bs;case"caldav":default:return Hs}}function B6(t){switch(t){case"microsoft":return"Read only";case"macos_local":return"Read + write";default:return"Read + write"}}function U6(t){switch(t){case"google":return"Local PKCE";case"microsoft":return"Guided sign-in";case"macos_local":return"Host machine";case"apple":return"App password";case"caldav":default:return"CalDAV credentials"}}function W6(t){switch(t){case"google":return"Sign in from the same machine running Forge. After connection, Forge can mirror the calendars you choose and reuse the current shared Forge write target, creating one only when the runtime does not already have one.";case"apple":return"Use your Apple ID email and app-specific password. Forge discovers your iCloud calendars before you choose what to mirror.";case"microsoft":return"Use the guided Microsoft sign-in flow. Forge mirrors the Exchange calendars you choose and keeps this provider read only.";case"macos_local":return"Use the calendars already configured in Calendar.app on this Mac. Forge requests Calendar access through macOS, discovers host calendars by account source, and replaces overlapping remote account connections instead of duplicating them.";case"caldav":default:return"Enter a CalDAV server URL and account credentials. Forge discovers the calendars on that account before you choose what to mirror."}}function Bg(t){return`${t} connection${t===1?"":"s"}`}function H6(){var me,se,we,ve,_;const t=pt(),[s,a]=ws(),[i,r]=u.useState(!1),[n,l]=u.useState("google"),[o,d]=u.useState(void 0),[m,h]=u.useState(null),[c,p]=u.useState([]),[g,x]=u.useState(!1),[f,b]=u.useState(null),[A,T]=u.useState(()=>aw()),I=Me({queryKey:["forge-operator-session"],queryFn:mr}),y=I.isSuccess,N=Me({queryKey:["forge-settings"],queryFn:pr,enabled:y}),k=Me({queryKey:["forge-calendar-connections"],queryFn:DN,enabled:y}),w=Me({queryKey:["forge-calendar-resources"],queryFn:YN,enabled:y}),P=async()=>{await Promise.all([t.invalidateQueries({queryKey:["forge-settings"]}),t.invalidateQueries({queryKey:["forge-calendar-connections"]}),t.invalidateQueries({queryKey:["forge-calendar-resources"]}),t.invalidateQueries({queryKey:["forge-calendar-overview"]}),Zt(t)])},j=De({mutationFn:GN,onSuccess:P}),R=De({mutationFn:F=>QN(F),onSuccess:P}),v=De({mutationFn:({connectionId:F,patch:O})=>VN(F,O),onSuccess:P}),D=De({mutationFn:F=>XN(F),onSuccess:P});u.useEffect(()=>{if(!y)return;const F=s.get("intent"),O=s.get("provider");if(F!=="connect")return;l(O==="apple"||O==="caldav"||O==="google"||O==="microsoft"||O==="macos_local"?O:"google"),d(O==="microsoft"?"credentials":void 0),r(!0);const ce=new URLSearchParams(s);ce.delete("intent"),ce.delete("provider"),a(ce,{replace:!0})},[y,s,a]);const L=u.useMemo(()=>{var F,O;return Vf(((F=w.data)==null?void 0:F.calendars)??[],((O=k.data)==null?void 0:O.connections)??[])},[(me=w.data)==null?void 0:me.calendars,(se=k.data)==null?void 0:se.connections]),Q=u.useMemo(()=>{const F=new Map;for(const O of L){const ce=F.get(O.connectionId)??[];ce.push(O),F.set(O.connectionId,ce)}return F},[L]),Z=u.useMemo(()=>{var O;const F={};for(const ce of((O=k.data)==null?void 0:O.connections)??[])F[ce.provider]=(F[ce.provider]??0)+1;return F},[(we=k.data)==null?void 0:we.connections]),V=u.useMemo(()=>rw(L,A.calendarColors),[L,A.calendarColors]),B=u.useMemo(()=>{var F;return(((F=k.data)==null?void 0:F.connections)??[]).find(O=>{var ce;return typeof((ce=O.config)==null?void 0:ce.forgeCalendarUrl)=="string"&&O.config.forgeCalendarUrl.trim().length>0})??null},[(ve=k.data)==null?void 0:ve.connections]),$=u.useMemo(()=>{var F;return((F=k.data)==null?void 0:F.connections.find(O=>O.id===m))??null},[k.data,m]),E=u.useMemo(()=>{var F;return((F=k.data)==null?void 0:F.connections.find(O=>O.id===f))??null},[k.data,f]),X=u.useMemo(()=>m?Q.get(m)??[]:[],[Q,m]),W=Me({queryKey:["forge-calendar-connection-discovery",m],queryFn:()=>HN(m),enabled:y&&m!==null});u.useEffect(()=>{if(!m){p([]),x(!1);return}const F=X.filter(O=>O.selectedForSync).map(O=>Lr(O.remoteId));p(F),x(!0)},[m,X]),u.useEffect(()=>{Q3(A)},[A]);const q=u.useMemo(()=>[{id:"mirrors",eyebrow:"Mirroring",title:"Choose which calendars Forge should mirror",description:"Unselected calendars stop showing up in Forge’s mirrored calendar views. The Forge write calendar stays available for work blocks and timeboxes.",render:(F,O)=>{var Ee,Ce;if(W.isLoading)return e.jsx("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-6 text-sm leading-6 text-white/58",children:"Rediscovering calendars for this connection."});if(W.isError||!((Ee=W.data)!=null&&Ee.discovery))return e.jsx("div",{className:"rounded-[24px] border border-rose-400/20 bg-rose-400/10 px-4 py-6 text-sm leading-6 text-rose-100",children:W.error instanceof Error?W.error.message:"Forge could not rediscover calendars for this connection."});const ce=W.data.discovery,J=($==null?void 0:$.provider)==="microsoft",je=typeof((Ce=$==null?void 0:$.config)==null?void 0:Ce.forgeCalendarUrl)=="string"?Lr($.config.forgeCalendarUrl):null;return e.jsx("div",{className:"grid gap-3",children:ce.calendars.map(Ke=>{const Pe=Lr(Ke.url),M=g?F.selectedCalendarUrls.includes(Pe):X.some(he=>he.selectedForSync&&Lr(he.remoteId)===Pe),U=je===Pe;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:Jr(Ke)}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[Ke.timezone||"No timezone exposed"," ·"," ",Ke.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[U&&!J?e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge writes here"}):null,J?e.jsx(S,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,Ke.isPrimary?e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:"Primary"}):null]})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:e.jsx("button",{type:"button",disabled:U&&!J,onClick:()=>O({selectedCalendarUrls:M?F.selectedCalendarUrls.filter(he=>he!==Pe):[...F.selectedCalendarUrls,Pe]}),className:`rounded-full px-3 py-2 text-sm transition ${U&&!J?"cursor-not-allowed bg-white/[0.05] text-white/35":M?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:U&&!J?"Always available for Forge writes":M?"Mirrored into Forge":"Do not mirror"})})]},Ke.url)})})}}],[$,W]);if(I.isLoading||N.isLoading||k.isLoading||w.isLoading)return e.jsx(gs,{eyebrow:"Settings · Calendar",title:"Loading calendar settings",description:"Checking the operator session and loading provider connections.",columns:2,blocks:6});if(I.isError)return e.jsx(ct,{eyebrow:"Settings · Calendar",error:I.error,onRetry:()=>void I.refetch()});if(N.isError||k.isError||w.isError||!((_=N.data)!=null&&_.settings)||!k.data||!w.data)return e.jsx(ct,{eyebrow:"Settings · Calendar",error:N.error??k.error??w.error??new Error("Calendar settings are unavailable."),onRetry:()=>{N.refetch(),k.refetch(),w.refetch()}});const{providers:G,connections:z}=k.data,ge=N.data.settings.calendarProviders.google,ke=N.data.settings.calendarProviders.microsoft;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(mt,{title:"Calendar settings",description:"Manage provider connections, review the shared Forge write target, and open guided setup only when you need to connect or reconfigure a provider.",badge:`${z.length} connection${z.length===1?"":"s"}`}),e.jsx(Aa,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(le,{className:"surface-section-panel grid gap-5 rounded-[30px] border",children:[e.jsxs("div",{className:"max-w-3xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Provider connections"}),e.jsxs("p",{className:"mt-2 text-sm leading-6 text-white/60",children:["Connect a provider here, then choose which calendars Forge should mirror. Writable providers publish work blocks and owned timeboxes through one shared"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"})," write target, creating it only when the runtime does not already have one."]})]}),e.jsx("div",{className:"grid gap-4 lg:grid-cols-2",children:G.map(F=>{const O=q6(F.provider),ce=Z[F.provider]??0,J=ce>0;return e.jsxs("div",{className:`flex min-h-[248px] flex-col rounded-[26px] border p-5 shadow-[inset_0_1px_0_var(--ui-border-subtle)] ${J?"border-emerald-400/24 bg-[linear-gradient(180deg,color-mix(in_srgb,#10b981_18%,var(--surface-panel)_82%),var(--ui-surface-2))]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]"}`,children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`rounded-[18px] p-3 ${J?"bg-emerald-400/16 text-emerald-100":"bg-[var(--primary)]/14 text-[var(--primary)]"}`,children:e.jsx(O,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"font-medium text-[var(--ui-ink-strong)]",children:F.label}),J?e.jsxs(e.Fragment,{children:[e.jsx(S,{className:"bg-emerald-400/16 text-emerald-50",children:"Connected"}),e.jsx(S,{className:"bg-white/[0.08] text-white/82",children:Bg(ce)})]}):null]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:W6(F.provider)}),J?e.jsxs("div",{className:"mt-3 text-sm text-emerald-100/88",children:["Forge already has"," ",Bg(ce)," for this provider. Open the guided flow again to add another account or reconfigure one."]}):null]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsx(S,{tone:"signal",className:"bg-[var(--primary)]/14 text-white/86",children:U6(F.provider)}),e.jsx(S,{className:F.supportsDedicatedForgeCalendar?"bg-emerald-500/16 text-emerald-100":"bg-sky-400/14 text-sky-100",children:B6(F.provider)})]}),e.jsx("div",{className:"mt-auto pt-5",children:e.jsxs(H,{variant:"secondary",className:"w-full justify-center",onClick:()=>{l(F.provider),d(F.provider==="google"||F.provider==="microsoft"?"credentials":void 0),r(!0)},children:[e.jsx(Ra,{className:"size-4"}),K6(F.provider)]})})]},F.provider)})})]}),e.jsxs(le,{className:"surface-section-panel grid gap-4 rounded-[30px] border",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar colors"}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:"Calendar colors are on by default so each mirrored calendar stays legible in the week view. Adjust any display color here without changing the provider itself."})]}),e.jsx("button",{type:"button",onClick:()=>T(F=>({...F,useCalendarColors:!F.useCalendarColors})),className:`rounded-full px-4 py-2 text-sm transition ${A.useCalendarColors?"bg-[var(--ui-accent-soft)] text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] text-[var(--ui-ink-soft)] hover:bg-[var(--ui-surface-hover)]"}`,children:A.useCalendarColors?"Colors on":"Colors off"})]}),L.length>0?e.jsx("div",{className:"grid gap-3",children:L.map(F=>{const O=Jr(F);return e.jsxs("div",{className:"grid gap-3 rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-4 md:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{"aria-hidden":"true",className:"size-3 shrink-0 rounded-full",style:{backgroundColor:V[F.id]}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-[var(--ui-ink-strong)]",children:O}),e.jsxs("div",{className:"mt-1 text-sm text-[var(--ui-ink-soft)]",children:[F.canWrite?"Writable":"Read only"," ·"," ",F.timezone]})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{"aria-label":`Choose display color for ${O}`,type:"color",value:V[F.id],onChange:ce=>T(J=>({...J,calendarColors:{...J.calendarColors,[F.id]:ce.target.value}})),className:"h-10 w-12 cursor-pointer rounded-[14px] border border-[var(--ui-border-subtle)] bg-transparent p-1"}),e.jsx(H,{size:"sm",variant:"secondary",onClick:()=>T(ce=>{const J={...ce.calendarColors};return delete J[F.id],{...ce,calendarColors:J}}),children:"Reset palette"})]})]},F.id)})}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-4 py-5 text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Connect a provider first, then Forge will let you tune the display color of each mirrored calendar here."})]}),e.jsxs(le,{className:"surface-section-panel grid gap-4 rounded-[30px] border",children:[e.jsx("div",{className:"flex items-center justify-between gap-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Connected providers"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Review connection health, confirm which provider calendars Forge can read or mirror, and see which connection currently owns the shared Forge write target."})]})}),z.length>0?e.jsx("div",{className:"grid gap-3",children:z.map(F=>{var J;const O=Q.get(F.id)??[],ce=F.provider!=="microsoft"&&B!==null&&B.id!==F.id;return e.jsxs("div",{className:"rounded-[24px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-[var(--ui-ink-strong)]",children:F.label}),e.jsxs("div",{className:"mt-1 text-sm text-[var(--ui-ink-soft)]",children:[qg(F.provider)," ·"," ",F.accountLabel||"No account label yet"]}),F.lastSyncedAt?e.jsxs("div",{className:"mt-2 text-sm text-[var(--ui-ink-faint)]",children:["Last synced"," ",new Date(F.lastSyncedAt).toLocaleString()]}):null,F.lastSyncError?e.jsx("div",{className:"mt-2 text-sm text-rose-200",children:F.lastSyncError}):null,ce?e.jsxs("div",{className:"mt-2 text-sm text-[var(--ui-ink-soft)]",children:["Forge writes through"," ",e.jsx("span",{className:"font-medium text-[var(--ui-ink-strong)]",children:B.label}),B.accountLabel?` · ${B.accountLabel}`:"","."]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:F.status}),((J=F.config)==null?void 0:J.readOnly)===!0?e.jsx(S,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,e.jsxs(H,{size:"sm",variant:"secondary",pending:R.isPending&&R.variables===F.id,pendingLabel:"Syncing",onClick:()=>void R.mutateAsync(F.id),children:[e.jsx(sa,{className:"size-4"}),"Sync"]}),e.jsxs(H,{size:"sm",variant:"secondary",onClick:()=>{const je=(Q.get(F.id)??[]).filter(Ee=>Ee.selectedForSync).map(Ee=>Lr(Ee.remoteId));p(je),x(!0),h(F.id)},children:[e.jsx(Ff,{className:"size-4"}),"Manage mirrored calendars"]}),e.jsxs(H,{size:"sm",variant:"secondary",onClick:()=>b(F.id),children:[e.jsx(Wt,{className:"size-4"}),"Remove"]})]})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:O.map(je=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-[var(--ui-ink-strong)]",children:Jr(je)}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:[je.canWrite?"Writable":"Read only"," ·"," ",je.timezone]})]}),je.forgeManaged?e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge"}):e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[e.jsx(bs,{className:"mr-1 size-3.5"}),"Mirrored"]})]},je.id))})]},F.id)})}):e.jsxs("div",{className:"rounded-[26px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-6 text-sm leading-6 text-white/60",children:["No provider is connected yet. Open a guided setup flow above when you are ready. Forge will reuse one shared"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"})," write target across writable providers when it already exists, create one only when none exists yet, and mirror selected calendars in read-only mode for providers like Exchange Online."]})]})]}),e.jsx(z6,{open:i,onOpenChange:F=>{r(F),F||d(void 0)},initialProvider:n,initialStepId:o,googleSetup:ge,microsoftSetup:ke,existingConnections:z.map(F=>({id:F.id,label:F.label,provider:F.provider,status:F.status,accountLabel:F.accountLabel,forgeCalendarId:F.forgeCalendarId,config:F.config})),onCalendarSettingsChanged:P,pending:j.isPending,onSubmit:async F=>{await j.mutateAsync(F)}}),e.jsx(Kt,{open:m!==null,onOpenChange:F=>{F||h(null)},eyebrow:"Calendar settings",title:"Manage mirrored calendars",description:"Choose which calendars this connection should mirror into Forge.",value:{selectedCalendarUrls:c},onChange:F=>p(F.selectedCalendarUrls),draftPersistenceKey:m?`settings.calendar.manage.${m}`:"settings.calendar.manage",steps:q,pending:v.isPending,pendingLabel:"Saving",submitLabel:"Save mirror selection",error:v.error instanceof Error?v.error.message:null,onSubmit:async()=>{m&&(await v.mutateAsync({connectionId:m,patch:{selectedCalendarUrls:c.map(Lr)}}),x(!1),h(null))}}),e.jsx(Kt,{open:f!==null,onOpenChange:F=>{F||b(null)},eyebrow:"Calendar settings",title:"Remove calendar connection",description:"This removes the provider connection, stops syncing its calendars, removes mirrored external events from Forge, and keeps Forge-native events local.",value:{acknowledgement:!1},onChange:()=>{},draftPersistenceKey:f?`settings.calendar.remove.${f}`:"settings.calendar.remove",steps:[{id:"confirm",eyebrow:"Disconnect",title:E?`Remove ${E.label}?`:"Remove this connection?",description:"Use this when you want to disconnect the account entirely. You can reconnect later with the guided setup flow.",render:()=>e.jsx("div",{className:"rounded-[24px] border border-rose-400/20 bg-rose-400/10 p-4 text-sm leading-6 text-rose-100",children:E?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"font-medium text-white",children:[qg(E.provider)," ·"," ",E.accountLabel||"No account label"]}),e.jsx("div",{className:"mt-2",children:"Mirrored provider calendars and external mirrored events from this connection will be removed. Forge-owned events, work blocks, and timeboxes remain in Forge."})]}):"This connection will be removed from Forge."})}],pending:D.isPending,pendingLabel:"Removing",submitLabel:"Remove connection",error:D.error instanceof Error?D.error.message:null,onSubmit:async()=>{f&&(await D.mutateAsync(f),b(null))}})]})}function G6(t){return t.replaceAll("."," ")}function Q6(t){const s=typeof t.sleepNights=="number"?t.sleepNights:typeof t.sleepSessions=="number"?t.sleepSessions:0,a=typeof t.sleepSegments=="number"?t.sleepSegments:0,i=typeof t.sleepRawRecords=="number"?t.sleepRawRecords:0,r=typeof t.sleepSessions=="number"?t.sleepSessions:0,n=typeof t.workouts=="number"?t.workouts:0,l=t.vitals&&typeof t.vitals=="object"&&!Array.isArray(t.vitals)&&typeof t.vitals.metricEntries=="number"?t.vitals.metricEntries:0;return`${s||r} nights · ${a} segments · ${i} raw records · ${n} workouts · ${l} vitals`}function Ug(t){return t?"signal":"meta"}function V6(t){return t.replaceAll("_"," ")}function X6(t){return t?new Date(t).toLocaleString():"Waiting for device update"}function Y6(t,s){return t?s?"signal":"default":"meta"}function J6(t){return t.transportMode==="iroh"?"Iroh":"Manual HTTP"}function Z6(t){return t.transportMode==="iroh"?"signal":"meta"}function eE(){const t=Ct(),s=pt(),a=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],i=Is(a),[r,n]=u.useState(null),[l,o]=u.useState(!1),[d,m]=u.useState(!1),[h,c]=u.useState(!1),[p,g]=u.useState(null),x=Me({queryKey:["forge-companion-overview",...a],queryFn:async()=>(await xb(a)).overview}),f=De({mutationFn:async(R="iroh")=>J1({userId:i??null,transportMode:R}),onSuccess:async R=>{g({qrPayload:R.qrPayload}),o(!0),await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),b=De({mutationFn:async R=>Z1(R),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),A=De({mutationFn:async()=>t2({userIds:a,includeRevoked:!1}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),T=De({mutationFn:async R=>e2(R.pairingSessionId,R.source,R.desiredEnabled),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}});if(u.useEffect(()=>{if(!p){n(null);return}vj.toDataURL(JSON.stringify(p.qrPayload),{width:320,margin:1}).then(n)},[p]),u.useEffect(()=>{m(!1),c(!1)},[p]),x.isLoading)return e.jsx(gs,{eyebrow:"Companion",title:"Loading mobile companion",description:"Checking pairing state and recent sync status.",columns:2,blocks:5});if(x.isError||!x.data)return e.jsx(ct,{eyebrow:"Companion",error:x.error??new Error("Companion overview unavailable"),onRetry:()=>void x.refetch()});const I=x.data,y=I.pairings.filter(R=>R.status!=="revoked"),N=I.pairings.length-y.length,k=p?JSON.stringify(p.qrPayload,null,2):"",w=async()=>{if(p&&l){o(!1);return}if(p&&!l){o(!0);return}await f.mutateAsync("iroh")},P=async()=>{await f.mutateAsync("manual-http")},j=async()=>{if(k){if(!navigator.clipboard){m(!0);return}try{await navigator.clipboard.writeText(k),c(!0),window.setTimeout(()=>c(!1),1800)}catch{m(!0)}}};return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5 pb-24 lg:pb-0",children:[e.jsx(mt,{title:"Mobile companion",description:"Pair the native iPhone companion, sync Apple Health, and keep the bridge open for watch and location signals.",badge:I.healthState.replaceAll("_"," ")}),e.jsx(Aa,{}),e.jsxs("section",{className:"grid gap-4",children:[null,e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pair iPhone"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Pair your iPhone privately"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Forge uses its own Iroh/QUIC companion route by default. Scan once from the iPhone app; manual HTTP stays as the advanced LAN or Tailscale path."})]}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:flex-wrap sm:justify-end",children:[e.jsxs(H,{variant:"secondary",className:"w-full sm:w-auto",onClick:()=>void P(),pending:f.isPending&&f.variables==="manual-http",pendingLabel:"Generating",children:[e.jsx(jj,{className:"size-4"}),"Advanced HTTP"]}),e.jsxs(H,{className:"w-full sm:w-auto",onClick:()=>void w(),pending:f.isPending&&f.variables!=="manual-http",pendingLabel:"Generating",children:[e.jsx(kj,{className:"size-4"}),p?l?"Hide QR":"Show QR":"Generate Forge QR",p?l?e.jsx(en,{className:"size-4"}):e.jsx(Ta,{className:"size-4"}):null]})]})]}),l?e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] p-4 sm:p-5",children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(260px,360px)_1fr]",children:[r?e.jsxs("div",{className:"grid justify-items-center gap-4 rounded-[24px] bg-white px-6 py-6 text-slate-950",children:[e.jsx("img",{src:r,alt:"Forge Companion pairing QR code",className:"w-full max-w-[320px]"}),e.jsx("div",{className:"max-w-[320px] text-center text-sm text-slate-600",children:"Scan this code from Forge Companion on iPhone."})]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-8 text-center text-sm text-white/55",children:"Generating the QR code now."}),e.jsxs("div",{className:"grid content-start gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p?e.jsxs(S,{tone:Z6(p.qrPayload),children:[e.jsx(Df,{className:"size-3"}),J6(p.qrPayload)]}):null,e.jsxs(S,{tone:"meta",children:[e.jsx(ap,{className:"size-3"}),"One-time token"]})]}),e.jsxs("div",{className:"grid gap-3 text-sm leading-6 text-white/66",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Nj,{className:"mt-1 size-4 shrink-0 text-white/45"}),e.jsx("span",{children:"Open Forge Companion and choose Scan Forge QR."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ap,{className:"mt-1 size-4 shrink-0 text-white/45"}),e.jsx("span",{children:"The iPhone receives the desktop node, relay hint, and pairing token for the Forge Iroh route."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ia,{className:"mt-1 size-4 shrink-0 text-white/45"}),e.jsx("span",{children:"After verification, the app moves straight into native permissions and first sync."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/62",children:p?e.jsxs("span",{children:["Expires"," ",new Date(p.qrPayload.expiresAt).toLocaleString(),"."]}):"Generate the one-time QR and scan it from the iPhone app."}),p?e.jsxs(H,{variant:"secondary",pending:f.isPending,pendingLabel:"Generating",onClick:()=>void f.mutateAsync("iroh"),children:[e.jsx(sa,{className:"size-4"}),"Regenerate QR"]}):null]})]})]}),p?e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/62",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("div",{className:"text-white/78",children:"Fallback pairing payload"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/45",children:"Use this only when the iPhone camera cannot scan the QR. The payload contains the same Forge Iroh connection recipe."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(H,{variant:"secondary",onClick:()=>void j(),children:[h?e.jsx(Ia,{className:"size-4"}):e.jsx(Sj,{className:"size-4"}),h?"Copied":"Copy payload"]}),e.jsxs(H,{variant:"secondary",onClick:()=>m(R=>!R),children:[d?"Hide payload":"Show payload",d?e.jsx(en,{className:"size-4"}):e.jsx(Ta,{className:"size-4"})]})]})]}),d?e.jsx("pre",{className:"max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-[16px] bg-slate-950/60 p-3 font-mono text-[11px] leading-5 text-white/70",children:k}):null]}):null]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-6 text-sm leading-6 text-white/55",children:"Generate a one-time Forge QR when the iPhone is in your hand. The code expires automatically and can be regenerated anytime."})]}),e.jsxs(le,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Companion state"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Pairings"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:y.length}),N>0?e.jsxs("div",{className:"mt-2 text-xs text-white/42",children:[N," revoked hidden"]}):null]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Sleep sessions"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.sleepSessions})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Raw sleep records"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.sleepRawRecords})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workouts"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.workouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Vitals days"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.vitalsDaySummaries??0})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Vital entries"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.vitalsMetricEntries??0})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Reflected sleep"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.reflectiveSleepSessions})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked workouts"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.linkedWorkouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Habit-generated"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.habitGeneratedWorkouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Reconciled"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:I.counts.reconciledWorkouts})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{children:I.healthState.replaceAll("_"," ")}),I.lastSyncAt?e.jsxs(S,{tone:"meta",children:["Last sync ",new Date(I.lastSyncAt).toLocaleString()]}):null,e.jsxs(S,{tone:Ug(I.permissions.healthKitAuthorized),children:["HealthKit ",I.permissions.healthKitAuthorized?"ready":"needed"]}),e.jsxs(S,{tone:Ug(I.permissions.backgroundRefreshEnabled),children:["Background refresh"," ",I.permissions.backgroundRefreshEnabled?"ready":"not yet"]}),e.jsxs(S,{tone:"meta",children:["Location ",I.permissions.locationReady?"ready":"later"]}),e.jsxs(S,{tone:"meta",children:["Motion ",I.permissions.motionReady?"ready":"later"]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pairing path"}),e.jsxs("div",{className:"grid gap-2 text-sm text-white/62",children:[e.jsx("div",{children:"1. Generate the Forge QR from this page."}),e.jsx("div",{children:"2. Scan it in Forge Companion to pass the desktop node and pairing token."}),e.jsx("div",{children:"3. Approve Health access on iPhone, then run the first sync."}),e.jsx("div",{children:"4. Use Advanced HTTP only for a local, Tailscale, or direct TCP route."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[y.length>0?e.jsx("div",{className:"flex justify-end",children:e.jsxs(H,{variant:"secondary",pending:A.isPending,pendingLabel:"Revoking all",onClick:()=>void A.mutateAsync(),children:[e.jsx(ip,{className:"size-4"}),"Revoke all"]})}):null,y.map(R=>e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-base text-white",children:R.deviceName??R.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[R.platform??"ios"," · ",R.status]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{tone:R.status==="healthy"?"signal":"meta",children:R.status.replaceAll("_"," ")}),R.lastSyncAt?e.jsxs(S,{tone:"meta",children:["Synced ",new Date(R.lastSyncAt).toLocaleString()]}):null]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:R.capabilities.map(v=>e.jsx(S,{tone:"meta",size:"sm",wrap:!0,children:G6(v)},v))}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-sm text-white/55",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{children:R.apiBaseUrl}),e.jsxs("div",{children:["Expires ",new Date(R.expiresAt).toLocaleString()]}),R.lastSyncError?e.jsx("div",{className:"text-rose-200/80",children:R.lastSyncError}):null]}),e.jsxs(H,{variant:"secondary",pending:b.isPending&&b.variables===R.id,pendingLabel:"Revoking",disabled:R.status==="revoked",onClick:()=>void b.mutateAsync(R.id),children:[e.jsx(ip,{className:"size-4"}),R.status==="revoked"?"Revoked":"Revoke"]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[16px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Device sync sources"}),[["health","Health"],["movement","Movement"],["screenTime","Screen Time"]].map(([v,D])=>{var V,B;const L=R.sourceStates[v],Q=L.desiredEnabled!==L.appliedEnabled,Z=T.isPending&&((V=T.variables)==null?void 0:V.pairingSessionId)===R.id&&((B=T.variables)==null?void 0:B.source)===v;return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[14px] border border-white/6 bg-white/[0.03] px-3 py-3",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-sm text-white",children:D}),e.jsx(S,{tone:Y6(L.desiredEnabled,L.syncEligible),size:"sm",children:L.desiredEnabled?"Enabled":"Off"}),Q?e.jsx(S,{tone:"meta",size:"sm",children:"Pending on phone"}):e.jsx(S,{tone:"meta",size:"sm",children:"Applied"})]}),e.jsxs("div",{className:"text-xs text-white/55",children:["Authorization ",V6(L.authorizationStatus)," · ","Last seen ",X6(L.lastObservedAt)]})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":L.desiredEnabled,"aria-label":`${D} sync source`,disabled:Z,onClick:()=>void T.mutateAsync({pairingSessionId:R.id,source:v,desiredEnabled:!L.desiredEnabled}),className:`relative inline-flex h-7 w-12 items-center rounded-full border transition ${L.desiredEnabled?"border-[rgba(171,232,255,0.4)] bg-[rgba(111,133,232,0.36)]":"border-white/10 bg-white/[0.06]"} ${Z?"opacity-60":""}`,children:e.jsx("span",{className:`inline-block size-5 rounded-full bg-white shadow transition ${L.desiredEnabled?"translate-x-6":"translate-x-1"}`})})]},v)})]})]},R.id)),y.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-6 text-sm text-white/55",children:"No companion paired yet. Generate a QR code, then open the iOS companion and scan it."}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(H,{variant:"secondary",onClick:()=>void x.refetch(),children:[e.jsx(sa,{className:"size-4"}),"Refresh status"]}),e.jsxs(et,{to:"/sleep",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(Hs,{className:"size-4"}),"Open sleep view"]}),e.jsxs(et,{to:"/sports",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(Hs,{className:"size-4"}),"Open sports view"]}),e.jsxs(et,{to:"/vitals",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(Hs,{className:"size-4"}),"Open vitals view"]})]})]})]}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Sync history"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Recent HealthKit import runs"})]}),e.jsxs(S,{tone:"meta",children:[I.importRuns.length," recent runs"]})]}),e.jsxs("div",{className:"grid gap-3",children:[I.importRuns.map(R=>e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4 lg:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Cj,{className:"size-4 text-white/55"}),e.jsxs("div",{className:"text-base text-white",children:[R.sourceDevice||"iPhone"," import"]}),e.jsx(S,{tone:R.status==="completed"?"signal":"meta",children:R.status})]}),e.jsxs("div",{className:"text-sm text-white/60",children:[new Date(R.importedAt).toLocaleString()," ·"," ",Q6(R.payloadSummary)]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs(S,{tone:"meta",children:["Imported ",R.importedCount]}),e.jsxs(S,{tone:"meta",children:["Created ",R.createdCount]}),e.jsxs(S,{tone:"meta",children:["Updated ",R.updatedCount]}),e.jsxs(S,{tone:"meta",children:["Merged ",R.mergedCount]})]}),R.errorMessage?e.jsx("div",{className:"text-sm text-rose-200/80",children:R.errorMessage}):null]}),R.pairingSessionId?e.jsxs("div",{className:"text-sm text-white/45 lg:text-right",children:["Pairing ",R.pairingSessionId]}):null]},R.id)),I.importRuns.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-6 text-sm text-white/55",children:"No sync runs yet. Pair the iPhone companion and run the first HealthKit import."}):null]})]})]})}function su(t="openai-api"){return{label:t==="openai-codex"?"OpenAI Codex":t==="openai-compatible"?"Local compatible endpoint":t==="mock"?"Workbench mock runtime":"OpenAI API",provider:t,baseUrl:t==="openai-codex"?"https://chatgpt.com/backend-api":t==="openai-compatible"?"http://127.0.0.1:11434/v1":t==="mock"?"mock://workbench":"https://api.openai.com/v1",model:t==="mock"?"mock-echo":"gpt-5.4-mini",apiKey:""}}function tE(t){return{id:t.id,label:t.label,provider:t.provider,baseUrl:t.baseUrl,model:t.model,apiKey:""}}function sE(){var Q,Z,V;const t=pt(),[s,a]=u.useState(()=>su()),[i,r]=u.useState(""),[n,l]=u.useState("gpt-5.4-mini"),[o,d]=u.useState(""),[m,h]=u.useState("gpt-5.4-mini"),[c,p]=u.useState(""),[g,x]=u.useState(null),[f,b]=u.useState(null),A=Me({queryKey:["forge-settings"],queryFn:pr}),T=Me({queryKey:["forge-openai-codex-oauth",g],queryFn:async()=>{if(!g)throw new Error("Missing OAuth session id");return await w1(g)},enabled:!!g,refetchInterval:B=>{var E;const $=(E=B.state.data)==null?void 0:E.session.status;return $&&["authorized","error","consumed","expired"].includes($)?!1:1500}}),I=async()=>{await t.invalidateQueries({queryKey:["forge-settings"]}),await t.invalidateQueries({queryKey:["forge-openai-codex-oauth",g]})},y=De({mutationFn:()=>gi({modelSettings:{forgeAgent:{basicChat:{connectionId:i||null,model:n},wiki:{connectionId:o||null,model:m}}}}),onSuccess:I}),N=De({mutationFn:()=>g1({id:s.id,label:s.label,provider:s.provider,authMode:s.provider==="openai-codex"?"oauth":"api_key",baseUrl:s.baseUrl,model:s.model,apiKey:s.provider==="openai-codex"?void 0:s.apiKey||void 0,oauthSessionId:s.provider==="openai-codex"?g??void 0:void 0}),onSuccess:async()=>{b("Connection saved."),s.provider==="openai-codex"&&(x(null),p("")),a(su(s.provider)),await I()}}),k=De({mutationFn:f1,onSuccess:I}),w=De({mutationFn:async()=>b1({connectionId:s.id,provider:s.provider,baseUrl:s.baseUrl,model:s.model,apiKey:s.provider==="openai-codex"?void 0:s.apiKey||void 0}),onSuccess:({result:B})=>{b(`Connection test succeeded: ${B.outputPreview}`)},onError:B=>{b(B instanceof Error?B.message:"Connection test failed.")}}),P=De({mutationFn:y1,onSuccess:({session:B})=>{x(B.id),b("OpenAI Codex OAuth started."),B.authUrl&&window.open(B.authUrl,"_blank","noopener,noreferrer")}}),j=De({mutationFn:async()=>{if(!g)throw new Error("No OAuth session started yet.");return await v1(g,c)},onSuccess:({session:B})=>{b(B.status==="authorized"?"OpenAI Codex OAuth authorized.":"Manual OAuth code submitted.")}});u.useEffect(()=>{var $;const B=($=A.data)==null?void 0:$.settings;B&&(r(B.modelSettings.forgeAgent.basicChat.connectionId??""),l(B.modelSettings.forgeAgent.basicChat.model),d(B.modelSettings.forgeAgent.wiki.connectionId??""),h(B.modelSettings.forgeAgent.wiki.model))},[A.data]);const R=((Q=A.data)==null?void 0:Q.settings.modelSettings.connections)??[],v=((Z=T.data)==null?void 0:Z.session)??null,D=u.useMemo(()=>!s.label.trim()||!s.model.trim()?!1:s.provider==="openai-codex"?!!(s.id||(v==null?void 0:v.status)==="authorized"):s.provider==="mock"?!0:s.apiKey.trim().length>0||!!s.id,[s,v==null?void 0:v.status]);if(A.isLoading)return e.jsx(zt,{eyebrow:"Models",title:"Loading model settings",description:"Fetching Forge agent defaults and configured AI connections."});if(A.isError||!((V=A.data)!=null&&V.settings))return e.jsx(ct,{eyebrow:"Models",error:A.error??new Error("Forge returned an empty model settings payload."),onRetry:()=>void A.refetch()});const L=A.data.settings;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(mt,{eyebrow:"AI runtime",title:"Model Settings",description:"Manage Forge Agent defaults, OpenAI OAuth/API connections, and local OpenAI-compatible endpoints as first-class chat agents.",badge:`${R.length} model connection${R.length===1?"":"s"}`}),e.jsx(Aa,{}),e.jsxs(le,{className:"grid gap-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sa,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Forge Agent defaults"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Forge Agent stays the default system agent. Choose which model connection powers basic chat and the managed wiki workflow."})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Basic chat connection"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:i,onChange:B=>r(B.target.value),children:[e.jsx("option",{value:"",children:"No external connection"}),R.map(B=>e.jsxs("option",{value:B.id,children:[B.label," (",B.agentLabel,")"]},B.id))]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:n,onChange:B=>l(B.target.value),placeholder:"Model"})]}),e.jsxs("label",{className:"grid gap-2 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("span",{className:"text-sm text-white/72",children:"KarpaWiki model connection"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:o,onChange:B=>d(B.target.value),children:[e.jsx("option",{value:"",children:"No external connection"}),R.map(B=>e.jsxs("option",{value:B.id,children:[B.label," (",B.agentLabel,")"]},B.id))]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:m,onChange:B=>h(B.target.value),placeholder:"Model"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(H,{pending:y.isPending,pendingLabel:"Saving defaults",onClick:()=>void y.mutateAsync(),children:"Save Forge Agent defaults"}),e.jsxs(S,{className:"bg-white/[0.06] text-white/78",children:["Forge Agent",L.modelSettings.forgeAgent.basicChat.connectionLabel?` basic chat: ${L.modelSettings.forgeAgent.basicChat.connectionLabel}`:" basic chat stays local"]}),e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:L.modelSettings.forgeAgent.wiki.connectionLabel?`KarpaWiki: ${L.modelSettings.forgeAgent.wiki.connectionLabel}`:"KarpaWiki: no external model selected"})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ij,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Connection editor"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Every saved connection becomes a first-class agent layered on top of Forge Agent."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Provider"}),e.jsx("div",{className:"grid gap-2 md:grid-cols-3",children:[["openai-api","OpenAI API"],["openai-codex","OpenAI Codex OAuth"],["openai-compatible","OpenAI-compatible"]].map(([B,$])=>e.jsx("button",{type:"button",className:`rounded-[18px] px-4 py-3 text-left text-sm transition ${s.provider===B?"bg-[var(--primary)]/[0.18] text-white":"bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"}`,onClick:()=>{a(su(B)),x(null),p("")},children:$},B))})]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.label,onChange:B=>a($=>({...$,label:B.target.value})),placeholder:"Connection label"}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.model,onChange:B=>a($=>({...$,model:B.target.value})),placeholder:"Model"}),s.provider==="mock"?e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white",children:"The Workbench mock runtime is only meant for local development and test workflows."}),e.jsxs("div",{className:"text-xs leading-5 text-white/52",children:["Use mock models like ",e.jsx("code",{children:"mock-echo"}),", ",e.jsx("code",{children:"mock-json"}),",",e.jsx("code",{children:"mock-tool-search"}),", ",e.jsx("code",{children:"mock-tool-note"}),", or",e.jsx("code",{children:"mock-chat-memory"})," to exercise deterministic flow behavior without a real external model."]})]}):s.provider!=="openai-codex"?e.jsxs(e.Fragment,{children:[e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.baseUrl,onChange:B=>a($=>({...$,baseUrl:B.target.value})),placeholder:"Base URL"}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.apiKey,onChange:B=>a($=>({...$,apiKey:B.target.value})),placeholder:s.id?"Leave blank to keep the stored key":"API key",type:"password"})]}):e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"text-sm text-white",children:["OpenAI Codex uses the documented PKCE flow with the local callback at ",L.modelSettings.oauth.openAiCodex.callbackUrl,"."]}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Start OAuth, finish the browser sign-in, then save the resulting connection as a chat agent backed by the ChatGPT Codex runtime."}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(H,{variant:"secondary",pending:P.isPending,pendingLabel:"Starting OAuth",onClick:()=>void P.mutateAsync(),children:[e.jsx(Ut,{className:"size-4"}),"Start OAuth"]}),v!=null&&v.authUrl?e.jsxs(H,{variant:"secondary",onClick:()=>window.open(v.authUrl??"","_blank","noopener,noreferrer"),children:["Open sign-in",e.jsx(Ra,{className:"size-4"})]}):null]}),v?e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-black/20 p-3 text-sm text-white/72",children:[e.jsxs("div",{children:["Status: ",v.status]}),v.accountLabel?e.jsxs("div",{children:["Account: ",v.accountLabel]}):null,v.error?e.jsx("div",{className:"text-rose-200",children:v.error}):null]}):null,e.jsxs("div",{className:"grid gap-2",children:[e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:c,onChange:B=>p(B.target.value),placeholder:"Paste the authorization code or full redirect URL"}),e.jsx(H,{variant:"secondary",disabled:!c.trim()||!g,pending:j.isPending,pendingLabel:"Submitting",onClick:()=>void j.mutateAsync(),children:"Submit manual code"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(H,{pending:N.isPending,pendingLabel:"Saving connection",disabled:!D,onClick:()=>void N.mutateAsync(),children:"Save connection"}),e.jsxs(H,{variant:"secondary",pending:w.isPending,pendingLabel:"Testing",disabled:s.provider==="openai-codex"?!s.id:s.provider==="mock"?!1:!s.id&&!s.apiKey.trim(),onClick:()=>void w.mutateAsync(),children:[e.jsx(rr,{className:"size-4"}),"Test connection"]})]}),f?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:f}):null]})]}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sa,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Connected agents"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Each connection registers its own chat-facing agent identity."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[R.length===0?e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-5 text-sm leading-6 text-white/58",children:"No external model connection yet. Add one with OAuth or API credentials and Forge will expose it as a first-class agent."}):null,R.map(B=>e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-white",children:B.label}),e.jsxs("div",{className:"mt-1 text-xs text-white/46",children:[B.agentLabel," · ",B.provider," ·"," ",B.model]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"secondary",onClick:()=>{a(tE(B)),x(null),p("")},children:"Edit"}),e.jsx(H,{variant:"secondary",pending:k.isPending,pendingLabel:"Deleting",onClick:()=>void k.mutateAsync(B.id),children:e.jsx(Wt,{className:"size-4"})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:B.authMode==="oauth"?"OAuth":"API key"}),e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:B.status}),e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:B.baseUrl}),B.accountLabel?e.jsx(S,{className:"bg-white/[0.06] text-white/78",children:B.accountLabel}):null]})]},B.id))]})]})]})]})}const aE=["error","warning","info","debug"],iE=["server","ui","system","agent","openclaw"],rE=60;function vl(t){return t.trim().toLowerCase()}function Ur(t){return Array.from(new Set(t.map(s=>(s==null?void 0:s.trim())??"").filter(Boolean)))}function _r(t,s){const a=Ur(t.getAll(s));if(a.length>0)return a;const i=t.get(s);return i!=null&&i.trim()?[i.trim()]:[]}function nE(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}).format(new Date(t))}function Cv(t){return t==="error"?"border-rose-400/20 bg-rose-500/[0.08] text-rose-100":t==="warning"?"border-amber-400/20 bg-amber-500/[0.08] text-amber-100":t==="info"?"border-sky-400/20 bg-sky-500/[0.08] text-sky-100":"border-white/10 bg-white/[0.04] text-white/68"}function au(t){return t==="error"?"Errors":t==="warning"?"Warnings":t==="info"?"Info":"Debug"}function iu(t){return t==="openclaw"?"OpenClaw":t.charAt(0).toUpperCase()+t.slice(1)}function lE(t){return[t.scope?`scope: ${t.scope}`:null,t.eventKey?`event: ${t.eventKey}`:null,t.route?`route: ${t.route}`:null,t.functionName?`function: ${t.functionName}`:null,t.jobId?`job: ${t.jobId}`:null,t.entityType&&t.entityId?`entity: ${t.entityType}:${t.entityId}`:null,t.requestId?`request: ${t.requestId}`:null].filter(s=>!!s)}function oE(t){return vl([t.message,t.scope,t.eventKey,t.route,t.functionName,t.requestId,t.entityType,t.entityId,t.jobId,JSON.stringify(t.details)].filter(Boolean).join(" "))}function zi(t,s){return e.jsx(S,{size:"sm",className:te("bg-white/[0.08] text-white/74",s),children:t})}function Wg(t,s){return nS(t)?e.jsx(Qe,{kind:t,label:s,compact:!0,gradient:!1}):zi(s,"bg-[rgba(192,193,255,0.12)] text-white/84")}function Fr({label:t,placeholder:s,options:a,selectedIds:i,onChange:r,emptyMessage:n="No matches yet."}){const[l,o]=u.useState(!1),[d,m]=u.useState(""),[h,c]=u.useState(0),p=u.useRef(null),g=u.useRef(null),x=Eb(p,l,{offset:8,preferredMaxHeight:320,minHeight:160}),f=u.useMemo(()=>i.map(y=>a.find(N=>N.id===y)??null).filter(y=>y!==null),[a,i]),b=vl(d),A=u.useMemo(()=>{const y=a.filter(N=>!i.includes(N.id));return b?y.filter(N=>vl(`${N.label} ${N.description??""} ${N.searchText??""}`).includes(b)).slice(0,10):y.slice(0,10)},[b,a,i]),T=y=>{i.includes(y)||(r([...i,y]),m(""),c(0),o(!1))},I=y=>{r(i.filter(N=>N!==y))};return u.useEffect(()=>{if(!l)return;const y=k=>{var P,j;const w=k.target;(P=p.current)!=null&&P.contains(w)||(j=g.current)!=null&&j.contains(w)||o(!1)},N=k=>{k.key==="Escape"&&o(!1)};return document.addEventListener("pointerdown",y),document.addEventListener("keydown",N),()=>{document.removeEventListener("pointerdown",y),document.removeEventListener("keydown",N)}},[l]),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.18em] text-white/45",children:t}),e.jsxs("div",{ref:p,className:"relative rounded-[20px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[f.length>0?e.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:f.map(y=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/8 bg-white/[0.05] px-1.5 py-1",children:[y.badge,e.jsx("button",{type:"button",className:"rounded-full p-0.5 text-white/46 transition hover:text-white",onClick:()=>I(y.id),"aria-label":`Remove ${y.label}`,children:e.jsx(Lt,{className:"size-3"})})]},y.id))}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"size-3.5 text-white/34"}),e.jsx("input",{value:d,onChange:y=>{m(y.target.value),c(0),o(!0)},onFocus:()=>o(!0),onKeyDown:y=>{if(y.key==="Backspace"&&!d&&i.length>0){I(i[i.length-1]);return}if(y.key==="ArrowDown"){y.preventDefault(),o(!0),c(N=>A.length===0?0:Math.min(A.length-1,N+1));return}if(y.key==="ArrowUp"){y.preventDefault(),c(N=>Math.max(0,N-1));return}if(y.key==="Escape"){o(!1);return}y.key==="Enter"&&A[h]&&(y.preventDefault(),T(A[h].id))},placeholder:s,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),l&&x&&typeof document<"u"?Ti.createPortal(e.jsx("div",{ref:g,role:"listbox","aria-multiselectable":"true",className:"z-[80] overflow-y-auto overscroll-contain rounded-[20px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl [webkit-overflow-scrolling:touch]",style:x,children:A.length>0?A.map((y,N)=>e.jsx("button",{type:"button",role:"option","aria-selected":!1,className:te("flex w-full items-start justify-between gap-3 rounded-[16px] px-3 py-2 text-left transition",N===h?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>c(N),onMouseDown:k=>k.preventDefault(),onClick:()=>T(y.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:y.menuBadge??y.badge}),y.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:y.description}):null]})},y.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-white/42",children:n})}),document.body):null]})]})}function dE(t,s){const a=`${s.entityType}:${s.entityId}`;t.has(a)||t.set(a,{id:a,label:s.label,description:s.description,searchText:s.searchText,badge:s.badge,menuBadge:s.menuBadge})}function cE(t){const s=new Map;for(const a of t){if(!a.entityType||!a.entityId)continue;const i=`${a.entityType}:${a.entityId}`;if(s.has(i))continue;const r=a.entityType==="wiki_ingest_job"?`Ingest ${a.entityId}`:`${a.entityType} ${a.entityId}`;dE(s,{entityType:a.entityType,entityId:a.entityId,label:r,description:"Seen in diagnostics logs",searchText:vl(`${r} ${a.scope} ${a.message} ${a.eventKey}`),badge:Wg(a.entityType,r),menuBadge:Wg(a.entityType,r)})}return Array.from(s.values()).sort((a,i)=>a.label.localeCompare(i.label))}const uE=u.memo(function({entry:s}){const[a,i]=u.useState(!1),r=u.useMemo(()=>a&&Object.keys(s.details).length>0?JSON.stringify(s.details,null,2):"",[a,s.details]);return e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:te("rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em]",Cv(s.level)),children:s.level}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/60",children:s.source}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/60",children:s.scope}),s.eventKey?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/46",children:s.eventKey}):null]}),e.jsx("div",{className:"text-base font-medium text-white",children:s.message}),e.jsx("div",{className:"flex flex-wrap gap-3 text-xs text-white/45",children:lE(s).map(n=>e.jsx("span",{children:n},n))})]}),e.jsxs("div",{className:"shrink-0 text-right text-xs text-white/40",children:[e.jsx("div",{children:nE(s.createdAt)}),e.jsx("div",{className:"mt-1 font-mono text-[11px]",children:s.id})]})]}),Object.keys(s.details).length>0?e.jsxs("details",{className:"rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",onToggle:n=>i(n.currentTarget.open),children:[e.jsx("summary",{className:"cursor-pointer text-sm text-white/70",children:"View structured details"}),a?e.jsx("pre",{className:"mt-3 overflow-x-auto whitespace-pre-wrap text-xs leading-6 text-white/58",children:r}):null]}):null]})});function mE(){const[t,s]=ws(),a=u.useMemo(()=>{var j,R;const k=((j=t.get("entityType"))==null?void 0:j.trim())||"",w=((R=t.get("entityId"))==null?void 0:R.trim())||"",P=_r(t,"entity");return P.length===0&&k&&w&&P.push(`${k}:${w}`),{search:t.get("search")||"",levels:_r(t,"level"),sources:_r(t,"source"),scopes:_r(t,"scope"),routes:_r(t,"route"),jobs:_r(t,"jobId"),entities:Ur(P)}},[t]),i=pu({queryKey:["forge-diagnostic-logs","settings-filters"],initialPageParam:null,queryFn:({pageParam:k})=>R2({limit:rE,beforeCreatedAt:k==null?void 0:k.beforeCreatedAt,beforeId:k==null?void 0:k.beforeId}),getNextPageParam:k=>k.nextCursor,retry:!1,refetchOnWindowFocus:!1}),r=(k,w)=>{const P=new URLSearchParams(t);w.trim()?P.set(k,w.trim()):P.delete(k),s(P,{replace:!0})},n=(k,w,P=[])=>{const j=new URLSearchParams(t);j.delete(k);for(const R of P)j.delete(R);for(const R of Ur(w))j.append(k,R);s(j,{replace:!0})},l=()=>{const k=new URLSearchParams(t);["search","level","source","scope","route","jobId","entity","entityType","entityId"].forEach(w=>k.delete(w)),s(k,{replace:!0})},o=u.useMemo(()=>{var k;return((k=i.data)==null?void 0:k.pages.flatMap(w=>w.logs))??[]},[i.data]),d=vl(a.search),m=u.useRef(null),h=u.useMemo(()=>aE.map(k=>({id:k,label:au(k),searchText:`${k} ${au(k)}`,badge:e.jsx(S,{size:"sm",className:Cv(k),children:au(k)})})),[]),c=u.useMemo(()=>iE.map(k=>({id:k,label:iu(k),searchText:`${k} ${iu(k)}`,badge:zi(iu(k))})),[]),p=u.useMemo(()=>Ur(o.map(k=>k.scope)).map(k=>({id:k,label:k,searchText:k,badge:zi(k)})),[o]),g=u.useMemo(()=>Ur(o.map(k=>k.route)).map(k=>({id:k,label:k,description:"Filter logs to one or more exact routes.",searchText:k,badge:zi(k,"max-w-[16rem]"),menuBadge:zi(k)})),[o]),x=u.useMemo(()=>Ur(o.map(k=>k.jobId)).map(k=>({id:k,label:k,description:"Background job or ingest run id.",searchText:k,badge:zi(k,"max-w-[14rem]"),menuBadge:zi(k)})),[o]),f=u.useMemo(()=>cE(o),[o]),b=u.useMemo(()=>o.filter(k=>{if(d&&!oE(k).includes(d)||a.levels.length>0&&!a.levels.includes(k.level)||a.sources.length>0&&!a.sources.includes(k.source)||a.scopes.length>0&&!a.scopes.includes(k.scope)||a.routes.length>0&&!a.routes.includes(k.route??"")||a.jobs.length>0&&!a.jobs.includes(k.jobId??""))return!1;if(a.entities.length>0){const w=k.entityType&&k.entityId?`${k.entityType}:${k.entityId}`:"";if(!w||!a.entities.includes(w))return!1}return!0}),[a,d,o]),A=[a.search,a.levels.join("|"),a.sources.join("|"),a.scopes.join("|"),a.routes.join("|"),a.jobs.join("|"),a.entities.join("|")].join("::");u.useEffect(()=>{var k;(k=m.current)==null||k.scrollTo({top:0})},[A]);const T=Ad({count:b.length,getScrollElement:()=>m.current,estimateSize:()=>260,overscan:8}),I=T.getVirtualItems(),y=()=>{const k=m.current;if(!k||!i.hasNextPage||i.isFetchingNextPage)return;k.scrollHeight-k.scrollTop-k.clientHeight<=800&&i.fetchNextPage()},N=a.levels.length+a.sources.length+a.scopes.length+a.routes.length+a.jobs.length+a.entities.length+(a.search.trim()?1:0);return i.isPending?e.jsx(gs,{eyebrow:"Settings",title:"Loading diagnostics",description:"Collecting the latest frontend, backend, and runtime traces.",columns:1,blocks:6}):i.isError?e.jsx(ct,{eyebrow:"Settings",error:i.error,onRetry:()=>void i.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(mt,{title:"Logs",description:"Inspect shared diagnostics from the UI, backend routes, background jobs, and LLM flows.",badge:`${b.length} matching${b.length!==o.length?` · ${o.length} loaded`:""}${i.hasNextPage?" · more available":""}`}),e.jsx(Aa,{}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Filters"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Use token filters with OR-style badge selections for levels, sources, routes, jobs, scopes, and linked entities. Search still matches the message body and structured details."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[N>0?e.jsxs(H,{variant:"ghost",size:"sm",onClick:l,children:["Clear ",N]}):null,e.jsx(H,{variant:"secondary",size:"sm",onClick:()=>void i.refetch(),pending:i.isRefetching&&!i.isFetchingNextPage,pendingLabel:"Refreshing",children:"Refresh"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.18em] text-white/45",children:"Search message or details"}),e.jsx(be,{value:a.search,onChange:k=>r("search",k.target.value),placeholder:"LLM compilation failed, wiki_ingest, request_failed…",className:"h-11 rounded-[20px]"})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsx(Fr,{label:"Levels",placeholder:"Add one or more levels",options:h,selectedIds:a.levels,onChange:k=>n("level",k),emptyMessage:"No additional log levels."}),e.jsx(Fr,{label:"Sources",placeholder:"Add one or more sources",options:c,selectedIds:a.sources,onChange:k=>n("source",k),emptyMessage:"No additional log sources."}),e.jsx(Fr,{label:"Scopes",placeholder:"Search scopes",options:p,selectedIds:a.scopes,onChange:k=>n("scope",k),emptyMessage:"No scopes match the current logs."}),e.jsx(Fr,{label:"Routes",placeholder:"Search exact routes",options:g,selectedIds:a.routes,onChange:k=>n("route",k),emptyMessage:"No routes match the current logs."}),e.jsx(Fr,{label:"Jobs",placeholder:"Search job ids",options:x,selectedIds:a.jobs,onChange:k=>n("jobId",k),emptyMessage:"No job ids match the current logs."}),e.jsx(Fr,{label:"Entities",placeholder:"Search Forge entities or logged ids",options:f,selectedIds:a.entities,onChange:k=>n("entity",k,["entityType","entityId"]),emptyMessage:"No logged entities match yet."})]})]}),e.jsx("div",{className:"grid gap-3",children:b.length===0?e.jsx(le,{className:"text-sm text-white/58",children:"No diagnostic entries match the current filters yet."}):e.jsx(le,{className:"p-0",children:e.jsxs("div",{ref:m,onScroll:y,className:"h-[72vh] overflow-y-auto px-3 py-3",children:[e.jsx("div",{className:"relative",style:{height:`${T.getTotalSize()}px`},children:I.map(k=>{const w=b[k.index];return w?e.jsx("div",{"data-index":k.index,ref:T.measureElement,className:"absolute left-0 top-0 w-full pb-3",style:{transform:`translateY(${k.start}px)`},children:e.jsx(uE,{entry:w})},w.id):null})}),e.jsx("div",{className:"border-t border-white/6 px-1 py-3 text-center text-xs text-white/46",children:i.isFetchingNextPage?"Loading older logs…":i.hasNextPage?"Scroll to load older logs.":`Showing all ${o.length} loaded logs.`})]})})})]})}function hE(t){switch(t){case"platinum":return"text-cyan-200";case"gold":return"text-amber-200";case"silver":return"text-slate-200";default:return"text-orange-200"}}function pE(t){switch(t){case"surging":return"from-[rgba(192,193,255,0.3)] via-[rgba(78,222,163,0.22)] to-[rgba(255,185,95,0.22)]";case"steady":return"from-[rgba(192,193,255,0.24)] via-[rgba(192,193,255,0.14)] to-[rgba(78,222,163,0.18)]";default:return"from-[rgba(255,185,95,0.2)] via-[rgba(255,185,95,0.12)] to-[rgba(192,193,255,0.16)]"}}function xE({profile:t,achievements:s,milestoneRewards:a,momentumPulse:i,recentLedger:r=[],className:n,tone:l="core"}){const o=s.filter(p=>p.unlocked),d=(o.length>0?o:s).slice(0,3),m=a.slice(0,3),h=r.slice(0,3),c=Math.min(100,Math.round(t.currentLevelXp/t.nextLevelXp*100));return e.jsxs("section",{className:te("min-w-0 overflow-hidden rounded-[30px] border border-white/6 bg-[linear-gradient(180deg,rgba(18,24,40,0.96),rgba(11,16,28,0.94))] shadow-[0_24px_70px_rgba(4,8,18,0.3)]",l==="psyche"&&"bg-[linear-gradient(180deg,rgba(18,27,35,0.96),rgba(12,20,26,0.94))]",n),children:[e.jsx("div",{className:te("bg-gradient-to-r px-5 py-5",pE(i.status)),children:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/55",children:"Weekly progress"}),e.jsx("h2",{className:"mt-3 font-display text-3xl leading-none text-white lg:text-4xl",children:i.headline}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/68",children:i.detail})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap gap-2",children:[e.jsxs(S,{wrap:!0,className:"bg-black/20 text-white/84",children:["Level ",t.level]}),e.jsxs(S,{wrap:!0,className:"bg-black/20 text-white/84",children:[t.streakDays," day streak"]}),e.jsxs(S,{wrap:!0,className:"bg-black/20 text-white/84",children:[t.weeklyXp," weekly XP"]})]})]})}),e.jsxs("div",{className:"grid gap-5 px-5 py-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(Ms.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.24,ease:"easeOut"},className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-white",children:"Next reward"}),e.jsx("div",{className:"mt-2 text-sm text-white/60",children:i.nextMilestoneLabel})]}),e.jsx(S,{wrap:!0,className:"max-w-[12rem] shrink-0 self-start text-[var(--tertiary)]",children:i.celebrationLabel})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Gs,{value:c})}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-xs uppercase tracking-[0.16em] text-white/38",children:[e.jsxs("span",{children:[t.currentLevelXp,"/",t.nextLevelXp," XP"]}),e.jsxs("span",{children:[t.comboMultiplier.toFixed(2),"x combo"]})]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:d.map((p,g)=>e.jsxs(Ms.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.24,delay:.04*g,ease:"easeOut"},className:"overflow-hidden rounded-[22px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:p.title}),e.jsx(S,{wrap:!0,className:te("max-w-[8rem] shrink-0 self-start",hE(p.tier)),children:p.tier})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:p.summary}),e.jsx("div",{className:"mt-4 text-xs uppercase tracking-[0.16em] text-white/40",children:p.progressLabel})]},p.id))})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Rewards in progress"}),e.jsx("div",{className:"mt-4 grid gap-3",children:m.map(p=>{const g=Math.min(100,Math.round(p.current/p.target*100));return e.jsxs("div",{className:"overflow-hidden rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:p.title}),e.jsx(S,{wrap:!0,className:te("max-w-[10.5rem] shrink-0 self-start",p.completed?"text-emerald-300":"text-white/68"),children:p.rewardLabel})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:p.summary}),e.jsx("div",{className:"mt-4",children:e.jsx(Gs,{value:g})}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:p.progressLabel})]},p.id)})})]}),h.length>0?e.jsxs("div",{className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recent XP changes"}),e.jsx("div",{className:"mt-4 grid gap-3",children:h.map(p=>e.jsxs("div",{className:"overflow-hidden rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:p.reasonTitle}),e.jsxs(S,{wrap:!0,className:te("max-w-[8rem] shrink-0 self-start",p.deltaXp>=0?"text-emerald-300":"text-amber-300"),children:[p.deltaXp>0?"+":"",p.deltaXp," XP"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:p.reasonSummary}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:Ml(p.createdAt)})]},p.id))})]}):null]})]})]})}function gE(t){return JSON.stringify(t,null,2)}function Hg(t){const s=t.trim();if(!s)return{};const a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Expected a JSON object.");return a}function fE(){var j,R,v;const t=Ct(),s=pt(),[a,i]=u.useState(""),[r,n]=u.useState(null),[l,o]=u.useState(null),d=Me({queryKey:["forge-operator-session"],queryFn:mr}),m=d.isSuccess,h=Me({queryKey:["forge-xp-metrics"],queryFn:_m}),c=Me({queryKey:["forge-reward-rules"],queryFn:S2,enabled:m}),p=Me({queryKey:["forge-reward-ledger"],queryFn:()=>T2(30),enabled:m}),g=Me({queryKey:["forge-psyche-overview"],queryFn:async()=>(await Dd()).overview}),x=Yo({defaultValues:{title:"",description:"",active:!0,configJson:"{}"}}),f=Yo({defaultValues:{entityType:"task",entityId:"",deltaXp:15,reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"}}),b=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-xp-metrics"]}),s.invalidateQueries({queryKey:["forge-reward-rules"]}),s.invalidateQueries({queryKey:["forge-reward-ledger"]})])},A=De({mutationFn:D=>C2(D.ruleId,{title:D.title,description:D.description,active:D.active,config:D.config}),onSuccess:b}),T=De({mutationFn:I2,onSuccess:b}),I=((j=c.data)==null?void 0:j.rules)??[],y=u.useMemo(()=>{var D,L,Q,Z,V,B;return{system:[{id:"operator_manual_reward",label:"Operator reward ledger"}],goal:t.snapshot.goals.map($=>({id:$.id,label:$.title})),project:t.snapshot.dashboard.projects.map($=>({id:$.id,label:$.title})),task:t.snapshot.tasks.map($=>({id:$.id,label:$.title})),habit:t.snapshot.habits.map($=>({id:$.id,label:$.title})),tag:t.snapshot.tags.map($=>({id:$.id,label:$.name})),note:[],insight:[],psyche_value:(((D=g.data)==null?void 0:D.values)??[]).map($=>({id:$.id,label:$.title})),behavior_pattern:(((L=g.data)==null?void 0:L.patterns)??[]).map($=>({id:$.id,label:$.title})),behavior:(((Q=g.data)==null?void 0:Q.behaviors)??[]).map($=>({id:$.id,label:$.title})),belief_entry:(((Z=g.data)==null?void 0:Z.beliefs)??[]).map($=>({id:$.id,label:$.statement})),mode_profile:(((V=g.data)==null?void 0:V.modes)??[]).map($=>({id:$.id,label:$.title})),trigger_report:(((B=g.data)==null?void 0:B.reports)??[]).map($=>({id:$.id,label:$.title}))}},[g.data,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits,t.snapshot.tags,t.snapshot.tasks]);u.useEffect(()=>{var Z;const D=f.getValues("entityType"),L=f.getValues("entityId"),Q=y[D]??[];L&&Q.some(V=>V.id===L)||f.setValue("entityId",((Z=Q[0])==null?void 0:Z.id)??"")},[f,y]),u.useEffect(()=>{I.length&&(!a||!I.some(D=>D.id===a))&&i(I[0].id)},[I,a]);const N=I.find(D=>D.id===a)??I[0]??null;u.useEffect(()=>{N&&(x.reset({title:N.title,description:N.description,active:N.active,configJson:gE(N.config)}),n(null))},[N,x]);const k=(R=h.data)==null?void 0:R.metrics,P=(((v=p.data)==null?void 0:v.ledger)??[]).filter(D=>D.metadata.manual===!0).slice(0,8);return d.isLoading?e.jsx(gs,{eyebrow:"Settings · Rewards",title:"Loading reward controls",description:"Establishing the operator session and fetching reward configuration.",columns:2,blocks:6}):d.isError?e.jsx(ct,{eyebrow:"Settings · Rewards",error:d.error,onRetry:()=>void d.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(mt,{title:"Rewards",description:"XP command deck, reward rule editor, manual bonus grants, and ledger history."}),e.jsx(Aa,{}),e.jsx("div",{className:"grid gap-5",children:e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Reward operations"}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[k?e.jsx(xE,{profile:k.profile,achievements:k.achievements,milestoneRewards:k.milestoneRewards,momentumPulse:k.momentumPulse,recentLedger:k.recentLedger}):null,k?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Os,{label:"Total XP",value:k.profile.totalXp,tone:"core"}),e.jsx(Os,{label:"Daily ambient",value:`${k.dailyAmbientXp} / ${k.dailyAmbientCap}`,tone:"core"})]}):null,e.jsxs("div",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Reward rule editor"}),I.length>0?e.jsxs("form",{className:"mt-4 grid gap-4",onSubmit:x.handleSubmit(async D=>{try{n(null);const L=Hg(D.configJson);if(!N)return;await A.mutateAsync({ruleId:N.id,title:D.title,description:D.description,active:D.active,config:L})}catch(L){n(L instanceof Error?L.message:"Invalid reward rule config.")}}),children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Rule"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:a,onChange:D=>i(D.target.value),children:I.map(D=>e.jsx("option",{value:D.id,children:D.title},D.id))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Title"}),e.jsx(be,{...x.register("title")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Description"}),e.jsx(st,{className:"min-h-24",...x.register("description")})]}),e.jsxs("label",{className:"flex items-center justify-between rounded-[18px] bg-[rgba(8,13,28,0.68)] px-4 py-3",children:[e.jsx("span",{className:"text-white/72",children:"Rule is active"}),e.jsx("input",{type:"checkbox",...x.register("active")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Config JSON"}),e.jsx(st,{className:"min-h-28 font-mono text-xs",...x.register("configJson")})]}),r?e.jsx("div",{className:"text-sm text-amber-300",children:r}):null,e.jsx(H,{type:"submit",pending:A.isPending,pendingLabel:"Saving rule",children:"Save reward rule"})]}):e.jsx("div",{className:"mt-4 text-sm text-white/58",children:"Loading reward rules…"})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Manual bonus XP"}),e.jsxs("form",{className:"mt-4 grid gap-4",onSubmit:f.handleSubmit(async D=>{try{o(null);const L=Hg(D.metadataJson);await T.mutateAsync({entityType:D.entityType,entityId:D.entityId,deltaXp:D.deltaXp,reasonTitle:D.reasonTitle,reasonSummary:D.reasonSummary,metadata:L}),f.reset({...D,entityId:"",reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"})}catch(L){o(L instanceof Error?L.message:"Invalid metadata payload.")}}),children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Entity type"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",...f.register("entityType"),children:Object.keys(y).map(D=>e.jsx("option",{value:D,children:D.replaceAll("_"," ")},D))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Entity id"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",...f.register("entityId"),children:(y[f.watch("entityType")]??[]).map(D=>e.jsx("option",{value:D.id,children:D.label},D.id))})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Delta XP"}),e.jsx(be,{type:"number",...f.register("deltaXp",{valueAsNumber:!0})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Reason title"}),e.jsx(be,{...f.register("reasonTitle")})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Reason summary"}),e.jsx(st,{className:"min-h-24",...f.register("reasonSummary")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Metadata JSON"}),e.jsx(st,{className:"min-h-24 font-mono text-xs",...f.register("metadataJson")})]}),l?e.jsx("div",{className:"text-sm text-amber-300",children:l}):null,e.jsx(H,{type:"submit",pending:T.isPending,pendingLabel:"Issuing bonus",children:"Issue bonus XP"})]}),T.data?e.jsxs("div",{className:"mt-4 rounded-[18px] bg-[rgba(192,193,255,0.12)] p-4 text-sm text-white",children:["Granted ",T.data.reward.deltaXp>0?"+":"",T.data.reward.deltaXp," XP for ",e.jsx("strong",{children:T.data.reward.reasonTitle}),"."]}):null]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Manual bonus history"}),e.jsx("div",{className:"mt-4 grid gap-3",children:P.length===0?e.jsx("div",{className:"rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4 text-sm text-white/58",children:"No manual bonus grants yet."}):P.map(D=>e.jsxs("div",{className:"rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:D.reasonTitle}),e.jsxs(S,{className:D.deltaXp>=0?"text-emerald-300":"text-amber-300",children:[D.deltaXp>0?"+":"",D.deltaXp," XP"]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:D.reasonSummary||"No summary supplied."}),e.jsxs("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/38",children:[D.entityType," · ",D.entityId," · ",new Date(D.createdAt).toLocaleString()]})]},D.id))})]})]})]})})]})}const Iv=[{id:"visibility",label:"Discovery and visibility",description:"What the source user can discover, inspect, and pull into read flows on the target side.",rights:[{key:"discoverable",label:"Discoverable",description:"The target appears as a reachable collaborator in the source user's graph and pickers."},{key:"canListUsers",label:"List users",description:"The source user can include the target in directory, comparison, and routing surfaces."},{key:"canReadProfile",label:"Read profile",description:"The source user can inspect the target's identity card, handle, type, and description."},{key:"canReadEntities",label:"Read entities",description:"The source user can read the target's goals, projects, tasks, notes, strategies, and related records."},{key:"canSearchEntities",label:"Search entities",description:"The source user can find the target's work through Forge search and entity pickers."}]},{id:"coordination",label:"Messaging, context, and handoff",description:"What the source user can message, connect, and coordinate on the target side before changing execution.",rights:[{key:"canLinkEntities",label:"Share context",description:"The source user can attach the target's records into shared notes, strategies, calendar context, and cross-owner plans."},{key:"canCoordinate",label:"Message and coordinate",description:"The source user can communicate with the target through Forge, hand off work, and coordinate execution."},{key:"canViewMetrics",label:"View metrics",description:"The source user can inspect the target's XP, alignment, and progress metrics."},{key:"canViewActivity",label:"View activity",description:"The source user can inspect the target's activity stream, evidence, and execution trail."}]},{id:"execution",label:"Plan and execution control",description:"What the source user can actually change on the target side once collaboration is trusted.",rights:[{key:"canManageStrategies",label:"Manage strategies",description:"The source user can draft and update strategies that belong to the target."},{key:"canCreateOnBehalf",label:"Create on behalf",description:"The source user can intentionally create new target-owned entities."},{key:"canAffectEntities",label:"Affect entities",description:"The source user can mutate work that belongs to the target."}]}],bE=[{id:"full_collab",label:"Full collaboration",description:"Use when two humans or agents can see, coordinate, plan, and change each other's work.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!0,canCoordinate:!0,canAffectEntities:!0,canManageStrategies:!0,canCreateOnBehalf:!0,canViewMetrics:!0,canViewActivity:!0}},{id:"coordination_only",label:"Coordinate only",description:"Use when the source user may see and coordinate with the target but should not directly mutate target-owned work.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!0,canCoordinate:!0,canAffectEntities:!1,canManageStrategies:!0,canCreateOnBehalf:!1,canViewMetrics:!0,canViewActivity:!0}},{id:"observe_only",label:"Observe only",description:"Use when the source user should keep visibility into the target without planning or execution control.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!1,canCoordinate:!1,canAffectEntities:!1,canManageStrategies:!1,canCreateOnBehalf:!1,canViewMetrics:!0,canViewActivity:!0}},{id:"hidden",label:"Hidden edge",description:"Use when this direction should stop discovering, reading, or acting on the target.",rights:{discoverable:!1,canListUsers:!1,canReadProfile:!1,canReadEntities:!1,canSearchEntities:!1,canLinkEntities:!1,canCoordinate:!1,canAffectEntities:!1,canManageStrategies:!1,canCreateOnBehalf:!1,canViewMetrics:!1,canViewActivity:!1}}],Zr=Iv.reduce((t,s)=>t+s.rights.length,0);function sc(t){return Object.values(t.config.rights).filter(Boolean).length}function Tv(t){const s=[];return t.config.rights.canReadEntities&&s.push("See"),t.config.rights.canCoordinate&&s.push("Message"),t.config.rights.canManageStrategies&&s.push("Plan"),t.config.rights.canAffectEntities&&s.push("Affect"),s.join(" · ")||"Hidden"}function yE(t){return!t.config.rights.discoverable&&!t.config.rights.canReadEntities?"Hidden":t.config.rights.canAffectEntities&&t.config.rights.canManageStrategies?"Trusted":t.config.rights.canCoordinate||t.config.rights.canLinkEntities?"Coordinated":"Observed"}function Pv(t){return[{id:"see",label:"See",enabled:t.config.rights.discoverable&&t.config.rights.canReadEntities&&t.config.rights.canSearchEntities},{id:"message",label:"Message",enabled:t.config.rights.canCoordinate},{id:"share",label:"Share context",enabled:t.config.rights.canLinkEntities},{id:"plan",label:"Plan",enabled:t.config.rights.canManageStrategies},{id:"affect",label:"Affect",enabled:t.config.rights.canAffectEntities||t.config.rights.canCreateOnBehalf}]}function wE(t,s){return Object.entries(s.rights).every(([a,i])=>t.config.rights[a]===i)}function vE(t,s){const a=t.filter(p=>p.kind==="human"),i=t.filter(p=>p.kind==="bot"),r={x:560,y:360},n={width:226,height:132},l=a[0]??null,d=[...a.slice(l?1:0).map(p=>({user:p,radius:245,offset:-90})),...i.map(p=>({user:p,radius:390,offset:-90}))],m=d.length,h=[...l?[{user:l,position:{x:r.x-n.width/2,y:r.y-n.height/2}}]:[],...d.map((p,g)=>{const x=(p.offset+360/Math.max(m,1)*g)*Math.PI/180;return{user:p.user,position:{x:r.x+Math.cos(x)*p.radius-n.width/2,y:r.y+Math.sin(x)*p.radius-n.height/2}}})],c=new Set(s.selectedGrant?[s.selectedGrant.subjectUserId,s.selectedGrant.targetUserId]:s.selectedUserId?[s.selectedUserId]:[]);return h.map(({user:p,position:g})=>{const x=c.has(p.id),f=p.id===s.selectedUserId;return{id:p.id,position:g,draggable:!1,selectable:!1,data:{label:e.jsxs("div",{className:`min-w-[206px] rounded-[22px] border px-4 py-4 shadow-[0_24px_60px_rgba(0,0,0,0.28)] transition ${f?"border-[rgba(244,185,122,0.45)] bg-[rgba(27,16,10,0.92)]":x?"border-white/18 bg-[rgba(14,20,34,0.94)]":"border-white/10 bg-[rgba(9,15,28,0.92)]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ht,{user:p}),e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:p.kind})]}),e.jsxs("div",{className:"mt-3 text-xs text-white/52",children:["@",p.handle]}),e.jsx("div",{className:"mt-2 line-clamp-2 text-xs leading-5 text-white/46",children:p.description||"No user description yet."})]})},style:{background:"transparent",border:"none",padding:0}}})}function jE(t,s,a){return t.filter(i=>i.subjectUserId!==i.targetUserId).map(i=>{const r=s===i.id,n=a!==null&&(i.subjectUserId===a||i.targetUserId===a),l=sc(i),o=r?"#f4b97a":!i.config.rights.discoverable&&!i.config.rights.canReadEntities?"rgba(248,113,113,0.55)":n?"rgba(192,193,255,0.78)":"rgba(255,255,255,0.32)";return{id:i.id,source:i.subjectUserId,target:i.targetUserId,label:`${Tv(i)} · ${l}/${Zr}`,markerEnd:{type:bm.ArrowClosed,color:o},labelStyle:{fill:r?"#f4b97a":"rgba(255,255,255,0.68)",fontSize:11,fontWeight:600},labelBgStyle:{fill:r?"rgba(34,23,16,0.96)":"rgba(8,13,24,0.94)",stroke:r?"rgba(244,185,122,0.36)":"rgba(255,255,255,0.14)",strokeWidth:1},labelBgPadding:[7,5],labelBgBorderRadius:8,style:{stroke:o,strokeWidth:r?2.5:n?1.8:1.25},animated:r}})}function kE({users:t,grants:s,selectedGrantId:a=null,selectedUserId:i=null,onOpenGrant:r,onOpenUser:n}){const l=s.find(g=>g.id===a)??null,o=u.useMemo(()=>vE(t,{selectedUserId:i,selectedGrant:l}),[l,i,t]),d=u.useMemo(()=>jE(s,a,i),[s,a,i]),m=u.useMemo(()=>s.filter(g=>g.subjectUserId!==g.targetUserId),[s]),h=m.filter(g=>sc(g)===Zr).length,c=m.filter(g=>g.config.rights.canCoordinate).length,p=m.filter(g=>g.config.rights.canAffectEntities||g.config.rights.canCreateOnBehalf).length;return e.jsxs(le,{className:"overflow-hidden p-0",children:[e.jsxs("div",{className:"grid gap-4 border-b border-white/8 px-5 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Directed relationship graph"}),e.jsx(Tt,{content:"Keep Forge, OpenClaw, Hermes, and the browser on the same runtime and storage root when these arrows should describe one shared human and bot system.",label:"Explain the shared runtime rule"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Click a user card to open that user's settings. Click any arrow to open the exact directional relationship flow for that lane."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[m.length," edges"]}),e.jsxs(S,{className:"bg-emerald-500/12 text-emerald-200",children:[h," fully open"]})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Full collaboration"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:h}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions still running with the default fully open posture."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Coordination lanes"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:c}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions allowed to coordinate directly through Forge."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Execution control"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:p}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions allowed to create or mutate target-owned work."})]})]})]}),e.jsx("div",{className:"h-[min(72vh,54rem)] min-h-[34rem] bg-[radial-gradient(circle_at_top,rgba(244,185,122,0.08),transparent_34%),linear-gradient(180deg,rgba(6,10,20,0.97),rgba(8,14,26,0.94))]",children:e.jsxs(Td,{className:"user-relationship-flow",nodes:o,edges:d,fitView:!0,fitViewOptions:{padding:.18,maxZoom:.95},nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,onNodeClick:(g,x)=>{n(x.id)},onEdgeClick:(g,x)=>{r(x.id)},attributionPosition:"bottom-left",children:[e.jsx(fm,{showInteractive:!1}),e.jsx(Pd,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})]})}const NE={kind:"human",handle:"",displayName:"",description:"",accentColor:"#c0c1ff"};function Gg(t){return t?{kind:t.kind,handle:t.handle,displayName:t.displayName,description:t.description,accentColor:t.accentColor}:NE}function SE({open:t,onOpenChange:s,user:a,grants:i,ownership:r,xp:n,pending:l=!1,onSubmit:o,onOpenRelationship:d}){const[m,h]=u.useState(()=>Gg(a)),[c,p]=u.useState(null);u.useEffect(()=>{t&&(h(Gg(a)),p(null))},[t,a]);const g=u.useMemo(()=>i.filter(A=>A.subjectUserId!==A.targetUserId),[i]),x=u.useMemo(()=>a?g.filter(A=>A.subjectUserId===a.id):[],[g,a]),f=u.useMemo(()=>a?g.filter(A=>A.targetUserId===a.id):[],[g,a]),b=[{id:"identity",eyebrow:a?"Edit user":"Create user",title:a?"Update the user identity":"Add a human or bot user",description:"Set the owner type and the public identity Forge will use across ownership, routing, and collaboration surfaces.",render:(A,T)=>e.jsxs(e.Fragment,{children:[e.jsx(oe,{label:"Kind",description:"Humans represent real people. Bots represent agents or automations with their own ownership lane.",children:e.jsx(St,{columns:2,value:A.kind,onChange:I=>T({kind:I}),options:[{value:"human",label:"Human",description:"Use for a real person in the Forge runtime."},{value:"bot",label:"Bot",description:"Use for an agent, assistant, or automation actor."}]})}),e.jsx(oe,{label:"Handle",description:"This becomes the stable short id shown as @handle.",hint:"Use lowercase and a durable label, for example forge-operator or planner-bot.",children:e.jsx(be,{value:A.handle,onChange:I=>T({handle:I.target.value}),placeholder:"forge-operator"})}),e.jsx(oe,{label:"Display name",description:"This is the human-readable label used across the UI.",children:e.jsx(be,{value:A.displayName,onChange:I=>T({displayName:I.target.value}),placeholder:"Forge Operator"})})]})},{id:"profile",eyebrow:"Profile",title:"Describe the user lane",description:"Capture what this user represents in the shared Forge runtime and pick the accent color that helps the lane stay recognizable.",render:(A,T)=>e.jsxs(e.Fragment,{children:[e.jsx(oe,{label:"Description",description:"Explain what this user is responsible for and what side of the system it represents.",children:e.jsx(st,{value:A.description,onChange:I=>T({description:I.target.value}),className:"min-h-36",placeholder:"Primary human operator for strategy, execution, and review."})}),e.jsx(oe,{label:"Accent color",description:"Forge uses this accent to help the user stand out in ownership and collaboration surfaces.",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(be,{value:A.accentColor,onChange:I=>T({accentColor:I.target.value}),placeholder:"#c0c1ff"}),e.jsx("div",{className:"size-10 shrink-0 rounded-full border border-white/10",style:{backgroundColor:A.accentColor||"#c0c1ff"}})]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Owned records"}),e.jsx("div",{className:"mt-2 text-white",children:(r==null?void 0:r.totalOwnedEntities)??0})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Total XP"}),e.jsx("div",{className:"mt-2 text-white",children:(n==null?void 0:n.totalXp)??0})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Weekly XP"}),e.jsx("div",{className:"mt-2 text-white",children:(n==null?void 0:n.weeklyXp)??0})]})]})]})},{id:"relationships",eyebrow:"Relationships",title:"Open directional relationship settings",description:"Each arrow is a separate contract. Open the exact lane you want to adjust and Forge will take you into the relationship flow.",render:()=>a?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx(ht,{user:a}),e.jsxs("div",{className:"mt-3 text-sm leading-6 text-white/56",children:["@",a.handle," · ",a.description||"No description yet."]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Outbound lanes"}),x.length>0?x.map(A=>e.jsxs("button",{type:"button",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-left transition hover:bg-white/[0.05]",onClick:()=>d(A.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ht,{user:A.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(ht,{user:A.targetUser})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:Tv(A)}),e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[sc(A),"/",Zr," rights"]})]})]},A.id)):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm text-white/52",children:"No outbound relationship lanes yet."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Inbound lanes"}),f.length>0?f.map(A=>e.jsxs("button",{type:"button",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-left transition hover:bg-white/[0.05]",onClick:()=>d(A.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ht,{user:A.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(ht,{user:A.targetUser})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Pv(A).map(T=>e.jsx(S,{className:T.enabled?"bg-white/[0.08] text-white/74":"bg-white/[0.04] text-white/38",children:T.label},`${A.id}-${T.id}`))})]},A.id)):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm text-white/52",children:"No inbound relationship lanes yet."})]})]})]}):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm leading-6 text-white/52",children:"Create the user first, then Forge will generate the directional relationship lanes you can tune from here."})}];return e.jsx(Kt,{open:t,onOpenChange:s,eyebrow:a?"User settings":"Create user",title:a?"User settings":"Create user",description:"Edit the user identity, clarify what this lane represents, and jump into relationship settings without crowding the page.",value:m,onChange:h,draftPersistenceKey:a?`users.settings.${a.id}`:"users.settings.new",steps:b,submitLabel:a?"Save user":"Create user",pending:l,pendingLabel:a?"Saving user":"Creating user",error:c,contentClassName:"lg:w-[min(58rem,calc(100vw-1.5rem))]",onSubmit:async()=>{const A=m.handle.trim(),T=m.displayName.trim();if(A.length===0){p("Add a handle before saving this user.");return}if(T.length===0){p("Add a display name before saving this user.");return}await o({userId:a==null?void 0:a.id,input:{kind:m.kind,handle:A,displayName:T,description:m.description.trim(),accentColor:m.accentColor.trim()||"#c0c1ff"}}),s(!1)}})}function Qg(t,s){return{accessLevel:(t==null?void 0:t.accessLevel)??"manage",applyScope:"this_arrow",rights:{discoverable:(t==null?void 0:t.config.rights.discoverable)??!0,canListUsers:(t==null?void 0:t.config.rights.canListUsers)??!0,canReadProfile:(t==null?void 0:t.config.rights.canReadProfile)??!0,canReadEntities:(t==null?void 0:t.config.rights.canReadEntities)??!0,canSearchEntities:(t==null?void 0:t.config.rights.canSearchEntities)??!0,canLinkEntities:(t==null?void 0:t.config.rights.canLinkEntities)??!0,canCoordinate:(t==null?void 0:t.config.rights.canCoordinate)??!0,canAffectEntities:(t==null?void 0:t.config.rights.canAffectEntities)??!0,canManageStrategies:(t==null?void 0:t.config.rights.canManageStrategies)??!0,canCreateOnBehalf:(t==null?void 0:t.config.rights.canCreateOnBehalf)??!0,canViewMetrics:(t==null?void 0:t.config.rights.canViewMetrics)??!0,canViewActivity:(t==null?void 0:t.config.rights.canViewActivity)??!0}}}function CE({open:t,onOpenChange:s,grant:a,grants:i,pending:r=!1,onSubmit:n}){const l=u.useMemo(()=>a?i.find(p=>p.subjectUserId===a.targetUserId&&p.targetUserId===a.subjectUserId)??null:null,[a,i]),[o,d]=u.useState(()=>Qg(a,!!l));u.useEffect(()=>{t&&d(Qg(a,!!l))},[a,t,l]);const m=u.useMemo(()=>Object.values(o.rights).filter(Boolean).length,[o.rights]),h=Math.round(m/Zr*100),c=[{id:"posture",eyebrow:"Relationship posture",title:"Set the trust mode for this arrow",description:"Each arrow is directional. Decide whether you want to tune only this lane or mirror the same contract onto both directions.",render:(p,g)=>e.jsxs(e.Fragment,{children:[a?e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ht,{user:a.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(ht,{user:a.targetUser})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/74",children:yE(a)}),e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:[sc(a),"/",Zr," rights"]})]})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Access level"}),e.jsx(St,{columns:2,value:p.accessLevel,onChange:x=>g({accessLevel:x}),options:[{value:"view",label:"View",description:"Use when this lane should stay mostly observational."},{value:"manage",label:"Manage",description:"Use when the source side can actively collaborate or act."}]})]}),l?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Apply scope"}),e.jsx(St,{columns:2,value:p.applyScope,onChange:x=>g({applyScope:x}),options:[{value:"this_arrow",label:"This arrow",description:"Only change the exact direction you opened."},{value:"both_arrows",label:"Both arrows",description:"Mirror the same contract onto the reverse direction too."}]})]}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Quick preset"}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:bE.map(x=>e.jsxs("button",{type:"button",className:`rounded-[22px] border p-4 text-left transition ${a&&wE(a,x)?"border-[rgba(244,185,122,0.35)] bg-[rgba(244,185,122,0.08)]":"border-white/8 bg-white/[0.03] hover:bg-white/[0.05]"}`,onClick:()=>g({rights:{...p.rights,...x.rights}}),children:[e.jsx("div",{className:"text-sm font-medium text-white",children:x.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:x.description})]},x.id))})]})]})},{id:"rights",eyebrow:"Rights",title:"Tune the individual permissions",description:"Use the preset as the starting point, then sharpen the exact boundaries only where this relationship needs them.",render:(p,g)=>e.jsx(e.Fragment,{children:Iv.map(x=>e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:x.label}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/54",children:x.description})]}),e.jsx("div",{className:"grid gap-2",children:x.rights.map(f=>e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:f.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:f.description})]}),e.jsx("input",{type:"checkbox",checked:p.rights[f.key],onChange:b=>g({rights:{...p.rights,[f.key]:b.target.checked}})})]},f.key))})]},x.id))})},{id:"review",eyebrow:"Review",title:"Review the final relationship contract",description:"Check the enabled capabilities, confirm whether both directions should match, and then save the relationship.",render:p=>{var g,x;return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Capability coverage"}),e.jsx("div",{className:"mt-4",children:e.jsx(Gs,{value:h})}),e.jsxs("div",{className:"mt-3 text-sm text-white/62",children:[m,"/",Zr," rights enabled"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Pv({...a??{id:"draft",subjectUserId:"",targetUserId:"",accessLevel:p.accessLevel,config:{self:!1,mutable:!0,linkedEntities:!0,rights:p.rights},createdAt:"",updatedAt:"",subjectUser:null,targetUser:null},accessLevel:p.accessLevel,config:{...(a==null?void 0:a.config)??{self:!1,mutable:!0,linkedEntities:!0},rights:p.rights}}).map(f=>e.jsx(S,{className:f.enabled?"bg-white/[0.08] text-white/74":"bg-white/[0.04] text-white/38",children:f.label},f.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Save scope"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:p.applyScope==="both_arrows"&&l?"Forge will apply the same access level and rights to both directions of this pair.":"Forge will only update the exact arrow you opened."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:["access ",p.accessLevel]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/74",children:["scope"," ",p.applyScope==="both_arrows"&&l?"both arrows":"this arrow"]})]}),l?e.jsxs("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/54",children:["Reverse arrow available:"," ",((g=l.subjectUser)==null?void 0:g.displayName)??l.subjectUserId," ","→"," ",((x=l.targetUser)==null?void 0:x.displayName)??l.targetUserId]}):null]})]})})}}];return e.jsx(Kt,{open:t,onOpenChange:s,eyebrow:"Relationship settings",title:"Relationship settings",description:"Edit the exact directional contract between two users without keeping the full rights editor pinned on the page.",value:o,onChange:d,draftPersistenceKey:a?`users.relationship.${a.id}`:"users.relationship.new",steps:c,submitLabel:"Save relationship",pending:r,pendingLabel:"Saving relationship",contentClassName:"lg:w-[min(62rem,calc(100vw-1.5rem))]",onSubmit:async()=>{a&&(await n({grantId:a.id,patch:{accessLevel:o.accessLevel,rights:o.rights},reverseGrantId:(l==null?void 0:l.id)??null,applyToReverse:o.applyScope==="both_arrows"&&l!==null}),s(!1))}})}function IE(){var j;const t=Ct(),[s,a]=u.useState(null),[i,r]=u.useState(null),[n,l]=u.useState(!1),[o,d]=u.useState(!1),[m,h]=u.useState(""),c=Me({queryKey:["forge-user-directory"],queryFn:a2}),p=async()=>{await Promise.all([t.refresh(),c.refetch()])},g=De({mutationFn:async({input:R,userId:v})=>v?(await n2(v,R)).user:(await r2(R)).user,onSuccess:async()=>{a(null),l(!1),await p()}}),x=De({mutationFn:async({grantId:R,patch:v})=>(await i2(R,v)).grant,onSuccess:p}),f=(j=c.data)==null?void 0:j.directory,b=(f==null?void 0:f.grants.find(R=>R.id===i))??null,A=u.useMemo(()=>new Map(((f==null?void 0:f.ownership)??[]).map(R=>[R.userId,R])),[f==null?void 0:f.ownership]),T=u.useMemo(()=>new Map(((f==null?void 0:f.xp)??[]).map(R=>[R.userId,R])),[f==null?void 0:f.xp]),I=u.useMemo(()=>{const R=new Map;for(const v of(f==null?void 0:f.grants)??[]){if(!v.targetUser||v.subjectUserId===v.targetUserId)continue;const D=R.get(v.subjectUserId)??[];D.push(v.targetUser),R.set(v.subjectUserId,D)}return R},[f==null?void 0:f.grants]),y=u.useMemo(()=>{const R=((f==null?void 0:f.grants)??[]).filter(v=>v.subjectUserId!==v.targetUserId);return{totalEdges:R.length,fullyOpenEdges:R.filter(v=>Object.values(v.config.rights).every(Boolean)).length,coordinationEdges:R.filter(v=>v.config.rights.canCoordinate).length,executionEdges:R.filter(v=>v.config.rights.canAffectEntities||v.config.rights.canCreateOnBehalf).length}},[f==null?void 0:f.grants]),N=m.trim().toLowerCase(),k=u.useMemo(()=>{const v=((f==null?void 0:f.users)??t.snapshot.users).filter(D=>N?[D.displayName,D.handle,D.kind,D.description].join(" ").toLowerCase().includes(N):!0);return{humans:v.filter(D=>D.kind==="human"),bots:v.filter(D=>D.kind==="bot")}},[f==null?void 0:f.users,N,t.snapshot.users]),w=(b==null?void 0:b.subjectUserId)??(s==null?void 0:s.id)??null,P=(b==null?void 0:b.id)??null;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(mt,{title:"Users",description:"Forge users can be human or bot. Ownership, search, and routing are prepared so work can move across both sides of the system.",badge:`${t.snapshot.users.length} users`}),e.jsx(Aa,{}),e.jsx(SE,{open:n,onOpenChange:l,user:s,grants:(f==null?void 0:f.grants)??[],ownership:s?A.get(s.id)??null:null,xp:s?T.get(s.id)??null:null,pending:g.isPending,onSubmit:async R=>{await g.mutateAsync(R)},onOpenRelationship:R=>{l(!1),r(R),d(!0)}}),e.jsx(CE,{open:o,onOpenChange:d,grant:b,grants:(f==null?void 0:f.grants)??[],pending:x.isPending,onSubmit:async R=>{await x.mutateAsync({grantId:R.grantId,patch:R.patch}),R.applyToReverse&&R.reverseGrantId&&await x.mutateAsync({grantId:R.reverseGrantId,patch:R.patch})}}),e.jsxs(le,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Multi-user posture"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:(f==null?void 0:f.posture.summary)??"Forge is preparing modular user access while keeping the current posture permissive."})]}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:(f==null?void 0:f.posture.accessModel)??"permissive"})]}),e.jsx("div",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:e.jsx(be,{value:m,onChange:R=>h(R.target.value),placeholder:"Search human, bot, @handle, or description"})})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Multi-agent onboarding"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:"Forge now treats the users graph as the collaboration control plane. Create each human or bot here, keep the runtime shared, then narrow only the specific arrows that should stop seeing, coordinating, planning, or affecting another user."})]}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:"default open"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Directional edges"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y.totalEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Fully open"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y.fullyOpenEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Coordination"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y.coordinationEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Execution control"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y.executionEdges})]})]}),e.jsxs("div",{className:"grid gap-2 text-sm leading-6 text-white/56",children:[e.jsx("div",{children:"1. Create the human and bot users that should exist in the shared Forge system."}),e.jsx("div",{children:"2. Point OpenClaw, Hermes, and the browser at the same Forge runtime and storage root."}),e.jsx("div",{children:"3. Use the graph below to decide what each direction can see, message, plan, or change."}),e.jsx("div",{children:"4. Keep strategy drafting open while the plan is negotiated, then lock the strategy once it becomes the contract."})]})]}),e.jsx(kE,{users:(f==null?void 0:f.users)??t.snapshot.users,grants:(f==null?void 0:f.grants)??[],selectedGrantId:P,selectedUserId:w,onOpenUser:R=>{const v=((f==null?void 0:f.users)??t.snapshot.users).find(D=>D.id===R)??null;r(null),a(v),l(!0)},onOpenGrant:R=>{a(null),r(R),d(!0)}}),e.jsxs(le,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Agent onboarding"}),e.jsx("div",{className:"text-sm leading-6 text-white/60",children:"OpenClaw, Hermes, and the Forge UI all read this same multi-user graph. Keep the defaults open while you are still wiring collaboration, then narrow specific arrows when one user or agent should stop seeing, messaging, planning, or changing another user's work."}),e.jsx("div",{className:"text-sm leading-6 text-white/52",children:"Forge now treats every owner as either human or bot, keeps search cross-user by default, and allows cross-owner links plus explicit coordination lanes between projects, tasks, notes, and strategies."}),e.jsx("div",{children:e.jsx(et,{to:"/settings/agents",className:"inline-flex min-h-10 items-center justify-center rounded-[var(--radius-control)] bg-white/8 px-3 py-2 text-[13px] font-medium text-white transition hover:bg-white/12",children:"Open agent onboarding"})})]})]}),e.jsx(le,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"User directory"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:"Open any user to edit its identity and jump into the exact directional relationship lanes from the user settings flow."})]}),e.jsx(H,{onClick:()=>{r(null),a(null),l(!0)},children:"Create user"})]})}),e.jsx("div",{className:"grid gap-5",children:[{title:"Human users",users:k.humans},{title:"Bot users",users:k.bots}].map(R=>e.jsxs(le,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:R.title}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:R.users.length})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:R.users.map(v=>{var D,L,Q,Z,V,B;return e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(ht,{user:v}),e.jsxs("div",{className:"mt-3 text-sm text-white/58",children:["@",v.handle]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:v.description||"No description yet."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[((D=T.get(v.id))==null?void 0:D.totalXp)??0," XP"]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[((L=T.get(v.id))==null?void 0:L.weeklyXp)??0," weekly"]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[((Q=T.get(v.id))==null?void 0:Q.rewardEventCount)??0," ","rewards"]}),Object.entries(((Z=A.get(v.id))==null?void 0:Z.entityCounts)??{}).sort(($,E)=>E[1]-$[1]).slice(0,4).map(([$,E])=>e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[E," ",$]},`${v.id}-${$}`)),e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[((V=A.get(v.id))==null?void 0:V.totalOwnedEntities)??0," ","owned"]})]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/50",children:["Can currently read:"," ",(I.get(v.id)??[]).map($=>`${$.displayName} (${$.kind})`).join(", ")||"no other users"]}),(B=T.get(v.id))!=null&&B.lastRewardAt?e.jsxs("div",{className:"mt-2 text-xs leading-5 text-white/45",children:["Last XP movement:"," ",new Date(T.get(v.id).lastRewardAt).toLocaleString()]}):null]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(H,{variant:"secondary",onClick:()=>{r(null),a(v),l(!0)},children:"Open settings"})})]})},v.id)})})]},R.title))})]})]})}const Eh=[{id:"xp_levels",label:"XP and level",trophyCount:8,unlockCount:4},{id:"streaks",label:"Streak and comeback",trophyCount:14,unlockCount:10},{id:"tasks",label:"Tasks and focus runs",trophyCount:14,unlockCount:4},{id:"projects",label:"Projects, goals, and strategy",trophyCount:14,unlockCount:4},{id:"wiki",label:"Wiki, notes, and knowledge graph",trophyCount:16,unlockCount:6},{id:"psyche",label:"Psyche",trophyCount:18,unlockCount:10},{id:"habits",label:"Habits, Life Force, and health",trophyCount:8,unlockCount:8},{id:"agents",label:"Agents and collaboration",trophyCount:4,unlockCount:2}],TE=[1,2,3,5,7,14,21,30,45,60,90,180,365,730],PE=[1,2,3,5,7,10,14,21,30,60];function Te(t,s){return{metric:t,threshold:s}}function At(...t){return{allOf:t}}function wd(t){return t.toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function AE(t,s){const a=(t+1)/s;return a>.82?"platinum":a>.55?"gold":a>.25?"silver":"bronze"}function ME(t){return t==="platinum"?"legendary":t==="gold"?"hard":t==="silver"?"standard":"intro"}function EE(t){return t==="platinum"?"legendary":t==="gold"?"epic":t==="silver"?"rare":"common"}function LE(t){return`item-${t.kind}-${wd(t.category)}-${wd(t.title)}`}function Ze(t,s,a,i,r,n){return{category:t,kind:"trophy",title:s,summary:r,requirement:a,requirementText:i,reward:`${s} trophy on the Forge shelf`}}function gt(t,s,a,i,r,n,l){return{category:t,kind:"unlock",title:s,summary:n,requirement:i,requirementText:r,reward:`${s} cosmetic`,unlockType:a,rewardPayload:l}}const _E=[Ze("xp_levels","The First Heat",Te("nonManualXp",5e3),"Earn 5,000 non-manual XP.","The first real furnace of work is hot enough to be noticed."),Ze("xp_levels","Bellows Graduate",Te("nonManualXp",1e4),"Earn 10,000 non-manual XP.","Your reward ledger is no longer a spark; it is a system."),Ze("xp_levels","Iron Apprentice",Te("nonManualXp",2e4),"Earn 20,000 non-manual XP.","You have repeated the work enough that the anvil knows your hand."),Ze("xp_levels","Steel Temper",Te("nonManualXp",5e4),"Earn 50,000 non-manual XP.","Pressure has started to make the metal cleaner instead of louder."),Ze("xp_levels","Crown of Coals",Te("nonManualXp",1e5),"Earn 100,000 non-manual XP.","A visible crown for an invisible mountain of completed work."),Ze("xp_levels","Obsidian Master",Te("nonManualXp",25e4),"Earn 250,000 non-manual XP.","The Forge Smith stops testing your seriousness and starts respecting it."),Ze("xp_levels","Star-Forge Adept",Te("nonManualXp",5e5),"Earn 500,000 non-manual XP.","Your XP trail burns like a constellation across the operating system."),Ze("xp_levels","Mythic Smith",Te("nonManualXp",1e6),"Earn 1,000,000 non-manual XP.","A ridiculous trophy for a ridiculous amount of lived execution.")],FE=[gt("xp_levels","Obsidian Smith","mascot_skin",Te("nonManualXp",8e3),"Earn 8,000 non-manual XP.","A dramatic black-iron Forge Smith skin.",{mascotSkin:"obsidian-smith"}),gt("xp_levels","Molten Progress Bar","hud_treatment",Te("nonManualXp",25e3),"Earn 25,000 non-manual XP.","A bright molten XP fill for the level ring.",{hudTreatment:"molten-progress"}),gt("xp_levels","Apex Level Frame","icon_frame",Te("nonManualXp",1e5),"Earn 100,000 non-manual XP.","A high-tier frame for level and trophy icons.",{iconFrame:"apex-level"}),gt("xp_levels","Masterwork Glow","celebration_variant",Te("nonManualXp",25e4),"Earn 250,000 non-manual XP.","A stronger forge-bell reveal for major unlocks.",{celebrationVariant:"masterwork-glow"})],RE=[Ze("streaks","Spark Kept",Te("longestStreakDays",1),"Play one qualifying day.","The first day is small, but the forge heard it."),Ze("streaks","Three-Day Furnace",Te("longestStreakDays",3),"Reach a 3-day streak.","Three returns make the first shape of discipline."),Ze("streaks","Week-Fire",Te("longestStreakDays",7),"Reach a 7-day streak.","Seven days changes the temperature of your life."),Ze("streaks","Twin-Week Bellows",Te("longestStreakDays",14),"Reach a 14-day streak.","Two weeks of showing up makes the room expect you."),Ze("streaks","Cinder Discipline",Te("longestStreakDays",21),"Reach a 21-day streak.","The fire is not accidental anymore."),Ze("streaks","Monthly Forge",Te("longestStreakDays",30),"Reach a 30-day streak.","A full month of returns becomes a personal weather system."),Ze("streaks","Sixty-Day Flame",Te("longestStreakDays",60),"Reach a 60-day streak.","The Smith grows stronger because you stopped disappearing."),Ze("streaks","Quarter-Anvil",Te("longestStreakDays",90),"Reach a 90-day streak.","Ninety days is not motivation. It is architecture."),Ze("streaks","Half-Year Inferno",Te("longestStreakDays",180),"Reach a 180-day streak.","The forge is now a season of your life."),Ze("streaks","Year of Steel",Te("longestStreakDays",365),"Reach a 365-day streak.","A year of returns. The anvil has become a witness."),Ze("streaks","Comeback Hammer",Te("comebackAfter7Count",1),"Return after 7+ missed days and complete a qualifying action.","You came back after the room went cold."),Ze("streaks","Repair Artist",Te("comebackAfter7Count",3),"Complete 3 major comebacks.","Breaking the chain did not become breaking the story."),Ze("streaks","Rust Refuser",At(Te("comebackAfter7Count",5),Te("longestStreakDays",30)),"Complete 5 major comebacks and reach a 30-day streak.","You repeatedly turned absence into a new strike."),Ze("streaks","Relentless Return",At(Te("comebackAfter7Count",8),Te("longestStreakDays",90)),"Complete 8 major comebacks and reach a 90-day streak.","This trophy is for the part of you that keeps coming back.")],DE=[gt("streaks","Bronze Ember Flame","streak_effect",Te("longestStreakDays",3),"Reach a 3-day streak.","A small ember around the streak HUD.",{streakEffect:"bronze-ember"}),gt("streaks","Blue Forge-Fire","streak_effect",Te("longestStreakDays",7),"Reach a 7-day streak.","A cool blue streak flame.",{streakEffect:"blue-forge-fire"}),gt("streaks","Violet Arc Flame","streak_effect",Te("longestStreakDays",21),"Reach a 21-day streak.","A sharper violet flame effect.",{streakEffect:"violet-arc"}),gt("streaks","Molten Crown Fire","streak_effect",Te("longestStreakDays",60),"Reach a 60-day streak.","A crown-like fire treatment for streaks.",{streakEffect:"molten-crown"}),gt("streaks","Stern Pressure Pose","mascot_pose",Te("comebackAfter7Count",1),"Complete a major comeback.","Unlocks the Smith's stern pressure pose.",{mascotPose:"stern-pressure"}),gt("streaks","Comeback Pose","mascot_pose",Te("comebackAfter7Count",2),"Complete 2 major comebacks.","Unlocks the Smith's comeback repair pose.",{mascotPose:"comeback"}),gt("streaks","Awakening Forge Pose","mascot_pose",Te("longestStreakDays",30),"Reach a 30-day streak.","Unlocks the forge awakening mascot pose.",{mascotPose:"awakening-forge"}),gt("streaks","Yearfire Aura","streak_effect",Te("longestStreakDays",365),"Reach a 365-day streak.","A huge aura for year-scale presence.",{streakEffect:"yearfire-aura"}),gt("streaks","Old Foundry Shelf","trophy_shelf",Te("longestStreakDays",90),"Reach a 90-day streak.","A warmer trophy shelf skin.",{trophyShelf:"old-foundry"}),gt("streaks","Relentless Bell","celebration_variant",Te("longestStreakDays",180),"Reach a 180-day streak.","A heavier celebration sound-and-spark treatment.",{celebrationVariant:"relentless-bell"})],$E=[Ze("tasks","First Strike",Te("taskCompletionCount",25),"Complete 25 tasks.","A real task trail begins."),Ze("tasks","Clean Swing",At(Te("taskCompletionCount",50),Te("focusRunCount",10)),"Complete 50 tasks and 10 task runs.","Tasks and time-tracked execution start to converge."),Ze("tasks","Five Rivets",At(Te("taskCompletionCount",75),Te("taskCloseoutReportCount",5)),"Complete 75 tasks and 5 completion reports.","You are leaving proof behind, not just checkmarks."),Ze("tasks","Task Blade",At(Te("taskCompletionCount",120),Te("focusRunCount",25)),"Complete 120 tasks and 25 task runs.","A sharp blade forged out of repeated finishes."),Ze("tasks","Anvil Marathon",At(Te("taskCompletionCount",300),Te("focusRunCount",75)),"Complete 300 tasks and 75 task runs.","The long road achievement for serious execution."),Ze("tasks","Deep-Work Maul",Te("creditedFocusMinutes",3e3),"Log 3,000 credited focus minutes.","The heavy hammer of deliberate time."),Ze("tasks","Planned Heat",Te("plannedFocusRunCount",25),"Complete 25 planned task runs.","You planned the heat before striking the metal."),Ze("tasks","Closeout Scribe",Te("taskCloseoutReportCount",25),"Write 25 task completion reports.","The Forge remembers what changed because you wrote it down."),Ze("tasks","Hundred-Hammer Road",Te("taskCompletionCount",500),"Complete 500 tasks.","A road paved with finished work."),Ze("tasks","Timebox Knight",At(Te("plannedFocusRunCount",75),Te("creditedFocusMinutes",7500)),"Complete 75 planned runs and 7,500 focus minutes.","A trophy for time that obeyed the mission."),Ze("tasks","Backlog Breaker",Te("taskCompletionCount",750),"Complete 750 tasks.","The backlog learned to fear your return."),Ze("tasks","Execution Monarch",At(Te("taskCompletionCount",1e3),Te("focusRunCount",200)),"Complete 1,000 tasks and 200 task runs.","A crown for turning vague intention into finished artifacts."),Ze("tasks","Forge Ledger Exact",Te("taskCloseoutReportCount",100),"Write 100 task completion reports.","The most boring discipline becomes the most useful history."),Ze("tasks","The Hammer Does Not Blink",At(Te("taskCompletionCount",1500),Te("creditedFocusMinutes",15e3)),"Complete 1,500 tasks and 15,000 focus minutes.","For absurd consistency under real load.")],OE=[gt("tasks","Hammer Cursor","icon_frame",Te("taskCompletionCount",75),"Complete 75 tasks.","A hammer-shaped action accent.",{iconFrame:"hammer-cursor"}),gt("tasks","Focus Rail Glow","hud_treatment",Te("focusRunCount",25),"Complete 25 task runs.","A task-run glow for compact HUDs.",{hudTreatment:"focus-rail-glow"}),gt("tasks","Completion Burst","celebration_variant",Te("taskCloseoutReportCount",25),"Write 25 completion reports.","A sharper task-completion burst.",{celebrationVariant:"completion-burst"}),gt("tasks","Ember Knight","mascot_skin",Te("taskCompletionCount",500),"Complete 500 tasks.","A molten-armored Forge Smith skin for execution mastery.",{mascotSkin:"ember-knight"})],zE=[Ze("projects","Aligned Spark",Te("goalLinkedTaskCompletionCount",25),"Complete 25 goal-linked tasks.","Work starts pointing at something bigger."),Ze("projects","Goal Rivet",At(Te("goalLinkedTaskCompletionCount",50),Te("distinctGoalsWithCompletions",3)),"Complete 50 goal-linked tasks across 3 goals.","Several goals now have real rivets, not just titles."),Ze("projects","Strategist's Seal",At(Te("goalLinkedTaskCompletionCount",50),Te("distinctGoalsWithCompletions",5)),"Complete 50 goal-linked tasks across 5 goals.","A seal for strategy that survived contact with execution."),Ze("projects","Project Spine",At(Te("projectLinkedTaskCompletionCount",100),Te("activeProjectCount",5)),"Complete 100 project-linked tasks while maintaining 5 active projects.","The work has a spine across multiple initiatives."),Ze("projects","Strategy Weld",Te("strategyCount",10),"Create 10 strategies.","You forged planning layers instead of improvising every day."),Ze("projects","Purpose Hammer",Te("goalLinkedTaskCompletionCount",150),"Complete 150 goal-linked tasks.","The hammer keeps landing where your stated life points."),Ze("projects","Arc Builder",At(Te("projectLinkedTaskCompletionCount",250),Te("distinctGoalsWithCompletions",8)),"Complete 250 project-linked tasks across 8 goals.","Multiple arcs moved because you kept building."),Ze("projects","North-Star Foundry",At(Te("goalLinkedTaskCompletionCount",300),Te("strategyCount",20)),"Complete 300 goal-linked tasks and create 20 strategies.","The north star is no longer decorative."),Ze("projects","Project Finisher",Te("projectCompletionCount",5),"Complete 5 projects.","Finished projects leave heavier evidence than active dreams."),Ze("projects","Life-Work Crown",At(Te("projectCompletionCount",10),Te("goalLinkedTaskCompletionCount",500)),"Complete 10 projects and 500 goal-linked tasks.","A crown for long arcs that actually closed."),Ze("projects","Portfolio Anvil",Te("activeProjectCount",12),"Maintain 12 active projects.","A large operating portfolio, held without flattening."),Ze("projects","Tracer Bullet Guild",At(Te("projectCompletionCount",15),Te("strategyCount",35)),"Complete 15 projects and create 35 strategies.","Strategy and delivery joined hands repeatedly."),Ze("projects","Mountain Moved",Te("goalLinkedTaskCompletionCount",1e3),"Complete 1,000 goal-linked tasks.","The trophy for moving a mountain one task at a time."),Ze("projects","The Work Had A Spine",At(Te("projectCompletionCount",25),Te("distinctGoalsWithCompletions",12)),"Complete 25 projects across 12 goals.","Your life map became execution history.")],KE=[gt("projects","Goal Compass Frame","icon_frame",Te("goalLinkedTaskCompletionCount",50),"Complete 50 goal-linked tasks.","A compass frame for aligned-work trophies.",{iconFrame:"goal-compass"}),gt("projects","War-Room Iron Shelf","trophy_shelf",Te("projectLinkedTaskCompletionCount",150),"Complete 150 project-linked tasks.","A darker tactical trophy shelf.",{trophyShelf:"war-room-iron"}),gt("projects","North-Star HUD","hud_treatment",Te("strategyCount",20),"Create 20 strategies.","A strategy-forward HUD treatment.",{hudTreatment:"north-star"}),gt("projects","Foundry Compass Burst","celebration_variant",Te("projectCompletionCount",10),"Complete 10 projects.","A compass-shaped major reveal.",{celebrationVariant:"foundry-compass"})],qE=[Ze("wiki","First Inscription",Te("wikiPageCount",50),"Create 50 wiki pages.","Knowledge has started to become an archive."),Ze("wiki","Memory Rivet",Te("noteCount",100),"Create 100 notes.","The system remembers because you gave it material."),Ze("wiki","Archive Ember",At(Te("wikiPageCount",150),Te("wikiLinkCount",50)),"Create 150 wiki pages and 50 wiki links.","The archive starts connecting to itself."),Ze("wiki","Knowledge Anvil",At(Te("wikiPageCount",250),Te("wikiLinkCount",150)),"Create 250 wiki pages and 150 wiki links.","A serious anvil of memory and links."),Ze("wiki","Living Index",At(Te("wikiPageWithSummaryCount",100),Te("linkedWikiPageCount",100)),"Maintain 100 wiki pages with summaries and linked entities.","Pages now carry shape, summary, and relationships."),Ze("wiki","Black Library",At(Te("wikiPageCount",500),Te("wikiLinkCount",300)),"Create 500 wiki pages and 300 wiki links.","The great hard knowledge trophy."),Ze("wiki","Obsidian Index",At(Te("wikiPageWithSummaryCount",250),Te("wikiLinkCount",500)),"Maintain 250 summarized pages and 500 links.","The archive is no longer just big; it is navigable."),Ze("wiki","Graph Lantern",Te("knowledgeGraphNodeCount",500),"Reach 500 Knowledge Graph nodes.","The graph has enough stars to navigate by."),Ze("wiki","Entity Weaver",Te("linkedWikiPageCount",200),"Link 200 wiki pages to other pages or entities.","Your memory connects to the operating system."),Ze("wiki","Codex Temper",At(Te("wikiPageCount",750),Te("wikiLinkCount",750)),"Create 750 wiki pages and 750 wiki links.","A codex tempered by breadth and connection."),Ze("wiki","Note Furnace",Te("noteCount",500),"Create 500 notes.","Raw notes became a real furnace of evidence."),Ze("wiki","Archive Cartographer",At(Te("wikiPageWithSummaryCount",400),Te("linkedWikiPageCount",300)),"Maintain 400 summarized pages and 300 linked pages.","You mapped the archive enough that it can map you back."),Ze("wiki","The Shelf Breathes",Te("knowledgeGraphNodeCount",1e3),"Reach 1,000 Knowledge Graph nodes.","The knowledge system feels alive at a glance."),Ze("wiki","Librarian of Coals",At(Te("noteCount",1e3),Te("wikiLinkCount",1e3)),"Create 1,000 notes and 1,000 wiki links.","A trophy for the long, quiet archive discipline."),Ze("wiki","Living Codex",At(Te("wikiPageCount",1500),Te("wikiPageWithSummaryCount",750),Te("wikiLinkCount",1500)),"Create 1,500 pages, 750 summarized pages, and 1,500 links.","The living memory crown."),Ze("wiki","Memory Starfield",Te("knowledgeGraphNodeCount",2e3),"Reach 2,000 Knowledge Graph nodes.","The graph becomes a sky.")],BE=[gt("wiki","Quiet Library Shelf","trophy_shelf",Te("wikiPageCount",150),"Create 150 wiki pages.","A quiet library shelf skin.",{trophyShelf:"quiet-library"}),gt("wiki","Rune Page Frame","icon_frame",Te("wikiLinkCount",150),"Create 150 wiki links.","A runic frame for knowledge trophies.",{iconFrame:"rune-page"}),gt("wiki","Scholar Glass HUD","hud_treatment",Te("wikiPageWithSummaryCount",100),"Maintain 100 summarized wiki pages.","A glassy scholar HUD treatment.",{hudTreatment:"scholar-glass"}),gt("wiki","Archive Sparks","celebration_variant",Te("linkedWikiPageCount",200),"Link 200 wiki pages to other pages or entities.","A page-flare reveal variant.",{celebrationVariant:"archive-sparks"}),gt("wiki","Astral Archive Shelf","trophy_shelf",Te("knowledgeGraphNodeCount",1e3),"Reach 1,000 Knowledge Graph nodes.","A cosmic trophy shelf for memory work.",{trophyShelf:"astral-archive"}),gt("wiki","Reading Smith Pose","mascot_pose",Te("wikiPageWithSummaryCount",250),"Maintain 250 summarized wiki pages.","Unlocks the Forge Smith reading pose.",{mascotPose:"reading"})],UE=[Ze("psyche","Named Spark",Te("psycheValueCount",5),"Create 5 Psyche values.","You named the values the forge should obey."),Ze("psyche","Pattern Tongs",Te("behaviorPatternCount",5),"Create 5 behavior patterns.","The recurring loops are now held with tongs."),Ze("psyche","Belief Crucible",Te("beliefEntryCount",5),"Create 5 belief entries.","Beliefs entered the fire where they can be worked."),Ze("psyche","Mode Lantern",Te("modeProfileCount",3),"Create 3 mode profiles.","The inner cast has names and lantern light."),Ze("psyche","Trigger Witness",Te("triggerReportCount",3),"Create 3 trigger reports.","You turned moments of activation into evidence."),Ze("psyche","Mode Cartographer",At(Te("modeProfileCount",8),Te("linkedModeProfileCount",8)),"Create 8 mode profiles, each linked to a value, behavior, or pattern.","A map of modes, not a pile of labels."),Ze("psyche","Trigger Alchemist",At(Te("triggerReportRichCount",30),Te("triggerReportCompletedCount",20)),"Complete 30 rich trigger reports and mark 20 reports beyond draft.","Activation was turned into material for change."),Ze("psyche","Pattern Breaker",At(Te("behaviorPatternCount",20),Te("behaviorPatternWithReplacementCount",10)),"Create 20 patterns and link 10 to replacement responses.","The old loops now have counter-moves."),Ze("psyche","Belief Temperer",At(Te("beliefEntryCount",25),Te("beliefFlexibleAlternativeCount",25)),"Create 25 beliefs with flexible alternatives.","Rigid beliefs were heated until they could bend."),Ze("psyche","Value Blade",At(Te("psycheValueCount",10),Te("goalLinkedTaskCompletionCount",100)),"Create 10 values and complete 100 goal-linked tasks.","Values and work started cutting in the same direction."),Ze("psyche","Shadow Temper",At(Te("modeProfileCount",12),Te("triggerReportRichCount",50)),"Create 12 modes and 50 rich trigger reports.","Shadow material became usable steel."),Ze("psyche","Inner Forge",At(Te("psycheValueCount",12),Te("behaviorPatternCount",25),Te("beliefFlexibleAlternativeCount",30)),"Create 12 values, 25 patterns, and 30 flexible beliefs.","A full inner forge takes shape."),Ze("psyche","Schema Bell",Te("questionnaireRunCount",40),"Complete 40 questionnaire runs.","Structured self-observation rang the bell repeatedly."),Ze("psyche","Mode Guide",Te("modeGuideSessionCount",5),"Complete 5 mode guide sessions.","Guided mode work became an actual practice."),Ze("psyche","Repair Script",Te("behaviorCount",10),"Create 10 Psyche behaviors.","Behaviors now carry repair plans, not just names."),Ze("psyche","Flexible Self",Te("beliefFlexibleAlternativeCount",50),"Create 50 beliefs with flexible alternatives.","A trophy for not letting old beliefs remain iron cages."),Ze("psyche","Trigger Cartography",Te("triggerReportRichCount",100),"Create 100 rich trigger reports.","The map of activation became detailed enough to steer by."),Ze("psyche","The Inner Council",At(Te("modeProfileCount",20),Te("behaviorCount",20),Te("beliefFlexibleAlternativeCount",75)),"Create 20 modes, 20 behaviors, and 75 flexible beliefs.","The inner system became a council instead of noise.")],WE=[gt("psyche","Scholar Smith","mascot_skin",Te("psycheValueCount",7),"Create 7 Psyche values.","A wise, bookish Forge Smith skin.",{mascotSkin:"scholar-smith"}),gt("psyche","Wise Smith Pose","mascot_pose",Te("modeProfileCount",3),"Create 3 mode profiles.","Unlocks the wise mentor pose.",{mascotPose:"wise"}),gt("psyche","Reflection Frame","icon_frame",Te("beliefEntryCount",10),"Create 10 belief entries.","A reflective frame for Psyche trophies.",{iconFrame:"reflection"}),gt("psyche","Mode Lens HUD","hud_treatment",Te("modeProfileCount",8),"Create 8 mode profiles.","A HUD tuned to Psyche work.",{hudTreatment:"mode-lens"}),gt("psyche","Shadow Smith","mascot_skin",Te("triggerReportRichCount",25),"Create 25 rich trigger reports.","A darker Smith skin for shadow work.",{mascotSkin:"shadow-smith"}),gt("psyche","Arcane Metallurgist","mascot_skin",Te("beliefFlexibleAlternativeCount",25),"Create 25 beliefs with flexible alternatives.","A rune-lit Smith skin for deep reflection.",{mascotSkin:"arcane-metallurgist"}),gt("psyche","Inner-Fire Halo","streak_effect",Te("psycheValueCount",10),"Create 10 Psyche values.","A halo-like flame for reflective momentum.",{streakEffect:"inner-fire-halo"}),gt("psyche","Mode Lantern Reveal","celebration_variant",Te("modeProfileCount",12),"Create 12 mode profiles.","A lantern reveal for Psyche unlocks.",{celebrationVariant:"mode-lantern"}),gt("psyche","Therapist's Shelf","trophy_shelf",Te("triggerReportRichCount",50),"Create 50 rich trigger reports.","A quiet shelf for inner-work trophies.",{trophyShelf:"therapist-shelf"}),gt("psyche","Prismatic Crucible","celebration_variant",Te("beliefFlexibleAlternativeCount",50),"Create 50 flexible belief alternatives.","A prismatic reveal for belief work.",{celebrationVariant:"prismatic-crucible"})],HE=[Ze("habits","Ritual Spark",Te("habitAlignedCount",25),"Record 25 aligned habit check-ins.","Your recurring commitments have started to leave marks."),Ze("habits","Routine Rivet",Te("habitAlignedCount",75),"Record 75 aligned habit check-ins.","The habit rail is no longer decorative."),Ze("habits","Habit Heat",At(Te("habitAlignedCount",150),Te("habitStreakMax",14)),"Record 150 aligned check-ins and a 14-day habit streak.","One behavior got hot enough to shape you."),Ze("habits","Ritual Iron",Te("habitAlignedCount",365),"Record 365 aligned habit check-ins.","The hard habit trophy."),Ze("habits","Recovery Shield",Te("recoveryEventCount",50),"Earn 50 recovery rewards.","Recovery was treated as part of the work."),Ze("habits","Life-Force Alloy",Te("lifeForceSnapshotCount",100),"Record 100 Life Force day snapshots.","Energy accounting became a usable alloy."),Ze("habits","Sleep Temper",Te("healthSleepSessionCount",120),"Import 120 sleep sessions.","Sleep became evidence, not a guess."),Ze("habits","Vitality Forge",At(Te("workoutSessionCount",100),Te("healthSleepSessionCount",200)),"Import 100 workouts and 200 sleep sessions.","Body data and execution entered the same forge.")],GE=[gt("habits","Recovery Blue Flame","streak_effect",Te("recoveryEventCount",20),"Earn 20 recovery rewards.","A cooler recovery flame.",{streakEffect:"recovery-blue"}),gt("habits","Ritual Check Glow","hud_treatment",Te("habitAlignedCount",75),"Record 75 aligned habit check-ins.","A habit-check glow for the HUD.",{hudTreatment:"ritual-check"}),gt("habits","Storm Forger","mascot_skin",Te("workoutSessionCount",50),"Import 50 workouts.","A storm-lit Smith skin for movement arcs.",{mascotSkin:"storm-forger"}),gt("habits","Clockwork Smith","mascot_skin",Te("habitAlignedCount",150),"Record 150 aligned habit check-ins.","A clockwork skin for ritual precision.",{mascotSkin:"clockwork-smith"}),gt("habits","Vital Flame","streak_effect",Te("healthSleepSessionCount",90),"Import 90 sleep sessions.","A vital-sign flame around streak indicators.",{streakEffect:"vital-flame"}),gt("habits","Life-Force Frame","icon_frame",Te("lifeForceSnapshotCount",100),"Record 100 Life Force snapshots.","An AP-inspired frame for body trophies.",{iconFrame:"life-force"}),gt("habits","Steady-State Aura","streak_effect",Te("habitStreakMax",60),"Reach a 60-day habit streak.","An aura for long stable rituals.",{streakEffect:"steady-state"}),gt("habits","Celestial Smith","mascot_skin",At(Te("workoutSessionCount",100),Te("healthSleepSessionCount",200)),"Import 100 workouts and 200 sleep sessions.","A celestial skin for body stewardship.",{mascotSkin:"celestial-smith"})],QE=[Ze("agents","Companion Spark",Te("agentActionCount",5),"Record 5 agent actions.","The first sign of a working human-agent council."),Ze("agents","Bot Bellows",Te("agentCompletedActionCount",20),"Complete 20 agent actions.","Agents are not just present; they are moving work."),Ze("agents","Council Spark",Te("collaborationRewardCount",50),"Earn 50 collaboration rewards.","The collaboration trophy for meaningful assisted work."),Ze("agents","Guild Forge",At(Te("agentCompletedActionCount",100),Te("collaborationRewardCount",100)),"Complete 100 agent actions and earn 100 collaboration rewards.","The Forge has become a small guild.")],VE=[gt("agents","Guild Badge Frame","icon_frame",Te("agentCompletedActionCount",20),"Complete 20 agent actions.","A guild frame for agent trophies.",{iconFrame:"guild-badge"}),gt("agents","Council Sparks Reveal","celebration_variant",Te("collaborationRewardCount",50),"Earn 50 collaboration rewards.","A council-sparks reveal for collaboration.",{celebrationVariant:"council-sparks"})],XE=[..._E,...FE,...RE,...DE,...$E,...OE,...zE,...KE,...qE,...BE,...UE,...WE,...HE,...GE,...QE,...VE];function YE(){let t=0,s=0,a=0;const i=new Map;return XE.map(r=>{const n=Eh.find(p=>p.id===r.category);if(!n)throw new Error(`Unknown gamification category ${r.category}`);const l=i.get(r.category)??{trophy:0,unlock:0},o=l[r.kind];l[r.kind]+=1,i.set(r.category,l);const d=r.kind==="trophy"?n.trophyCount:n.unlockCount,m=AE(o,d),h=`${r.kind}-${wd(r.category)}-${wd(r.title)}`,c=r.kind==="trophy"?s++:a++;return{id:h,kind:r.kind,category:r.category,tier:m,difficulty:ME(m),hidden:r.hidden??!1,title:r.title,summary:r.summary,requirement:r.requirement,requirementText:r.requirementText,reward:r.reward,unlockType:r.kind==="unlock"?r.unlockType??"icon_frame":null,rewardPayload:r.kind==="unlock"?r.rewardPayload??{}:{trophyId:h},assetKey:LE(r),sheetKey:`${r.kind==="trophy"?"trophies":"unlocks"}-r${Math.floor(c/10)+1}-c${c%10+1}`,rarity:EE(m),sortOrder:t++}})}const Ba=YE();function JE(){if(Ba.length!==144)throw new Error(`GAMIFICATION_CATALOG must contain exactly 144 items; found ${Ba.length}.`);const t=Ba.filter(i=>i.kind==="trophy").length,s=Ba.filter(i=>i.kind==="unlock").length;if(t!==96||s!==48)throw new Error(`GAMIFICATION_CATALOG must contain 96 trophies and 48 unlocks; found ${t}/${s}.`);for(const i of Eh){const r=Ba.filter(l=>l.category===i.id&&l.kind==="trophy").length,n=Ba.filter(l=>l.category===i.id&&l.kind==="unlock").length;if(r!==i.trophyCount||n!==i.unlockCount)throw new Error(`${i.id} expected ${i.trophyCount}/${i.unlockCount}, found ${r}/${n}.`)}if(new Set(Ba.map(i=>i.assetKey)).size!==Ba.length)throw new Error("Every trophy and unlock must have a unique asset key.")}JE();const Vg=Eh.map(t=>({id:t.id,label:t.label})),ZE=Array.from({length:30},(t,s)=>`mascot-state-${String(s+1).padStart(3,"0")}`),eL=TE.map((t,s)=>[t,`mascot-state-${String(17+s).padStart(3,"0")}`]),tL=PE.map((t,s)=>[t,`mascot-state-${String(10-s).padStart(3,"0")}`]),em=ZE;if(em.length!==30)throw new Error(`GAMIFICATION_MASCOT_KEYS must contain exactly 30 mascot/state keys; found ${em.length}.`);function sL(t){switch(t.category){case"xp_levels":return"#f59e0b";case"streaks":return"#fb923c";case"tasks":return"#f97316";case"projects":return"#38bdf8";case"wiki":return"#a78bfa";case"psyche":return"#8b5cf6";case"habits":return"#4ade80";case"agents":return"#22d3ee";default:return"#f59e0b"}}function aL(t){return["cinematic stylized blacksmith game icon",t.category.replace(/_/g," "),t.kind,t.title,"obsidian iron, ember gold, cool violet and cyan steel highlights, no text"].join(", ")}const iL=Object.fromEntries(Ba.map(t=>[t.assetKey,{key:t.assetKey,role:"item",itemKind:t.kind,alt:`${t.title} ${t.kind} icon.`,dominantColor:sL(t),tierFrame:t.tier,sourcePath:`gamification/source/themes/dark-fantasy/items/${t.assetKey}.png`,spritePath:`gamification/sprites/themes/dark-fantasy/items/${t.assetKey}-{size}.webp`,sheetKey:t.sheetKey,prompt:aL(t)}])),rL=Object.fromEntries(em.map(t=>{const s=Number(t.replace("mascot-state-","")),a=s<=10,i=s>=17;return[t,{key:t,role:i||a?"streak":"mascot",alt:a?"The Forge Smith in a safe cold-forge absence state.":"The Forge Smith mascot in a dramatic blacksmith game-art pose.",dominantColor:a?"#64748b":i?"#fb923c":"#38bdf8",tierFrame:"none",sourcePath:`gamification/source/themes/dark-fantasy/mascots/${t}.png`,spritePath:`gamification/sprites/themes/dark-fantasy/mascots/${t}-{size}.webp`,sheetKey:null,prompt:"dramatic Forge Smith blacksmith mascot, premium game art, no text, no watermark"}]}));({...iL,...rL});function Ki(t){t.currentTarget.hidden=!0}const nL=["all","bronze","silver","gold","platinum"],lL=[{id:"trophies",label:"Trophies"},{id:"unlocks",label:"Unlocks"},{id:"armory",label:"Mascot Armory"},{id:"streak",label:"Streak Forge"}],tm={mascot_skin:{field:"selectedMascotSkin",payloadKey:"mascotSkin",label:"Mascot skin"},hud_treatment:{field:"selectedHudTreatment",payloadKey:"hudTreatment",label:"HUD treatment"},streak_effect:{field:"selectedStreakEffect",payloadKey:"streakEffect",label:"Streak flame"},trophy_shelf:{field:"selectedTrophyShelf",payloadKey:"trophyShelf",label:"Trophy shelf"},celebration_variant:{field:"selectedCelebrationVariant",payloadKey:"celebrationVariant",label:"Celebration"}};function Av(t){switch(t){case"platinum":return"border-cyan-200/35 text-cyan-100";case"gold":return"border-amber-200/35 text-amber-100";case"silver":return"border-slate-200/35 text-slate-100";default:return"border-orange-300/35 text-orange-100"}}function oL(t){const s=t.unlockType?tm[t.unlockType]:null,a=s?t.rewardPayload[s.payloadKey]:null;return typeof a=="string"?a:null}function dL({item:t,gamificationTheme:s,onSelect:a}){return e.jsxs("button",{type:"button",onClick:()=>a(t),className:te("group relative min-h-[19rem] overflow-hidden rounded-[18px] border border-white/8 bg-white/[0.045] p-4 text-left transition hover:-translate-y-0.5 hover:border-white/16 hover:bg-white/[0.07]",!t.unlocked&&"opacity-78"),children:[e.jsx("div",{className:"absolute inset-0 -z-10 bg-[radial-gradient(circle_at_50%_0%,rgba(249,115,22,0.16),transparent_38%)]"}),e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx(S,{className:te("border bg-black/18",Av(t.tier)),children:t.tier}),e.jsx(S,{className:"bg-white/[0.06] text-white/58",children:t.unlocked?"earned":"locked"})]}),e.jsx("div",{className:"mt-3 grid place-items-center",children:e.jsx("img",{src:ja(t.assetKey,512,s),alt:"",onError:Ki,className:te("size-36 object-contain drop-shadow-[0_22px_34px_rgba(0,0,0,0.44)] transition group-hover:scale-[1.03]",!t.unlocked&&"grayscale")})}),e.jsxs("div",{className:"mt-3 min-w-0",children:[e.jsx("div",{className:"font-display text-lg text-white",children:t.title}),e.jsx("p",{className:"mt-2 line-clamp-2 text-sm leading-6 text-white/58",children:t.unlocked?t.summary:t.requirementText})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Gs,{value:t.progressPercent}),e.jsxs("div",{className:"mt-2 flex justify-between gap-3 text-[11px] uppercase tracking-[0.16em] text-white/38",children:[e.jsxs("span",{children:[t.progressCurrent,"/",t.progressTarget]}),e.jsxs("span",{children:[t.progressPercent,"%"]})]})]})]})}function cL(){var j,R,v,D;const t=Ct(),s=Bm(),a=pt(),i=gr(),r=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[n,l]=u.useState("trophies"),[o,d]=u.useState("all"),[m,h]=u.useState("all"),[c,p]=u.useState("all"),[g,x]=u.useState(""),[f,b]=u.useState(null),A=Me({queryKey:["forge-gamification-catalog",...r],queryFn:()=>P2(r)}),T=Vm(r),I=De({mutationFn:L=>A2(L,r),onSuccess:async()=>{await Promise.all([a.invalidateQueries({queryKey:["forge-gamification-catalog"]}),a.invalidateQueries({queryKey:["forge-xp-metrics"]})]),i(Ja.util.invalidateTags(["Gamification"]))}}),y=(j=A.data)==null?void 0:j.catalog,N=(y==null?void 0:y.items)??[],k=u.useMemo(()=>{const L=g.trim().toLowerCase();return N.filter(Q=>n==="trophies"&&Q.kind!=="trophy"||n==="unlocks"&&Q.kind!=="unlock"||(n==="armory"||n==="streak")&&Q.kind!=="unlock"||n==="armory"&&!Q.unlockType||n==="streak"&&Q.unlockType!=="streak_effect"||o!=="all"&&Q.category!==o||m!=="all"&&Q.tier!==m||c==="unlocked"&&!Q.unlocked||c==="locked"&&Q.unlocked?!1:L?`${Q.title} ${Q.summary} ${Q.requirementText} ${Q.reward}`.toLowerCase().includes(L):!0)},[o,N,g,c,n,m]),w=(y==null?void 0:y.equipment)??((R=T.data)==null?void 0:R.metrics.equipment)??null,P=N.filter(L=>L.kind==="unlock"&&L.unlockType&&tm[L.unlockType]);return A.isError?e.jsx(ct,{eyebrow:"Rewards",error:A.error,onRetry:()=>void A.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1320px] gap-5",children:[e.jsx(mt,{title:"Trophy Hall",description:"Achievements are earned from real Forge behavior: tasks, runs, goals, wiki links, Psyche work, habits, Life Force, health, and collaboration.",badge:y?`${y.unlockedCount}/${y.totalCount} earned`:"Loading",actions:(v=T.data)!=null&&v.metrics?e.jsx(Mi,{metrics:T.data.metrics.profile}):null}),e.jsxs("section",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(20rem,0.42fr)]",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.045] p-4",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:lL.map(L=>e.jsxs(H,{type:"button",variant:n===L.id?"primary":"secondary",size:"sm",onClick:()=>l(L.id),children:[L.id==="trophies"?e.jsx(ll,{className:"size-4"}):null,L.id==="armory"?e.jsx(Tj,{className:"size-4"}):null,L.id==="streak"?e.jsx(nl,{className:"size-4"}):null,L.id==="unlocks"?e.jsx(Ut,{className:"size-4"}):null,L.label]},L.id))}),e.jsxs("div",{className:"mt-4 flex min-w-0 flex-wrap items-center gap-2",children:[["all","unlocked","locked"].map(L=>e.jsxs(H,{type:"button",variant:c===L?"primary":"secondary",size:"sm",onClick:()=>p(L),children:[L==="locked"?e.jsx(rp,{className:"size-4"}):null,L]},L)),e.jsxs("label",{className:"ml-auto flex min-h-10 min-w-[16rem] max-w-full items-center gap-2 rounded-full border border-white/8 bg-black/18 px-3 text-sm text-white/70",children:[e.jsx(Bt,{className:"size-4 shrink-0 text-white/38"}),e.jsx("input",{value:g,onChange:L=>x(L.target.value),placeholder:"Search rewards",className:"min-w-0 flex-1 bg-transparent text-white outline-none placeholder:text-white/34"})]})]}),e.jsxs("div",{className:"mt-4 flex min-w-0 flex-wrap gap-2",children:[e.jsx(H,{type:"button",variant:o==="all"?"primary":"secondary",size:"sm",onClick:()=>d("all"),children:"all categories"}),Vg.map(L=>e.jsx(H,{type:"button",variant:o===L.id?"primary":"secondary",size:"sm",onClick:()=>d(L.id),children:L.label},L.id))]}),e.jsx("div",{className:"mt-4 flex min-w-0 flex-wrap gap-2",children:nL.map(L=>e.jsx(H,{type:"button",variant:m===L?"primary":"secondary",size:"sm",onClick:()=>h(L),children:L},L))})]}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] border border-white/8 bg-black/18 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-white",children:[e.jsx(Ut,{className:"size-4 text-[var(--tertiary)]"}),"Near completion"]}),((y==null?void 0:y.nextTargets)??[]).map(L=>e.jsxs("button",{type:"button",onClick:()=>b(L),className:"grid grid-cols-[2.75rem_minmax(0,1fr)_3rem] items-center gap-3 rounded-2xl bg-white/[0.045] p-2 text-left",children:[e.jsx("img",{src:ja(L.assetKey,256,s),alt:"",onError:Ki,className:"size-11 object-contain"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm text-white/82",children:L.title}),e.jsx("span",{className:"block truncate text-[11px] text-white/42",children:L.requirementText})]}),e.jsxs("span",{className:"text-right text-xs text-white/50",children:[L.progressPercent,"%"]})]},L.id))]})]}),n==="armory"?e.jsxs("section",{className:"grid gap-3 lg:grid-cols-[minmax(18rem,0.42fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative min-h-[24rem] overflow-hidden rounded-[24px] border border-white/8 bg-[linear-gradient(145deg,rgba(15,23,42,0.92),rgba(24,24,36,0.88))] p-4",children:[e.jsx("img",{src:ja(((D=T.data)==null?void 0:D.metrics.mascot.spriteKey)??"mascot-state-014",512,s),alt:"Forge Smith mascot",onError:Ki,className:"absolute inset-x-0 bottom-0 mx-auto h-[23rem] object-contain"}),e.jsxs("div",{className:"relative z-10",children:[e.jsx(S,{className:"bg-black/30 text-[var(--tertiary)]",children:"Equipped"}),e.jsxs("div",{className:"mt-3 grid gap-1 text-sm text-white/68",children:[e.jsxs("span",{children:["Skin: ",(w==null?void 0:w.selectedMascotSkin)??"default"]}),e.jsxs("span",{children:["HUD: ",(w==null?void 0:w.selectedHudTreatment)??"default"]}),e.jsxs("span",{children:["Flame: ",(w==null?void 0:w.selectedStreakEffect)??"default"]}),e.jsxs("span",{children:["Shelf: ",(w==null?void 0:w.selectedTrophyShelf)??"default"]})]})]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:P.map(L=>{const Q=L.unlockType?tm[L.unlockType]:null,Z=oL(L),V=!!(Q&&Z&&(w==null?void 0:w[Q.field])===Z);return e.jsxs(le,{className:te("p-4",!L.unlocked&&"opacity-70"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx(S,{className:"bg-white/[0.06] text-white/58",children:(Q==null?void 0:Q.label)??"Cosmetic"}),V?e.jsx(Ia,{className:"size-4 text-emerald-200"}):null]}),e.jsx("img",{src:ja(L.assetKey,256,s),alt:"",onError:Ki,className:te("mx-auto mt-3 size-28 object-contain",!L.unlocked&&"grayscale")}),e.jsx("div",{className:"mt-3 font-display text-lg text-white",children:L.title}),e.jsx("p",{className:"mt-2 line-clamp-2 text-sm leading-6 text-white/56",children:L.unlocked?L.summary:L.requirementText}),e.jsx(H,{type:"button",variant:V?"secondary":"primary",size:"sm",disabled:!L.unlocked||!Q||!Z||I.isPending,className:"mt-4 w-full",onClick:()=>{!Q||!Z||I.mutate({[Q.field]:V?null:Z})},children:V?"Unequip":L.unlocked?"Equip":"Locked"})]},L.id)})})]}):n==="streak"?e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 font-display text-xl text-white",children:[e.jsx(nl,{className:"size-5 text-[var(--tertiary)]"}),"Streak power states"]}),e.jsx("div",{className:"mt-4 grid gap-3 sm:grid-cols-2 md:grid-cols-4 xl:grid-cols-5",children:eL.map(([L,Q])=>e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("img",{src:ja(Q,256,s),alt:"",onError:Ki,className:"mx-auto size-28 object-contain"}),e.jsxs("div",{className:"mt-2 text-center text-sm text-white/74",children:[L," day power"]})]},Q))})]}),e.jsxs(le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 font-display text-xl text-white",children:[e.jsx(rp,{className:"size-5 text-slate-300"}),"Absence pressure states"]}),e.jsx("div",{className:"mt-4 grid gap-3 sm:grid-cols-2 md:grid-cols-4 xl:grid-cols-5",children:tL.map(([L,Q])=>e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("img",{src:ja(Q,256,s),alt:"",onError:Ki,className:"mx-auto size-28 object-contain"}),e.jsxs("div",{className:"mt-2 text-center text-sm text-white/74",children:[L," days away"]})]},Q))})]})]}):e.jsx("section",{className:"grid gap-5",children:Vg.map(L=>{const Q=k.filter(Z=>Z.category===L.id);return Q.length===0?null:e.jsxs("section",{className:"grid gap-3",children:[e.jsx("div",{className:"flex items-end justify-between gap-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-xl text-white",children:L.label}),e.jsxs("div",{className:"text-sm text-white/44",children:[Q.length," visible rewards"]})]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:Q.map(Z=>e.jsx(dL,{item:Z,gamificationTheme:s,onSelect:b},Z.id))})]},L.id)})}),f?e.jsx("div",{className:"fixed inset-0 z-50 grid place-items-center bg-black/72 p-4 backdrop-blur-sm",onClick:()=>b(null),children:e.jsxs("div",{className:"w-full max-w-[34rem] rounded-[26px] border border-white/10 bg-[rgb(12,17,30)] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.6)]",onClick:L=>L.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("img",{src:ja(f.assetKey,512,s),alt:"",onError:Ki,className:"size-32 object-contain"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{className:te("border bg-black/18",Av(f.tier)),children:f.tier}),e.jsx(S,{className:"bg-white/[0.06] text-white/58",children:f.kind})]}),e.jsx("div",{className:"mt-3 font-display text-2xl text-white",children:f.title}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/62",children:f.summary})]})]}),e.jsxs("div",{className:"mt-5 rounded-[18px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:"Requirement"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:f.requirementText}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Gs,{value:f.progressPercent}),e.jsxs("div",{className:"mt-2 flex justify-between text-[11px] uppercase tracking-[0.16em] text-white/40",children:[e.jsxs("span",{children:[f.progressCurrent,"/",f.progressTarget]}),e.jsx("span",{children:f.unlocked?"earned":"locked"})]})]})]}),e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx(H,{type:"button",variant:"secondary",onClick:()=>b(null),children:"Close"})})]})}):null]})}function qa(t,s,a,i){return{value:t,label:s,description:a,searchText:`${s} ${a}`,kind:i}}function Mv(t){const s=t.goals??[],a=t.projects??[],i=t.tasks??[],r=t.habits??[],n=t.values??[],l=t.patterns??[],o=t.behaviors??[],d=t.beliefs??[],m=t.reports??[];return[...s.map(h=>qa(`goal:${h.id}`,h.title,"Goal","goal")),...a.map(h=>qa(`project:${h.id}`,h.title,"Project","project")),...i.map(h=>qa(`task:${h.id}`,h.title,"Task","task")),...r.map(h=>qa(`habit:${h.id}`,h.title,"Habit","habit")),...n.map(h=>qa(`psyche_value:${h.id}`,h.title,"Value","value")),...l.map(h=>qa(`behavior_pattern:${h.id}`,h.title,"Pattern","pattern")),...o.map(h=>qa(`behavior:${h.id}`,h.title,"Behavior","behavior")),...d.map(h=>qa(`belief_entry:${h.id}`,h.statement,"Belief","belief")),...m.map(h=>qa(`trigger_report:${h.id}`,h.title,"Report","report"))]}function Ev(t){return t.map(s=>{const a=s.indexOf(":");if(a===-1)return null;const i=s.slice(0,a),r=s.slice(a+1);return!i||!r?null:{entityType:i,entityId:r,relationshipType:"context"}}).filter(s=>s!==null)}const uL=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Xg={awake:{label:"Awake",strong:"rgba(251, 191, 36, 0.95)",soft:"rgba(251, 191, 36, 0.16)",text:"text-amber-200"},core:{label:"Core",strong:"rgba(165, 180, 252, 0.96)",soft:"rgba(165, 180, 252, 0.18)",text:"text-indigo-100"},deep:{label:"Deep",strong:"rgba(45, 212, 191, 0.96)",soft:"rgba(45, 212, 191, 0.18)",text:"text-teal-100"},rem:{label:"REM",strong:"rgba(96, 165, 250, 0.96)",soft:"rgba(96, 165, 250, 0.18)",text:"text-sky-100"},in_bed:{label:"In bed",strong:"rgba(255, 255, 255, 0.4)",soft:"rgba(255, 255, 255, 0.1)",text:"text-white/72"},asleep_unspecified:{label:"Asleep",strong:"rgba(196, 181, 253, 0.96)",soft:"rgba(196, 181, 253, 0.16)",text:"text-violet-100"}};function jl(t){return Xg[t]??Xg.asleep_unspecified}function zs(t){if(t<=0)return"0m";const s=Math.floor(t/3600),a=Math.round(t%3600/60);return s===0?`${a}m`:a===0?`${s}h`:`${s}h ${a}m`}function mL(t){const s=Math.round(t/60);return s===0?"on baseline":`${s>0?"+":"-"}${Math.abs(s)}m`}function xn(t){return`${Math.round(t*100)}%`}function Vr(t,s){return t?new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",timeZone:s}).format(new Date(t)):"n/a"}function Lv(t,s){return new Intl.DateTimeFormat(void 0,{weekday:"long",day:"numeric",month:"long",timeZone:s}).format(new Date(t))}function Wo(t,s,a){return`${Vr(t,a)} - ${Vr(s,a)}`}function hL(t){const[s,a]=t.split("-").map(Number);return new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(s,(a??1)-1,1))}function _v(t){const s=new Date(t),a=(t.getDay()+6)%7;return s.setDate(t.getDate()-a),s}function pL(t){const s=_v(t);return s.setDate(s.getDate()+6),s}function xL(t){const s=t.getFullYear(),a=`${t.getMonth()+1}`.padStart(2,"0"),i=`${t.getDate()}`.padStart(2,"0");return`${s}-${a}-${i}`}function Po(t){return{qualitySummary:typeof t.annotations.qualitySummary=="string"?t.annotations.qualitySummary:"",notes:typeof t.annotations.notes=="string"?t.annotations.notes:"",tagsText:Array.isArray(t.annotations.tags)?t.annotations.tags.join(", "):"",linkValues:Array.isArray(t.links)?t.links.map(s=>`${s.entityType}:${s.entityId}`):[]}}function gL(t,s){if(!t)return[];const[a,i]=t.split("-").map(Number),r=new Date(a,(i??1)-1,1),n=new Date(a,i??1,0),l=_v(r),o=pL(n),d=new Map(s.map(h=>[h.dateKey,h])),m=[];for(const h=new Date(l);h<=o;h.setDate(h.getDate()+1)){const c=xL(h);m.push({dateKey:c,dayNumber:h.getDate(),outsideMonth:h.getMonth()!==r.getMonth(),sleep:d.get(c)??null})}return m}function fL(t){return t>0?"text-emerald-200":t<0?"text-rose-200":"text-white/70"}function Fv(t){return t==="recharged"||t==="recovered"?"bg-emerald-400/16 text-emerald-100":t==="steady"||t==="stable"?"bg-sky-400/16 text-sky-100":t==="fragile"||t==="strained"?"bg-amber-400/16 text-amber-100":t==="depleted"?"bg-rose-400/16 text-rose-100":"bg-white/10 text-white/76"}function bL(t){return t==="provider_raw"?"bg-emerald-400/16 text-emerald-100":t==="historical_raw"?"bg-amber-400/16 text-amber-100":"bg-white/10 text-white/70"}function yL(t){return t==="provider_raw"?"Provider raw data":t==="historical_raw"?"Historical raw data":"Raw data unavailable"}function wL(t){return t.qualityKind==="provider_native"?"bg-emerald-400/16 text-emerald-100":"bg-amber-400/16 text-amber-100"}function vL(t,s){const a=t.stage;if(typeof a=="string"&&a.trim().length>0)return a;const i=t.sourceType;if(typeof i=="string"&&i.trim().length>0)return i;const r=t.stageBreakdown;if(Array.isArray(r)&&r.length>0){const n=r[0];if(n&&typeof n=="object"&&typeof n.stage=="string")return(n.stage||"asleep_unspecified").trim()}return s.includes("awake")?"awake":"asleep_unspecified"}function jL(t){const s=t,a=(s==null?void 0:s.segments)??(s==null?void 0:s.rawSegments)??[],i=(s==null?void 0:s.auditLogs)??(s==null?void 0:s.rawLogs)??[],r=s!=null&&s.sourceRecords&&s.sourceRecords.length>0?s.sourceRecords:i.filter(l=>typeof l.startedAt=="string"&&typeof l.endedAt=="string").map(l=>({id:l.id,importRunId:l.importRunId,pairingSessionId:l.pairingSessionId,sleepSessionId:l.sleepSessionId,userId:l.userId,provider:l.source,providerRecordType:l.logType,providerRecordUid:l.externalUid??l.id,sourceDevice:"",sourceTimezone:l.sourceTimezone,localDateKey:l.localDateKey,startedAt:l.startedAt,endedAt:l.endedAt,rawStage:vL(l.payload,l.logType),rawValue:null,qualityKind:"historical_import",payload:l.payload,metadata:l.metadata,ingestedAt:l.createdAt})),n=(s==null?void 0:s.rawDataStatus)??(r.length>0?"historical_raw":"raw_unavailable");return{sourceRecords:r,segments:a,auditLogs:i,rawDataStatus:n}}function Rv({stages:t}){const s=t.reduce((a,i)=>a+i.seconds,0);return t.length===0||s===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No stage composition was stored for this night yet."}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"flex h-3 overflow-hidden rounded-full bg-white/[0.08]",children:t.map(a=>{const i=jl(a.stage);return e.jsx("div",{className:"h-full",style:{width:`${Math.max(4,a.seconds/s*100)}%`,background:i.strong},title:`${i.label} · ${zs(a.seconds)}`},a.stage)})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-4",children:t.map(a=>{const i=jl(a.stage),r="percentage"in a&&typeof a.percentage=="number"?a.percentage:s>0?a.seconds/s:0;return e.jsxs("div",{className:"rounded-[16px] border border-white/8 px-3 py-3",style:{background:i.soft},children:[e.jsx("div",{className:te("text-sm font-medium",i.text),children:i.label}),e.jsx("div",{className:"mt-1 text-lg text-white",children:zs(a.seconds)}),e.jsx("div",{className:"text-xs text-white/54",children:xn(r)})]},a.stage)})})]})}function Yg({blocks:t,selectedBlockId:s,onSelect:a}){return e.jsxs("div",{className:"relative h-12 overflow-hidden rounded-[18px] border border-white/8 bg-black/20",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(255,255,255,0.06)_1px,transparent_1px)] bg-[length:25%_100%]"}),t.map(i=>{const r=jl(i.stage),n=s===i.id;return e.jsx("button",{type:"button",onClick:()=>a(i.id),className:te("absolute inset-y-[5px] rounded-[12px] border transition",n?"border-white/60 shadow-[0_0_0_1px_rgba(255,255,255,0.18)]":"border-white/10"),style:{left:`${i.offsetRatio*100}%`,width:`${Math.max(i.widthRatio*100,1.8)}%`,background:r.strong},title:`${i.label} · ${zs(i.durationSeconds)} · ${i.startedAt} - ${i.endedAt}`,children:i.widthRatio>.13?e.jsx("span",{className:"truncate px-2 text-[10px] font-medium text-slate-950/85",children:i.label}):null},i.id)})]})}function kL({timeline:t,timeZone:s}){var d,m;const a=t.blocks.filter(h=>h.lane==="in_bed"),i=t.blocks.filter(h=>h.lane==="sleep"),r=((d=i[0])==null?void 0:d.id)??((m=a[0])==null?void 0:m.id)??null,[n,l]=u.useState(r);u.useEffect(()=>{l(r)},[r,t.startedAt,t.endedAt,t.totalSeconds]);const o=t.blocks.find(h=>h.id===n)??null;return t.hasRawSegments?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[a.length>0?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed window"}),e.jsx(Yg,{blocks:a,selectedBlockId:n,onSelect:l})]}):null,e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:t.hasSleepStageData?"Sleep phases":"Recorded sleep coverage"}),e.jsx(Yg,{blocks:i.length>0?i:a,selectedBlockId:n,onSelect:l})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-white/48",children:[e.jsx("span",{children:Vr(t.startedAt,s)}),e.jsx("span",{children:zs(t.totalSeconds)}),e.jsx("span",{children:Vr(t.endedAt,s)})]}),o?e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:te("text-sm font-medium",jl(o.stage).text),children:o.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[Vr(o.startedAt,s)," -"," ",Vr(o.endedAt,s)]})]}),e.jsx(S,{tone:"meta",children:zs(o.durationSeconds)})]})}):null]}):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-black/10 px-4 py-5 text-sm text-white/56",children:"Phase timing is unavailable for this night. Forge still keeps the canonical overnight summary, but the companion did not store segment-level timing."})}function NL({latestNight:t}){return t?e.jsx(le,{className:"overflow-hidden border-white/8 bg-[linear-gradient(135deg,rgba(7,17,40,0.96),rgba(16,24,54,0.94))] p-0",children:e.jsxs("div",{className:"relative overflow-hidden px-6 py-6 sm:px-7 sm:py-7",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(96,165,250,0.22),transparent_36%),radial-gradient(circle_at_bottom_left,rgba(45,212,191,0.14),transparent_34%)]"}),e.jsxs("div",{className:"relative grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(S,{className:te("border-white/0",Fv(t.recoveryState)),children:t.qualitativeState}),e.jsx(S,{tone:"meta",children:t.sourceTimezone}),t.hasReflection?e.jsx(S,{tone:"meta",children:"Has reflection"}):null,t.hasRawSegments?e.jsxs(S,{tone:"meta",children:[t.rawSegmentCount," raw segments"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Last night"}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end gap-x-4 gap-y-2",children:[e.jsx("div",{className:"text-[clamp(2.5rem,6vw,5rem)] font-medium leading-none text-white",children:zs(t.asleepSeconds)}),e.jsxs("div",{className:"pb-2 text-sm text-white/58",children:["asleep across ",Wo(t.startedAt,t.endedAt,t.sourceTimezone)]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/64",children:Lv(t.endedAt,t.sourceTimezone)}),t.qualitySummary?e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-white/72",children:t.qualitySummary}):e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-white/56",children:"Canonical overnight summary computed from synced sleep segments, with raw evidence still available underneath."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:zs(t.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Score"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:t.score??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Regularity"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:t.regularity??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:xn(t.efficiency)})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/20 px-5 py-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Baseline"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Compared with recent nights"})]}),e.jsx(ym,{className:"size-5 text-[var(--primary)]"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"7-night average"}),e.jsx("span",{className:"text-sm text-white",children:zs(t.weeklyAverageSleepSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Versus baseline"}),e.jsx("span",{className:te("text-sm",fL(t.deltaFromWeeklyAverageSeconds)),children:mL(t.deltaFromWeeklyAverageSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Bedtime drift"}),e.jsxs("span",{className:"text-sm text-white",children:[t.bedtimeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Wake drift"}),e.jsxs("span",{className:"text-sm text-white",children:[t.wakeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Restorative share"}),e.jsx("span",{className:"text-sm text-white",children:xn(t.restorativeShare)})]})]})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/20 px-5 py-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(Rv,{stages:t.stageBreakdown})})]})]})]})]})}):e.jsxs(le,{className:"overflow-hidden p-6",children:[e.jsx("div",{className:"text-sm uppercase tracking-[0.18em] text-white/42",children:"Sleep"}),e.jsx("div",{className:"mt-4 text-2xl text-white",children:"No overnight sleep yet"}),e.jsx("div",{className:"mt-3 max-w-2xl text-sm leading-6 text-white/58",children:"The sleep page will switch to a night-first summary once the companion syncs a canonical overnight session."})]})}function ru({title:t,value:s,description:a}){return e.jsxs(le,{className:"h-full border-white/8 bg-white/[0.03]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsx("div",{className:"mt-3 text-3xl text-white",children:s}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/56",children:a})]})}function SL({days:t,selectedSleepId:s,onSelect:a}){const i=u.useMemo(()=>Array.from(new Set(t.map(d=>d.dateKey.slice(0,7)))).sort((d,m)=>d.localeCompare(m)),[t]),[r,n]=u.useState(i[i.length-1]??"");u.useEffect(()=>{if(i.length===0){n("");return}i.includes(r)||n(i[i.length-1]??"")},[r,i]);const l=i.indexOf(r),o=u.useMemo(()=>gL(r,t),[t,r]);return r?e.jsx(le,{className:"overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(10,17,33,0.98),rgba(12,20,40,0.96))] p-0",children:e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sleep calendar"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:hL(r)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:l<=0,onClick:()=>n(i[Math.max(0,l-1)]??r),children:"Previous"}),e.jsx(H,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:l===-1||l>=i.length-1,onClick:()=>n(i[Math.min(i.length-1,l+1)]??r),children:"Next"})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-2 text-center text-[11px] uppercase tracking-[0.16em] text-white/38",children:uL.map(d=>e.jsx("div",{children:d},d))}),e.jsx("div",{className:"grid grid-cols-7 gap-2",children:o.map(d=>{const m=d.sleep,h=(m==null?void 0:m.sleepId)===s,c=m&&typeof m.score=="number"?m.score>=80?"rgba(45,212,191,0.22)":m.score>=65?"rgba(96,165,250,0.22)":"rgba(251,191,36,0.18)":"rgba(255,255,255,0.04)";return e.jsxs("button",{type:"button",disabled:!m,"aria-pressed":h,"aria-label":`Select sleep for ${d.dateKey}`,onClick:()=>{m&&(n(m.dateKey.slice(0,7)),a(m.sleepId,m.dateKey.slice(0,7)))},className:te("min-h-[90px] rounded-[18px] border px-2 py-2 text-left transition",m?"border-white/10 hover:border-white/22 hover:bg-white/[0.05]":"border-white/6 bg-white/[0.02]",h&&"border-[var(--primary)] bg-[var(--primary)]/12",d.outsideMonth&&!m&&"opacity-35"),style:m?{background:`linear-gradient(180deg, ${c}, rgba(255,255,255,0.03))`}:void 0,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:te("text-sm",d.outsideMonth?"text-white/40":"text-white/82"),children:d.dayNumber}),m!=null&&m.hasReflection?e.jsx("span",{className:"size-2 rounded-full bg-emerald-300"}):null]}),m?e.jsxs("div",{className:"mt-4 grid gap-1",children:[e.jsxs("div",{className:"text-lg text-white",children:[m.sleepHours.toFixed(1),"h"]}),e.jsxs("div",{className:"text-xs text-white/52",children:[m.score??"n/a"," score"]}),e.jsx("div",{className:"text-xs text-white/40",children:m.hasRawSegments?"phases available":"summary only"})]}):null]},d.dateKey)})})]})}):e.jsx(le,{className:"border-white/8 bg-white/[0.03] px-5 py-8 text-sm leading-6 text-white/56",children:"No canonical nights are available for the calendar yet."})}function nu({active:t,children:s,onClick:a}){return e.jsx("button",{type:"button",onClick:a,className:te("rounded-full border px-4 py-2 text-sm transition",t?"border-[var(--primary)] bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.03] text-white/60 hover:text-white"),children:s})}function CL({session:t,draft:s,rawDetail:a,rawDetailLoading:i,pending:r,tab:n,linkOptions:l,onTabChange:o,onDraftChange:d,onSave:m}){const[h,c]=u.useState(null),p=u.useMemo(()=>jL(a),[a]),g=typeof t.derived.efficiency=="number"?t.derived.efficiency:t.timeInBedSeconds>0?t.asleepSeconds/t.timeInBedSeconds:0,x=typeof t.derived.restorativeShare=="number"?t.derived.restorativeShare:0,f=typeof t.derived.recoveryState=="string"?t.derived.recoveryState:null;return e.jsx(le,{className:"overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(10,17,33,0.98),rgba(13,20,38,0.96))] p-0",children:e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{className:te("border-white/0",Fv(f)),children:f?f.replaceAll("_"," "):"Canonical night"}),e.jsxs(S,{tone:"meta",children:[t.rawSegmentCount," raw segments"]}),e.jsx(S,{tone:"meta",children:t.sourceTimezone})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected night"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Lv(t.endedAt,t.sourceTimezone)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:Wo(t.startedAt,t.endedAt,t.sourceTimezone)})]}),e.jsxs("div",{className:"grid gap-2 text-right",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Summary"}),e.jsx("div",{className:"text-3xl text-white",children:zs(t.asleepSeconds)}),e.jsx("div",{className:"text-sm text-white/54",children:"asleep"})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:zs(t.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Awake"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:zs(t.awakeSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:xn(g)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Restorative"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:xn(x)})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(nu,{active:n==="summary",onClick:()=>o("summary"),children:"Summary"}),e.jsx(nu,{active:n==="reflection",onClick:()=>o("reflection"),children:"Reflection"}),e.jsx(nu,{active:n==="raw",onClick:()=>o("raw"),children:"Show raw data"})]}),n==="summary"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/18 px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Phase timeline"}),e.jsx("div",{className:"mt-4",children:i?e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-6 text-sm text-white/56",children:"Loading phase timing from raw sleep segments…"}):e.jsx(kL,{timeline:(a==null?void 0:a.phaseTimeline)??{startedAt:t.startedAt,endedAt:t.endedAt,totalSeconds:Math.max(0,Math.round((new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime())/1e3)),hasRawSegments:!1,hasSleepStageData:!1,blocks:[]},timeZone:t.sourceTimezone})})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/18 px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(Rv,{stages:t.stageBreakdown})})]})]}):null,n==="reflection"?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Quality summary"}),e.jsx(be,{value:s.qualitySummary,onChange:b=>d({qualitySummary:b.target.value}),placeholder:"Recovered after a late evening, but sleep onset drifted."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Night notes"}),e.jsx(st,{className:"min-h-[200px]",value:s.notes,onChange:b=>d({notes:b.target.value}),placeholder:"What shaped this night, and what should we remember about it?"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(be,{value:s.tagsText,onChange:b=>d({tagsText:b.target.value}),placeholder:"travel, stress, good-routine, late-caffeine"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Linked context"}),e.jsx(bt,{options:l,selectedValues:s.linkValues,onChange:b=>d({linkValues:b}),placeholder:"Search goals, tasks, habits, beliefs, reports, or patterns…"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(H,{type:"button",pending:r,pendingLabel:"Saving",onClick:m,children:[e.jsx(Ni,{className:"size-4"}),"Save reflection"]})})]}):null,n==="raw"?e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm leading-6 text-white/56",children:"Forge shows the canonical overnight session by default. This view reveals the evidence stack underneath it: raw provider or historical imported records first, then Forge-normalized sleep segments."}),i?e.jsx("div",{className:"text-sm text-white/56",children:"Loading raw sleep evidence…"}):null,i?null:e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{className:te("border-white/0",bL(p.rawDataStatus)),children:yL(p.rawDataStatus)}),p.rawDataStatus==="historical_raw"?e.jsx(S,{tone:"meta",children:"Partial evidence"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Raw data"}),p.sourceRecords.length?p.sourceRecords.map(b=>e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-black/18 px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{className:te("border-white/0",wL(b)),children:b.qualityKind==="provider_native"?"Provider raw":"Historical raw"}),e.jsx(S,{tone:"meta",className:"capitalize",children:b.rawStage.replaceAll("_"," ")}),e.jsx("span",{className:"text-sm text-white/64",children:Wo(b.startedAt,b.endedAt,b.sourceTimezone)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-white/42",children:b.providerRecordType.replaceAll("_"," ")}),e.jsx(H,{type:"button",variant:"secondary",className:"h-8 rounded-full px-3",onClick:()=>c(A=>A===b.id?null:b.id),children:h===b.id?"Hide JSON":"See JSON"})]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/50",children:zs(Math.max(0,Math.round((new Date(b.endedAt).getTime()-new Date(b.startedAt).getTime())/1e3)))}),h===b.id?e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[14px] border border-white/8 bg-slate-950/70 p-3 text-xs leading-6 text-white/72",children:JSON.stringify({payload:b.payload,metadata:b.metadata},null,2)}):null]},b.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No raw data was stored for this night."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sleep segments"}),p.segments.length?p.segments.map(b=>e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-black/18 px-4 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{tone:"meta",className:"capitalize",children:b.stage.replaceAll("_"," ")}),e.jsx(S,{tone:"meta",children:b.qualityKind==="provider_native"?"provider-backed":"historical"}),e.jsx("span",{className:"text-sm text-white/64",children:Wo(b.startedAt,b.endedAt,b.sourceTimezone)})]}),e.jsx("span",{className:"text-sm text-white/50",children:zs(Math.max(0,Math.round((new Date(b.endedAt).getTime()-new Date(b.startedAt).getTime())/1e3)))})]})},b.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No normalized sleep segments were stored for this night."})]})]})]}):null]})})}function IL(){var R;const t=Ct(),s=pt(),[a,i]=u.useState({}),[r,n]=u.useState(null),[l,o]=u.useState("summary"),d=Array.isArray(t==null?void 0:t.selectedUserIds)?t.selectedUserIds:[],m=t==null?void 0:t.snapshot,h=Me({queryKey:["forge-sleep",...d],queryFn:async()=>(await Lm(d)).sleep}),c=Me({queryKey:["forge-sleep-raw",r],enabled:!!r,queryFn:async()=>F1(r)}),p=Me({queryKey:["forge-sleep-values",...d],queryFn:async()=>(await ia(d)).values}),g=Me({queryKey:["forge-sleep-patterns",...d],queryFn:async()=>(await si(d)).patterns}),x=Me({queryKey:["forge-sleep-behaviors",...d],queryFn:async()=>(await ra(d)).behaviors}),f=Me({queryKey:["forge-sleep-beliefs",...d],queryFn:async()=>(await Oa(d)).beliefs}),b=Me({queryKey:["forge-sleep-reports",...d],queryFn:async()=>(await Ai(d)).reports});u.useEffect(()=>{h.data&&i(Object.fromEntries(h.data.sessions.map(v=>[v.id,Po(v)])))},[h.data]),u.useEffect(()=>{var D,L,Q;if(!((D=h.data)!=null&&D.sessions.length)){n(null);return}h.data.sessions.some(Z=>Z.id===r)||n(((L=h.data.latestNight)==null?void 0:L.sleepId)??((Q=h.data.sessions[0])==null?void 0:Q.id)??null)},[r,h.data]),u.useEffect(()=>{o("summary")},[r]);const A=De({mutationFn:async v=>vb(v.sleepId,{qualitySummary:v.qualitySummary,notes:v.notes,tags:v.tagsText.split(",").map(D=>D.trim()).filter(Boolean),links:Ev(v.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-sleep"]}),await s.invalidateQueries({queryKey:["forge-sleep-raw"]})}});if(h.isLoading)return e.jsx(gs,{eyebrow:"Sleep",title:"Loading sleep surface",description:"Reading canonical nights, calendar summaries, and sleep phase detail.",columns:2,blocks:6});if(h.isError||!h.data)return e.jsx(ct,{eyebrow:"Sleep",error:h.error??new Error("Sleep data unavailable"),onRetry:()=>void h.refetch()});const T=h.data,I=T.sessions,y=new Map(I.map(v=>[v.id,v])),N=(r?y.get(r):null)??(T.latestNight?y.get(T.latestNight.sleepId):null)??I[0]??null,k=N?a[N.id]??Po(N):null,w=Mv({goals:(m==null?void 0:m.dashboard.goals)??[],projects:(m==null?void 0:m.dashboard.projects)??[],tasks:(m==null?void 0:m.dashboard.tasks)??[],habits:(m==null?void 0:m.dashboard.habits)??[],values:p.data??[],patterns:g.data??[],behaviors:x.data??[],beliefs:f.data??[],reports:b.data??[]});function P(v,D){i(L=>{const Q=I.find(V=>V.id===v),Z=L[v]??(Q?Po(Q):{qualitySummary:"",notes:"",tagsText:"",linkValues:[]});return{...L,[v]:{...Z,...D}}})}async function j(v){const D=I.find(Q=>Q.id===v);if(!D)return;const L=a[v]??Po(D);await A.mutateAsync({sleepId:v,qualitySummary:L.qualitySummary,notes:L.notes,tagsText:L.tagsText,linkValues:L.linkValues})}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(mt,{eyebrow:"Health",title:"Sleep",description:"Canonical overnight sessions first, with last-night recovery, a clickable night calendar, and raw segment evidence only when you ask for it.",badge:`${I.length} nights`}),e.jsx(Es,{}),e.jsx(vy,{children:e.jsx(NL,{latestNight:T.latestNight})}),e.jsx(jy,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]",children:[e.jsx(ru,{title:"Weekly average",value:zs(T.summary.averageSleepSeconds),description:"Average overnight sleep duration across the recent week, used as the baseline for the latest-night comparison."}),e.jsx(ru,{title:"Regularity",value:`${T.summary.averageRegularityScore}`,description:`Average bedtime drift ${T.summary.averageBedtimeConsistencyMinutes}m and wake drift ${T.summary.averageWakeConsistencyMinutes}m.`}),e.jsx(ru,{title:"Restorative share",value:xn(T.summary.averageRestorativeShare),description:`Deep + REM share across recent nights, with ${T.summary.reflectiveNightCount} nights already carrying context.`}),e.jsxs(le,{className:"border-white/8 bg-white/[0.03]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Recent stage mix"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:"Average nightly phases"})]}),e.jsx(bs,{className:"size-5 text-[var(--primary)]"})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:T.stageAverages.length>0?T.stageAverages.slice(0,5).map(v=>e.jsxs(S,{tone:"meta",children:[jl(v.stage).label," ",zs(v.averageSeconds)]},v.stage)):e.jsx("div",{className:"text-sm text-white/52",children:"Stage averages will appear once nights include phase data."})})]})]})}),e.jsx(ky,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(SL,{days:T.calendarDays,selectedSleepId:(N==null?void 0:N.id)??null,onSelect:v=>n(v)}),N&&k?e.jsx(CL,{session:N,draft:k,rawDetail:c.data??null,rawDetailLoading:c.isLoading,pending:A.isPending&&((R=A.variables)==null?void 0:R.sleepId)===N.id,tab:l,linkOptions:w,onTabChange:o,onDraftChange:v=>P(N.id,v),onSave:()=>void j(N.id)}):e.jsx(le,{className:"border-white/8 bg-white/[0.03] px-6 py-8 text-sm leading-6 text-white/58",children:"Pick a night from the calendar to inspect its phase timing, stage summary, and reflection context."})]})})]})}function cr(t){return t?t.replace(/^activity_/i,"").replaceAll("_"," ").replace(/\s+/g," ").replace(/\b\w/g,s=>s.toUpperCase()):"Unknown"}function al(t){return`${Math.round(t/60)}m`}function sm(t){return t?`${(t/1e3).toFixed(1)} km`:"n/a"}function il(t,s){const a=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}),i=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${a.format(new Date(t))} · ${i.format(new Date(t))} - ${i.format(new Date(s))}`}function qn(t){return{subjectiveEffort:t.subjectiveEffort!==null?String(t.subjectiveEffort):"",moodBefore:t.moodBefore??"",moodAfter:t.moodAfter??"",meaningText:t.meaningText??"",plannedContext:t.plannedContext??"",socialContext:t.socialContext??"",tagsText:Array.isArray(t.tags)?t.tags.join(", "):"",linkValues:Array.isArray(t.links)?t.links.map(s=>`${s.entityType}:${s.entityId}`):[]}}function Dv(t){return t.trim().toLowerCase()}function ar(t){var s;return((s=t.workoutTypeLabel)==null?void 0:s.trim())||cr(t.workoutType)}function kl(t){var s;return((s=t.activityFamilyLabel)==null?void 0:s.trim())||cr(t.activityFamily)}function $v(t){return cr(t.sourceSystem??t.source)}function TL(t){return t==null?"n/a":typeof t=="boolean"?t?"Yes":"No":typeof t=="number"?Number.isInteger(t)?String(t):t.toFixed(1):t}function PL(t){const s=TL(t.value);return!t.unit||t.unit==="count"?s:`${s} ${t.unit}`}function AL(t,s){return Dv([t.workoutType,ar(t),t.activityFamily,kl(t),t.sourceSystem,$v(t),t.sourceType,t.sourceDevice,t.reconciliationStatus,t.moodBefore,t.moodAfter,t.meaningText,t.plannedContext,t.socialContext,t.tags.join(" "),s.moodBefore,s.moodAfter,s.meaningText,s.plannedContext,s.socialContext,s.tagsText,il(t.startedAt,t.endedAt)].join(" "))}function ML(t){const s=new Map;for(const a of t)s.set(`workout:${a.workoutType}`,{id:`workout:${a.workoutType}`,label:ar(a),description:"Workout type",searchText:`${ar(a)} workout`,badge:e.jsx(S,{tone:"meta",children:ar(a)})}),s.set(`source:${a.sourceType}`,{id:`source:${a.sourceType}`,label:a.sourceType.replaceAll("_"," "),description:"Source type",searchText:`${a.sourceType} source`,badge:e.jsx(S,{tone:"meta",className:"capitalize",children:a.sourceType.replaceAll("_"," ")})}),s.set(`status:${a.reconciliationStatus}`,{id:`status:${a.reconciliationStatus}`,label:a.reconciliationStatus.replaceAll("_"," "),description:"Reconciliation status",searchText:`${a.reconciliationStatus} status`,badge:e.jsx(S,{tone:"meta",className:"capitalize",children:a.reconciliationStatus.replaceAll("_"," ")})});return s.set("linked:yes",{id:"linked:yes",label:"Linked",description:"Already tied to Forge or Psyche context",badge:e.jsx(S,{tone:"meta",children:"Linked"})}),s.set("linked:no",{id:"linked:no",label:"Needs links",description:"No Forge or Psyche links yet",badge:e.jsx(S,{tone:"meta",children:"Needs links"})}),s.set("habit:yes",{id:"habit:yes",label:"Habit-generated",description:"Created from a habit completion",badge:e.jsx(S,{tone:"meta",children:"Habit-generated"})}),s.set("effort:rated",{id:"effort:rated",label:"Effort rated",description:"Already has a subjective effort score",badge:e.jsx(S,{tone:"meta",children:"Effort rated"})}),Array.from(s.values())}function EL(t,s){return s.every(a=>a.startsWith("workout:")?t.workoutType===a.slice(8):a.startsWith("source:")?t.sourceType===a.slice(7):a.startsWith("status:")?t.reconciliationStatus===a.slice(7):a==="linked:yes"?t.links.length>0:a==="linked:no"?t.links.length===0:a==="habit:yes"?!!t.generatedFromHabitId:a==="effort:rated"?t.subjectiveEffort!==null:!0)}function LL({session:t,draft:s,linkOptions:a,pending:i,step:r,onStepChange:n,onDraftChange:l,onSave:o}){var m,h,c,p,g,x,f,b,A;const d=[{id:"context",title:"Session context",description:"Quick facts, effort, and how this session happened."},{id:"reflection",title:"Reflection",description:"Mood, meaning, and what the session actually did for you."},{id:"links",title:"Links",description:"Tie the session back to Forge and Psyche context."}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] p-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-lg text-white",children:[e.jsx(pm,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:ar(t)})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:il(t.startedAt,t.endedAt)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{children:al(t.durationSeconds)}),t.totalEnergyKcal?e.jsxs(S,{tone:"meta",children:[Math.round(t.totalEnergyKcal)," kcal"]}):null,t.distanceMeters?e.jsx(S,{tone:"meta",children:sm(t.distanceMeters)}):null,e.jsx(S,{tone:"meta",children:kl(t)}),e.jsx(S,{tone:"meta",className:"capitalize",children:t.reconciliationStatus.replaceAll("_"," ")})]})]})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:d.map((T,I)=>e.jsxs("button",{type:"button",onClick:()=>n(I),className:`rounded-[20px] border px-4 py-3 text-left transition ${r===I?"border-[var(--primary)] bg-[var(--primary)]/10 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.06] hover:text-white"}`,children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:["Step ",I+1]}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:T.title})]},T.id))}),e.jsxs("div",{className:"rounded-[24px] bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:d[r].title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:d[r].description}),r===0?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Activity family"}),e.jsx("div",{className:"mt-2 text-lg text-white capitalize",children:kl(t)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source system"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:$v(t)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source device"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.sourceDevice||"n/a"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Steps"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.stepCount??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Avg HR"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.averageHeartRate?Math.round(t.averageHeartRate):"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Max HR"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.maxHeartRate?Math.round(t.maxHeartRate):"n/a"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Effort"}),e.jsx(be,{type:"number",min:1,max:10,value:s.subjectiveEffort,onChange:T=>l({subjectiveEffort:T.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Planned vs spontaneous"}),e.jsx(be,{value:s.plannedContext,onChange:T=>l({plannedContext:T.target.value}),placeholder:"Planned recovery block"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Social context"}),e.jsx(be,{value:s.socialContext,onChange:T=>l({socialContext:T.target.value}),placeholder:"Solo, coach, group class, partner"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(be,{value:s.tagsText,onChange:T=>l({tagsText:T.target.value}),placeholder:"recovery, interval-block, stress-release"})]})]}):null,r===1?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood before"}),e.jsx(be,{value:s.moodBefore,onChange:T=>l({moodBefore:T.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood after"}),e.jsx(be,{value:s.moodAfter,onChange:T=>l({moodAfter:T.target.value})})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Meaning, impact, and why this session mattered"}),e.jsx(st,{className:"min-h-[160px]",value:s.meaningText,onChange:T=>l({meaningText:T.target.value}),placeholder:"This session was planned as active recovery after a heavy work block and helped reset stress before sleep."})]})]}):null,r===2?e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Search goals, projects, habits, values, beliefs, patterns, or reports and attach the ones that explain this session."}),e.jsx(bt,{options:a,selectedValues:s.linkValues,onChange:T=>l({linkValues:T}),placeholder:"Search Forge and Psyche records…"})]}):null,e.jsxs("div",{className:"mt-5 grid gap-4 border-t border-white/8 pt-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Captured data"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Source-native workout metrics, events, and phases exposed through the adapter layer."})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:[(((m=t.details)==null?void 0:m.metrics)??[]).slice(0,12).map(T=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:T.label}),e.jsx("div",{className:"mt-2 text-lg text-white",children:PL(T)}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.14em] text-white/38",children:[cr(T.category)," · ",cr(T.statistic)]})]},`${T.category}:${T.key}:${T.statistic}`)),(((c=(h=t.details)==null?void 0:h.metrics)==null?void 0:c.length)??0)===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/50",children:"No provider metrics were captured for this session yet."}):null]}),(((g=(p=t.details)==null?void 0:p.events)==null?void 0:g.length)??0)>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workout events"}),e.jsx("div",{className:"grid gap-2",children:(x=t.details)==null?void 0:x.events.map(T=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-white",children:T.label}),e.jsx(S,{tone:"meta",children:al(T.durationSeconds)})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:il(T.startedAt,T.endedAt??T.startedAt)})]},`${T.type}:${T.startedAt}`))})]}):null,(((b=(f=t.details)==null?void 0:f.components)==null?void 0:b.length)??0)>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workout phases"}),e.jsx("div",{className:"grid gap-2",children:(A=t.details)==null?void 0:A.components.map(T=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-white",children:T.activity.canonicalLabel}),e.jsx(S,{tone:"meta",children:al(T.durationSeconds)})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:il(T.startedAt,T.endedAt??T.startedAt)})]},T.externalUid))})]}):null]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm text-white/48",children:r<d.length-1?"Move through the session one step at a time, then save when the context is clean.":"Everything is in place. Save the session metadata back into Forge."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(H,{type:"button",variant:"secondary",onClick:()=>n(Math.max(0,r-1)),disabled:r===0,children:"Back"}),r<d.length-1?e.jsxs(H,{type:"button",onClick:()=>n(r+1),children:["Next",e.jsx(Ca,{className:"size-4"})]}):null,e.jsxs(H,{type:"button",pending:i,pendingLabel:"Saving",onClick:o,children:[e.jsx(Ni,{className:"size-4"}),"Save session"]})]})]})]})}function _L(){var E;const t=Ct(),s=pt(),a=u.useRef(null),i=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[r,n]=u.useState({}),[l,o]=u.useState(""),[d,m]=u.useState([]),[h,c]=u.useState(null),[p,g]=u.useState(0),x=Me({queryKey:["forge-fitness",...i],queryFn:async()=>(await gb(i)).fitness}),f=Me({queryKey:["forge-health-values",...i],queryFn:async()=>(await ia(i)).values}),b=Me({queryKey:["forge-health-patterns",...i],queryFn:async()=>(await si(i)).patterns}),A=Me({queryKey:["forge-health-behaviors",...i],queryFn:async()=>(await ra(i)).behaviors}),T=Me({queryKey:["forge-health-beliefs",...i],queryFn:async()=>(await Oa(i)).beliefs}),I=Me({queryKey:["forge-health-reports",...i],queryFn:async()=>(await Ai(i)).reports});u.useEffect(()=>{x.data&&n(Object.fromEntries(x.data.sessions.map(X=>[X.id,qn(X)])))},[x.data]);const y=De({mutationFn:async X=>s2(X.workoutId,{subjectiveEffort:X.subjectiveEffort.trim().length>0?Number(X.subjectiveEffort):null,moodBefore:X.moodBefore,moodAfter:X.moodAfter,meaningText:X.meaningText,plannedContext:X.plannedContext,socialContext:X.socialContext,tags:X.tagsText.split(",").map(W=>W.trim()).filter(Boolean),links:Ev(X.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-fitness"]})}}),N=x.data,k=(N==null?void 0:N.sessions)??[],w=Mv({goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.dashboard.tasks,habits:t.snapshot.dashboard.habits,values:f.data??[],patterns:b.data??[],behaviors:A.data??[],beliefs:T.data??[],reports:I.data??[]}),P=u.useMemo(()=>ML(k),[k]),j=u.useMemo(()=>{const X=Dv(l);return[...k].sort((W,q)=>new Date(q.startedAt).getTime()-new Date(W.startedAt).getTime()).filter(W=>{const q=r[W.id]??qn(W);return(X.length===0||AL(W,q).includes(X))&&EL(W,d)})},[r,l,d,k]),R=j.length===k.length&&l.trim().length===0&&d.length===0?`${k.length} workout sessions visible`:`${j.length} of ${k.length} workout sessions visible`,v=j.find(X=>X.id===h)??k.find(X=>X.id===h)??null,D=v?r[v.id]??qn(v):null,L=Ad({count:j.length,getScrollElement:()=>a.current,estimateSize:()=>108,overscan:8});if(x.isLoading)return e.jsx(gs,{eyebrow:"Sports",title:"Loading sports view",description:"Reading synced workouts and local reflection metadata.",columns:2,blocks:6});if(x.isError||!N)return e.jsx(ct,{eyebrow:"Sports",error:x.error??new Error("Sports data unavailable"),onRetry:()=>void x.refetch()});const{summary:Q,weeklyTrend:Z,typeBreakdown:V}=N;function B(X,W){n(q=>{const G=q[X]??qn(k.find(z=>z.id===X));return{...q,[X]:{...G,...W}}})}async function $(X){const W=k.find(G=>G.id===X);if(!W)return;const q=r[X]??qn(W);await y.mutateAsync({workoutId:X,subjectiveEffort:q.subjectiveEffort,moodBefore:q.moodBefore,moodAfter:q.moodAfter,meaningText:q.meaningText,plannedContext:q.plannedContext,socialContext:q.socialContext,tagsText:q.tagsText,linkValues:q.linkValues}),c(null),g(0)}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(mt,{entityKind:"project",title:"Sports",description:"A session-first training surface for workout data, subjective meaning, and links back into Forge execution and Psyche.",badge:`${k.length} sessions`}),e.jsx(Ny,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Weekly volume"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:al(Q.weeklyVolumeSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Total training time in the recent week."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Exercise minutes"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.exerciseMinutes}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Aggregate exercise minutes from synced sessions."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Energy burned"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.energyBurnedKcal}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Recent weekly kcal."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training streak"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.streakDays}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Distinct workout days in the recent week."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average session"}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[Q.averageSessionMinutes,"m"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean duration across recent sessions."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average effort"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.averageEffort||"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Subjective effort across sessions that carry a rating."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked sessions"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Q.linkedSessionCount}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Sessions already tied to Forge or Psyche entities."})]}),e.jsxs(le,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Top block"}),e.jsx("div",{className:"mt-3 text-xl text-white",children:Q.topWorkoutTypeLabel??Q.topWorkoutType??"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Dominant workout type across the recent window."})]})]})}),e.jsx(Sy,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[1.05fr_0.95fr]",children:[e.jsxs(le,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recent volume"}),e.jsx("div",{className:"grid gap-3",children:Z.map(X=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[110px_150px_minmax(0,1fr)_90px]",children:[e.jsx("div",{className:"text-sm text-white/62",children:X.dateKey}),e.jsx("div",{className:"text-sm text-white",children:X.workoutTypeLabel??cr(X.workoutType)}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--primary)]",style:{width:`${Math.min(100,X.durationMinutes/120*100)}%`}})}),e.jsxs("div",{className:"text-sm text-white",children:[X.durationMinutes,"m"]})]}),e.jsxs("div",{className:"text-sm text-white/62",children:[X.energyKcal," kcal"]})]},X.id))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Distance"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:sm(Q.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Planned sessions"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Q.plannedSessionCount})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Imported / merged"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[Q.importedSessionCount," / ",Q.reconciledSessionCount]})]})]})]}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training composition"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Workout type and provenance mix"})]}),e.jsx("div",{className:"grid gap-3",children:V.slice(0,6).map(X=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[minmax(0,1fr)_90px_90px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white",children:X.workoutTypeLabel??cr(X.workoutType)}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[X.sessionCount," sessions · ",X.activityFamilyLabel??"Other"]})]}),e.jsxs("div",{className:"text-sm text-white/72",children:[X.totalMinutes,"m"]}),e.jsxs("div",{className:"text-sm text-white/72",children:[X.energyKcal," kcal"]})]},X.workoutType))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Habit-generated"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Q.habitGeneratedSessionCount})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Forge-linked"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Q.linkedSessionCount})]})]})]})]})}),e.jsx(Cy,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(Ii,{title:"Session browser",description:"Search past activities by workout type, source, reconciliation state, or whether they still need context.",query:l,onQueryChange:o,options:P,selectedOptionIds:d,onSelectedOptionIdsChange:m,resultSummary:R,placeholder:"Search workouts, devices, notes, moods, or filter chips",emptyStateMessage:"Keep typing or pick a filter chip to narrow the activity history."}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Activity history"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a workout to add reflection and links in a guided modal."})]}),e.jsx(S,{tone:"meta",children:R})]}),e.jsx("div",{ref:a,className:"h-[34rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:j.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No workout matches the current search yet. Clear some filters or search by workout type, device, or reflection text."}):e.jsx("div",{className:"relative w-full",style:{height:`${L.getTotalSize()}px`},children:L.getVirtualItems().map(X=>{const W=j[X.index],q=W.meaningText.trim().length>0||W.moodBefore.trim().length>0||W.moodAfter.trim().length>0||W.tags.length>0||W.links.length>0;return e.jsx("div",{className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${X.start}px)`},children:e.jsxs("button",{type:"button",className:"grid w-full gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>{c(W.id),g(0)},children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(pm,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:ar(W)})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-sm text-white/56",children:[e.jsx(bs,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:il(W.startedAt,W.endedAt)})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/46",children:[kl(W)," · ",W.sourceDevice]})]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.05] px-3 py-1.5 text-xs text-white/70",children:[e.jsx("span",{children:q?"Reflected":"Needs reflection"}),e.jsx(Ca,{className:"size-3.5"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{children:al(W.durationSeconds)}),W.totalEnergyKcal?e.jsxs(S,{tone:"meta",children:[Math.round(W.totalEnergyKcal)," kcal"]}):null,W.distanceMeters?e.jsx(S,{tone:"meta",children:sm(W.distanceMeters)}):null,W.averageHeartRate?e.jsxs(S,{tone:"meta",children:[e.jsx(Sf,{className:"mr-1 size-3.5"}),Math.round(W.averageHeartRate)," bpm"]}):null,e.jsx(S,{tone:"meta",children:kl(W)}),e.jsx(S,{tone:"meta",className:"capitalize",children:W.sourceType.replaceAll("_"," ")}),e.jsx(S,{tone:"meta",className:"capitalize",children:W.reconciliationStatus.replaceAll("_"," ")})]})]})},W.id)})})})]})]})}),v&&D?e.jsx(Pa,{open:!!v,onOpenChange:X=>{X||(c(null),g(0))},eyebrow:"Sports session",title:ar(v),description:"Add contextual meaning without crowding the main training surface.",children:e.jsx(LL,{session:v,draft:D,linkOptions:w,pending:y.isPending&&((E=y.variables)==null?void 0:E.workoutId)===v.id,step:p,onStepChange:g,onDraftChange:X=>B(v.id,X),onSave:()=>void $(v.id)})}):null]})}function Fs({label:t,help:s}){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/58",children:[e.jsx("span",{children:t}),s?e.jsx(Tt,{content:s,label:`Explain ${t}`}):null]})}const Ao=[{status:"backlog",label:"Backlog",description:"Not started yet.",icon:Va},{status:"focus",label:"Focus",description:"Ready to start soon.",icon:Sl},{status:"in_progress",label:"In progress",description:"Work is active now.",icon:ta},{status:"blocked",label:"Blocked",description:"Something is stopping progress.",icon:Pf},{status:"done",label:"Done",description:"The task is completed.",icon:ml}],FL={issue:{label:"Issue",noun:"issue",descriptor:"Vertical slice issue",heroDescription:"Track the vertical slice, keep the acceptance bar explicit, and surface the execution context without losing the product-level story."},task:{label:"Task",noun:"task",descriptor:"AI session task",heroDescription:"Drive one focused AI execution session, keep the work contract crisp, and show the concrete evidence of what changed."},subtask:{label:"Subtask",noun:"subtask",descriptor:"Granular child step",heroDescription:"Keep the child step sharply scoped, trace its parent chain, and make the work evidence visible without opening the editor."}},RL={commit:{label:"Commit",className:"bg-emerald-500/12 text-emerald-100"},branch:{label:"Branch",className:"bg-sky-500/12 text-sky-100"},pull_request:{label:"Pull request",className:"bg-fuchsia-500/12 text-fuchsia-100"}};function lu(t){return t==="issue"?"issue":"task"}function DL(t,s){switch(t){case"goal":return`/goals/${s}`;case"project":return`/projects/${s}`;case"task":return`/tasks/${s}`;case"strategy":return`/strategies/${s}`;case"habit":return"/habits";default:return null}}function Di(t){if(!t||t<=0)return"0 min";if(t<3600)return`${Math.max(1,Math.round(t/60))} min`;const s=Math.floor(t/3600),a=Math.round(t%3600/60);return a===0?`${s} h`:`${s} h ${a} min`}function $i({eyebrow:t,title:s,description:a,children:i,className:r}){return e.jsxs("div",{className:te("rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.025))] p-4 sm:p-5",r),children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsx("div",{className:"mt-2 text-lg font-medium text-white",children:s}),a?e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/56",children:a}):null,e.jsx("div",{className:"mt-4",children:i})]})}function Bs({label:t,value:s,hint:a,className:i}){return e.jsxs("div",{className:te("rounded-[18px] border border-white/8 bg-white/[0.035] px-4 py-3",i),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:t}),e.jsx("div",{className:"mt-2 text-base font-medium text-white",children:s}),a?e.jsx("div",{className:"mt-1 text-sm leading-5 text-white/52",children:a}):null]})}function $L(){var Be,at,Le,Y,ee,xe,ye;const{t,formatDate:s,formatDateTime:a}=Gt(),i=Ct(),r=Array.isArray(i.selectedUserIds)?i.selectedUserIds:[],n=aa(),l=Ht(),o=pt(),d=Is(r),[m,h]=u.useState(!1),[c,p]=u.useState(!1),[g,x]=u.useState(!1),[f,b]=u.useState(!1),[A,T]=u.useState(!1),[I,y]=u.useState(null),[N,k]=u.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 1023px)").matches:!1),[w]=u.useState(()=>{const ue=new Date,$e=new Date(ue);$e.setHours(0,0,0,0);const Xe=new Date(ue);return Xe.setHours(23,59,59,999),{from:$e.toISOString(),to:Xe.toISOString()}}),[P]=u.useState(()=>{const ue=new Date,$e=new Date(ue);$e.setHours(0,0,0,0);const Xe=new Date($e);return Xe.setDate(Xe.getDate()+7),Xe.setHours(23,59,59,999),{from:$e.toISOString(),to:Xe.toISOString()}});u.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const ue=window.matchMedia("(max-width: 1023px)"),$e=Xe=>k(Xe?Xe.matches:ue.matches);return $e(),typeof ue.addEventListener=="function"?(ue.addEventListener("change",$e),()=>ue.removeEventListener("change",$e)):(ue.addListener($e),()=>ue.removeListener($e))},[]);const j=Me({queryKey:["task-context",n.taskId],queryFn:()=>q2(n.taskId),enabled:!!n.taskId}),R=Me({queryKey:["task-calendar-overview",n.taskId,w.from,w.to,...r],queryFn:()=>nn({...w,userIds:r}),enabled:!!n.taskId}),v=Me({queryKey:["forge-life-force",...r],queryFn:async()=>(await hr(r)).lifeForce}),D=Me({queryKey:["task-calendar-overview",n.taskId,P.from,P.to,...r],queryFn:()=>nn({...P,userIds:r}),enabled:!!n.taskId}),L=async()=>{await Promise.all([Zt(o),o.invalidateQueries({queryKey:["task-context",n.taskId]}),o.invalidateQueries({queryKey:["activity-archive"]}),o.invalidateQueries({queryKey:["project-board"]}),o.invalidateQueries({queryKey:["forge-xp-metrics"]}),o.invalidateQueries({queryKey:["forge-reward-ledger"]}),o.invalidateQueries({queryKey:["forge-operator-context"]}),o.invalidateQueries({queryKey:["task-calendar-overview",n.taskId]}),o.invalidateQueries({queryKey:["forge-calendar-overview"]})])},Q=De({mutationFn:({taskId:ue,patch:$e})=>i.patchTask(ue,$e),onSuccess:L}),Z=De({mutationFn:ue=>Km(ue),onSuccess:L}),V=De({mutationFn:ue=>Sb(ue),onSuccess:L}),B=De({mutationFn:({runId:ue,actor:$e,note:Xe})=>Ib(ue,{actor:$e,note:Xe??""}),onSuccess:L}),$=De({mutationFn:({runId:ue,actor:$e,note:Xe})=>Cb(ue,{actor:$e,note:Xe??""}),onSuccess:L}),E=De({mutationFn:qm,onSuccess:L}),X=De({mutationFn:ue=>zm(ue),onSuccess:L}),W=De({mutationFn:mb,onSuccess:L}),q=De({mutationFn:({timeboxId:ue,patch:$e})=>vu(ue,$e),onSuccess:L}),G=De({mutationFn:hb,onSuccess:L}),z=j.data;if(j.isLoading)return e.jsx(gs,{});if(j.isError)return e.jsx(ct,{eyebrow:t("common.taskDetail.errorEyebrow"),error:j.error,onRetry:()=>void j.refetch()});if(!z)return e.jsx(ct,{eyebrow:t("common.taskDetail.errorEyebrow"),error:new Error(t("common.taskDetail.emptyPayload")),onRetry:()=>void j.refetch()});const ge=z.activeTaskRun??null,ke=z.task.actionPointSummary??null,me=Ao.find(ue=>ue.status===z.task.status)??Ao[0],se=z.task.level??"task",we=z.task.aiInstructions??"",ve=IP(z.task,(Be=z.project)==null?void 0:Be.schedulingRules),_=Xw({rules:ve,overview:(at=R.data)==null?void 0:at.calendar}),F=(((Le=D.data)==null?void 0:Le.calendar.timeboxes)??[]).filter(ue=>ue.taskId===z.task.id).sort((ue,$e)=>Date.parse(ue.startsAt)-Date.parse($e.startsAt)),O=F[0]??null,ce=FL[se],J=lu(se),je=i.snapshot.workItems??i.snapshot.tasks??[],Ee=z.task.parentWorkItemId?je.find(ue=>ue.id===z.task.parentWorkItemId)??null:null,Ce=je.filter(ue=>ue.parentWorkItemId===z.task.id).sort((ue,$e)=>ue.sortOrder-$e.sortOrder),Ke=i.snapshot.tags??[],Pe=(z.task.tagIds??[]).map(ue=>Ke.find($e=>$e.id===ue)??null).filter(ue=>!!ue),M=z.task.acceptanceCriteria??[],U=z.task.blockerLinks??[],he=z.task.gitRefs??[],Ne=z.task.completionReport,fe=new Set((Ne==null?void 0:Ne.linkedGitRefIds)??[]),Se=he.filter(ue=>fe.has(ue.id)),Je=he.filter(ue=>!fe.has(ue.id)),nt=((Y=z.task.user)==null?void 0:Y.kind)==="bot"||((ee=z.task.ownerUser)==null?void 0:ee.kind)==="bot",K=(z.task.assignees??[]).filter(ue=>ue.kind==="bot"),Ie=we.trim().length>0,_e=N?"w-full justify-start":"",ae=ue=>{switch(ue){case"active":return"Active";case"completed":return"Completed";case"released":return"Paused";case"timed_out":return"Timed out";default:return ue}},Fe=async ue=>{await i.patchTaskStatus(z.task.id,ue),await L(),T(!1)},ie=async()=>{window.confirm(`Delete ${ce.noun} "${z.task.title}"?`)&&(await X.mutateAsync(z.task.id),l(z.project?`/projects/${z.project.id}`:z.goal?`/goals/${z.goal.id}`:"/kanban"))};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(mt,{entityKind:J,title:e.jsx(It,{kind:J,label:z.task.title,variant:"heading",size:"lg",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),titleText:z.task.title,description:z.task.description?e.jsx(Ws,{markdown:z.task.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):ce.heroDescription,badge:ke?`${z.task.points} xp · ${Math.round(ke.totalCostAp)} AP`:`${z.task.points} xp`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Mi,{metrics:i.snapshot.metrics}),e.jsx(Qd,{userId:d,domain:"tasks",entityType:"task",entityId:z.task.id,label:z.task.title,description:z.task.description}),e.jsx(fr,{entityType:"task",entityId:z.task.id})]})}),e.jsxs(le,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:ce.label}),e.jsx("div",{className:"mt-2",children:e.jsx(It,{kind:J,label:z.task.title,variant:"heading",size:"xl",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"})}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:z.task.description?e.jsx(Ws,{markdown:z.task.description,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):`This page shows the ${ce.noun}, where it belongs, what is driving it, and the concrete evidence of what has happened on it so far.`})]}),e.jsx("div",{className:te("shrink-0",N?"w-full":""),children:e.jsxs("div",{className:te("flex flex-wrap items-center gap-2",N&&"grid w-full grid-cols-1"),children:[e.jsxs(H,{className:_e,pending:j.isFetching,pendingLabel:ge?"Opening":"Starting",onClick:async()=>{await i.startTaskNow(z.task.id),await L()},children:[e.jsx(ta,{className:"size-4 fill-current"}),ge?"Focus work":"Start work"]}),ge?e.jsxs(e.Fragment,{children:[e.jsx(H,{className:_e,variant:"secondary",pending:B.isPending,pendingLabel:"Pausing",onClick:async()=>{await B.mutateAsync({runId:ge.id,actor:ge.actor,note:ge.note})},children:"Pause"}),e.jsx(H,{className:_e,variant:"secondary",pending:$.isPending,pendingLabel:"Completing",onClick:async()=>{await $.mutateAsync({runId:ge.id,actor:ge.actor,note:ge.note})},children:"Complete"})]}):null,e.jsxs(H,{className:_e,variant:"secondary",onClick:()=>T(!0),children:[e.jsx(me.icon,{className:"size-4"}),"Change status"]}),e.jsxs(H,{className:_e,variant:"secondary",onClick:()=>h(!0),children:[e.jsx(Pi,{className:"size-4"}),"Edit ",ce.noun]}),e.jsxs(H,{className:_e,variant:"secondary",onClick:()=>p(!0),children:[e.jsx(Va,{className:"size-4"}),"Adjust work"]}),e.jsxs(H,{className:_e,variant:"secondary",pending:W.isPending,pendingLabel:"Planning",onClick:()=>x(!0),children:[e.jsx(bs,{className:"size-4"}),"Time Box"]}),z.task.status==="done"?e.jsx(H,{className:_e,variant:"secondary",onClick:async()=>{await Z.mutateAsync(z.task.id)},children:"Mark as not done"}):null,e.jsxs(H,{className:te(_e,"text-rose-200 hover:bg-rose-500/10"),variant:"ghost",pending:X.isPending,pendingLabel:t("common.taskDetail.deleting"),onClick:()=>void ie(),children:["Delete ",ce.noun]})]})})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:ce.label}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ce.descriptor}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:me.label}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.priority.${z.task.priority}`)}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.effort.${z.task.effort}`)}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.energy.${z.task.energy}`)}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:[z.task.points," xp"]}),z.task.time.totalCreditedSeconds>0?e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(z.task.time.totalCreditedSeconds/60)," min tracked"]}):null,ge?e.jsx(S,{className:"bg-emerald-500/12 text-emerald-200",children:"Timer active"}):null,z.task.executionMode?e.jsx(S,{className:z.task.executionMode==="afk"?"bg-emerald-500/12 text-emerald-100":"bg-amber-500/12 text-amber-100",children:z.task.executionMode.toUpperCase()}):null,Ie?e.jsx(S,{className:"bg-sky-500/12 text-sky-100",children:"AI brief ready"}):null,nt||K.length>0?e.jsx(S,{className:"bg-fuchsia-500/12 text-fuchsia-100",children:"Bot collaboration live"}):null,O?e.jsx(et,{to:`/calendar?timeboxId=${encodeURIComponent(O.id)}`,className:"inline-flex",children:e.jsxs(S,{className:"cursor-pointer bg-[var(--primary)]/16 text-[var(--primary)] transition hover:bg-[var(--primary)]/24",children:["Timeboxed · ",a(O.startsAt)]})}):null]}),N?null:e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Status"}),e.jsx("div",{className:"mt-3 grid gap-2 md:grid-cols-2 xl:grid-cols-5",children:Ao.map(ue=>{const $e=ue.icon,Xe=ue.status===z.task.status;return e.jsxs("button",{type:"button",disabled:Xe||Q.isPending,className:`rounded-[18px] border px-3.5 py-3 text-left transition ${Xe?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.08]"}`,onClick:()=>void Fe(ue.status),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"font-medium",children:ue.label})]}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/54",children:ue.description})]},ue.status)})})]}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsx($i,{eyebrow:"Hierarchy",title:"Context map",description:`See where this ${ce.noun} sits in the larger planning ladder without opening the board.`,children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx(Fs,{label:"Project",help:`The project is the main work stream this ${ce.noun} belongs to.`}),e.jsx("div",{className:"mt-2",children:z.project?e.jsx(et,{to:`/projects/${z.project.id}`,className:"inline-flex max-w-full",children:e.jsx(Qe,{kind:"project",label:z.project.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No project linked"})})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Goal",help:"The goal shows the longer-term result this work supports."}),e.jsx("div",{className:"mt-2",children:z.goal?e.jsx(et,{to:`/goals/${z.goal.id}`,className:"inline-flex max-w-full",children:e.jsx(Qe,{kind:"goal",label:z.goal.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No goal linked"})})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Parent item",help:"Issues parent tasks, tasks parent subtasks, and split child items stay legible here."}),e.jsx("div",{className:"mt-2",children:Ee?e.jsx(et,{to:`/tasks/${Ee.id}`,className:"inline-flex max-w-full",children:e.jsx(Qe,{kind:lu(Ee.level),label:Ee.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No parent work item"})})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Child items",help:"Child work items let you scan the next layer down without leaving the detail view."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Ce.length>0?Ce.map(ue=>e.jsx(et,{to:`/tasks/${ue.id}`,className:"inline-flex max-w-full",children:e.jsx(Qe,{kind:lu(ue.level),label:ue.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})},ue.id)):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No child work items"})})]})]})}),e.jsx($i,{eyebrow:"Execution",title:"Execution profile",description:"Surface the operating mode, AI posture, tags, and blockers as a single readable brief.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Bs,{label:"Work-item type",value:ce.descriptor,hint:se==="task"?"Tasks are meant to fit one focused AI session.":se==="issue"?"Issues hold the vertical slice and its delivery contract.":"Subtasks stay intentionally small and concrete."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{label:"Execution mode",value:z.task.executionMode?z.task.executionMode.toUpperCase():"Not set"}),e.jsx(Bs,{label:"AI posture",value:Ie?"AI brief ready":se==="issue"?"Issue narrative only":"Needs AI brief"})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Tags",help:"Tags shape filtering and fast scanning across the board and hierarchy views."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Pe.length>0?Pe.map(ue=>e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue.name},ue.id)):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No tags"})})]}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Blockers",help:"Blockers tie this work item to the entities that currently constrain it."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:U.length>0?U.map(ue=>{const $e=DL(ue.entityType,ue.entityId),Xe=e.jsx(S,{wrap:!0,className:"bg-amber-500/12 text-amber-100",children:ue.label??`${ue.entityType} · ${ue.entityId}`},`${ue.entityType}:${ue.entityId}`);return $e?e.jsx(et,{to:$e,className:"inline-flex max-w-full",children:Xe},`${ue.entityType}:${ue.entityId}`):Xe}):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No blockers linked"})})]})]})}),e.jsx($i,{eyebrow:"People and timing",title:"Accountability surface",description:"Show who owns the work, who is helping, and when the record moved.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Bs,{label:"Owner",value:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[z.task.user?e.jsx(ht,{user:z.task.user,compact:!0}):null,e.jsx("span",{children:z.task.owner}),nt?e.jsxs(S,{className:"bg-fuchsia-500/12 text-fuchsia-100",children:[e.jsx(Sa,{className:"mr-1 size-3.5"}),"Bot owner"]}):null]})}),e.jsxs("div",{children:[e.jsx(Fs,{label:"Assignees"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:z.task.assignees&&z.task.assignees.length>0?z.task.assignees.map(ue=>e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.05] px-3 py-1.5 text-sm text-white/72",children:[e.jsx(ht,{user:ue,compact:!0}),e.jsx("span",{children:ue.displayName}),ue.kind==="bot"?e.jsx(Sa,{className:"size-3.5 text-fuchsia-200"}):null]},ue.id)):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No assignees"})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{label:"Due date",value:s(z.task.dueDate),hint:`Use due dates only when timing materially matters for this ${ce.noun}.`}),e.jsx(Bs,{label:"Completed",value:z.task.completedAt?a(z.task.completedAt):"Not completed"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{label:"Created",value:a(z.task.createdAt)}),e.jsx(Bs,{label:"Updated",value:a(z.task.updatedAt)})]})]})})]}),Ie||M.length>0||Ne||he.length>0?e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1.05fr)_minmax(0,1fr)]",children:[e.jsx($i,{eyebrow:"Execution brief",title:"AI and delivery instructions",description:"The narrative, criteria, and execution intent live together so the detail view can stand on its own.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(Ut,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:"AI instructions"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/72",children:Ie?e.jsx(Ws,{markdown:we,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):`No AI instructions have been written for this ${ce.noun} yet.`})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(Sl,{className:"size-4 text-emerald-200"}),e.jsx("span",{children:"Acceptance criteria"})]}),M.length>0?e.jsx("div",{className:"mt-3 grid gap-2",children:M.map((ue,$e)=>e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/72",children:ue},`${z.task.id}-criterion-${$e}`))}):e.jsx("div",{className:"mt-3 rounded-[16px] border border-dashed border-white/10 px-4 py-3 text-sm text-white/52",children:"No acceptance criteria captured yet."})]})]})}),e.jsx($i,{eyebrow:"Evidence",title:"Work done, changed files, and git traceability",description:"Show the work summary, file footprint, and linked refs directly in the detail view.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(cm,{className:"size-4 text-sky-200"}),e.jsx("span",{children:"Work summary"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/72",children:Ne!=null&&Ne.workSummary?e.jsx(Ws,{markdown:Ne.workSummary,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):"No work summary yet."})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(Af,{className:"size-4 text-amber-200"}),e.jsx("span",{children:"Changed files"})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Ne!=null&&Ne.modifiedFiles&&Ne.modifiedFiles.length>0?Ne.modifiedFiles.map(ue=>e.jsx(S,{wrap:!0,className:"bg-white/[0.08] font-mono text-[11px] text-white/74",children:ue},ue)):e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No changed files listed"})})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/62",children:[e.jsx(Na,{className:"size-4 text-fuchsia-200"}),e.jsx("span",{children:"Git refs"})]}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[[Se,Je].filter(ue=>ue.length>0).map((ue,$e)=>e.jsxs("div",{className:"grid gap-2",children:[Se.length>0&&Je.length>0?e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:$e===0?"Linked in completion report":"Other recorded refs"}):null,ue.map(Xe=>{const Ge=RL[Xe.refType],re=e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(S,{className:Ge.className,children:Ge.label}),e.jsx("div",{className:"font-mono text-sm text-white/84",children:Xe.refValue})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Xe.displayTitle||Xe.repository||Xe.provider})]});return Xe.url?e.jsxs("a",{href:Xe.url,target:"_blank",rel:"noreferrer",className:"group block",children:[re,e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1 text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:["Open ref",e.jsx(Ks,{className:"size-3.5 transition group-hover:translate-x-0.5 group-hover:-translate-y-0.5"})]})]},Xe.id):e.jsx("div",{children:re},Xe.id)})]},`git-group-${$e}`)),he.length===0?e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:"No git refs recorded"}):null]})]})]})})]}):null,e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs($i,{eyebrow:"Work done",title:"Execution ledger",description:"Surface tracked work, credited work, and manual adjustments without opening the timer history.",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Bs,{label:"Tracked total",value:Di(z.task.time.totalTrackedSeconds)}),e.jsx(Bs,{label:"Credited total",value:Di(z.task.time.totalCreditedSeconds)}),e.jsx(Bs,{label:"Live work",value:Di(z.task.time.liveCreditedSeconds)}),e.jsx(Bs,{label:"Manual adjustments",value:Di(z.task.time.manualAdjustedSeconds)})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Today credited ",Di(z.task.time.todayCreditedSeconds??0)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Live tracked ",Di(z.task.time.liveTrackedSeconds)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Active runs ",z.task.time.activeRunCount]})]})]}),e.jsxs($i,{eyebrow:"Workflow health",title:"Signal scan",description:"A fast read on how ready this work item is for execution and closeout.",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{label:"Closeout readiness",value:Ne!=null&&Ne.workSummary||Se.length>0?"Evidence present":"Needs closeout evidence",hint:(xe=Ne==null?void 0:Ne.modifiedFiles)!=null&&xe.length?`${Ne.modifiedFiles.length} changed file${Ne.modifiedFiles.length===1?"":"s"} listed`:"No changed-file evidence captured yet."}),e.jsx(Bs,{label:"Collaboration model",value:nt||K.length>0?"Human + bot":z.task.assignees&&z.task.assignees.length>0?"Shared human work":"Single owner",hint:K.length>0?`${K.length} bot assignee${K.length===1?"":"s"} attached`:"No bot assignee attached."})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Priority ",t(`common.enums.priority.${z.task.priority}`)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Effort ",t(`common.enums.effort.${z.task.effort}`)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Energy ",t(`common.enums.energy.${z.task.energy}`)]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Duration ",Di(z.task.plannedDurationSeconds)]})]})]})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Action Point load"}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Total cost"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ke?Et(ke.totalCostAp):"Not calibrated"})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Today debit"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ke?Et(ke.spentTodayAp):"0 AP"})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Sustain rate"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ke?Xt(ke.sustainRateApPerHour):"0 AP/h"})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Expected duration"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ke?`${Math.round(ke.expectedDurationSeconds/3600)} h`:"No target"})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[(ye=z.task.splitSuggestion)!=null&&ye.shouldSplit?e.jsx(S,{className:"bg-amber-400/12 text-amber-100",children:"Split it"}):null,ke?e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Remaining ",Et(ke.remainingAp)]}):null,ke?e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Spent total ",Et(ke.spentTotalAp)]}):null,ke?e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ke.costBand}):null]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"This task only debits the Action Points you actually worked today. Marking it done does not consume the full estimate by itself."})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Today's Life Force context"}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Daily AP"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:v.data?`${Et(v.data.spentTodayAp)} / ${Et(v.data.dailyBudgetAp)}`:"Loading..."})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Instant headroom"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:v.data?Xt(v.data.instantFreeApPerHour):"Loading..."})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Forecast"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:v.data?`${Et(v.data.forecastAp)} / ${Et(v.data.dailyBudgetAp)}`:"Loading..."})]})]})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/58",children:[e.jsx("span",{children:"Current timer"}),e.jsx(Tt,{content:"This shows whether work is running on the task right now and how much time has been credited.",label:"Explain current timer"})]}),e.jsx("div",{className:"mt-3 text-white",children:ge?`${ge.timerMode==="planned"?"Planned":"Unlimited"} timer active with ${Math.floor(ge.creditedSeconds/60)} credited minutes.`:"No timer is running on this task right now."})]}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Task scheduling"}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Rule source"}),e.jsx("div",{className:"mt-2 text-white",children:z.task.schedulingRules?"Task-specific override":"Uses project defaults"})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Fs,{label:"Planned duration"}),e.jsx("div",{className:"mt-2 text-white",children:z.task.plannedDurationSeconds?`${Math.round(z.task.plannedDurationSeconds/60)} min`:"No duration target"})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/58",children:"Scheduling rules now live behind the guided modal flow instead of an inline editor. Use it to change eligible blocks, blocked contexts, and the planning duration without overcrowding the task page."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(H,{onClick:()=>b(!0),children:[e.jsx(bs,{className:"size-4"}),"Edit task scheduling"]}),e.jsx(et,{to:"/calendar",children:e.jsx(H,{variant:"secondary",children:"Open calendar workspace"})})]})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar status"}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(S,{className:_.tone==="blocked"?"bg-rose-500/14 text-rose-100":_.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:_.label}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:z.task.schedulingRules?"Task override":"Using project defaults"}),z.task.plannedDurationSeconds?e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:[Math.round(z.task.plannedDurationSeconds/60)," min target"]}):null]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"Forge checks these rules before a live run starts. If the current calendar context is blocked, you can still override with an explicit reason."}),_.context.length>0?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Current context"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:_.context.map(ue=>e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue},ue))})]}):null,_.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:_.conflicts.map(ue=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:ue},ue))}):null,e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:e.jsxs(H,{pending:W.isPending||q.isPending,pendingLabel:"Planning",onClick:()=>{y(null),x(!0)},children:[e.jsx(bs,{className:"size-4"}),"Time Box"]})})]})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Scheduled blocks"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:"Open a scheduled block to edit the day, the hour range, or the AP profile tied to this task."})]}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:F.length})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[F.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.03] px-4 py-4 text-sm text-white/55",children:"No future timeboxes are attached to this task yet."}):null,F.map(ue=>e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{y(ue),x(!0)},onKeyDown:$e=>{($e.key==="Enter"||$e.key===" ")&&($e.preventDefault(),y(ue),x(!0))},className:"rounded-[18px] border border-white/8 bg-[linear-gradient(180deg,rgba(26,32,49,0.86),rgba(16,21,34,0.86))] p-4 text-left transition hover:bg-[linear-gradient(180deg,rgba(30,36,54,0.92),rgba(18,23,37,0.92))]",children:[e.jsx("div",{className:"flex flex-wrap items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-2 font-medium leading-6 text-white",children:ue.title}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-sm text-white/58",children:[e.jsx(Va,{className:"size-3.5 shrink-0"}),a(ue.startsAt)," to ",a(ue.endsAt)]})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue.source}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue.status}),e.jsx(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:Xt(on(ue).rateApPerHour)}),e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:Et(on(ue).totalAp)}),ue.overrideReason?e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:ue.overrideReason}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx("span",{className:"rounded-[999px] bg-white/[0.08] px-3 py-1 text-xs text-white/72",children:"Edit in guide"}),e.jsx(et,{to:`/calendar?timeboxId=${encodeURIComponent(ue.id)}`,onClick:$e=>$e.stopPropagation(),className:"rounded-[999px] bg-white/[0.08] px-3 py-1 text-xs text-white/72 transition hover:bg-white/[0.12]",children:"Open in calendar"})]})]},ue.id))]})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Gd,{entityType:"task",entityId:z.task.id,title:`${ce.label} notes`,description:`Capture real progress, blockers, and context in Markdown so the ${ce.noun} keeps a durable work log.`,invalidateQueryKeys:[["task-context",n.taskId],...z.task.projectId?[["project-board",z.task.projectId]]:[]]})}),e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Activity"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[z.activity.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/55",children:"No activity has been recorded for this task yet."}):null,z.activity.map(ue=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:Vd(ue)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:Xd(ue)}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:a(ue.createdAt)})]}),e.jsx(H,{variant:"ghost",className:"shrink-0",onClick:async()=>{await V.mutateAsync(ue.id)},children:"Remove"})]}),Za(ue)&&bl(ue)?e.jsx(et,{to:Za(ue),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:bl(ue)}):null]},ue.id))]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Timer sessions"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[z.taskRuns.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/55",children:"No timer sessions have been recorded for this task yet."}):null,z.taskRuns.map(ue=>{var $e,Xe,Ge,re,Ae;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:ue.actor}),e.jsx(S,{children:ae(ue.status)})]}),($e=ue.gitContext)!=null&&$e.branch||(Xe=ue.gitContext)!=null&&Xe.pullRequestNumber?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[(Ge=ue.gitContext)!=null&&Ge.branch?e.jsxs(S,{className:"bg-sky-500/12 text-sky-100",children:[e.jsx(Na,{className:"mr-1 size-3"}),ue.gitContext.branch]}):null,(re=ue.gitContext)!=null&&re.pullRequestNumber?e.jsxs(S,{className:"bg-fuchsia-500/12 text-fuchsia-100",children:[e.jsx(ul,{className:"mr-1 size-3"}),"PR #",ue.gitContext.pullRequestNumber]}):null,(Ae=ue.gitContext)!=null&&Ae.repository?e.jsx(S,{className:"bg-white/[0.08] text-white/68",children:ue.gitContext.repository}):null]}):null,e.jsx("div",{className:"mt-2 text-sm text-white/58",children:ue.note||t("common.labels.noRunNote")}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:a(ue.updatedAt)})]},ue.id)})]})]})]}),e.jsx(Bd,{open:m,goals:i.snapshot.goals,projects:i.snapshot.dashboard.projects,workItems:i.snapshot.workItems,tags:i.snapshot.tags,users:i.snapshot.users,editingTask:z.task,defaultUserId:z.task.userId??d,onRefreshEntities:i.refresh,currentCreditedSeconds:z.task.time.totalCreditedSeconds,onOpenChange:h,onAdjustTrackedTime:async ue=>{await E.mutateAsync(ue)},onSubmit:async(ue,$e)=>{$e&&await Q.mutateAsync({taskId:$e,patch:ue})}}),e.jsx(Qw,{open:c,onOpenChange:p,entityType:"task",entityId:z.task.id,targetLabel:z.task.title,currentCreditedSeconds:z.task.time.totalCreditedSeconds,pending:E.isPending,onSubmit:async ue=>{await E.mutateAsync(ue)}}),e.jsx(ew,{open:g,onOpenChange:ue=>{x(ue),ue||y(null)},tasks:[z.task],initialTaskId:z.task.id,lockedTaskId:z.task.id,editingTimebox:I,from:P.from,to:P.to,userIds:r,onCreateTimebox:async ue=>{await W.mutateAsync({...ue,userId:d??void 0})},onUpdateTimebox:async(ue,$e)=>{await q.mutateAsync({timeboxId:ue,patch:{...$e,userId:d??void 0}})},onDeleteTimebox:async ue=>{await G.mutateAsync(ue)}}),e.jsx(Jy,{open:f,onOpenChange:b,tasks:[z.task],onSave:async({taskId:ue,schedulingRules:$e,plannedDurationSeconds:Xe})=>{await Q.mutateAsync({taskId:ue,patch:{schedulingRules:$e,plannedDurationSeconds:Xe}}),await o.invalidateQueries({queryKey:["task-calendar-overview",n.taskId]})}}),e.jsx(Pa,{open:A,onOpenChange:T,eyebrow:`${ce.label} status`,title:"Change status",description:`Pick the state that best matches where this ${ce.noun} is right now.`,children:e.jsx("div",{className:"grid gap-3",children:Ao.map(ue=>{const $e=ue.icon,Xe=ue.status===z.task.status;return e.jsx("button",{type:"button",disabled:Xe||Q.isPending,className:`rounded-[22px] border px-4 py-4 text-left transition ${Xe?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.08]"}`,onClick:()=>void Fe(ue.status),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($e,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ue.label}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:ue.description})]})]})},ue.status)})})})]})}function Jg(t,s,a){var i;return((i=s.find(r=>r.id===t.goalId))==null?void 0:i.title)??a}function OL(t,s){return t.tagIds.map(a=>s.find(i=>i.id===a)).filter(Boolean)}function zL(t,s){(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),s())}function KL(t,s){switch(t.status){case"backlog":return{label:s.backlog,action:"start",icon:ta};case"focus":return{label:s.focus,action:"start",icon:ta};case"in_progress":return{label:s.in_progress,nextStatus:"done",action:"move",icon:ml};case"blocked":return{label:s.blocked,action:"start",icon:ta};default:return null}}function qL({tasks:t,timeline:s,goals:a,tags:i,notesSummaryByEntity:r,selectedTaskId:n,onSelectTask:l,onMove:o,onStartTask:d}){const{t:m,formatDate:h}=Gt(),c={backlog:m("common.dailyRunway.actionBacklog"),focus:m("common.dailyRunway.actionFocus"),in_progress:m("common.dailyRunway.actionProgress"),blocked:m("common.dailyRunway.actionBlocked")};return e.jsxs("div",{className:"grid min-w-0 gap-4 2xl:grid-cols-[minmax(0,1.3fr)_minmax(17rem,0.9fr)]",children:[e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:m("common.dailyRunway.runwayEyebrow")}),e.jsx(Tt,{content:"These are the tasks that matter most for today. Click a card to open the task details. Use Start to begin work immediately."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-white",children:m("common.dailyRunway.runwayTitle")})]}),e.jsx(S,{className:"shrink-0 text-[var(--primary)]",children:m(t.length===1?"common.dailyRunway.prioritiesOne":"common.dailyRunway.prioritiesOther",{count:t.length})})]}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:t.map((p,g)=>{const x=KL(p,c),f=OL(p,i).slice(0,2),b=n===p.id,A=la(r,"task",p.id).count;return e.jsxs("article",{role:"button",tabIndex:0,"aria-pressed":b,className:`grid w-full gap-3 rounded-[22px] px-4 py-4 text-left transition ${b?"bg-[linear-gradient(180deg,rgba(192,193,255,0.16),rgba(192,193,255,0.05))] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"bg-white/[0.03] hover:bg-white/[0.06]"}`,onClick:()=>l(p.id),onKeyDown:T=>zL(T,()=>l(p.id)),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:m("common.dailyRunway.runwayItem",{index:g+1})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(Qe,{kind:"goal",label:Jg(p,a,m("common.dailyRunway.unassigned")),compact:!0,gradient:!1}),p.time.activeRunCount>0?e.jsx(S,{className:"bg-emerald-500/12 text-emerald-200",children:"Live"}):null]}),e.jsx("div",{className:"mt-2",children:e.jsx(It,{kind:"task",label:p.title,variant:"heading",size:"md"})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:p.description||m("common.dailyRunway.noNote")})]}),e.jsx(S,{className:"shrink-0 self-start",children:p.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(S,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[p.points," xp"]}),e.jsx(Vs,{entityType:"task",entityId:p.id,count:A}),p.time.totalCreditedSeconds>0?e.jsxs(S,{className:"bg-white/[0.08] text-white/70",children:[Math.floor(p.time.totalCreditedSeconds/60)," min tracked"]}):null,e.jsx(S,{className:"bg-white/[0.08] text-white/70",children:p.effort}),e.jsx(S,{className:"bg-white/[0.08] text-white/70",children:h(p.dueDate)}),f.map(T=>e.jsx(S,{className:"bg-white/[0.08]",style:{color:T.color},children:T.name},T.id))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:p.owner}),x?e.jsxs(H,{variant:x.action==="start"?"primary":"secondary",className:"px-3 py-2 text-[11px] uppercase tracking-[0.16em]",onClick:async T=>{if(T.stopPropagation(),x.action==="start"){await d(p.id);return}x.nextStatus&&await o(p.id,x.nextStatus)},children:[e.jsx(x.icon,{className:"mr-2 size-3.5"}),x.label]}):null]})]},p.id)})})]}),e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:m("common.dailyRunway.timelineEyebrow")}),e.jsx(Tt,{content:"This groups today's tasks by status, so you can see what is already moving, what is ready to start, what is blocked, and what is done."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-white",children:m("common.dailyRunway.timelineTitle")}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:s.map(p=>e.jsxs("div",{className:"min-w-0 overflow-hidden rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:p.label}),e.jsx(S,{className:"bg-white/[0.08] text-white/65",children:p.tasks.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[p.tasks.slice(0,3).map(g=>e.jsxs("button",{type:"button",className:"flex min-w-0 items-center justify-between gap-3 overflow-hidden rounded-[16px] bg-white/[0.03] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>l(g.id),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(It,{kind:"task",label:g.title,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("div",{className:"mt-2",children:e.jsx(Qe,{kind:"goal",label:Jg(g,a,m("common.dailyRunway.unassigned")),compact:!0,gradient:!1})})]}),e.jsx(Ca,{className:"size-4 shrink-0 text-white/35"})]},g.id)),p.tasks.length===0?e.jsx("div",{className:"text-sm text-white/42",children:m("common.dailyRunway.emptyBucket")}):null]})]},p.id))})]})]})}const BL=5;function UL(){const t=new Date;t.setHours(0,0,0,0);const s=new Date(t);return s.setDate(s.getDate()+1),{start:t,end:s,from:t.toISOString(),to:s.toISOString()}}function WL(t,s){const a=new Date(t.startAt),i=new Date(t.endAt);return a<s.end&&i>s.start}function HL(t){if(t.isAllDay)return"All day";const s=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});return`${s.format(new Date(t.startAt))} - ${s.format(new Date(t.endAt))}`}function GL(){var x;const{t}=Gt(),s=Ct(),a=Ht(),i=u.useMemo(()=>UL(),[]),r=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],n=Me({queryKey:["forge-calendar-overview",i.from,i.to,...r],queryFn:()=>nn({from:i.from,to:i.to,userIds:r})}),l=s.snapshot.today.directive.task,o=s.snapshot.today.milestoneRewards.find(f=>!f.completed)??s.snapshot.today.milestoneRewards[0]??null,d=s.snapshot.risk.blockedTasks[0]??s.snapshot.risk.overdueTasks[0]??null,m=Math.max(0,s.snapshot.metrics.nextLevelXp-s.snapshot.metrics.currentLevelXp),h=u.useMemo(()=>{var f;return(((f=n.data)==null?void 0:f.calendar.events)??[]).filter(b=>!b.deletedAt&&b.status!=="cancelled"&&WL(b,i)).sort((b,A)=>new Date(b.startAt).getTime()-new Date(A.startAt).getTime())},[(x=n.data)==null?void 0:x.calendar.events,i]),c=h.slice(0,BL);if(!(s.snapshot.lifeForce!==void 0||l!==null||s.snapshot.overview.topTasks.length>0||s.snapshot.today.dueHabits.length>0||s.snapshot.today.dailyQuests.length>0||s.snapshot.today.milestoneRewards.length>0||h.length>0)&&!n.isLoading)return e.jsxs("div",{className:"grid gap-4",children:[e.jsx(mt,{title:"Today",titleText:"Today",description:"Start a task, earn XP, and keep today's work clear.",badge:`${s.snapshot.metrics.weeklyXp} weekly xp`}),e.jsx(rs,{eyebrow:t("common.todayPage.heroEyebrow"),title:t("common.todayPage.emptyTitle"),description:t("common.todayPage.emptyDescription"),action:e.jsx(et,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium whitespace-nowrap text-slate-950 transition hover:opacity-90",children:t("common.todayPage.emptyAction")})})]});const g=[{id:"hero",title:"Today",description:"Compact page header.",defaultWidth:12,defaultHeight:2,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(Oy,{children:e.jsx(mt,{title:"Today",titleText:"Today",description:(l==null?void 0:l.description)??"Start one real task, collect XP, and keep today's work moving.",badge:`${s.snapshot.metrics.weeklyXp} weekly xp`})})},{id:"life-force",title:"Life Force",description:"Instant headroom, AP use today, and tiredness signals.",defaultWidth:12,defaultHeight:3,minWidth:5,render:()=>e.jsx(sT,{selectedUserIds:s.selectedUserIds,fallbackLifeForce:s.snapshot.lifeForce,onRefresh:s.refresh})},{id:"metrics",title:"Live metrics",description:"XP, level, and momentum stay visible but lighter than before.",defaultWidth:5,defaultHeight:4,minWidth:4,render:({compact:f})=>e.jsx(zy,{children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs(le,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Weekly XP"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-[var(--primary)]",children:s.snapshot.metrics.weeklyXp}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[s.snapshot.metrics.totalXp," total XP"]})]}),e.jsxs(le,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Level"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:s.snapshot.metrics.level}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[m," xp to the next level"]}),f?null:e.jsx("div",{className:"mt-3",children:e.jsx(Gs,{value:s.snapshot.metrics.currentLevelXp/s.snapshot.metrics.nextLevelXp*100,tone:"tertiary"})})]}),e.jsxs(le,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Momentum"}),e.jsxs("div",{className:"mt-2 font-display text-4xl text-white",children:[s.snapshot.metrics.momentumScore,"%"]}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[s.snapshot.metrics.streakDays," day streak"]})]}),e.jsxs(le,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Next reward"}),e.jsx("div",{className:"mt-2 text-base font-semibold text-white",children:(o==null?void 0:o.title)??"Keep showing up"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:(o==null?void 0:o.progressLabel)??"The next visible win comes from a task completion or aligned habit check-in."})]})]})})},{id:"runway",title:"Runway",description:"The execution lane itself can be widened or narrowed.",defaultWidth:7,defaultHeight:6,minWidth:5,render:()=>e.jsx(Ky,{children:e.jsx(qL,{tasks:s.snapshot.overview.topTasks,timeline:s.snapshot.today.timeline,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:(l==null?void 0:l.id)??null,onSelectTask:f=>a(`/tasks/${f}`),onStartTask:async f=>{await s.startTaskNow(f)},onMove:async(f,b)=>{await s.patchTaskStatus(f,b)}})})},{id:"calendar",title:"Calendar",description:"Today's events stay grouped with their results instead of splitting search from outcome.",defaultWidth:5,defaultHeight:5,minWidth:4,render:({compact:f})=>e.jsx(qy,{children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"inline-flex size-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--primary)]/14 text-[var(--primary)]",children:e.jsx(bs,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Today's calendar"}),e.jsx("div",{className:"text-sm font-semibold text-white",children:new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(i.start)}),e.jsxs("div",{className:"text-sm text-white/58",children:[h.length," event",h.length===1?"":"s"]})]})]}),e.jsxs(et,{to:"/calendar",className:"inline-flex shrink-0 items-center gap-2 rounded-full bg-white/[0.06] px-3 py-2 text-xs font-medium text-white/72 transition hover:bg-white/[0.1] hover:text-white",children:["Open calendar",e.jsx(wm,{className:"size-3.5"})]})]}),h.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:"Nothing is scheduled yet for today."}):c.map(b=>e.jsxs("button",{type:"button",className:"grid min-w-0 gap-2 rounded-[18px] bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>a("/calendar"),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:b.title}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:HL(b)})]}),e.jsx(S,{className:"shrink-0 bg-white/[0.08] text-white/72",children:b.originType==="native"?"Forge":b.originType})]}),!f&&b.description?e.jsx("div",{className:"line-clamp-2 text-sm leading-6 text-white/52",children:b.description}):null]},b.id))]})})},{id:"focus",title:"Current focus",description:"Current task, comeback task, and due habits stay in one movable stack.",defaultWidth:12,defaultHeight:4,minWidth:6,render:({compact:f})=>{var b;return e.jsx(By,{children:e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Current task"}),l?e.jsx(Vs,{entityType:"task",entityId:l.id,count:((b=s.snapshot.dashboard.notesSummaryByEntity[`task:${l.id}`])==null?void 0:b.count)??0}):null]}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:(l==null?void 0:l.title)??"Pick a task from the runway"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(l==null?void 0:l.description)??"Once a task is active, the timer rail and this panel stay aligned."}),l?e.jsx("button",{type:"button",className:"mt-4 inline-flex min-h-10 items-center justify-center rounded-2xl bg-[rgba(192,193,255,0.16)] px-3.5 py-2 text-sm font-medium text-[var(--primary)] transition hover:bg-[rgba(192,193,255,0.24)]",onClick:async()=>{await s.startTaskNow(l.id)},children:"Start work"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Recovery task"}),e.jsx("div",{className:"mt-3 text-sm font-semibold text-white",children:(d==null?void 0:d.title)??"No blocked or overdue task is dominating today"}),f?null:e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:(d==null?void 0:d.description)??"If something slips, it will surface here as the clean comeback move."})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Due habits"}),e.jsx("div",{className:"mt-3 grid gap-2",children:s.snapshot.today.dueHabits.slice(0,f?2:3).map(A=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:A.title}),f?null:e.jsx("div",{className:"text-sm text-white/52",children:A.frequency})]}),e.jsxs(S,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[A.rewardXp," xp"]})]},A.id))})]})]})]})})}},{id:"time",title:"Clock",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:f})=>e.jsx(Ol,{compact:f})},{id:"weather",title:"Weather",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:f})=>e.jsx(ql,{compact:f})},{id:"mini-calendar",title:"Mini calendar",description:"Optional utility widget.",defaultWidth:4,defaultHeight:3,defaultHidden:!0,render:({compact:f})=>e.jsx(zl,{compact:f})},{id:"spotify",title:"Spotify",description:"Optional utility widget.",defaultWidth:4,defaultHeight:2,defaultHidden:!0,render:()=>e.jsx(Kl,{surfaceId:"today"})},{id:"quick-capture",title:"Quick capture",description:"Save a note or wiki draft without leaving Today.",defaultWidth:5,defaultHeight:3,defaultHidden:!0,render:({compact:f})=>{var b;return e.jsx(Bl,{compact:f,defaultUserId:s.selectedUserIds[0]??((b=s.snapshot.users[0])==null?void 0:b.id)??null})}}];return e.jsx(Zd,{surfaceId:"today",baseWidgets:g})}const QL=["restingHeartRate","heartRateVariabilitySDNN","vo2Max","oxygenSaturation","bodyMass","stepCount"];function am(t){return t?new Date(`${t}T12:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}):"No date yet"}function Zg(t,s){return s==="cumulative"?t.total??t.latest??t.maximum??t.average:t.latest??t.average??t.maximum??t.minimum}function hi(t,s){if(s==null)return"No reading";const a=t.unit==="steps"||t.unit==="flights"||t.unit==="kcal"||t.unit==="min"?0:(t.unit==="%",1);return`${s.toLocaleString(void 0,{maximumFractionDigits:a,minimumFractionDigits:a===0||s>=100?0:1})} ${t.unit}`}function Ov(t){return t.deltaValue==null?"No baseline yet":`${t.deltaValue>0?"+":""}${hi(t,t.deltaValue)}`}function VL(t){return t.deltaValue==null||t.deltaValue===0?"steady":t.deltaValue>0?"up":"down"}function rl(t){switch(t){case"recovery":return{ring:"border-[rgba(255,122,167,0.18)]",badge:"bg-[rgba(255,122,167,0.16)] text-[rgb(255,179,205)]",glow:"from-[rgba(255,122,167,0.2)] via-[rgba(109,76,255,0.06)] to-transparent"};case"cardio":return{ring:"border-[rgba(109,173,255,0.22)]",badge:"bg-[rgba(109,173,255,0.16)] text-[rgb(186,220,255)]",glow:"from-[rgba(109,173,255,0.22)] via-[rgba(64,108,255,0.08)] to-transparent"};case"breathing":return{ring:"border-[rgba(111,232,195,0.2)]",badge:"bg-[rgba(111,232,195,0.15)] text-[rgb(195,255,237)]",glow:"from-[rgba(111,232,195,0.2)] via-[rgba(29,154,123,0.08)] to-transparent"};case"composition":return{ring:"border-[rgba(247,211,110,0.18)]",badge:"bg-[rgba(247,211,110,0.15)] text-[rgb(255,235,176)]",glow:"from-[rgba(247,211,110,0.18)] via-[rgba(184,128,24,0.08)] to-transparent"};case"temperature":return{ring:"border-[rgba(255,153,102,0.18)]",badge:"bg-[rgba(255,153,102,0.16)] text-[rgb(255,214,190)]",glow:"from-[rgba(255,153,102,0.2)] via-[rgba(255,91,46,0.06)] to-transparent"};default:return{ring:"border-[rgba(163,174,208,0.16)]",badge:"bg-[rgba(163,174,208,0.14)] text-[rgb(220,228,255)]",glow:"from-[rgba(163,174,208,0.14)] via-[rgba(112,120,167,0.06)] to-transparent"}}}function zv(t){switch(t){case"restingHeartRate":case"walkingHeartRateAverage":case"heartRateRecoveryOneMinute":return cu;case"heartRateVariabilitySDNN":case"vo2Max":return Ut;case"oxygenSaturation":case"respiratoryRate":return Mj;case"bodyMass":case"bodyFatPercentage":case"leanBodyMass":return Aj;case"stepCount":case"flightsClimbed":case"appleExerciseTime":return Pj;case"basalEnergyBurned":return nl;default:return Cd}}function XL({metric:t,className:s}){const a=t.days.slice(-14).map(o=>Zg(o,t.aggregation)).filter(o=>o!=null);if(a.length===0)return e.jsx("div",{className:te("flex h-16 items-center justify-center rounded-[18px] border border-dashed border-white/8 bg-white/[0.025] text-xs text-white/36",s),children:"Waiting for daily points"});const i=Math.min(...a),r=Math.max(...a),n=Math.max(r-i,1),l=t.days.slice(-14);return e.jsx("div",{className:te("flex h-16 items-end gap-1 rounded-[18px] border border-white/8 bg-white/[0.025] px-3 py-2",s),children:l.map((o,d)=>{const m=Zg(o,t.aggregation),h=m==null?12:18+Math.round((m-i)/n*34),c=d===l.length-1;return e.jsx("div",{className:"flex min-w-0 flex-1 flex-col items-center justify-end gap-1",children:e.jsx("div",{className:te("w-full rounded-full bg-gradient-to-t from-white/28 to-white/60 transition",c&&"from-[var(--primary)] to-[rgba(171,232,255,0.9)]"),style:{height:h},title:`${o.dateKey}: ${m==null?"No reading":hi(t,m)}`})},`${t.metric}-${o.dateKey}`)})})}function Mo({title:t,description:s,metric:a}){const i=a?zv(a.metric):Cd,r=rl(a?a.category:"default"),n=a?VL(a):"steady";return e.jsxs(le,{className:te("relative overflow-hidden rounded-[28px] border bg-[rgba(12,18,36,0.82)] p-5 shadow-[0_18px_60px_rgba(4,8,18,0.3)]",r.ring),children:[e.jsx("div",{className:te("pointer-events-none absolute inset-0 bg-gradient-to-br opacity-90",r.glow)}),e.jsxs("div",{className:"relative grid gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:t}),e.jsx("div",{className:"text-sm leading-6 text-white/56",children:s})]}),e.jsx("div",{className:"rounded-[18px] border border-white/10 bg-white/[0.05] p-3 text-white/80",children:e.jsx(i,{className:"size-5"})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xl font-semibold text-white",children:a?hi(a,a.latestValue):"No signal yet"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-white/56",children:[a?e.jsx(S,{className:r.badge,children:a.label}):null,a?e.jsx(S,{className:te("border-none",n==="up"?"bg-[rgba(111,232,195,0.14)] text-[rgb(190,255,231)]":n==="down"?"bg-[rgba(255,122,167,0.14)] text-[rgb(255,193,215)]":"bg-white/[0.08] text-white/72"),children:Ov(a)}):null,a?e.jsxs(S,{tone:"meta",children:[a.coverageDays," days tracked"]}):null]}),e.jsx("div",{className:"text-xs text-white/48",children:a?`Latest reading on ${am(a.latestDateKey)}`:"Forge will populate this card as soon as HealthKit has recent readings."})]})]})]})}function YL(){const t=Ct(),s=Me({queryKey:["forge-vitals-view",...t.selectedUserIds],queryFn:async()=>(await fb(t.selectedUserIds)).vitals});if(s.isLoading)return e.jsx(zt,{title:"Loading body signals",description:"Reading recent HealthKit body metrics, recovery signals, and daily aggregates."});if(s.isError||!s.data)return e.jsx(ct,{error:s.error??new Error("Vitals data unavailable"),onRetry:()=>void s.refetch()});const a=s.data,i=QL.map(l=>a.metrics.find(o=>o.metric===l)??null),r=a.summary.categoryBreakdown,n=r.map(l=>({...l,metrics:a.metrics.filter(o=>o.category===l.category)}));return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1380px] gap-5",children:[e.jsx(mt,{title:"Vitals",description:"Forge now keeps a daily body-signals layer across recovery, cardio fitness, breathing, composition, temperature, and activity. Use this surface to spot drift early, not just admire numbers late.",badge:`${a.summary.metricCount} live metrics`}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[e.jsx(Mo,{title:"Recovery pulse",description:"Resting heart rate and HRV are the fastest read on load, stress, and whether today needs a gentler edge.",metric:i[0]??i[1]}),e.jsx(Mo,{title:"Cardio engine",description:"VO2 max and walking heart rate show whether baseline fitness is improving or whether your effort is costing more than usual.",metric:i[2]}),e.jsx(Mo,{title:"Breath and oxygen",description:"Respiratory rate and oxygen saturation help catch nights or stretches where recovery quality starts to slip.",metric:i[3]}),e.jsx(Mo,{title:"Body composition",description:"Mass and composition stay close to the daily story so progress is visible without flattening everything into weight alone.",metric:i[4]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(340px,0.9fr)]",children:[e.jsxs(le,{className:"overflow-hidden rounded-[30px] border-white/8 bg-[radial-gradient(circle_at_top_left,rgba(108,99,255,0.16),transparent_36%),linear-gradient(180deg,rgba(15,19,38,0.98),rgba(9,13,28,0.98))] p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Coverage"}),e.jsxs("div",{className:"text-2xl font-semibold text-white",children:[a.summary.trackedDays," tracked days across ",a.summary.metricCount," metrics"]}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/58",children:"The companion is compressing HealthKit into daily signal bands, so what you see here is designed for decisions: how your recovery is trending, where your physiology is changing, and which body systems are actually being observed consistently."})]}),e.jsxs(S,{className:"bg-white/[0.08] text-white/72",children:["Latest snapshot ",am(a.summary.latestDateKey)]})]}),e.jsx("div",{className:"mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:r.map(l=>{const o=rl(l.category);return e.jsxs("div",{className:te("rounded-[22px] border bg-white/[0.03] p-4",o.ring),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(S,{className:o.badge,children:l.category}),e.jsxs("div",{className:"text-xs text-white/44",children:[l.coverageDays," days"]})]}),e.jsx("div",{className:"mt-3 text-2xl font-semibold text-white",children:l.metricCount}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:["active metric",l.metricCount===1?"":"s"]})]},l.category)})})]}),e.jsx(le,{className:"rounded-[30px] border-white/8 bg-[linear-gradient(180deg,rgba(13,19,37,0.96),rgba(10,14,30,0.96))] p-6",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Daily interpretation"}),e.jsx("div",{className:"text-lg font-semibold text-white",children:"Body signals should feel operational, not medical-chart dead."}),e.jsxs("div",{className:"grid gap-3 text-sm leading-6 text-white/58",children:[e.jsx("div",{children:"Lower resting heart rate paired with stable or rising HRV usually means recovery is holding."}),e.jsx("div",{children:"Rising walking heart rate, falling HRV, or a jump in respiratory rate usually means you are carrying more load than the calendar admits."}),e.jsx("div",{children:"Composition and temperature metrics move slower, but they make the fast signals easier to trust because you can see the surrounding body context."})]}),e.jsxs("div",{className:"mt-2 rounded-[22px] border border-white/8 bg-white/[0.035] p-4 text-sm text-white/70",children:[a.summary.latestMetricCount," metrics updated on the latest tracked day."]})]})})]}),e.jsx("section",{className:"grid gap-5",children:n.map(l=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:l.category}),e.jsxs("div",{className:"mt-1 text-2xl font-semibold text-white",children:[l.metrics.length," signals in this lane"]})]}),e.jsxs(S,{className:rl(l.category).badge,children:[l.coverageDays," days of coverage"]})]}),e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:l.metrics.map(o=>{const d=zv(o.metric),m=rl(o.category),h=o.days.at(-1);return e.jsxs(le,{className:te("overflow-hidden rounded-[28px] border bg-[linear-gradient(180deg,rgba(12,18,36,0.94),rgba(8,12,24,0.98))] p-5",m.ring),children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-[18px] border border-white/10 bg-white/[0.04] p-3 text-white/84",children:e.jsx(d,{className:"size-5"})}),e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:o.category}),e.jsx("div",{className:"text-xl font-semibold text-white",children:o.label}),e.jsxs("div",{className:"text-sm text-white/52",children:[o.coverageDays," tracked day",o.coverageDays===1?"":"s"]})]})]}),e.jsx(S,{className:m.badge,children:o.aggregation})]}),e.jsxs("div",{className:"mt-5 grid gap-4 md:grid-cols-[minmax(0,0.95fr)_minmax(220px,1.05fr)]",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Latest"}),e.jsx("div",{className:"mt-1 text-3xl font-semibold text-white",children:hi(o,o.latestValue)}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:o.latestDateKey?`Latest reading on ${am(o.latestDateKey)}`:"Waiting for the first successful reading"})]}),e.jsxs("div",{className:"grid gap-2 rounded-[22px] border border-white/8 bg-white/[0.03] p-4 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Baseline"}),e.jsx("span",{className:"font-medium text-white",children:hi(o,o.baselineValue)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Delta"}),e.jsx("span",{className:te("font-medium",o.deltaValue==null?"text-white/58":o.deltaValue>0?"text-[rgb(190,255,231)]":o.deltaValue<0?"text-[rgb(255,198,219)]":"text-white"),children:Ov(o)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Latest samples"}),e.jsx("span",{className:"font-medium text-white",children:(h==null?void 0:h.sampleCount)??0})]})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx(XL,{metric:o}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-white/48",children:[e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.025] px-3 py-2",children:[e.jsx("div",{children:"Min"}),e.jsx("div",{className:"mt-1 font-medium text-white/78",children:hi(o,(h==null?void 0:h.minimum)??null)})]}),e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.025] px-3 py-2",children:[e.jsx("div",{children:"Average"}),e.jsx("div",{className:"mt-1 font-medium text-white/78",children:hi(o,(h==null?void 0:h.average)??null)})]}),e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.025] px-3 py-2",children:[e.jsx("div",{children:"Max"}),e.jsx("div",{className:"mt-1 font-medium text-white/78",children:hi(o,(h==null?void 0:h.maximum)??null)})]})]})]})]})]},o.metric)})})]},l.category))})]})}function JL(t){const s=[];let a,i;for(const r of t){const n=r.trim();if(!n)continue;const l=n.indexOf(":");if(l<=0){s.push({label:"Note",value:n});continue}const o=n.slice(0,l).trim(),d=n.slice(l+1).trim();if(!d)continue;const m=o.toLowerCase();if(m==="title"){a=d;continue}if(m==="summary"){i=d;continue}s.push({label:o,value:d})}return{title:a,summary:i,rows:s}}function ZL(t){const s=[],a=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let i=0,r=null;for(;(r=a.exec(t))!==null;){if(r.index>i&&s.push({type:"text",value:t.slice(i,r.index)}),r[1]&&r[2]){const n=r[2].trim(),l=r[1].startsWith("!"),o=n.indexOf("|"),d=o>=0?n.slice(0,o).trim():n,m=o>=0?n.slice(o+1).trim():d;if(d.toLowerCase().startsWith("forge:")){const[,h,...c]=d.split(":");s.push({type:"forge-link",entityType:h??"",entityId:c.join(":").trim(),label:m})}else s.push({type:"wiki-link",target:d,label:m,embed:l})}else r[3]&&r[4]?s.push({type:"link",label:r[3],href:r[4].trim()}):r[5]?s.push({type:"code",value:r[5]}):r[6]?s.push({type:"strong",value:r[6]}):r[7]&&s.push({type:"em",value:r[7]});i=a.lastIndex}return i<t.length&&s.push({type:"text",value:t.slice(i)}),s}function e_(t){const s=t.replace(/\r/g,"").split(`
59
59
  `),a=[],i=[];let r=null,n=0;for(;n<s.length;){const l=s[n]??"",o=l.trim();if(!o){n+=1;continue}if(o.startsWith("```")){const c=[];for(n+=1;n<s.length&&!(s[n]??"").trim().startsWith("```");)c.push(s[n]??""),n+=1;n+=1,a.push({type:"code",code:c.join(`
60
60
  `)});continue}const d=o.match(/^:::([a-z0-9-]+)\s*$/i);if(d){const c=d[1].toLowerCase(),p=[];for(n+=1;n<s.length&&(s[n]??"").trim()!==":::";)p.push(s[n]??""),n+=1;n<s.length&&(n+=1);const g=[`:::${c}`,...p,":::"].join(`
61
61
  `);i.push({kind:c,lines:p,raw:g}),c==="forge-infobox"?r=JL(p):c==="note"||c==="tip"||c==="warning"||c==="danger"?a.push({type:"admonition",kind:c,lines:p}):(c==="forge-links"||c==="forge-media"||c==="forge-related")&&a.push({type:c,lines:p});continue}const m=l.match(/^(#{1,6})\s+(.*)$/);if(m){a.push({type:"heading",level:m[1].length,text:m[2].trim()}),n+=1;continue}if(/^>\s?/.test(l)){const c=[];for(;n<s.length&&/^>\s?/.test(s[n]??"");)c.push((s[n]??"").replace(/^>\s?/,"")),n+=1;a.push({type:"quote",text:c.join(" ").trim()});continue}if(/^[-*+]\s+/.test(l)||/^\d+\.\s+/.test(l)){const c=/^\d+\.\s+/.test(l),p=[];for(;n<s.length&&(/^[-*+]\s+/.test(s[n]??"")||/^\d+\.\s+/.test(s[n]??""));)p.push((s[n]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"").trim()),n+=1;a.push({type:"list",ordered:c,items:p});continue}const h=[];for(;n<s.length;){const c=s[n]??"",p=c.trim();if(!p||p.startsWith("```")||p.startsWith(":::")||/^#{1,6}\s+/.test(c)||/^>\s?/.test(c)||/^[-*+]\s+/.test(c)||/^\d+\.\s+/.test(c))break;h.push(p),n+=1}if(h.length>0){a.push({type:"paragraph",text:h.join(" ")});continue}n+=1}return{blocks:a,infobox:r,directives:i}}function t_(t,s,a){return t.map((i,r)=>{const n=`${s}-${r}`;switch(i.type){case"text":return e.jsx(u.Fragment,{children:i.value},n);case"code":return e.jsx("code",{className:"rounded bg-black/10 px-1.5 py-0.5 font-mono text-[0.92em] text-white",children:i.value},n);case"strong":return e.jsx("strong",{className:"font-semibold text-white",children:i.value},n);case"em":return e.jsx("em",{className:"italic text-white/82",children:i.value},n);case"link":{const l=/^https?:\/\//i.test(i.href);return e.jsx("a",{href:i.href,target:l?"_blank":void 0,rel:l?"noreferrer":void 0,className:"text-[var(--secondary)] underline decoration-current/30 underline-offset-2 transition hover:text-white",children:i.label},n)}case"forge-link":{const l=Si(i.entityType,i.entityId),o=l?nr(l):null;return o?e.jsx("a",{href:o,className:"rounded-sm bg-white/[0.08] px-1.5 py-0.5 text-white no-underline ring-1 ring-black/5 transition hover:bg-white/[0.12]",children:i.label},n):e.jsx("span",{className:"rounded-sm bg-white/[0.08] px-1.5 py-0.5 text-white/64",children:i.label},n)}case"wiki-link":return e.jsx(et,{to:{pathname:`/wiki/page/${encodeURIComponent(i.target)}`,search:a?`?spaceId=${encodeURIComponent(a)}`:""},className:te("underline decoration-current/30 underline-offset-2 transition hover:text-white",i.embed?"text-[var(--primary)]":"text-[var(--secondary)]"),children:i.label},n)}})}function pi(t,s,a){return t_(ZL(t),s,a)}function s_(t,s){const a=t.map(i=>i.trim()).filter(Boolean);return a.length===0?null:e.jsx("ul",{className:"space-y-1.5 pl-4 text-[13px] leading-6 text-white/76",children:a.map((i,r)=>e.jsx("li",{children:pi(i,`directive-${r}`,s)},`${i}-${r}`))})}function ef(t,s,a){switch(t.type){case"heading":{const i=t.level===1?"text-[1.9rem] leading-[1.08]":t.level===2?"text-[1.25rem] leading-[1.2]":t.level===3?"text-[1.05rem] leading-[1.3]":"text-[0.92rem] leading-[1.35]";return e.jsx("h2",{className:te("font-semibold tracking-[-0.02em] text-white",s>0&&"mt-6",i),children:pi(t.text,`heading-${s}`,a)},`heading-${s}`)}case"paragraph":return e.jsx("p",{className:"text-[14px] leading-7 text-white/78",children:pi(t.text,`paragraph-${s}`,a)},`paragraph-${s}`);case"quote":return e.jsx("blockquote",{className:"border-l-[3px] border-white/16 pl-4 text-[14px] leading-7 text-white/62",children:pi(t.text,`quote-${s}`,a)},`quote-${s}`);case"list":{const i=t.ordered?"ol":"ul";return e.jsx(i,{className:te("space-y-1.5 pl-5 text-[14px] leading-7 text-white/78",t.ordered?"list-decimal":"list-disc"),children:t.items.map((r,n)=>e.jsx("li",{children:pi(r,`list-${s}-${n}`,a)},`item-${s}-${n}`))},`list-${s}`)}case"code":return e.jsx("pre",{className:"overflow-x-auto rounded-xl bg-[rgba(10,16,30,0.9)] px-4 py-3 text-[12px] leading-6 text-white ring-1 ring-black/5",children:e.jsx("code",{children:t.code})},`code-${s}`);case"admonition":return e.jsxs("aside",{className:te("rounded-xl border px-4 py-3",t.kind==="warning"||t.kind==="danger"?"border-amber-500/25 bg-amber-500/8":"border-white/12 bg-white/[0.04]"),children:[e.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/48",children:t.kind}),e.jsx("div",{className:"grid gap-2 text-[13px] leading-6 text-white/76",children:t.lines.map((i,r)=>e.jsx("p",{children:pi(i,`admonition-${s}-${r}`,a)},`admonition-line-${r}`))})]},`admonition-${s}`);case"forge-links":case"forge-media":case"forge-related":return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/48",children:t.type.replace("forge-","")}),s_(t.lines,a)]},`${t.type}-${s}`)}}function a_(t,s,a){return e.jsx("div",{className:"text-[13px] leading-6 text-white/76",children:pi(t,s,a)})}function i_({infobox:t,spaceId:s,className:a}){return e.jsxs("aside",{className:te("wiki-infobox rounded-2xl border border-white/10 bg-white/[0.03] p-4",a),children:[t.title?e.jsx("div",{className:"text-[1rem] font-semibold leading-tight text-white",children:t.title}):null,t.summary?e.jsx("p",{className:"mt-2 text-[13px] leading-6 text-white/60",children:pi(t.summary,"infobox-summary",s)}):null,e.jsx("dl",{className:"mt-3 grid gap-2",children:t.rows.map((i,r)=>e.jsxs("div",{className:"grid gap-1 border-t border-white/10 pt-2 first:border-t-0 first:pt-0",children:[e.jsx("dt",{className:"text-[10px] font-semibold uppercase tracking-[0.16em] text-white/48",children:i.label}),e.jsx("dd",{children:a_(i.value,`infobox-row-${r}`,s)})]},`${i.label}-${r}`))})]})}function r_(t){const s=[],a=[];let i=!1;for(const r of t)!i&&r.type==="heading"&&r.level<=2&&s.length>0&&(i=!0),i?a.push(r):s.push(r);return{intro:s.length>0?s:t.slice(0,1),rest:s.length>0?a:t.slice(1)}}function Kv({markdown:t,spaceId:s,className:a}){const i=e_(t),{intro:r,rest:n}=r_(i.blocks);return e.jsxs("div",{className:te("grid gap-4",a),children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_19rem] xl:items-start",children:[e.jsx("div",{className:"grid gap-4",children:r.map((l,o)=>ef(l,o,s))}),i.infobox?e.jsx(i_,{infobox:i.infobox,spaceId:s,className:"order-2 xl:order-none"}):null]}),n.length>0?e.jsx("div",{className:"grid gap-4",children:n.map((l,o)=>ef(l,o+r.length,s))}):null]})}const Rr=new Set(["queued","processing"]),tf=15e3,n_=["goal","project","task","habit","strategy","psyche_value","note"];function sf(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function bi(t,s){const a=t[s];return typeof a=="number"&&Number.isFinite(a)?a:null}function Js(t,s){const a=t[s];return typeof a=="string"&&a.trim().length>0?a:null}function l_(t,s){const a=Js(t.metadata,"currentFileName")??Js(t.metadata,"fileName")??"current source",i=Js(t.metadata,"status")??"in_progress",r=bi(t.metadata,"chunkIndex"),n=bi(t.metadata,"chunkCount"),l=bi(t.metadata,"currentFileIndex"),o=bi(t.metadata,"currentFileTotal"),d=l!==null&&o!==null?`${a} (${l}/${o})`:a,m=r!==null&&n!==null&&n>1?` · chunk ${r}/${n}`:"";return`Waiting for OpenAI on ${d}${m}. ${s} polls · ${i}.`}function o_(t){const s=[];for(const a of t){const i=Js(a.metadata,"scope"),n=Js(a.metadata,"eventKey")==="llm_compile_background_polled",l=Js(a.metadata,"currentFileName")??Js(a.metadata,"fileName"),o=bi(a.metadata,"chunkIndex"),d=bi(a.metadata,"chunkCount"),m=n?["poll",i??"",l??"",o??"",d??""].join(":"):null,h=s[s.length-1],c=h&&Js(h.metadata,"eventKey"),p=h&&(Js(h.metadata,"currentFileName")??Js(h.metadata,"fileName")),g=h&&bi(h.metadata,"chunkIndex"),x=h&&bi(h.metadata,"chunkCount"),f=h&&c==="llm_compile_background_polled"?["poll",Js(h.metadata,"scope")??"",p??"",g??"",x??""].join(":"):null;if(n&&h&&f===m){s[s.length-1]={...a,repetitionCount:h.repetitionCount+1,metadata:{...a.metadata,aggregatedPollCount:h.repetitionCount+1}};continue}s.push({...a,repetitionCount:1})}return s}function Eo(t){return cs(t)}function af(t){return typeof t=="string"&&n_.includes(t)}function d_(t,s){return typeof s.title=="string"&&s.title.trim().length>0?s.title:typeof s.displayName=="string"&&s.displayName.trim().length>0?s.displayName:typeof s.statement=="string"&&s.statement.trim().length>0?s.statement:`${t}:${String(s.id??"")}`}function c_(t,s){const i=[s.description,s.summary,s.overview,s.valuedDirection,s.whyItMatters,s.originNote].find(r=>typeof r=="string"&&r.trim().length>0);return i||(t==="note"&&typeof s.kind=="string"?s.kind:"")}function u_({candidate:t,decision:s,onDecisionChange:a,spaceId:i}){const r=af(t.payload.entityType)?t.payload.entityType:null,[n,l]=u.useState(s.mappedEntityLabel||t.title||""),[o,d]=u.useState(s.targetNoteLabel||t.title||""),m=typeof t.payload.contentMarkdown=="string"?t.payload.contentMarkdown:typeof t.payload.patchSummary=="string"?t.payload.patchSummary:typeof t.payload.rationale=="string"?t.payload.rationale:t.summary,h=Me({queryKey:["forge-wiki-ingest-map-search",r,n.trim()],enabled:t.candidateType==="entity"&&s.action==="map_existing"&&r!==null&&n.trim().length>0,queryFn:async()=>{var T;const A=(await kb({searches:[{entityTypes:r?[r]:void 0,query:n.trim(),limit:8}]})).results[0];return((T=A==null?void 0:A.matches)==null?void 0:T.filter(I=>!!(I&&af(I.entityType)&&typeof I.id=="string"&&I.entity&&typeof I.entity=="object")).map(I=>({entityType:I.entityType,entityId:I.id,label:d_(I.entityType,I.entity),description:c_(I.entityType,I.entity),kind:Eo(I.entityType)})))??[]}}),c=h.data??[],p=Me({queryKey:["forge-wiki-ingest-merge-search",i,o.trim()],enabled:t.candidateType==="page"&&s.action==="merge_existing"&&o.trim().length>0,queryFn:async()=>(await TN({spaceId:i,kind:"wiki",mode:"text",query:o.trim(),limit:8})).results.map(A=>({noteId:A.page.id,title:A.page.title,slug:A.page.slug,summary:A.page.summary}))}),g=p.data??[],x=s.mappedEntityId&&s.mappedEntityType?c.find(b=>b.entityId===s.mappedEntityId&&b.entityType===s.mappedEntityType)??(s.mappedEntityLabel?{entityId:s.mappedEntityId,entityType:s.mappedEntityType,label:s.mappedEntityLabel,kind:Eo(s.mappedEntityType)}:null):null,f=s.targetNoteId?g.find(b=>b.noteId===s.targetNoteId)??(s.targetNoteLabel?{noteId:s.targetNoteId,title:s.targetNoteLabel}:null):null;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:t.candidateType.replaceAll("_"," ")}),e.jsx("div",{className:"mt-2 text-base font-semibold text-white",children:t.title||t.targetKey||"Untitled candidate"}),r?e.jsx("div",{className:"mt-2",children:Eo(r)?e.jsx(Qe,{kind:Eo(r),label:r.replaceAll("_"," "),compact:!0,gradient:!1}):e.jsx(S,{className:"bg-white/[0.08] text-white/72",children:r.replaceAll("_"," ")})}):null,t.summary?e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/58",children:t.summary}):null]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] p-1",children:[e.jsx("button",{type:"button",className:te("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="keep"?"bg-[rgba(192,193,255,0.2)] text-white":"text-white/54 hover:text-white"),onClick:()=>a({...s,action:"keep"}),children:"Keep"}),t.candidateType==="entity"&&r?e.jsx("button",{type:"button",className:te("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="map_existing"?"bg-[rgba(133,222,255,0.18)] text-white":"text-white/54 hover:text-white"),onClick:()=>a({...s,action:"map_existing",mappedEntityType:r}),children:"Map existing"}):null,t.candidateType==="page"?e.jsx("button",{type:"button",className:te("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="merge_existing"?"bg-[rgba(133,222,255,0.18)] text-white":"text-white/54 hover:text-white"),onClick:()=>a({...s,action:"merge_existing"}),children:"Merge existing"}):null,e.jsx("button",{type:"button",className:te("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="discard"?"bg-[rgba(255,255,255,0.12)] text-white":"text-white/54 hover:text-white"),onClick:()=>a({...s,action:"discard"}),children:"Discard"})]})]}),t.candidateType==="entity"&&r&&s.action==="map_existing"?e.jsxs("div",{className:"mt-4 grid gap-3 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.55)] p-4",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:["Map to existing ",r.replaceAll("_"," ")]}),x?e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[x.kind?e.jsx(Qe,{kind:x.kind,label:x.label,compact:!0,gradient:!1,className:"max-w-[20rem]"}):e.jsx(S,{className:"bg-white/[0.08] text-white/78",children:x.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>a({...s,mappedEntityId:void 0,mappedEntityLabel:void 0}),"aria-label":"Clear mapped entity",children:e.jsx(Lt,{className:"size-3.5"})})]})}):null,e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(Bt,{className:"size-4 text-white/34"}),e.jsx("input",{value:n,onChange:b=>{l(b.target.value),s.mappedEntityId&&a({...s,mappedEntityId:void 0,mappedEntityLabel:void 0})},placeholder:`Search existing ${r.replaceAll("_"," ")}`,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),e.jsx("div",{className:"grid gap-2",children:h.isPending?e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/48",children:"Searching Forge…"}):c.length===0?e.jsxs("div",{className:"rounded-[16px] border border-dashed border-white/10 px-3 py-3 text-sm text-white/42",children:["No existing ",r.replaceAll("_"," ")," matches yet."]}):c.map(b=>{const A=s.mappedEntityType===b.entityType&&s.mappedEntityId===b.entityId;return e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] border px-3 py-3 text-left transition",A?"border-[rgba(133,222,255,0.24)] bg-[rgba(133,222,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/72 hover:bg-white/[0.06] hover:text-white"),onClick:()=>a({action:"map_existing",mappedEntityType:b.entityType,mappedEntityId:b.entityId,mappedEntityLabel:b.label}),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:b.kind?e.jsx(Qe,{kind:b.kind,label:b.label,compact:!0,gradient:!1}):b.label}),b.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:b.description}):null]})},`${b.entityType}:${b.entityId}`)})})]}):null,t.candidateType==="page"&&s.action==="merge_existing"?e.jsxs("div",{className:"mt-4 grid gap-3 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.55)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Merge into existing page"}),f?e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[e.jsx(S,{className:"bg-white/[0.08] text-white/78",children:f.title}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>a({...s,targetNoteId:void 0,targetNoteLabel:void 0}),"aria-label":"Clear merge target",children:e.jsx(Lt,{className:"size-3.5"})})]})}):null,e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(Bt,{className:"size-4 text-white/34"}),e.jsx("input",{value:o,onChange:b=>{d(b.target.value),s.targetNoteId&&a({...s,targetNoteId:void 0,targetNoteLabel:void 0})},placeholder:"Search existing wiki pages",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),e.jsx("div",{className:"grid gap-2",children:p.isPending?e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/48",children:"Searching Forge…"}):g.length===0?e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 px-3 py-3 text-sm text-white/42",children:"No existing wiki pages match yet."}):g.map(b=>{const A=s.targetNoteId===b.noteId;return e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] border px-3 py-3 text-left transition",A?"border-[rgba(133,222,255,0.24)] bg-[rgba(133,222,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/72 hover:bg-white/[0.06] hover:text-white"),onClick:()=>a({action:"merge_existing",targetNoteId:b.noteId,targetNoteLabel:b.title}),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:b.title}),e.jsxs("div",{className:"mt-1 text-xs leading-5 text-white/46",children:[b.slug?`${b.slug}`:"",b.summary?`${b.slug?" · ":""}${b.summary}`:""]})]})},b.noteId)})})]}):null,m?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.65)] px-4 py-3 text-sm leading-6 text-white/72",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans",children:m})}):null]})}function qv({open:t,onOpenChange:s,spaces:a,llmProfiles:i,initialSpaceId:r,selectedJobId:n,onJobSelected:l,linkedEntityHints:o=[]}){var ce;const d=Ht(),m=pt(),[h,c]=u.useState("files"),[p,g]=u.useState(r),[x,f]=u.useState(""),[b,A]=u.useState(""),[T,I]=u.useState(""),[y,N]=u.useState([]),[k,w]=u.useState(!1),[P,j]=u.useState(!1),R=u.useMemo(()=>i.filter(J=>J.enabled&&!!J.secretId),[i]),[v,D]=u.useState(((ce=R[0])==null?void 0:ce.id)??""),[L,Q]=u.useState("auto"),[Z,V]=u.useState({}),[B,$]=u.useState(null),[E,X]=u.useState(null),W=u.useRef({});u.useEffect(()=>{r&&g(r)},[r]),u.useEffect(()=>{var J;!v&&((J=R[0])!=null&&J.id)&&D(R[0].id)},[v,R]);const q=R.find(J=>J.id===v)??R[0]??null,G=Me({queryKey:["forge-wiki-ingest-job",n],queryFn:()=>IN(n),enabled:t&&!!n,refetchInterval:J=>{const je=J.state.data;return je&&Rr.has(je.job.status)?2e3:!1}});u.useEffect(()=>{const J=G.data;J&&V(je=>{const Ee={};for(const Ce of J.candidates)Ee[Ce.id]=je[Ce.id]??(Ce.status==="rejected"?{action:"discard"}:{action:"keep"});return Ee})},[G.data]),u.useEffect(()=>{E&&X(null)},[Z,E]);const z=De({mutationFn:async J=>AN(J),onSuccess:(J,je)=>{J.job&&m.setQueryData(["forge-wiki-ingest-job",je],J.job),m.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),m.invalidateQueries({queryKey:["forge-wiki-ingest-history"]})}});u.useEffect(()=>{const J=G.data;if(!J||!Rr.has(J.job.status))return;const je=J.logs.reduce((U,he)=>{const Ne=Number(new Date(he.createdAt));return Number.isFinite(Ne)?Math.max(U,Ne):U},0),Ee=Number(new Date(J.job.updatedAt)),Ce=Math.max(Number.isFinite(Ee)?Ee:0,je);if(!Number.isFinite(Ce)||Ce<=0)return;const Ke=Date.now();if(!(Ke-Ce>=tf)||z.isPending)return;const M=W.current[J.job.id]??0;Ke-M<tf||(W.current[J.job.id]=Ke,z.mutate(J.job.id))},[G.data,z]);const ge=De({mutationFn:async()=>{if(!q)throw new Error("Set up an OpenAI wiki ingest profile first. Forge now requires an LLM profile before auto-ingest can turn source material into draft pages and entities.");if(h==="files"){if(y.length===0)throw new Error("Select at least one file to ingest.");return CN({files:y,spaceId:p||void 0,titleHint:x.trim()||void 0,llmProfileId:q.id,parseStrategy:L,createAsKind:"wiki",linkedEntityHints:o})}if(h==="url"){if(!b.trim())throw new Error("Enter a URL to ingest.");return hp({spaceId:p||void 0,titleHint:x.trim()||void 0,sourceKind:"url",sourceUrl:b.trim(),llmProfileId:q.id,parseStrategy:L,createAsKind:"wiki",linkedEntityHints:o})}if(!T.trim())throw new Error("Paste some text to ingest.");return hp({spaceId:p||void 0,titleHint:x.trim()||void 0,sourceKind:"raw_text",sourceText:T,mimeType:"text/plain",llmProfileId:q.id,parseStrategy:L,createAsKind:"wiki",linkedEntityHints:o})},onSuccess:async J=>{var Ee;const je=((Ee=J.job)==null?void 0:Ee.job.id)??null;await m.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),await m.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),je&&l(je),$(null),X(null)},onError:J=>{$(J instanceof Error?J.message:"Unable to start ingest.")}}),ke=De({mutationFn:async()=>{if(!n||!G.data)throw new Error("Choose an ingest job first.");const J=G.data.candidates.map(je=>{const Ee=Z[je.id]??{action:"keep"};if(Ee.action==="map_existing"&&(!Ee.mappedEntityType||!Ee.mappedEntityId))throw new Error(`Choose an existing ${String(je.payload.entityType??"entity").replaceAll("_"," ")} before publishing the review.`);if(Ee.action==="merge_existing"&&!Ee.targetNoteId)throw new Error(`Choose an existing wiki page before publishing the review for ${je.title||"this page candidate"}.`);return Ee.action==="map_existing"?{candidateId:je.id,action:"map_existing",mappedEntityType:Ee.mappedEntityType,mappedEntityId:Ee.mappedEntityId}:Ee.action==="merge_existing"?{candidateId:je.id,action:"merge_existing",targetNoteId:Ee.targetNoteId}:{candidateId:je.id,action:Ee.action}});return MN({jobId:n,decisions:J})},onSuccess:async J=>{X(null),m.setQueryData(["forge-wiki-ingest-job",J.job.job.id],J.job),await Promise.all([m.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),m.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),m.invalidateQueries({queryKey:["forge-wiki-ingest-job",J.job.job.id]}),m.invalidateQueries({queryKey:["forge-wiki-home"]}),m.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),m.invalidateQueries({queryKey:["forge-wiki-tree"]})])},onError:J=>{X(J instanceof Error?J.message:"Unable to publish review.")}}),me=De({mutationFn:async()=>{if(!n)throw new Error("Choose an ingest job first.");return PN(n)},onSuccess:async J=>{var Ee;const je=((Ee=J.job)==null?void 0:Ee.job.id)??null;await Promise.all([m.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),m.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),m.invalidateQueries({queryKey:["forge-wiki-ingest-job",n]})]),je&&l(je),$(null),X(null)},onError:J=>{$(J instanceof Error?J.message:"Unable to rerun ingest.")}}),se=De({mutationFn:async()=>{if(!n)throw new Error("Choose an ingest job first.");return cb(n)},onSuccess:async()=>{await Promise.all([m.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),m.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),m.invalidateQueries({queryKey:["forge-wiki-ingest-job",n]})]),O(),$(null),X(null)},onError:J=>{$(J instanceof Error?J.message:"Unable to delete ingest.")}}),we=G.data??null,ve=we&&!Rr.has(we.job.status),_=u.useMemo(()=>(we==null?void 0:we.candidates.filter(J=>["suggested","rejected","failed"].includes(J.status)))??[],[we]),F=u.useMemo(()=>o_((we==null?void 0:we.logs)??[]),[we==null?void 0:we.logs]),O=()=>{l(null),N([]),A(""),I(""),f(""),$(null),X(null)};return e.jsx(es,{open:t,onOpenChange:J=>{s(J),J||($(null),X(null))},children:e.jsxs(ts,{children:[e.jsx(ss,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.78)] backdrop-blur-sm"}),e.jsxs(as,{className:"fixed inset-x-4 bottom-4 top-4 z-50 mx-auto flex max-w-[min(74rem,calc(100vw-2rem))] flex-col overflow-hidden rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,27,42,0.98),rgba(10,15,28,0.98))] shadow-[0_36px_110px_rgba(3,8,18,0.48)]",children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"KarpaWiki Ingest"}),e.jsx(is,{className:"mt-2 font-display text-[1.5rem] tracking-[-0.04em] text-white",children:we?"Ingest review and progress":"Build KarpaWiki memory from source files"}),e.jsx(os,{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Upload notes, media, ZIP archives, links, or pasted text. Forge will process them in the background, propose pages and entities, and let you keep only what belongs."})]}),e.jsx(ds,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close ingest modal",children:e.jsx(Lt,{className:"size-4"})})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-5",children:we?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:["Job ",we.job.id]}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:we.job.latestMessage||"Ingest job"}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/56",children:[we.job.status," · ",we.job.phase," · started ",sf(we.job.createdAt)]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(H,{variant:"secondary",size:"sm",onClick:O,children:"New ingest"}),ve?e.jsxs(e.Fragment,{children:[e.jsxs(H,{variant:"secondary",size:"sm",pending:me.isPending,pendingLabel:"Rerunning",onClick:()=>void me.mutateAsync(),children:[e.jsx(Ut,{className:"size-3.5"}),"Rerun"]}),e.jsx(H,{variant:"ghost",size:"sm",className:"border border-rose-300/18 bg-rose-400/10 text-rose-100 hover:bg-rose-400/16",pending:se.isPending,pendingLabel:"Deleting",onClick:()=>{window.confirm("Delete this ingest history entry? Published pages or entities will stay, but discarded or unreviewed ingest data will be removed.")&&se.mutateAsync()},children:"Delete"})]}):null]})]}),e.jsx("div",{className:"mt-5 grid gap-3 sm:grid-cols-4",children:[{label:"Progress",value:`${we.job.progressPercent}%`},{label:"Files",value:`${we.job.processedFiles}/${we.job.totalFiles}`},{label:"Pages",value:String(we.job.createdPageCount)},{label:"Entities",value:String(we.job.createdEntityCount)}].map(J=>e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-[rgba(8,12,22,0.68)] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:J.label}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:J.value})]},J.label))}),e.jsx("div",{className:"mt-5",children:e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-white/[0.06]",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(192,193,255,0.8),rgba(133,222,255,0.8))] transition-all duration-300",style:{width:`${we.job.progressPercent}%`}})})}),B?e.jsx("div",{className:"mt-4 rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:B}):null]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Rich log"}),e.jsx(H,{variant:"secondary",size:"sm",onClick:()=>d(`/settings/logs?jobId=${encodeURIComponent(we.job.id)}`),children:"Open full logs"})]}),e.jsx("div",{className:"mt-4 grid max-h-[28rem] gap-2 overflow-y-auto",children:F.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/45",children:"Waiting for the backend to emit progress."}):F.map(J=>e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/55",children:J.level}),typeof J.metadata.scope=="string"?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/38",children:J.metadata.scope}):null,typeof J.metadata.eventKey=="string"?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/38",children:J.metadata.eventKey}):null]}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:Js(J.metadata,"eventKey")==="llm_compile_background_polled"?l_(J,J.repetitionCount):J.message}),J.repetitionCount>1?e.jsxs("div",{className:"mt-2 text-xs text-white/44",children:["Combined ",J.repetitionCount," repeated polling updates."]}):null,Object.keys(J.metadata).length>0?e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"cursor-pointer text-xs text-white/45",children:"View metadata"}),e.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap rounded-[14px] border border-white/8 bg-black/20 px-3 py-3 text-[11px] leading-5 text-white/52",children:JSON.stringify(J.metadata,null,2)})]}):null]}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-white/38",children:sf(J.createdAt)})]})},J.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Source files"}),e.jsx("div",{className:"mt-4 grid gap-2",children:we.assets.map(J=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:J.fileName||J.sourceLocator||"Source"}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:J.mimeType||J.sourceKind})]}),e.jsx("div",{className:"shrink-0 text-[11px] uppercase tracking-[0.14em] text-white/40",children:J.status})]},J.id))})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Review"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Keep the candidates that belong in Forge and discard the rest."})]}),Rr.has(we.job.status)?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs text-white/58",children:[e.jsx(Cl,{className:"size-3.5 animate-spin"}),"Processing"]}):null]}),e.jsx("div",{className:"mt-4 grid gap-3",children:_.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/45",children:Rr.has(we.job.status)?"Candidates will appear here while the job progresses.":"This job has no reviewable candidates left."}):_.map(J=>e.jsx(u_,{candidate:J,spaceId:we.job.spaceId,decision:Z[J.id]??{action:"keep"},onDecisionChange:je=>V(Ee=>({...Ee,[J.id]:je}))},J.id))}),E?e.jsx("div",{className:"mt-4 rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:E}):null,_.length>0&&!Rr.has(we.job.status)?e.jsx("div",{className:"mt-5",children:e.jsxs(H,{className:"min-h-12",pending:ke.isPending,pendingLabel:"Publishing review",onClick:()=>void ke.mutateAsync(),children:[e.jsx(Jo,{className:"size-4"}),"Publish kept candidates"]})}):null]})]})]}):e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1.15fr)_minmax(18rem,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{id:"files",label:"Files and ZIP",detail:"Drag many files or one archive.",icon:ac},{id:"url",label:"URL",detail:"Pull a webpage or remote file.",icon:Ej},{id:"text",label:"Paste text",detail:"Turn notes or transcripts into pages.",icon:Go}].map(J=>{const je=J.icon,Ee=J.id===h;return e.jsxs("button",{type:"button",className:te("rounded-[24px] border px-4 py-4 text-left transition",Ee?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07] hover:text-white"),onClick:()=>c(J.id),children:[e.jsx(je,{className:"size-4 text-[var(--secondary)]"}),e.jsx("div",{className:"mt-3 text-sm font-semibold",children:J.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/48",children:J.detail})]},J.id)})}),e.jsx("div",{className:"rounded-[28px] border border-white/8 bg-[rgba(9,14,26,0.72)] p-4 sm:p-5",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(be,{value:x,onChange:J=>f(J.target.value),placeholder:"Optional title hint"}),h==="files"?e.jsxs("div",{className:te("rounded-[28px] border-2 border-dashed px-5 py-8 text-center transition",k?"border-[rgba(192,193,255,0.35)] bg-[rgba(192,193,255,0.08)]":"border-white/10 bg-white/[0.03]"),onDragEnter:J=>{J.preventDefault(),w(!0)},onDragLeave:J=>{J.preventDefault(),w(!1)},onDragOver:J=>{J.preventDefault(),w(!0)},onDrop:J=>{J.preventDefault(),w(!1);const je=Array.from(J.dataTransfer.files);N(Ee=>[...Ee,...je])},children:[e.jsx("div",{className:"mx-auto flex size-14 items-center justify-center rounded-full border border-white/10 bg-white/[0.05]",children:e.jsx(ac,{className:"size-5 text-white/72"})}),e.jsx("div",{className:"mt-4 text-base font-semibold text-white",children:"Drop files, media, notes, or ZIP archives here"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/50",children:"Forge accepts many files at once and queues the ingest in the background so the UI stays responsive."}),e.jsxs("label",{className:"mt-5 inline-flex cursor-pointer items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm text-white/78 transition hover:bg-white/[0.08] hover:text-white",children:[e.jsx(ac,{className:"size-4"}),"Choose files",e.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:J=>N(Array.from(J.target.files??[]))})]}),y.length>0?e.jsx("div",{className:"mt-5 grid gap-2 text-left",children:y.map(J=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:[e.jsx("span",{className:"truncate",children:J.name}),e.jsx("span",{className:"shrink-0 text-xs text-white/42",children:J.name.toLowerCase().endsWith(".zip")?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Lj,{className:"size-3.5"}),"ZIP"]}):`${Math.max(1,Math.round(J.size/1024))} KB`})]},`${J.name}-${J.size}-${J.lastModified}`))}):null]}):null,h==="url"?e.jsx(be,{value:b,onChange:J=>A(J.target.value),placeholder:"https://example.com/source"}):null,h==="text"?e.jsx(st,{value:T,onChange:J=>I(J.target.value),placeholder:"Paste notes, transcripts, meeting writeups, or source material here…",className:"min-h-[18rem]"}):null]})})]}),e.jsxs("aside",{className:"grid h-fit gap-4",children:[q?null:e.jsxs("div",{className:"rounded-[30px] border border-amber-300/28 bg-[linear-gradient(180deg,rgba(120,74,14,0.28),rgba(37,22,8,0.42))] p-5 shadow-[0_24px_64px_rgba(12,6,0,0.22)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-full border border-amber-200/20 bg-amber-300/12 text-amber-100",children:e.jsx(Tl,{className:"size-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-amber-100/62",children:"OpenAI setup required for smart ingest"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:"Forge can only do a raw import without OpenAI"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/78",children:"Without an OpenAI ingest profile, Forge cannot extract key insights, split the source into draft wiki pages, or propose Forge entities. The fallback is just a direct text import or media reference with no structured synthesis."}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"Set up the API key, model, thinking, and verbosity first, then come back here to build real draft pages and reviewable entity proposals."})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-2",children:[e.jsxs(H,{className:"w-full",onClick:()=>{s(!1),d("/settings/wiki?setupLlm=1")},children:[e.jsx(Ut,{className:"size-4"}),"Open OpenAI setup"]}),e.jsx(H,{variant:"secondary",className:"w-full",onClick:()=>{s(!1),d("/settings/wiki")},children:"Open KarpaWiki settings"})]})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 text-left",onClick:()=>j(J=>!J),children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Advanced"}),e.jsx("div",{className:"mt-2 text-sm text-white/72",children:"Model, parse, and target controls."})]}),e.jsx(Ut,{className:"size-4 text-white/58"})]}),P?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Space"}),e.jsx("div",{className:"grid gap-2",children:a.map(J=>e.jsxs("button",{type:"button",className:te("rounded-[18px] border px-3 py-3 text-left text-sm transition",p===J.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>g(J.id),children:[e.jsx("div",{children:J.label}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:J.description||`/${J.slug}`})]},J.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"LLM profile"}),e.jsxs("div",{className:"grid gap-2",children:[R.map(J=>e.jsxs("button",{type:"button",className:te("rounded-[18px] border px-3 py-3 text-left text-sm transition",v===J.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>D(J.id),children:[e.jsx("div",{children:J.label}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:J.model})]},J.id)),R.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/48",children:"No enabled profile with a saved key yet."}):null]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Parse mode"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:[{id:"auto",label:"Auto"},{id:"multimodal",label:"Multimodal"},{id:"text_only",label:"Text only"}].map(J=>e.jsx("button",{type:"button",className:te("rounded-[18px] border px-3 py-3 text-sm transition",L===J.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>Q(J.id),children:J.label},J.id))})]})]}):null]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(192,193,255,0.12),rgba(192,193,255,0.05))] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Jo,{className:"size-4 text-[var(--secondary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Publish only what belongs"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"Forge stages candidate pages, proposed entity records, and page updates first. You review the output before anything is committed to the live memory graph."})]}),B?e.jsx("div",{className:"rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:B}):null,e.jsxs(H,{className:"min-h-12",pending:ge.isPending,pendingLabel:"Starting ingest",disabled:!q,onClick:()=>void ge.mutateAsync(),children:[e.jsx(Ut,{className:"size-4"}),"Start background ingest"]})]})]})})]})]})})}function m_(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"}).format(new Date(t))}function h_(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Bv({nodes:t,activeSlug:s,spaceId:a,depth:i=0}){return e.jsx("ul",{className:te("grid gap-1",i>0&&"mt-1"),children:t.map(r=>{const n=r.page.slug===s;return e.jsxs("li",{className:"grid gap-1",children:[e.jsx(et,{to:{pathname:r.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(r.page.slug)}`,search:`?spaceId=${encodeURIComponent(a)}`},className:te("rounded-lg px-2 py-1.5 text-[12px] leading-5 transition",n?"bg-white/[0.08] text-white":"text-white/64 hover:bg-white/[0.04] hover:text-white"),style:{paddingLeft:`${.5+i*.7}rem`},children:r.page.title}),r.children.length>0?e.jsx(Bv,{nodes:r.children,activeSlug:s,spaceId:a,depth:i+1}):null]},r.page.id)})})}function p_({open:t,onOpenChange:s,spaces:a,activeSpaceId:i,onSelect:r}){var l;const n=((l=a.find(o=>o.visibility==="shared"))==null?void 0:l.id)??"";return e.jsx(es,{open:t,onOpenChange:s,children:e.jsxs(ts,{children:[e.jsx(ss,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs(as,{className:"fixed left-1/2 top-[14vh] z-50 w-[min(28rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(is,{className:"font-display text-[1.2rem] tracking-[-0.04em] text-white",children:"Choose KarpaWiki space"}),e.jsx(os,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Switch the reading space without leaving the article surface."})]}),e.jsx(ds,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close space picker",children:e.jsx(Lt,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:a.map(o=>{const d=o.id===i,m=o.id===n;return e.jsxs("button",{type:"button",className:te("flex items-center justify-between gap-3 rounded-[22px] border px-4 py-3 text-left transition",d?"border-[rgba(192,193,255,0.22)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/78 hover:bg-white/[0.06] hover:text-white"),onClick:()=>{r(o.id),s(!1)},children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-semibold text-inherit",children:o.label}),e.jsx("span",{className:"mt-1 block text-[12px] leading-5 text-white/52",children:o.description||`/${o.slug}`}),m?e.jsx("span",{className:"mt-2 inline-flex rounded-full bg-amber-200/90 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-stone-950",children:"Recovered pages"}):null]}),d?e.jsx(Ia,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},o.id)})})]})]})})}function rf(){var _,F,O,ce,J,je,Ee,Ce,Ke,Pe;const t=Ct(),s=Ht(),a=pt(),{slug:i}=aa(),[r,n]=ws(),[l,o]=u.useState(!1),[d,m]=u.useState(!1),[h,c]=u.useState(!1),[p,g]=u.useState("hybrid"),[x,f]=u.useState(""),[b,A]=u.useState(""),T=u.useRef(null),I=r.get("spaceId")??"",y=r.get("ingest")==="1",N=r.get("ingestJobId"),k=Me({queryKey:["forge-wiki-settings"],queryFn:Od}),w=I||((F=(_=k.data)==null?void 0:_.settings.spaces[0])==null?void 0:F.id)||"",P=((O=k.data)==null?void 0:O.settings.embeddingProfiles.filter(M=>M.enabled))??[];u.useEffect(()=>{var M;!b&&((M=P[0])!=null&&M.id)&&A(P[0].id)},[P,b]),u.useEffect(()=>{var M,U;if(!I&&((U=(M=k.data)==null?void 0:M.settings.spaces[0])!=null&&U.id)){const he=new URLSearchParams(r);he.set("spaceId",k.data.settings.spaces[0].id),n(he,{replace:!0})}},[r,I,n,k.data]);const j=Me({queryKey:["forge-wiki-home",w],queryFn:()=>gN({spaceId:w||void 0}),enabled:!!w&&!i}),R=Me({queryKey:["forge-wiki-page-by-slug",w,i],queryFn:()=>fN({slug:i??"index",spaceId:w||void 0}),enabled:!!w&&!!i}),v=Me({queryKey:["forge-wiki-tree",w],queryFn:()=>bN({spaceId:w||void 0,kind:"wiki"}),enabled:!!w}),D=Me({queryKey:["forge-wiki-modal-search",w,p,x,b],queryFn:()=>vN({spaceId:w||void 0,mode:p,query:x.trim(),profileId:(p==="semantic"||p==="hybrid")&&b||void 0,limit:30}),enabled:l&&!!w&&x.trim().length>0}),L=i?R.data??null:j.data??null,[Q,Z]=u.useState(null);u.useEffect(()=>{L&&Z(L)},[L]);const V=!!w&&(i?R.isFetching:j.isFetching),B=L??(V?Q:null),$=(B==null?void 0:B.page)??null,E=((ce=k.data)==null?void 0:ce.settings.spaces.find(M=>M.id===w))??null,X=((J=k.data)==null?void 0:J.settings.spaces.find(M=>M.visibility==="shared"))??null,W=!!X&&!!E&&(E==null?void 0:E.id)!==(X==null?void 0:X.id)&&(E==null?void 0:E.visibility)==="personal",q=($==null?void 0:$.slug)!=="index",G=i&&R.error instanceof Ya&&R.error.status===404?i.trim():null;u.useEffect(()=>{if(!w||!G)return;const M=new URLSearchParams;M.set("spaceId",w),M.set("title",G);const U=h_(G);U&&M.set("slug",U),s(`/wiki/new?${M.toString()}`,{replace:!0})},[w,G,s]);const z=u.useMemo(()=>(($==null?void 0:$.links)??[]).map(M=>({id:`${M.entityType}:${M.entityId}`,href:Si(M.entityType,M.entityId),label:`${M.entityType} · ${M.entityId}`})),[$==null?void 0:$.links]),ge=De({mutationFn:async M=>wN(M),onSuccess:async()=>{await Promise.all([a.invalidateQueries({queryKey:["forge-wiki-tree"]}),a.invalidateQueries({queryKey:["forge-wiki-home"]}),a.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),a.invalidateQueries({queryKey:["forge-wiki-modal-search"]})]),s(`/wiki${w?`?spaceId=${encodeURIComponent(w)}`:""}`)}}),ke=(M,U=!1)=>{const he=new URLSearchParams(r);M(he),n(he,{replace:U})},me=M=>{ke(U=>{U.set("ingest","1"),M?U.set("ingestJobId",M):U.delete("ingestJobId"),w&&U.set("spaceId",w)})},se=()=>{ke(M=>{M.delete("ingest"),M.delete("ingestJobId")})},we=M=>{ke(U=>{U.set("ingest","1"),M?U.set("ingestJobId",M):U.delete("ingestJobId"),w&&U.set("spaceId",w)})},ve=()=>{!$||!q||ge.isPending||!window.confirm(`Delete KarpaWiki page "${$.title}"? You can restore it later from the bin.`)||ge.mutateAsync($.id)};return u.useEffect(()=>{if(!h)return;const M=he=>{var Ne;(Ne=T.current)!=null&&Ne.contains(he.target)||c(!1)},U=he=>{he.key==="Escape"&&c(!1)};return document.addEventListener("pointerdown",M),document.addEventListener("keydown",U),()=>{document.removeEventListener("pointerdown",M),document.removeEventListener("keydown",U)}},[h]),!$&&(k.isLoading||v.isLoading||!i&&j.isLoading||i&&R.isLoading)?e.jsx(zt,{eyebrow:"KarpaWiki",title:"Loading the article",description:"Preparing the current space, article, and KarpaWiki index."}):!$&&!G&&(k.isError||j.isError||R.isError||v.isError)?e.jsx(ct,{eyebrow:"KarpaWiki",error:k.error??j.error??R.error??v.error,onRetry:()=>{k.refetch(),j.refetch(),R.refetch(),v.refetch()}}):$?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-[1680px] flex-col gap-4",children:[e.jsxs("section",{className:"wiki-frame px-3 py-3 sm:px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Qe,{kind:"wiki_page",label:"KarpaWiki page",compact:!0,gradient:!1}),E?e.jsx(Qe,{kind:"wiki_space",label:E.label,compact:!0,gradient:!1,wrap:!0,className:"max-w-[20rem]"}):null,e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:m_($.updatedAt)}),e.jsx(Mi,{metrics:t.snapshot.metrics,className:"ml-auto"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row lg:items-center",children:[e.jsxs("button",{type:"button",className:"wiki-search-launch flex min-h-[2.9rem] w-full items-center gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 text-left text-[14px] text-white/56 transition hover:bg-white/[0.06] hover:text-white lg:flex-1",onClick:()=>o(!0),children:[e.jsx(Bt,{className:"size-4 shrink-0 text-white/44"}),e.jsx("span",{children:"Search KarpaWiki"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 lg:shrink-0",children:[e.jsxs("button",{type:"button",className:"wiki-space-trigger inline-flex min-h-[2.9rem] items-center gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 text-[13px] font-medium text-white/78 transition hover:bg-white/[0.07] hover:text-white",onClick:()=>m(!0),children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.14em] text-white/38",children:"Space"}),e.jsx("span",{className:"max-w-[16rem] truncate",children:(E==null?void 0:E.label)??"KarpaWiki space"}),e.jsx(Ta,{className:"size-3.5 text-white/44"})]}),e.jsxs("div",{className:"relative",ref:T,children:[e.jsxs(H,{variant:"secondary",size:"sm",className:"min-h-[2.9rem]",onClick:()=>c(M=>!M),children:[e.jsx(Ut,{className:"size-3.5"}),"Ingest",e.jsx(Ta,{className:"size-3.5"})]}),h?e.jsxs("div",{className:"absolute right-0 top-[calc(100%+0.5rem)] z-20 grid min-w-[15rem] gap-2 rounded-[22px] border border-white/10 bg-[rgba(9,14,27,0.98)] p-2 shadow-[0_24px_60px_rgba(0,0,0,0.35)]",children:[e.jsxs("button",{type:"button",className:"flex items-start gap-3 rounded-[18px] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{c(!1),me()},children:[e.jsx(Ut,{className:"mt-0.5 size-4 shrink-0 text-[var(--primary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium text-white",children:"New ingest"}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:"Start a fresh import from files, URLs, or pasted text."})]})]}),e.jsxs("button",{type:"button",className:"flex items-start gap-3 rounded-[18px] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{c(!1),s(`/wiki/ingest-history${w?`?spaceId=${encodeURIComponent(w)}`:""}`)},children:[e.jsx(Rf,{className:"mt-0.5 size-4 shrink-0 text-[var(--secondary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium text-white",children:"History"}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:"Browse prior ingests, reopen reviews, and delete old ingest records."})]})]})]}):null]}),e.jsxs(H,{variant:"secondary",size:"sm",className:"min-h-[2.9rem]",onClick:()=>s(`/wiki/edit/${encodeURIComponent($.id)}?spaceId=${encodeURIComponent(w)}`,{state:{initialPage:$}}),children:[e.jsx(vm,{className:"size-3.5"}),"Edit"]}),e.jsx(fr,{entityType:"note",entityId:$.id,label:"Open in graph",size:"sm"}),e.jsxs(H,{variant:"secondary",size:"sm",className:te("min-h-[2.9rem] border border-rose-400/18 bg-rose-500/10 text-rose-100 hover:bg-rose-500/18",!q&&"opacity-60"),onClick:ve,pending:ge.isPending,pendingLabel:"Deleting",disabled:!q,title:q?"Delete this KarpaWiki page":"The KarpaWiki home page cannot be deleted",children:[e.jsx(Wt,{className:"size-3.5"}),"Delete"]}),e.jsxs(H,{size:"sm",className:"min-h-[2.9rem]",onClick:()=>s(`/wiki/new?spaceId=${encodeURIComponent(w)}`),children:[e.jsx(ps,{className:"size-3.5"}),"New page"]})]})]}),W&&X?e.jsxs("div",{className:"mt-3 flex flex-col gap-3 rounded-[22px] border border-amber-300/20 bg-amber-300/[0.08] px-4 py-3 text-[13px] leading-6 text-amber-50 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("span",{children:["You are viewing the personal starter wiki. The recovered people, story, and conversation pages are in"," ",e.jsx("strong",{children:X.label}),"."]}),e.jsx("button",{type:"button",className:"inline-flex min-h-10 shrink-0 items-center justify-center rounded-2xl bg-amber-200 px-4 text-[12px] font-semibold uppercase tracking-[0.14em] text-stone-950 transition hover:bg-amber-100",onClick:()=>{s({pathname:"/wiki",search:`?spaceId=${encodeURIComponent(X.id)}`})},children:"Open shared memory"})]}):null]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[15rem_minmax(0,1fr)] xl:grid-cols-[16rem_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"wiki-frame h-fit px-2 py-3 sm:px-3 lg:sticky lg:top-[5.75rem]",children:[e.jsx("div",{className:"px-2 pb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Index"}),e.jsx(Bv,{nodes:((je=v.data)==null?void 0:je.tree)??[],activeSlug:$.slug,spaceId:w})]}),e.jsxs("article",{"aria-busy":V,className:te("wiki-frame relative overflow-hidden px-4 py-5 transition-[opacity,transform] duration-200 sm:px-6 sm:py-6",V&&"opacity-[0.985]"),children:[V?e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-[linear-gradient(90deg,transparent,rgba(192,193,255,0.8),transparent)] opacity-90"}):null,e.jsxs("div",{className:"wiki-reading-copy wiki-reading-flow mx-auto max-w-[76rem]",children:[ge.isError?e.jsx("div",{className:"mb-4 rounded-[18px] border border-rose-400/20 bg-rose-500/10 px-4 py-3 text-sm text-rose-100",children:ge.error instanceof Error?ge.error.message:"Forge could not delete this KarpaWiki page."}):null,e.jsx(Kv,{markdown:$.contentMarkdown,spaceId:w}),$.summary.trim()?e.jsx("p",{className:"mt-5 border-t border-white/8 pt-4 text-[13px] leading-6 text-white/56",children:$.summary}):null,z.length>0?e.jsxs("section",{className:"mt-8 border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Forge links"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:z.map(M=>e.jsx("a",{href:M.href?nr(M.href):void 0,className:"rounded-full bg-white/[0.05] px-3 py-1.5 text-[12px] text-white/76 transition hover:bg-white/[0.1] hover:text-white",children:M.label},M.id))})]}):null,B!=null&&B.backlinkSourceNotes.length?e.jsxs("section",{className:"mt-8 border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Linked here"}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:B.backlinkSourceNotes.map(M=>e.jsxs(et,{to:{pathname:M.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(M.slug)}`,search:`?spaceId=${encodeURIComponent(M.spaceId)}`},className:"rounded-xl border border-white/8 bg-white/[0.03] px-4 py-3 transition hover:bg-white/[0.06]",children:[e.jsx("div",{className:"text-[13px] font-semibold text-white",children:M.title}),M.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:M.summary}):null]},M.id))})]}):null]})]})]})]})}),e.jsx(es,{open:l,onOpenChange:o,children:e.jsxs(ts,{children:[e.jsx(ss,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.8)] backdrop-blur-sm"}),e.jsxs(as,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(54rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.96)] p-4 shadow-[0_30px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsx("div",{children:e.jsx(is,{className:"font-display text-[1.35rem] tracking-[-0.04em] text-white",children:"Search the wiki"})}),e.jsx(ds,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close search",children:e.jsx(Lt,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx(be,{autoFocus:!0,value:x,onChange:M=>f(M.target.value),placeholder:"Search KarpaWiki pages",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[["text","hybrid","semantic","entity"].map(M=>e.jsx("button",{type:"button",className:te("rounded-full px-3 py-1.5 text-[12px] font-medium uppercase tracking-[0.14em] transition",p===M?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/54 hover:bg-white/[0.08] hover:text-white"),onClick:()=>g(M),children:M},M)),(p==="semantic"||p==="hybrid")&&P.length>0?e.jsx("select",{className:"ml-auto rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[12px] text-white",value:b,onChange:M=>A(M.target.value),children:P.map(M=>e.jsx("option",{value:M.id,children:M.label},M.id))}):null]})]}),e.jsx("div",{className:"mt-4 max-h-[60vh] overflow-y-auto",children:x.trim()?D.isLoading?e.jsx(zt,{eyebrow:"KarpaWiki search",title:"Searching",description:"Ranking matching pages for this query."}):D.isError?e.jsx(ct,{eyebrow:"KarpaWiki search",error:D.error,onRetry:()=>void D.refetch()}):(Ee=D.data)!=null&&Ee.results.length?e.jsx("div",{className:"grid gap-2",children:D.data.results.map(M=>e.jsx("button",{type:"button",className:"rounded-2xl border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{o(!1),s({pathname:M.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(M.page.slug)}`,search:`?spaceId=${encodeURIComponent(M.page.spaceId)}`})},children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:M.page.title}),M.page.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:M.page.summary}):null]}),e.jsx(S,{size:"sm",tone:"meta",children:M.score.toFixed(2)})]})},M.page.id))}):e.jsx("div",{className:"rounded-2xl border border-dashed border-white/10 px-4 py-10 text-center text-[13px] leading-6 text-white/42",children:"No pages matched this search."}):e.jsx("div",{className:"rounded-2xl border border-dashed border-white/10 px-4 py-10 text-center text-[13px] leading-6 text-white/42",children:"Start typing to search the current KarpaWiki space."})})]})]})}),e.jsx(p_,{open:d,onOpenChange:m,spaces:((Ce=k.data)==null?void 0:Ce.settings.spaces)??[],activeSpaceId:w,onSelect:M=>{s({pathname:"/wiki",search:`?spaceId=${encodeURIComponent(M)}`},{replace:!0})}}),e.jsx(qv,{open:y,onOpenChange:M=>{if(M){me(N);return}se()},spaces:((Ke=k.data)==null?void 0:Ke.settings.spaces)??[],llmProfiles:((Pe=k.data)==null?void 0:Pe.settings.llmProfiles)??[],initialSpaceId:w,selectedJobId:N,onJobSelected:we,linkedEntityHints:$.links.map(M=>({entityType:M.entityType,entityId:M.entityId,anchorKey:null}))??[]})]}):G?e.jsx(zt,{eyebrow:"KarpaWiki",title:"Opening a new page",description:`Creating a draft for ${G}.`}):e.jsx(rs,{eyebrow:"KarpaWiki",title:"Article not found",description:"This page does not exist in the selected space."})}const x_=[{value:"all",label:"All"},{value:"queued",label:"Queued"},{value:"processing",label:"Processing"},{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"review",label:"Review"},{value:"reviewed",label:"Reviewed"}];function g_(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(t))}function f_(t,s){return s==="all"?!0:t.job.status===s||t.job.phase===s}function b_(){var I,y,N,k,w,P;const t=Ht(),s=pt(),[a,i]=ws(),r=a.get("spaceId")||"",n=a.get("q")||"",l=a.get("tag")||"all",o=a.get("from")||"",d=a.get("to")||"",m=a.get("ingest")==="1",h=a.get("ingestJobId"),c=Me({queryKey:["forge-wiki-settings"],queryFn:Od}),p=Me({queryKey:["forge-wiki-ingest-history",r],queryFn:()=>db({spaceId:r||void 0,limit:200}),enabled:c.isSuccess}),g=De({mutationFn:j=>cb(j),onSuccess:async(j,R)=>{if(await s.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),await s.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),h===R){const v=new URLSearchParams(a);v.delete("ingest"),v.delete("ingestJobId"),i(v,{replace:!0})}}}),x=(j,R)=>{const v=new URLSearchParams(a);R.trim()?v.set(j,R.trim()):v.delete(j),i(v,{replace:!0})},f=u.useMemo(()=>{var v;const j=((v=p.data)==null?void 0:v.jobs)??[],R=n.trim().toLowerCase();return j.filter(D=>{if(!f_(D,l))return!1;const L=D.job.createdAt.slice(0,10);return o&&L<o||d&&L>d?!1:R?[D.job.titleHint,D.job.latestMessage,D.job.sourceLocator,D.job.status,D.job.phase,D.job.mimeType].join(" ").toLowerCase().includes(R):!0})},[o,(I=p.data)==null?void 0:I.jobs,n,l,d]),b=r||((N=(y=c.data)==null?void 0:y.settings.spaces[0])==null?void 0:N.id)||"",A=j=>{const R=new URLSearchParams(a);R.set("ingest","1"),j?R.set("ingestJobId",j):R.delete("ingestJobId"),i(R,{replace:!0})},T=()=>{const j=new URLSearchParams(a);j.delete("ingest"),j.delete("ingestJobId"),i(j,{replace:!0})};return c.isLoading||p.isLoading?e.jsx(gs,{eyebrow:"KarpaWiki",title:"Loading ingest history",description:"Gathering prior imports, statuses, and review state.",columns:1,blocks:6}):c.isError||p.isError?e.jsx(ct,{eyebrow:"KarpaWiki",error:c.error??p.error,onRetry:()=>{c.refetch(),p.refetch()}}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto grid w-full max-w-[1480px] gap-5",children:[e.jsx(mt,{title:"KarpaWiki Ingest History",description:"Search prior ingests, reopen a review, or clear ingest records without touching pages and entities that were already published.",badge:`${f.length} matching jobs`}),e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"History Filters"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Narrow by free text, date range, space, or status tags."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(H,{variant:"secondary",onClick:()=>t(`/wiki${r?`?spaceId=${encodeURIComponent(r)}`:""}`),children:"Back to KarpaWiki"}),e.jsxs(H,{onClick:()=>A(),children:[e.jsx(Ut,{className:"size-3.5"}),"New ingest"]})]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,0.8fr)]",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Free text"}),e.jsx(be,{value:n,onChange:j=>x("q",j.target.value),placeholder:"title, source, status, failure message…"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"From"}),e.jsx(be,{type:"date",value:o,onChange:j=>x("from",j.target.value)})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"To"}),e.jsx(be,{type:"date",value:d,onChange:j=>x("to",j.target.value)})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Space"}),e.jsxs("select",{className:"h-11 rounded-[18px] border border-white/10 bg-white/[0.04] px-3 text-sm text-white",value:r,onChange:j=>x("spaceId",j.target.value),children:[e.jsx("option",{value:"",children:"All spaces"}),(((k=c.data)==null?void 0:k.settings.spaces)??[]).map(j=>e.jsx("option",{value:j.id,children:j.label},j.id))]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:x_.map(j=>e.jsx("button",{type:"button",className:te("rounded-full px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition",l===j.value?"bg-[var(--primary)]/[0.18] text-[var(--primary)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),onClick:()=>x("tag",j.value==="all"?"":j.value),children:j.label},j.value))})]}),f.length===0?e.jsx(rs,{eyebrow:"KarpaWiki ingest",title:"No ingest jobs match these filters",description:"Try widening the dates or clearing a status tag."}):e.jsx("div",{className:"grid gap-3",children:f.map(j=>{const R=j.job.titleHint||j.job.latestMessage||j.job.sourceLocator||"KarpaWiki ingest",v=!["queued","processing"].includes(j.job.status);return e.jsxs(le,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>A(j.job.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"KarpaWiki ingest"}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-white/60",children:j.job.status}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-white/44",children:j.job.phase})]}),e.jsx("div",{className:"mt-3 text-lg font-semibold text-white",children:R}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm text-white/56",children:[e.jsxs("span",{children:[j.job.progressPercent,"% · ",j.job.createdPageCount," pages ·"," ",j.job.createdEntityCount," entities"]}),e.jsx("span",{children:g_(j.job.createdAt)}),j.job.sourceLocator?e.jsx("span",{className:"truncate",children:j.job.sourceLocator}):null]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(H,{variant:"secondary",size:"sm",onClick:()=>A(j.job.id),children:"Open review"}),e.jsxs(H,{variant:"secondary",size:"sm",disabled:!v||g.isPending,pending:g.isPending&&g.variables===j.job.id,pendingLabel:"Deleting",onClick:()=>{!v||!window.confirm("Delete this ingest history entry? Published pages and entities will stay, but discarded or unreviewed ingest artifacts will be removed.")||g.mutateAsync(j.job.id)},children:[e.jsx(Wt,{className:"size-3.5"}),"Delete"]})]})]}),j.job.errorMessage?e.jsx("div",{className:"rounded-[18px] border border-rose-400/18 bg-rose-500/[0.08] px-4 py-3 text-sm text-rose-100/86",children:j.job.errorMessage}):null,["queued","processing"].includes(j.job.status)?e.jsxs("div",{className:"inline-flex items-center gap-2 text-sm text-white/50",children:[e.jsx(Cl,{className:"size-4 animate-spin"}),"This ingest is still active and cannot be deleted yet."]}):null]},j.job.id)})})]})}),e.jsx(qv,{open:m,onOpenChange:j=>{j||T()},spaces:((w=c.data)==null?void 0:w.settings.spaces)??[],llmProfiles:((P=c.data)==null?void 0:P.settings.llmProfiles)??[],initialSpaceId:b,selectedJobId:h,onJobSelected:j=>A(j)})]})}function Wr(t,s){return`${t}:${s}`}function y_(t){const s=t.indexOf(":");return s<=0||s>=t.length-1?null:{entityType:t.slice(0,s),entityId:t.slice(s+1)}}function Uv(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Dr(t){return Array.from(new Set(t.split(",").map(s=>s.trim()).filter(Boolean)))}function w_(t){if(!t.trim())return{};try{const s=JSON.parse(t);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}}function Wv(){return{pageId:null,kind:"wiki",title:"",slug:"",parentSlug:"index",indexOrder:0,showInIndex:!0,summary:"",aliasesText:"",contentMarkdown:`# Untitled