forge-openclaw-plugin 0.2.34 → 0.2.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/index-1tJkFTs1.css +1 -0
- package/dist/assets/{index-B5_GwlGE.js → index-BuExFDtM.js} +2 -2
- package/dist/assets/{index-B5_GwlGE.js.map → index-BuExFDtM.js.map} +1 -1
- package/dist/index.html +2 -2
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/dist/assets/index-CAx52RA7.css +0 -1
|
@@ -17,7 +17,7 @@ Route: ${t.definition.routePath??"n/a"}`,output:s,logs:i})}function _S(t,s,a){co
|
|
|
17
17
|
`):"No wiki pages are available.";return wa(t,{primaryText:a,output:{summary:a,pages:s}})}function KS(t){var l,o;const s=((o=(l=t.context.services.wiki).getHealth)==null?void 0:o.call(l))??null,a=Sa(s),i=Array.isArray(a==null?void 0:a.unresolvedLinks)?a.unresolvedLinks.length:null,r=Array.isArray(a==null?void 0:a.orphanPages)?a.orphanPages.length:null,n=a?["Wiki health summary",i!==null?`${i} unresolved links`:null,r!==null?`${r} orphan pages`:null].filter(Boolean).join(`
|
|
18
18
|
`):"No wiki health payload is available.";return wa(t,{primaryText:n,output:a?{summary:n,health:a}:{summary:n}})}const Pf=["text","number","boolean","object","array","json","tool","summary","entity","entity_list","context","metrics","filters","markdown","timeline","selection","record","record_list"],qS={goal:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"status",label:"Status",kind:"text"},{key:"horizon",label:"Horizon",kind:"text"}],project:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"status",label:"Status",kind:"text"},{key:"goalId",label:"Goal id",kind:"text"}],task:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"status",label:"Status",kind:"text"},{key:"priority",label:"Priority",kind:"text"},{key:"projectId",label:"Project id",kind:"text"}],strategy:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"status",label:"Status",kind:"text"},{key:"overview",label:"Overview",kind:"markdown"}],habit:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"status",label:"Status",kind:"text"},{key:"frequency",label:"Frequency",kind:"text"},{key:"polarity",label:"Polarity",kind:"text"}],note:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"summary",label:"Summary",kind:"markdown"},{key:"kind",label:"Kind",kind:"text"},{key:"updatedAt",label:"Updated at",kind:"text"}],insight:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"summary",label:"Summary",kind:"markdown"},{key:"status",label:"Status",kind:"text"}],calendar_event:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"startsAt",label:"Starts at",kind:"text"},{key:"endsAt",label:"Ends at",kind:"text"},{key:"origin",label:"Origin",kind:"text"}],wiki_page:[{key:"id",label:"Id",kind:"text",required:!0},{key:"title",label:"Title",kind:"text",required:!0},{key:"slug",label:"Slug",kind:"text"},{key:"summary",label:"Summary",kind:"markdown"}],sleep_session:[{key:"id",label:"Id",kind:"text",required:!0},{key:"startAt",label:"Start",kind:"text"},{key:"endAt",label:"End",kind:"text"},{key:"totalSleepMinutes",label:"Total sleep minutes",kind:"number"}],workout_session:[{key:"id",label:"Id",kind:"text",required:!0},{key:"type",label:"Type",kind:"text"},{key:"startedAt",label:"Started at",kind:"text"},{key:"durationMinutes",label:"Duration minutes",kind:"number"}]},BS={WorkbenchUserMessage:[{key:"message",label:"Message",kind:"text",required:!0}],WorkbenchUserContext:[{key:"context",label:"Context",kind:"record"}],WorkbenchMergedContext:[{key:"merged",label:"Merged",kind:"record",required:!0}],WorkbenchTemplateOutput:[{key:"rendered",label:"Rendered",kind:"markdown",required:!0}],WorkbenchSelectedValue:[{key:"selected",label:"Selected",kind:"record",required:!0}],WorkbenchPublishedOutput:[{key:"published",label:"Published",kind:"record",required:!0}],WeeklyReviewPayload:[{key:"wins",label:"Wins",kind:"record_list"},{key:"trends",label:"Trends",kind:"record_list"}],InsightsPayload:[{key:"insights",label:"Insights",kind:"record_list"},{key:"heatmap",label:"Heatmap",kind:"record_list"}],OperatorOverviewPayload:[{key:"summary",label:"Summary",kind:"markdown"},{key:"currentWork",label:"Current work",kind:"record_list"}],OperatorContextPayload:[{key:"tasks",label:"Tasks",kind:"record_list"},{key:"focus",label:"Focus",kind:"record_list"}],SleepViewData:[{key:"sessions",label:"Sessions",kind:"record_list"},{key:"metrics",label:"Metrics",kind:"metrics"}]};function US(t){var r,n,l;const s=(r=t.kind)==null?void 0:r.trim().toLowerCase();if(s&&Pf.includes(s))return s;const a=((n=t.key)==null?void 0:n.trim().toLowerCase())??"",i=((l=t.modelName)==null?void 0:l.trim().toLowerCase())??"";return s==="content"?a==="summary"||i.includes("summary")?"summary":a==="answer"||a==="rendered"||i.includes("answer")||i.includes("markdown")||i.includes("template")?"markdown":a==="message"||a==="query"||a==="title"||i.includes("message")?"text":t.itemKind?"entity_list":"record":a.endsWith("count")||a==="limit"?"number":a==="summary"?"summary":a==="answer"||a==="rendered"?"markdown":a==="message"||a==="query"?"text":t.itemKind?"entity_list":"record"}function Qu(t){return t?qS[t]??[]:[]}function Vu(t){return t?BS[t]??[]:[]}function Un(t){const s=US(t),a=Qu(t.itemKind),i=Vu(t.modelName),r=t.shape&&t.shape.length>0?t.shape:a.length>0?a:i;return{...t,kind:s,shape:r.length>0?r:[]}}function Nl(t){return t.map(s=>Un(s))}function WS(t,s){return Object.assign(t,{workbench:{...s,WebView:t}})}function Af(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Wn(t){const s=t.itemKind?Qu(t.itemKind):[],a=t.modelName?Vu(t.modelName):[];return Un({key:t.key,label:t.label,kind:t.kind,description:t.description,required:t.required??!1,modelName:t.modelName,itemKind:t.itemKind,shape:t.shape??(s.length>0?s:a),exampleValue:t.exampleValue})}function Ld(t){const s=t.itemKind?Qu(t.itemKind):[],a=t.modelName?Vu(t.modelName):[];return Un({key:t.key,label:t.label,kind:t.kind,description:t.description,required:t.required??!1,modelName:t.modelName,itemKind:t.itemKind,shape:t.shape??(s.length>0?s:a),exampleValue:t.exampleValue})}function Dd(t){return{key:t.key,label:t.label,kind:t.kind,description:t.description,required:t.required??!1,options:t.options}}function it(t){return Wn({key:"summary",label:(t==null?void 0:t.label)??"Summary",kind:"summary",description:(t==null?void 0:t.description)??"Human-readable summary of what this node currently knows or produced.",modelName:"WorkbenchSummary",exampleValue:t==null?void 0:t.exampleValue})}function gs(t){const s=Af(t.itemKind);return[it({label:t.summaryLabel??"Search summary",description:`Compact summary of the current ${t.itemLabel.toLowerCase()} search results.`}),Wn({key:t.collectionKey??"matches",label:t.collectionLabel??`${t.itemLabel} matches`,kind:"entity_list",description:`Structured ${t.itemLabel.toLowerCase()} records returned by Forge search.`,modelName:`${s}SearchResults`,itemKind:t.itemKind,exampleValue:`[{"id":"...","title":"Example ${t.itemLabel}"}]`}),Wn({key:"matchCount",label:"Match count",kind:"number",description:"Number of records returned by the search.",modelName:`${s}SearchCount`,exampleValue:"12"})]}function Ss(t){const s=Af(t.itemKind);return[Ld({key:"query",label:"Query",kind:"text",description:`Search text for narrowing ${t.itemLabel.toLowerCase()} results.`,modelName:`${s}SearchQuery`,exampleValue:"backlog"}),Ld({key:"entityTypes",label:"Entity types",kind:"array",description:"Entity types to include in the Forge search.",modelName:`${s}SearchEntityTypes`,exampleValue:JSON.stringify(t.defaultEntityTypes??[t.itemKind])}),Ld({key:"limit",label:"Limit",kind:"number",description:"Maximum number of results to request.",modelName:`${s}SearchLimit`,exampleValue:String(t.defaultLimit??20)})]}function Cs(t){return[Dd({key:"query",label:"Default query",kind:"text",description:"Used when no query input edge is connected."}),Dd({key:"entityTypes",label:"Default entity types",kind:"array",description:"Used when no entity types input edge is connected. Enter a JSON array or comma-separated values."}),Dd({key:"limit",label:"Default limit",kind:"number",description:"Used when no limit input edge is connected."})]}function rs(t){return Wn({key:t.key,label:t.label,kind:"context",description:t.description,modelName:t.modelName,shape:t.shape,exampleValue:t.exampleValue})}function Mf(t){return Wn({key:t.key,label:t.label,kind:"record_list",description:t.description,modelName:t.modelName,itemKind:t.itemKind,exampleValue:t.exampleValue})}function cs(t){return{key:"forge.search_entities",label:"Search Forge entities",description:t,accessMode:"read",argsSchema:{type:"object",properties:{query:{type:"string",description:"Search text to match against Forge entities."},entityTypes:{type:"array",items:{type:"string"},description:"Optional entity types to narrow the search."},limit:{type:"number",description:"Maximum number of results to return."}}}}}function Co(t){return{key:"forge.create_note",label:"Create note",description:t,accessMode:"write",argsSchema:{type:"object",properties:{title:{type:"string",description:"Title of the note to create."},summary:{type:"string",description:"Optional short summary for the note."},markdown:{type:"string",description:"Markdown content that should become the note body."}}}}}function Io(t){return{key:"forge.update_task_status",label:"Move task",description:t,accessMode:"write",argsSchema:{type:"object",properties:{taskId:{type:"string",description:"Task id to update."},status:{type:"string",description:"New Forge task status.",enum:["backlog","focus","in_progress","blocked","done"]}}}}}function HS(t){return[t.kind,t.modelName,t.itemKind?`item:${t.itemKind}`:null].filter(Boolean).join(" · ")}function bm({title:t,ports:s,align:a}){return e.jsxs("div",{className:"grid gap-1.5",children:[e.jsxs("div",{className:Z("flex items-center gap-1 text-[10px] uppercase tracking-[0.18em] text-white/34",a==="left"?"text-left":"text-right"),children:[e.jsx("span",{children:t}),e.jsx(yt,{content:a==="left"?"Inputs are values this box expects from upstream nodes.":"Outputs are values this box publishes for downstream nodes.",label:a==="left"?"Explain box inputs":"Explain box outputs"})]}),s.length===0?e.jsx("div",{className:"rounded-full border border-dashed border-white/10 px-3 py-1.5 text-[11px] text-white/28",children:"None"}):null,s.map(i=>e.jsxs("div",{className:Z("relative rounded-[16px] bg-white/[0.05] px-3 py-2 text-[11px] text-white/62",a==="left"?"pl-5 text-left":"pr-5 text-right"),children:[e.jsx(Ux,{type:a==="left"?"target":"source",position:a==="left"?go.Left:go.Right,id:i.key,className:"!size-2.5 !border !border-white/80 !bg-[#b8c5ff]",style:{[a]:6}}),e.jsx("div",{children:i.label}),e.jsx("div",{className:"mt-1 text-[10px] text-white/38",children:HS(i)})]},i.key))]})}function Ot(t){return function(a){const[i,r]=u.useState(!1);return e.jsxs("div",{className:"min-w-[280px] rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(20,28,45,0.98),rgba(11,16,29,0.98))] p-3 shadow-[0_26px_80px_rgba(0,0,0,0.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:"truncate text-sm font-semibold text-white",children:t.title}),e.jsx("div",{className:"mt-1 line-clamp-2 text-[12px] leading-5 text-white/48",children:t.description})]}),e.jsx("div",{className:"rounded-full bg-white/[0.06] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-white/56",children:"box"})]}),t.params.length>0?e.jsxs("div",{className:"mt-3 rounded-[18px] bg-white/[0.04] px-3 py-2 text-[11px] text-white/52",children:[t.params.length," param",t.params.length===1?"":"s"," configurable in the flow editor"]}):null,t.tools.length>0?e.jsxs("div",{className:"mt-2 rounded-[18px] bg-white/[0.04] px-3 py-2 text-[11px] text-white/52",children:[t.tools.length," tool",t.tools.length===1?"":"s"," available"]}):null,e.jsx("div",{className:"mt-2",children:e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.05] px-3 py-1.5 text-[11px] text-white/56 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>r(n=>!n),children:i?"Hide schema":"Preview schema"})}),e.jsxs("div",{className:"mt-3 grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-3",children:[e.jsx(bm,{title:"Inputs",ports:t.inputs,align:"left"}),e.jsx(bm,{title:"Outputs",ports:t.output,align:"right"})]}),i?e.jsxs("div",{className:"mt-3 rounded-[18px] border border-white/8 bg-black/20 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase tracking-[0.18em] text-white/38",children:[e.jsx("span",{children:"Box contract"}),e.jsx(yt,{content:"This preview summarizes what the box consumes, publishes, and what tools it can expose to AI nodes.",label:"Explain box contract preview"})]}),e.jsx("pre",{className:"mt-2 overflow-auto whitespace-pre-wrap text-[11px] leading-5 text-white/64",children:JSON.stringify({inputs:t.inputs.map(({key:n,kind:l,required:o,description:d,modelName:h,itemKind:m,shape:c,exampleValue:g})=>({key:n,kind:l,required:!!o,description:d,modelName:h,itemKind:m,shape:c,exampleValue:g})),outputs:t.output.map(({key:n,kind:l,required:o,description:d,modelName:h,itemKind:m,shape:c,exampleValue:g})=>({key:n,kind:l,required:!!o,description:d,modelName:h,itemKind:m,shape:c,exampleValue:g})),tools:t.tools.map(({key:n,accessMode:l,argsSchema:o})=>({key:n,accessMode:l,argsSchema:o}))},null,2)})]}):null]})}}function GS(t){const s=new Date(t.getFullYear(),t.getMonth(),1),a=(s.getDay()+6)%7,i=new Date(s);return i.setDate(i.getDate()-a),Array.from({length:35},(r,n)=>{const l=new Date(i);return l.setDate(i.getDate()+n),l})}function QS(t,s){return typeof window>"u"?s:window.localStorage.getItem(t)??s}function VS(t,s){typeof window>"u"||window.localStorage.setItem(t,s)}function cl({compact:t}){const[s,a]=u.useState(()=>new Date);return u.useEffect(()=>{const i=window.setInterval(()=>a(new Date),3e4);return()=>window.clearInterval(i)},[]),e.jsxs("div",{className:"flex h-full flex-col justify-between gap-4 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/45",children:[e.jsx($x,{className:"size-4"}),e.jsx("span",{className:"text-[12px] uppercase tracking-[0.16em]",children:"Local time"})]}),e.jsx("div",{className:Z("font-display text-white",t?"text-3xl":"text-5xl"),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(s)}),e.jsx("div",{className:"text-sm text-white/58",children:new Intl.DateTimeFormat(void 0,{weekday:"long",month:"long",day:"numeric"}).format(s)})]})}function ul({compact:t}){const s=new Date,a=u.useMemo(()=>GS(s),[s]),i=t?["M","T","W","T","F","S","S"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];return e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white",children:[e.jsx(ds,{className:"size-4 text-[var(--primary)]"}),new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(s)]}),e.jsx("div",{className:"text-[12px] text-white/45",children:t?"Mini":"Month view"})]}),e.jsxs("div",{className:"grid grid-cols-7 gap-1.5",children:[i.map(r=>e.jsx("div",{className:"text-center text-[11px] uppercase tracking-[0.14em] text-white/35",children:r},r)),a.map(r=>{const n=r.getMonth()===s.getMonth(),l=r.toDateString()===s.toDateString();return e.jsx("div",{className:Z("flex min-h-9 items-center justify-center rounded-xl text-sm",l?"bg-[var(--primary)] text-slate-950":n?"bg-white/[0.04] text-white/78":"bg-transparent text-white/24"),children:r.getDate()},r.toISOString())})]})]})}function hl({surfaceId:t}){const s=`forge.utility.spotify.${t}`,[a,i]=u.useState(()=>QS(s,"https://open.spotify.com/"));return u.useEffect(()=>{VS(s,a)},[s,a]),e.jsxs("div",{className:"grid h-full gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Bw,{className:"size-4 text-[var(--secondary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Spotify link"})]}),e.jsx("input",{value:a,onChange:r=>i(r.target.value),className:"w-full rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2.5 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]",placeholder:"Paste a playlist, album, or artist URL"}),e.jsxs("a",{href:a,target:"_blank",rel:"noreferrer",className:"inline-flex min-h-10 items-center justify-center gap-2 rounded-2xl bg-[rgba(78,222,163,0.14)] px-3 py-2 text-sm font-medium text-[var(--secondary)] transition hover:bg-[rgba(78,222,163,0.22)]",children:["Open Spotify",e.jsx(Ga,{className:"size-4"})]})]})}function ml({compact:t}){const[s,a]=u.useState(null),[i,r]=u.useState("Locating…");return u.useEffect(()=>{if(typeof navigator>"u"||!navigator.geolocation){r("Location unavailable");return}let n=!1;return navigator.geolocation.getCurrentPosition(async l=>{try{const d=await(await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${l.coords.latitude}&longitude=${l.coords.longitude}¤t=temperature_2m,weather_code`)).json();if(n||!d.current)return;a({temperature:Number(d.current.temperature_2m??0),weatherCode:Number(d.current.weather_code??0)}),r("Live")}catch{n||r("Weather unavailable")}},()=>{n||r("Permission denied")},{maximumAge:3e5,timeout:6e3}),()=>{n=!0}},[]),e.jsxs("div",{className:"flex h-full flex-col justify-between gap-4 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Uw,{className:"size-4 text-[var(--tertiary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Weather"})]}),s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Z("font-display text-white",t?"text-3xl":"text-5xl"),children:[Math.round(s.temperature),"°"]}),e.jsxs("div",{className:"text-sm text-white/58",children:["Code ",s.weatherCode," · ",i]})]}):e.jsx("div",{className:"text-sm text-white/58",children:i})]})}function pl({compact:t,defaultUserId:s}){const a=ct(),i=u.useRef(null),r=u.useRef(null),[n,l]=u.useState(""),[o,d]=u.useState(""),h=De({mutationFn:async()=>nl({contentMarkdown:`# ${n.trim()||"Quick note"}
|
|
19
19
|
|
|
20
|
-
${o.trim()}`,author:"Forge quick capture",userId:s??null,links:[]}),onSuccess:async()=>{l(""),d(""),await a.invalidateQueries({queryKey:["notes-index"]})}}),m=De({mutationFn:async()=>kg({title:n.trim()||"Quick capture",contentMarkdown:o.trim(),summary:o.trim().slice(0,180),author:"Forge quick capture"}),onSuccess:async()=>{l(""),d(""),await a.invalidateQueries({queryKey:["wiki-pages"]})}});function c(g,x=g){const p=r.current;if(!p)return;const f=p.selectionStart??0,b=p.selectionEnd??0,M=o.slice(f,b),P=`${o.slice(0,f)}${g}${M}${x}${o.slice(b)}`;d(P),requestAnimationFrame(()=>{p.focus(),p.selectionStart=f+g.length,p.selectionEnd=b+g.length})}return e.jsxs("div",{className:"grid h-full min-h-0 gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(ai,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Quick capture"})]}),e.jsx("input",{ref:i,value:n,onChange:g=>l(g.target.value),className:"w-full rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2.5 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]",placeholder:"Title"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{label:"B",action:()=>c("**")},{label:"I",action:()=>c("_")},{label:"H1",action:()=>c("# ","")},{label:"[]",action:()=>c("- [ ] ","")}].map(g=>e.jsx("button",{type:"button",className:"inline-flex min-h-8 items-center justify-center rounded-xl bg-white/[0.05] px-2.5 text-[12px] font-semibold text-white/72 transition hover:bg-white/[0.08] hover:text-white",onClick:g.action,children:g.label},g.label))}),e.jsx("textarea",{ref:r,value:o,onChange:g=>d(g.target.value),className:Z("min-h-0 w-full rounded-[20px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]",t?"h-28":"h-40"),placeholder:"Write a quick note or rough wiki draft"}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("button",{type:"button",className:"inline-flex min-h-10 items-center justify-center gap-2 rounded-2xl bg-[rgba(192,193,255,0.16)] px-3 py-2 text-sm font-medium text-[var(--primary)] transition hover:bg-[rgba(192,193,255,0.24)] disabled:opacity-50",disabled:!o.trim()||h.isPending,onClick:()=>h.mutate(),children:[e.jsx(ri,{className:"size-4"}),"Save as note"]}),e.jsxs("button",{type:"button",className:"inline-flex min-h-10 items-center justify-center gap-2 rounded-2xl bg-[rgba(255,185,95,0.16)] px-3 py-2 text-sm font-medium text-[var(--tertiary)] transition hover:bg-[rgba(255,185,95,0.24)] disabled:opacity-50",disabled:!o.trim()||m.isPending,onClick:()=>m.mutate(),children:[e.jsx(ai,{className:"size-4"}),"Save as wiki"]})]})]})}const XS={id:"surface:utility:time",surfaceId:"utility",routePath:null,title:"Clock",icon:"timer",description:"Live local time widget.",category:"Utilities",tags:["utility","clock"],inputs:[],params:[],output:[it({label:"Current time",description:"Formatted local time string published by the clock widget."}),rs({key:"clock",label:"Clock state",description:"Structured clock state including the current ISO timestamp.",modelName:"ForgeClockState"})],tools:[],NodeView:Ot({title:"Clock",description:"Live local time widget.",inputs:[],params:[],output:[it({label:"Current time",description:"Formatted local time string published by the clock widget."}),rs({key:"clock",label:"Clock state",description:"Structured clock state including the current ISO timestamp.",modelName:"ForgeClockState"})],tools:[]}),WebView:cl,execute:t=>Pt(t,{clock:{now:t.context.now}},new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.context.now)))};cl.workbench=XS;const YS={id:"surface:utility:mini-calendar",surfaceId:"utility",routePath:null,title:"Mini calendar",icon:"calendar",description:"Compact month calendar widget.",category:"Utilities",tags:["utility","calendar"],inputs:[],params:[],output:[it({label:"Month view",description:"Summary of the compact month calendar widget."}),rs({key:"calendarView",label:"Calendar view",description:"Structured mini-calendar state including the current month anchor.",modelName:"ForgeMiniCalendarView"})],tools:[],NodeView:Ot({title:"Mini calendar",description:"Compact month calendar widget.",inputs:[],params:[],output:[it({label:"Month view",description:"Summary of the compact month calendar widget."}),rs({key:"calendarView",label:"Calendar view",description:"Structured mini-calendar state including the current month anchor.",modelName:"ForgeMiniCalendarView"})],tools:[]}),WebView:ul,execute:t=>Pt(t,{calendarView:{now:t.context.now}},"Compact month calendar")};ul.workbench=YS;const JS={id:"surface:utility:spotify",surfaceId:"utility",routePath:null,title:"Spotify",icon:"music",description:"Pinned music link widget.",category:"Utilities",tags:["utility","spotify"],inputs:[{key:"surfaceId",label:"Surface id",kind:"text",required:!1}],params:[],output:[it({label:"Spotify link",description:"Summary of the pinned music link widget."}),rs({key:"spotifyLink",label:"Spotify state",description:"Structured Spotify widget state and pinned surface context.",modelName:"ForgeSpotifyWidgetState"})],tools:[],NodeView:Ot({title:"Spotify",description:"Pinned music link widget.",inputs:[{key:"surfaceId",label:"Surface id",kind:"text"}],params:[],output:[it({label:"Spotify link",description:"Summary of the pinned music link widget."}),rs({key:"spotifyLink",label:"Spotify state",description:"Structured Spotify widget state and pinned surface context.",modelName:"ForgeSpotifyWidgetState"})],tools:[]}),WebView:hl,execute:t=>Pt(t,{spotifyLink:{surfaceId:t.inputs.surfaceId??null}},"Pinned Spotify link")};hl.workbench=JS;const ZS={id:"surface:utility:weather",surfaceId:"utility",routePath:null,title:"Weather",icon:"weather",description:"Location-aware weather widget.",category:"Utilities",tags:["utility","weather"],inputs:[],params:[],output:[it({label:"Weather summary",description:"Summary of the weather widget state."}),rs({key:"weather",label:"Weather payload",description:"Structured weather widget payload.",modelName:"ForgeWeatherWidgetState"})],tools:[],NodeView:Ot({title:"Weather",description:"Location-aware weather widget.",inputs:[],params:[],output:[it({label:"Weather summary",description:"Summary of the weather widget state."}),rs({key:"weather",label:"Weather payload",description:"Structured weather widget payload.",modelName:"ForgeWeatherWidgetState"})],tools:[]}),WebView:ml,execute:t=>Pt(t,{weather:null},"Weather widget")};ml.workbench=ZS;const e4={id:"surface:utility:quick-capture",surfaceId:"utility",routePath:null,title:"Quick capture",icon:"capture",description:"Draft a quick note or wiki page.",category:"Capture",tags:["capture","notes"],inputs:[{key:"defaultUserId",label:"Default user id",kind:"text",required:!1}],params:[],output:[it({label:"Draft summary",description:"Summary of the quick-capture draft state."}),rs({key:"draft",label:"Draft context",description:"Structured quick-capture draft context.",modelName:"ForgeQuickCaptureDraft"})],tools:[Co("Create a Forge evidence note from captured markdown.")],NodeView:Ot({title:"Quick capture",description:"Draft a quick note or wiki page.",inputs:[{key:"defaultUserId",label:"Default user id",kind:"text"}],params:[],output:[it({label:"Draft summary",description:"Summary of the quick-capture draft state."}),rs({key:"draft",label:"Draft context",description:"Structured quick-capture draft context.",modelName:"ForgeQuickCaptureDraft"})],tools:[Co("Create a Forge evidence note from captured markdown.")]}),WebView:pl,execute:t=>Pt(t,{draft:{defaultUserId:t.inputs.defaultUserId??null}},"Quick capture can draft notes and wiki pages.")};pl.workbench=e4;function ts(t,s){const a=i=>t(i);return a.displayName=s.title.replace(/\s+/g,""),WS(a,s)}function t4({children:t}){return e.jsx(e.Fragment,{children:t})}function Ef(t,s,a,i,r,n){return ts(t4,{id:t,surfaceId:"insights",routePath:"/insights",title:s,icon:"insights",description:a,category:"Insights",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const s4=Ef("surface:insights:feed","Insights feed","Current coaching feed, status summary, and evidence-backed insight stream.",["insights","feed"],t=>Tf(t),[it({label:"Insight summary",description:"Summary of the current coaching feed and evidence-backed insight stream."}),rs({key:"insights",label:"Insight payload",description:"Structured status and coaching payload returned by Forge insights.",modelName:"ForgeInsightsPayload"})]),a4=Ef("surface:insights:coaching","Coaching recommendation","Single-action coaching summary for what Forge thinks matters next.",["insights","coaching"],t=>Pt(t,{focus:"coaching_recommendation"},"Coaching recommendation surface for the highest-leverage next move."),[it({label:"Coaching recommendation",description:"Summary of the highest-leverage coaching recommendation."})]);function Xu({children:t}){return e.jsx(e.Fragment,{children:t})}const Er=Ss({itemKind:"task",itemLabel:"Task",defaultEntityTypes:["task"],defaultLimit:24}),Lr=Cs(),Lf=ts(Xu,{id:"surface:kanban-index:summary",surfaceId:"kanban-index",routePath:"/kanban",title:"Kanban summary",icon:"kanban",description:"Board summary and execution posture.",category:"Execution",tags:["kanban","summary"],inputs:Er,params:Lr,output:[it({label:"Kanban summary",description:"Summary of board posture and execution pressure."})],tools:[],NodeView:Ot({title:"Kanban summary",description:"Board summary and execution posture.",inputs:Er,params:Lr,output:[it({label:"Kanban summary",description:"Summary of board posture and execution pressure."})],tools:[]}),execute:t=>ps(t,{query:"",entityTypes:["task"],limit:24})}),Df=ts(Xu,{id:"surface:kanban-index:filters",surfaceId:"kanban-index",routePath:"/kanban",title:"Kanban filters",icon:"filter",description:"Goal, owner, and tag filters for board scope.",category:"Execution",tags:["kanban","filters"],inputs:Er,params:Lr,output:[it({label:"Filter summary",description:"Summary of the current Kanban filters and scope."})],tools:[cs("Search Forge entities by query and entity types.")],NodeView:Ot({title:"Kanban filters",description:"Goal, owner, and tag filters for board scope.",inputs:Er,params:Lr,output:[it({label:"Filter summary",description:"Summary of the current Kanban filters and scope."})],tools:[cs("Search Forge entities by query and entity types.")]}),execute:t=>ps(t,{query:"",entityTypes:["task"],limit:24})}),Ff=ts(Xu,{id:"surface:kanban-index:board",surfaceId:"kanban-index",routePath:"/kanban",title:"Kanban board",icon:"board",description:"Task board with move and execution actions.",category:"Execution",tags:["kanban","board","tasks"],inputs:Er,params:Lr,output:gs({itemKind:"kanban_task",itemLabel:"Kanban task"}),tools:[cs("Search Forge entities by query and entity types."),Io("Update a task status.")],NodeView:Ot({title:"Kanban board",description:"Task board with move and execution actions.",inputs:Er,params:Lr,output:gs({itemKind:"kanban_task",itemLabel:"Kanban task"}),tools:[cs("Search Forge entities by query and entity types."),Io("Update a task status.")]}),execute:t=>ps(t,{query:"",entityTypes:["task"],limit:24})});function i4({children:t}){return e.jsx(e.Fragment,{children:t})}function Yu(t,s,a,i,r,n,l,o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(i4,{id:t,surfaceId:"calendar",routePath:"/calendar",title:s,icon:"calendar",description:a,category:"Calendar",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const r4=Yu("surface:calendar:overview","Calendar overview","Main calendar surface for mirrored events, work blocks, and planned timeboxes.",["calendar","overview"],t=>Pt(t,{surfaces:["events","work_blocks","timeboxes"]},"Calendar overview spanning mirrored events, work blocks, and timeboxes."),[it({label:"Calendar summary",description:"Summary of mirrored events, work blocks, and timeboxes."})],[]),n4=Yu("surface:calendar:events","Calendar events","Mirrored calendar events and Forge-managed calendar records.",["calendar","events","mirrored"],t=>ps(t,{query:"",entityTypes:["calendar_event"],limit:20}),gs({itemKind:"calendar_event",itemLabel:"Calendar event"}),[cs("Search calendar-backed Forge entities and planning records.")],{inputs:Ss({itemKind:"calendar_event",itemLabel:"Calendar event",defaultEntityTypes:["calendar_event"],defaultLimit:20}),params:Cs()}),l4=Yu("surface:calendar:planning","Planning blocks","Planned task timeboxes and reusable work block templates.",["calendar","planning","timeboxes"],t=>ps(t,{query:"",entityTypes:["task_timebox","work_block_template"],limit:20}),gs({itemKind:"calendar_plan",itemLabel:"Planning record"}),[cs("Search calendar-backed Forge entities and planning records.")],{inputs:Ss({itemKind:"calendar_plan",itemLabel:"Planning record",defaultEntityTypes:["task_timebox","work_block_template"],defaultLimit:20}),params:Cs()});function o4({children:t}){return e.jsx(e.Fragment,{children:t})}function Ju(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(o4,{id:t,surfaceId:"goals",routePath:"/goals",title:s,icon:"goal",description:a,category:"Goals",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const d4=Ju("surface:goals:hero","Goals hero","Goals page header and long-horizon direction context.",["goals","hero"],t=>Pt(t,null,"Goals page header."),[it({label:"Goals summary",description:"High-level goals page framing."})]),c4=Ju("surface:goals:search-results","Goals list and results","Goal browser, linked context, and search results.",["goals","search"],t=>ps(t,{query:"",entityTypes:["goal"],limit:20}),gs({itemKind:"goal",itemLabel:"Goal"}),[cs("Search goal entities by query and entity types.")],{inputs:Ss({itemKind:"goal",itemLabel:"Goal",defaultEntityTypes:["goal"],defaultLimit:20}),params:Cs()}),u4=Ju("surface:goals:summary","Goals summary","Goal collection summary and state context.",["goals","summary"],t=>Pt(t,null,"Goal collection summary."),[it({label:"Goals summary",description:"Summary of the goal collection and its current state."})]);function h4({children:t}){return e.jsx(e.Fragment,{children:t})}function Zu(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(h4,{id:t,surfaceId:"habits",routePath:"/habits",title:s,icon:"habit",description:a,category:"Habits",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const m4=Zu("surface:habits:hero","Habits hero","Habits page header and recurring execution context.",["habits","hero"],t=>Pt(t,null,"Habits page header."),[it({label:"Habits summary",description:"High-level habits page framing."})]),p4=Zu("surface:habits:search-results","Habits list and results","Habit browser, due habits, and recurring check-in context.",["habits","search","check-ins"],t=>ps(t,{query:"",entityTypes:["habit"],limit:20}),gs({itemKind:"habit",itemLabel:"Habit"}),[cs("Search habit entities by query and entity types.")],{inputs:Ss({itemKind:"habit",itemLabel:"Habit",defaultEntityTypes:["habit"],defaultLimit:20}),params:Cs()}),x4=Zu("surface:habits:summary","Habits summary","Habit streaks, due state, and collection-level rhythm context.",["habits","summary","streaks"],t=>Pt(t,null,"Habit collection summary."),[it({label:"Habit summary",description:"Summary of habit streaks, due state, and collection rhythm."})]);function g4({children:t}){return e.jsx(e.Fragment,{children:t})}function qr(t){return ts(g4,{id:t.id,surfaceId:t.surfaceId,routePath:t.routePath,title:t.title,icon:t.surfaceId,description:t.description,category:t.category,tags:t.tags,inputs:[],params:[],output:t.output,tools:[],NodeView:Ot({title:t.title,description:t.description,inputs:[],params:[],output:t.output,tools:[]}),execute:t.execute})}const _f=qr({id:"surface:sleep-index:summary",surfaceId:"sleep-index",routePath:"/sleep",title:"Sleep summary",description:"Recent nightly sleep metrics and recovery posture.",category:"Sleep",tags:["sleep","summary"],execute:t=>Hu(t),output:[it({label:"Sleep summary",description:"Summary of recent sleep and recovery posture."}),rs({key:"sleepView",label:"Sleep view",description:"Structured sleep history and derived sleep patterns.",modelName:"ForgeSleepView"})]}),Rf=qr({id:"surface:sleep-index:patterns",surfaceId:"sleep-index",routePath:"/sleep",title:"Sleep patterns",description:"Weekly baseline, stage mix, and timing patterns around canonical nights.",category:"Sleep",tags:["sleep","patterns"],execute:t=>Hu(t),output:[it({label:"Sleep pattern summary",description:"Summary of trend, stage averages, and recovery state."}),rs({key:"sleepView",label:"Sleep view",description:"Structured sleep trend, stage averages, and recovery signals.",modelName:"ForgeSleepView"})]}),$f=qr({id:"surface:sleep-index:browser",surfaceId:"sleep-index",routePath:"/sleep",title:"Night detail",description:"Interactive sleep calendar, selected-night detail, and optional raw evidence.",category:"Sleep",tags:["sleep","browser","history"],execute:t=>Hu(t),output:[it({label:"Night detail summary",description:"Summary of the sleep calendar and selected-night detail."}),rs({key:"sleepView",label:"Sleep view",description:"Structured canonical nights, calendar summaries, and phase detail.",modelName:"ForgeSleepView"})]}),Of=qr({id:"surface:sports-index:summary",surfaceId:"sports-index",routePath:"/sports",title:"Sports summary",description:"Recent workout metrics, streaks, and linked-session totals.",category:"Sports",tags:["sports","summary"],execute:t=>Gu(t),output:[it({label:"Sports summary",description:"Summary of recent workout metrics and streaks."}),rs({key:"sportsView",label:"Sports view",description:"Structured workout metrics, streaks, and linked session totals.",modelName:"ForgeSportsView"})]}),zf=qr({id:"surface:sports-index:composition",surfaceId:"sports-index",routePath:"/sports",title:"Training composition",description:"Workout mix, trend, and session composition context.",category:"Sports",tags:["sports","composition","trend"],execute:t=>Gu(t),output:[it({label:"Composition summary",description:"Summary of workout mix, trend, and session composition."}),rs({key:"sportsView",label:"Sports view",description:"Structured workout mix, trend, and session composition data.",modelName:"ForgeSportsView"})]}),Kf=qr({id:"surface:sports-index:browser",surfaceId:"sports-index",routePath:"/sports",title:"Session browser",description:"Searchable and virtualized workout history browser.",category:"Sports",tags:["sports","browser","history"],execute:t=>Gu(t),output:[it({label:"Session browser summary",description:"Summary of searchable workout history."}),rs({key:"sportsView",label:"Sports view",description:"Structured workout history for browsing and analysis.",modelName:"ForgeSportsView"})]});function f4({children:t}){return e.jsx(e.Fragment,{children:t})}function xl(t,s,a,i,r,n){return ts(f4,{id:t,surfaceId:"movement-index",routePath:"/movement",title:s,icon:"movement",description:a,category:"Movement",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const qf=xl("surface:movement-index:summary","Movement summary","Tracking mode, daily totals, and passive capture posture.",["movement","summary"],t=>Pt(t,null,"Movement summary is available."),[it({label:"Movement summary",description:"Summary of tracking mode, daily totals, and passive capture posture."})]),Bf=xl("surface:movement-index:selection","Movement selection aggregate","Selected-stay and selected-trip aggregate totals.",["movement","selection","aggregate"],t=>Pt(t,null,"Selected stay and trip aggregate totals."),[it({label:"Selection summary",description:"Summary of selected-stay and selected-trip aggregates."})]),Uf=xl("surface:movement-index:timeline","Movement life timeline","Life-scale stay and trip timeline with edit access.",["movement","timeline","life"],t=>Pt(t,null,"Movement life timeline with stay and trip history."),[it({label:"Timeline summary",description:"Summary of the movement life timeline and trip history."})]),Wf=xl("surface:movement-index:places","Known places","Known places, aliases, and category tags.",["movement","places"],t=>RS(t),[it({label:"Places summary",description:"Summary of known places, aliases, and category tags."}),Mf({key:"places",label:"Known places",description:"Structured list of places known to Forge movement tracking.",modelName:"ForgeMovementPlaces",itemKind:"movement_place"})]),Hf=xl("surface:movement-index:data-browser","Movement data browser","Datapoint browsing, invalid records, and movement data cleanup.",["movement","data","browser"],t=>Pt(t,null,"Movement datapoint browser with cleanup actions."),[it({label:"Data browser summary",description:"Summary of movement datapoint browsing and cleanup."})]);function eh({children:t}){return e.jsx(e.Fragment,{children:t})}const To=Ss({itemKind:"note",itemLabel:"Note",defaultEntityTypes:["note"],defaultLimit:20}),Po=Cs(),Gf=ts(eh,{id:"surface:notes-index:filters",surfaceId:"notes-index",routePath:"/notes",title:"Note filters",icon:"filter",description:"Entity, tag, text, author, and date filters for notes.",category:"Notes",tags:["notes","filters","search"],inputs:To,params:Po,output:[it({label:"Filter summary",description:"Summary of the current note filters and search scope."})],tools:[cs("Search Forge entities by query and entity types.")],NodeView:Ot({title:"Note filters",description:"Entity, tag, text, author, and date filters for notes.",inputs:To,params:Po,output:[it({label:"Filter summary",description:"Summary of the current note filters and search scope."})],tools:[cs("Search Forge entities by query and entity types.")]}),execute:t=>ps(t,{query:"",entityTypes:["note"],limit:20})}),Qf=ts(eh,{id:"surface:notes-index:composer",surfaceId:"notes-index",routePath:"/notes",title:"Note composer",icon:"write",description:"Markdown note composer with links, tags, and capture actions.",category:"Notes",tags:["notes","composer","capture"],inputs:To,params:Po,output:[it({label:"Draft summary",description:"Summary of the current note drafting surface."})],tools:[Co("Create an evidence note from markdown content.")],NodeView:Ot({title:"Note composer",description:"Markdown note composer with links, tags, and capture actions.",inputs:To,params:Po,output:[it({label:"Draft summary",description:"Summary of the current note drafting surface."})],tools:[Co("Create an evidence note from markdown content.")]}),execute:t=>Pt(t,{draftable:!0},"This node can draft or create a note.")}),Vf=ts(eh,{id:"surface:notes-index:library",surfaceId:"notes-index",routePath:"/notes",title:"Notes library",icon:"library",description:"Filtered library of Forge notes and linked evidence.",category:"Notes",tags:["notes","library","history"],inputs:[],params:[],output:gs({itemKind:"note",itemLabel:"Note"}),tools:[],NodeView:Ot({title:"Notes library",description:"Filtered library of Forge notes and linked evidence.",inputs:[],params:[],output:gs({itemKind:"note",itemLabel:"Note"}),tools:[]}),execute:t=>ps(t,{query:"",entityTypes:["note"],limit:20})});function b4({children:t}){return e.jsx(e.Fragment,{children:t})}function th(t,s,a,i,r,n){return ts(b4,{id:t,surfaceId:"overview",routePath:"/overview",title:s,icon:"overview",description:a,category:"Overview",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const v4=th("surface:overview:snapshot","Forge snapshot","Live overview of goals, projects, tasks, habits, and current operating pressure.",["overview","snapshot"],t=>$S(t),[it({label:"Overview summary",description:"Compact summary of goals, projects, tasks, and habits."}),rs({key:"context",label:"Overview context",description:"Structured Forge overview context for the current operating picture.",modelName:"ForgeOverviewContext"})]),w4=th("surface:overview:momentum","Momentum and health","Momentum-focused summary of streaks, neglected areas, and active execution pressure.",["overview","momentum"],t=>Pt(t,{dimensions:["momentum","neglected_goals","domain_balance"]},"Overview momentum surface tracking neglected goals, domain balance, and execution pressure."),[it({label:"Momentum summary",description:"Summary of momentum, neglected goals, and execution pressure."})]),y4=th("surface:overview:insights","Overview insights","Insight-oriented summary of the current Forge operating picture.",["overview","insights"],t=>Tf(t),[it({label:"Insight summary",description:"Compact explanation of the current insight payload."}),rs({key:"insights",label:"Insight payload",description:"Structured insight and coaching payload returned by Forge.",modelName:"ForgeInsightsPayload"})]);function j4({children:t}){return e.jsx(e.Fragment,{children:t})}function sh(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(j4,{id:t,surfaceId:"projects",routePath:"/projects",title:s,icon:"projects",description:a,category:"Projects",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const Xf=sh("surface:projects:hero","Projects hero","Projects page header.",["projects","hero"],t=>Pt(t,null,"Projects page header."),[it({label:"Projects summary",description:"High-level projects page framing."})]),Yf=sh("surface:projects:search-results","Search and results","Project browser, filters, and search context.",["projects","search"],t=>ps(t,{query:"",entityTypes:["project"],limit:20}),gs({itemKind:"project",itemLabel:"Project"}),[cs("Search project entities by query and entity types.")],{inputs:Ss({itemKind:"project",itemLabel:"Project",defaultEntityTypes:["project"],defaultLimit:20}),params:Cs()}),Jf=sh("surface:projects:summary","Collection summary","Collection summary and project state metrics.",["projects","summary"],t=>Pt(t,null,"Project collection summary."),[it({label:"Project summary",description:"Summary of the project collection and current state."})]);function N4({children:t}){return e.jsx(e.Fragment,{children:t})}function ah(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(N4,{id:t,surfaceId:"preferences",routePath:"/preferences",title:s,icon:"preferences",description:a,category:"Preferences",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const k4=ah("surface:preferences:workspace","Preferences workspace","Main preference modeling workspace, including summaries, tradeoffs, and evidence.",["preferences","workspace"],t=>Pt(t,{surfaces:["summary","comparison_game","evidence"]},"Preferences workspace with summary, pairwise comparison, and evidence views."),[it({label:"Preference summary",description:"Summary of the active preference modeling workspace."})]),S4=ah("surface:preferences:contexts","Preference contexts","Preference contexts that shape which tradeoffs and evidence are active.",["preferences","contexts"],t=>ps(t,{query:"",entityTypes:["preference_context"],limit:20}),gs({itemKind:"preference_context",itemLabel:"Preference context"}),[cs("Search preference contexts and modeled preference items.")],{inputs:Ss({itemKind:"preference_context",itemLabel:"Preference context",defaultEntityTypes:["preference_context"],defaultLimit:20}),params:Cs()}),C4=ah("surface:preferences:items","Preference items","Preference items scored and compared inside the active context.",["preferences","items"],t=>ps(t,{query:"",entityTypes:["preference_item"],limit:20}),gs({itemKind:"preference_item",itemLabel:"Preference item"}),[cs("Search preference contexts and modeled preference items.")],{inputs:Ss({itemKind:"preference_item",itemLabel:"Preference item",defaultEntityTypes:["preference_item"],defaultLimit:20}),params:Cs()});function I4({children:t}){return e.jsx(e.Fragment,{children:t})}function ih(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(I4,{id:t,surfaceId:"psyche",routePath:"/psyche",title:s,icon:"psyche",description:a,category:"Psyche",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const T4=ih("surface:psyche:overview","Psyche overview","High-level overview of values, patterns, beliefs, modes, and reports.",["psyche","overview"],t=>Pt(t,{surfaces:["values","patterns","beliefs","modes","reports"]},"Psyche overview spanning values, patterns, beliefs, modes, and reports."),[it({label:"Psyche summary",description:"Summary of values, patterns, beliefs, modes, and reports."})]),P4=ih("surface:psyche:values","Psyche values","Values and long-lived internal directions tracked inside Forge.",["psyche","values"],t=>ps(t,{query:"",entityTypes:["psyche_value"],limit:20}),gs({itemKind:"psyche_value",itemLabel:"Psyche value"}),[cs("Search psyche entities and reflective records.")],{inputs:Ss({itemKind:"psyche_value",itemLabel:"Psyche value",defaultEntityTypes:["psyche_value"],defaultLimit:20}),params:Cs()}),A4=ih("surface:psyche:reports","Trigger reports","Trigger reports and behavior-pattern signals linked to reflective work.",["psyche","reports","patterns"],t=>ps(t,{query:"",entityTypes:["trigger_report","behavior_pattern","belief_entry","mode_profile"],limit:20}),gs({itemKind:"psyche_record",itemLabel:"Psyche record"}),[cs("Search psyche entities and reflective records.")],{inputs:Ss({itemKind:"psyche_record",itemLabel:"Psyche record",defaultEntityTypes:["trigger_report","behavior_pattern","belief_entry","mode_profile"],defaultLimit:20}),params:Cs()});function M4({children:t}){return e.jsx(e.Fragment,{children:t})}function rh(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(M4,{id:t,surfaceId:"questionnaires",routePath:"/psyche/questionnaires",title:s,icon:"questionnaire",description:a,category:"Questionnaires",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const E4=rh("surface:questionnaires:library","Questionnaire library","Library of questionnaire instruments available in Forge.",["questionnaires","library"],t=>ps(t,{query:"",entityTypes:["questionnaire_instrument"],limit:20}),gs({itemKind:"questionnaire_instrument",itemLabel:"Questionnaire"}),[cs("Search questionnaire instruments and related records.")],{inputs:Ss({itemKind:"questionnaire_instrument",itemLabel:"Questionnaire",defaultEntityTypes:["questionnaire_instrument"],defaultLimit:20}),params:Cs()}),L4=rh("surface:questionnaires:drafting","Questionnaire drafting","Drafting and publishing context for questionnaire instruments.",["questionnaires","drafting","authoring"],t=>Pt(t,{states:["draft","published","run"]},"Questionnaire drafting surface with draft, publish, and run lifecycle context."),[it({label:"Drafting summary",description:"Summary of questionnaire drafting and lifecycle context."})]),D4=rh("surface:questionnaires:self-observation","Self-observation calendar","Calendar of self-observation notes and linked psyche context.",["questionnaires","self-observation","psyche"],t=>Pt(t,{linkedDomains:["patterns","reports","notes"]},"Self-observation calendar surface with linked psyche context."),[it({label:"Observation summary",description:"Summary of the self-observation calendar and linked psyche context."})]);function F4({children:t}){return e.jsx(e.Fragment,{children:t})}function Zf(t,s,a,i,r,n){return ts(F4,{id:t,surfaceId:"review",routePath:"/review/weekly",title:s,icon:"review",description:a,category:"Review",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const _4=Zf("surface:review:weekly-summary","Weekly review summary","Weekly review payload with momentum, wins, calibration, and completion state.",["review","weekly"],t=>OS(t),[it({label:"Weekly review summary",description:"Summary of momentum, wins, calibration, and review completion state."}),rs({key:"weeklyReview",label:"Weekly review payload",description:"Structured weekly review payload returned by Forge.",modelName:"ForgeWeeklyReview"})]),R4=Zf("surface:review:reward","Review reward","Reward framing and completion incentive for closing the current review cycle.",["review","reward"],t=>Pt(t,{reward:"weekly_review_completion"},"Weekly review reward surface for locking the current cycle into evidence."),[it({label:"Review reward summary",description:"Summary of the reward framing for closing the current review cycle."})]);function $4({children:t}){return e.jsx(e.Fragment,{children:t})}function nh(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts($4,{id:t,surfaceId:"strategies",routePath:"/strategies",title:s,icon:"strategy",description:a,category:"Strategies",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const O4=nh("surface:strategies:hero","Strategies hero","Strategies page header and sequencing context.",["strategies","hero"],t=>Pt(t,null,"Strategies page header."),[it({label:"Strategies summary",description:"High-level strategies page framing."})]),z4=nh("surface:strategies:search-results","Strategies list and results","Strategy browser and structured operating context.",["strategies","search"],t=>ps(t,{query:"",entityTypes:["strategy"],limit:20}),gs({itemKind:"strategy",itemLabel:"Strategy"}),[cs("Search strategy entities by query and entity types.")],{inputs:Ss({itemKind:"strategy",itemLabel:"Strategy",defaultEntityTypes:["strategy"],defaultLimit:20}),params:Cs()}),K4=nh("surface:strategies:summary","Strategies summary","Strategy collection summary and state context.",["strategies","summary"],t=>Pt(t,null,"Strategy collection summary."),[it({label:"Strategy summary",description:"Summary of strategy state and collection context."})]);function q4({children:t}){return e.jsx(e.Fragment,{children:t})}function lh(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(q4,{id:t,surfaceId:"tasks",routePath:"/today",title:s,icon:"task",description:a,category:"Tasks",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const B4=lh("surface:tasks:inbox","Task queue","Searchable task queue spanning backlog, focus, and in-progress work.",["tasks","queue","search"],t=>ps(t,{query:"",entityTypes:["task"],limit:20}),gs({itemKind:"task",itemLabel:"Task"}),[cs("Search task entities by title, status, or linked context."),Io("Move a task between backlog, focus, in progress, blocked, and done.")],{inputs:Ss({itemKind:"task",itemLabel:"Task",defaultEntityTypes:["task"],defaultLimit:20}),params:Cs()}),U4=lh("surface:tasks:focus-lane","Focus lane","Focused task lane for what should happen next right now.",["tasks","focus","execution"],t=>Pt(t,{hint:"Use this surface to represent active or next-up work."},"Focus lane context for the current execution board."),[it({label:"Focus summary",description:"Human-readable explanation of what the focus lane represents."})],[Io("Change task state as the flow decides what should happen next.")]),W4=lh("surface:tasks:summary","Task summary","High-level summary of the current task system and work state.",["tasks","summary"],t=>Pt(t,{states:["backlog","focus","in_progress","blocked","done"]},"Task system summary with the key task states Forge tracks."),[it({label:"Task summary",description:"High-level summary of the current task system and work state."})]);function H4({children:t}){return e.jsx(e.Fragment,{children:t})}function gl(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(H4,{id:t,surfaceId:"today",routePath:"/today",title:s,icon:"today",description:a,category:"Today",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const eb=gl("surface:today:hero","Today hero","Daily execution header and directive.",["today","hero"],t=>Pt(t,null,"Daily execution header."),[it({label:"Today summary",description:"High-level framing for today's execution."})]),tb=gl("surface:today:metrics","Live metrics","Daily XP, level, and momentum metrics.",["today","metrics"],t=>Pt(t,null,"Daily metrics."),[it({label:"Metrics summary",description:"Summary of today's XP, level, and momentum metrics."})]),sb=gl("surface:today:runway","Runway","Execution lane and current work.",["today","execution"],t=>ps(t,{query:"",entityTypes:["task","habit"],limit:16}),gs({itemKind:"execution_item",itemLabel:"Execution item"}),[cs("Search today's active tasks and habits by query and entity types.")],{inputs:Ss({itemKind:"execution_item",itemLabel:"Execution item",defaultEntityTypes:["task","habit"],defaultLimit:16}),params:Cs()}),ab=gl("surface:today:calendar","Calendar","Calendar context for today.",["today","calendar"],t=>Pt(t,null,"Today's calendar context."),[it({label:"Calendar summary",description:"Summary of today's calendar context."})]),ib=gl("surface:today:focus","Current focus","Today priorities and focus context.",["today","focus"],t=>ps(t,{query:"",entityTypes:["task","habit"],limit:16}),gs({itemKind:"focus_item",itemLabel:"Focus item"}),[cs("Search today's priority tasks and habits by query and entity types.")],{inputs:Ss({itemKind:"focus_item",itemLabel:"Focus item",defaultEntityTypes:["task","habit"],defaultLimit:16}),params:Cs()});function G4({children:t}){return e.jsx(e.Fragment,{children:t})}function oh(t,s,a,i,r,n){return ts(G4,{id:t,surfaceId:"wiki",routePath:"/wiki",title:s,icon:"wiki",description:a,category:"Wiki",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const Q4=oh("surface:wiki:pages","Wiki pages","Live list of wiki pages that can be used as memory or authored knowledge.",["wiki","pages"],t=>zS(t),[it({label:"Wiki page summary",description:"Summary of the currently available wiki pages."}),Mf({key:"pages",label:"Wiki pages",description:"Structured wiki page records available in Forge memory.",modelName:"ForgeWikiPages",itemKind:"wiki_page"})]),V4=oh("surface:wiki:health","Wiki health","Index health, unresolved links, and orphaned-page signals for the wiki.",["wiki","health"],t=>KS(t),[it({label:"Wiki health summary",description:"Summary of unresolved links and orphaned-page signals."}),rs({key:"health",label:"Wiki health",description:"Structured wiki health payload returned by Forge.",modelName:"ForgeWikiHealth"})]),X4=oh("surface:wiki:authoring","Wiki authoring","Authoring and ingest surface for creating or refining Forge memory.",["wiki","authoring","ingest"],t=>Pt(t,{actions:["upsert","ingest","reindex"]},"Wiki authoring surface for ingesting sources and maintaining memory pages."),[it({label:"Wiki authoring summary",description:"Summary of wiki authoring and ingest actions available on this surface."})]),Y4=[cl,ul,hl,ml,pl,r4,n4,l4,d4,c4,u4,m4,p4,x4,s4,a4,Lf,Df,Ff,Gf,Qf,Vf,v4,w4,y4,qf,Bf,Uf,Wf,Hf,_f,Rf,$f,Of,zf,Kf,Xf,Yf,Jf,k4,S4,C4,T4,P4,A4,E4,L4,D4,_4,R4,O4,z4,K4,B4,U4,W4,eb,tb,sb,ab,ib,Q4,V4,X4],rb=new Map(Y4.filter(t=>t.workbench).map(t=>[t.workbench.id,t.workbench]));function dh(){return Array.from(rb.values())}function nb(t){return rb.get(t)??null}function lb(){return dh().map(t=>({id:t.id,boxId:t.id,surfaceId:t.surfaceId,routePath:t.routePath,title:t.title,label:t.title,icon:t.icon??null,description:t.description,category:t.category,tags:t.tags,capabilityModes:["content",...t.tools.length>0?["tool"]:[]],inputs:Nl(t.inputs),params:Nl(t.params),output:Nl(t.output),tools:t.tools,outputs:Nl(t.output),toolAdapters:t.tools,snapshotResolverKey:void 0}))}const ob=u.createContext(null),J4={definitions:dh(),catalog:lb(),getDefinition:nb};function Z4({children:t}){const s=u.useMemo(()=>({definitions:dh(),catalog:lb(),getDefinition:nb}),[]);return e.jsx(ob.Provider,{value:s,children:t})}function db(){return u.useContext(ob)??J4}function e5(){return db().catalog}function t5(t){const s=db();return t?s.getDefinition(t):null}function s5({children:t}){return e.jsx(e.Fragment,{children:t})}function a5({children:t}){return e.jsx(e.Fragment,{children:t})}function Fd(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g," ")}function i5({eyebrow:t,titleText:s,entityKind:a,copyMode:i}){if(!t||i==="title_only"||typeof t!="string")return null;const r=Fd(t),n=s?Fd(s):null,l=a?Fd(Bs(a).label):null;return!r||n&&(r===n||n.includes(r)||r.includes(n))||l&&r===l?null:t}function rt({eyebrow:t,entityKind:s,title:a,titleText:i,description:r,badge:n,actions:l,copyMode:o="title_only"}){const d=s?Bs(s):null,h=d==null?void 0:d.icon,m=i5({eyebrow:t,titleText:i,entityKind:s,copyMode:o}),c=!!(d||m||n);return e.jsxs("header",{className:"relative min-w-0 w-full max-w-full overflow-hidden border-b border-white/6 px-5 py-5 sm:px-6 lg:grid lg:grid-cols-[minmax(0,1fr)_auto] lg:items-end lg:px-7 lg:py-6",style:{background:"var(--hero-gradient)",paddingTop:"var(--forge-shell-hero-padding-top)",paddingBottom:"var(--forge-shell-hero-padding-bottom)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{background:"radial-gradient(circle at top right, color-mix(in srgb, var(--forge-body-ambient-primary) 94%, transparent), transparent 34%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-white/10"}),e.jsxs("div",{className:"relative min-w-0 w-full max-w-full",children:[c?e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 text-[11px] font-medium uppercase tracking-[0.2em] text-white/40",children:[d&&h?e.jsxs("span",{className:"inline-flex items-center gap-2 text-white/56","aria-label":d.label,title:d.label,children:[e.jsx(h,{className:Z("size-3.5",d.iconClassName)}),e.jsx("span",{children:d.label})]}):null,m?e.jsx("span",{className:"text-[var(--secondary)]/80",children:m}):null,n?e.jsx(I,{tone:"signal",className:"h-8 rounded-full border border-white/8 bg-white/[0.04] px-3 text-[11px] font-medium tracking-[0.14em] text-white/80 uppercase",children:n}):null]}):null,e.jsx("div",{className:Z("min-w-0 max-w-4xl text-[clamp(1.85rem,3.5vw,4rem)] font-medium leading-[0.92] text-white",c?"mt-3":""),style:{transform:"translateY(var(--forge-shell-hero-title-translate-y)) scale(var(--forge-shell-hero-title-scale))",transformOrigin:"top left",willChange:"transform"},children:a}),e.jsx("div",{className:"mt-2 min-w-0 max-w-3xl text-[14px] leading-6 text-white/58 sm:text-[15px]",style:{opacity:"var(--forge-shell-hero-description-opacity)",transform:"translateY(var(--forge-shell-hero-description-translate-y))",willChange:"opacity, transform"},children:r})]}),l?e.jsx("div",{className:"relative mt-4 flex min-w-0 w-full max-w-full flex-wrap items-center gap-2 lg:mt-0 lg:max-w-[26rem] lg:justify-end",children:l}):null]})}function Aa(t){return t.entityType==="goal"?`/goals/${t.entityId}`:t.entityType==="project"?`/projects/${t.entityId}`:t.entityType==="task"?`/tasks/${t.entityId}`:t.entityType==="strategy"?`/strategies/${t.entityId}`:t.entityType==="habit"?"/habits":t.entityType==="task_run"&&typeof t.metadata.taskId=="string"?`/tasks/${t.metadata.taskId}`:null}function Hn(t){return t.entityType==="goal"?"Open goal":t.entityType==="project"?"Open project":t.entityType==="strategy"?"Open strategy":t.entityType==="habit"?"Open habits":t.entityType==="task"||t.entityType==="task_run"?"Open task":null}const hr=n0(),vm=[hr.accessor("title",{header:"Event",cell:t=>{const s=Aa(t.row.original);return s?e.jsx(Xe,{to:s,className:"font-medium text-white transition hover:text-[var(--primary)]",children:t.getValue()}):e.jsx("div",{className:"font-medium text-white",children:t.getValue()})}}),hr.accessor("source",{header:"Source",cell:t=>e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/50",children:t.getValue()})}),hr.display({id:"owner",header:"Owner",cell:t=>t.row.original.user?e.jsx(nt,{user:t.row.original.user,compact:!0}):e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/32",children:"Unowned"})}),hr.accessor("createdAt",{header:"When",cell:t=>e.jsx("div",{className:"text-sm text-white/55",children:ma(t.getValue())})}),hr.display({id:"actions",header:"Open",cell:t=>{const s=Aa(t.row.original);return s?e.jsx(Xe,{to:s,className:"inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)] transition hover:text-white",children:"Open"}):e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/32",children:"Archive only"})}})];function r5({rows:t,onRemove:s}){const a=s?[...vm,hr.display({id:"remove",header:"Correct",cell:r=>e.jsx(z,{variant:"ghost",className:"h-auto px-0 py-0 text-[11px] uppercase tracking-[0.16em] text-white/55",onClick:()=>{s(r.row.original.id)},children:"Remove log"})})]:vm,i=l0({columns:a,data:t,getCoreRowModel:o0()});return e.jsx(ie,{className:"overflow-hidden p-0",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:i.getHeaderGroups().map(r=>e.jsx("tr",{className:"bg-white/[0.03]",children:r.headers.map(n=>e.jsx("th",{className:"px-5 py-4 text-left font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:n.isPlaceholder?null:Eh(n.column.columnDef.header,n.getContext())},n.id))},r.id))}),e.jsx("tbody",{children:i.getRowModel().rows.map(r=>e.jsx("tr",{className:"bg-white/[0.015] transition hover:bg-white/[0.035]",children:r.getVisibleCells().map(n=>e.jsx("td",{className:"px-5 py-4 align-top",children:Eh(n.column.columnDef.cell,n.getContext())},n.id))},r.id))})]})})}function n5(){var c;const t=jt(),s=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[a]=us(),i=ct(),r=a.get("entityId")??void 0,n=a.get("entityType")??void 0,l=a.get("eventId"),o=Me({queryKey:["activity-archive",n,r,...s],queryFn:()=>Fk({limit:100,entityType:n,entityId:r,userIds:s})}),d=De({mutationFn:g=>qg(g),onSuccess:async()=>{await Promise.all([i.invalidateQueries({queryKey:["activity-archive"]}),i.invalidateQueries({queryKey:["forge-snapshot"]}),i.invalidateQueries({queryKey:["task-context"]}),i.invalidateQueries({queryKey:["project-board"]})])}}),h=((c=o.data)==null?void 0:c.activity)??[];if(o.isLoading)return e.jsx(Et,{eyebrow:"Evidence archive",title:"Loading activity",description:"Pulling the visible audit trail, grouped evidence, and correction history."});if(o.isError)return e.jsx(st,{eyebrow:"Evidence archive",error:o.error,onRetry:()=>void o.refetch()});if(h.length===0)return e.jsx(Bt,{eyebrow:"Evidence archive",title:r?"No evidence matched this filter":"No activity recorded yet",description:r?"Forge could not find visible events for this specific entity yet. Try a broader archive view or create some work first.":"As you complete work, log runs, or make corrections, the audit trail will appear here."});const m=h.reduce((g,x)=>{const p=x.createdAt.slice(0,10);return g[p]=[...g[p]??[],x],g},{});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(rt,{title:"Activity",description:r?"This filtered archive shows the evidence connected to the item you opened, so you can confirm what changed and when.":"Activity is your visible audit trail. Use it to inspect progress, confirm corrections, and trace work back to the goal, project, or task it came from.",badge:`${h.length} recent events`}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsx(r5,{rows:h,onRemove:async g=>{await d.mutateAsync(g)}}),e.jsx("div",{className:"grid gap-4",children:Object.entries(m).slice(0,6).map(([g,x])=>e.jsxs(ie,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:g}),e.jsx("div",{className:"mt-4 grid gap-3",children:x.slice(0,3).map(p=>e.jsxs("div",{className:`rounded-[18px] p-4 ${l===p.id?"bg-[rgba(192,193,255,0.12)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"bg-white/[0.04]"}`,children:[e.jsx("div",{className:"font-medium text-white",children:p.title}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:p.description}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:ma(p.createdAt)}),Aa(p)&&Hn(p)?e.jsx(Xe,{to:Aa(p),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:Hn(p)}):null]},p.id))})]},g))})]})]})}function wm(t,s){const a=new Date(t);return Number.isNaN(a.getTime())?s:a.toISOString()}function Wi(t){const s=new Date(t);return new Date(s.getTime()-s.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function ym(t,s){var n,l,o,d,h;const a=new Date,i=new Date(a.getTime()+30*6e4),r=new Date(i.getTime()+60*6e4);return{title:(s==null?void 0:s.title)??(t==null?void 0:t.title)??"",description:(s==null?void 0:s.description)??(t==null?void 0:t.description)??"",location:(s==null?void 0:s.location)??(t==null?void 0:t.location)??"",placeAddress:((n=s==null?void 0:s.place)==null?void 0:n.address)??((l=t==null?void 0:t.place)==null?void 0:l.address)??"",placeTimezone:((o=s==null?void 0:s.place)==null?void 0:o.timezone)??((d=t==null?void 0:t.place)==null?void 0:d.timezone)??"",startAtLocal:t?Wi(t.startAt):s!=null&&s.startAt?Wi(s.startAt):Wi(i.toISOString()),endAtLocal:t?Wi(t.endAt):s!=null&&s.endAt?Wi(s.endAt):Wi(r.toISOString()),timezone:(s==null?void 0:s.timezone)??(t==null?void 0:t.timezone)??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:(s==null?void 0:s.availability)??(t==null?void 0:t.availability)??"busy",activityPresetKey:bf(t==null?void 0:t.actionProfile),customSustainRateApPerHour:vf(t==null?void 0:t.actionProfile),preferredCalendarId:s&&"preferredCalendarId"in s?s.preferredCalendarId:(t==null?void 0:t.calendarId)??void 0,categoriesText:((h=s==null?void 0:s.categories)==null?void 0:h.join(", "))??(t==null?void 0:t.categories.join(", "))??"",linkQuery:"",links:(s==null?void 0:s.links)??(t==null?void 0:t.links.map(m=>({entityType:m.entityType,entityId:m.entityId,relationshipType:m.relationshipType,label:`${m.entityType.replaceAll("_"," ")} · ${m.entityId}`})))??[]}}function l5({open:t,onOpenChange:s,writableCalendars:a,linkOptions:i,event:r,seed:n,onSubmit:l,pending:o=!1}){const[d,h]=u.useState(()=>ym(r,n)),[m,c]=u.useState(null);u.useEffect(()=>{t&&(h(ym(r,n)),c(null))},[r,t,n]);const g=u.useMemo(()=>i.map(p=>{const f=Vt(p.entityType);return{value:`${p.entityType}:${p.entityId}`,label:p.label,description:p.subtitle,searchText:`${p.label} ${p.subtitle} ${p.entityType}`,kind:f??void 0,menuBadge:f?e.jsx(Ue,{kind:f,label:p.label,compact:!0,gradient:!1}):void 0,badge:f?e.jsx(Ue,{kind:f,label:p.label,compact:!0}):void 0}}),[i]),x=u.useMemo(()=>[{id:"identity",eyebrow:"Event",title:r?"Refine the Forge event":"Create a Forge calendar event",description:"This event belongs to Forge first. If you choose a writable calendar, Forge will also project it to the connected provider.",render:(p,f)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(le,{label:"Title",children:e.jsx(ke,{value:p.title,onChange:b=>f({title:b.target.value}),placeholder:"Weekly research supervision"})}),e.jsx(le,{label:"Description",children:e.jsx(Ve,{value:p.description,onChange:b=>f({description:b.target.value}),placeholder:"Agenda, context, or outcomes you want this event to carry."})}),e.jsx(le,{label:"Location",children:e.jsx(ke,{value:p.location,onChange:b=>f({location:b.target.value}),placeholder:"Clinic room 2 or Zoom"})}),e.jsx(le,{label:"Place address",children:e.jsx(ke,{value:p.placeAddress,onChange:b=>f({placeAddress:b.target.value}),placeholder:"Bahnhofstrasse 10, Zurich"})}),e.jsx(le,{label:"Place timezone",children:e.jsx(ke,{value:p.placeTimezone,onChange:b=>f({placeTimezone:b.target.value}),placeholder:"Europe/Zurich"})})]})},{id:"timing",eyebrow:"Timing",title:"Set the time and visibility",description:"Forge stores the real event window, timezone, and whether it should behave like a busy or free slot for scheduling rules.",render:(p,f)=>e.jsxs("div",{className:"grid gap-4",children:[(()=>{const b=new Date().toISOString(),M=new Date(Date.now()+3600*1e3).toISOString(),P=wn({title:p.title,availability:p.availability,activityPresetKey:p.activityPresetKey,customSustainRateApPerHour:p.customSustainRateApPerHour,startAt:wm(p.startAtLocal,b),endAt:wm(p.endAtLocal,M)});return e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Kt(P.rateApPerHour)}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:kt(P.totalAp)})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Availability controls whether the event blocks planning. The activity profile controls AP drain, and you can override it with a custom AP per hour."})]})})(),e.jsx(le,{label:"Activity profile",children:e.jsx(vt,{value:p.activityPresetKey??(p.availability==="busy"?"meeting":"light_context"),columns:3,onChange:b=>f({activityPresetKey:b}),options:ji().filter(b=>b.key!=="task_inherited").map(b=>({value:b.key,label:b.label,description:`${Kt(b.defaultRateApPerHour)} · ${b.description}`}))})}),e.jsx(le,{label:"Custom AP per hour",children:e.jsx(ke,{type:"number",min:0,step:.5,value:p.customSustainRateApPerHour??"",onChange:b=>f({customSustainRateApPerHour:b.target.value.trim()===""?null:Number(b.target.value)}),placeholder:"Leave empty to use the activity default"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Starts",children:e.jsx(ke,{type:"datetime-local",value:p.startAtLocal,onChange:b=>f({startAtLocal:b.target.value})})}),e.jsx(le,{label:"Ends",children:e.jsx(ke,{type:"datetime-local",value:p.endAtLocal,onChange:b=>f({endAtLocal:b.target.value})})})]}),e.jsx(le,{label:"Timezone",children:e.jsx(ke,{value:p.timezone,onChange:b=>f({timezone:b.target.value}),placeholder:"Europe/Zurich"})}),e.jsx(le,{label:"Availability",children:e.jsx(vt,{value:p.availability,onChange:b=>f({availability:b}),options:[{value:"busy",label:"Busy",description:"This event should block timebox recommendations and rule checks."},{value:"free",label:"Free",description:"This event stays visible in the calendar without blocking work."}]})})]})},{id:"links",eyebrow:"Meaning",title:"Connect the event to Forge entities",description:"Attach this event to strategies, goals, projects, tasks, or habits so the calendar carries multi-user operating context instead of staying isolated.",render:(p,f)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(le,{label:"Search Forge entities",description:"Search across human and bot-owned entities; the linked records use the same icon, color, and owner system as the rest of Forge.",children:e.jsx(ht,{options:g,selectedValues:p.links.map(b=>`${b.entityType}:${b.entityId}`),onChange:b=>{f({links:b.map(M=>{const[P,...T]=M.split(":"),w=T.join(":"),j=i.find(v=>v.entityType===P&&v.entityId===w);return j?{entityType:j.entityType,entityId:j.entityId,relationshipType:"context",label:j.label}:null}).filter(M=>M!==null)})},placeholder:"Search strategies, goals, projects, tasks, habits, human, or bot owners",emptyMessage:"No matching Forge entities found."})})})},{id:"projection",eyebrow:"Projection",title:"Choose where this event should live remotely",description:"You can keep the event local to Forge, or choose a writable connected calendar so Forge also keeps a synced remote copy.",render:(p,f)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[a.length>0?e.jsxs("button",{type:"button",onClick:()=>f({preferredCalendarId:void 0}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===void 0?"border-[rgba(125,211,252,0.28)] bg-[rgba(125,211,252,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(ds,{className:"size-4"}),"Default synced calendar"]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:"Let Forge use the default writable connected calendar automatically."})]}):null,e.jsxs("button",{type:"button",onClick:()=>f({preferredCalendarId:null}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===null?"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.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(Ht,{className:"size-4"}),"Forge only"]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:"Keep the event in Forge without creating a remote provider copy yet."})]}),a.map(b=>e.jsxs("button",{type:"button",onClick:()=>f({preferredCalendarId:b.id}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===b.id?"border-[rgba(125,211,252,0.28)] bg-[rgba(125,211,252,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(ds,{className:"size-4"}),kr(b)]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:b.description||`${b.timezone} · writable`})]},b.id))]}),e.jsxs("div",{className:"grid gap-2 rounded-[22px] border border-white/8 bg-white/[0.04] p-4 text-sm text-white/66",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium text-white",children:[e.jsx(vu,{className:"size-4 text-[var(--primary)]"}),"Categories and filtering"]}),e.jsx(ke,{value:p.categoriesText,onChange:b=>f({categoriesText:b.target.value}),placeholder:"meeting, clinic, research"})]})]})}],[r,i,g,a]);return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:r?"Edit event":"New event",title:r?"Edit calendar event":"Create calendar event",description:"Forge-owned events can stay local or publish to a connected provider calendar.",value:d,onChange:h,steps:x,onSubmit:async()=>{if(!d.title.trim()){c("Add an event title before saving.");return}if(!d.startAtLocal||!d.endAtLocal){c("Set both the start and end time before saving.");return}if(new Date(d.endAtLocal).getTime()<=new Date(d.startAtLocal).getTime()){c("The event end time must be after the start time.");return}c(null),await l({title:d.title.trim(),description:d.description.trim(),location:d.location.trim(),place:{label:d.location.trim(),address:d.placeAddress.trim(),timezone:d.placeTimezone.trim(),latitude:null,longitude:null,source:d.placeAddress.trim()?"manual":"",externalPlaceId:""},startAt:new Date(d.startAtLocal).toISOString(),endAt:new Date(d.endAtLocal).toISOString(),timezone:d.timezone.trim()||"UTC",availability:d.availability,activityPresetKey:d.activityPresetKey,customSustainRateApPerHour:d.customSustainRateApPerHour,categories:d.categoriesText.split(",").map(p=>p.trim()).filter(Boolean),links:d.links.map(p=>({entityType:p.entityType,entityId:p.entityId,relationshipType:p.relationshipType})),...d.preferredCalendarId!==void 0?{preferredCalendarId:d.preferredCalendarId}:{}})},submitLabel:r?"Save event":"Create event",pending:o,pendingLabel:r?"Saving":"Creating",error:m})}function o5({open:t,onOpenChange:s,initialTitle:a,pending:i=!1,onSubmit:r}){const[n,l]=u.useState(a),[o,d]=u.useState(null);return u.useEffect(()=>{t&&(l(a),d(null))},[a,t]),e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Quick rename",description:"Rename the event without reopening the full event guide.",value:{title:n},onChange:h=>l(h.title),steps:[{id:"rename",eyebrow:"Rename",title:"Update the event title",description:"Keep the rename fast and direct. Everything else on the event stays unchanged.",render:(h,m)=>e.jsx(le,{label:"Event title",children:e.jsx(ke,{value:h.title,onChange:c=>m({title:c.target.value}),placeholder:"Weekly research supervision"})})}],submitLabel:"Save title",pending:i,pendingLabel:"Saving",error:o,onSubmit:async()=>{const h=n.trim();if(!h){d("Add a title before saving.");return}d(null),await r(h),s(!1)}})}const d5=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],qc=[{kind:"main_activity",label:"Main activity",title:"Main Activity",startMinute:480,endMinute:720,color:"#f97316",blockingState:"blocked"},{kind:"secondary_activity",label:"Secondary activity",title:"Secondary Activity",startMinute:780,endMinute:1020,color:"#22c55e",blockingState:"allowed"},{kind:"third_activity",label:"Third activity",title:"Third Activity",startMinute:1020,endMinute:1260,color:"#38bdf8",blockingState:"allowed"},{kind:"rest",label:"Rest",title:"Rest",startMinute:1260,endMinute:1380,color:"#a855f7",blockingState:"blocked"},{kind:"holiday",label:"Holiday",title:"Holiday",startMinute:0,endMinute:1440,color:"#14b8a6",blockingState:"blocked"}];function Mn(t=new Date){const s=new Date(t),a=s.getUTCDay(),i=a===0?-6:1-a;return s.setUTCDate(s.getUTCDate()+i),s.setUTCHours(0,0,0,0),s}function Pi(t,s){const a=new Date(t);return a.setUTCDate(a.getUTCDate()+s),a}function cb(t){return Array.from({length:7},(s,a)=>Pi(t,a))}function Ai(t){return new Intl.DateTimeFormat("en",{weekday:"short",month:"short",day:"numeric"}).format(t)}function jm(t){const s=Math.floor(t/60).toString().padStart(2,"0"),a=String(t%60).padStart(2,"0");return`${s}:${a}`}function Nm(t){return`${t.toString().padStart(2,"0")}:00`}function ub({eyebrow:t="Week view",description:s,weekStart:a,status:i,badges:r,onPrevious:n,onCurrent:l,onNext:o}){return 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:t}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:s}),i?e.jsx("div",{className:"mt-3",children:i}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[e.jsx(ds,{className:"mr-1 size-3.5"}),"Week of ",Ai(a)]}),r,e.jsx(z,{variant:"secondary",onClick:n,children:"Previous"}),e.jsx(z,{variant:"secondary",onClick:l,children:"This week"}),e.jsx(z,{variant:"secondary",onClick:o,children:"Next"})]})]})}const km=[{value:"main_activity",label:"Main activity"},{value:"secondary_activity",label:"Secondary activity"},{value:"third_activity",label:"Third activity"},{value:"rest",label:"Rest"},{value:"holiday",label:"Holiday"},{value:"custom",label:"Custom"}],Sm=[{value:"busy",label:"Busy"},{value:"free",label:"Free"}],ea={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function Hi(t){return t.join(", ")}function Gi(t){return t.split(",").map(s=>s.trim()).filter(Boolean)}function kl({label:t,selected:s,onToggle:a,options:i}){return e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}),e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map(r=>{const n=s.includes(r.value);return e.jsx("button",{type:"button",onClick:()=>a(r.value),className:`rounded-full px-3 py-2 text-sm transition ${n?"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:r.label},r.value)})})]})}function hb({title:t,subtitle:s,initialRules:a,initialPlannedDurationSeconds:i,onSave:r,saveLabel:n="Save scheduling rules",allowPlannedDuration:l=!1}){const[o,d]=u.useState((a==null?void 0:a.allowWorkBlockKinds)??ea.allowWorkBlockKinds),[h,m]=u.useState((a==null?void 0:a.blockWorkBlockKinds)??ea.blockWorkBlockKinds),[c,g]=u.useState((a==null?void 0:a.allowAvailability)??ea.allowAvailability),[x,p]=u.useState((a==null?void 0:a.blockAvailability)??ea.blockAvailability),[f,b]=u.useState(Hi((a==null?void 0:a.allowCalendarIds)??ea.allowCalendarIds)),[M,P]=u.useState(Hi((a==null?void 0:a.blockCalendarIds)??ea.blockCalendarIds)),[T,w]=u.useState(Hi((a==null?void 0:a.allowEventTypes)??ea.allowEventTypes)),[j,v]=u.useState(Hi((a==null?void 0:a.blockEventTypes)??ea.blockEventTypes)),[y,E]=u.useState(Hi((a==null?void 0:a.allowEventKeywords)??ea.allowEventKeywords)),[S,B]=u.useState(Hi((a==null?void 0:a.blockEventKeywords)??ea.blockEventKeywords)),[N,A]=u.useState(i?String(Math.round(i/60)):"30"),[q,W]=u.useState(!1),Y=u.useMemo(()=>({allowWorkBlockKinds:o,blockWorkBlockKinds:h,allowCalendarIds:Gi(f),blockCalendarIds:Gi(M),allowEventTypes:Gi(T),blockEventTypes:Gi(j),allowEventKeywords:Gi(y),blockEventKeywords:Gi(S),allowAvailability:c,blockAvailability:x}),[c,f,y,T,o,x,M,S,j,h]),K=Object.values(Y).every(R=>R.length===0),O=(R,F,H)=>{F(R.includes(H)?R.filter(G=>G!==H):[...R,H])};return e.jsxs(ie,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:s})]}),l?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Planned duration"}),e.jsx(ke,{type:"number",min:15,step:15,value:N,onChange:R=>A(R.target.value),placeholder:"30"})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(kl,{label:"Allow work blocks",selected:o,onToggle:R=>O(o,d,R),options:km}),e.jsx(kl,{label:"Block work blocks",selected:h,onToggle:R=>O(h,m,R),options:km}),e.jsx(kl,{label:"Allow availability",selected:c,onToggle:R=>O(c,g,R),options:Sm}),e.jsx(kl,{label:"Block availability",selected:x,onToggle:R=>O(x,p,R),options:Sm})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow calendar ids"}),e.jsx(ke,{value:f,onChange:R=>b(R.target.value),placeholder:"calendar_123, primary"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block calendar ids"}),e.jsx(ke,{value:M,onChange:R=>P(R.target.value),placeholder:"calendar_456"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow event types"}),e.jsx(ke,{value:T,onChange:R=>w(R.target.value),placeholder:"focus, personal"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block event types"}),e.jsx(ke,{value:j,onChange:R=>v(R.target.value),placeholder:"out-of-office, main-work"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow event keywords"}),e.jsx(ke,{value:y,onChange:R=>E(R.target.value),placeholder:"creative, writing"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block event keywords"}),e.jsx(ke,{value:S,onChange:R=>B(R.target.value),placeholder:"psychiatrist, clinic, rest"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(z,{pending:q,pendingLabel:"Saving",onClick:async()=>{W(!0);try{await r({schedulingRules:K?ea:Y,plannedDurationSeconds:l?Math.max(15,Number(N||30))*60:void 0})}finally{W(!1)}},children:n}),e.jsx(z,{variant:"secondary",onClick:async()=>{W(!0);try{d([]),m([]),g([]),p([]),b(""),P(""),w(""),v(""),E(""),B(""),await r({schedulingRules:null,plannedDurationSeconds:l?Math.max(15,Number(N||30))*60:void 0})}finally{W(!1)}},children:"Clear custom rules"})]})]})}function mb({open:t,onOpenChange:s,tasks:a,onSave:i}){const r=u.useMemo(()=>a.filter(d=>d.status!=="done"),[a]),[n,l]=u.useState("");u.useEffect(()=>{if(t){if(r.length===0){l("");return}l(d=>d&&r.some(h=>h.id===d)?d:r[0].id)}},[r,t]);const o=r.find(d=>d.id===n)??null;return e.jsx(oa,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Adjust task scheduling rules",description:"Choose a task, then tell Forge which work blocks, calendar conditions, or keywords should allow or block that work.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(Ht,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Guided rule editing"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Use this when a task should only run in certain blocks such as Secondary Activity, or should stay blocked during clinic, rest, or other provider events."})]})]})}),r.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Task"}),e.jsx("select",{value:n,onChange:d=>l(d.target.value),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:r.map(d=>e.jsx("option",{value:d.id,children:d.title},d.id))})]}),o?e.jsx(hb,{title:"Task rules",subtitle:"These rules are saved directly on the task. They drive blocked-now checks and future timebox recommendations.",initialRules:o.schedulingRules,initialPlannedDurationSeconds:o.plannedDurationSeconds,allowPlannedDuration:!0,saveLabel:"Save task rules",onSave:async({schedulingRules:d,plannedDurationSeconds:h})=>{await i({taskId:o.id,schedulingRules:d,plannedDurationSeconds:h===void 0?o.plannedDurationSeconds:h??null}),s(!1)}}):null]}):e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-white/[0.04]",children:[e.jsx("div",{className:"font-medium text-white",children:"No schedulable tasks yet"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Create or reopen a task first, then come back here to define work-block and calendar eligibility."}),e.jsx("div",{className:"mt-4",children:e.jsx(z,{variant:"secondary",onClick:()=>s(!1),children:"Close"})})]})]})})}function Ni(t){return t.slice(0,10)}function c5(t){return new Date(`${t}T00:00:00`).toISOString()}function u5(t){return new Date(`${t}T23:59:59.999`).toISOString()}function Bc(t,s,a){return t<s?s:t>a?a:t}function Cm(t,s){const a=Ni(t),i=Ni(s),r=new Date(`${a}T12:00:00`);return r.setDate(r.getDate()+1),Bc(Ni(r.toISOString()),a,i)}function Im(t){return String(t).padStart(2,"0")}function Sl(t){return`${Im(t.getHours())}:${Im(t.getMinutes())}`}function Tm(t,s){if(!t||!s)return null;const a=new Date(`${t}T${s}:00`);return Number.isNaN(a.getTime())?null:a}function Cl(t,s,a){if(a){const l=new Date(a.startsAt),o=new Date(a.endsAt);return{startTime:Sl(l),endTime:Sl(o)}}const i=new Date(`${t}T09:00:00`),r=Math.max(1800,Math.min(s??3600,360*60)),n=new Date(i.getTime()+r*1e3);return{startTime:Sl(i),endTime:Sl(n)}}function pb(t,s){return`${new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})} - ${new Date(s).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function od(t,s){return`${Ai(new Date(t))} · ${pb(t,s)}`}function _d({title:t,subtitle:s,emptyLabel:a,children:i}){const r=Array.isArray(i)?i:i?[i]:[];return e.jsxs("div",{className:"rounded-[24px] border border-white/8 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-medium text-white",children:t}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:s})]}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:r.length})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:r.length>0?r:e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/46",children:a})})]})}function h5({event:t}){return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:t.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:t.availability})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:od(t.startAt,t.endAt)})]})}function m5({block:t}){return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:t.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:t.blockingState})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:od(t.startAt,t.endAt)})]})}function p5({timebox:t}){const s=Mr(t);return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:t.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:t.source})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:od(t.startsAt,t.endsAt)}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:Kt(s.rateApPerHour)}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:kt(s.totalAp)})]})]})}function xb({open:t,onOpenChange:s,tasks:a,from:i,to:r,onCreateTimebox:n,onUpdateTimebox:l,onDeleteTimebox:o,initialTaskId:d,lockedTaskId:h,editingTimebox:m,userIds:c}){var Ne,fe,V,Ce,L,D;const g=!!m,x=u.useMemo(()=>{const _=h??(m==null?void 0:m.taskId)??null,ee=a.filter(te=>te.status!=="done"||te.id===_);if(!_)return ee;const U=ee.find(te=>te.id===_);return U?[U]:[]},[m==null?void 0:m.taskId,h,a]),p=Ni(i),f=Ni(r),b=m?Bc(Ni(m.startsAt),p,f):Cm(i,r),M=h??(m==null?void 0:m.taskId)??d??((Ne=x[0])==null?void 0:Ne.id)??"",P=x.find(_=>_.id===M)??x[0]??null,T=Cl(b,P==null?void 0:P.plannedDurationSeconds,m?{startsAt:m.startsAt,endsAt:m.endsAt}:null),[w,j]=u.useState({taskId:M,preferredDate:b,plannerMode:m?"manual":"suggested",selectedTimeboxId:"",activityPresetKey:((fe=m==null?void 0:m.actionProfile)==null?void 0:fe.profileKey)??"task_inherited",customSustainRateApPerHour:((V=m==null?void 0:m.actionProfile)==null?void 0:V.sourceMethod)==="manual"?m.actionProfile.sustainRateApPerHour:null,manualStartTime:T.startTime,manualEndTime:T.endTime,manualTitle:(m==null?void 0:m.title)??(P==null?void 0:P.title)??"",overrideReason:(m==null?void 0:m.overrideReason)??""}),[v,y]=u.useState(null),[E,S]=u.useState(!1),[B,N]=u.useState(!1);u.useEffect(()=>{var ve,pe,Ee;if(!t)return;const _=h??d??((ve=x[0])==null?void 0:ve.id)??"",ee=(m==null?void 0:m.taskId)??_,U=x.find(ce=>ce.id===ee)??x[0]??null,te=m?Bc(Ni(m.startsAt),p,f):Cm(i,r),J=Cl(te,U==null?void 0:U.plannedDurationSeconds,m?{startsAt:m.startsAt,endsAt:m.endsAt}:null);y(null),j({taskId:ee,preferredDate:te,plannerMode:m?"manual":"suggested",selectedTimeboxId:"",activityPresetKey:((pe=m==null?void 0:m.actionProfile)==null?void 0:pe.profileKey)??"task_inherited",customSustainRateApPerHour:((Ee=m==null?void 0:m.actionProfile)==null?void 0:Ee.sourceMethod)==="manual"?m.actionProfile.sustainRateApPerHour:null,manualStartTime:J.startTime,manualEndTime:J.endTime,manualTitle:(m==null?void 0:m.title)??(U==null?void 0:U.title)??"",overrideReason:(m==null?void 0:m.overrideReason)??""})},[x,m,i,d,h,f,p,t,r]);const A=x.find(_=>_.id===w.taskId)??null,q=u.useMemo(()=>({from:c5(w.preferredDate),to:u5(w.preferredDate)}),[w.preferredDate]),W=Me({queryKey:["forge-calendar-suggestions-dialog",w.taskId,q.from,q.to],queryFn:()=>mN({taskId:w.taskId,from:q.from,to:q.to,limit:8}),enabled:t&&w.taskId.length>0}),Y=Me({queryKey:["forge-calendar-timebox-dialog-day",q.from,q.to,...c??[]],queryFn:()=>Pr({from:q.from,to:q.to,userIds:c}),enabled:t});u.useEffect(()=>{var ee;if(!t)return;const _=((ee=W.data)==null?void 0:ee.timeboxes)??[];if(!_.length){j(U=>U.selectedTimeboxId?{...U,selectedTimeboxId:""}:U);return}j(U=>U.selectedTimeboxId&&_.some(te=>te.id===U.selectedTimeboxId)?U:{...U,selectedTimeboxId:_[0].id})},[t,W.data]);const K=(Ce=Y.data)==null?void 0:Ce.calendar,O=(K==null?void 0:K.events)??[],R=(K==null?void 0:K.workBlockInstances)??[],F=(K==null?void 0:K.timeboxes)??[],H=(((L=W.data)==null?void 0:L.timeboxes)??[]).find(_=>_.id===w.selectedTimeboxId),G=Tm(w.preferredDate,w.manualStartTime),$=Tm(w.preferredDate,w.manualEndTime),Q=G&&$?Mr({startsAt:G.toISOString(),endsAt:$.toISOString(),actionProfile:w.customSustainRateApPerHour!==null||w.activityPresetKey!=="task_inherited"?{id:"manual-preview",profileKey:"manual-preview",title:w.manualTitle||(A==null?void 0:A.title)||"Manual timebox",entityType:"task_timebox",mode:"container",startupAp:0,totalCostAp:0,expectedDurationSeconds:null,sustainRateApPerHour:w.customSustainRateApPerHour??((D=ji().find(_=>_.key===w.activityPresetKey))==null?void 0:D.defaultRateApPerHour)??100/24,demandWeights:{activation:.1,focus:.3,vigor:.1,composure:.1,flow:.4},doubleCountPolicy:"container_only",sourceMethod:"manual",costBand:"light",recoveryEffect:0,metadata:{},createdAt:G.toISOString(),updatedAt:G.toISOString()}:null}):null,X=g?"Review the task tied to this scheduled block":h?"Review the task you are planning":"Choose the task you want to place into the calendar",ae=g?"The timebox stays linked to this task. Update the day, hours, title, or AP profile without leaving the planning flow.":h?"Forge will use this task's current duration target and scheduling rules while it looks for viable slots.":"Forge will use the task's current planned duration and scheduling rules when it searches for valid slots.",Pe=u.useMemo(()=>[{id:"task",eyebrow:"Planning",title:X,description:ae,render:(_,ee)=>e.jsxs("div",{className:"grid gap-4",children:[h?null:e.jsx(le,{label:"Task",children:e.jsx("select",{value:_.taskId,onChange:U=>(()=>{const te=x.find(ve=>ve.id===U.target.value),J=Cl(_.preferredDate,te==null?void 0:te.plannedDurationSeconds);ee({taskId:U.target.value,selectedTimeboxId:"",activityPresetKey:"task_inherited",customSustainRateApPerHour:null,manualStartTime:J.startTime,manualEndTime:J.endTime,manualTitle:(te==null?void 0:te.title)??_.manualTitle})})(),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:x.map(U=>e.jsx("option",{value:U.id,children:U.title},U.id))})}),A?e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(28,36,54,0.78),rgba(15,22,34,0.78))] p-5 shadow-[0_18px_40px_rgba(5,12,24,0.22)]",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/42",children:"Time Box"}),e.jsx("div",{className:"mt-2 font-display text-[1.4rem] leading-tight text-white",children:A.title})]}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:A.status})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:A.plannedDurationSeconds?`${Math.round(A.plannedDurationSeconds/60)} min target`:"No duration yet"}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:A.schedulingRules?"Task-specific rules":"Uses project rules"}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[A.points," xp"]}),A.plannedDurationSeconds?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[kt(A.plannedDurationSeconds/3600/24*100)," target load"]}):null]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/60",children:"Pick a day first, then either accept one of Forge's suggested slots or set the block manually."}),g&&m&&o?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-3 rounded-[20px] border border-rose-400/18 bg-rose-400/8 px-4 py-3",children:[e.jsx("div",{className:"text-sm leading-6 text-rose-100/84",children:"Remove this planned timebox if you no longer want it in the calendar."}),e.jsx(z,{type:"button",variant:"ghost",className:"text-rose-100 hover:bg-rose-500/12",pending:B,pendingLabel:"Deleting",onClick:()=>void(async()=>{y(null),N(!0);try{await o(m.id),s(!1)}catch(U){y(U instanceof Error?U.message:"Forge could not delete this timebox.")}finally{N(!1)}})(),children:"Delete timebox"})]}):null]}):null]})},{id:"day",eyebrow:"Calendar",title:"Choose the day and review what is already there",description:"Forge reads the real day first so the timebox stays grounded in your provider events, work blocks, and already-planned work.",render:(_,ee)=>e.jsx("div",{className:"grid gap-5",children:e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(le,{label:"Date",description:"Choose the day you want to protect for this task.",children:e.jsx(ke,{type:"date",min:p,max:f,value:_.preferredDate,onChange:U=>{const te=Cl(U.target.value,A==null?void 0:A.plannedDurationSeconds,m?{startsAt:`${U.target.value}T${_.manualStartTime}:00`,endsAt:`${U.target.value}T${_.manualEndTime}:00`}:null);ee({preferredDate:U.target.value,selectedTimeboxId:"",manualStartTime:te.startTime,manualEndTime:te.endTime})}})}),e.jsx(le,{label:"Planning style",description:"Take Forge's slot recommendation when it fits, or set the block yourself.",children:e.jsx(vt,{value:_.plannerMode,onChange:U=>ee({plannerMode:U}),options:[{value:"suggested",label:"Use suggestions",description:"Forge proposes slots that fit the task rules and the selected day."},{value:"manual",label:"Set it manually",description:"You choose the exact start and end time yourself."}]})})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,31,44,0.86),rgba(11,17,28,0.86))] p-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:"Selected day"}),e.jsx("div",{className:"mt-2 font-display text-[1.3rem] leading-tight text-white",children:_.preferredDate?new Date(`${_.preferredDate}T12:00:00`).toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"}):"Choose a day"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[O.length," events"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[R.length," work blocks"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[F.length," timeboxes"]})]})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"This is the context Forge will use while recommending a slot. You can still place the block manually if you want something more exact."}),Y.isLoading?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-4 text-sm text-white/56",children:"Loading the selected day…"}):e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-3",children:[e.jsx(_d,{title:"Provider events",subtitle:"Busy or free events already on the day.",emptyLabel:"No mirrored events on this day.",children:O.slice(0,4).map(U=>e.jsx(h5,{event:U},U.id))}),e.jsx(_d,{title:"Work blocks",subtitle:"Recurring allowed or blocked containers.",emptyLabel:"No work blocks land on this day.",children:R.slice(0,4).map(U=>e.jsx(m5,{block:U},U.id))}),e.jsx(_d,{title:"Planned timeboxes",subtitle:"Existing owned work already placed there.",emptyLabel:"No other planned timeboxes yet.",children:F.slice(0,4).map(U=>e.jsx(p5,{timebox:U},U.id))})]})]})]})})},{id:"slot",eyebrow:w.plannerMode==="suggested"?"Suggestion":"Manual",title:w.plannerMode==="suggested"?"Choose one of Forge's suggested slots":"Set the exact timebox yourself",description:w.plannerMode==="suggested"?"Forge proposes slots that fit the selected day, the task rules, and the current calendar picture.":"Use manual mode when the right block is obvious to you or when you want to place the timebox despite imperfect recommendations.",render:(_,ee)=>{var te;if(_.plannerMode==="manual")return e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(le,{label:"Day",description:"Pick the day for the block. Forge defaults to a future day, but you can move it.",children:e.jsx(ke,{type:"date",min:p,max:f,value:_.preferredDate,onChange:J=>ee({preferredDate:J.target.value})})}),e.jsx(le,{label:"Start time",description:"Choose when the protected work block should begin.",children:e.jsx(ke,{type:"time",step:300,value:_.manualStartTime,onChange:J=>ee({manualStartTime:J.target.value})})}),e.jsx(le,{label:"End time",description:"Choose when the work block should end.",children:e.jsx(ke,{type:"time",step:300,value:_.manualEndTime,onChange:J=>ee({manualEndTime:J.target.value})})})]}),e.jsx(le,{label:"Title",description:"By default Forge uses the task title. Tighten it only if a shorter calendar label would help.",children:e.jsx(ke,{value:_.manualTitle,onChange:J=>ee({manualTitle:J.target.value}),placeholder:(A==null?void 0:A.title)??"Task timebox"})}),e.jsx(le,{label:"Override reason",description:"Optional. Add a short reason only if you are intentionally placing the block despite the normal rules or calendar shape.",children:e.jsx(ke,{value:_.overrideReason,onChange:J=>ee({overrideReason:J.target.value}),placeholder:"Protected writing block before clinic."})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Activity profile",children:e.jsx("select",{value:_.activityPresetKey??"task_inherited",onChange:J=>ee({activityPresetKey:J.target.value}),className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:ji().map(J=>e.jsx("option",{value:J.key,children:J.label},J.key))})}),e.jsx(le,{label:"Custom AP per hour",children:e.jsx(ke,{type:"number",min:0,step:.5,value:_.customSustainRateApPerHour??"",onChange:J=>ee({customSustainRateApPerHour:J.target.value.trim()===""?null:Number(J.target.value)}),placeholder:"Leave empty to use the activity profile"})})]}),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-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:_.manualTitle||(A==null?void 0:A.title)||"Manual timebox"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:G&&$?`${G.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"})} · ${pb(G.toISOString(),$.toISOString())}`:"Choose a start and end time."})]}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:"manual"})]}),Q?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:Kt(Q.rateApPerHour)}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:kt(Q.totalAp)})]}):null]})]});const U=((te=W.data)==null?void 0:te.timeboxes)??[];return W.isLoading?e.jsx("div",{className:"text-sm text-white/62",children:"Looking for valid slots on the selected day…"}):U.length?e.jsx("div",{className:"grid gap-3",children:U.map(J=>{var Ee;const ve=_.selectedTimeboxId===J.id,pe=Mr({...J,actionProfile:_.customSustainRateApPerHour!==null||_.activityPresetKey!=="task_inherited"?{id:"suggested-preview",profileKey:"suggested-preview",title:J.title,entityType:"task_timebox",mode:"container",startupAp:0,totalCostAp:0,expectedDurationSeconds:null,sustainRateApPerHour:_.customSustainRateApPerHour??((Ee=ji().find(ce=>ce.key===_.activityPresetKey))==null?void 0:Ee.defaultRateApPerHour)??100/24,demandWeights:{activation:.1,focus:.3,vigor:.1,composure:.1,flow:.4},doubleCountPolicy:"container_only",sourceMethod:"manual",costBand:"light",recoveryEffect:0,metadata:{},createdAt:J.startsAt,updatedAt:J.startsAt}:null});return e.jsxs("button",{type:"button",onClick:()=>ee({selectedTimeboxId:J.id}),className:`rounded-[24px] border px-4 py-4 text-left transition ${ve?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white shadow-[0_18px_36px_rgba(5,12,24,0.24)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium",children:J.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:J.source})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:od(J.startsAt,J.endsAt)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Kt(pe.rateApPerHour)}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:kt(pe.totalAp)})]}),ve?e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Activity profile",children:e.jsx("select",{value:_.activityPresetKey??"task_inherited",onChange:ce=>ee({activityPresetKey:ce.target.value}),className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:ji().map(ce=>e.jsx("option",{value:ce.key,children:ce.label},ce.key))})}),e.jsx(le,{label:"Custom AP per hour",children:e.jsx(ke,{type:"number",min:0,step:.5,value:_.customSustainRateApPerHour??"",onChange:ce=>ee({customSustainRateApPerHour:ce.target.value.trim()===""?null:Number(ce.target.value)}),placeholder:"Leave empty to use the activity profile"})})]}):null]},J.id)})}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"rounded-[24px] border border-amber-400/20 bg-amber-400/10 px-4 py-4 text-sm leading-6 text-amber-100/86",children:"Forge could not find a valid slot on this day. Try another day, adjust the task rules, or switch to manual placement if you already know the right block."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(z,{variant:"secondary",onClick:()=>void W.refetch(),children:"Refresh suggestions"}),e.jsx(z,{variant:"secondary",onClick:()=>ee({plannerMode:"manual"}),children:"Switch to manual"})]})]})}}],[x,Y.isLoading,R,O,F,w.plannerMode,m,i,h,f,Q,p,A,W.data,W.isLoading,ae,X,r]);return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Calendar",title:g?"Edit timebox":"Plan work",description:g?"Update the day, hour range, title, and AP profile for this scheduled block without leaving the task or calendar view.":"Review the day, let Forge recommend valid slots, and place a real timebox on the task without leaving the detail view.",value:w,onChange:j,steps:Pe,submitLabel:g?"Save timebox":"Schedule timebox",pending:E,pendingLabel:"Scheduling",error:v,contentClassName:"md:w-[min(70rem,calc(100vw-1.5rem))]",onSubmit:async()=>{if(!A){y("Choose a task before scheduling a timebox.");return}if(w.plannerMode==="manual"){if(!G||!$){y("Choose a valid manual start and end time.");return}if($<=G){y("The manual timebox needs an end time after the start time.");return}y(null),S(!0);try{const _={title:w.manualTitle.trim()||A.title,startsAt:G.toISOString(),endsAt:$.toISOString(),overrideReason:w.overrideReason.trim()||null,activityPresetKey:w.activityPresetKey,customSustainRateApPerHour:w.customSustainRateApPerHour};m&&l?await l(m.id,_):await n({taskId:A.id,projectId:A.projectId,..._,source:"manual"}),s(!1)}catch(_){y(_ instanceof Error?_.message:"Forge could not create the manual timebox.")}finally{S(!1)}return}if(!H){y("Pick one suggested slot before scheduling the timebox.");return}y(null),S(!0);try{const _={title:H.title,startsAt:H.startsAt,endsAt:H.endsAt,activityPresetKey:w.activityPresetKey,customSustainRateApPerHour:w.customSustainRateApPerHour};m&&l?await l(m.id,_):await n({taskId:A.id,projectId:A.projectId,..._,source:H.source}),s(!1)}catch(_){y(_ instanceof Error?_.message:"Forge could not create the selected timebox.")}finally{S(!1)}}})}function Pm(t){if(t)return{title:t.title,kind:t.kind,color:t.color,timezone:t.timezone,weekDays:t.weekDays,startMinute:t.startMinute,endMinute:t.endMinute,startsOn:t.startsOn,endsOn:t.endsOn,blockingState:t.blockingState,activityPresetKey:bf(t.actionProfile),customSustainRateApPerHour:vf(t.actionProfile)};const s=qc[0];return{title:s.title,kind:s.kind,color:s.color,timezone:typeof Intl<"u"&&Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",weekDays:[1,2,3,4,5],startMinute:s.startMinute,endMinute:s.endMinute,startsOn:null,endsOn:null,blockingState:s.blockingState,activityPresetKey:s.kind==="main_activity"?"deep_work":s.kind==="secondary_activity"?"admin":s.kind==="holiday"?"holiday_leisure":s.kind==="rest"?"recovery_break":"maintenance",customSustainRateApPerHour:null}}function Am(t){return t??""}function Rd({draft:t}){const s=V2({kind:t.kind,startMinute:t.startMinute,endMinute:t.endMinute,activityPresetKey:t.activityPresetKey,customSustainRateApPerHour:t.customSustainRateApPerHour}),a=t.endMinute>t.startMinute?t.endMinute-t.startMinute:1440-t.startMinute+t.endMinute;return e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Kt(s.rateApPerHour)}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[kt(s.totalAp)," / block"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[Math.round(a/60),"h ",a%60,"m"]})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"This is the default Life Force container drain for each occurrence of the block when no richer task run or timebox already covers that window."})]})}function x5({open:t,onOpenChange:s,onSubmit:a,pending:i=!1,template:r=null}){const[n,l]=u.useState(()=>Pm(r)),[o,d]=u.useState(null),h=r!==null;u.useEffect(()=>{t&&(d(null),l(Pm(r)))},[t,r]);const m=u.useMemo(()=>[{id:"preset",eyebrow:"Preset",title:"Start from a recurring block that already matches the rhythm",description:"Use a preset to seed the schedule, then tune the dates and recurrence in the next step.",render:(c,g)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Rd,{draft:c}),e.jsx(le,{label:"Activity profile",children:e.jsx(vt,{value:c.activityPresetKey??"maintenance",columns:3,onChange:x=>g({activityPresetKey:x,customSustainRateApPerHour:c.customSustainRateApPerHour}),options:ji().filter(x=>x.key!=="task_inherited").map(x=>({value:x.key,label:x.label,description:`${Kt(x.defaultRateApPerHour)} · ${x.description}`}))})}),e.jsx(le,{label:"Custom AP per hour",children:e.jsx(ke,{type:"number",min:0,step:.5,value:c.customSustainRateApPerHour??"",onChange:x=>g({customSustainRateApPerHour:x.target.value.trim()===""?null:Number(x.target.value)}),placeholder:"Leave empty to use the activity default"})}),e.jsx(le,{label:"Block type",children:e.jsx(vt,{value:c.kind,columns:3,onChange:x=>{const p=qc.find(f=>f.kind===x);if(p){const f=p.kind==="holiday"?[0,1,2,3,4,5,6]:[1,2,3,4,5];g({kind:p.kind,title:p.title,color:p.color,weekDays:f,startMinute:p.startMinute,endMinute:p.endMinute,blockingState:p.blockingState,activityPresetKey:p.kind==="main_activity"?"deep_work":p.kind==="secondary_activity"?"admin":p.kind==="holiday"?"holiday_leisure":p.kind==="rest"?"recovery_break":"maintenance",customSustainRateApPerHour:null});return}g({kind:"custom",title:"Custom block",color:"#7dd3fc",activityPresetKey:"maintenance",customSustainRateApPerHour:null})},options:[...qc.map(x=>({value:x.kind,label:x.title,description:`${jm(x.startMinute)}-${jm(x.endMinute)}`})),{value:"custom",label:"Custom",description:"Build a different recurring window."}]})})]})},{id:"shape",eyebrow:"Schedule",title:"Define when this recurring block should exist",description:"Weekdays and times describe the recurring pattern. Optional start and end dates bound when the template is active.",render:(c,g)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Rd,{draft:c}),e.jsx(le,{label:"Block title",children:e.jsx(ke,{value:c.title,onChange:x=>g({title:x.target.value}),placeholder:"Main Activity"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Start minute",children:e.jsx(ke,{type:"number",min:0,max:1440,step:15,value:c.startMinute,onChange:x=>g({startMinute:Number(x.target.value)||0})})}),e.jsx(le,{label:"End minute",children:e.jsx(ke,{type:"number",min:0,max:1440,step:15,value:c.endMinute,onChange:x=>g({endMinute:Number(x.target.value)||0})})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Start date",children:e.jsx(ke,{type:"date",value:Am(c.startsOn),onChange:x=>g({startsOn:x.target.value.trim()||null})})}),e.jsx(le,{label:"End date",children:e.jsx(ke,{type:"date",value:Am(c.endsOn),onChange:x=>g({endsOn:x.target.value.trim()||null})})})]}),e.jsx("div",{className:"text-sm leading-6 text-white/54",children:"Leave the end date empty to keep repeating indefinitely. Holiday blocks work well with all seven weekdays and `0-1440`, and they still carry AP load because leisure and holiday time are real activities."}),e.jsx(le,{label:"Weekdays",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:d5.map((x,p)=>{const f=c.weekDays.includes(p);return e.jsx("button",{type:"button",onClick:()=>g({weekDays:f?c.weekDays.filter(b=>b!==p):[...c.weekDays,p].sort((b,M)=>b-M)}),className:`rounded-full px-3 py-2 text-sm transition ${f?"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:x},x)})})})]})},{id:"policy",eyebrow:"Policy",title:"Tell Forge whether this block allows or blocks work",description:"Use blocked mode for time that should normally stop optional work. Use allowed mode for protected focus windows.",render:(c,g)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Rd,{draft:c}),e.jsx(le,{label:"Work effect",children:e.jsx(vt,{value:c.blockingState,onChange:x=>g({blockingState:x}),options:[{value:"blocked",label:"Blocks work",description:"Starting blocked tasks should require an explicit override."},{value:"allowed",label:"Allows work",description:"Use this for protected windows where the right tasks should fit."}]})}),e.jsx(le,{label:"Color",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[22px] border border-white/8 bg-white/6 px-4 py-3",children:[e.jsx("input",{className:"h-10 w-12 rounded-lg border border-white/10 bg-transparent",type:"color",value:c.color,onChange:x=>g({color:x.target.value})}),e.jsx(ke,{className:"border-none bg-transparent px-0 py-0",value:c.color,onChange:x=>g({color:x.target.value})})]})})]})}],[]);return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Calendar",title:h?"Edit work block":"Create a work block",description:h?"Adjust the recurring pattern, date bounds, or work policy for this block.":"Build recurring half-day, holiday, or custom blocks so Forge can understand when work should be protected or blocked.",value:n,onChange:l,steps:m,submitLabel:h?"Save changes":"Save work block",pending:i,pendingLabel:h?"Saving changes":"Saving",error:o,onSubmit:async()=>{if(!n.title.trim()){d("Give the block a title so it stays readable in the calendar.");return}if(n.weekDays.length===0){d("Select at least one weekday for the recurring block.");return}if(n.endMinute<=n.startMinute){d("The end minute needs to be later than the start minute.");return}if(n.startsOn&&n.endsOn&&n.endsOn<n.startsOn){d("The end date needs to be on or after the start date.");return}try{d(null),await a({...n,title:n.title.trim()}),s(!1)}catch(c){d(c instanceof Error?c.message:"Forge could not save this work block.")}}})}function Rs({className:t}){return e.jsx("div",{className:Z("surface-pulse rounded-2xl bg-white/[0.05]",t)})}function ns({header:t=!0,sideRail:s=!0,className:a,eyebrow:i,title:r,description:n,columns:l=2,blocks:o=4}){const d=Array.from({length:Math.max(2,o)});return e.jsxs("div",{className:Z("grid gap-5",a),"aria-hidden":"true",children:[t?e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:Z("h-3",i?"w-40":"w-32")}),e.jsx(Rs,{className:Z("h-12",r?"max-w-2xl":"max-w-3xl")}),e.jsx(Rs,{className:Z("h-5",n?"max-w-3xl":"max-w-2xl")})]}):null,e.jsxs("section",{className:Z("grid gap-5",s?"xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]":""),children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:"h-3 w-28"}),e.jsx(Rs,{className:"h-28 w-full"})]}),e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:"h-3 w-40"}),e.jsx("div",{className:Z("grid gap-3",l>1?"md:grid-cols-2":""),children:d.map((h,m)=>e.jsx(Rs,{className:"h-28 w-full"},m))})]})]}),s?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:"h-3 w-24"}),e.jsx(Rs,{className:"h-20 w-full"})]}),e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:"h-3 w-36"}),e.jsx(Rs,{className:"h-16 w-full"}),e.jsx(Rs,{className:"h-16 w-full"})]})]}):null]})]})}function dd({open:t,title:s,subtitle:a,items:i,position:r,onClose:n}){return u.useEffect(()=>{if(!t)return;let l=!1;const o=window.setTimeout(()=>{l=!0},0),d=m=>{m.key==="Escape"&&n()},h=()=>{l&&n()};return window.addEventListener("keydown",d),window.addEventListener("pointerdown",h),()=>{window.clearTimeout(o),window.removeEventListener("keydown",d),window.removeEventListener("pointerdown",h)}},[n,t]),!t||!r||typeof document>"u"?null:Ri.createPortal(e.jsx("div",{className:"fixed inset-0 z-[70]","aria-hidden":"true",children:e.jsxs("div",{className:"fixed z-[71] w-[min(22rem,calc(100vw-1.5rem))] rounded-[26px] border border-white/10 bg-[rgba(10,15,27,0.97)] p-2 shadow-[0_28px_80px_rgba(4,8,18,0.4)] backdrop-blur-xl",style:{left:Math.min(r.x,window.innerWidth-24-352),top:Math.min(r.y,window.innerHeight-24-320)},onPointerDown:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[20px] bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:s}),a?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:a}):null]}),e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.04] p-2 text-white/55 transition hover:bg-white/[0.08] hover:text-white",onClick:n,children:e.jsx(Tt,{className:"size-4"})})]}),e.jsx("div",{className:"mt-2 grid gap-1",children:i.map(l=>{const o=l.icon;return e.jsxs("button",{type:"button",disabled:l.disabled,onClick:()=>{l.disabled||(l.onSelect(),n())},className:Z("flex w-full items-start gap-3 rounded-[20px] px-4 py-3 text-left transition",l.disabled?"cursor-not-allowed bg-white/[0.02] text-white/28":l.tone==="danger"?"bg-rose-400/[0.05] text-rose-100 hover:bg-rose-400/[0.12]":"bg-white/[0.03] text-white/76 hover:bg-white/[0.08] hover:text-white"),children:[o?e.jsx("span",{className:Z("mt-0.5 rounded-[14px] p-2",l.disabled?"bg-white/[0.03] text-white/28":l.tone==="danger"?"bg-rose-400/[0.12] text-rose-100":"bg-[var(--primary)]/12 text-[var(--primary)]"),children:e.jsx(o,{className:"size-4"})}):null,e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:l.label}),l.description?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:l.description}):null]})]},l.id)})})]})}),document.body)}const gb="forge.calendar-display-preferences",Mm=["#7dd3fc","#34d399","#f59e0b","#fb7185","#60a5fa","#a3e635","#f97316","#22c55e"],$d={useCalendarColors:!0,calendarColors:{}};function fb(t){return typeof t=="string"&&/^#[0-9a-fA-F]{6}$/.test(t)}function bb(){if(typeof window>"u")return $d;const t=window.localStorage.getItem(gb);if(!t)return $d;try{const s=JSON.parse(t);return{useCalendarColors:s.useCalendarColors??!0,calendarColors:s.calendarColors&&typeof s.calendarColors=="object"?Object.fromEntries(Object.entries(s.calendarColors).filter(a=>fb(a[1]))):{}}}catch{return $d}}function g5(t){typeof window>"u"||window.localStorage.setItem(gb,JSON.stringify(t))}function vb(t){return Mm[t%Mm.length]??"#7dd3fc"}function wb(t,s){return Object.fromEntries(t.map((a,i)=>[a.id,fb(s[a.id])?s[a.id]:vb(i)]))}function Em(t){let s=0;for(let a=0;a<t.length;a+=1)s=s*31+t.charCodeAt(a)>>>0;return vb(s)}const Il=Ww(t=>({entry:null,setEntry:s=>t({entry:s}),clear:()=>t({entry:null}),completePaste:()=>t(s=>{var a;return{entry:((a=s.entry)==null?void 0:a.mode)==="cut"?null:s.entry}})}));function f5(t){const s=new Date(t);s.setUTCHours(9,0,0,0);const a=new Date(s.getTime()+3600*1e3);return{startAt:s.toISOString(),endAt:a.toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:"busy"}}function Lm(t){var l;const s=Math.max(60,Math.floor((Date.parse(t.endsAt)-Date.parse(t.startsAt))/1e3)),a=((l=ji().find(o=>o.key===t.activityPresetKey))==null?void 0:l.defaultRateApPerHour)??100/24,i=t.customSustainRateApPerHour??a,r=Number((s/3600*i).toFixed(2)),n=new Date().toISOString();return{id:`preview_${t.entityType}_${t.entityId}`,profileKey:`${String(t.entityType)}_${t.entityId}`,title:t.title,entityType:t.entityType,mode:"container",startupAp:0,totalCostAp:r,expectedDurationSeconds:s,sustainRateApPerHour:i,demandWeights:{activation:.1,focus:.35,vigor:.1,composure:.15,flow:.3},doubleCountPolicy:"container_only",sourceMethod:t.customSustainRateApPerHour!==null&&t.customSustainRateApPerHour!==void 0?"manual":t.activityPresetKey?"seeded":"inferred",costBand:i>=10?"standard":"light",recoveryEffect:0,metadata:{activityPresetKey:t.activityPresetKey??null,customSustainRateApPerHour:t.customSustainRateApPerHour??null},createdAt:n,updatedAt:n}}function Dm(t){const s=typeof t.location=="string"?t.location:"",a=t.place??{label:s,address:"",timezone:"",latitude:null,longitude:null,source:"",externalPlaceId:""};return{...t,place:{label:a.label||s,address:a.address??"",timezone:a.timezone??"",latitude:a.latitude??null,longitude:a.longitude??null,source:a.source??"",externalPlaceId:a.externalPlaceId??""}}}function Fm(t,s){const a=new Date(t.startAt),r=new Date(t.endAt).getTime()-a.getTime(),n=new Date(s);n.setUTCHours(a.getUTCHours(),a.getUTCMinutes(),0,0);const l=new Date(n.getTime()+r);return{startAt:n.toISOString(),endAt:l.toISOString()}}function _m(t){return{type:"calendar_event",eventId:t.id,title:t.title,description:t.description,location:t.location,startAt:t.startAt,endAt:t.endAt,timezone:t.timezone,availability:t.availability,preferredCalendarId:t.calendarId,categories:t.categories,links:t.links.map(s=>({entityType:s.entityType,entityId:s.entityId,relationshipType:s.relationshipType}))}}function b5(t){switch(t){case"apple":return"Apple";case"google":return"Google";case"caldav":return"CalDAV";case"native":return"Forge";default:return"Derived"}}function v5(t,s){var a;if(t.calendarId){const i=(a=s.get(t.calendarId))==null?void 0:a.trim();if(i)return i}return t.originType==="native"?"Forge only":b5(t.originType)}function Rm(t){switch(t){case"main_activity":return"Main activity";case"secondary_activity":return"Secondary activity";case"third_activity":return"Third activity";case"rest":return"Rest";case"holiday":return"Holiday";default:return"Custom"}}function $m(t){return t.startsOn&&t.endsOn?`${t.startsOn} to ${t.endsOn}`:t.startsOn?`From ${t.startsOn}`:t.endsOn?`Until ${t.endsOn}`:"Repeats with no end date"}function w5(){var we,Ie,Se,Ge,Be;const t=_t(),[s,a]=us(),i=jt(),r=Array.isArray(i.selectedUserIds)?i.selectedUserIds:[],n=fs(r),l=ct(),o=Il(xe=>xe.entry),d=Il(xe=>xe.setEntry),h=Il(xe=>xe.clear),m=Il(xe=>xe.completePaste),[c,g]=u.useState(()=>Mn()),[x,p]=u.useState(null),[f,b]=u.useState(null),[M,P]=u.useState(!1),[T,w]=u.useState(null),[j,v]=u.useState(!1),[y,E]=u.useState(!1),[S,B]=u.useState(null),[N,A]=u.useState(!1),[q,W]=u.useState(null),[Y,K]=u.useState(null),O=u.useMemo(()=>bb(),[]),[R,F]=u.useState(null),[H,G]=u.useState(null),[$,Q]=u.useState(null),X=s.get("timeboxId"),ae=u.useMemo(()=>{const xe=c.toISOString(),Ae=Pi(c,7).toISOString();return{from:xe,to:Ae}},[c]),Pe=Me({queryKey:["forge-calendar-overview",ae.from,ae.to,...r],queryFn:()=>Pr({...ae,userIds:r})}),Ne=Me({queryKey:["forge-life-force",...r],queryFn:()=>Ki(r)}),fe=["forge-calendar-overview",ae.from,ae.to,...r],V=xe=>{if(xe.deletedAt)return!1;const Ae=new Date(xe.startAt).getTime();return Ae>=new Date(ae.from).getTime()&&Ae<new Date(ae.to).getTime()},Ce=xe=>{l.setQueryData(fe,Ae=>Ae&&xe(Ae))},L=async()=>{await Promise.all([l.invalidateQueries({queryKey:["forge-calendar-overview"]}),l.invalidateQueries({queryKey:["forge-snapshot"]}),l.invalidateQueries({queryKey:["task-context"]}),l.invalidateQueries({queryKey:["project-board"]})])},D=De({mutationFn:xe=>lN({...xe,userId:xe.userId??n}),onSuccess:L}),_=De({mutationFn:({templateId:xe,patch:Ae})=>oN(xe,Ae),onSuccess:L}),ee=De({mutationFn:dN,onSuccess:L}),U=De({mutationFn:xe=>Tg({...xe,userId:n}),onSuccess:L}),te=De({mutationFn:({timeboxId:xe,startsAt:Ae,endsAt:He})=>Ac(xe,{startsAt:Ae,endsAt:He}),onSuccess:L}),J=De({mutationFn:({timeboxId:xe,patch:Ae})=>Ac(xe,Ae),onSuccess:L}),ve=De({mutationFn:Pg,onSuccess:async()=>{B(null),E(!1),await L()}}),pe=De({mutationFn:xe=>cN({...xe,userId:xe.userId??n}),onMutate:async xe=>{var tt,k,se,Le,ze,We,gt;Q({tone:"saving",message:"Saving event changes in the background…"}),await l.cancelQueries({queryKey:fe});const Ae=l.getQueryData(fe),He=(Ae==null?void 0:Ae.calendar.calendars.find(Mt=>Mt.canWrite&&Mt.selectedForSync))??(Ae==null?void 0:Ae.calendar.calendars.find(Mt=>Mt.canWrite))??null,ot=new Date().toISOString(),It=`calendar_event_optimistic_${Date.now()}`,Oe={id:It,connectionId:(He==null?void 0:He.connectionId)??null,calendarId:xe.preferredCalendarId===void 0?(He==null?void 0:He.id)??null:xe.preferredCalendarId,remoteId:null,ownership:"forge",originType:"native",status:"confirmed",title:xe.title,description:xe.description??"",location:xe.location??"",place:{label:((tt=xe.place)==null?void 0:tt.label)??xe.location??"",address:((k=xe.place)==null?void 0:k.address)??"",timezone:((se=xe.place)==null?void 0:se.timezone)??xe.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",latitude:((Le=xe.place)==null?void 0:Le.latitude)??null,longitude:((ze=xe.place)==null?void 0:ze.longitude)??null,source:((We=xe.place)==null?void 0:We.source)??"forge",externalPlaceId:((gt=xe.place)==null?void 0:gt.externalPlaceId)??""},startAt:xe.startAt,endAt:xe.endAt,timezone:xe.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",isAllDay:xe.isAllDay??!1,availability:xe.availability??"busy",eventType:xe.eventType??"general",categories:xe.categories??[],sourceMappings:[],links:(xe.links??[]).map((Mt,Qt)=>({id:`calendar_event_link_optimistic_${Date.now()}_${Qt}`,entityType:Mt.entityType,entityId:Mt.entityId,relationshipType:Mt.relationshipType??"context",createdAt:ot,updatedAt:ot})),actionProfile:Lm({entityType:"calendar_event",entityId:It,title:xe.title,startsAt:xe.startAt,endsAt:xe.endAt,activityPresetKey:xe.activityPresetKey??null,customSustainRateApPerHour:xe.customSustainRateApPerHour??null}),remoteUpdatedAt:null,deletedAt:null,createdAt:ot,updatedAt:ot};return Ae&&V(Oe)&&Ce(Mt=>({...Mt,calendar:{...Mt.calendar,events:[Oe,...Mt.calendar.events]}})),{previous:Ae,optimisticEventId:Oe.id}},onError:(xe,Ae,He)=>{He!=null&&He.previous&&l.setQueryData(fe,He.previous),Q({tone:"error",message:xe instanceof Error?xe.message:"Forge could not sync that event change."})},onSuccess:({event:xe},Ae,He)=>{Q(null),Ce(ot=>({...ot,calendar:{...ot.calendar,events:(V(xe)?[xe,...ot.calendar.events.filter(It=>It.id!==(He==null?void 0:He.optimisticEventId))]:ot.calendar.events.filter(It=>It.id!==(He==null?void 0:He.optimisticEventId))).filter((It,Oe,tt)=>tt.findIndex(k=>k.id===It.id)===Oe)}}))},onSettled:L}),Ee=De({mutationFn:({eventId:xe,patch:Ae})=>uN(xe,Ae),onMutate:async({eventId:xe,patch:Ae})=>{Q({tone:"saving",message:"Saving event changes in the background…"}),await l.cancelQueries({queryKey:fe});const He=l.getQueryData(fe);return He&&Ce(ot=>{var k,se,Le,ze,We;const It=ot.calendar.events.find(gt=>gt.id===xe);if(!It)return ot;const Oe=Dm(It),tt={...Oe,...Ae,place:Ae.place?{...Oe.place,...Ae.place}:Oe.place,calendarId:Ae.preferredCalendarId===void 0?Oe.calendarId:Ae.preferredCalendarId,links:((k=Ae.links)==null?void 0:k.map((gt,Mt)=>{var Qt,Ds;return{id:((Qt=Oe.links[Mt])==null?void 0:Qt.id)??`calendar_event_link_optimistic_${Date.now()}_${Mt}`,entityType:gt.entityType,entityId:gt.entityId,relationshipType:gt.relationshipType??"context",createdAt:((Ds=Oe.links[Mt])==null?void 0:Ds.createdAt)??Oe.createdAt,updatedAt:new Date().toISOString()}}))??Oe.links,actionProfile:Lm({entityType:"calendar_event",entityId:xe,title:Ae.title??Oe.title,startsAt:Ae.startAt??Oe.startAt,endsAt:Ae.endAt??Oe.endAt,activityPresetKey:Ae.activityPresetKey===void 0?(Le=(se=Oe.actionProfile)==null?void 0:se.metadata)==null?void 0:Le.activityPresetKey:Ae.activityPresetKey,customSustainRateApPerHour:Ae.customSustainRateApPerHour===void 0?typeof((We=(ze=Oe.actionProfile)==null?void 0:ze.metadata)==null?void 0:We.customSustainRateApPerHour)=="number"?Oe.actionProfile.metadata.customSustainRateApPerHour:null:Ae.customSustainRateApPerHour}),updatedAt:new Date().toISOString()};return{...ot,calendar:{...ot.calendar,events:ot.calendar.events.map(gt=>gt.id===xe?tt:gt).filter(V)}}}),{previous:He}},onError:(xe,Ae,He)=>{He!=null&&He.previous&&l.setQueryData(fe,He.previous),Q({tone:"error",message:xe instanceof Error?xe.message:"Forge could not sync that event change."})},onSuccess:({event:xe})=>{Q(null),Ce(Ae=>({...Ae,calendar:{...Ae.calendar,events:Ae.calendar.events.map(He=>He.id===xe.id?xe:He).filter(V)}}))},onSettled:L}),ce=De({mutationFn:hN,onMutate:async xe=>{Q({tone:"saving",message:"Removing the event in the background…"}),await l.cancelQueries({queryKey:fe});const Ae=l.getQueryData(fe);return Ae&&Ce(He=>({...He,calendar:{...He.calendar,events:He.calendar.events.filter(ot=>ot.id!==xe)}})),{previous:Ae}},onError:(xe,Ae,He)=>{He!=null&&He.previous&&l.setQueryData(fe,He.previous),Q({tone:"error",message:xe instanceof Error?xe.message:"Forge could not delete that event."})},onSuccess:()=>{Q(null)},onSettled:L}),ue=(we=Pe.data)==null?void 0:we.calendar,Fe=u.useMemo(()=>cb(c),[c]),ye=u.useMemo(()=>ue?{...ue,events:ue.events.map(Dm)}:{generatedAt:"",providers:[],connections:[],calendars:[],events:[],workBlockTemplates:[],workBlockInstances:[],timeboxes:[]},[ue]),he=u.useMemo(()=>new Map(ye.calendars.map(xe=>[xe.id,kr(xe)])),[ye.calendars]),me=u.useMemo(()=>wb(ye.calendars,O.calendarColors),[O.calendarColors,ye.calendars]),Ke=pe.isPending||Ee.isPending||ce.isPending,ge=ye.timeboxes.filter(xe=>xe.status==="planned"),C=ye.calendars.filter(xe=>xe.canWrite),ne=(xe,Ae)=>Ae?`${xe} · ${Ae}`:xe,Re=[...i.snapshot.goals.map(xe=>({entityType:"goal",entityId:xe.id,label:xe.title,subtitle:ne("Goal",ls(xe.user))})),...i.snapshot.projects.map(xe=>({entityType:"project",entityId:xe.id,label:xe.title,subtitle:ne("Project",ls(xe.user))})),...i.snapshot.tasks.map(xe=>({entityType:"task",entityId:xe.id,label:xe.title,subtitle:ne("Task",ls(xe.user))})),...i.snapshot.strategies.map(xe=>({entityType:"strategy",entityId:xe.id,label:xe.title,subtitle:ne("Strategy",ls(xe.user))})),...i.snapshot.habits.map(xe=>({entityType:"habit",entityId:xe.id,label:xe.title,subtitle:ne("Habit",ls(xe.user))}))],at=u.useMemo(()=>new Map(Re.map(xe=>[`${xe.entityType}:${xe.entityId}`,xe.label])),[Re]),lt=ye.connections.length===0?"No providers connected":`${ye.connections.filter(xe=>xe.status==="connected").length}/${ye.connections.length} healthy`,Te=(o==null?void 0:o.items.filter(xe=>xe.type==="calendar_event"))??[];u.useEffect(()=>{if(!X)return;const xe=ye.timeboxes.find(He=>He.id===X);if(!xe)return;const Ae=Mn(new Date(xe.startsAt));if(Ae.getTime()!==c.getTime()){g(Ae);return}((S==null?void 0:S.id)!==xe.id||!y)&&(B(xe),E(!0))},[X,ye.timeboxes,S==null?void 0:S.id,y,c]);const qe=()=>{if(!X)return;const xe=new URLSearchParams(s);xe.delete("timeboxId"),a(xe,{replace:!0})},Je=xe=>{E(xe),xe||(B(null),qe())},Ze=xe=>{W(null),F(f5(xe)),A(!0)},re=async(xe,Ae)=>{const He=Fm({startAt:xe.startAt,endAt:xe.endAt},Ae);await Ee.mutateAsync({eventId:xe.id,patch:He})},oe=async xe=>{if(Te.length!==0){for(const Ae of Te){const He=Fm(Ae,xe);(o==null?void 0:o.mode)==="cut"?await Ee.mutateAsync({eventId:Ae.eventId,patch:He}):await pe.mutateAsync({title:Ae.title,description:Ae.description,location:Ae.location,startAt:He.startAt,endAt:He.endAt,timezone:Ae.timezone,availability:Ae.availability,preferredCalendarId:Ae.preferredCalendarId,categories:Ae.categories,links:Ae.links})}m()}},je=u.useMemo(()=>{if(!H)return[];if(H.kind==="day"){const Ae=Fe.find(He=>He.toISOString().slice(0,10)===H.dayKey);return Ae?[{id:"create-event",label:"Create event",description:"Open the event guide with this day already selected.",icon:ra,onSelect:()=>Ze(Ae)},{id:"create-work-block",label:"Create work block",description:"Open the guided work-block flow while you are looking at this day.",icon:Sn,onSelect:()=>{w(null),P(!0)}},{id:"paste",label:(o==null?void 0:o.mode)==="cut"?"Paste moved event":"Paste copied event",description:Te.length>0?`${Te.length} calendar item${Te.length===1?"":"s"} ready to paste here.`:o?"The current clipboard entry does not contain calendar events.":"Copy or cut an event first, then paste it into this day.",icon:Hw,disabled:Te.length===0,onSelect:()=>void oe(Ae)}]:[]}if(H.kind==="work-block"){const Ae=ye.workBlockTemplates.find(He=>He.id===H.templateId);return Ae?[{id:"edit-work-block",label:"Edit",description:"Adjust the recurring pattern, date bounds, or work policy.",icon:ra,onSelect:()=>{w(Ae),P(!0)}},{id:"delete-work-block",label:"Delete",description:"Remove this recurring work block from Forge.",icon:$t,tone:"danger",onSelect:()=>{(T==null?void 0:T.id)===Ae.id&&w(null),ee.mutateAsync(Ae.id)}}]:[]}const xe=ye.events.find(Ae=>Ae.id===H.eventId);return xe?[{id:"rename",label:"Quick rename",description:"Change the event title without opening the full event flow.",icon:ra,onSelect:()=>K(xe)},{id:"copy",label:"Copy",description:"Put this event on the Forge clipboard so you can paste it into another day.",icon:Wx,onSelect:()=>d({id:`clipboard_${xe.id}_${Date.now()}`,mode:"copy",source:"calendar",label:xe.title,createdAt:new Date().toISOString(),items:[_m(xe)]})},{id:"cut",label:"Cut",description:"Move this event by pasting it into another day.",icon:Go,onSelect:()=>d({id:`clipboard_cut_${xe.id}_${Date.now()}`,mode:"cut",source:"calendar",label:xe.title,createdAt:new Date().toISOString(),items:[_m(xe)]})},{id:"delete",label:"Delete",description:"Remove the event from Forge and delete any connected remote projection.",icon:$t,tone:"danger",onSelect:()=>{(o==null?void 0:o.mode)==="cut"&&Te.some(Ae=>Ae.eventId===xe.id)&&h(),ce.mutateAsync(xe.id)}}]:[]},[h,Te,o,Fe,ce,ee,H,ye.events,ye.workBlockTemplates,T,d]);return Pe.isLoading?e.jsx(ns,{}):Pe.isError||!Pe.data?e.jsx(st,{eyebrow:"Calendar",error:Pe.error??new Error("Calendar data is unavailable"),onRetry:()=>void Pe.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(rt,{entityKind:"project",titleText:"Calendar",title:"Calendar",description:"See the real week first, then open guided flows for work blocks, task rules, timeboxing, and provider setup.",badge:`${ye.connections.length} connection${ye.connections.length===1?"":"s"}`}),(Ie=Ne.data)!=null&&Ie.lifeForce?e.jsxs(ie,{className:"grid gap-3 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(15,25,36,0.98),rgba(9,15,26,0.96))] p-4 md:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force today"}),e.jsxs("div",{className:"mt-2 text-3xl font-semibold text-white",children:[Math.round(Ne.data.lifeForce.spentTodayAp),e.jsxs("span",{className:"ml-2 text-lg text-white/44",children:["/ ",Math.round(Ne.data.lifeForce.dailyBudgetAp)," AP"]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Instant headroom"}),e.jsxs("div",{className:"mt-2 text-2xl font-semibold text-[var(--primary)]",children:[Ne.data.lifeForce.instantFreeApPerHour.toFixed(1)," AP/h"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Calendar containers now speak the same AP language as live work."})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Forecast"}),e.jsxs("div",{className:"mt-2 text-2xl font-semibold text-white",children:[Math.round(Ne.data.lifeForce.forecastAp)," AP"]}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:["Planned remaining ",kt(Ne.data.lifeForce.plannedRemainingAp)]})]})]}):null,e.jsxs(ie,{className:"grid gap-4 rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,28,39,0.985),rgba(10,17,29,0.985))]",children:[e.jsx(ub,{description:"The calendar is the priority surface here. Connected provider events, recurring work blocks, and owned task timeboxes all stay visible together.",weekStart:c,status:$?e.jsx("div",{className:`inline-flex max-w-full items-center gap-2 rounded-full px-3 py-1.5 text-xs ${$.tone==="error"?"border border-rose-400/20 bg-rose-400/10 text-rose-200":"border border-[var(--primary)]/18 bg-[var(--primary)]/12 text-[var(--primary)]"}`,children:$.message}):null,badges:e.jsxs(e.Fragment,{children:[(Se=Ne.data)!=null&&Se.lifeForce?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[Math.round(Ne.data.lifeForce.spentTodayAp),"/",Math.round(Ne.data.lifeForce.dailyBudgetAp)," AP"]}):null,Ke?e.jsxs(I,{className:"bg-white/[0.08] text-white/78",children:[e.jsx(qs,{className:"mr-1 size-3.5 animate-spin"}),"Syncing changes"]}):null,o?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[o.mode==="cut"?"Cut":"Copied"," · ",o.label]}):null]}),onPrevious:()=>g(Pi(c,-7)),onCurrent:()=>g(Mn()),onNext:()=>g(Pi(c,7))}),e.jsx("div",{className:"grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(min(100%,17rem),1fr))] 2xl:[grid-template-columns:repeat(7,minmax(0,1fr))]",children:Fe.map(xe=>{const Ae=xe.toISOString().slice(0,10),He=ye.events.filter(Oe=>Oe.startAt.slice(0,10)===Ae&&!Oe.deletedAt),ot=ye.workBlockInstances.filter(Oe=>Oe.dateKey===Ae),It=ye.timeboxes.filter(Oe=>Oe.startsAt.slice(0,10)===Ae);return e.jsxs("div",{"data-calendar-day":Ae,onClick:Oe=>{Oe.target.closest("[data-calendar-item='true']")||G({kind:"day",dayKey:Ae,position:{x:Oe.clientX,y:Oe.clientY}})},onDragOver:Oe=>{Oe.preventDefault()},onDrop:Oe=>{Oe.preventDefault();const tt=Oe.dataTransfer.getData("text/forge-event-id")||f;if(tt){const Qt=ye.events.find(Ds=>Ds.id===tt);Qt&&re(Qt,xe),b(null);return}const k=Oe.dataTransfer.getData("text/forge-timebox-id")||x;if(!k)return;const se=ye.timeboxes.find(Qt=>Qt.id===k);if(!se)return;const Le=new Date(se.startsAt),We=new Date(se.endsAt).getTime()-Le.getTime(),gt=new Date(xe);gt.setUTCHours(Le.getUTCHours(),Le.getUTCMinutes(),0,0);const Mt=new Date(gt.getTime()+We);te.mutateAsync({timeboxId:k,startsAt:gt.toISOString(),endsAt:Mt.toISOString()}),p(null)},className:"min-w-0 overflow-hidden rounded-[24px] border border-white/6 bg-white/[0.03] p-3 transition hover:border-white/12 hover:bg-white/[0.045]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] bg-[rgba(10,16,30,0.96)] px-3 py-2 text-sm font-medium text-white",children:[e.jsx("span",{className:"min-w-0 truncate",children:Ai(xe)}),e.jsx("button",{type:"button","aria-label":`Open actions for ${Ai(xe)}`,className:"rounded-full bg-white/[0.06] p-2 text-white/58 transition hover:bg-white/[0.1] hover:text-white",onClick:Oe=>{Oe.stopPropagation(),G({kind:"day",dayKey:Ae,position:{x:Oe.clientX,y:Oe.clientY}})},children:e.jsx(Ci,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-3 grid min-w-0 gap-2",children:[ot.map(Oe=>e.jsxs("div",{"data-calendar-item":"true",className:"min-w-0 overflow-hidden rounded-[18px] px-3 py-2 text-sm text-white",style:{backgroundColor:`${Oe.color}22`,border:`1px solid ${Oe.color}55`},children:[(()=>{const tt=Q2(Oe);return e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"min-w-0 [overflow-wrap:anywhere] font-medium",children:Oe.title}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(I,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:Oe.blockingState}),e.jsx(I,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:Rm(Oe.kind)}),tt.rateApPerHour>0?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:"sm",className:"shrink-0 bg-[var(--primary)]/14 text-[var(--primary)]",children:Kt(tt.rateApPerHour)}),e.jsx(I,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/72",children:kt(tt.totalAp)})]}):e.jsx(I,{size:"sm",className:"shrink-0 bg-emerald-400/12 text-emerald-100",children:"Recovery"})]})]}),e.jsx("button",{type:"button","aria-label":`Open actions for ${Oe.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:k=>{k.stopPropagation(),G({kind:"work-block",templateId:Oe.templateId,position:{x:k.clientX,y:k.clientY}})},children:e.jsx(Ci,{className:"size-4"})})]})})(),e.jsxs("div",{className:"mt-1 text-white/60",children:[new Date(Oe.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(Oe.endAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),e.jsx("div",{className:"mt-2 text-xs text-white/48",children:$m(ye.workBlockTemplates.find(tt=>tt.id===Oe.templateId)??{id:Oe.templateId,title:Oe.title,kind:Oe.kind,color:Oe.color,startsOn:null,endsOn:null,blockingState:Oe.blockingState,createdAt:Oe.createdAt,updatedAt:Oe.updatedAt})})]},Oe.id)),He.map(Oe=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:tt=>{b(Oe.id),tt.dataTransfer.setData("text/forge-event-id",Oe.id)},onClick:tt=>{tt.stopPropagation(),W(Oe),F(null),A(!0)},className:`min-w-0 cursor-move overflow-hidden rounded-[18px] px-3 py-2 text-left text-sm text-white/82 transition ${O.useCalendarColors?"hover:brightness-110":"border border-white/10 bg-white/[0.05] hover:border-white/18 hover:bg-white/[0.08] hover:shadow-[0_12px_32px_rgba(4,9,20,0.22)]"}`,style:O.useCalendarColors?{backgroundColor:`${(Oe.calendarId?me[Oe.calendarId]:null)??Em(`origin:${Oe.originType}`)}1f`,border:`1px solid ${(Oe.calendarId?me[Oe.calendarId]:null)??Em(`origin:${Oe.originType}`)}55`}:void 0,children:[(wn(Oe),e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-2 [overflow-wrap:anywhere] font-medium",children:Oe.title}),e.jsxs("div",{className:"mt-1 text-white/55",children:[new Date(Oe.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(Oe.endAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsx("button",{type:"button","aria-label":`Open quick actions for ${Oe.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:tt=>{tt.stopPropagation(),G({kind:"event",eventId:Oe.id,position:{x:tt.clientX,y:tt.clientY}})},children:e.jsx(Ci,{className:"size-4"})})})]})),e.jsxs("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(I,{size:"sm",className:"max-w-full bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/70",children:v5(Oe,he)}),wn(Oe).rateApPerHour>0?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:"sm",className:"bg-[var(--primary)]/14 px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-[var(--primary)]",children:Kt(wn(Oe).rateApPerHour)}),e.jsx(I,{size:"sm",className:"bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/70",children:kt(wn(Oe).totalAp)})]}):null,Oe.calendarId&&O.useCalendarColors?e.jsx("span",{"aria-hidden":"true",className:"size-2.5 shrink-0 rounded-full",style:{backgroundColor:me[Oe.calendarId]}}):null]}),Oe.place.address||Oe.place.timezone?e.jsxs("div",{className:"mt-2 text-xs leading-5 text-white/50",children:[Oe.place.address||Oe.location,Oe.place.address&&Oe.place.timezone?" · ":"",Oe.place.timezone]}):null,Oe.links.length>0?e.jsx("div",{className:"mt-2 flex min-w-0 flex-wrap gap-1.5",children:Oe.links.slice(0,3).map(tt=>{const k=Vt(tt.entityType);return k?e.jsx(Ue,{kind:k,label:at.get(`${tt.entityType}:${tt.entityId}`)??tt.entityType,compact:!0,gradient:!1},tt.id):e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:tt.entityType},tt.id)})}):null]},Oe.id)),It.map(Oe=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:tt=>{p(Oe.id),tt.dataTransfer.setData("text/forge-timebox-id",Oe.id)},onClick:()=>{B(Oe),E(!0)},className:"min-w-0 cursor-move overflow-hidden rounded-[18px] border border-[rgba(192,193,255,0.18)] bg-[linear-gradient(180deg,rgba(67,72,112,0.34),rgba(43,47,80,0.32))] px-3 py-2 text-left text-sm text-white/82 shadow-[inset_0_0_0_1px_rgba(192,193,255,0.08)] transition hover:border-[rgba(192,193,255,0.32)] hover:bg-[linear-gradient(180deg,rgba(74,79,122,0.4),rgba(48,53,92,0.36))]",children:[(()=>{const tt=Mr(Oe);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex min-w-0 items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-2 font-medium leading-5 text-white",children:Oe.title}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-white/58",children:[e.jsx(Ia,{className:"size-3.5 shrink-0"}),new Date(Oe.startsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(Oe.endsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})}),e.jsxs("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(I,{size:"sm",className:"bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/72",children:Oe.status}),e.jsx(I,{size:"sm",className:"bg-[var(--primary)]/14 px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-[var(--primary)]",children:Kt(tt.rateApPerHour)}),e.jsx(I,{size:"sm",className:"bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/72",children:kt(tt.totalAp)})]})]})})(),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:tt=>{tt.stopPropagation(),B(Oe),E(!0)},className:"rounded-[999px] bg-white/[0.08] px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-white/78 transition hover:bg-white/[0.14]",children:"Edit"}),e.jsx("button",{type:"button",onClick:tt=>{tt.stopPropagation(),t(`/tasks/${Oe.taskId}`)},className:"rounded-[999px] bg-white/[0.08] px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-white/78 transition hover:bg-white/[0.14]",children:"Open task"})]})]},Oe.id)),ot.length===0&&He.length===0&&It.length===0?e.jsx("div",{className:"min-h-[10rem] rounded-[18px] border border-dashed border-white/8 px-3 py-4 text-sm leading-8 text-white/42",children:"Nothing scheduled here yet. Click inside this day to create, block, or paste."}):null]})]},Ae)})})]}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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(ra,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Create event"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Add a native Forge event with linked context."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Create a real calendar event even with no provider connected, then project it remotely whenever you choose."}),e.jsx("div",{className:"mt-4",children:e.jsxs(z,{onClick:()=>{w(null),W(null),F(null),A(!0)},children:[e.jsx(ra,{className:"size-4"}),"Open event guide"]})})]}),e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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(Sn,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Create work block"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Block main activity or protect creative windows."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Open the guided flow to create half-day presets, holidays, or custom recurring work blocks."}),e.jsx("div",{className:"mt-4",children:e.jsxs(z,{onClick:()=>{w(null),P(!0)},children:[e.jsx(Sn,{className:"size-4"}),"Open work-block guide"]})})]}),e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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(Ht,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Plan timebox"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Let Forge recommend valid upcoming slots."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Choose a task, review the suggested windows, and schedule directly into the calendar."}),e.jsx("div",{className:"mt-4",children:e.jsxs(z,{onClick:()=>E(!0),children:[e.jsx(Ht,{className:"size-4"}),"Open planning guide"]})})]}),e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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(Es,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Manage provider settings"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:lt})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Provider connections and setup instructions now live in Settings so the calendar view can stay focused on the week."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(z,{variant:"secondary",onClick:()=>t("/settings/calendar"),children:[e.jsx(Ls,{className:"size-4"}),"Open calendar settings"]}),e.jsxs(z,{variant:"secondary",onClick:()=>t("/settings/calendar?intent=connect"),children:[e.jsx(Es,{className:"size-4"}),"Connect provider"]})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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/45",children:"This week"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Quick status for the currently visible week."})]}),e.jsxs(z,{variant:"secondary",onClick:()=>void Pe.refetch(),children:[e.jsx(qs,{className:"size-4"}),"Refresh view"]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Provider events"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:ye.events.length})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Work blocks"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:ye.workBlockInstances.length})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Planned timeboxes"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:ge.length})]})]})]}),e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Guided actions"}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>v(!0),className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4 text-left transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:"Adjust task blocking rules"}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:"Guided"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Decide which work blocks, calendar conditions, and event keywords should block or allow a task."})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:"Active templates"}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:ye.workBlockTemplates.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[ye.workBlockTemplates.slice(0,4).map(xe=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/74",children:[e.jsx("div",{className:"font-medium text-white",children:xe.title}),e.jsxs("div",{className:"mt-1 text-white/56",children:[Rm(xe.kind)," · ",xe.weekDays.length," day",xe.weekDays.length===1?"":"s"," · ",xe.blockingState]}),e.jsx("div",{className:"mt-1 text-white/46",children:$m(xe)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(z,{variant:"secondary",size:"sm",onClick:()=>{w(xe),P(!0)},children:[e.jsx(ra,{className:"size-3.5"}),"Edit"]}),e.jsxs(z,{variant:"secondary",size:"sm",onClick:()=>void ee.mutateAsync(xe.id),children:[e.jsx($t,{className:"size-3.5"}),"Delete"]})]})]},xe.id)),ye.workBlockTemplates.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No recurring templates yet. Open the work-block guide to create the first one."}):null]})]})]})]})]})]}),e.jsx(x5,{open:M,onOpenChange:xe=>{P(xe),xe||w(null)},pending:D.isPending||_.isPending,template:T,onSubmit:async xe=>{if(T){await _.mutateAsync({templateId:T.id,patch:xe});return}await D.mutateAsync(xe)}}),e.jsx(mb,{open:j,onOpenChange:v,tasks:i.snapshot.tasks,onSave:async({taskId:xe,schedulingRules:Ae,plannedDurationSeconds:He})=>{await Ec(xe,{schedulingRules:Ae,plannedDurationSeconds:He}),await i.refresh(),await L(),await l.invalidateQueries({queryKey:["task-context",xe]})}}),e.jsx(xb,{open:y,onOpenChange:Je,tasks:i.snapshot.tasks,editingTimebox:S,from:ae.from,to:ae.to,onCreateTimebox:async xe=>{await U.mutateAsync(xe)},onUpdateTimebox:async(xe,Ae)=>{await J.mutateAsync({timeboxId:xe,patch:Ae})},onDeleteTimebox:async xe=>{await ve.mutateAsync(xe),qe()}}),e.jsx(l5,{open:N,onOpenChange:xe=>{A(xe),xe||(W(null),F(null))},writableCalendars:C,linkOptions:Re,event:q,seed:R??void 0,onSubmit:async xe=>{if(q){const Ae=q.id;A(!1),W(null),F(null),Ee.mutateAsync({eventId:Ae,patch:xe}).catch(()=>{});return}else{A(!1),W(null),F(null),pe.mutateAsync(xe).catch(()=>{});return}},pending:pe.isPending||Ee.isPending}),e.jsx(o5,{open:Y!==null,onOpenChange:xe=>{xe||K(null)},initialTitle:(Y==null?void 0:Y.title)??"",pending:Ee.isPending,onSubmit:async xe=>{if(!Y)return;const Ae=Y.id;K(null),Ee.mutateAsync({eventId:Ae,patch:{title:xe}}).catch(()=>{})}}),e.jsx(dd,{open:H!==null,title:(H==null?void 0:H.kind)==="event"?((Ge=ye.events.find(xe=>xe.id===H.eventId))==null?void 0:Ge.title)??"Event actions":(H==null?void 0:H.kind)==="work-block"?((Be=ye.workBlockTemplates.find(xe=>xe.id===H.templateId))==null?void 0:Be.title)??"Work block actions":(H==null?void 0:H.kind)==="day"?Ai(Fe.find(xe=>xe.toISOString().slice(0,10)===H.dayKey)??c):"Calendar actions",subtitle:(H==null?void 0:H.kind)==="day"?"Choose what to create or paste into this day.":(H==null?void 0:H.kind)==="work-block"?"Edit or remove this recurring work block.":o?`Clipboard ready: ${o.label}`:"Quick calendar event actions.",items:je,position:(H==null?void 0:H.position)??null,onClose:()=>G(null)})]})}function Bi({entityType:t,entityId:s,view:a,label:i="Open in graph",variant:r="secondary",size:n}){const l=_t();return e.jsxs(z,{variant:r,size:n,onClick:()=>l(H2(t,s,{view:a})),children:[e.jsx($r,{className:"size-4"}),i]})}function Tl(t,s){const a=[],i=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let r=0,n=null,l=0;for(;(n=i.exec(t))!==null;){if(n.index>r&&(a.push(e.jsx(u.Fragment,{children:t.slice(r,n.index)},`${s}-text-${l}`)),l+=1),n[1]&&n[2]){const o=n[2].trim(),d=n[1].startsWith("!"),h=o.indexOf("|"),m=h>=0?o.slice(0,h).trim():o,c=h>=0?o.slice(h+1).trim():m;if(m.toLowerCase().startsWith("forge:")){const[,g,x]=m.split(":"),p=g&&x?li(g,x):null,f=p?ni(p):null;a.push(f?e.jsxs("a",{href:f,className:"inline-flex items-center gap-1 rounded-full bg-amber-400/10 px-2 py-0.5 text-[0.9em] text-amber-100 transition hover:bg-amber-400/18",children:[e.jsx("span",{className:"text-[0.72em] uppercase tracking-[0.14em] text-amber-200/72",children:"Forge"}),e.jsx("span",{children:c})]},`${s}-forge-${l}`):e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-white/[0.06] px-2 py-0.5 text-[0.9em] text-white/66",children:c},`${s}-forge-${l}`))}else{const g=ni(`/wiki/page/${encodeURIComponent(m)}`);a.push(e.jsxs("a",{href:g,className:Z("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[0.9em] transition",d?"bg-cyan-400/14 text-cyan-50 hover:bg-cyan-400/22":"bg-white/[0.06] text-[var(--secondary)] hover:bg-white/[0.1]"),children:[d?e.jsx("span",{className:"text-[0.72em] uppercase tracking-[0.14em] text-cyan-100/68",children:"Embed"}):null,e.jsx("span",{children:c})]},`${s}-wiki-${l}`))}}else if(n[3]&&n[4]){const o=n[4].trim(),d=/^https?:\/\//i.test(o);a.push(e.jsx("a",{href:o,className:"text-[var(--secondary)] underline decoration-[rgba(125,211,252,0.4)] underline-offset-4 transition hover:text-white",target:d?"_blank":void 0,rel:d?"noreferrer":void 0,children:n[3]},`${s}-link-${l}`))}else n[5]?a.push(e.jsx("code",{className:"rounded bg-white/[0.08] px-1.5 py-0.5 text-[0.92em] text-white/90",children:n[5]},`${s}-code-${l}`)):n[6]?a.push(e.jsx("strong",{className:"font-semibold text-white",children:n[6]},`${s}-strong-${l}`)):n[7]&&a.push(e.jsx("em",{className:"italic text-white/88",children:n[7]},`${s}-em-${l}`));r=i.lastIndex,l+=1}return r<t.length&&a.push(e.jsx(u.Fragment,{children:t.slice(r)},`${s}-tail-${l}`)),a}function y5(t){const s=t.replace(/\r/g,"").split(`
|
|
20
|
+
${o.trim()}`,author:"Forge quick capture",userId:s??null,links:[]}),onSuccess:async()=>{l(""),d(""),await a.invalidateQueries({queryKey:["notes-index"]})}}),m=De({mutationFn:async()=>kg({title:n.trim()||"Quick capture",contentMarkdown:o.trim(),summary:o.trim().slice(0,180),author:"Forge quick capture"}),onSuccess:async()=>{l(""),d(""),await a.invalidateQueries({queryKey:["wiki-pages"]})}});function c(g,x=g){const p=r.current;if(!p)return;const f=p.selectionStart??0,b=p.selectionEnd??0,M=o.slice(f,b),P=`${o.slice(0,f)}${g}${M}${x}${o.slice(b)}`;d(P),requestAnimationFrame(()=>{p.focus(),p.selectionStart=f+g.length,p.selectionEnd=b+g.length})}return e.jsxs("div",{className:"grid h-full min-h-0 gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(ai,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Quick capture"})]}),e.jsx("input",{ref:i,value:n,onChange:g=>l(g.target.value),className:"w-full rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2.5 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]",placeholder:"Title"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{label:"B",action:()=>c("**")},{label:"I",action:()=>c("_")},{label:"H1",action:()=>c("# ","")},{label:"[]",action:()=>c("- [ ] ","")}].map(g=>e.jsx("button",{type:"button",className:"inline-flex min-h-8 items-center justify-center rounded-xl bg-white/[0.05] px-2.5 text-[12px] font-semibold text-white/72 transition hover:bg-white/[0.08] hover:text-white",onClick:g.action,children:g.label},g.label))}),e.jsx("textarea",{ref:r,value:o,onChange:g=>d(g.target.value),className:Z("min-h-0 w-full rounded-[20px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]",t?"h-28":"h-40"),placeholder:"Write a quick note or rough wiki draft"}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("button",{type:"button",className:"inline-flex min-h-10 items-center justify-center gap-2 rounded-2xl bg-[rgba(192,193,255,0.16)] px-3 py-2 text-sm font-medium text-[var(--primary)] transition hover:bg-[rgba(192,193,255,0.24)] disabled:opacity-50",disabled:!o.trim()||h.isPending,onClick:()=>h.mutate(),children:[e.jsx(ri,{className:"size-4"}),"Save as note"]}),e.jsxs("button",{type:"button",className:"inline-flex min-h-10 items-center justify-center gap-2 rounded-2xl bg-[rgba(255,185,95,0.16)] px-3 py-2 text-sm font-medium text-[var(--tertiary)] transition hover:bg-[rgba(255,185,95,0.24)] disabled:opacity-50",disabled:!o.trim()||m.isPending,onClick:()=>m.mutate(),children:[e.jsx(ai,{className:"size-4"}),"Save as wiki"]})]})]})}const XS={id:"surface:utility:time",surfaceId:"utility",routePath:null,title:"Clock",icon:"timer",description:"Live local time widget.",category:"Utilities",tags:["utility","clock"],inputs:[],params:[],output:[it({label:"Current time",description:"Formatted local time string published by the clock widget."}),rs({key:"clock",label:"Clock state",description:"Structured clock state including the current ISO timestamp.",modelName:"ForgeClockState"})],tools:[],NodeView:Ot({title:"Clock",description:"Live local time widget.",inputs:[],params:[],output:[it({label:"Current time",description:"Formatted local time string published by the clock widget."}),rs({key:"clock",label:"Clock state",description:"Structured clock state including the current ISO timestamp.",modelName:"ForgeClockState"})],tools:[]}),WebView:cl,execute:t=>Pt(t,{clock:{now:t.context.now}},new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.context.now)))};cl.workbench=XS;const YS={id:"surface:utility:mini-calendar",surfaceId:"utility",routePath:null,title:"Mini calendar",icon:"calendar",description:"Compact month calendar widget.",category:"Utilities",tags:["utility","calendar"],inputs:[],params:[],output:[it({label:"Month view",description:"Summary of the compact month calendar widget."}),rs({key:"calendarView",label:"Calendar view",description:"Structured mini-calendar state including the current month anchor.",modelName:"ForgeMiniCalendarView"})],tools:[],NodeView:Ot({title:"Mini calendar",description:"Compact month calendar widget.",inputs:[],params:[],output:[it({label:"Month view",description:"Summary of the compact month calendar widget."}),rs({key:"calendarView",label:"Calendar view",description:"Structured mini-calendar state including the current month anchor.",modelName:"ForgeMiniCalendarView"})],tools:[]}),WebView:ul,execute:t=>Pt(t,{calendarView:{now:t.context.now}},"Compact month calendar")};ul.workbench=YS;const JS={id:"surface:utility:spotify",surfaceId:"utility",routePath:null,title:"Spotify",icon:"music",description:"Pinned music link widget.",category:"Utilities",tags:["utility","spotify"],inputs:[{key:"surfaceId",label:"Surface id",kind:"text",required:!1}],params:[],output:[it({label:"Spotify link",description:"Summary of the pinned music link widget."}),rs({key:"spotifyLink",label:"Spotify state",description:"Structured Spotify widget state and pinned surface context.",modelName:"ForgeSpotifyWidgetState"})],tools:[],NodeView:Ot({title:"Spotify",description:"Pinned music link widget.",inputs:[{key:"surfaceId",label:"Surface id",kind:"text"}],params:[],output:[it({label:"Spotify link",description:"Summary of the pinned music link widget."}),rs({key:"spotifyLink",label:"Spotify state",description:"Structured Spotify widget state and pinned surface context.",modelName:"ForgeSpotifyWidgetState"})],tools:[]}),WebView:hl,execute:t=>Pt(t,{spotifyLink:{surfaceId:t.inputs.surfaceId??null}},"Pinned Spotify link")};hl.workbench=JS;const ZS={id:"surface:utility:weather",surfaceId:"utility",routePath:null,title:"Weather",icon:"weather",description:"Location-aware weather widget.",category:"Utilities",tags:["utility","weather"],inputs:[],params:[],output:[it({label:"Weather summary",description:"Summary of the weather widget state."}),rs({key:"weather",label:"Weather payload",description:"Structured weather widget payload.",modelName:"ForgeWeatherWidgetState"})],tools:[],NodeView:Ot({title:"Weather",description:"Location-aware weather widget.",inputs:[],params:[],output:[it({label:"Weather summary",description:"Summary of the weather widget state."}),rs({key:"weather",label:"Weather payload",description:"Structured weather widget payload.",modelName:"ForgeWeatherWidgetState"})],tools:[]}),WebView:ml,execute:t=>Pt(t,{weather:null},"Weather widget")};ml.workbench=ZS;const e4={id:"surface:utility:quick-capture",surfaceId:"utility",routePath:null,title:"Quick capture",icon:"capture",description:"Draft a quick note or wiki page.",category:"Capture",tags:["capture","notes"],inputs:[{key:"defaultUserId",label:"Default user id",kind:"text",required:!1}],params:[],output:[it({label:"Draft summary",description:"Summary of the quick-capture draft state."}),rs({key:"draft",label:"Draft context",description:"Structured quick-capture draft context.",modelName:"ForgeQuickCaptureDraft"})],tools:[Co("Create a Forge evidence note from captured markdown.")],NodeView:Ot({title:"Quick capture",description:"Draft a quick note or wiki page.",inputs:[{key:"defaultUserId",label:"Default user id",kind:"text"}],params:[],output:[it({label:"Draft summary",description:"Summary of the quick-capture draft state."}),rs({key:"draft",label:"Draft context",description:"Structured quick-capture draft context.",modelName:"ForgeQuickCaptureDraft"})],tools:[Co("Create a Forge evidence note from captured markdown.")]}),WebView:pl,execute:t=>Pt(t,{draft:{defaultUserId:t.inputs.defaultUserId??null}},"Quick capture can draft notes and wiki pages.")};pl.workbench=e4;function ts(t,s){const a=i=>t(i);return a.displayName=s.title.replace(/\s+/g,""),WS(a,s)}function t4({children:t}){return e.jsx(e.Fragment,{children:t})}function Ef(t,s,a,i,r,n){return ts(t4,{id:t,surfaceId:"insights",routePath:"/insights",title:s,icon:"insights",description:a,category:"Insights",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const s4=Ef("surface:insights:feed","Insights feed","Current coaching feed, status summary, and evidence-backed insight stream.",["insights","feed"],t=>Tf(t),[it({label:"Insight summary",description:"Summary of the current coaching feed and evidence-backed insight stream."}),rs({key:"insights",label:"Insight payload",description:"Structured status and coaching payload returned by Forge insights.",modelName:"ForgeInsightsPayload"})]),a4=Ef("surface:insights:coaching","Coaching recommendation","Single-action coaching summary for what Forge thinks matters next.",["insights","coaching"],t=>Pt(t,{focus:"coaching_recommendation"},"Coaching recommendation surface for the highest-leverage next move."),[it({label:"Coaching recommendation",description:"Summary of the highest-leverage coaching recommendation."})]);function Xu({children:t}){return e.jsx(e.Fragment,{children:t})}const Er=Ss({itemKind:"task",itemLabel:"Task",defaultEntityTypes:["task"],defaultLimit:24}),Lr=Cs(),Lf=ts(Xu,{id:"surface:kanban-index:summary",surfaceId:"kanban-index",routePath:"/kanban",title:"Kanban summary",icon:"kanban",description:"Board summary and execution posture.",category:"Execution",tags:["kanban","summary"],inputs:Er,params:Lr,output:[it({label:"Kanban summary",description:"Summary of board posture and execution pressure."})],tools:[],NodeView:Ot({title:"Kanban summary",description:"Board summary and execution posture.",inputs:Er,params:Lr,output:[it({label:"Kanban summary",description:"Summary of board posture and execution pressure."})],tools:[]}),execute:t=>ps(t,{query:"",entityTypes:["task"],limit:24})}),Df=ts(Xu,{id:"surface:kanban-index:filters",surfaceId:"kanban-index",routePath:"/kanban",title:"Kanban filters",icon:"filter",description:"Goal, owner, and tag filters for board scope.",category:"Execution",tags:["kanban","filters"],inputs:Er,params:Lr,output:[it({label:"Filter summary",description:"Summary of the current Kanban filters and scope."})],tools:[cs("Search Forge entities by query and entity types.")],NodeView:Ot({title:"Kanban filters",description:"Goal, owner, and tag filters for board scope.",inputs:Er,params:Lr,output:[it({label:"Filter summary",description:"Summary of the current Kanban filters and scope."})],tools:[cs("Search Forge entities by query and entity types.")]}),execute:t=>ps(t,{query:"",entityTypes:["task"],limit:24})}),Ff=ts(Xu,{id:"surface:kanban-index:board",surfaceId:"kanban-index",routePath:"/kanban",title:"Kanban board",icon:"board",description:"Task board with move and execution actions.",category:"Execution",tags:["kanban","board","tasks"],inputs:Er,params:Lr,output:gs({itemKind:"kanban_task",itemLabel:"Kanban task"}),tools:[cs("Search Forge entities by query and entity types."),Io("Update a task status.")],NodeView:Ot({title:"Kanban board",description:"Task board with move and execution actions.",inputs:Er,params:Lr,output:gs({itemKind:"kanban_task",itemLabel:"Kanban task"}),tools:[cs("Search Forge entities by query and entity types."),Io("Update a task status.")]}),execute:t=>ps(t,{query:"",entityTypes:["task"],limit:24})});function i4({children:t}){return e.jsx(e.Fragment,{children:t})}function Yu(t,s,a,i,r,n,l,o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(i4,{id:t,surfaceId:"calendar",routePath:"/calendar",title:s,icon:"calendar",description:a,category:"Calendar",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const r4=Yu("surface:calendar:overview","Calendar overview","Main calendar surface for mirrored events, work blocks, and planned timeboxes.",["calendar","overview"],t=>Pt(t,{surfaces:["events","work_blocks","timeboxes"]},"Calendar overview spanning mirrored events, work blocks, and timeboxes."),[it({label:"Calendar summary",description:"Summary of mirrored events, work blocks, and timeboxes."})],[]),n4=Yu("surface:calendar:events","Calendar events","Mirrored calendar events and Forge-managed calendar records.",["calendar","events","mirrored"],t=>ps(t,{query:"",entityTypes:["calendar_event"],limit:20}),gs({itemKind:"calendar_event",itemLabel:"Calendar event"}),[cs("Search calendar-backed Forge entities and planning records.")],{inputs:Ss({itemKind:"calendar_event",itemLabel:"Calendar event",defaultEntityTypes:["calendar_event"],defaultLimit:20}),params:Cs()}),l4=Yu("surface:calendar:planning","Planning blocks","Planned task timeboxes and reusable work block templates.",["calendar","planning","timeboxes"],t=>ps(t,{query:"",entityTypes:["task_timebox","work_block_template"],limit:20}),gs({itemKind:"calendar_plan",itemLabel:"Planning record"}),[cs("Search calendar-backed Forge entities and planning records.")],{inputs:Ss({itemKind:"calendar_plan",itemLabel:"Planning record",defaultEntityTypes:["task_timebox","work_block_template"],defaultLimit:20}),params:Cs()});function o4({children:t}){return e.jsx(e.Fragment,{children:t})}function Ju(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(o4,{id:t,surfaceId:"goals",routePath:"/goals",title:s,icon:"goal",description:a,category:"Goals",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const d4=Ju("surface:goals:hero","Goals hero","Goals page header and long-horizon direction context.",["goals","hero"],t=>Pt(t,null,"Goals page header."),[it({label:"Goals summary",description:"High-level goals page framing."})]),c4=Ju("surface:goals:search-results","Goals list and results","Goal browser, linked context, and search results.",["goals","search"],t=>ps(t,{query:"",entityTypes:["goal"],limit:20}),gs({itemKind:"goal",itemLabel:"Goal"}),[cs("Search goal entities by query and entity types.")],{inputs:Ss({itemKind:"goal",itemLabel:"Goal",defaultEntityTypes:["goal"],defaultLimit:20}),params:Cs()}),u4=Ju("surface:goals:summary","Goals summary","Goal collection summary and state context.",["goals","summary"],t=>Pt(t,null,"Goal collection summary."),[it({label:"Goals summary",description:"Summary of the goal collection and its current state."})]);function h4({children:t}){return e.jsx(e.Fragment,{children:t})}function Zu(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(h4,{id:t,surfaceId:"habits",routePath:"/habits",title:s,icon:"habit",description:a,category:"Habits",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const m4=Zu("surface:habits:hero","Habits hero","Habits page header and recurring execution context.",["habits","hero"],t=>Pt(t,null,"Habits page header."),[it({label:"Habits summary",description:"High-level habits page framing."})]),p4=Zu("surface:habits:search-results","Habits list and results","Habit browser, due habits, and recurring check-in context.",["habits","search","check-ins"],t=>ps(t,{query:"",entityTypes:["habit"],limit:20}),gs({itemKind:"habit",itemLabel:"Habit"}),[cs("Search habit entities by query and entity types.")],{inputs:Ss({itemKind:"habit",itemLabel:"Habit",defaultEntityTypes:["habit"],defaultLimit:20}),params:Cs()}),x4=Zu("surface:habits:summary","Habits summary","Habit streaks, due state, and collection-level rhythm context.",["habits","summary","streaks"],t=>Pt(t,null,"Habit collection summary."),[it({label:"Habit summary",description:"Summary of habit streaks, due state, and collection rhythm."})]);function g4({children:t}){return e.jsx(e.Fragment,{children:t})}function qr(t){return ts(g4,{id:t.id,surfaceId:t.surfaceId,routePath:t.routePath,title:t.title,icon:t.surfaceId,description:t.description,category:t.category,tags:t.tags,inputs:[],params:[],output:t.output,tools:[],NodeView:Ot({title:t.title,description:t.description,inputs:[],params:[],output:t.output,tools:[]}),execute:t.execute})}const _f=qr({id:"surface:sleep-index:summary",surfaceId:"sleep-index",routePath:"/sleep",title:"Sleep summary",description:"Recent nightly sleep metrics and recovery posture.",category:"Sleep",tags:["sleep","summary"],execute:t=>Hu(t),output:[it({label:"Sleep summary",description:"Summary of recent sleep and recovery posture."}),rs({key:"sleepView",label:"Sleep view",description:"Structured sleep history and derived sleep patterns.",modelName:"ForgeSleepView"})]}),Rf=qr({id:"surface:sleep-index:patterns",surfaceId:"sleep-index",routePath:"/sleep",title:"Sleep patterns",description:"Weekly baseline, stage mix, and timing patterns around canonical nights.",category:"Sleep",tags:["sleep","patterns"],execute:t=>Hu(t),output:[it({label:"Sleep pattern summary",description:"Summary of trend, stage averages, and recovery state."}),rs({key:"sleepView",label:"Sleep view",description:"Structured sleep trend, stage averages, and recovery signals.",modelName:"ForgeSleepView"})]}),$f=qr({id:"surface:sleep-index:browser",surfaceId:"sleep-index",routePath:"/sleep",title:"Night detail",description:"Interactive sleep calendar, selected-night detail, and optional raw evidence.",category:"Sleep",tags:["sleep","browser","history"],execute:t=>Hu(t),output:[it({label:"Night detail summary",description:"Summary of the sleep calendar and selected-night detail."}),rs({key:"sleepView",label:"Sleep view",description:"Structured canonical nights, calendar summaries, and phase detail.",modelName:"ForgeSleepView"})]}),Of=qr({id:"surface:sports-index:summary",surfaceId:"sports-index",routePath:"/sports",title:"Sports summary",description:"Recent workout metrics, streaks, and linked-session totals.",category:"Sports",tags:["sports","summary"],execute:t=>Gu(t),output:[it({label:"Sports summary",description:"Summary of recent workout metrics and streaks."}),rs({key:"sportsView",label:"Sports view",description:"Structured workout metrics, streaks, and linked session totals.",modelName:"ForgeSportsView"})]}),zf=qr({id:"surface:sports-index:composition",surfaceId:"sports-index",routePath:"/sports",title:"Training composition",description:"Workout mix, trend, and session composition context.",category:"Sports",tags:["sports","composition","trend"],execute:t=>Gu(t),output:[it({label:"Composition summary",description:"Summary of workout mix, trend, and session composition."}),rs({key:"sportsView",label:"Sports view",description:"Structured workout mix, trend, and session composition data.",modelName:"ForgeSportsView"})]}),Kf=qr({id:"surface:sports-index:browser",surfaceId:"sports-index",routePath:"/sports",title:"Session browser",description:"Searchable and virtualized workout history browser.",category:"Sports",tags:["sports","browser","history"],execute:t=>Gu(t),output:[it({label:"Session browser summary",description:"Summary of searchable workout history."}),rs({key:"sportsView",label:"Sports view",description:"Structured workout history for browsing and analysis.",modelName:"ForgeSportsView"})]});function f4({children:t}){return e.jsx(e.Fragment,{children:t})}function xl(t,s,a,i,r,n){return ts(f4,{id:t,surfaceId:"movement-index",routePath:"/movement",title:s,icon:"movement",description:a,category:"Movement",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const qf=xl("surface:movement-index:summary","Movement summary","Tracking mode, daily totals, and passive capture posture.",["movement","summary"],t=>Pt(t,null,"Movement summary is available."),[it({label:"Movement summary",description:"Summary of tracking mode, daily totals, and passive capture posture."})]),Bf=xl("surface:movement-index:selection","Movement selection aggregate","Selected-stay and selected-trip aggregate totals.",["movement","selection","aggregate"],t=>Pt(t,null,"Selected stay and trip aggregate totals."),[it({label:"Selection summary",description:"Summary of selected-stay and selected-trip aggregates."})]),Uf=xl("surface:movement-index:timeline","Movement life timeline","Life-scale stay and trip timeline with edit access.",["movement","timeline","life"],t=>Pt(t,null,"Movement life timeline with stay and trip history."),[it({label:"Timeline summary",description:"Summary of the movement life timeline and trip history."})]),Wf=xl("surface:movement-index:places","Known places","Known places, aliases, and category tags.",["movement","places"],t=>RS(t),[it({label:"Places summary",description:"Summary of known places, aliases, and category tags."}),Mf({key:"places",label:"Known places",description:"Structured list of places known to Forge movement tracking.",modelName:"ForgeMovementPlaces",itemKind:"movement_place"})]),Hf=xl("surface:movement-index:data-browser","Movement data browser","Datapoint browsing, invalid records, and movement data cleanup.",["movement","data","browser"],t=>Pt(t,null,"Movement datapoint browser with cleanup actions."),[it({label:"Data browser summary",description:"Summary of movement datapoint browsing and cleanup."})]);function eh({children:t}){return e.jsx(e.Fragment,{children:t})}const To=Ss({itemKind:"note",itemLabel:"Note",defaultEntityTypes:["note"],defaultLimit:20}),Po=Cs(),Gf=ts(eh,{id:"surface:notes-index:filters",surfaceId:"notes-index",routePath:"/notes",title:"Note filters",icon:"filter",description:"Entity, tag, text, author, and date filters for notes.",category:"Notes",tags:["notes","filters","search"],inputs:To,params:Po,output:[it({label:"Filter summary",description:"Summary of the current note filters and search scope."})],tools:[cs("Search Forge entities by query and entity types.")],NodeView:Ot({title:"Note filters",description:"Entity, tag, text, author, and date filters for notes.",inputs:To,params:Po,output:[it({label:"Filter summary",description:"Summary of the current note filters and search scope."})],tools:[cs("Search Forge entities by query and entity types.")]}),execute:t=>ps(t,{query:"",entityTypes:["note"],limit:20})}),Qf=ts(eh,{id:"surface:notes-index:composer",surfaceId:"notes-index",routePath:"/notes",title:"Note composer",icon:"write",description:"Markdown note composer with links, tags, and capture actions.",category:"Notes",tags:["notes","composer","capture"],inputs:To,params:Po,output:[it({label:"Draft summary",description:"Summary of the current note drafting surface."})],tools:[Co("Create an evidence note from markdown content.")],NodeView:Ot({title:"Note composer",description:"Markdown note composer with links, tags, and capture actions.",inputs:To,params:Po,output:[it({label:"Draft summary",description:"Summary of the current note drafting surface."})],tools:[Co("Create an evidence note from markdown content.")]}),execute:t=>Pt(t,{draftable:!0},"This node can draft or create a note.")}),Vf=ts(eh,{id:"surface:notes-index:library",surfaceId:"notes-index",routePath:"/notes",title:"Notes library",icon:"library",description:"Filtered library of Forge notes and linked evidence.",category:"Notes",tags:["notes","library","history"],inputs:[],params:[],output:gs({itemKind:"note",itemLabel:"Note"}),tools:[],NodeView:Ot({title:"Notes library",description:"Filtered library of Forge notes and linked evidence.",inputs:[],params:[],output:gs({itemKind:"note",itemLabel:"Note"}),tools:[]}),execute:t=>ps(t,{query:"",entityTypes:["note"],limit:20})});function b4({children:t}){return e.jsx(e.Fragment,{children:t})}function th(t,s,a,i,r,n){return ts(b4,{id:t,surfaceId:"overview",routePath:"/overview",title:s,icon:"overview",description:a,category:"Overview",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const v4=th("surface:overview:snapshot","Forge snapshot","Live overview of goals, projects, tasks, habits, and current operating pressure.",["overview","snapshot"],t=>$S(t),[it({label:"Overview summary",description:"Compact summary of goals, projects, tasks, and habits."}),rs({key:"context",label:"Overview context",description:"Structured Forge overview context for the current operating picture.",modelName:"ForgeOverviewContext"})]),w4=th("surface:overview:momentum","Momentum and health","Momentum-focused summary of streaks, neglected areas, and active execution pressure.",["overview","momentum"],t=>Pt(t,{dimensions:["momentum","neglected_goals","domain_balance"]},"Overview momentum surface tracking neglected goals, domain balance, and execution pressure."),[it({label:"Momentum summary",description:"Summary of momentum, neglected goals, and execution pressure."})]),y4=th("surface:overview:insights","Overview insights","Insight-oriented summary of the current Forge operating picture.",["overview","insights"],t=>Tf(t),[it({label:"Insight summary",description:"Compact explanation of the current insight payload."}),rs({key:"insights",label:"Insight payload",description:"Structured insight and coaching payload returned by Forge.",modelName:"ForgeInsightsPayload"})]);function j4({children:t}){return e.jsx(e.Fragment,{children:t})}function sh(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(j4,{id:t,surfaceId:"projects",routePath:"/projects",title:s,icon:"projects",description:a,category:"Projects",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const Xf=sh("surface:projects:hero","Projects hero","Projects page header.",["projects","hero"],t=>Pt(t,null,"Projects page header."),[it({label:"Projects summary",description:"High-level projects page framing."})]),Yf=sh("surface:projects:search-results","Search and results","Project browser, filters, and search context.",["projects","search"],t=>ps(t,{query:"",entityTypes:["project"],limit:20}),gs({itemKind:"project",itemLabel:"Project"}),[cs("Search project entities by query and entity types.")],{inputs:Ss({itemKind:"project",itemLabel:"Project",defaultEntityTypes:["project"],defaultLimit:20}),params:Cs()}),Jf=sh("surface:projects:summary","Collection summary","Collection summary and project state metrics.",["projects","summary"],t=>Pt(t,null,"Project collection summary."),[it({label:"Project summary",description:"Summary of the project collection and current state."})]);function N4({children:t}){return e.jsx(e.Fragment,{children:t})}function ah(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(N4,{id:t,surfaceId:"preferences",routePath:"/preferences",title:s,icon:"preferences",description:a,category:"Preferences",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const k4=ah("surface:preferences:workspace","Preferences workspace","Main preference modeling workspace, including summaries, tradeoffs, and evidence.",["preferences","workspace"],t=>Pt(t,{surfaces:["summary","comparison_game","evidence"]},"Preferences workspace with summary, pairwise comparison, and evidence views."),[it({label:"Preference summary",description:"Summary of the active preference modeling workspace."})]),S4=ah("surface:preferences:contexts","Preference contexts","Preference contexts that shape which tradeoffs and evidence are active.",["preferences","contexts"],t=>ps(t,{query:"",entityTypes:["preference_context"],limit:20}),gs({itemKind:"preference_context",itemLabel:"Preference context"}),[cs("Search preference contexts and modeled preference items.")],{inputs:Ss({itemKind:"preference_context",itemLabel:"Preference context",defaultEntityTypes:["preference_context"],defaultLimit:20}),params:Cs()}),C4=ah("surface:preferences:items","Preference items","Preference items scored and compared inside the active context.",["preferences","items"],t=>ps(t,{query:"",entityTypes:["preference_item"],limit:20}),gs({itemKind:"preference_item",itemLabel:"Preference item"}),[cs("Search preference contexts and modeled preference items.")],{inputs:Ss({itemKind:"preference_item",itemLabel:"Preference item",defaultEntityTypes:["preference_item"],defaultLimit:20}),params:Cs()});function I4({children:t}){return e.jsx(e.Fragment,{children:t})}function ih(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(I4,{id:t,surfaceId:"psyche",routePath:"/psyche",title:s,icon:"psyche",description:a,category:"Psyche",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const T4=ih("surface:psyche:overview","Psyche overview","High-level overview of values, patterns, beliefs, modes, and reports.",["psyche","overview"],t=>Pt(t,{surfaces:["values","patterns","beliefs","modes","reports"]},"Psyche overview spanning values, patterns, beliefs, modes, and reports."),[it({label:"Psyche summary",description:"Summary of values, patterns, beliefs, modes, and reports."})]),P4=ih("surface:psyche:values","Psyche values","Values and long-lived internal directions tracked inside Forge.",["psyche","values"],t=>ps(t,{query:"",entityTypes:["psyche_value"],limit:20}),gs({itemKind:"psyche_value",itemLabel:"Psyche value"}),[cs("Search psyche entities and reflective records.")],{inputs:Ss({itemKind:"psyche_value",itemLabel:"Psyche value",defaultEntityTypes:["psyche_value"],defaultLimit:20}),params:Cs()}),A4=ih("surface:psyche:reports","Trigger reports","Trigger reports and behavior-pattern signals linked to reflective work.",["psyche","reports","patterns"],t=>ps(t,{query:"",entityTypes:["trigger_report","behavior_pattern","belief_entry","mode_profile"],limit:20}),gs({itemKind:"psyche_record",itemLabel:"Psyche record"}),[cs("Search psyche entities and reflective records.")],{inputs:Ss({itemKind:"psyche_record",itemLabel:"Psyche record",defaultEntityTypes:["trigger_report","behavior_pattern","belief_entry","mode_profile"],defaultLimit:20}),params:Cs()});function M4({children:t}){return e.jsx(e.Fragment,{children:t})}function rh(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(M4,{id:t,surfaceId:"questionnaires",routePath:"/psyche/questionnaires",title:s,icon:"questionnaire",description:a,category:"Questionnaires",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const E4=rh("surface:questionnaires:library","Questionnaire library","Library of questionnaire instruments available in Forge.",["questionnaires","library"],t=>ps(t,{query:"",entityTypes:["questionnaire_instrument"],limit:20}),gs({itemKind:"questionnaire_instrument",itemLabel:"Questionnaire"}),[cs("Search questionnaire instruments and related records.")],{inputs:Ss({itemKind:"questionnaire_instrument",itemLabel:"Questionnaire",defaultEntityTypes:["questionnaire_instrument"],defaultLimit:20}),params:Cs()}),L4=rh("surface:questionnaires:drafting","Questionnaire drafting","Drafting and publishing context for questionnaire instruments.",["questionnaires","drafting","authoring"],t=>Pt(t,{states:["draft","published","run"]},"Questionnaire drafting surface with draft, publish, and run lifecycle context."),[it({label:"Drafting summary",description:"Summary of questionnaire drafting and lifecycle context."})]),D4=rh("surface:questionnaires:self-observation","Self-observation calendar","Calendar of self-observation notes and linked psyche context.",["questionnaires","self-observation","psyche"],t=>Pt(t,{linkedDomains:["patterns","reports","notes"]},"Self-observation calendar surface with linked psyche context."),[it({label:"Observation summary",description:"Summary of the self-observation calendar and linked psyche context."})]);function F4({children:t}){return e.jsx(e.Fragment,{children:t})}function Zf(t,s,a,i,r,n){return ts(F4,{id:t,surfaceId:"review",routePath:"/review/weekly",title:s,icon:"review",description:a,category:"Review",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const _4=Zf("surface:review:weekly-summary","Weekly review summary","Weekly review payload with momentum, wins, calibration, and completion state.",["review","weekly"],t=>OS(t),[it({label:"Weekly review summary",description:"Summary of momentum, wins, calibration, and review completion state."}),rs({key:"weeklyReview",label:"Weekly review payload",description:"Structured weekly review payload returned by Forge.",modelName:"ForgeWeeklyReview"})]),R4=Zf("surface:review:reward","Review reward","Reward framing and completion incentive for closing the current review cycle.",["review","reward"],t=>Pt(t,{reward:"weekly_review_completion"},"Weekly review reward surface for locking the current cycle into evidence."),[it({label:"Review reward summary",description:"Summary of the reward framing for closing the current review cycle."})]);function $4({children:t}){return e.jsx(e.Fragment,{children:t})}function nh(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts($4,{id:t,surfaceId:"strategies",routePath:"/strategies",title:s,icon:"strategy",description:a,category:"Strategies",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const O4=nh("surface:strategies:hero","Strategies hero","Strategies page header and sequencing context.",["strategies","hero"],t=>Pt(t,null,"Strategies page header."),[it({label:"Strategies summary",description:"High-level strategies page framing."})]),z4=nh("surface:strategies:search-results","Strategies list and results","Strategy browser and structured operating context.",["strategies","search"],t=>ps(t,{query:"",entityTypes:["strategy"],limit:20}),gs({itemKind:"strategy",itemLabel:"Strategy"}),[cs("Search strategy entities by query and entity types.")],{inputs:Ss({itemKind:"strategy",itemLabel:"Strategy",defaultEntityTypes:["strategy"],defaultLimit:20}),params:Cs()}),K4=nh("surface:strategies:summary","Strategies summary","Strategy collection summary and state context.",["strategies","summary"],t=>Pt(t,null,"Strategy collection summary."),[it({label:"Strategy summary",description:"Summary of strategy state and collection context."})]);function q4({children:t}){return e.jsx(e.Fragment,{children:t})}function lh(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(q4,{id:t,surfaceId:"tasks",routePath:"/today",title:s,icon:"task",description:a,category:"Tasks",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const B4=lh("surface:tasks:inbox","Task queue","Searchable task queue spanning backlog, focus, and in-progress work.",["tasks","queue","search"],t=>ps(t,{query:"",entityTypes:["task"],limit:20}),gs({itemKind:"task",itemLabel:"Task"}),[cs("Search task entities by title, status, or linked context."),Io("Move a task between backlog, focus, in progress, blocked, and done.")],{inputs:Ss({itemKind:"task",itemLabel:"Task",defaultEntityTypes:["task"],defaultLimit:20}),params:Cs()}),U4=lh("surface:tasks:focus-lane","Focus lane","Focused task lane for what should happen next right now.",["tasks","focus","execution"],t=>Pt(t,{hint:"Use this surface to represent active or next-up work."},"Focus lane context for the current execution board."),[it({label:"Focus summary",description:"Human-readable explanation of what the focus lane represents."})],[Io("Change task state as the flow decides what should happen next.")]),W4=lh("surface:tasks:summary","Task summary","High-level summary of the current task system and work state.",["tasks","summary"],t=>Pt(t,{states:["backlog","focus","in_progress","blocked","done"]},"Task system summary with the key task states Forge tracks."),[it({label:"Task summary",description:"High-level summary of the current task system and work state."})]);function H4({children:t}){return e.jsx(e.Fragment,{children:t})}function gl(t,s,a,i,r,n,l=[],o){const d=(o==null?void 0:o.inputs)??[],h=(o==null?void 0:o.params)??[];return ts(H4,{id:t,surfaceId:"today",routePath:"/today",title:s,icon:"today",description:a,category:"Today",tags:i,inputs:d,params:h,output:n,tools:l,NodeView:Ot({title:s,description:a,inputs:d,params:h,output:n,tools:l}),execute:r})}const eb=gl("surface:today:hero","Today hero","Daily execution header and directive.",["today","hero"],t=>Pt(t,null,"Daily execution header."),[it({label:"Today summary",description:"High-level framing for today's execution."})]),tb=gl("surface:today:metrics","Live metrics","Daily XP, level, and momentum metrics.",["today","metrics"],t=>Pt(t,null,"Daily metrics."),[it({label:"Metrics summary",description:"Summary of today's XP, level, and momentum metrics."})]),sb=gl("surface:today:runway","Runway","Execution lane and current work.",["today","execution"],t=>ps(t,{query:"",entityTypes:["task","habit"],limit:16}),gs({itemKind:"execution_item",itemLabel:"Execution item"}),[cs("Search today's active tasks and habits by query and entity types.")],{inputs:Ss({itemKind:"execution_item",itemLabel:"Execution item",defaultEntityTypes:["task","habit"],defaultLimit:16}),params:Cs()}),ab=gl("surface:today:calendar","Calendar","Calendar context for today.",["today","calendar"],t=>Pt(t,null,"Today's calendar context."),[it({label:"Calendar summary",description:"Summary of today's calendar context."})]),ib=gl("surface:today:focus","Current focus","Today priorities and focus context.",["today","focus"],t=>ps(t,{query:"",entityTypes:["task","habit"],limit:16}),gs({itemKind:"focus_item",itemLabel:"Focus item"}),[cs("Search today's priority tasks and habits by query and entity types.")],{inputs:Ss({itemKind:"focus_item",itemLabel:"Focus item",defaultEntityTypes:["task","habit"],defaultLimit:16}),params:Cs()});function G4({children:t}){return e.jsx(e.Fragment,{children:t})}function oh(t,s,a,i,r,n){return ts(G4,{id:t,surfaceId:"wiki",routePath:"/wiki",title:s,icon:"wiki",description:a,category:"Wiki",tags:i,inputs:[],params:[],output:n,tools:[],NodeView:Ot({title:s,description:a,inputs:[],params:[],output:n,tools:[]}),execute:r})}const Q4=oh("surface:wiki:pages","Wiki pages","Live list of wiki pages that can be used as memory or authored knowledge.",["wiki","pages"],t=>zS(t),[it({label:"Wiki page summary",description:"Summary of the currently available wiki pages."}),Mf({key:"pages",label:"Wiki pages",description:"Structured wiki page records available in Forge memory.",modelName:"ForgeWikiPages",itemKind:"wiki_page"})]),V4=oh("surface:wiki:health","Wiki health","Index health, unresolved links, and orphaned-page signals for the wiki.",["wiki","health"],t=>KS(t),[it({label:"Wiki health summary",description:"Summary of unresolved links and orphaned-page signals."}),rs({key:"health",label:"Wiki health",description:"Structured wiki health payload returned by Forge.",modelName:"ForgeWikiHealth"})]),X4=oh("surface:wiki:authoring","Wiki authoring","Authoring and ingest surface for creating or refining Forge memory.",["wiki","authoring","ingest"],t=>Pt(t,{actions:["upsert","ingest","reindex"]},"Wiki authoring surface for ingesting sources and maintaining memory pages."),[it({label:"Wiki authoring summary",description:"Summary of wiki authoring and ingest actions available on this surface."})]),Y4=[cl,ul,hl,ml,pl,r4,n4,l4,d4,c4,u4,m4,p4,x4,s4,a4,Lf,Df,Ff,Gf,Qf,Vf,v4,w4,y4,qf,Bf,Uf,Wf,Hf,_f,Rf,$f,Of,zf,Kf,Xf,Yf,Jf,k4,S4,C4,T4,P4,A4,E4,L4,D4,_4,R4,O4,z4,K4,B4,U4,W4,eb,tb,sb,ab,ib,Q4,V4,X4],rb=new Map(Y4.filter(t=>t.workbench).map(t=>[t.workbench.id,t.workbench]));function dh(){return Array.from(rb.values())}function nb(t){return rb.get(t)??null}function lb(){return dh().map(t=>({id:t.id,boxId:t.id,surfaceId:t.surfaceId,routePath:t.routePath,title:t.title,label:t.title,icon:t.icon??null,description:t.description,category:t.category,tags:t.tags,capabilityModes:["content",...t.tools.length>0?["tool"]:[]],inputs:Nl(t.inputs),params:Nl(t.params),output:Nl(t.output),tools:t.tools,outputs:Nl(t.output),toolAdapters:t.tools,snapshotResolverKey:void 0}))}const ob=u.createContext(null),J4={definitions:dh(),catalog:lb(),getDefinition:nb};function Z4({children:t}){const s=u.useMemo(()=>({definitions:dh(),catalog:lb(),getDefinition:nb}),[]);return e.jsx(ob.Provider,{value:s,children:t})}function db(){return u.useContext(ob)??J4}function e5(){return db().catalog}function t5(t){const s=db();return t?s.getDefinition(t):null}function s5({children:t}){return e.jsx(e.Fragment,{children:t})}function a5({children:t}){return e.jsx(e.Fragment,{children:t})}function Fd(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g," ")}function i5({eyebrow:t,titleText:s,entityKind:a,copyMode:i}){if(!t||i==="title_only"||typeof t!="string")return null;const r=Fd(t),n=s?Fd(s):null,l=a?Fd(Bs(a).label):null;return!r||n&&(r===n||n.includes(r)||r.includes(n))||l&&r===l?null:t}function rt({eyebrow:t,entityKind:s,title:a,titleText:i,description:r,badge:n,actions:l,copyMode:o="title_only"}){const d=s?Bs(s):null,h=d==null?void 0:d.icon,m=i5({eyebrow:t,titleText:i,entityKind:s,copyMode:o}),c=!!(d||m||n);return e.jsxs("header",{className:"relative min-w-0 w-full max-w-full overflow-hidden border-b border-white/6 px-5 py-5 sm:px-6 lg:grid lg:grid-cols-[minmax(0,1fr)_auto] lg:items-end lg:px-7 lg:py-6",style:{background:"var(--hero-gradient)",paddingTop:"var(--forge-shell-hero-padding-top)",paddingBottom:"var(--forge-shell-hero-padding-bottom)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{background:"radial-gradient(circle at top right, color-mix(in srgb, var(--forge-body-ambient-primary) 94%, transparent), transparent 34%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-white/10"}),e.jsxs("div",{className:"relative min-w-0 w-full max-w-full",children:[c?e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 text-[11px] font-medium uppercase tracking-[0.2em] text-white/40",children:[d&&h?e.jsxs("span",{className:"inline-flex items-center gap-2 text-white/56","aria-label":d.label,title:d.label,children:[e.jsx(h,{className:Z("size-3.5",d.iconClassName)}),e.jsx("span",{children:d.label})]}):null,m?e.jsx("span",{className:"text-[var(--secondary)]/80",children:m}):null,n?e.jsx(I,{tone:"signal",className:"h-8 rounded-full border border-white/8 bg-white/[0.04] px-3 text-[11px] font-medium tracking-[0.14em] text-white/80 uppercase",children:n}):null]}):null,e.jsx("div",{className:Z("min-w-0 max-w-4xl text-[clamp(1.85rem,3.5vw,4rem)] font-medium leading-[0.92] text-white",c?"mt-3":""),style:{transform:"translateY(var(--forge-shell-hero-title-translate-y)) scale(var(--forge-shell-hero-title-scale))",transformOrigin:"top left",willChange:"transform"},children:a}),e.jsx("div",{className:"mt-2 min-w-0 max-w-3xl text-[14px] leading-6 text-white/58 sm:text-[15px]",style:{opacity:"var(--forge-shell-hero-description-opacity)",transform:"translateY(var(--forge-shell-hero-description-translate-y))",willChange:"opacity, transform"},children:r})]}),l?e.jsx("div",{className:"relative mt-4 flex min-w-0 w-full max-w-full flex-wrap items-center gap-2 lg:mt-0 lg:max-w-[26rem] lg:justify-end",children:l}):null]})}function Aa(t){return t.entityType==="goal"?`/goals/${t.entityId}`:t.entityType==="project"?`/projects/${t.entityId}`:t.entityType==="task"?`/tasks/${t.entityId}`:t.entityType==="strategy"?`/strategies/${t.entityId}`:t.entityType==="habit"?"/habits":t.entityType==="task_run"&&typeof t.metadata.taskId=="string"?`/tasks/${t.metadata.taskId}`:null}function Hn(t){return t.entityType==="goal"?"Open goal":t.entityType==="project"?"Open project":t.entityType==="strategy"?"Open strategy":t.entityType==="habit"?"Open habits":t.entityType==="task"||t.entityType==="task_run"?"Open task":null}const hr=n0(),vm=[hr.accessor("title",{header:"Event",cell:t=>{const s=Aa(t.row.original);return s?e.jsx(Xe,{to:s,className:"font-medium text-white transition hover:text-[var(--primary)]",children:t.getValue()}):e.jsx("div",{className:"font-medium text-white",children:t.getValue()})}}),hr.accessor("source",{header:"Source",cell:t=>e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/50",children:t.getValue()})}),hr.display({id:"owner",header:"Owner",cell:t=>t.row.original.user?e.jsx(nt,{user:t.row.original.user,compact:!0}):e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/32",children:"Unowned"})}),hr.accessor("createdAt",{header:"When",cell:t=>e.jsx("div",{className:"text-sm text-white/55",children:ma(t.getValue())})}),hr.display({id:"actions",header:"Open",cell:t=>{const s=Aa(t.row.original);return s?e.jsx(Xe,{to:s,className:"inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)] transition hover:text-white",children:"Open"}):e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/32",children:"Archive only"})}})];function r5({rows:t,onRemove:s}){const a=s?[...vm,hr.display({id:"remove",header:"Correct",cell:r=>e.jsx(z,{variant:"ghost",className:"h-auto px-0 py-0 text-[11px] uppercase tracking-[0.16em] text-white/55",onClick:()=>{s(r.row.original.id)},children:"Remove log"})})]:vm,i=l0({columns:a,data:t,getCoreRowModel:o0()});return e.jsx(ie,{className:"overflow-hidden p-0",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:i.getHeaderGroups().map(r=>e.jsx("tr",{className:"bg-white/[0.03]",children:r.headers.map(n=>e.jsx("th",{className:"px-5 py-4 text-left font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:n.isPlaceholder?null:Eh(n.column.columnDef.header,n.getContext())},n.id))},r.id))}),e.jsx("tbody",{children:i.getRowModel().rows.map(r=>e.jsx("tr",{className:"bg-white/[0.015] transition hover:bg-white/[0.035]",children:r.getVisibleCells().map(n=>e.jsx("td",{className:"px-5 py-4 align-top",children:Eh(n.column.columnDef.cell,n.getContext())},n.id))},r.id))})]})})}function n5(){var c;const t=jt(),s=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[a]=us(),i=ct(),r=a.get("entityId")??void 0,n=a.get("entityType")??void 0,l=a.get("eventId"),o=Me({queryKey:["activity-archive",n,r,...s],queryFn:()=>Fk({limit:100,entityType:n,entityId:r,userIds:s})}),d=De({mutationFn:g=>qg(g),onSuccess:async()=>{await Promise.all([i.invalidateQueries({queryKey:["activity-archive"]}),i.invalidateQueries({queryKey:["forge-snapshot"]}),i.invalidateQueries({queryKey:["task-context"]}),i.invalidateQueries({queryKey:["project-board"]})])}}),h=((c=o.data)==null?void 0:c.activity)??[];if(o.isLoading)return e.jsx(Et,{eyebrow:"Evidence archive",title:"Loading activity",description:"Pulling the visible audit trail, grouped evidence, and correction history."});if(o.isError)return e.jsx(st,{eyebrow:"Evidence archive",error:o.error,onRetry:()=>void o.refetch()});if(h.length===0)return e.jsx(Bt,{eyebrow:"Evidence archive",title:r?"No evidence matched this filter":"No activity recorded yet",description:r?"Forge could not find visible events for this specific entity yet. Try a broader archive view or create some work first.":"As you complete work, log runs, or make corrections, the audit trail will appear here."});const m=h.reduce((g,x)=>{const p=x.createdAt.slice(0,10);return g[p]=[...g[p]??[],x],g},{});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(rt,{title:"Activity",description:r?"This filtered archive shows the evidence connected to the item you opened, so you can confirm what changed and when.":"Activity is your visible audit trail. Use it to inspect progress, confirm corrections, and trace work back to the goal, project, or task it came from.",badge:`${h.length} recent events`}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsx(r5,{rows:h,onRemove:async g=>{await d.mutateAsync(g)}}),e.jsx("div",{className:"grid gap-4",children:Object.entries(m).slice(0,6).map(([g,x])=>e.jsxs(ie,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:g}),e.jsx("div",{className:"mt-4 grid gap-3",children:x.slice(0,3).map(p=>e.jsxs("div",{className:`rounded-[18px] p-4 ${l===p.id?"bg-[rgba(192,193,255,0.12)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"bg-white/[0.04]"}`,children:[e.jsx("div",{className:"font-medium text-white",children:p.title}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:p.description}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:ma(p.createdAt)}),Aa(p)&&Hn(p)?e.jsx(Xe,{to:Aa(p),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:Hn(p)}):null]},p.id))})]},g))})]})]})}function wm(t,s){const a=new Date(t);return Number.isNaN(a.getTime())?s:a.toISOString()}function Wi(t){const s=new Date(t);return new Date(s.getTime()-s.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function ym(t,s){var n,l,o,d,h;const a=new Date,i=new Date(a.getTime()+30*6e4),r=new Date(i.getTime()+60*6e4);return{title:(s==null?void 0:s.title)??(t==null?void 0:t.title)??"",description:(s==null?void 0:s.description)??(t==null?void 0:t.description)??"",location:(s==null?void 0:s.location)??(t==null?void 0:t.location)??"",placeAddress:((n=s==null?void 0:s.place)==null?void 0:n.address)??((l=t==null?void 0:t.place)==null?void 0:l.address)??"",placeTimezone:((o=s==null?void 0:s.place)==null?void 0:o.timezone)??((d=t==null?void 0:t.place)==null?void 0:d.timezone)??"",startAtLocal:t?Wi(t.startAt):s!=null&&s.startAt?Wi(s.startAt):Wi(i.toISOString()),endAtLocal:t?Wi(t.endAt):s!=null&&s.endAt?Wi(s.endAt):Wi(r.toISOString()),timezone:(s==null?void 0:s.timezone)??(t==null?void 0:t.timezone)??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:(s==null?void 0:s.availability)??(t==null?void 0:t.availability)??"busy",activityPresetKey:bf(t==null?void 0:t.actionProfile),customSustainRateApPerHour:vf(t==null?void 0:t.actionProfile),preferredCalendarId:s&&"preferredCalendarId"in s?s.preferredCalendarId:(t==null?void 0:t.calendarId)??void 0,categoriesText:((h=s==null?void 0:s.categories)==null?void 0:h.join(", "))??(t==null?void 0:t.categories.join(", "))??"",linkQuery:"",links:(s==null?void 0:s.links)??(t==null?void 0:t.links.map(m=>({entityType:m.entityType,entityId:m.entityId,relationshipType:m.relationshipType,label:`${m.entityType.replaceAll("_"," ")} · ${m.entityId}`})))??[]}}function l5({open:t,onOpenChange:s,writableCalendars:a,linkOptions:i,event:r,seed:n,onSubmit:l,pending:o=!1}){const[d,h]=u.useState(()=>ym(r,n)),[m,c]=u.useState(null);u.useEffect(()=>{t&&(h(ym(r,n)),c(null))},[r,t,n]);const g=u.useMemo(()=>i.map(p=>{const f=Vt(p.entityType);return{value:`${p.entityType}:${p.entityId}`,label:p.label,description:p.subtitle,searchText:`${p.label} ${p.subtitle} ${p.entityType}`,kind:f??void 0,menuBadge:f?e.jsx(Ue,{kind:f,label:p.label,compact:!0,gradient:!1}):void 0,badge:f?e.jsx(Ue,{kind:f,label:p.label,compact:!0}):void 0}}),[i]),x=u.useMemo(()=>[{id:"identity",eyebrow:"Event",title:r?"Refine the Forge event":"Create a Forge calendar event",description:"This event belongs to Forge first. If you choose a writable calendar, Forge will also project it to the connected provider.",render:(p,f)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(le,{label:"Title",children:e.jsx(ke,{value:p.title,onChange:b=>f({title:b.target.value}),placeholder:"Weekly research supervision"})}),e.jsx(le,{label:"Description",children:e.jsx(Ve,{value:p.description,onChange:b=>f({description:b.target.value}),placeholder:"Agenda, context, or outcomes you want this event to carry."})}),e.jsx(le,{label:"Location",children:e.jsx(ke,{value:p.location,onChange:b=>f({location:b.target.value}),placeholder:"Clinic room 2 or Zoom"})}),e.jsx(le,{label:"Place address",children:e.jsx(ke,{value:p.placeAddress,onChange:b=>f({placeAddress:b.target.value}),placeholder:"Bahnhofstrasse 10, Zurich"})}),e.jsx(le,{label:"Place timezone",children:e.jsx(ke,{value:p.placeTimezone,onChange:b=>f({placeTimezone:b.target.value}),placeholder:"Europe/Zurich"})})]})},{id:"timing",eyebrow:"Timing",title:"Set the time and visibility",description:"Forge stores the real event window, timezone, and whether it should behave like a busy or free slot for scheduling rules.",render:(p,f)=>e.jsxs("div",{className:"grid gap-4",children:[(()=>{const b=new Date().toISOString(),M=new Date(Date.now()+3600*1e3).toISOString(),P=wn({title:p.title,availability:p.availability,activityPresetKey:p.activityPresetKey,customSustainRateApPerHour:p.customSustainRateApPerHour,startAt:wm(p.startAtLocal,b),endAt:wm(p.endAtLocal,M)});return e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Kt(P.rateApPerHour)}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:kt(P.totalAp)})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Availability controls whether the event blocks planning. The activity profile controls AP drain, and you can override it with a custom AP per hour."})]})})(),e.jsx(le,{label:"Activity profile",children:e.jsx(vt,{value:p.activityPresetKey??(p.availability==="busy"?"meeting":"light_context"),columns:3,onChange:b=>f({activityPresetKey:b}),options:ji().filter(b=>b.key!=="task_inherited").map(b=>({value:b.key,label:b.label,description:`${Kt(b.defaultRateApPerHour)} · ${b.description}`}))})}),e.jsx(le,{label:"Custom AP per hour",children:e.jsx(ke,{type:"number",min:0,step:.5,value:p.customSustainRateApPerHour??"",onChange:b=>f({customSustainRateApPerHour:b.target.value.trim()===""?null:Number(b.target.value)}),placeholder:"Leave empty to use the activity default"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Starts",children:e.jsx(ke,{type:"datetime-local",value:p.startAtLocal,onChange:b=>f({startAtLocal:b.target.value})})}),e.jsx(le,{label:"Ends",children:e.jsx(ke,{type:"datetime-local",value:p.endAtLocal,onChange:b=>f({endAtLocal:b.target.value})})})]}),e.jsx(le,{label:"Timezone",children:e.jsx(ke,{value:p.timezone,onChange:b=>f({timezone:b.target.value}),placeholder:"Europe/Zurich"})}),e.jsx(le,{label:"Availability",children:e.jsx(vt,{value:p.availability,onChange:b=>f({availability:b}),options:[{value:"busy",label:"Busy",description:"This event should block timebox recommendations and rule checks."},{value:"free",label:"Free",description:"This event stays visible in the calendar without blocking work."}]})})]})},{id:"links",eyebrow:"Meaning",title:"Connect the event to Forge entities",description:"Attach this event to strategies, goals, projects, tasks, or habits so the calendar carries multi-user operating context instead of staying isolated.",render:(p,f)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(le,{label:"Search Forge entities",description:"Search across human and bot-owned entities; the linked records use the same icon, color, and owner system as the rest of Forge.",children:e.jsx(ht,{options:g,selectedValues:p.links.map(b=>`${b.entityType}:${b.entityId}`),onChange:b=>{f({links:b.map(M=>{const[P,...T]=M.split(":"),w=T.join(":"),j=i.find(v=>v.entityType===P&&v.entityId===w);return j?{entityType:j.entityType,entityId:j.entityId,relationshipType:"context",label:j.label}:null}).filter(M=>M!==null)})},placeholder:"Search strategies, goals, projects, tasks, habits, human, or bot owners",emptyMessage:"No matching Forge entities found."})})})},{id:"projection",eyebrow:"Projection",title:"Choose where this event should live remotely",description:"You can keep the event local to Forge, or choose a writable connected calendar so Forge also keeps a synced remote copy.",render:(p,f)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[a.length>0?e.jsxs("button",{type:"button",onClick:()=>f({preferredCalendarId:void 0}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===void 0?"border-[rgba(125,211,252,0.28)] bg-[rgba(125,211,252,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(ds,{className:"size-4"}),"Default synced calendar"]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:"Let Forge use the default writable connected calendar automatically."})]}):null,e.jsxs("button",{type:"button",onClick:()=>f({preferredCalendarId:null}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===null?"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.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(Ht,{className:"size-4"}),"Forge only"]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:"Keep the event in Forge without creating a remote provider copy yet."})]}),a.map(b=>e.jsxs("button",{type:"button",onClick:()=>f({preferredCalendarId:b.id}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===b.id?"border-[rgba(125,211,252,0.28)] bg-[rgba(125,211,252,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(ds,{className:"size-4"}),kr(b)]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:b.description||`${b.timezone} · writable`})]},b.id))]}),e.jsxs("div",{className:"grid gap-2 rounded-[22px] border border-white/8 bg-white/[0.04] p-4 text-sm text-white/66",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium text-white",children:[e.jsx(vu,{className:"size-4 text-[var(--primary)]"}),"Categories and filtering"]}),e.jsx(ke,{value:p.categoriesText,onChange:b=>f({categoriesText:b.target.value}),placeholder:"meeting, clinic, research"})]})]})}],[r,i,g,a]);return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:r?"Edit event":"New event",title:r?"Edit calendar event":"Create calendar event",description:"Forge-owned events can stay local or publish to a connected provider calendar.",value:d,onChange:h,steps:x,onSubmit:async()=>{if(!d.title.trim()){c("Add an event title before saving.");return}if(!d.startAtLocal||!d.endAtLocal){c("Set both the start and end time before saving.");return}if(new Date(d.endAtLocal).getTime()<=new Date(d.startAtLocal).getTime()){c("The event end time must be after the start time.");return}c(null),await l({title:d.title.trim(),description:d.description.trim(),location:d.location.trim(),place:{label:d.location.trim(),address:d.placeAddress.trim(),timezone:d.placeTimezone.trim(),latitude:null,longitude:null,source:d.placeAddress.trim()?"manual":"",externalPlaceId:""},startAt:new Date(d.startAtLocal).toISOString(),endAt:new Date(d.endAtLocal).toISOString(),timezone:d.timezone.trim()||"UTC",availability:d.availability,activityPresetKey:d.activityPresetKey,customSustainRateApPerHour:d.customSustainRateApPerHour,categories:d.categoriesText.split(",").map(p=>p.trim()).filter(Boolean),links:d.links.map(p=>({entityType:p.entityType,entityId:p.entityId,relationshipType:p.relationshipType})),...d.preferredCalendarId!==void 0?{preferredCalendarId:d.preferredCalendarId}:{}})},submitLabel:r?"Save event":"Create event",pending:o,pendingLabel:r?"Saving":"Creating",error:m})}function o5({open:t,onOpenChange:s,initialTitle:a,pending:i=!1,onSubmit:r}){const[n,l]=u.useState(a),[o,d]=u.useState(null);return u.useEffect(()=>{t&&(l(a),d(null))},[a,t]),e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Quick rename",description:"Rename the event without reopening the full event guide.",value:{title:n},onChange:h=>l(h.title),steps:[{id:"rename",eyebrow:"Rename",title:"Update the event title",description:"Keep the rename fast and direct. Everything else on the event stays unchanged.",render:(h,m)=>e.jsx(le,{label:"Event title",children:e.jsx(ke,{value:h.title,onChange:c=>m({title:c.target.value}),placeholder:"Weekly research supervision"})})}],submitLabel:"Save title",pending:i,pendingLabel:"Saving",error:o,onSubmit:async()=>{const h=n.trim();if(!h){d("Add a title before saving.");return}d(null),await r(h),s(!1)}})}const d5=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],qc=[{kind:"main_activity",label:"Main activity",title:"Main Activity",startMinute:480,endMinute:720,color:"#f97316",blockingState:"blocked"},{kind:"secondary_activity",label:"Secondary activity",title:"Secondary Activity",startMinute:780,endMinute:1020,color:"#22c55e",blockingState:"allowed"},{kind:"third_activity",label:"Third activity",title:"Third Activity",startMinute:1020,endMinute:1260,color:"#38bdf8",blockingState:"allowed"},{kind:"rest",label:"Rest",title:"Rest",startMinute:1260,endMinute:1380,color:"#a855f7",blockingState:"blocked"},{kind:"holiday",label:"Holiday",title:"Holiday",startMinute:0,endMinute:1440,color:"#14b8a6",blockingState:"blocked"}];function Mn(t=new Date){const s=new Date(t),a=s.getUTCDay(),i=a===0?-6:1-a;return s.setUTCDate(s.getUTCDate()+i),s.setUTCHours(0,0,0,0),s}function Pi(t,s){const a=new Date(t);return a.setUTCDate(a.getUTCDate()+s),a}function cb(t){return Array.from({length:7},(s,a)=>Pi(t,a))}function Ai(t){return new Intl.DateTimeFormat("en",{weekday:"short",month:"short",day:"numeric"}).format(t)}function jm(t){const s=Math.floor(t/60).toString().padStart(2,"0"),a=String(t%60).padStart(2,"0");return`${s}:${a}`}function Nm(t){return`${t.toString().padStart(2,"0")}:00`}function ub({eyebrow:t="Week view",description:s,weekStart:a,status:i,badges:r,onPrevious:n,onCurrent:l,onNext:o}){return 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:t}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:s}),i?e.jsx("div",{className:"mt-3",children:i}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[e.jsx(ds,{className:"mr-1 size-3.5"}),"Week of ",Ai(a)]}),r,e.jsx(z,{variant:"secondary",onClick:n,children:"Previous"}),e.jsx(z,{variant:"secondary",onClick:l,children:"This week"}),e.jsx(z,{variant:"secondary",onClick:o,children:"Next"})]})]})}const km=[{value:"main_activity",label:"Main activity"},{value:"secondary_activity",label:"Secondary activity"},{value:"third_activity",label:"Third activity"},{value:"rest",label:"Rest"},{value:"holiday",label:"Holiday"},{value:"custom",label:"Custom"}],Sm=[{value:"busy",label:"Busy"},{value:"free",label:"Free"}],ea={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function Hi(t){return t.join(", ")}function Gi(t){return t.split(",").map(s=>s.trim()).filter(Boolean)}function kl({label:t,selected:s,onToggle:a,options:i}){return e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}),e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map(r=>{const n=s.includes(r.value);return e.jsx("button",{type:"button",onClick:()=>a(r.value),className:`rounded-full px-3 py-2 text-sm transition ${n?"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:r.label},r.value)})})]})}function hb({title:t,subtitle:s,initialRules:a,initialPlannedDurationSeconds:i,onSave:r,saveLabel:n="Save scheduling rules",allowPlannedDuration:l=!1}){const[o,d]=u.useState((a==null?void 0:a.allowWorkBlockKinds)??ea.allowWorkBlockKinds),[h,m]=u.useState((a==null?void 0:a.blockWorkBlockKinds)??ea.blockWorkBlockKinds),[c,g]=u.useState((a==null?void 0:a.allowAvailability)??ea.allowAvailability),[x,p]=u.useState((a==null?void 0:a.blockAvailability)??ea.blockAvailability),[f,b]=u.useState(Hi((a==null?void 0:a.allowCalendarIds)??ea.allowCalendarIds)),[M,P]=u.useState(Hi((a==null?void 0:a.blockCalendarIds)??ea.blockCalendarIds)),[T,w]=u.useState(Hi((a==null?void 0:a.allowEventTypes)??ea.allowEventTypes)),[j,v]=u.useState(Hi((a==null?void 0:a.blockEventTypes)??ea.blockEventTypes)),[y,E]=u.useState(Hi((a==null?void 0:a.allowEventKeywords)??ea.allowEventKeywords)),[S,B]=u.useState(Hi((a==null?void 0:a.blockEventKeywords)??ea.blockEventKeywords)),[N,A]=u.useState(i?String(Math.round(i/60)):"30"),[q,W]=u.useState(!1),Y=u.useMemo(()=>({allowWorkBlockKinds:o,blockWorkBlockKinds:h,allowCalendarIds:Gi(f),blockCalendarIds:Gi(M),allowEventTypes:Gi(T),blockEventTypes:Gi(j),allowEventKeywords:Gi(y),blockEventKeywords:Gi(S),allowAvailability:c,blockAvailability:x}),[c,f,y,T,o,x,M,S,j,h]),K=Object.values(Y).every(R=>R.length===0),O=(R,F,H)=>{F(R.includes(H)?R.filter(G=>G!==H):[...R,H])};return e.jsxs(ie,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:s})]}),l?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Planned duration"}),e.jsx(ke,{type:"number",min:15,step:15,value:N,onChange:R=>A(R.target.value),placeholder:"30"})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(kl,{label:"Allow work blocks",selected:o,onToggle:R=>O(o,d,R),options:km}),e.jsx(kl,{label:"Block work blocks",selected:h,onToggle:R=>O(h,m,R),options:km}),e.jsx(kl,{label:"Allow availability",selected:c,onToggle:R=>O(c,g,R),options:Sm}),e.jsx(kl,{label:"Block availability",selected:x,onToggle:R=>O(x,p,R),options:Sm})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow calendar ids"}),e.jsx(ke,{value:f,onChange:R=>b(R.target.value),placeholder:"calendar_123, primary"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block calendar ids"}),e.jsx(ke,{value:M,onChange:R=>P(R.target.value),placeholder:"calendar_456"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow event types"}),e.jsx(ke,{value:T,onChange:R=>w(R.target.value),placeholder:"focus, personal"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block event types"}),e.jsx(ke,{value:j,onChange:R=>v(R.target.value),placeholder:"out-of-office, main-work"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow event keywords"}),e.jsx(ke,{value:y,onChange:R=>E(R.target.value),placeholder:"creative, writing"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block event keywords"}),e.jsx(ke,{value:S,onChange:R=>B(R.target.value),placeholder:"psychiatrist, clinic, rest"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(z,{pending:q,pendingLabel:"Saving",onClick:async()=>{W(!0);try{await r({schedulingRules:K?ea:Y,plannedDurationSeconds:l?Math.max(15,Number(N||30))*60:void 0})}finally{W(!1)}},children:n}),e.jsx(z,{variant:"secondary",onClick:async()=>{W(!0);try{d([]),m([]),g([]),p([]),b(""),P(""),w(""),v(""),E(""),B(""),await r({schedulingRules:null,plannedDurationSeconds:l?Math.max(15,Number(N||30))*60:void 0})}finally{W(!1)}},children:"Clear custom rules"})]})]})}function mb({open:t,onOpenChange:s,tasks:a,onSave:i}){const r=u.useMemo(()=>a.filter(d=>d.status!=="done"),[a]),[n,l]=u.useState("");u.useEffect(()=>{if(t){if(r.length===0){l("");return}l(d=>d&&r.some(h=>h.id===d)?d:r[0].id)}},[r,t]);const o=r.find(d=>d.id===n)??null;return e.jsx(oa,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Adjust task scheduling rules",description:"Choose a task, then tell Forge which work blocks, calendar conditions, or keywords should allow or block that work.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(Ht,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Guided rule editing"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Use this when a task should only run in certain blocks such as Secondary Activity, or should stay blocked during clinic, rest, or other provider events."})]})]})}),r.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Task"}),e.jsx("select",{value:n,onChange:d=>l(d.target.value),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:r.map(d=>e.jsx("option",{value:d.id,children:d.title},d.id))})]}),o?e.jsx(hb,{title:"Task rules",subtitle:"These rules are saved directly on the task. They drive blocked-now checks and future timebox recommendations.",initialRules:o.schedulingRules,initialPlannedDurationSeconds:o.plannedDurationSeconds,allowPlannedDuration:!0,saveLabel:"Save task rules",onSave:async({schedulingRules:d,plannedDurationSeconds:h})=>{await i({taskId:o.id,schedulingRules:d,plannedDurationSeconds:h===void 0?o.plannedDurationSeconds:h??null}),s(!1)}}):null]}):e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-white/[0.04]",children:[e.jsx("div",{className:"font-medium text-white",children:"No schedulable tasks yet"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Create or reopen a task first, then come back here to define work-block and calendar eligibility."}),e.jsx("div",{className:"mt-4",children:e.jsx(z,{variant:"secondary",onClick:()=>s(!1),children:"Close"})})]})]})})}function Ni(t){return t.slice(0,10)}function c5(t){return new Date(`${t}T00:00:00`).toISOString()}function u5(t){return new Date(`${t}T23:59:59.999`).toISOString()}function Bc(t,s,a){return t<s?s:t>a?a:t}function Cm(t,s){const a=Ni(t),i=Ni(s),r=new Date(`${a}T12:00:00`);return r.setDate(r.getDate()+1),Bc(Ni(r.toISOString()),a,i)}function Im(t){return String(t).padStart(2,"0")}function Sl(t){return`${Im(t.getHours())}:${Im(t.getMinutes())}`}function Tm(t,s){if(!t||!s)return null;const a=new Date(`${t}T${s}:00`);return Number.isNaN(a.getTime())?null:a}function Cl(t,s,a){if(a){const l=new Date(a.startsAt),o=new Date(a.endsAt);return{startTime:Sl(l),endTime:Sl(o)}}const i=new Date(`${t}T09:00:00`),r=Math.max(1800,Math.min(s??3600,360*60)),n=new Date(i.getTime()+r*1e3);return{startTime:Sl(i),endTime:Sl(n)}}function pb(t,s){return`${new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})} - ${new Date(s).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function od(t,s){return`${Ai(new Date(t))} · ${pb(t,s)}`}function _d({title:t,subtitle:s,emptyLabel:a,children:i}){const r=Array.isArray(i)?i:i?[i]:[];return e.jsxs("div",{className:"rounded-[24px] border border-white/8 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-medium text-white",children:t}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:s})]}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:r.length})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:r.length>0?r:e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/46",children:a})})]})}function h5({event:t}){return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:t.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:t.availability})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:od(t.startAt,t.endAt)})]})}function m5({block:t}){return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:t.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:t.blockingState})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:od(t.startAt,t.endAt)})]})}function p5({timebox:t}){const s=Mr(t);return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:t.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:t.source})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:od(t.startsAt,t.endsAt)}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:Kt(s.rateApPerHour)}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:kt(s.totalAp)})]})]})}function xb({open:t,onOpenChange:s,tasks:a,from:i,to:r,onCreateTimebox:n,onUpdateTimebox:l,onDeleteTimebox:o,initialTaskId:d,lockedTaskId:h,editingTimebox:m,userIds:c}){var Ne,fe,V,Ce,L,D;const g=!!m,x=u.useMemo(()=>{const _=h??(m==null?void 0:m.taskId)??null,ee=a.filter(te=>te.status!=="done"||te.id===_);if(!_)return ee;const U=ee.find(te=>te.id===_);return U?[U]:[]},[m==null?void 0:m.taskId,h,a]),p=Ni(i),f=Ni(r),b=m?Bc(Ni(m.startsAt),p,f):Cm(i,r),M=h??(m==null?void 0:m.taskId)??d??((Ne=x[0])==null?void 0:Ne.id)??"",P=x.find(_=>_.id===M)??x[0]??null,T=Cl(b,P==null?void 0:P.plannedDurationSeconds,m?{startsAt:m.startsAt,endsAt:m.endsAt}:null),[w,j]=u.useState({taskId:M,preferredDate:b,plannerMode:m?"manual":"suggested",selectedTimeboxId:"",activityPresetKey:((fe=m==null?void 0:m.actionProfile)==null?void 0:fe.profileKey)??"task_inherited",customSustainRateApPerHour:((V=m==null?void 0:m.actionProfile)==null?void 0:V.sourceMethod)==="manual"?m.actionProfile.sustainRateApPerHour:null,manualStartTime:T.startTime,manualEndTime:T.endTime,manualTitle:(m==null?void 0:m.title)??(P==null?void 0:P.title)??"",overrideReason:(m==null?void 0:m.overrideReason)??""}),[v,y]=u.useState(null),[E,S]=u.useState(!1),[B,N]=u.useState(!1);u.useEffect(()=>{var ve,pe,Ee;if(!t)return;const _=h??d??((ve=x[0])==null?void 0:ve.id)??"",ee=(m==null?void 0:m.taskId)??_,U=x.find(ce=>ce.id===ee)??x[0]??null,te=m?Bc(Ni(m.startsAt),p,f):Cm(i,r),J=Cl(te,U==null?void 0:U.plannedDurationSeconds,m?{startsAt:m.startsAt,endsAt:m.endsAt}:null);y(null),j({taskId:ee,preferredDate:te,plannerMode:m?"manual":"suggested",selectedTimeboxId:"",activityPresetKey:((pe=m==null?void 0:m.actionProfile)==null?void 0:pe.profileKey)??"task_inherited",customSustainRateApPerHour:((Ee=m==null?void 0:m.actionProfile)==null?void 0:Ee.sourceMethod)==="manual"?m.actionProfile.sustainRateApPerHour:null,manualStartTime:J.startTime,manualEndTime:J.endTime,manualTitle:(m==null?void 0:m.title)??(U==null?void 0:U.title)??"",overrideReason:(m==null?void 0:m.overrideReason)??""})},[x,m,i,d,h,f,p,t,r]);const A=x.find(_=>_.id===w.taskId)??null,q=u.useMemo(()=>({from:c5(w.preferredDate),to:u5(w.preferredDate)}),[w.preferredDate]),W=Me({queryKey:["forge-calendar-suggestions-dialog",w.taskId,q.from,q.to],queryFn:()=>mN({taskId:w.taskId,from:q.from,to:q.to,limit:8}),enabled:t&&w.taskId.length>0}),Y=Me({queryKey:["forge-calendar-timebox-dialog-day",q.from,q.to,...c??[]],queryFn:()=>Pr({from:q.from,to:q.to,userIds:c}),enabled:t});u.useEffect(()=>{var ee;if(!t)return;const _=((ee=W.data)==null?void 0:ee.timeboxes)??[];if(!_.length){j(U=>U.selectedTimeboxId?{...U,selectedTimeboxId:""}:U);return}j(U=>U.selectedTimeboxId&&_.some(te=>te.id===U.selectedTimeboxId)?U:{...U,selectedTimeboxId:_[0].id})},[t,W.data]);const K=(Ce=Y.data)==null?void 0:Ce.calendar,O=(K==null?void 0:K.events)??[],R=(K==null?void 0:K.workBlockInstances)??[],F=(K==null?void 0:K.timeboxes)??[],H=(((L=W.data)==null?void 0:L.timeboxes)??[]).find(_=>_.id===w.selectedTimeboxId),G=Tm(w.preferredDate,w.manualStartTime),$=Tm(w.preferredDate,w.manualEndTime),Q=G&&$?Mr({startsAt:G.toISOString(),endsAt:$.toISOString(),actionProfile:w.customSustainRateApPerHour!==null||w.activityPresetKey!=="task_inherited"?{id:"manual-preview",profileKey:"manual-preview",title:w.manualTitle||(A==null?void 0:A.title)||"Manual timebox",entityType:"task_timebox",mode:"container",startupAp:0,totalCostAp:0,expectedDurationSeconds:null,sustainRateApPerHour:w.customSustainRateApPerHour??((D=ji().find(_=>_.key===w.activityPresetKey))==null?void 0:D.defaultRateApPerHour)??100/24,demandWeights:{activation:.1,focus:.3,vigor:.1,composure:.1,flow:.4},doubleCountPolicy:"container_only",sourceMethod:"manual",costBand:"light",recoveryEffect:0,metadata:{},createdAt:G.toISOString(),updatedAt:G.toISOString()}:null}):null,X=g?"Review the task tied to this scheduled block":h?"Review the task you are planning":"Choose the task you want to place into the calendar",ae=g?"The timebox stays linked to this task. Update the day, hours, title, or AP profile without leaving the planning flow.":h?"Forge will use this task's current duration target and scheduling rules while it looks for viable slots.":"Forge will use the task's current planned duration and scheduling rules when it searches for valid slots.",Pe=u.useMemo(()=>[{id:"task",eyebrow:"Planning",title:X,description:ae,render:(_,ee)=>e.jsxs("div",{className:"grid gap-4",children:[h?null:e.jsx(le,{label:"Task",children:e.jsx("select",{value:_.taskId,onChange:U=>(()=>{const te=x.find(ve=>ve.id===U.target.value),J=Cl(_.preferredDate,te==null?void 0:te.plannedDurationSeconds);ee({taskId:U.target.value,selectedTimeboxId:"",activityPresetKey:"task_inherited",customSustainRateApPerHour:null,manualStartTime:J.startTime,manualEndTime:J.endTime,manualTitle:(te==null?void 0:te.title)??_.manualTitle})})(),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:x.map(U=>e.jsx("option",{value:U.id,children:U.title},U.id))})}),A?e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(28,36,54,0.78),rgba(15,22,34,0.78))] p-5 shadow-[0_18px_40px_rgba(5,12,24,0.22)]",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/42",children:"Time Box"}),e.jsx("div",{className:"mt-2 font-display text-[1.4rem] leading-tight text-white",children:A.title})]}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:A.status})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:A.plannedDurationSeconds?`${Math.round(A.plannedDurationSeconds/60)} min target`:"No duration yet"}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:A.schedulingRules?"Task-specific rules":"Uses project rules"}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[A.points," xp"]}),A.plannedDurationSeconds?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[kt(A.plannedDurationSeconds/3600/24*100)," target load"]}):null]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/60",children:"Pick a day first, then either accept one of Forge's suggested slots or set the block manually."}),g&&m&&o?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-3 rounded-[20px] border border-rose-400/18 bg-rose-400/8 px-4 py-3",children:[e.jsx("div",{className:"text-sm leading-6 text-rose-100/84",children:"Remove this planned timebox if you no longer want it in the calendar."}),e.jsx(z,{type:"button",variant:"ghost",className:"text-rose-100 hover:bg-rose-500/12",pending:B,pendingLabel:"Deleting",onClick:()=>void(async()=>{y(null),N(!0);try{await o(m.id),s(!1)}catch(U){y(U instanceof Error?U.message:"Forge could not delete this timebox.")}finally{N(!1)}})(),children:"Delete timebox"})]}):null]}):null]})},{id:"day",eyebrow:"Calendar",title:"Choose the day and review what is already there",description:"Forge reads the real day first so the timebox stays grounded in your provider events, work blocks, and already-planned work.",render:(_,ee)=>e.jsx("div",{className:"grid gap-5",children:e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(le,{label:"Date",description:"Choose the day you want to protect for this task.",children:e.jsx(ke,{type:"date",min:p,max:f,value:_.preferredDate,onChange:U=>{const te=Cl(U.target.value,A==null?void 0:A.plannedDurationSeconds,m?{startsAt:`${U.target.value}T${_.manualStartTime}:00`,endsAt:`${U.target.value}T${_.manualEndTime}:00`}:null);ee({preferredDate:U.target.value,selectedTimeboxId:"",manualStartTime:te.startTime,manualEndTime:te.endTime})}})}),e.jsx(le,{label:"Planning style",description:"Take Forge's slot recommendation when it fits, or set the block yourself.",children:e.jsx(vt,{value:_.plannerMode,onChange:U=>ee({plannerMode:U}),options:[{value:"suggested",label:"Use suggestions",description:"Forge proposes slots that fit the task rules and the selected day."},{value:"manual",label:"Set it manually",description:"You choose the exact start and end time yourself."}]})})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,31,44,0.86),rgba(11,17,28,0.86))] p-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:"Selected day"}),e.jsx("div",{className:"mt-2 font-display text-[1.3rem] leading-tight text-white",children:_.preferredDate?new Date(`${_.preferredDate}T12:00:00`).toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"}):"Choose a day"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[O.length," events"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[R.length," work blocks"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[F.length," timeboxes"]})]})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"This is the context Forge will use while recommending a slot. You can still place the block manually if you want something more exact."}),Y.isLoading?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-4 text-sm text-white/56",children:"Loading the selected day…"}):e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-3",children:[e.jsx(_d,{title:"Provider events",subtitle:"Busy or free events already on the day.",emptyLabel:"No mirrored events on this day.",children:O.slice(0,4).map(U=>e.jsx(h5,{event:U},U.id))}),e.jsx(_d,{title:"Work blocks",subtitle:"Recurring allowed or blocked containers.",emptyLabel:"No work blocks land on this day.",children:R.slice(0,4).map(U=>e.jsx(m5,{block:U},U.id))}),e.jsx(_d,{title:"Planned timeboxes",subtitle:"Existing owned work already placed there.",emptyLabel:"No other planned timeboxes yet.",children:F.slice(0,4).map(U=>e.jsx(p5,{timebox:U},U.id))})]})]})]})})},{id:"slot",eyebrow:w.plannerMode==="suggested"?"Suggestion":"Manual",title:w.plannerMode==="suggested"?"Choose one of Forge's suggested slots":"Set the exact timebox yourself",description:w.plannerMode==="suggested"?"Forge proposes slots that fit the selected day, the task rules, and the current calendar picture.":"Use manual mode when the right block is obvious to you or when you want to place the timebox despite imperfect recommendations.",render:(_,ee)=>{var te;if(_.plannerMode==="manual")return e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(le,{label:"Day",description:"Pick the day for the block. Forge defaults to a future day, but you can move it.",children:e.jsx(ke,{type:"date",min:p,max:f,value:_.preferredDate,onChange:J=>ee({preferredDate:J.target.value})})}),e.jsx(le,{label:"Start time",description:"Choose when the protected work block should begin.",children:e.jsx(ke,{type:"time",step:300,value:_.manualStartTime,onChange:J=>ee({manualStartTime:J.target.value})})}),e.jsx(le,{label:"End time",description:"Choose when the work block should end.",children:e.jsx(ke,{type:"time",step:300,value:_.manualEndTime,onChange:J=>ee({manualEndTime:J.target.value})})})]}),e.jsx(le,{label:"Title",description:"By default Forge uses the task title. Tighten it only if a shorter calendar label would help.",children:e.jsx(ke,{value:_.manualTitle,onChange:J=>ee({manualTitle:J.target.value}),placeholder:(A==null?void 0:A.title)??"Task timebox"})}),e.jsx(le,{label:"Override reason",description:"Optional. Add a short reason only if you are intentionally placing the block despite the normal rules or calendar shape.",children:e.jsx(ke,{value:_.overrideReason,onChange:J=>ee({overrideReason:J.target.value}),placeholder:"Protected writing block before clinic."})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Activity profile",children:e.jsx("select",{value:_.activityPresetKey??"task_inherited",onChange:J=>ee({activityPresetKey:J.target.value}),className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:ji().map(J=>e.jsx("option",{value:J.key,children:J.label},J.key))})}),e.jsx(le,{label:"Custom AP per hour",children:e.jsx(ke,{type:"number",min:0,step:.5,value:_.customSustainRateApPerHour??"",onChange:J=>ee({customSustainRateApPerHour:J.target.value.trim()===""?null:Number(J.target.value)}),placeholder:"Leave empty to use the activity profile"})})]}),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-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:_.manualTitle||(A==null?void 0:A.title)||"Manual timebox"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:G&&$?`${G.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"})} · ${pb(G.toISOString(),$.toISOString())}`:"Choose a start and end time."})]}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:"manual"})]}),Q?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:Kt(Q.rateApPerHour)}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:kt(Q.totalAp)})]}):null]})]});const U=((te=W.data)==null?void 0:te.timeboxes)??[];return W.isLoading?e.jsx("div",{className:"text-sm text-white/62",children:"Looking for valid slots on the selected day…"}):U.length?e.jsx("div",{className:"grid gap-3",children:U.map(J=>{var Ee;const ve=_.selectedTimeboxId===J.id,pe=Mr({...J,actionProfile:_.customSustainRateApPerHour!==null||_.activityPresetKey!=="task_inherited"?{id:"suggested-preview",profileKey:"suggested-preview",title:J.title,entityType:"task_timebox",mode:"container",startupAp:0,totalCostAp:0,expectedDurationSeconds:null,sustainRateApPerHour:_.customSustainRateApPerHour??((Ee=ji().find(ce=>ce.key===_.activityPresetKey))==null?void 0:Ee.defaultRateApPerHour)??100/24,demandWeights:{activation:.1,focus:.3,vigor:.1,composure:.1,flow:.4},doubleCountPolicy:"container_only",sourceMethod:"manual",costBand:"light",recoveryEffect:0,metadata:{},createdAt:J.startsAt,updatedAt:J.startsAt}:null});return e.jsxs("button",{type:"button",onClick:()=>ee({selectedTimeboxId:J.id}),className:`rounded-[24px] border px-4 py-4 text-left transition ${ve?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white shadow-[0_18px_36px_rgba(5,12,24,0.24)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium",children:J.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:J.source})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:od(J.startsAt,J.endsAt)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Kt(pe.rateApPerHour)}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:kt(pe.totalAp)})]}),ve?e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Activity profile",children:e.jsx("select",{value:_.activityPresetKey??"task_inherited",onChange:ce=>ee({activityPresetKey:ce.target.value}),className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:ji().map(ce=>e.jsx("option",{value:ce.key,children:ce.label},ce.key))})}),e.jsx(le,{label:"Custom AP per hour",children:e.jsx(ke,{type:"number",min:0,step:.5,value:_.customSustainRateApPerHour??"",onChange:ce=>ee({customSustainRateApPerHour:ce.target.value.trim()===""?null:Number(ce.target.value)}),placeholder:"Leave empty to use the activity profile"})})]}):null]},J.id)})}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"rounded-[24px] border border-amber-400/20 bg-amber-400/10 px-4 py-4 text-sm leading-6 text-amber-100/86",children:"Forge could not find a valid slot on this day. Try another day, adjust the task rules, or switch to manual placement if you already know the right block."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(z,{variant:"secondary",onClick:()=>void W.refetch(),children:"Refresh suggestions"}),e.jsx(z,{variant:"secondary",onClick:()=>ee({plannerMode:"manual"}),children:"Switch to manual"})]})]})}}],[x,Y.isLoading,R,O,F,w.plannerMode,m,i,h,f,Q,p,A,W.data,W.isLoading,ae,X,r]);return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Calendar",title:g?"Edit timebox":"Plan work",description:g?"Update the day, hour range, title, and AP profile for this scheduled block without leaving the task or calendar view.":"Review the day, let Forge recommend valid slots, and place a real timebox on the task without leaving the detail view.",value:w,onChange:j,steps:Pe,submitLabel:g?"Save timebox":"Schedule timebox",pending:E,pendingLabel:"Scheduling",error:v,contentClassName:"md:w-[min(70rem,calc(100vw-1.5rem))]",onSubmit:async()=>{if(!A){y("Choose a task before scheduling a timebox.");return}if(w.plannerMode==="manual"){if(!G||!$){y("Choose a valid manual start and end time.");return}if($<=G){y("The manual timebox needs an end time after the start time.");return}y(null),S(!0);try{const _={title:w.manualTitle.trim()||A.title,startsAt:G.toISOString(),endsAt:$.toISOString(),overrideReason:w.overrideReason.trim()||null,activityPresetKey:w.activityPresetKey,customSustainRateApPerHour:w.customSustainRateApPerHour};m&&l?await l(m.id,_):await n({taskId:A.id,projectId:A.projectId,..._,source:"manual"}),s(!1)}catch(_){y(_ instanceof Error?_.message:"Forge could not create the manual timebox.")}finally{S(!1)}return}if(!H){y("Pick one suggested slot before scheduling the timebox.");return}y(null),S(!0);try{const _={title:H.title,startsAt:H.startsAt,endsAt:H.endsAt,activityPresetKey:w.activityPresetKey,customSustainRateApPerHour:w.customSustainRateApPerHour};m&&l?await l(m.id,_):await n({taskId:A.id,projectId:A.projectId,..._,source:H.source}),s(!1)}catch(_){y(_ instanceof Error?_.message:"Forge could not create the selected timebox.")}finally{S(!1)}}})}function Pm(t){if(t)return{title:t.title,kind:t.kind,color:t.color,timezone:t.timezone,weekDays:t.weekDays,startMinute:t.startMinute,endMinute:t.endMinute,startsOn:t.startsOn,endsOn:t.endsOn,blockingState:t.blockingState,activityPresetKey:bf(t.actionProfile),customSustainRateApPerHour:vf(t.actionProfile)};const s=qc[0];return{title:s.title,kind:s.kind,color:s.color,timezone:typeof Intl<"u"&&Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",weekDays:[1,2,3,4,5],startMinute:s.startMinute,endMinute:s.endMinute,startsOn:null,endsOn:null,blockingState:s.blockingState,activityPresetKey:s.kind==="main_activity"?"deep_work":s.kind==="secondary_activity"?"admin":s.kind==="holiday"?"holiday_leisure":s.kind==="rest"?"recovery_break":"maintenance",customSustainRateApPerHour:null}}function Am(t){return t??""}function Rd({draft:t}){const s=V2({kind:t.kind,startMinute:t.startMinute,endMinute:t.endMinute,activityPresetKey:t.activityPresetKey,customSustainRateApPerHour:t.customSustainRateApPerHour}),a=t.endMinute>t.startMinute?t.endMinute-t.startMinute:1440-t.startMinute+t.endMinute;return e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Kt(s.rateApPerHour)}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[kt(s.totalAp)," / block"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[Math.round(a/60),"h ",a%60,"m"]})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"This is the default Life Force container drain for each occurrence of the block when no richer task run or timebox already covers that window."})]})}function x5({open:t,onOpenChange:s,onSubmit:a,pending:i=!1,template:r=null}){const[n,l]=u.useState(()=>Pm(r)),[o,d]=u.useState(null),h=r!==null;u.useEffect(()=>{t&&(d(null),l(Pm(r)))},[t,r]);const m=u.useMemo(()=>[{id:"preset",eyebrow:"Preset",title:"Start from a recurring block that already matches the rhythm",description:"Use a preset to seed the schedule, then tune the dates and recurrence in the next step.",render:(c,g)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Rd,{draft:c}),e.jsx(le,{label:"Activity profile",children:e.jsx(vt,{value:c.activityPresetKey??"maintenance",columns:3,onChange:x=>g({activityPresetKey:x,customSustainRateApPerHour:c.customSustainRateApPerHour}),options:ji().filter(x=>x.key!=="task_inherited").map(x=>({value:x.key,label:x.label,description:`${Kt(x.defaultRateApPerHour)} · ${x.description}`}))})}),e.jsx(le,{label:"Custom AP per hour",children:e.jsx(ke,{type:"number",min:0,step:.5,value:c.customSustainRateApPerHour??"",onChange:x=>g({customSustainRateApPerHour:x.target.value.trim()===""?null:Number(x.target.value)}),placeholder:"Leave empty to use the activity default"})}),e.jsx(le,{label:"Block type",children:e.jsx(vt,{value:c.kind,columns:3,onChange:x=>{const p=qc.find(f=>f.kind===x);if(p){const f=p.kind==="holiday"?[0,1,2,3,4,5,6]:[1,2,3,4,5];g({kind:p.kind,title:p.title,color:p.color,weekDays:f,startMinute:p.startMinute,endMinute:p.endMinute,blockingState:p.blockingState,activityPresetKey:p.kind==="main_activity"?"deep_work":p.kind==="secondary_activity"?"admin":p.kind==="holiday"?"holiday_leisure":p.kind==="rest"?"recovery_break":"maintenance",customSustainRateApPerHour:null});return}g({kind:"custom",title:"Custom block",color:"#7dd3fc",activityPresetKey:"maintenance",customSustainRateApPerHour:null})},options:[...qc.map(x=>({value:x.kind,label:x.title,description:`${jm(x.startMinute)}-${jm(x.endMinute)}`})),{value:"custom",label:"Custom",description:"Build a different recurring window."}]})})]})},{id:"shape",eyebrow:"Schedule",title:"Define when this recurring block should exist",description:"Weekdays and times describe the recurring pattern. Optional start and end dates bound when the template is active.",render:(c,g)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Rd,{draft:c}),e.jsx(le,{label:"Block title",children:e.jsx(ke,{value:c.title,onChange:x=>g({title:x.target.value}),placeholder:"Main Activity"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Start minute",children:e.jsx(ke,{type:"number",min:0,max:1440,step:15,value:c.startMinute,onChange:x=>g({startMinute:Number(x.target.value)||0})})}),e.jsx(le,{label:"End minute",children:e.jsx(ke,{type:"number",min:0,max:1440,step:15,value:c.endMinute,onChange:x=>g({endMinute:Number(x.target.value)||0})})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Start date",children:e.jsx(ke,{type:"date",value:Am(c.startsOn),onChange:x=>g({startsOn:x.target.value.trim()||null})})}),e.jsx(le,{label:"End date",children:e.jsx(ke,{type:"date",value:Am(c.endsOn),onChange:x=>g({endsOn:x.target.value.trim()||null})})})]}),e.jsx("div",{className:"text-sm leading-6 text-white/54",children:"Leave the end date empty to keep repeating indefinitely. Holiday blocks work well with all seven weekdays and `0-1440`, and they still carry AP load because leisure and holiday time are real activities."}),e.jsx(le,{label:"Weekdays",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:d5.map((x,p)=>{const f=c.weekDays.includes(p);return e.jsx("button",{type:"button",onClick:()=>g({weekDays:f?c.weekDays.filter(b=>b!==p):[...c.weekDays,p].sort((b,M)=>b-M)}),className:`rounded-full px-3 py-2 text-sm transition ${f?"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:x},x)})})})]})},{id:"policy",eyebrow:"Policy",title:"Tell Forge whether this block allows or blocks work",description:"Use blocked mode for time that should normally stop optional work. Use allowed mode for protected focus windows.",render:(c,g)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Rd,{draft:c}),e.jsx(le,{label:"Work effect",children:e.jsx(vt,{value:c.blockingState,onChange:x=>g({blockingState:x}),options:[{value:"blocked",label:"Blocks work",description:"Starting blocked tasks should require an explicit override."},{value:"allowed",label:"Allows work",description:"Use this for protected windows where the right tasks should fit."}]})}),e.jsx(le,{label:"Color",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[22px] border border-white/8 bg-white/6 px-4 py-3",children:[e.jsx("input",{className:"h-10 w-12 rounded-lg border border-white/10 bg-transparent",type:"color",value:c.color,onChange:x=>g({color:x.target.value})}),e.jsx(ke,{className:"border-none bg-transparent px-0 py-0",value:c.color,onChange:x=>g({color:x.target.value})})]})})]})}],[]);return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Calendar",title:h?"Edit work block":"Create a work block",description:h?"Adjust the recurring pattern, date bounds, or work policy for this block.":"Build recurring half-day, holiday, or custom blocks so Forge can understand when work should be protected or blocked.",value:n,onChange:l,steps:m,submitLabel:h?"Save changes":"Save work block",pending:i,pendingLabel:h?"Saving changes":"Saving",error:o,onSubmit:async()=>{if(!n.title.trim()){d("Give the block a title so it stays readable in the calendar.");return}if(n.weekDays.length===0){d("Select at least one weekday for the recurring block.");return}if(n.endMinute<=n.startMinute){d("The end minute needs to be later than the start minute.");return}if(n.startsOn&&n.endsOn&&n.endsOn<n.startsOn){d("The end date needs to be on or after the start date.");return}try{d(null),await a({...n,title:n.title.trim()}),s(!1)}catch(c){d(c instanceof Error?c.message:"Forge could not save this work block.")}}})}function Rs({className:t}){return e.jsx("div",{className:Z("surface-pulse rounded-2xl bg-white/[0.05]",t)})}function ns({header:t=!0,sideRail:s=!0,className:a,eyebrow:i,title:r,description:n,columns:l=2,blocks:o=4}){const d=Array.from({length:Math.max(2,o)});return e.jsxs("div",{className:Z("grid gap-5",a),"aria-hidden":"true",children:[t?e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:Z("h-3",i?"w-40":"w-32")}),e.jsx(Rs,{className:Z("h-12",r?"max-w-2xl":"max-w-3xl")}),e.jsx(Rs,{className:Z("h-5",n?"max-w-3xl":"max-w-2xl")})]}):null,e.jsxs("section",{className:Z("grid gap-5",s?"xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]":""),children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:"h-3 w-28"}),e.jsx(Rs,{className:"h-28 w-full"})]}),e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:"h-3 w-40"}),e.jsx("div",{className:Z("grid gap-3",l>1?"md:grid-cols-2":""),children:d.map((h,m)=>e.jsx(Rs,{className:"h-28 w-full"},m))})]})]}),s?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:"h-3 w-24"}),e.jsx(Rs,{className:"h-20 w-full"})]}),e.jsxs(ie,{className:"grid gap-4",children:[e.jsx(Rs,{className:"h-3 w-36"}),e.jsx(Rs,{className:"h-16 w-full"}),e.jsx(Rs,{className:"h-16 w-full"})]})]}):null]})]})}function dd({open:t,title:s,subtitle:a,items:i,position:r,onClose:n}){return u.useEffect(()=>{if(!t)return;let l=!1;const o=window.setTimeout(()=>{l=!0},0),d=m=>{m.key==="Escape"&&n()},h=()=>{l&&n()};return window.addEventListener("keydown",d),window.addEventListener("pointerdown",h),()=>{window.clearTimeout(o),window.removeEventListener("keydown",d),window.removeEventListener("pointerdown",h)}},[n,t]),!t||!r||typeof document>"u"?null:Ri.createPortal(e.jsx("div",{className:"fixed inset-0 z-[70]","aria-hidden":"true",children:e.jsxs("div",{className:"fixed z-[71] flex max-h-[min(34rem,calc(100dvh-1.5rem))] w-[min(22rem,calc(100vw-1.5rem))] flex-col overflow-hidden rounded-[26px] border border-white/10 bg-[rgba(10,15,27,0.97)] p-2 shadow-[0_28px_80px_rgba(4,8,18,0.4)] backdrop-blur-xl",style:{left:Math.min(r.x,window.innerWidth-24-352),top:Math.min(r.y,window.innerHeight-24-544)},onPointerDown:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[20px] bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:s}),a?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:a}):null]}),e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.04] p-2 text-white/55 transition hover:bg-white/[0.08] hover:text-white",onClick:n,children:e.jsx(Tt,{className:"size-4"})})]}),e.jsx("div",{className:"mt-2 min-h-0 overflow-y-auto overscroll-contain pr-1",children:e.jsx("div",{className:"grid gap-1",children:i.map(l=>{const o=l.icon;return e.jsxs("button",{type:"button",disabled:l.disabled,onClick:()=>{l.disabled||(l.onSelect(),n())},className:Z("flex w-full items-start gap-3 rounded-[20px] px-4 py-3 text-left transition",l.disabled?"cursor-not-allowed bg-white/[0.02] text-white/28":l.tone==="danger"?"bg-rose-400/[0.05] text-rose-100 hover:bg-rose-400/[0.12]":"bg-white/[0.03] text-white/76 hover:bg-white/[0.08] hover:text-white"),children:[o?e.jsx("span",{className:Z("mt-0.5 rounded-[14px] p-2",l.disabled?"bg-white/[0.03] text-white/28":l.tone==="danger"?"bg-rose-400/[0.12] text-rose-100":"bg-[var(--primary)]/12 text-[var(--primary)]"),children:e.jsx(o,{className:"size-4"})}):null,e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:l.label}),l.description?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:l.description}):null]})]},l.id)})})})]})}),document.body)}const gb="forge.calendar-display-preferences",Mm=["#7dd3fc","#34d399","#f59e0b","#fb7185","#60a5fa","#a3e635","#f97316","#22c55e"],$d={useCalendarColors:!0,calendarColors:{}};function fb(t){return typeof t=="string"&&/^#[0-9a-fA-F]{6}$/.test(t)}function bb(){if(typeof window>"u")return $d;const t=window.localStorage.getItem(gb);if(!t)return $d;try{const s=JSON.parse(t);return{useCalendarColors:s.useCalendarColors??!0,calendarColors:s.calendarColors&&typeof s.calendarColors=="object"?Object.fromEntries(Object.entries(s.calendarColors).filter(a=>fb(a[1]))):{}}}catch{return $d}}function g5(t){typeof window>"u"||window.localStorage.setItem(gb,JSON.stringify(t))}function vb(t){return Mm[t%Mm.length]??"#7dd3fc"}function wb(t,s){return Object.fromEntries(t.map((a,i)=>[a.id,fb(s[a.id])?s[a.id]:vb(i)]))}function Em(t){let s=0;for(let a=0;a<t.length;a+=1)s=s*31+t.charCodeAt(a)>>>0;return vb(s)}const Il=Ww(t=>({entry:null,setEntry:s=>t({entry:s}),clear:()=>t({entry:null}),completePaste:()=>t(s=>{var a;return{entry:((a=s.entry)==null?void 0:a.mode)==="cut"?null:s.entry}})}));function f5(t){const s=new Date(t);s.setUTCHours(9,0,0,0);const a=new Date(s.getTime()+3600*1e3);return{startAt:s.toISOString(),endAt:a.toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:"busy"}}function Lm(t){var l;const s=Math.max(60,Math.floor((Date.parse(t.endsAt)-Date.parse(t.startsAt))/1e3)),a=((l=ji().find(o=>o.key===t.activityPresetKey))==null?void 0:l.defaultRateApPerHour)??100/24,i=t.customSustainRateApPerHour??a,r=Number((s/3600*i).toFixed(2)),n=new Date().toISOString();return{id:`preview_${t.entityType}_${t.entityId}`,profileKey:`${String(t.entityType)}_${t.entityId}`,title:t.title,entityType:t.entityType,mode:"container",startupAp:0,totalCostAp:r,expectedDurationSeconds:s,sustainRateApPerHour:i,demandWeights:{activation:.1,focus:.35,vigor:.1,composure:.15,flow:.3},doubleCountPolicy:"container_only",sourceMethod:t.customSustainRateApPerHour!==null&&t.customSustainRateApPerHour!==void 0?"manual":t.activityPresetKey?"seeded":"inferred",costBand:i>=10?"standard":"light",recoveryEffect:0,metadata:{activityPresetKey:t.activityPresetKey??null,customSustainRateApPerHour:t.customSustainRateApPerHour??null},createdAt:n,updatedAt:n}}function Dm(t){const s=typeof t.location=="string"?t.location:"",a=t.place??{label:s,address:"",timezone:"",latitude:null,longitude:null,source:"",externalPlaceId:""};return{...t,place:{label:a.label||s,address:a.address??"",timezone:a.timezone??"",latitude:a.latitude??null,longitude:a.longitude??null,source:a.source??"",externalPlaceId:a.externalPlaceId??""}}}function Fm(t,s){const a=new Date(t.startAt),r=new Date(t.endAt).getTime()-a.getTime(),n=new Date(s);n.setUTCHours(a.getUTCHours(),a.getUTCMinutes(),0,0);const l=new Date(n.getTime()+r);return{startAt:n.toISOString(),endAt:l.toISOString()}}function _m(t){return{type:"calendar_event",eventId:t.id,title:t.title,description:t.description,location:t.location,startAt:t.startAt,endAt:t.endAt,timezone:t.timezone,availability:t.availability,preferredCalendarId:t.calendarId,categories:t.categories,links:t.links.map(s=>({entityType:s.entityType,entityId:s.entityId,relationshipType:s.relationshipType}))}}function b5(t){switch(t){case"apple":return"Apple";case"google":return"Google";case"caldav":return"CalDAV";case"native":return"Forge";default:return"Derived"}}function v5(t,s){var a;if(t.calendarId){const i=(a=s.get(t.calendarId))==null?void 0:a.trim();if(i)return i}return t.originType==="native"?"Forge only":b5(t.originType)}function Rm(t){switch(t){case"main_activity":return"Main activity";case"secondary_activity":return"Secondary activity";case"third_activity":return"Third activity";case"rest":return"Rest";case"holiday":return"Holiday";default:return"Custom"}}function $m(t){return t.startsOn&&t.endsOn?`${t.startsOn} to ${t.endsOn}`:t.startsOn?`From ${t.startsOn}`:t.endsOn?`Until ${t.endsOn}`:"Repeats with no end date"}function w5(){var we,Ie,Se,Ge,Be;const t=_t(),[s,a]=us(),i=jt(),r=Array.isArray(i.selectedUserIds)?i.selectedUserIds:[],n=fs(r),l=ct(),o=Il(xe=>xe.entry),d=Il(xe=>xe.setEntry),h=Il(xe=>xe.clear),m=Il(xe=>xe.completePaste),[c,g]=u.useState(()=>Mn()),[x,p]=u.useState(null),[f,b]=u.useState(null),[M,P]=u.useState(!1),[T,w]=u.useState(null),[j,v]=u.useState(!1),[y,E]=u.useState(!1),[S,B]=u.useState(null),[N,A]=u.useState(!1),[q,W]=u.useState(null),[Y,K]=u.useState(null),O=u.useMemo(()=>bb(),[]),[R,F]=u.useState(null),[H,G]=u.useState(null),[$,Q]=u.useState(null),X=s.get("timeboxId"),ae=u.useMemo(()=>{const xe=c.toISOString(),Ae=Pi(c,7).toISOString();return{from:xe,to:Ae}},[c]),Pe=Me({queryKey:["forge-calendar-overview",ae.from,ae.to,...r],queryFn:()=>Pr({...ae,userIds:r})}),Ne=Me({queryKey:["forge-life-force",...r],queryFn:()=>Ki(r)}),fe=["forge-calendar-overview",ae.from,ae.to,...r],V=xe=>{if(xe.deletedAt)return!1;const Ae=new Date(xe.startAt).getTime();return Ae>=new Date(ae.from).getTime()&&Ae<new Date(ae.to).getTime()},Ce=xe=>{l.setQueryData(fe,Ae=>Ae&&xe(Ae))},L=async()=>{await Promise.all([l.invalidateQueries({queryKey:["forge-calendar-overview"]}),l.invalidateQueries({queryKey:["forge-snapshot"]}),l.invalidateQueries({queryKey:["task-context"]}),l.invalidateQueries({queryKey:["project-board"]})])},D=De({mutationFn:xe=>lN({...xe,userId:xe.userId??n}),onSuccess:L}),_=De({mutationFn:({templateId:xe,patch:Ae})=>oN(xe,Ae),onSuccess:L}),ee=De({mutationFn:dN,onSuccess:L}),U=De({mutationFn:xe=>Tg({...xe,userId:n}),onSuccess:L}),te=De({mutationFn:({timeboxId:xe,startsAt:Ae,endsAt:He})=>Ac(xe,{startsAt:Ae,endsAt:He}),onSuccess:L}),J=De({mutationFn:({timeboxId:xe,patch:Ae})=>Ac(xe,Ae),onSuccess:L}),ve=De({mutationFn:Pg,onSuccess:async()=>{B(null),E(!1),await L()}}),pe=De({mutationFn:xe=>cN({...xe,userId:xe.userId??n}),onMutate:async xe=>{var tt,k,se,Le,ze,We,gt;Q({tone:"saving",message:"Saving event changes in the background…"}),await l.cancelQueries({queryKey:fe});const Ae=l.getQueryData(fe),He=(Ae==null?void 0:Ae.calendar.calendars.find(Mt=>Mt.canWrite&&Mt.selectedForSync))??(Ae==null?void 0:Ae.calendar.calendars.find(Mt=>Mt.canWrite))??null,ot=new Date().toISOString(),It=`calendar_event_optimistic_${Date.now()}`,Oe={id:It,connectionId:(He==null?void 0:He.connectionId)??null,calendarId:xe.preferredCalendarId===void 0?(He==null?void 0:He.id)??null:xe.preferredCalendarId,remoteId:null,ownership:"forge",originType:"native",status:"confirmed",title:xe.title,description:xe.description??"",location:xe.location??"",place:{label:((tt=xe.place)==null?void 0:tt.label)??xe.location??"",address:((k=xe.place)==null?void 0:k.address)??"",timezone:((se=xe.place)==null?void 0:se.timezone)??xe.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",latitude:((Le=xe.place)==null?void 0:Le.latitude)??null,longitude:((ze=xe.place)==null?void 0:ze.longitude)??null,source:((We=xe.place)==null?void 0:We.source)??"forge",externalPlaceId:((gt=xe.place)==null?void 0:gt.externalPlaceId)??""},startAt:xe.startAt,endAt:xe.endAt,timezone:xe.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",isAllDay:xe.isAllDay??!1,availability:xe.availability??"busy",eventType:xe.eventType??"general",categories:xe.categories??[],sourceMappings:[],links:(xe.links??[]).map((Mt,Qt)=>({id:`calendar_event_link_optimistic_${Date.now()}_${Qt}`,entityType:Mt.entityType,entityId:Mt.entityId,relationshipType:Mt.relationshipType??"context",createdAt:ot,updatedAt:ot})),actionProfile:Lm({entityType:"calendar_event",entityId:It,title:xe.title,startsAt:xe.startAt,endsAt:xe.endAt,activityPresetKey:xe.activityPresetKey??null,customSustainRateApPerHour:xe.customSustainRateApPerHour??null}),remoteUpdatedAt:null,deletedAt:null,createdAt:ot,updatedAt:ot};return Ae&&V(Oe)&&Ce(Mt=>({...Mt,calendar:{...Mt.calendar,events:[Oe,...Mt.calendar.events]}})),{previous:Ae,optimisticEventId:Oe.id}},onError:(xe,Ae,He)=>{He!=null&&He.previous&&l.setQueryData(fe,He.previous),Q({tone:"error",message:xe instanceof Error?xe.message:"Forge could not sync that event change."})},onSuccess:({event:xe},Ae,He)=>{Q(null),Ce(ot=>({...ot,calendar:{...ot.calendar,events:(V(xe)?[xe,...ot.calendar.events.filter(It=>It.id!==(He==null?void 0:He.optimisticEventId))]:ot.calendar.events.filter(It=>It.id!==(He==null?void 0:He.optimisticEventId))).filter((It,Oe,tt)=>tt.findIndex(k=>k.id===It.id)===Oe)}}))},onSettled:L}),Ee=De({mutationFn:({eventId:xe,patch:Ae})=>uN(xe,Ae),onMutate:async({eventId:xe,patch:Ae})=>{Q({tone:"saving",message:"Saving event changes in the background…"}),await l.cancelQueries({queryKey:fe});const He=l.getQueryData(fe);return He&&Ce(ot=>{var k,se,Le,ze,We;const It=ot.calendar.events.find(gt=>gt.id===xe);if(!It)return ot;const Oe=Dm(It),tt={...Oe,...Ae,place:Ae.place?{...Oe.place,...Ae.place}:Oe.place,calendarId:Ae.preferredCalendarId===void 0?Oe.calendarId:Ae.preferredCalendarId,links:((k=Ae.links)==null?void 0:k.map((gt,Mt)=>{var Qt,Ds;return{id:((Qt=Oe.links[Mt])==null?void 0:Qt.id)??`calendar_event_link_optimistic_${Date.now()}_${Mt}`,entityType:gt.entityType,entityId:gt.entityId,relationshipType:gt.relationshipType??"context",createdAt:((Ds=Oe.links[Mt])==null?void 0:Ds.createdAt)??Oe.createdAt,updatedAt:new Date().toISOString()}}))??Oe.links,actionProfile:Lm({entityType:"calendar_event",entityId:xe,title:Ae.title??Oe.title,startsAt:Ae.startAt??Oe.startAt,endsAt:Ae.endAt??Oe.endAt,activityPresetKey:Ae.activityPresetKey===void 0?(Le=(se=Oe.actionProfile)==null?void 0:se.metadata)==null?void 0:Le.activityPresetKey:Ae.activityPresetKey,customSustainRateApPerHour:Ae.customSustainRateApPerHour===void 0?typeof((We=(ze=Oe.actionProfile)==null?void 0:ze.metadata)==null?void 0:We.customSustainRateApPerHour)=="number"?Oe.actionProfile.metadata.customSustainRateApPerHour:null:Ae.customSustainRateApPerHour}),updatedAt:new Date().toISOString()};return{...ot,calendar:{...ot.calendar,events:ot.calendar.events.map(gt=>gt.id===xe?tt:gt).filter(V)}}}),{previous:He}},onError:(xe,Ae,He)=>{He!=null&&He.previous&&l.setQueryData(fe,He.previous),Q({tone:"error",message:xe instanceof Error?xe.message:"Forge could not sync that event change."})},onSuccess:({event:xe})=>{Q(null),Ce(Ae=>({...Ae,calendar:{...Ae.calendar,events:Ae.calendar.events.map(He=>He.id===xe.id?xe:He).filter(V)}}))},onSettled:L}),ce=De({mutationFn:hN,onMutate:async xe=>{Q({tone:"saving",message:"Removing the event in the background…"}),await l.cancelQueries({queryKey:fe});const Ae=l.getQueryData(fe);return Ae&&Ce(He=>({...He,calendar:{...He.calendar,events:He.calendar.events.filter(ot=>ot.id!==xe)}})),{previous:Ae}},onError:(xe,Ae,He)=>{He!=null&&He.previous&&l.setQueryData(fe,He.previous),Q({tone:"error",message:xe instanceof Error?xe.message:"Forge could not delete that event."})},onSuccess:()=>{Q(null)},onSettled:L}),ue=(we=Pe.data)==null?void 0:we.calendar,Fe=u.useMemo(()=>cb(c),[c]),ye=u.useMemo(()=>ue?{...ue,events:ue.events.map(Dm)}:{generatedAt:"",providers:[],connections:[],calendars:[],events:[],workBlockTemplates:[],workBlockInstances:[],timeboxes:[]},[ue]),he=u.useMemo(()=>new Map(ye.calendars.map(xe=>[xe.id,kr(xe)])),[ye.calendars]),me=u.useMemo(()=>wb(ye.calendars,O.calendarColors),[O.calendarColors,ye.calendars]),Ke=pe.isPending||Ee.isPending||ce.isPending,ge=ye.timeboxes.filter(xe=>xe.status==="planned"),C=ye.calendars.filter(xe=>xe.canWrite),ne=(xe,Ae)=>Ae?`${xe} · ${Ae}`:xe,Re=[...i.snapshot.goals.map(xe=>({entityType:"goal",entityId:xe.id,label:xe.title,subtitle:ne("Goal",ls(xe.user))})),...i.snapshot.projects.map(xe=>({entityType:"project",entityId:xe.id,label:xe.title,subtitle:ne("Project",ls(xe.user))})),...i.snapshot.tasks.map(xe=>({entityType:"task",entityId:xe.id,label:xe.title,subtitle:ne("Task",ls(xe.user))})),...i.snapshot.strategies.map(xe=>({entityType:"strategy",entityId:xe.id,label:xe.title,subtitle:ne("Strategy",ls(xe.user))})),...i.snapshot.habits.map(xe=>({entityType:"habit",entityId:xe.id,label:xe.title,subtitle:ne("Habit",ls(xe.user))}))],at=u.useMemo(()=>new Map(Re.map(xe=>[`${xe.entityType}:${xe.entityId}`,xe.label])),[Re]),lt=ye.connections.length===0?"No providers connected":`${ye.connections.filter(xe=>xe.status==="connected").length}/${ye.connections.length} healthy`,Te=(o==null?void 0:o.items.filter(xe=>xe.type==="calendar_event"))??[];u.useEffect(()=>{if(!X)return;const xe=ye.timeboxes.find(He=>He.id===X);if(!xe)return;const Ae=Mn(new Date(xe.startsAt));if(Ae.getTime()!==c.getTime()){g(Ae);return}((S==null?void 0:S.id)!==xe.id||!y)&&(B(xe),E(!0))},[X,ye.timeboxes,S==null?void 0:S.id,y,c]);const qe=()=>{if(!X)return;const xe=new URLSearchParams(s);xe.delete("timeboxId"),a(xe,{replace:!0})},Je=xe=>{E(xe),xe||(B(null),qe())},Ze=xe=>{W(null),F(f5(xe)),A(!0)},re=async(xe,Ae)=>{const He=Fm({startAt:xe.startAt,endAt:xe.endAt},Ae);await Ee.mutateAsync({eventId:xe.id,patch:He})},oe=async xe=>{if(Te.length!==0){for(const Ae of Te){const He=Fm(Ae,xe);(o==null?void 0:o.mode)==="cut"?await Ee.mutateAsync({eventId:Ae.eventId,patch:He}):await pe.mutateAsync({title:Ae.title,description:Ae.description,location:Ae.location,startAt:He.startAt,endAt:He.endAt,timezone:Ae.timezone,availability:Ae.availability,preferredCalendarId:Ae.preferredCalendarId,categories:Ae.categories,links:Ae.links})}m()}},je=u.useMemo(()=>{if(!H)return[];if(H.kind==="day"){const Ae=Fe.find(He=>He.toISOString().slice(0,10)===H.dayKey);return Ae?[{id:"create-event",label:"Create event",description:"Open the event guide with this day already selected.",icon:ra,onSelect:()=>Ze(Ae)},{id:"create-work-block",label:"Create work block",description:"Open the guided work-block flow while you are looking at this day.",icon:Sn,onSelect:()=>{w(null),P(!0)}},{id:"paste",label:(o==null?void 0:o.mode)==="cut"?"Paste moved event":"Paste copied event",description:Te.length>0?`${Te.length} calendar item${Te.length===1?"":"s"} ready to paste here.`:o?"The current clipboard entry does not contain calendar events.":"Copy or cut an event first, then paste it into this day.",icon:Hw,disabled:Te.length===0,onSelect:()=>void oe(Ae)}]:[]}if(H.kind==="work-block"){const Ae=ye.workBlockTemplates.find(He=>He.id===H.templateId);return Ae?[{id:"edit-work-block",label:"Edit",description:"Adjust the recurring pattern, date bounds, or work policy.",icon:ra,onSelect:()=>{w(Ae),P(!0)}},{id:"delete-work-block",label:"Delete",description:"Remove this recurring work block from Forge.",icon:$t,tone:"danger",onSelect:()=>{(T==null?void 0:T.id)===Ae.id&&w(null),ee.mutateAsync(Ae.id)}}]:[]}const xe=ye.events.find(Ae=>Ae.id===H.eventId);return xe?[{id:"rename",label:"Quick rename",description:"Change the event title without opening the full event flow.",icon:ra,onSelect:()=>K(xe)},{id:"copy",label:"Copy",description:"Put this event on the Forge clipboard so you can paste it into another day.",icon:Wx,onSelect:()=>d({id:`clipboard_${xe.id}_${Date.now()}`,mode:"copy",source:"calendar",label:xe.title,createdAt:new Date().toISOString(),items:[_m(xe)]})},{id:"cut",label:"Cut",description:"Move this event by pasting it into another day.",icon:Go,onSelect:()=>d({id:`clipboard_cut_${xe.id}_${Date.now()}`,mode:"cut",source:"calendar",label:xe.title,createdAt:new Date().toISOString(),items:[_m(xe)]})},{id:"delete",label:"Delete",description:"Remove the event from Forge and delete any connected remote projection.",icon:$t,tone:"danger",onSelect:()=>{(o==null?void 0:o.mode)==="cut"&&Te.some(Ae=>Ae.eventId===xe.id)&&h(),ce.mutateAsync(xe.id)}}]:[]},[h,Te,o,Fe,ce,ee,H,ye.events,ye.workBlockTemplates,T,d]);return Pe.isLoading?e.jsx(ns,{}):Pe.isError||!Pe.data?e.jsx(st,{eyebrow:"Calendar",error:Pe.error??new Error("Calendar data is unavailable"),onRetry:()=>void Pe.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(rt,{entityKind:"project",titleText:"Calendar",title:"Calendar",description:"See the real week first, then open guided flows for work blocks, task rules, timeboxing, and provider setup.",badge:`${ye.connections.length} connection${ye.connections.length===1?"":"s"}`}),(Ie=Ne.data)!=null&&Ie.lifeForce?e.jsxs(ie,{className:"grid gap-3 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(15,25,36,0.98),rgba(9,15,26,0.96))] p-4 md:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force today"}),e.jsxs("div",{className:"mt-2 text-3xl font-semibold text-white",children:[Math.round(Ne.data.lifeForce.spentTodayAp),e.jsxs("span",{className:"ml-2 text-lg text-white/44",children:["/ ",Math.round(Ne.data.lifeForce.dailyBudgetAp)," AP"]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Instant headroom"}),e.jsxs("div",{className:"mt-2 text-2xl font-semibold text-[var(--primary)]",children:[Ne.data.lifeForce.instantFreeApPerHour.toFixed(1)," AP/h"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Calendar containers now speak the same AP language as live work."})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Forecast"}),e.jsxs("div",{className:"mt-2 text-2xl font-semibold text-white",children:[Math.round(Ne.data.lifeForce.forecastAp)," AP"]}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:["Planned remaining ",kt(Ne.data.lifeForce.plannedRemainingAp)]})]})]}):null,e.jsxs(ie,{className:"grid gap-4 rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,28,39,0.985),rgba(10,17,29,0.985))]",children:[e.jsx(ub,{description:"The calendar is the priority surface here. Connected provider events, recurring work blocks, and owned task timeboxes all stay visible together.",weekStart:c,status:$?e.jsx("div",{className:`inline-flex max-w-full items-center gap-2 rounded-full px-3 py-1.5 text-xs ${$.tone==="error"?"border border-rose-400/20 bg-rose-400/10 text-rose-200":"border border-[var(--primary)]/18 bg-[var(--primary)]/12 text-[var(--primary)]"}`,children:$.message}):null,badges:e.jsxs(e.Fragment,{children:[(Se=Ne.data)!=null&&Se.lifeForce?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[Math.round(Ne.data.lifeForce.spentTodayAp),"/",Math.round(Ne.data.lifeForce.dailyBudgetAp)," AP"]}):null,Ke?e.jsxs(I,{className:"bg-white/[0.08] text-white/78",children:[e.jsx(qs,{className:"mr-1 size-3.5 animate-spin"}),"Syncing changes"]}):null,o?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[o.mode==="cut"?"Cut":"Copied"," · ",o.label]}):null]}),onPrevious:()=>g(Pi(c,-7)),onCurrent:()=>g(Mn()),onNext:()=>g(Pi(c,7))}),e.jsx("div",{className:"grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(min(100%,17rem),1fr))] 2xl:[grid-template-columns:repeat(7,minmax(0,1fr))]",children:Fe.map(xe=>{const Ae=xe.toISOString().slice(0,10),He=ye.events.filter(Oe=>Oe.startAt.slice(0,10)===Ae&&!Oe.deletedAt),ot=ye.workBlockInstances.filter(Oe=>Oe.dateKey===Ae),It=ye.timeboxes.filter(Oe=>Oe.startsAt.slice(0,10)===Ae);return e.jsxs("div",{"data-calendar-day":Ae,onClick:Oe=>{Oe.target.closest("[data-calendar-item='true']")||G({kind:"day",dayKey:Ae,position:{x:Oe.clientX,y:Oe.clientY}})},onDragOver:Oe=>{Oe.preventDefault()},onDrop:Oe=>{Oe.preventDefault();const tt=Oe.dataTransfer.getData("text/forge-event-id")||f;if(tt){const Qt=ye.events.find(Ds=>Ds.id===tt);Qt&&re(Qt,xe),b(null);return}const k=Oe.dataTransfer.getData("text/forge-timebox-id")||x;if(!k)return;const se=ye.timeboxes.find(Qt=>Qt.id===k);if(!se)return;const Le=new Date(se.startsAt),We=new Date(se.endsAt).getTime()-Le.getTime(),gt=new Date(xe);gt.setUTCHours(Le.getUTCHours(),Le.getUTCMinutes(),0,0);const Mt=new Date(gt.getTime()+We);te.mutateAsync({timeboxId:k,startsAt:gt.toISOString(),endsAt:Mt.toISOString()}),p(null)},className:"min-w-0 overflow-hidden rounded-[24px] border border-white/6 bg-white/[0.03] p-3 transition hover:border-white/12 hover:bg-white/[0.045]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] bg-[rgba(10,16,30,0.96)] px-3 py-2 text-sm font-medium text-white",children:[e.jsx("span",{className:"min-w-0 truncate",children:Ai(xe)}),e.jsx("button",{type:"button","aria-label":`Open actions for ${Ai(xe)}`,className:"rounded-full bg-white/[0.06] p-2 text-white/58 transition hover:bg-white/[0.1] hover:text-white",onClick:Oe=>{Oe.stopPropagation(),G({kind:"day",dayKey:Ae,position:{x:Oe.clientX,y:Oe.clientY}})},children:e.jsx(Ci,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-3 grid min-w-0 gap-2",children:[ot.map(Oe=>e.jsxs("div",{"data-calendar-item":"true",className:"min-w-0 overflow-hidden rounded-[18px] px-3 py-2 text-sm text-white",style:{backgroundColor:`${Oe.color}22`,border:`1px solid ${Oe.color}55`},children:[(()=>{const tt=Q2(Oe);return e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"min-w-0 [overflow-wrap:anywhere] font-medium",children:Oe.title}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(I,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:Oe.blockingState}),e.jsx(I,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:Rm(Oe.kind)}),tt.rateApPerHour>0?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:"sm",className:"shrink-0 bg-[var(--primary)]/14 text-[var(--primary)]",children:Kt(tt.rateApPerHour)}),e.jsx(I,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/72",children:kt(tt.totalAp)})]}):e.jsx(I,{size:"sm",className:"shrink-0 bg-emerald-400/12 text-emerald-100",children:"Recovery"})]})]}),e.jsx("button",{type:"button","aria-label":`Open actions for ${Oe.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:k=>{k.stopPropagation(),G({kind:"work-block",templateId:Oe.templateId,position:{x:k.clientX,y:k.clientY}})},children:e.jsx(Ci,{className:"size-4"})})]})})(),e.jsxs("div",{className:"mt-1 text-white/60",children:[new Date(Oe.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(Oe.endAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),e.jsx("div",{className:"mt-2 text-xs text-white/48",children:$m(ye.workBlockTemplates.find(tt=>tt.id===Oe.templateId)??{id:Oe.templateId,title:Oe.title,kind:Oe.kind,color:Oe.color,startsOn:null,endsOn:null,blockingState:Oe.blockingState,createdAt:Oe.createdAt,updatedAt:Oe.updatedAt})})]},Oe.id)),He.map(Oe=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:tt=>{b(Oe.id),tt.dataTransfer.setData("text/forge-event-id",Oe.id)},onClick:tt=>{tt.stopPropagation(),W(Oe),F(null),A(!0)},className:`min-w-0 cursor-move overflow-hidden rounded-[18px] px-3 py-2 text-left text-sm text-white/82 transition ${O.useCalendarColors?"hover:brightness-110":"border border-white/10 bg-white/[0.05] hover:border-white/18 hover:bg-white/[0.08] hover:shadow-[0_12px_32px_rgba(4,9,20,0.22)]"}`,style:O.useCalendarColors?{backgroundColor:`${(Oe.calendarId?me[Oe.calendarId]:null)??Em(`origin:${Oe.originType}`)}1f`,border:`1px solid ${(Oe.calendarId?me[Oe.calendarId]:null)??Em(`origin:${Oe.originType}`)}55`}:void 0,children:[(wn(Oe),e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-2 [overflow-wrap:anywhere] font-medium",children:Oe.title}),e.jsxs("div",{className:"mt-1 text-white/55",children:[new Date(Oe.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(Oe.endAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsx("button",{type:"button","aria-label":`Open quick actions for ${Oe.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:tt=>{tt.stopPropagation(),G({kind:"event",eventId:Oe.id,position:{x:tt.clientX,y:tt.clientY}})},children:e.jsx(Ci,{className:"size-4"})})})]})),e.jsxs("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(I,{size:"sm",className:"max-w-full bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/70",children:v5(Oe,he)}),wn(Oe).rateApPerHour>0?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:"sm",className:"bg-[var(--primary)]/14 px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-[var(--primary)]",children:Kt(wn(Oe).rateApPerHour)}),e.jsx(I,{size:"sm",className:"bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/70",children:kt(wn(Oe).totalAp)})]}):null,Oe.calendarId&&O.useCalendarColors?e.jsx("span",{"aria-hidden":"true",className:"size-2.5 shrink-0 rounded-full",style:{backgroundColor:me[Oe.calendarId]}}):null]}),Oe.place.address||Oe.place.timezone?e.jsxs("div",{className:"mt-2 text-xs leading-5 text-white/50",children:[Oe.place.address||Oe.location,Oe.place.address&&Oe.place.timezone?" · ":"",Oe.place.timezone]}):null,Oe.links.length>0?e.jsx("div",{className:"mt-2 flex min-w-0 flex-wrap gap-1.5",children:Oe.links.slice(0,3).map(tt=>{const k=Vt(tt.entityType);return k?e.jsx(Ue,{kind:k,label:at.get(`${tt.entityType}:${tt.entityId}`)??tt.entityType,compact:!0,gradient:!1},tt.id):e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:tt.entityType},tt.id)})}):null]},Oe.id)),It.map(Oe=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:tt=>{p(Oe.id),tt.dataTransfer.setData("text/forge-timebox-id",Oe.id)},onClick:()=>{B(Oe),E(!0)},className:"min-w-0 cursor-move overflow-hidden rounded-[18px] border border-[rgba(192,193,255,0.18)] bg-[linear-gradient(180deg,rgba(67,72,112,0.34),rgba(43,47,80,0.32))] px-3 py-2 text-left text-sm text-white/82 shadow-[inset_0_0_0_1px_rgba(192,193,255,0.08)] transition hover:border-[rgba(192,193,255,0.32)] hover:bg-[linear-gradient(180deg,rgba(74,79,122,0.4),rgba(48,53,92,0.36))]",children:[(()=>{const tt=Mr(Oe);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex min-w-0 items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-2 font-medium leading-5 text-white",children:Oe.title}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-white/58",children:[e.jsx(Ia,{className:"size-3.5 shrink-0"}),new Date(Oe.startsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(Oe.endsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})}),e.jsxs("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(I,{size:"sm",className:"bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/72",children:Oe.status}),e.jsx(I,{size:"sm",className:"bg-[var(--primary)]/14 px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-[var(--primary)]",children:Kt(tt.rateApPerHour)}),e.jsx(I,{size:"sm",className:"bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/72",children:kt(tt.totalAp)})]})]})})(),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:tt=>{tt.stopPropagation(),B(Oe),E(!0)},className:"rounded-[999px] bg-white/[0.08] px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-white/78 transition hover:bg-white/[0.14]",children:"Edit"}),e.jsx("button",{type:"button",onClick:tt=>{tt.stopPropagation(),t(`/tasks/${Oe.taskId}`)},className:"rounded-[999px] bg-white/[0.08] px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-white/78 transition hover:bg-white/[0.14]",children:"Open task"})]})]},Oe.id)),ot.length===0&&He.length===0&&It.length===0?e.jsx("div",{className:"min-h-[10rem] rounded-[18px] border border-dashed border-white/8 px-3 py-4 text-sm leading-8 text-white/42",children:"Nothing scheduled here yet. Click inside this day to create, block, or paste."}):null]})]},Ae)})})]}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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(ra,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Create event"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Add a native Forge event with linked context."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Create a real calendar event even with no provider connected, then project it remotely whenever you choose."}),e.jsx("div",{className:"mt-4",children:e.jsxs(z,{onClick:()=>{w(null),W(null),F(null),A(!0)},children:[e.jsx(ra,{className:"size-4"}),"Open event guide"]})})]}),e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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(Sn,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Create work block"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Block main activity or protect creative windows."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Open the guided flow to create half-day presets, holidays, or custom recurring work blocks."}),e.jsx("div",{className:"mt-4",children:e.jsxs(z,{onClick:()=>{w(null),P(!0)},children:[e.jsx(Sn,{className:"size-4"}),"Open work-block guide"]})})]}),e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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(Ht,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Plan timebox"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Let Forge recommend valid upcoming slots."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Choose a task, review the suggested windows, and schedule directly into the calendar."}),e.jsx("div",{className:"mt-4",children:e.jsxs(z,{onClick:()=>E(!0),children:[e.jsx(Ht,{className:"size-4"}),"Open planning guide"]})})]}),e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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(Es,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Manage provider settings"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:lt})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Provider connections and setup instructions now live in Settings so the calendar view can stay focused on the week."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(z,{variant:"secondary",onClick:()=>t("/settings/calendar"),children:[e.jsx(Ls,{className:"size-4"}),"Open calendar settings"]}),e.jsxs(z,{variant:"secondary",onClick:()=>t("/settings/calendar?intent=connect"),children:[e.jsx(Es,{className:"size-4"}),"Connect provider"]})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",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/45",children:"This week"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Quick status for the currently visible week."})]}),e.jsxs(z,{variant:"secondary",onClick:()=>void Pe.refetch(),children:[e.jsx(qs,{className:"size-4"}),"Refresh view"]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Provider events"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:ye.events.length})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Work blocks"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:ye.workBlockInstances.length})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Planned timeboxes"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:ge.length})]})]})]}),e.jsxs(ie,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Guided actions"}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>v(!0),className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4 text-left transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:"Adjust task blocking rules"}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:"Guided"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Decide which work blocks, calendar conditions, and event keywords should block or allow a task."})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:"Active templates"}),e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:ye.workBlockTemplates.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[ye.workBlockTemplates.slice(0,4).map(xe=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/74",children:[e.jsx("div",{className:"font-medium text-white",children:xe.title}),e.jsxs("div",{className:"mt-1 text-white/56",children:[Rm(xe.kind)," · ",xe.weekDays.length," day",xe.weekDays.length===1?"":"s"," · ",xe.blockingState]}),e.jsx("div",{className:"mt-1 text-white/46",children:$m(xe)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(z,{variant:"secondary",size:"sm",onClick:()=>{w(xe),P(!0)},children:[e.jsx(ra,{className:"size-3.5"}),"Edit"]}),e.jsxs(z,{variant:"secondary",size:"sm",onClick:()=>void ee.mutateAsync(xe.id),children:[e.jsx($t,{className:"size-3.5"}),"Delete"]})]})]},xe.id)),ye.workBlockTemplates.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No recurring templates yet. Open the work-block guide to create the first one."}):null]})]})]})]})]})]}),e.jsx(x5,{open:M,onOpenChange:xe=>{P(xe),xe||w(null)},pending:D.isPending||_.isPending,template:T,onSubmit:async xe=>{if(T){await _.mutateAsync({templateId:T.id,patch:xe});return}await D.mutateAsync(xe)}}),e.jsx(mb,{open:j,onOpenChange:v,tasks:i.snapshot.tasks,onSave:async({taskId:xe,schedulingRules:Ae,plannedDurationSeconds:He})=>{await Ec(xe,{schedulingRules:Ae,plannedDurationSeconds:He}),await i.refresh(),await L(),await l.invalidateQueries({queryKey:["task-context",xe]})}}),e.jsx(xb,{open:y,onOpenChange:Je,tasks:i.snapshot.tasks,editingTimebox:S,from:ae.from,to:ae.to,onCreateTimebox:async xe=>{await U.mutateAsync(xe)},onUpdateTimebox:async(xe,Ae)=>{await J.mutateAsync({timeboxId:xe,patch:Ae})},onDeleteTimebox:async xe=>{await ve.mutateAsync(xe),qe()}}),e.jsx(l5,{open:N,onOpenChange:xe=>{A(xe),xe||(W(null),F(null))},writableCalendars:C,linkOptions:Re,event:q,seed:R??void 0,onSubmit:async xe=>{if(q){const Ae=q.id;A(!1),W(null),F(null),Ee.mutateAsync({eventId:Ae,patch:xe}).catch(()=>{});return}else{A(!1),W(null),F(null),pe.mutateAsync(xe).catch(()=>{});return}},pending:pe.isPending||Ee.isPending}),e.jsx(o5,{open:Y!==null,onOpenChange:xe=>{xe||K(null)},initialTitle:(Y==null?void 0:Y.title)??"",pending:Ee.isPending,onSubmit:async xe=>{if(!Y)return;const Ae=Y.id;K(null),Ee.mutateAsync({eventId:Ae,patch:{title:xe}}).catch(()=>{})}}),e.jsx(dd,{open:H!==null,title:(H==null?void 0:H.kind)==="event"?((Ge=ye.events.find(xe=>xe.id===H.eventId))==null?void 0:Ge.title)??"Event actions":(H==null?void 0:H.kind)==="work-block"?((Be=ye.workBlockTemplates.find(xe=>xe.id===H.templateId))==null?void 0:Be.title)??"Work block actions":(H==null?void 0:H.kind)==="day"?Ai(Fe.find(xe=>xe.toISOString().slice(0,10)===H.dayKey)??c):"Calendar actions",subtitle:(H==null?void 0:H.kind)==="day"?"Choose what to create or paste into this day.":(H==null?void 0:H.kind)==="work-block"?"Edit or remove this recurring work block.":o?`Clipboard ready: ${o.label}`:"Quick calendar event actions.",items:je,position:(H==null?void 0:H.position)??null,onClose:()=>G(null)})]})}function Bi({entityType:t,entityId:s,view:a,label:i="Open in graph",variant:r="secondary",size:n}){const l=_t();return e.jsxs(z,{variant:r,size:n,onClick:()=>l(H2(t,s,{view:a})),children:[e.jsx($r,{className:"size-4"}),i]})}function Tl(t,s){const a=[],i=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let r=0,n=null,l=0;for(;(n=i.exec(t))!==null;){if(n.index>r&&(a.push(e.jsx(u.Fragment,{children:t.slice(r,n.index)},`${s}-text-${l}`)),l+=1),n[1]&&n[2]){const o=n[2].trim(),d=n[1].startsWith("!"),h=o.indexOf("|"),m=h>=0?o.slice(0,h).trim():o,c=h>=0?o.slice(h+1).trim():m;if(m.toLowerCase().startsWith("forge:")){const[,g,x]=m.split(":"),p=g&&x?li(g,x):null,f=p?ni(p):null;a.push(f?e.jsxs("a",{href:f,className:"inline-flex items-center gap-1 rounded-full bg-amber-400/10 px-2 py-0.5 text-[0.9em] text-amber-100 transition hover:bg-amber-400/18",children:[e.jsx("span",{className:"text-[0.72em] uppercase tracking-[0.14em] text-amber-200/72",children:"Forge"}),e.jsx("span",{children:c})]},`${s}-forge-${l}`):e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-white/[0.06] px-2 py-0.5 text-[0.9em] text-white/66",children:c},`${s}-forge-${l}`))}else{const g=ni(`/wiki/page/${encodeURIComponent(m)}`);a.push(e.jsxs("a",{href:g,className:Z("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[0.9em] transition",d?"bg-cyan-400/14 text-cyan-50 hover:bg-cyan-400/22":"bg-white/[0.06] text-[var(--secondary)] hover:bg-white/[0.1]"),children:[d?e.jsx("span",{className:"text-[0.72em] uppercase tracking-[0.14em] text-cyan-100/68",children:"Embed"}):null,e.jsx("span",{children:c})]},`${s}-wiki-${l}`))}}else if(n[3]&&n[4]){const o=n[4].trim(),d=/^https?:\/\//i.test(o);a.push(e.jsx("a",{href:o,className:"text-[var(--secondary)] underline decoration-[rgba(125,211,252,0.4)] underline-offset-4 transition hover:text-white",target:d?"_blank":void 0,rel:d?"noreferrer":void 0,children:n[3]},`${s}-link-${l}`))}else n[5]?a.push(e.jsx("code",{className:"rounded bg-white/[0.08] px-1.5 py-0.5 text-[0.92em] text-white/90",children:n[5]},`${s}-code-${l}`)):n[6]?a.push(e.jsx("strong",{className:"font-semibold text-white",children:n[6]},`${s}-strong-${l}`)):n[7]&&a.push(e.jsx("em",{className:"italic text-white/88",children:n[7]},`${s}-em-${l}`));r=i.lastIndex,l+=1}return r<t.length&&a.push(e.jsx(u.Fragment,{children:t.slice(r)},`${s}-tail-${l}`)),a}function y5(t){const s=t.replace(/\r/g,"").split(`
|
|
21
21
|
`),a=[];let i=0;for(;i<s.length;){const r=s[i]??"",n=r.trim();if(!n){i+=1;continue}if(n.startsWith("```")){const d=[];for(i+=1;i<s.length&&!(s[i]??"").trim().startsWith("```");)d.push(s[i]??""),i+=1;i+=1,a.push(e.jsx("pre",{className:"overflow-x-auto rounded-[18px] bg-[rgba(6,10,18,0.88)] px-4 py-3 text-xs leading-6 text-white/86",children:e.jsx("code",{children:d.join(`
|
|
22
22
|
`)})},`code-${i}`));continue}const l=r.match(/^(#{1,6})\s+(.*)$/);if(l){const d=l[1].length,h=d===1?"text-xl":d===2?"text-lg":d===3?"text-base":"text-sm";a.push(e.jsx("div",{className:Z("font-semibold text-white",h),children:Tl(l[2],`heading-${i}`)},`heading-${i}`)),i+=1;continue}if(/^>\s?/.test(r)){const d=[];for(;i<s.length&&/^>\s?/.test(s[i]??"");)d.push((s[i]??"").replace(/^>\s?/,"")),i+=1;a.push(e.jsx("blockquote",{className:"border-l-2 border-[var(--secondary)]/50 pl-4 text-sm leading-7 text-white/72",children:Tl(d.join(" "),`quote-${i}`)},`quote-${i}`));continue}if(/^[-*+]\s+/.test(r)||/^\d+\.\s+/.test(r)){const d=/^\d+\.\s+/.test(r),h=[];for(;i<s.length&&(/^[-*+]\s+/.test(s[i]??"")||/^\d+\.\s+/.test(s[i]??""));)h.push((s[i]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"")),i+=1;const m=d?"ol":"ul";a.push(e.jsx(m,{className:Z("space-y-1 pl-5 text-sm leading-7 text-white/74",d?"list-decimal":"list-disc"),children:h.map((c,g)=>e.jsx("li",{children:Tl(c,`list-${i}-${g}`)},`item-${i}-${g}`))},`list-${i}`));continue}const o=[];for(;i<s.length;){const d=s[i]??"";if(!d.trim()||d.trim().startsWith("```")||/^#{1,6}\s+/.test(d)||/^>\s?/.test(d)||/^[-*+]\s+/.test(d)||/^\d+\.\s+/.test(d))break;o.push(d.trim()),i+=1}a.push(e.jsx("p",{className:"text-sm leading-7 text-white/72",children:Tl(o.join(" "),`paragraph-${i}`)},`paragraph-${i}`))}return a}function Fs({markdown:t,className:s}){return e.jsx("div",{className:Z("grid gap-3",s),children:y5(t)})}const Om=[{value:"Working memory",label:"Working memory",description:"What you are actively working on right now."},{value:"Short-term memory",label:"Short-term memory",description:"What just happened and still needs near-term recall."},{value:"Episodic memory",label:"Episodic memory",description:"Long-term recall for what happened or what you did."},{value:"Semantic memory",label:"Semantic memory",description:"Long-term knowledge about what something is."},{value:"Procedural memory",label:"Procedural memory",description:"Long-term know-how and repeatable how-to knowledge."}];function vs(t){const s=new Set;return t.map(a=>a.trim()).filter(Boolean).filter(a=>{const i=a.toLowerCase();return s.has(i)?!1:(s.add(i),!0)})}function Ao(t){const s=t.trim();if(!s)return null;const a=new Date(s);return Number.isNaN(a.getTime())?null:a.toISOString()}function yb(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const a=s.getFullYear(),i=String(s.getMonth()+1).padStart(2,"0"),r=String(s.getDate()).padStart(2,"0"),n=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${a}-${i}-${r}T${n}:${l}`}function jb(t,s){const a=Number(t);if(!Number.isFinite(a)||a<=0)return null;const i=s==="hours"?3600*1e3:1440*60*1e3;return new Date(Date.now()+a*i).toISOString()}function j5(t){const s=new Set(Om.map(r=>r.value.toLowerCase())),a=Om.map(r=>({value:r.value,label:r.label,description:r.description,searchText:`${r.label} ${r.description}`,badge:e.jsx(I,{className:"bg-cyan-400/10 text-cyan-50",children:r.label}),menuBadge:e.jsx(I,{className:"bg-cyan-400/10 text-cyan-50",children:r.label})})),i=vs(t).filter(r=>!s.has(r.toLowerCase())).map(r=>({value:r,label:r,description:"Custom note tag",searchText:r,badge:e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:r}),menuBadge:e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:r})}));return[...a,...i]}function Mi({value:t,onChange:s,availableTags:a=[],placeholder:i="Add a memory tag or create a custom tag"}){const r=j5([...a,...t]);return e.jsx(ht,{options:r,selectedValues:vs(t),onChange:n=>s(vs(n)),placeholder:i,emptyMessage:"No note tags yet.",createLabel:"Add custom tag",onCreate:async n=>{const l=n.trim();return{value:l,label:l,description:"Custom note tag",searchText:l,badge:e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:l}),menuBadge:e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:l})}}})}function N5(t,s,a){return t.links.filter(i=>!(i.entityType===s&&i.entityId===a))}function k5(t,s){return t.entityType===s.entityType&&t.entityId===s.entityId&&(t.anchorKey??null)===(s.anchorKey??null)}function Od(t){const s=new Set;return t.filter(a=>{const i=`${a.entityType}:${a.entityId}:${a.anchorKey??""}`;return s.has(i)?!1:(s.add(i),!0)})}function zm(t,s,a){return Ao(t)??jb(s,a)}function cd({entityType:t,entityId:s,anchorKey:a,includeAnchorlessWhenAnchored:i=!1,title:r="Notes",description:n="Markdown notes linked to this entity stay searchable, editable, and visible alongside the work.",invalidateQueryKeys:l=[],compact:o=!1}){var ne,Re,at,lt,Te,qe,Je,Ze;const d=jt(),h=ct(),[m,c]=u.useState(""),[g,x]=u.useState(!1),[p,f]=u.useState(""),[b,M]=u.useState(!1),[P,T]=u.useState({entityType:"goal",entityId:""}),[w,j]=u.useState([]),[v,y]=u.useState([]),[E,S]=u.useState(""),[B,N]=u.useState(""),[A,q]=u.useState("days"),[W,Y]=u.useState(null),[K,O]=u.useState(""),[R,F]=u.useState(!1),[H,G]=u.useState([]),[$,Q]=u.useState({entityType:"goal",entityId:""}),[X,ae]=u.useState([]),[Pe,Ne]=u.useState(""),[fe,V]=u.useState(""),[Ce,L]=u.useState("days"),D=Pn(a),_=m1(t,a),ee=Me({queryKey:["notes",t,s],queryFn:()=>Ng({linkedEntityType:t,linkedEntityId:s,limit:100})}),U=Me({queryKey:["forge-psyche-values"],queryFn:Ws}),te=Me({queryKey:["forge-psyche-patterns"],queryFn:La}),J=Me({queryKey:["forge-psyche-behaviors"],queryFn:Hs}),ve=Me({queryKey:["forge-psyche-beliefs"],queryFn:va}),pe=Me({queryKey:["forge-psyche-modes"],queryFn:Da}),Ee=Me({queryKey:["forge-psyche-reports"],queryFn:ui}),ce=u.useMemo(()=>{var re,oe,je,we,Ie,Se,Ge;return{goal:d.snapshot.goals.map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),project:d.snapshot.dashboard.projects.map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),task:d.snapshot.tasks.map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),strategy:d.snapshot.strategies.map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),habit:d.snapshot.habits.map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),tag:d.snapshot.tags.map(Be=>({id:Be.id,label:Dt(Be.name,Be.user)})),note:(((re=ee.data)==null?void 0:re.notes)??[]).map(Be=>({id:Be.id,label:Be.contentPlain||Be.contentMarkdown})),insight:[],psyche_value:(((oe=U.data)==null?void 0:oe.values)??[]).map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),behavior_pattern:(((je=te.data)==null?void 0:je.patterns)??[]).map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),behavior:(((we=J.data)==null?void 0:we.behaviors)??[]).map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),belief_entry:(((Ie=ve.data)==null?void 0:Ie.beliefs)??[]).map(Be=>({id:Be.id,label:Dt(Be.statement,Be.user)})),mode_profile:(((Se=pe.data)==null?void 0:Se.modes)??[]).map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),mode_guide_session:[],event_type:[],emotion_definition:[],trigger_report:(((Ge=Ee.data)==null?void 0:Ge.reports)??[]).map(Be=>({id:Be.id,label:Dt(Be.title,Be.user)})),calendar_event:[],work_block_template:[],task_timebox:[],preference_catalog:[],preference_catalog_item:[],preference_context:[],preference_item:[],questionnaire_instrument:[],sleep_session:[],workout_session:[]}},[(ne=J.data)==null?void 0:ne.behaviors,(Re=ve.data)==null?void 0:Re.beliefs,(at=pe.data)==null?void 0:at.modes,(lt=ee.data)==null?void 0:lt.notes,(Te=te.data)==null?void 0:Te.patterns,(qe=Ee.data)==null?void 0:qe.reports,d.snapshot.dashboard.projects,d.snapshot.goals,d.snapshot.habits,d.snapshot.strategies,d.snapshot.tags,d.snapshot.tasks,(Je=U.data)==null?void 0:Je.values]),ue=async()=>{await Promise.all([h.invalidateQueries({queryKey:["notes",t,s]}),h.invalidateQueries({queryKey:["forge-snapshot"]}),...l.map(re=>h.invalidateQueries({queryKey:re}))])},Fe=De({mutationFn:async re=>nl({contentMarkdown:re,tags:vs(v),destroyAt:zm(E,B,A),links:Od([{entityType:t,entityId:s,anchorKey:a??null},...w])}),onSuccess:async()=>{f(""),M(!1),j([]),T({entityType:"goal",entityId:""}),y([]),S(""),N(""),q("days"),await ue()}}),ye=De({mutationFn:async({noteId:re,contentMarkdown:oe,links:je,tags:we,destroyAt:Ie})=>qn(re,{contentMarkdown:oe,links:je,tags:we,destroyAt:Ie}),onSuccess:async()=>{Y(null),O(""),F(!1),G([]),Q({entityType:"goal",entityId:""}),ae([]),Ne(""),V(""),L("days"),await ue()}}),he=De({mutationFn:async re=>Au(re),onSuccess:ue}),me=u.useMemo(()=>{var oe;return(((oe=ee.data)==null?void 0:oe.notes)??[]).filter(je=>a===void 0?!0:je.links.some(we=>we.entityType===t&&we.entityId===s&&((we.anchorKey??null)===a||i&&(we.anchorKey??null)===null))).filter(je=>{const we=m.trim().toLowerCase();return we?`${je.contentPlain} ${je.author??""} ${(je.tags??[]).join(" ")}`.toLowerCase().includes(we):!0})},[a,s,t,i,(Ze=ee.data)==null?void 0:Ze.notes,m]),Ke=(re,oe,je)=>{const we=re.entityId.trim();return we?(oe(Od([...je,{entityType:re.entityType,entityId:we,anchorKey:null}])),!0):!1},ge=re=>{var je,we;const oe=(je=ce[re.entityType])==null?void 0:je.find(Ie=>Ie.id===re.entityId);return(we=oe==null?void 0:oe.label)!=null&&we.trim()?oe.label.trim():`Deleted ${ka(re.entityType)}`},C=(re,oe,je,we,Ie)=>e.jsxs("div",{className:"rounded-[20px] bg-white/[0.03] p-4",children:[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/38",children:"Linked entities"}),e.jsxs(I,{className:"bg-white/[0.08] text-white/68",children:[re.length," linked"]})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:re.map(Se=>{const Ge=re.length>1;return e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.08] px-3 py-2 text-sm text-white/72",children:[e.jsxs("span",{children:[ka(Se.entityType)," · ",ge(Se)]}),Se.anchorKey?e.jsx("span",{className:"rounded-full bg-white/[0.08] px-2 py-0.5 text-[11px] text-white/54",children:Pn(Se.anchorKey)}):null,e.jsx("button",{type:"button",disabled:!Ge,className:"text-white/44 transition hover:text-white disabled:cursor-not-allowed disabled:opacity-30",onClick:()=>oe(re.filter(Be=>!k5(Be,Se))),"aria-label":`Remove ${ka(Se.entityType)} link to ${ge(Se)}`,children:e.jsx($t,{className:"size-3.5"})})]},`${Ie}-${Se.entityType}-${Se.entityId}-${Se.anchorKey??""}`)})}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-[minmax(0,11rem)_minmax(0,1fr)_auto]",children:[e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:je.entityType,onChange:Se=>we({...je,entityType:Se.target.value,entityId:""}),children:["goal","project","task","strategy","habit","tag","note","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","mode_guide_session","event_type","emotion_definition","trigger_report"].map(Se=>e.jsx("option",{value:Se,children:ka(Se)},Se))}),e.jsxs("select",{className:"min-w-0 rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:je.entityId,onChange:Se=>we({...je,entityId:Se.target.value}),children:[e.jsx("option",{value:"",children:(ce[je.entityType]??[]).length>0?"Choose linked item":"No linked items available"}),(ce[je.entityType]??[]).map(Se=>e.jsx("option",{value:Se.id,children:Se.label},Se.id))]}),e.jsx(z,{variant:"secondary",disabled:!je.entityId,onClick:()=>{Ke(je,oe,re)&&we({...je,entityId:""})},children:"Add link"})]})]});return e.jsx(ie,{id:"notes",className:o?"min-w-0 overflow-hidden p-0":"min-w-0 overflow-hidden",children:e.jsxs("div",{className:o?"p-4":void 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.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:r}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:n}),D?e.jsxs("div",{className:"mt-3 inline-flex items-center gap-2 rounded-full bg-white/[0.05] px-3 py-2 text-xs text-white/64",children:[e.jsxs("span",{children:["Pinned to ",D]}),_?e.jsx(yt,{content:_,label:`Explain ${D}`}):null]}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:Xg(me.length)}),g?null:e.jsxs(z,{type:"button",size:"sm",onClick:()=>x(!0),children:[e.jsx(os,{className:"size-4"}),"Add note"]})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 rounded-[22px] border border-white/8 bg-white/[0.04] px-3 py-3",children:[e.jsx(zt,{className:"size-4 text-white/34"}),e.jsx(ke,{value:m,onChange:re=>c(re.target.value),placeholder:"Search notes by content, author, or note tag",className:"border-0 bg-transparent px-0 py-0"})]}),g?e.jsxs("div",{className:"mt-4 rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/70",children:[e.jsx(os,{className:"size-4 text-[var(--secondary)]"}),"Add note"]}),e.jsxs(z,{type:"button",variant:"secondary",size:"sm",className:"gap-2",onClick:()=>M(re=>!re),children:[e.jsx(kh,{className:"size-4"}),b?"Back to editor":"Preview"]})]}),e.jsx("div",{className:"mt-3",children:b?e.jsxs("div",{className:"rounded-[20px] bg-[rgba(9,14,25,0.78)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Preview"}),e.jsx("div",{className:"mt-3",children:p.trim()?e.jsx(Fs,{markdown:p}):e.jsx("div",{className:"text-sm leading-6 text-white/42",children:"Markdown preview appears here once you have note content."})})]}):e.jsx(Ve,{value:p,onChange:re=>f(re.target.value),placeholder:"Write in Markdown. Summaries, blockers, what changed, and why all work well here.",className:"min-h-[12rem]"})}),e.jsx("div",{className:"mt-3",children:C(Od([{entityType:t,entityId:s,anchorKey:a??null},...w]),re=>j(re.filter(oe=>!(oe.entityType===t&&oe.entityId===s&&(oe.anchorKey??null)===(a??null)))),P,T,"composer-note-links")}),e.jsxs("div",{className:"mt-3 grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(Mi,{value:v,onChange:y}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Ephemeral auto-destroy"}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/46",children:"Set an exact destroy time or a relative delay. Leaving both blank keeps the note durable."})]}),e.jsx(ke,{type:"datetime-local",value:E,onChange:re=>S(re.target.value)}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ke,{type:"number",min:"1",value:B,onChange:re=>N(re.target.value),placeholder:"Destroy after"}),e.jsxs("select",{className:"rounded-[14px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:A,onChange:re=>q(re.target.value),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap justify-end gap-2",children:[e.jsx(z,{type:"button",variant:"secondary",onClick:()=>{x(!1),M(!1),f(""),j([]),T({entityType:"goal",entityId:""}),y([]),S(""),N(""),q("days")},children:"Cancel"}),e.jsx(z,{pending:Fe.isPending,pendingLabel:"Saving",disabled:p.trim().length===0,onClick:async()=>{await Fe.mutateAsync(p.trim()),x(!1)},children:"Save note"})]})]}):null,e.jsxs("div",{className:"mt-4 grid gap-3",children:[ee.isLoading?e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/56",children:"Loading notes…"}):null,!ee.isLoading&&me.length===0?e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/56",children:"No notes are linked here yet."}):null,me.map(re=>{const oe=W===re.id,je=N5(re,t,s);return e.jsxs("article",{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.jsxs("div",{className:"text-xs uppercase tracking-[0.16em] text-white/38",children:[(re.author??"Unknown author").toString()," •"," ",new Date(re.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[je.map(we=>e.jsxs(I,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[ka(we.entityType)," ·"," ",ge(we),we.anchorKey?` · ${Pn(we.anchorKey)}`:""]},`${re.id}-${we.entityType}-${we.entityId}-${we.anchorKey??""}`)),(re.tags??[]).map(we=>e.jsx(I,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:we},`${re.id}-tag-${we}`)),re.destroyAt?e.jsxs(I,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(re.destroyAt).toLocaleString()]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"inline-flex size-9 items-center justify-center rounded-full bg-white/[0.06] text-white/60 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>{Y(re.id),O(re.contentMarkdown),F(!1),G(re.links),Q({entityType:"goal",entityId:""}),ae(vs(re.tags??[])),Ne(yb(re.destroyAt??null)),V(""),L("days")},children:e.jsx(Pa,{className:"size-4"})}),e.jsx("button",{type:"button",className:"inline-flex size-9 items-center justify-center rounded-full bg-rose-500/10 text-rose-200 transition hover:bg-rose-500/16",onClick:()=>{he.mutateAsync(re.id)},children:e.jsx($t,{className:"size-4"})})]})]}),oe?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"flex flex-wrap items-center justify-end gap-2",children:e.jsxs(z,{type:"button",variant:"secondary",size:"sm",className:"gap-2",onClick:()=>F(we=>!we),children:[e.jsx(kh,{className:"size-4"}),R?"Back to editor":"Preview"]})}),e.jsx("div",{className:"mt-3",children:R?e.jsxs("div",{className:"rounded-[20px] bg-[rgba(9,14,25,0.78)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Preview"}),e.jsx("div",{className:"mt-3",children:K.trim()?e.jsx(Fs,{markdown:K}):e.jsx("div",{className:"text-sm text-white/42",children:"No content yet."})})]}):e.jsx(Ve,{value:K,onChange:we=>O(we.target.value),className:"min-h-[12rem]"})}),e.jsxs("div",{className:"mt-3 grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(Mi,{value:X,onChange:ae}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Ephemeral auto-destroy"}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/46",children:"Set an exact destroy time or a relative delay. Leaving both blank keeps the note durable."})]}),e.jsx(ke,{type:"datetime-local",value:Pe,onChange:we=>Ne(we.target.value)}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ke,{type:"number",min:"1",value:fe,onChange:we=>V(we.target.value),placeholder:"Destroy after"}),e.jsxs("select",{className:"rounded-[14px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:Ce,onChange:we=>L(we.target.value),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsx("div",{className:"mt-3",children:C(H,G,$,Q,`edit-note-links-${re.id}`)}),e.jsxs("div",{className:"mt-3 flex flex-wrap justify-end gap-2",children:[e.jsx(z,{variant:"secondary",onClick:()=>{Y(null),F(!1),ae([]),Ne(""),V(""),L("days")},children:"Cancel"}),e.jsx(z,{pending:ye.isPending,pendingLabel:"Saving",disabled:K.trim().length===0||H.length===0,onClick:async()=>{await ye.mutateAsync({noteId:re.id,contentMarkdown:K.trim(),links:H,tags:vs(X),destroyAt:zm(Pe,fe,Ce)})},children:"Save changes"})]})]}):e.jsx("div",{className:"mt-4",children:e.jsx(Fs,{markdown:re.contentMarkdown})})]},re.id)})]})]})})}function ud({userId:t,domain:s,entityType:a,entityId:i,label:r,description:n,tags:l,size:o="sm"}){const d=_t(),h=ct(),m=De({mutationFn:async()=>{if(!t)throw new Error("Select a single owner before sending entities to Preferences.");return Pc({userId:t,domain:s,entityType:a,entityId:i,label:r,description:n,tags:l})},onSuccess:async({item:c})=>{await h.invalidateQueries({queryKey:["forge-preferences"]}),d(`/preferences?userId=${encodeURIComponent(t??"")}&domain=${encodeURIComponent(s)}&focusItem=${encodeURIComponent(c.id)}`)}});return e.jsxs(z,{variant:"secondary",size:o,disabled:!t,pending:m.isPending,pendingLabel:"Sending to Preferences",onClick:()=>void m.mutateAsync(),title:t?"Add this entity to the Preferences compare queue.":"Select a single user scope before sending entities to Preferences.",children:[e.jsx(uu,{className:"size-4"}),"Send to Preferences"]})}const Km={active:"Active",paused:"Suspended",completed:"Finished",all:"All"};function ch({value:t,counts:s,onChange:a,className:i}){return e.jsx("div",{className:Z("flex flex-wrap gap-2",i),children:Object.keys(Km).map(r=>{const n=r===t;return e.jsxs("button",{type:"button",onClick:()=>a(r),className:Z("inline-flex min-h-10 items-center gap-2 rounded-full border px-4 py-2 text-sm transition",n?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.16)] text-white shadow-[0_16px_36px_rgba(8,12,24,0.18)]":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx("span",{children:Km[r]}),e.jsx("span",{className:Z("rounded-full px-2 py-0.5 text-[11px]",n?"bg-white/12 text-white/88":"bg-white/8 text-white/54"),children:s[r]})]},r)})})}function da({value:t,className:s,tone:a="primary"}){const i=`${Math.max(4,Math.min(100,t))}%`,r=a==="secondary"?"from-[var(--secondary)] to-[rgba(78,222,163,0.45)]":a==="tertiary"?"from-[var(--tertiary)] to-[rgba(255,185,95,0.45)]":"from-[var(--primary)] to-[rgba(192,193,255,0.45)]";return e.jsx("div",{className:Z("h-1.5 rounded-full bg-white/[0.08]",s),children:e.jsx("div",{className:Z("h-full rounded-full bg-gradient-to-r",r),style:{width:i}})})}function Nb(t){const s=`${t.title} ${t.description} ${t.source??""}`.toLowerCase();return s.includes("playwright")||s.includes("operator console")||s.includes("retroactive work logging")}function hd(t){return Nb(t)?"Work log added":t.title}function md(t){return Nb(t)?"This entry was added later so the work history stays complete and accurate.":t.description}function uh(t){return{active:t.filter(s=>s.status==="active").length,paused:t.filter(s=>s.status==="paused").length,completed:t.filter(s=>s.status==="completed").length,all:t.length}}function hh(t,s){return s==="all"?t:t.filter(a=>a.status===s)}function S5(){const{t}=Rt(),s=jt(),a=Us(),i=_t(),r=ct(),[n,l]=u.useState(!1),[o,d]=u.useState(!1),[h,m]=u.useState("active"),c=fs(s.selectedUserIds),[g,x]=u.useState(null),p=De({mutationFn:()=>Ok(a.goalId),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board"]}),r.invalidateQueries({queryKey:["task-context"]})]),i("/goals")}}),f=s.snapshot.dashboard.goals.find(N=>N.id===a.goalId)??null,b=u.useMemo(()=>s.snapshot.dashboard.projects.filter(N=>N.goalId===a.goalId),[a.goalId,s.snapshot.dashboard.projects]),M=u.useMemo(()=>uh(b),[b]),P=u.useMemo(()=>hh(b,h),[b,h]),T=new Set(b.map(N=>N.id)),w=new Set(s.snapshot.tasks.filter(N=>T.has(N.projectId??"")).map(N=>N.id)),j=s.snapshot.activity.filter(N=>N.entityId===a.goalId||T.has(N.entityId)||w.has(N.entityId)||N.entityType==="task_run"&&typeof N.metadata.taskId=="string"&&w.has(N.metadata.taskId));if(!f)return e.jsx(Bt,{eyebrow:t("common.goalDetail.eyebrow"),title:t("common.goalDetail.missingTitle"),description:t("common.goalDetail.missingDescription"),action:e.jsx(Xe,{to:"/goals",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center whitespace-nowrap rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium text-slate-950 transition hover:opacity-90",children:t("common.goalDetail.backToGoals")})});const v=P.find(N=>N.nextTaskTitle)??P[0]??null,y=s.snapshot.overview.neglectedGoals.find(N=>N.goalId===f.id)??null,E=j[0]??null,S=async N=>{x(N);try{await s.patchProject(N,{status:"active"})}finally{x(null)}},B=async()=>{window.confirm(t("common.goalDetail.deleteGoalConfirm",{title:f.title}))&&await p.mutateAsync()};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(rt,{entityKind:"goal",title:e.jsx(wt,{kind:"goal",label:f.title,variant:"heading",size:"lg"}),titleText:f.title,description:f.description?e.jsx(Fs,{markdown:f.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):"No strategic description yet.",badge:t(P.length===1?"common.goalDetail.heroBadgeOne":"common.goalDetail.heroBadgeOther",{count:P.length}),actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ud,{userId:c,domain:"projects",entityType:"goal",entityId:f.id,label:f.title,description:f.description}),e.jsx(Bi,{entityType:"goal",entityId:f.id})]})}),f.user?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/62",children:[e.jsx("span",{className:"text-white/42",children:"Owned by"}),e.jsx(nt,{user:f.user})]}):null,e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(z,{onClick:()=>l(!0),children:t("common.goalDetail.edit")}),e.jsx(z,{variant:"secondary",onClick:()=>d(!0),children:t("common.goalDetail.addProject")}),e.jsx(z,{variant:"ghost",className:"text-rose-200 hover:bg-rose-500/10",pending:p.isPending,pendingLabel:t("common.goalDetail.deleting"),onClick:()=>void B(),children:t("common.goalDetail.deleteGoal")})]}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsxs(ie,{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.goalDetail.sectionProjects")}),e.jsx(ch,{value:h,counts:M,onChange:m,className:"justify-end"})]}),P.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:h==="active"?t("common.goalDetail.noProjects"):"No projects match this lifecycle filter yet. Switch filters or restart one to make it active again."}):e.jsx("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:P.map(N=>e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-5 transition hover:bg-white/[0.08]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ue,{kind:"project",compact:!0,gradient:!1}),N.user?e.jsx(nt,{user:N.user,compact:!0}):null]}),e.jsx(I,{children:N.status})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Xe,{to:`/projects/${N.id}`,className:"transition hover:opacity-90",children:e.jsx(wt,{kind:"project",label:N.title,variant:"heading",size:"lg"})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:N.description}),e.jsx("div",{className:"mt-4",children:e.jsx(da,{value:N.progress})}),e.jsx("div",{className:"mt-4 text-[11px] uppercase tracking-[0.16em] text-white/40",children:N.nextTaskTitle?t("common.goalDetail.nextMove",{value:N.nextTaskTitle}):t("common.goalDetail.addNextTask")}),e.jsxs("div",{className:"mt-4 flex flex-wrap justify-between gap-3",children:[e.jsx(Xe,{to:`/projects/${N.id}`,children:e.jsx(z,{variant:"ghost",children:"Open project"})}),h!=="active"&&N.status!=="active"?e.jsx(z,{variant:"secondary",size:"sm",pending:g===N.id,pendingLabel:"Restarting…",onClick:()=>void S(N.id),children:"Restart"}):null]})]},N.id))})]}),e.jsx("div",{className:"grid min-w-0 gap-5",children:e.jsxs(ie,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.goalDetail.sectionHealth")}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[e.jsx(Ue,{kind:"goal",compact:!0,gradient:!1}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:t("common.goalDetail.progressTitle",{progress:f.progress,count:f.completedTasks})}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:t("common.goalDetail.progressDetail",{xp:f.earnedPoints})}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:t(P.length===1?"common.goalDetail.heroBadgeOne":"common.goalDetail.heroBadgeOther",{count:P.length})})]}),e.jsxs("div",{className:"mt-4 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:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldProgress")}),e.jsxs("div",{className:"mt-2 font-display text-xl text-white",children:[f.progress,"%"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldCompletedTasks")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:f.completedTasks})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldXpBanked")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:f.earnedPoints})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[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-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t("common.goalDetail.signalNext")}),v?e.jsx(Ue,{kind:"project",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(v==null?void 0:v.title)??t("common.goalDetail.noProject")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:v!=null&&v.nextTaskTitle?t("common.goalDetail.nextMove",{value:v.nextTaskTitle}):(v==null?void 0:v.description)||t("common.goalDetail.noProjectDetail")})]}),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:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t("common.goalDetail.signalRisk")}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(y==null?void 0:y.title)??t("common.goalDetail.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(y==null?void 0:y.summary)||t("common.goalDetail.noRiskDetail")})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t("common.goalDetail.signalEvidence")}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(E==null?void 0:E.title)??t("common.goalDetail.noEvidence")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(E==null?void 0:E.description)||t("common.goalDetail.noEvidenceDetail")})]})]})]})]})})]}),e.jsx(cd,{entityType:"goal",entityId:f.id,title:"Goal notes",description:"Use notes to capture strategy changes, meaning shifts, and progress context that belongs at the goal level."}),e.jsxs(ie,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.goalDetail.sectionEvidence")}),j.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:t("common.goalDetail.noEvidenceLogged")}):e.jsx("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:j.slice(0,6).map(N=>e.jsxs(Xe,{to:Aa(N)??`/activity?eventId=${N.id}`,className:"rounded-[18px] bg-white/[0.04] p-4 transition hover:bg-white/[0.08]",children:[e.jsx("div",{className:"font-medium text-white",children:hd(N)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:md(N)})]},N.id))})]}),e.jsx(Ou,{open:n,editingGoal:f,tags:s.snapshot.tags,users:s.snapshot.users,defaultUserId:f.userId??c,onOpenChange:l,onSubmit:async(N,A)=>{A&&await s.patchGoal(A,N)}}),e.jsx(rd,{open:o,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:null,initialGoalId:f.id,defaultUserId:f.userId??c,onOpenChange:d,onSubmit:async N=>{await s.createProject(N)}})]})}function _s({entityType:t,entityId:s,count:a,compact:i=!1,className:r=""}){const n=_t(),l=ll(t,s);return l?e.jsxs("span",{role:"link",tabIndex:0,className:`inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] text-white/72 transition hover:bg-white/[0.09] hover:text-white ${i?"min-h-5 gap-1 px-2 py-0.5 text-[10px]":"min-h-10 gap-2 px-3 py-2 text-xs"} ${r}`,onClick:o=>{o.stopPropagation(),n(l)},onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),o.stopPropagation(),n(l))},children:[e.jsx(ai,{className:i?"size-3":"size-3.5"}),Xg(a)]}):null}function C5({goals:t,tags:s,users:a,defaultUserId:i=null,pending:r=!1,onCreate:n,onUpdate:l}){const[o,d]=u.useState(!1),[h,m]=u.useState(null),c=t.find(g=>g.id===h)??null;return e.jsxs(e.Fragment,{children:[e.jsxs(ie,{children:[e.jsxs("div",{className:"flex 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:"Goal arcs"}),e.jsx("h3",{className:"mt-2 font-display text-3xl text-white",children:"Strategic arcs before tickets"}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/60",children:"This is the long-horizon map. Each arc shows why it matters, how much ground has been covered, and which project should move next."})]}),e.jsx(z,{onClick:()=>{m(null),d(!0)},children:"Create goal"})]}),e.jsxs("div",{className:"mt-5 grid gap-3 xl:grid-cols-2",children:[t.length===0?e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] p-5 text-sm leading-7 text-white/60 xl:col-span-2",children:"Start with a life goal. Once the destination is clear, you can attach projects and then fill those projects with tasks."}):null,t.map(g=>{const x=`${Math.max(6,Math.min(100,g.progress))}%`;return e.jsxs(Xe,{to:`/goals/${g.id}`,className:"rounded-[24px] border border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.03))] p-4 transition hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.09),rgba(255,255,255,0.04))]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(Ue,{kind:"goal",compact:!0,gradient:!1}),e.jsx("div",{className:"mt-2",children:e.jsx(wt,{kind:"goal",label:g.title,variant:"heading",size:"lg",showKind:!1,lines:2})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:g.description||"No strategic note attached yet."})]}),e.jsx("button",{className:"rounded-full bg-white/6 p-2 text-white/60 transition hover:bg-white/10 hover:text-white",type:"button",onClick:p=>{p.preventDefault(),p.stopPropagation(),m(g.id),d(!0)},children:e.jsx(ra,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:g.horizon}),e.jsx(I,{className:g.status==="active"?"text-emerald-300":g.status==="paused"?"text-amber-300":"text-[var(--tertiary)]",children:g.status}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[g.earnedPoints," / ",g.targetPoints," xp"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[g.totalTasks," tasks"]})]}),e.jsx("div",{className:"mt-4 h-1.5 rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,var(--primary)_0%,var(--secondary)_100%)]",style:{width:x}})}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:g.tags.map(p=>e.jsx(I,{className:"bg-white/[0.06] text-white/58",children:p.name},p.id))}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",children:g.momentumLabel}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-2",style:{color:g.themeColor},children:["Open arc",e.jsx(la,{className:"size-3.5"})]})]})]},g.id)})]})]}),e.jsx(Ou,{open:o,pending:r,editingGoal:c,tags:s,users:a,defaultUserId:i,onOpenChange:g=>{d(g),g||m(null)},onSubmit:async(g,x)=>{if(x){await l(x,g);return}await n(g)}})]})}function I5({eyebrow:t,title:s,description:a,meta:i,actions:r,className:n}){return e.jsxs("div",{className:Z("flex flex-wrap items-start justify-between gap-3",n),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[t?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}):null,e.jsxs("div",{className:Z("min-w-0",t&&"mt-2"),children:[e.jsx("div",{className:"min-w-0 text-lg text-white",children:s}),a?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:a}):null]})]}),i||r?e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:[i,r]}):null]})}function kb({children:t,className:s}){return e.jsx("div",{className:Z("flex flex-wrap gap-2",s),children:t})}function T5(){const t=jt(),[s,a]=u.useState("active"),[i,r]=u.useState(null),n=t.snapshot.dashboard.goals.length>0,l=uh(t.snapshot.dashboard.projects),o=hh(t.snapshot.dashboard.projects,s),d=fs(t.selectedUserIds),h=new Map(t.snapshot.dashboard.goals.map(c=>[c.id,o.filter(g=>g.goalId===c.id)])),m=async c=>{r(c);try{await t.patchProject(c,{status:"active"})}finally{r(null)}};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(rt,{entityKind:"goal",title:e.jsx(wt,{kind:"goal",label:"Life Goals",variant:"heading",size:"lg"}),titleText:"Life Goals",description:"Life goals are the destinations you care about over the long run. Each one can hold several projects, and those projects turn direction into real work.",badge:`${t.snapshot.dashboard.goals.length} active goals`,actions:n?e.jsxs("div",{className:"inline-flex min-h-10 items-center rounded-full border border-white/8 bg-white/[0.04] px-4 py-2 text-sm whitespace-nowrap text-white/68",children:[t.snapshot.dashboard.projects.length," live project",t.snapshot.dashboard.projects.length===1?"":"s"," ","attached"]}):null}),e.jsx(C5,{goals:t.snapshot.dashboard.goals,tags:t.snapshot.tags,users:t.snapshot.users,defaultUserId:d,onCreate:t.createGoal,onUpdate:t.patchGoal}),n?e.jsx(ch,{value:s,counts:l,onChange:a}):null,n?null:e.jsx(Bt,{eyebrow:"Life goals",title:"No life goals yet",description:"Define the first long-horizon direction above so Forge can attach projects, tasks, momentum, and evidence to something meaningful."}),n?e.jsx("div",{className:"grid gap-4",children:t.snapshot.dashboard.goals.map(c=>{const g=h.get(c.id)??[],x=Qs(t.snapshot.dashboard.notesSummaryByEntity,"goal",c.id);return e.jsx(Xe,{to:`/goals/${c.id}`,className:"min-w-0 overflow-hidden rounded-[28px] border border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.03))] p-4 transition hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.04))] sm:p-5",children:e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)] xl:gap-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(kb,{children:[c.tags.slice(0,3).map(p=>e.jsx(I,{className:"bg-white/[0.08]",style:{color:p.color},children:p.name},p.id)),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:c.horizon}),e.jsx(nt,{user:c.user,compact:!0})]}),e.jsx("div",{className:"mt-4",children:e.jsx(wt,{kind:"goal",label:c.title,variant:"heading",size:"xl",lines:2})}),e.jsx("p",{className:"mt-3 max-w-2xl text-sm leading-7 text-white/58",children:c.description}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Progress"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[c.progress,"%"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Tasks done"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[c.completedTasks,"/",Math.max(c.totalTasks,1)]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"XP banked"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:c.earnedPoints})]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(da,{value:c.progress})}),e.jsx("div",{className:"mt-4",children:e.jsx(_s,{entityType:"goal",entityId:c.id,count:x.count})})]}),e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx(I5,{title:"Projects carrying this direction",meta:e.jsx("div",{className:"shrink-0 text-sm text-white/48",children:g.length}),className:"gap-2"}),g.length===0?e.jsx("div",{className:"mt-4 text-sm leading-6 text-white/56",children:s==="active"?"No active project is attached yet. Create one so this direction starts producing visible work.":"No projects in this lifecycle view are attached yet. Switch filters or restart one to bring it back into active motion."}):e.jsx("div",{className:"mt-4 grid gap-3",children:g.slice(0,3).map(p=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.05] px-4 py-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(Ue,{kind:"project",compact:!0,gradient:!1}),e.jsx(wt,{kind:"project",label:p.title,className:"min-w-0",showIcon:!1,lines:2})]}),e.jsx(I,{className:"shrink-0",children:p.status})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:p.description}),e.jsxs("div",{className:"mt-3 text-sm text-white/42",children:["Next move:"," ",p.nextTaskTitle??"Define the first attached task"]}),s!=="active"&&p.status!=="active"?e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx(z,{variant:"secondary",size:"sm",pending:i===p.id,pendingLabel:"Restarting…",onClick:f=>{f.preventDefault(),f.stopPropagation(),m(p.id)},children:"Restart"})}):null]},p.id))})]})]})},c.id)})}):e.jsx(ie,{children:e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:"Goal cards will appear here once the first long-horizon direction is created."})})]})}function P5(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Br(t){u.useEffect(()=>{if(!t||typeof document>"u")return;const s=window.requestAnimationFrame(()=>{const a=document.querySelector(`[data-psyche-focus-id="${P5(t)}"]`);a&&a.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})});return()=>window.cancelAnimationFrame(s)},[t])}function Ur(t){return t?"border-[rgba(125,211,252,0.28)] bg-[linear-gradient(180deg,rgba(125,211,252,0.14),rgba(255,255,255,0.06))] shadow-[0_24px_60px_rgba(56,189,248,0.14)]":""}const zd={title:"",description:"",status:"active",userId:null,polarity:"positive",frequency:"daily",targetCount:1,weekDays:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],linkedValueIds:[],linkedPatternIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],linkedReportIds:[],linkedBehaviorId:"",rewardXp:12,penaltyXp:8,generatedHealthEventTemplate:{enabled:!1,workoutType:"workout",title:"",durationMinutes:45,xpReward:0,tags:[],links:[],notesTemplate:""}},A5=[{value:1,label:"Mon"},{value:2,label:"Tue"},{value:3,label:"Wed"},{value:4,label:"Thu"},{value:5,label:"Fri"},{value:6,label:"Sat"},{value:0,label:"Sun"}];function M5(t){return{title:t.title,description:t.description,status:t.status,userId:t.userId??null,polarity:t.polarity,frequency:t.frequency,targetCount:t.targetCount,weekDays:t.weekDays,linkedGoalIds:t.linkedGoalIds,linkedProjectIds:t.linkedProjectIds,linkedTaskIds:t.linkedTaskIds,linkedValueIds:t.linkedValueIds,linkedPatternIds:t.linkedPatternIds,linkedBehaviorIds:t.linkedBehaviorIds,linkedBeliefIds:t.linkedBeliefIds,linkedModeIds:t.linkedModeIds,linkedReportIds:t.linkedReportIds,linkedBehaviorId:t.linkedBehaviorId??"",rewardXp:t.rewardXp,penaltyXp:t.penaltyXp,generatedHealthEventTemplate:t.generatedHealthEventTemplate}}function E5({open:t,pending:s=!1,editingHabit:a,values:i,patterns:r,behaviors:n,beliefs:l,modes:o,reports:d,goals:h,projects:m,tasks:c,users:g,defaultUserId:x=null,onOpenChange:p,onSubmit:f}){const[b,M]=u.useState(zd),[P,T]=u.useState(null),[w,j]=u.useState({});u.useEffect(()=>{t&&(M(a?M5(a):{...zd,userId:x}),T(null),j({}))},[x,a,t]);const v=g.find(N=>N.id===x)??null,y=u.useMemo(()=>n.slice().sort((N,A)=>N.title.localeCompare(A.title)),[n]),E=N=>({linkedBehaviorIds:N,linkedBehaviorId:N[0]??""}),S=(N,A)=>N.includes(A)?N.filter(q=>q!==A):[...N,A],B=[{id:"intent",eyebrow:"Habit",title:"Name the recurring move",description:"Use habits for recurring commitments and recurring slips. Keep the title concrete so the daily check-in never needs interpretation.",render:(N,A)=>e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Title",error:w.title??null,children:e.jsx(ke,{value:N.title,onChange:q=>A({title:q.target.value}),placeholder:"Train lower body"})}),e.jsx(le,{label:"Description",children:e.jsx(Ve,{value:N.description,onChange:q=>A({description:q.target.value}),placeholder:"Write the habit description in Markdown. Define what counts, edge cases, and examples."})}),e.jsx(Vs,{value:N.userId,users:g,onChange:q=>A({userId:q}),label:"Owner user",defaultLabel:Gs(v),help:"Habits can be owned by humans or bots. When one scoped user is active, Forge uses that as the default."})]})},{id:"shape",eyebrow:"Shape",title:"Set direction and cadence",description:"Forge uses polarity to decide whether doing the habit is good or bad, and cadence to know when it should show up.",render:(N,A)=>e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Polarity",children:e.jsx(vt,{value:N.polarity,onChange:q=>A({polarity:q}),options:[{value:"positive",label:"Positive",description:"Doing it is aligned and should award XP."},{value:"negative",label:"Negative",description:"Doing it is a slip and should cost XP."}],columns:2})}),e.jsx(le,{label:"Frequency",children:e.jsx(vt,{value:N.frequency,onChange:q=>A({frequency:q}),options:[{value:"daily",label:"Daily",description:"Track against each day."},{value:"weekly",label:"Weekly",description:"Track only on the selected weekdays."}],columns:2})}),N.frequency==="weekly"?e.jsx(le,{label:"Weekdays",error:w.weekDays??null,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:A5.map(q=>{const W=N.weekDays.includes(q.value);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${W?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>A({weekDays:W?N.weekDays.filter(Y=>Y!==q.value):[...N.weekDays,q.value].sort()}),children:q.label},q.value)})})}):null,e.jsx(le,{label:"Status",children:e.jsx(vt,{value:N.status,onChange:q=>A({status:q}),options:[{value:"active",label:"Active",description:"Show it in the daily operating flow."},{value:"paused",label:"Paused",description:"Keep it visible but not currently due."},{value:"archived",label:"Archived",description:"Keep the record but retire it from active work."}]})})]})},{id:"generation",eyebrow:"Generation",title:"Decide whether this habit should create a workout record",description:"Use this when a completed habit should generate a structured sports or recovery session in Forge, then reconcile with HealthKit later if the same session gets imported.",render:(N,A)=>e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Generate workout record",children:e.jsx(vt,{value:N.generatedHealthEventTemplate.enabled?"enabled":"disabled",onChange:q=>A({generatedHealthEventTemplate:{...N.generatedHealthEventTemplate,enabled:q==="enabled"}}),options:[{value:"disabled",label:"Disabled",description:"This habit only affects the habit ledger."},{value:"enabled",label:"Enabled",description:"A completed check-in creates a workout or recovery session."}],columns:2})}),N.generatedHealthEventTemplate.enabled?e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Workout type",children:e.jsx(ke,{value:N.generatedHealthEventTemplate.workoutType,onChange:q=>A({generatedHealthEventTemplate:{...N.generatedHealthEventTemplate,workoutType:q.target.value}}),placeholder:"mobility, walk, strength, recovery"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Duration (minutes)",children:e.jsx(ke,{type:"number",min:1,max:1440,value:N.generatedHealthEventTemplate.durationMinutes,onChange:q=>A({generatedHealthEventTemplate:{...N.generatedHealthEventTemplate,durationMinutes:Number(q.target.value)||45}})})}),e.jsx(le,{label:"Workout XP",children:e.jsx(ke,{type:"number",min:0,max:500,value:N.generatedHealthEventTemplate.xpReward,onChange:q=>A({generatedHealthEventTemplate:{...N.generatedHealthEventTemplate,xpReward:Number(q.target.value)||0}})})})]}),e.jsx(le,{label:"Generated session note",children:e.jsx(Ve,{value:N.generatedHealthEventTemplate.notesTemplate,onChange:q=>A({generatedHealthEventTemplate:{...N.generatedHealthEventTemplate,notesTemplate:q.target.value}}),placeholder:"Morning routine session generated from habit completion."})})]}):null]})},{id:"links",eyebrow:"Links",title:"Connect the habit to real Forge work",description:"Link habits to the goals, projects, and tasks they support so they stay anchored in the same operating graph as everything else.",render:(N,A)=>e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Goals",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(q=>{const W=N.linkedGoalIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A({linkedGoalIds:S(N.linkedGoalIds,q.id)}),children:e.jsx(Ue,{kind:"goal",label:q.title,gradient:W,className:W?"":"opacity-75"})},q.id)})})}),e.jsx(le,{label:"Projects",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:m.map(q=>{const W=N.linkedProjectIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A({linkedProjectIds:S(N.linkedProjectIds,q.id)}),children:e.jsx(Ue,{kind:"project",label:q.title,gradient:W,className:W?"":"opacity-75"})},q.id)})})}),e.jsx(le,{label:"Tasks",children:e.jsx("div",{className:"flex max-h-48 flex-wrap gap-2 overflow-y-auto",children:c.map(q=>{const W=N.linkedTaskIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A({linkedTaskIds:S(N.linkedTaskIds,q.id)}),children:e.jsx(Ue,{kind:"task",label:q.title,gradient:W,className:W?"":"opacity-75",wrap:!0})},q.id)})})}),e.jsx(le,{label:"Values",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map(q=>{const W=N.linkedValueIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A({linkedValueIds:S(N.linkedValueIds,q.id)}),children:e.jsx(Ue,{kind:"value",label:q.title,gradient:W,className:W?"":"opacity-75"})},q.id)})})}),e.jsx(le,{label:"Patterns",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:r.map(q=>{const W=N.linkedPatternIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A({linkedPatternIds:S(N.linkedPatternIds,q.id)}),children:e.jsx(Ue,{kind:"pattern",label:q.title,gradient:W,className:W?"":"opacity-75",wrap:!0})},q.id)})})})]})},{id:"reward",eyebrow:"Reward",title:"Link the behavior and XP logic",description:"Habits can point back to a Psyche behavior. Reward XP is granted for aligned outcomes; penalty XP is applied for misaligned ones.",render:(N,A)=>e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Linked behavior",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:y.map(q=>{const W=N.linkedBehaviorIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A(E(S(N.linkedBehaviorIds,q.id))),children:e.jsx(Ue,{kind:"behavior",label:q.title,gradient:W,className:W?"":"opacity-75",wrap:!0})},q.id)})})}),e.jsx(le,{label:"Beliefs",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:l.map(q=>{const W=N.linkedBeliefIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A({linkedBeliefIds:S(N.linkedBeliefIds,q.id)}),children:e.jsx(Ue,{kind:"belief",label:q.statement,gradient:W,className:W?"":"opacity-75",wrap:!0})},q.id)})})}),e.jsx(le,{label:"Modes",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:o.map(q=>{const W=N.linkedModeIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A({linkedModeIds:S(N.linkedModeIds,q.id)}),children:e.jsx(Ue,{kind:"mode",label:q.title,gradient:W,className:W?"":"opacity-75",wrap:!0})},q.id)})})}),e.jsx(le,{label:"Reports",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:d.map(q=>{const W=N.linkedReportIds.includes(q.id);return e.jsx("button",{type:"button",onClick:()=>A({linkedReportIds:S(N.linkedReportIds,q.id)}),children:e.jsx(Ue,{kind:"report",label:q.title,gradient:W,className:W?"":"opacity-75",wrap:!0})},q.id)})})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(le,{label:"Target count",error:w.targetCount??null,children:e.jsx(ke,{type:"number",value:N.targetCount,onChange:q=>A({targetCount:Number(q.target.value)||1})})}),e.jsx(le,{label:"Reward XP",error:w.rewardXp??null,children:e.jsx(ke,{type:"number",value:N.rewardXp,onChange:q=>A({rewardXp:Number(q.target.value)||1})})}),e.jsx(le,{label:"Penalty XP",error:w.penaltyXp??null,children:e.jsx(ke,{type:"number",value:N.penaltyXp,onChange:q=>A({penaltyXp:Number(q.target.value)||1})})})]})]})}];return e.jsx(Lt,{open:t,onOpenChange:p,eyebrow:"Habit",title:a?"Edit habit":"Create habit",description:"Habits are recurring commitments or recurring slips with explicit XP consequences.",value:b,onChange:M,steps:B,pending:s,pendingLabel:a?"Save habit":"Create habit",submitLabel:a?"Save habit":"Create habit",error:P,onSubmit:async()=>{T(null);const N=L1.safeParse(b);if(!N.success){j(Object.fromEntries(Object.entries(N.error.flatten().fieldErrors).map(([A,q])=>[A,q==null?void 0:q[0]]))),T("Some habit fields still need attention.");return}j({});try{await f(N.data,a==null?void 0:a.id),M(zd),p(!1)}catch(A){T(A instanceof Error?A.message:"Habit update failed.")}}})}function no({label:t,value:s,options:a,onChange:i,className:r,triggerClassName:n,menuClassName:l}){const[o,d]=u.useState(!1),h=u.useRef(null),m=u.useRef(null),c=u.useId(),g=u.useMemo(()=>a.find(x=>x.value===s)??a[0],[a,s]);return u.useEffect(()=>{if(!o)return;const x=f=>{var b;(b=h.current)!=null&&b.contains(f.target)||d(!1)},p=f=>{var b;f.key==="Escape"&&(d(!1),(b=m.current)==null||b.focus())};return document.addEventListener("pointerdown",x),document.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",p)}},[o]),e.jsxs("div",{className:Z("relative",r),ref:h,children:[e.jsx("div",{className:"mb-1.5 text-[11px] font-medium uppercase tracking-[0.18em] text-white/42",children:t}),e.jsxs("button",{ref:m,type:"button",className:Z("flex min-h-11 w-full min-w-[15rem] items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-[linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.03))] px-4 py-2.5 text-left shadow-[0_16px_32px_rgba(15,23,42,0.18)] transition hover:border-white/14 hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.11),rgba(255,255,255,0.05))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[rgba(192,193,255,0.45)]",n),"aria-haspopup":"listbox","aria-expanded":o,"aria-controls":c,onClick:()=>d(x=>!x),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:(g==null?void 0:g.label)??s}),g!=null&&g.description?e.jsx("div",{className:"truncate text-xs text-white/48",children:g.description}):null]}),e.jsx(Ea,{className:Z("size-4 shrink-0 text-white/48 transition",o&&"rotate-180 text-white/72")})]}),o?e.jsx("div",{id:c,role:"listbox","aria-label":t,className:Z("absolute left-0 top-[calc(100%+0.6rem)] z-30 w-full overflow-hidden rounded-[22px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] p-2 shadow-[0_28px_64px_rgba(3,8,18,0.42)] backdrop-blur-xl",l),children:e.jsx("div",{className:"grid gap-1",children:a.map(x=>{const p=x.value===s;return e.jsxs("button",{type:"button",role:"option","aria-selected":p,className:Z("flex w-full items-start justify-between gap-3 rounded-[16px] px-3 py-2.5 text-left transition",p?"bg-[rgba(192,193,255,0.14)] text-white":"text-white/74 hover:bg-white/[0.06] hover:text-white"),onClick:()=>{i(x.value),d(!1)},children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:x.label}),x.description?e.jsx("div",{className:"mt-0.5 text-xs text-white/44",children:x.description}):null]}),e.jsx(Oi,{className:Z("mt-0.5 size-4 shrink-0 transition",p?"text-white":"opacity-0")})]},x.value)})})}):null]})}const L5=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],D5=["S","M","T","W","T","F","S"],F5=[{value:"name",label:"Name A-Z",description:"Keep the list stable alphabetically."},{value:"needs_attention",label:"Needs attention",description:"Bubble up habits still waiting on today."},{value:"streak",label:"Longest streak",description:"Put the strongest current streaks first."},{value:"created_at",label:"Newest created",description:"Show the most recently created habits first."},{value:"updated_at",label:"Recently updated",description:"Sort by the most recently changed habits."}];function _5(t){return t.frequency==="daily"?`${t.targetCount}x daily`:`${t.targetCount}x weekly · ${t.weekDays.map(s=>L5[s]).join(", ")}`}function yn(t){return t.toISOString().slice(0,10)}function Sb(t){const[s,a,i]=t.split("-").map(Number);return new Date(Date.UTC(s,a-1,i))}function Cb(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}function Pl(t,s){const a=new Date(t);return a.setUTCDate(a.getUTCDate()+s),a}function qm(t){const s=Cb(t),a=(s.getUTCDay()+6)%7;return s.setUTCDate(s.getUTCDate()-a),s}function rn(t){const s=typeof t=="string"?Sb(t):t;return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",timeZone:"UTC"}).format(s)}function Mo(t,s){return t.polarity==="positive"&&s==="done"||t.polarity==="negative"&&s==="missed"}function Uc(t,s){return t.polarity==="positive"?s==="done"?"Done":"Missed":s==="done"?"Performed":"Resisted"}function Ib(t){const s=yn(new Date),a=t.checkIns.find(i=>i.dateKey===s)??null;return t.dueToday?{tone:"pending",label:t.frequency==="daily"?"Waiting for today":"Awaiting this week's check-in",cardClass:"border-amber-300/24 shadow-[0_0_0_1px_rgba(251,191,36,0.12)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,191,36,0.18),transparent_44%)]",pillClass:"border border-amber-300/16 bg-amber-300/12 text-amber-100"}:a?Mo(t,a.status)?{tone:"aligned",label:`${Uc(t,a.status)} today`,cardClass:"border-emerald-300/20 shadow-[0_0_0_1px_rgba(52,211,153,0.08)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(52,211,153,0.16),transparent_44%)]",pillClass:"border border-emerald-300/16 bg-emerald-300/12 text-emerald-100"}:{tone:"unaligned",label:`${Uc(t,a.status)} today`,cardClass:"border-rose-300/20 shadow-[0_0_0_1px_rgba(251,113,133,0.08)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,113,133,0.16),transparent_44%)]",pillClass:"border border-rose-300/16 bg-rose-300/12 text-rose-100"}:t.polarity==="positive"?{tone:"neutral",label:"No update due right now",cardClass:"",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(52,211,153,0.09),transparent_40%)]",pillClass:"border border-white/10 bg-white/[0.06] text-white/62"}:{tone:"neutral",label:"No update due right now",cardClass:"",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,113,133,0.09),transparent_40%)]",pillClass:"border border-white/10 bg-white/[0.06] text-white/62"}}function R5(t){return t>=10?{Icon:Gw,className:"border border-amber-300/20 bg-amber-300/10 text-amber-100 shadow-[0_16px_32px_rgba(251,191,36,0.14)]",iconClass:"text-amber-200",valueClass:"text-amber-50",label:"Celebration pace"}:t>=5?{Icon:Qw,className:"border border-emerald-300/20 bg-emerald-300/10 text-emerald-100 shadow-[0_16px_32px_rgba(52,211,153,0.12)]",iconClass:"text-emerald-200",valueClass:"text-emerald-50",label:"Locked in"}:t>=1?{Icon:Vw,className:"border border-sky-300/18 bg-sky-300/10 text-sky-100 shadow-[0_16px_32px_rgba(125,211,252,0.1)]",iconClass:"text-sky-200",valueClass:"text-sky-50",label:"Building rhythm"}:{Icon:Xw,className:"border border-white/10 bg-white/[0.04] text-white/72 shadow-[0_16px_32px_rgba(15,23,42,0.16)]",iconClass:"text-white/55",valueClass:"text-white",label:"Cold start"}}function $5(t){return t>=80?"bg-emerald-400/12 text-emerald-100":t>=50?"bg-amber-300/12 text-amber-100":"bg-rose-400/12 text-rose-100"}function O5(t){var n;const s=new Date;if(t.frequency==="daily"){const l=Cb(s),o=[];for(let d=-6;d<=0;d+=1){const h=Pl(l,d),m=yn(h),c=t.checkIns.find(p=>p.dateKey===m)??null,g=D5[h.getUTCDay()],x=d===0;o.push({id:m,label:g,current:x,actionDateKey:m,actionLabel:rn(h),state:c?Mo(t,c.status)?"aligned":"unaligned":"unknown",title:`${rn(h)} · ${c?Uc(t,c.status):"Not informed"}`})}return{caption:"7-day rhythm",rangeLabel:"Past 7 days",showLabels:!0,startLabel:"",endLabel:"",cells:o}}const a=qm(s),i=new Map;for(const l of t.checkIns){const o=yn(qm(Sb(l.dateKey))),d=i.get(o)??[];d.push(l),i.set(o,d)}const r=[];for(let l=-6;l<=0;l+=1){const o=Pl(a,l*7),d=yn(o),h=i.get(d)??[],m=t.weekDays.length>0?[...t.weekDays].sort((f,b)=>b-f)[0]:0,c=yn(Pl(o,m)),g=((n=h[0])==null?void 0:n.dateKey)??c,x=h.filter(f=>Mo(t,f.status)).length,p=h.length-x;r.push({id:d,label:"",current:l===0,actionDateKey:g,actionLabel:`Week of ${rn(o)}`,state:h.length===0?"unknown":x>=p?"aligned":"unaligned",title:`${rn(o)} week · ${h.length===0?"Not informed":x>=p?"Mostly aligned":"Mostly off track"}`})}return{caption:"7-week rhythm",rangeLabel:"Past 7 weeks",showLabels:!1,startLabel:rn(Pl(a,-42)),endLabel:"This week",cells:r}}function z5(t,s){return Z("h-8 w-full rounded-[10px] border transition",t==="aligned"&&"border-emerald-300/20 bg-emerald-300/75 shadow-[0_8px_18px_rgba(52,211,153,0.18)]",t==="unaligned"&&"border-rose-300/20 bg-rose-300/75 shadow-[0_8px_18px_rgba(251,113,133,0.18)]",t==="unknown"&&"border-white/8 bg-white/[0.08]",s&&"shadow-[0_0_0_1px_rgba(255,255,255,0.16)]")}function K5({habit:t,onSelectCell:s}){const a=O5(t),i=Ib(t);return e.jsxs("div",{className:"w-full rounded-[18px] border border-white/8 bg-black/10 px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"shrink-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.16em] text-white/34",children:a.caption}),e.jsx("div",{className:"text-[11px] text-white/46",children:a.rangeLabel})]}),e.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:a.cells.map(r=>e.jsxs("button",{type:"button",className:"group flex min-w-0 flex-1 items-center gap-1 rounded-[10px] transition hover:bg-white/[0.04]",onClick:()=>s(t,r),title:`Log check-in for ${r.actionLabel}`,"aria-label":`Log check-in for ${r.actionLabel}`,children:[e.jsx("div",{className:Z(z5(r.state,r.current),"h-6 min-w-0 flex-1 rounded-[8px] transition duration-150 group-hover:-translate-y-0.5 group-hover:shadow-[0_10px_22px_rgba(15,23,42,0.22)]")}),a.showLabels?e.jsx("span",{className:"hidden text-[9px] uppercase tracking-[0.14em] text-white/26 transition group-hover:text-white/48 sm:inline",children:r.label}):null]},r.id))}),e.jsx("div",{className:Z("shrink-0 rounded-full px-2.5 py-1 text-[10px] font-medium",i.pillClass),children:i.label})]}),a.showLabels?null:e.jsxs("div",{className:"mt-1 text-right text-[10px] uppercase tracking-[0.14em] text-white/26",children:[a.startLabel," - ",a.endLabel]})]})}function q5(t){return t.polarity==="positive"?{alignedLabel:"Done",alignedDescription:"Log that the intended habit happened.",unalignedLabel:"Missed",unalignedDescription:"Log that the habit did not happen."}:{alignedLabel:"Resisted",alignedDescription:"Log that the unwanted behavior was resisted.",unalignedLabel:"Performed",unalignedDescription:"Log that the unwanted behavior happened."}}function Qi(t,s){return t.polarity==="positive"?s==="aligned"?"done":"missed":s==="aligned"?"missed":"done"}function Vi(t,s){return Mo(t,s)?"aligned":"unaligned"}function B5(){var $,Q,X,ae,Pe,Ne;const t=jt(),s=ct(),[a,i]=us(),[r,n]=u.useState(null),[l,o]=u.useState(null),[d,h]=u.useState(null),[m,c]=u.useState(""),[g,x]=u.useState(!1),[p,f]=u.useState(null),[b,M]=u.useState(null),P=a.get("focus"),T=a.get("orderBy")??"name",w=Hg(t.selectedUserIds),j=fs(w),v=["forge-habits",T,...w];Br(P);const y=Me({queryKey:v,queryFn:async()=>(await pN({userIds:w,orderBy:T})).habits}),E=Me({queryKey:["forge-psyche-overview",...w],queryFn:async()=>(await td(w)).overview}),S=Me({queryKey:["forge-life-force",...w],queryFn:async()=>(await Ki(w)).lifeForce});u.useEffect(()=>{a.get("create")==="1"&&(n(null),x(!0),i(fe=>{const V=new URLSearchParams(fe);return V.delete("create"),V},{replace:!0}))},[a,i]);const B=async()=>{await s.invalidateQueries({queryKey:["forge-habits"]}),await t.refresh()},N=De({mutationFn:async({input:fe,habitId:V})=>V?(await gN(V,fe)).habit:(await xN(fe)).habit,onSuccess:async()=>{M(null),await B()},onError:fe=>{M(fe instanceof Error?fe.message:"Habit save failed.")}}),A=De({mutationFn:async({habitId:fe,status:V,dateKey:Ce,note:L})=>bN(fe,{status:V,dateKey:Ce,note:L}),onSuccess:async()=>{M(null),await B()},onError:fe=>{M(fe instanceof Error?fe.message:"Habit check-in failed.")}}),q=De({mutationFn:async fe=>fN(fe),onMutate:async fe=>{await s.cancelQueries({queryKey:v});const V=s.getQueryData(v);return s.setQueryData(v,Ce=>(Ce==null?void 0:Ce.filter(L=>L.id!==fe))??[]),{previousHabits:V}},onSuccess:async()=>{M(null),f(null),await B()},onError:(fe,V,Ce)=>{Ce!=null&&Ce.previousHabits&&s.setQueryData(v,Ce.previousHabits),M(fe instanceof Error?fe.message:"Habit delete failed.")}}),W=u.useMemo(()=>(y.data??[]).filter(fe=>fe.status!=="archived"),[y.data]),Y=u.useMemo(()=>W.filter(fe=>fe.dueToday),[W]),K=u.useMemo(()=>Y.reduce((fe,V)=>{var D;const Ce=hm().totalAp,L=((D=Ed(V))==null?void 0:D.totalAp)??0;return fe+Ce+L},0),[Y]),O=u.useMemo(()=>W.reduce((fe,V)=>{var Ce;return fe+(((Ce=Ed(V))==null?void 0:Ce.totalAp)??0)},0),[W]),R=u.useMemo(()=>l?l.habit.checkIns.find(fe=>fe.dateKey===l.cell.actionDateKey)??null:null,[l]);if(u.useEffect(()=>{if(!l){h(null),c("");return}h((R==null?void 0:R.status)??null),c((R==null?void 0:R.note)??"")},[l,R]),y.error)throw y.error;const F=fe=>{i(V=>{const Ce=new URLSearchParams(V);return fe==="name"?Ce.delete("orderBy"):Ce.set("orderBy",fe),Ce},{replace:!0})},H=l?q5(l.habit):null,G=d==="done"||d==="missed"||R!==null;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(rt,{entityKind:"habit",title:e.jsx(wt,{kind:"habit",label:"Habits",variant:"heading",size:"lg"}),titleText:"Habits",description:"Habits track recurring commitments and recurring slips with explicit daily consequences, linked behaviors, and real XP movement.",badge:`${W.length} habits`,actions:e.jsxs(z,{onClick:()=>{n(null),x(!0)},children:[e.jsx(Ht,{className:"size-4"}),"New habit"]})}),b?e.jsx(ie,{className:"border-rose-400/22 bg-rose-400/8 text-rose-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Hx,{className:"mt-0.5 size-4 shrink-0"}),e.jsx("div",{children:b})]})}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(ie,{className:"border-amber-300/16 shadow-[0_0_0_1px_rgba(251,191,36,0.08)]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Due today"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:Y.length}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Habits that still need a check-in today."})]}),e.jsxs(ie,{className:"border-[var(--primary)]/16 shadow-[0_0_0_1px_rgba(245,158,11,0.08)]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Habit AP due"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:kt(K)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Default Action Point load if every due habit is logged today."})]}),e.jsxs(ie,{className:"border-emerald-300/16 shadow-[0_0_0_1px_rgba(52,211,153,0.08)]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Best streak"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-emerald-50",children:Math.max(0,...W.map(fe=>fe.streakCount))}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Longest current aligned streak across active habits."})]}),e.jsxs(ie,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average alignment"}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[W.length>0?Math.round(W.reduce((fe,V)=>fe+V.completionRate,0)/W.length):0,"%"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Share of recent habit check-ins that matched the intended direction."})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs(ie,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Life Force sync"}),e.jsx("div",{className:"mt-3 text-2xl font-display text-white",children:S.data?`${kt(S.data.spentTodayAp)} / ${kt(S.data.dailyBudgetAp)}`:"Loading..."}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Habit check-ins debit the same Action Point ledger as work, notes, movement, and workouts."})]}),e.jsxs(ie,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Instant headroom"}),e.jsx("div",{className:"mt-3 text-2xl font-display text-white",children:S.data?Kt(S.data.instantFreeApPerHour):"Loading..."}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Use this to tell whether now is a good moment for heavier habits or just a light check-in."})]}),e.jsxs(ie,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Workout-linked load"}),e.jsx("div",{className:"mt-3 text-2xl font-display text-white",children:kt(O)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Habit-generated workout templates stay visible as Action Point cost instead of hiding behind the XP reward."})]})]}),y.isLoading?e.jsx(ie,{children:"Loading habits..."}):W.length===0?e.jsx(Bt,{eyebrow:"Habits",title:"No recurring habits yet",description:"Create the recurring commitments or recurring slips you want Forge to track explicitly. Positive habits pay out when completed. Negative habits invert that logic.",action:e.jsx(z,{onClick:()=>{n(null),x(!0)},children:"Create habit"})}):e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 rounded-[24px] border border-white/8 bg-white/[0.03] p-4 shadow-[0_18px_36px_rgba(15,23,42,0.16)] sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"max-w-xl",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Habit list order"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Choose a stable ordering so the list does not reshuffle while you are logging check-ins."})]}),e.jsx(no,{label:"Order by",value:T,options:F5,onChange:F,className:"w-full sm:w-[19rem]"})]}),e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:W.map(fe=>{const V=Ib(fe),Ce=R5(fe.streakCount),L=Ce.Icon,D=hm(),_=Ed(fe),ee=Qs(t.snapshot.dashboard.notesSummaryByEntity,"habit",fe.id).count,U=fe.polarity==="positive"?{label:"Done",status:Qi(fe,"aligned"),Icon:Rn,className:"border-emerald-300/18 bg-emerald-300/14 text-emerald-50 shadow-[0_14px_28px_rgba(52,211,153,0.14)] hover:bg-emerald-300/20"}:{label:"Resisted",status:Qi(fe,"aligned"),Icon:Sn,className:"border-emerald-300/18 bg-emerald-300/14 text-emerald-50 shadow-[0_14px_28px_rgba(52,211,153,0.14)] hover:bg-emerald-300/20"},te=fe.polarity==="positive"?{label:"Missed",status:Qi(fe,"unaligned"),Icon:Sh,className:"border-rose-300/18 bg-rose-300/14 text-rose-50 shadow-[0_14px_28px_rgba(251,113,133,0.14)] hover:bg-rose-300/20"}:{label:"Performed",status:Qi(fe,"unaligned"),Icon:Zn,className:"border-rose-300/18 bg-rose-300/14 text-rose-50 shadow-[0_14px_28px_rgba(251,113,133,0.14)] hover:bg-rose-300/20"};return e.jsxs(ie,{className:Z("relative flex h-full flex-col overflow-hidden",V.cardClass,Ur(P===fe.id)),"data-psyche-focus-id":fe.id,children:[e.jsx("div",{className:Z("pointer-events-none absolute inset-0 opacity-100",V.overlayClass)}),e.jsxs("div",{className:"relative z-10 flex h-full flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(wt,{kind:"habit",label:fe.title,variant:"heading",size:"sm"}),e.jsx(nt,{user:fe.user,compact:!0}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:fe.status}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[e.jsx(ds,{className:"mr-1 size-3.5"}),_5(fe)]}),e.jsx(I,{className:fe.polarity==="positive"?"bg-emerald-400/12 text-emerald-200":"bg-rose-400/12 text-rose-200",children:fe.polarity==="positive"?"Positive":"Negative"}),fe.dueToday?e.jsx(I,{className:"bg-amber-300/12 text-amber-100",children:"Needs check-in"}):null,fe.linkedGoalIds.slice(0,1).map(J=>{const ve=t.snapshot.goals.find(pe=>pe.id===J);return ve?e.jsxs(I,{className:"bg-amber-400/12 text-amber-100",children:["Goal · ",ve.title]},ve.id):null}),fe.linkedProjectIds.slice(0,1).map(J=>{const ve=t.snapshot.dashboard.projects.find(pe=>pe.id===J);return ve?e.jsxs(I,{className:"bg-sky-400/12 text-sky-100",children:["Project · ",ve.title]},ve.id):null}),fe.linkedTaskIds.slice(0,1).map(J=>{const ve=t.snapshot.tasks.find(pe=>pe.id===J);return ve?e.jsxs(I,{className:"bg-indigo-400/12 text-indigo-100",children:["Task · ",ve.title]},ve.id):null})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:fe.description?e.jsx(Fs,{markdown:fe.description,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):"No extra notes yet."})]}),e.jsxs("div",{className:"ml-auto inline-flex shrink-0 flex-col items-end gap-2 self-start text-right",children:[e.jsxs("div",{className:Z("inline-flex flex-col self-end rounded-[20px] px-3 py-2.5 text-right",Ce.className),children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5 text-[10px] uppercase tracking-[0.16em]",children:[e.jsx("span",{children:"Streak"}),e.jsx(L,{className:Z("size-3.5 shrink-0",Ce.iconClass)})]}),e.jsx("div",{className:Z("mt-1.5 font-display text-[2.75rem] leading-none",Ce.valueClass),children:fe.streakCount}),e.jsx("div",{className:"mt-1 text-[11px] leading-tight text-white/68",children:Ce.label})]}),e.jsxs("div",{className:"ml-auto grid grid-cols-2 gap-1.5",children:[e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 min-w-0 rounded-[11px] border border-white/8 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",disabled:N.isPending,onClick:()=>{n(fe),x(!0)},"aria-label":`Edit ${fe.title}`,title:"Edit habit",children:e.jsx(Pa,{className:"size-4"})}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 min-w-0 rounded-[11px] border border-white/8 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",disabled:q.isPending,onClick:()=>f(fe),"aria-label":`Delete ${fe.title}`,title:"Delete habit",children:e.jsx($t,{className:"size-4"})})]})]})]}),e.jsxs("div",{className:"mt-auto grid gap-4 pt-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:Z("border-0",$5(fe.completionRate)),children:["Alignment ",fe.completionRate,"%"]}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:fe.polarity==="positive"?`+${fe.rewardXp} XP done`:`+${fe.rewardXp} XP resisted`}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:fe.polarity==="positive"?`-${fe.penaltyXp} XP missed`:`-${fe.penaltyXp} XP performed`}),e.jsxs(I,{className:"bg-[var(--primary)]/12 text-[var(--primary)]",children:[kt(D.totalAp)," check-in"]}),_?e.jsxs(I,{className:"bg-orange-400/12 text-orange-100",children:[kt(_.totalAp)," ","workout"]}):null,_?e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:Kt(_.rateApPerHour)}):null,e.jsx(_s,{entityType:"habit",entityId:fe.id,count:ee,className:"min-h-8 rounded-full border-white/8 bg-white/[0.04] px-3 py-1.5 text-[12px] text-white/68 hover:bg-white/[0.07]"}),fe.linkedBehaviorTitles.slice(0,2).map(J=>e.jsxs(I,{className:"bg-orange-400/12 text-orange-100",children:[e.jsx(Sn,{className:"mr-1 size-3.5"}),J]},J)),fe.linkedProjectIds.slice(1,2).map(J=>{const ve=t.snapshot.dashboard.projects.find(pe=>pe.id===J);return ve?e.jsxs(I,{className:"bg-sky-400/12 text-sky-100",children:["Project · ",ve.title]},ve.id):null}),fe.linkedTaskIds.slice(1,2).map(J=>{const ve=t.snapshot.tasks.find(pe=>pe.id===J);return ve?e.jsxs(I,{className:"bg-indigo-400/12 text-indigo-100",children:["Task · ",ve.title]},ve.id):null}),fe.linkedValueIds.slice(0,2).map(J=>{var pe;const ve=(pe=E.data)==null?void 0:pe.values.find(Ee=>Ee.id===J);return ve?e.jsxs(I,{className:"bg-emerald-400/12 text-emerald-100",children:["Value · ",ve.title]},ve.id):null}),fe.linkedPatternIds.slice(0,2).map(J=>{var pe;const ve=(pe=E.data)==null?void 0:pe.patterns.find(Ee=>Ee.id===J);return ve?e.jsxs(I,{className:"bg-cyan-400/12 text-cyan-100",children:["Pattern · ",ve.title]},ve.id):null}),fe.linkedBeliefIds.slice(0,2).map(J=>{var pe;const ve=(pe=E.data)==null?void 0:pe.beliefs.find(Ee=>Ee.id===J);return ve?e.jsxs(I,{className:"bg-rose-400/12 text-rose-100",children:["Belief · ",ve.statement]},ve.id):null}),fe.linkedModeIds.slice(0,2).map(J=>{var pe;const ve=(pe=E.data)==null?void 0:pe.modes.find(Ee=>Ee.id===J);return ve?e.jsxs(I,{className:"bg-violet-400/12 text-violet-100",children:["Mode · ",ve.title]},ve.id):null}),fe.linkedReportIds.slice(0,2).map(J=>{var pe;const ve=(pe=E.data)==null?void 0:pe.reports.find(Ee=>Ee.id===J);return ve?e.jsxs(I,{className:"bg-fuchsia-400/12 text-fuchsia-100",children:["Report · ",ve.title]},ve.id):null})]}),e.jsx("div",{className:"grid gap-4",children:e.jsx(K5,{habit:fe,onSelectCell:(J,ve)=>{o({habit:J,cell:ve}),M(null)}})}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs(z,{variant:"secondary",className:Z("h-11 rounded-[16px] border",U.className),disabled:A.isPending,onClick:()=>void A.mutateAsync({habitId:fe.id,status:U.status}),children:[e.jsx(U.Icon,{className:"size-4"}),U.label]}),e.jsxs(z,{variant:"secondary",className:Z("h-11 rounded-[16px] border",te.className),disabled:A.isPending,onClick:()=>void A.mutateAsync({habitId:fe.id,status:te.status}),children:[e.jsx(te.Icon,{className:"size-4"}),te.label]})]})]})]})]},fe.id)})})]}),e.jsx(E5,{open:g,pending:N.isPending,editingHabit:r,values:(($=E.data)==null?void 0:$.values)??[],patterns:((Q=E.data)==null?void 0:Q.patterns)??[],behaviors:((X=E.data)==null?void 0:X.behaviors)??[],beliefs:((ae=E.data)==null?void 0:ae.beliefs)??[],modes:((Pe=E.data)==null?void 0:Pe.modes)??[],reports:((Ne=E.data)==null?void 0:Ne.reports)??[],goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,users:t.snapshot.users,defaultUserId:(r==null?void 0:r.userId)??j,onOpenChange:x,onSubmit:async(fe,V)=>{try{await N.mutateAsync({input:fe,habitId:V})}catch(Ce){throw Ce instanceof ba,Ce}}}),e.jsx(Xt,{open:p!==null,onOpenChange:fe=>{!fe&&!q.isPending&&f(null)},children:e.jsxs(Yt,{children:[e.jsx(Jt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(Zt,{className:"fixed inset-x-4 top-1/2 z-50 mx-auto w-[min(30rem,calc(100vw-2rem))] max-w-[30rem] -translate-y-1/2 overflow-hidden rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.45)]",children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-4",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:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Delete habit"}),e.jsx(es,{className:"mt-2 text-lg font-semibold text-white",children:(p==null?void 0:p.title)??"Delete this habit?"}),e.jsx(is,{className:"mt-3 text-sm text-white/56",children:"Remove this habit from Forge. The habit card disappears immediately after delete succeeds."})]}),e.jsx(Gt,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"sm",className:"h-10 w-10 rounded-[14px] border border-white/8 bg-white/[0.04] px-0 text-white/72 hover:bg-white/[0.08] hover:text-white","aria-label":"Close delete habit modal",title:"Close",disabled:q.isPending,children:e.jsx(Tt,{className:"size-4"})})})]})}),e.jsxs("div",{className:"grid gap-4 p-5",children:[e.jsx("div",{className:"rounded-[20px] border border-rose-400/16 bg-rose-400/8 px-4 py-3 text-sm leading-6 text-rose-100/90",children:"This removes the habit and its check-in history from the habits page."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[e.jsx(z,{variant:"secondary",onClick:()=>f(null),disabled:q.isPending,children:"Cancel"}),e.jsx(z,{className:"border border-rose-300/18 bg-rose-300/14 text-rose-50 hover:bg-rose-300/20",pending:q.isPending,pendingLabel:"Deleting",onClick:()=>{p&&q.mutateAsync(p.id)},children:"Delete habit"})]})]})]})]})}),e.jsx(Xt,{open:l!==null,onOpenChange:fe=>{fe||o(null)},children:e.jsxs(Yt,{children:[e.jsx(Jt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(Zt,{className:"fixed inset-x-4 top-1/2 z-50 mx-auto w-[min(42rem,calc(100vw-2rem))] max-w-[42rem] -translate-y-1/2 overflow-hidden rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.45)]",children:[e.jsx(es,{className:"sr-only",children:"Habit history"}),e.jsx(is,{className:"sr-only",children:"Log or revise a habit check-in for a selected history point."}),l&&H?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-4",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:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Habit history"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-lg font-semibold text-white",children:l.habit.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:l.cell.actionLabel})]}),e.jsx("div",{className:"mt-3 text-sm text-white/56",children:l.habit.frequency==="daily"?"Log or revise the check-in for this specific day.":"Log or revise the representative check-in for this week."})]}),e.jsx(Gt,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"sm",className:"h-10 w-10 rounded-[14px] border border-white/8 bg-white/[0.04] px-0 text-white/72 hover:bg-white/[0.08] hover:text-white","aria-label":"Close history modal",title:"Close",children:e.jsx(Tt,{className:"size-4"})})})]})}),e.jsxs("div",{className:"grid gap-4 p-5",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("button",{type:"button","aria-pressed":d!==null&&Vi(l.habit,d)==="aligned",className:Z("rounded-[22px] border px-4 py-4 text-left transition",d!==null&&Vi(l.habit,d)==="aligned"?"border-emerald-300/24 bg-emerald-300/14 text-white shadow-[0_16px_36px_rgba(52,211,153,0.14)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"),onClick:()=>h(fe=>fe!==null&&Vi(l.habit,fe)==="aligned"?null:Qi(l.habit,"aligned")),children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-medium",children:[e.jsx(Rn,{className:"size-4"}),H.alignedLabel]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:H.alignedDescription})]}),e.jsxs("button",{type:"button","aria-pressed":d!==null&&Vi(l.habit,d)==="unaligned",className:Z("rounded-[22px] border px-4 py-4 text-left transition",d!==null&&Vi(l.habit,d)==="unaligned"?"border-rose-300/24 bg-rose-300/14 text-white shadow-[0_16px_36px_rgba(251,113,133,0.14)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"),onClick:()=>h(fe=>fe!==null&&Vi(l.habit,fe)==="unaligned"?null:Qi(l.habit,"unaligned")),children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-medium",children:[e.jsx(Sh,{className:"size-4"}),H.unalignedLabel]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:H.unalignedDescription})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Optional note"}),e.jsx(Ve,{value:m,onChange:fe=>c(fe.target.value),placeholder:"Add context for what happened on this day or week.",className:"min-h-24"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[e.jsx(z,{variant:"secondary",onClick:()=>o(null),disabled:A.isPending,children:"Cancel"}),e.jsx(z,{disabled:A.isPending||!G,pending:A.isPending,pendingLabel:"Saving",onClick:async()=>{G&&(d===null?(await vN(l.habit.id,l.cell.actionDateKey),await B()):await A.mutateAsync({habitId:l.habit.id,status:d,dateKey:l.cell.actionDateKey,note:m.trim()||void 0}),o(null))},children:"Save check-in"})]})]})]}):null]})]})})]})}const U5={title:"",description:"",level:"task",owner:"Albert",userId:null,assigneeUserIds:[],goalId:"",projectId:"",parentWorkItemId:null,priority:"medium",status:"focus",effort:"deep",energy:"steady",dueDate:"",points:60,plannedDurationSeconds:86400,actionCostBand:"standard",aiInstructions:"",executionMode:null,acceptanceCriteria:[],blockerLinks:[],completionReport:null,gitRefs:[],tagIds:[],notes:[]},W5={goalId:"",title:"",description:"",status:"active",workflowStatus:"backlog",userId:null,assigneeUserIds:[],targetPoints:240,themeColor:"#c0c1ff",productRequirementsDocument:"",notes:[]},H5={title:"",description:"",horizon:"year",status:"active",userId:null,targetPoints:400,themeColor:"#c8a46b",tagIds:[],notes:[]},G5=["goal","project","task","tag","note","insight","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","mode_guide_session","event_type","emotion_definition","trigger_report"];function Q5(t){return t!==null&&G5.includes(t)}function mh(t,s,a=96){const i=t.trim()||s.trim();return i.length<=a?i:`${i.slice(0,a-1).trimEnd()}…`}function V5(t){return[t.summary.trim(),t.rationale.trim()?`Why it matters: ${t.rationale.trim()}`:""].filter(Boolean).join(`
|
|
23
23
|
|
|
@@ -89,4 +89,4 @@ ${x.trim()}
|
|
|
89
89
|
`):s}function HM(t){return t.map(({key:s,kind:a,required:i,description:r,modelName:n,itemKind:l,shape:o,exampleValue:d})=>({key:s,kind:a,required:!!i,description:r,modelName:n,itemKind:l,shape:o,exampleValue:d}))}function GM(t){const s=Array.from(new Set(t.map(i=>i.trim()).filter(Boolean)));return(s.includes("answer")?s:["answer",...s]).map(i=>({key:i,label:i==="answer"?"Answer":i.split(/[_-]+/).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" "),kind:i==="answer"?"markdown":"record",description:i==="answer"?"Primary answer returned by this AI node.":`Named output published for downstream nodes under "${i}".`,modelName:i==="answer"?"WorkbenchAiAnswer":`Workbench${i.split(/[_-]+/).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}`,exampleValue:i==="answer"?"Concise answer":void 0}))}function QM(t,s){return ow(t,s)[0]??null}function ow(t,s){var l,o;const a=[],i=new Map(t.map(d=>[d.id,d]));t.length===0&&a.push("Add at least one node before running the flow.");const r=t.filter(d=>d.data.nodeType==="output");r.length===0&&a.push("Add an Output node so Forge knows what result the flow should publish.");const n=new Map;for(const d of s){n.set(d.target,(n.get(d.target)??0)+1);const h=i.get(d.source),m=i.get(d.target),c=(h==null?void 0:h.data.outputs)??[],g=(m==null?void 0:m.data.inputs)??[];h&&(d.sourceHandle&&!c.some(x=>x.key===d.sourceHandle)?a.push(`Edge from "${h.data.label}" points to missing output "${d.sourceHandle}". Update the edge or restore that output contract.`):!d.sourceHandle&&c.length>1&&a.push(`Edge from "${h.data.label}" does not name which output it should use. Pick one explicit output handle.`)),m&&(d.targetHandle&&!g.some(x=>x.key===d.targetHandle)?a.push(`Edge into "${m.data.label}" points to missing input "${d.targetHandle}". Update the edge or restore that input contract.`):!d.targetHandle&&g.length>1&&a.push(`Edge into "${m.data.label}" does not name which input it should feed. Pick one explicit input handle.`))}for(const d of r){(n.get(d.id)??0)===0&&a.push(`Connect something into the output node "${d.data.label}" so the flow has something to return.`);const h=s.filter(m=>m.target===d.id).flatMap(m=>{const c=i.get(m.source),g=(c==null?void 0:c.data.outputs)??[];return m.sourceHandle?g.filter(x=>x.key===m.sourceHandle).map(x=>x.key):g.map(x=>x.key)});d.data.outputKey&&h.length>0&&!h.includes(d.data.outputKey)&&a.push(`Output node "${d.data.label}" is configured to publish "${d.data.outputKey}", but that key is not arriving from its upstream nodes.`)}for(const d of t){const h=n.get(d.id)??0,m=s.filter(c=>c.source===d.id).length;d.data.nodeType!=="user_input"&&d.data.nodeType!=="value"&&h===0&&d.data.nodeType!=="box"&&a.push(`Connect an upstream source into "${d.data.label}" so it has real input to work with.`),d.data.nodeType==="merge"&&h<2&&a.push(`Merge node "${d.data.label}" should receive both left and right inputs before you run it.`),d.data.nodeType==="template"&&!(d.data.template??"").trim()&&a.push(`Add a template string to "${d.data.label}" before running the flow.`),d.data.nodeType==="pick_key"&&!(d.data.selectedKey??"").trim()&&a.push(`Choose which key "${d.data.label}" should pick from incoming objects.`),d.data.nodeType!=="output"&&m===0&&a.push(`Connect the output of "${d.data.label}" somewhere useful or remove the node from the graph.`)}for(const d of t)kn(d.data.nodeType)&&!((l=d.data.promptTemplate)!=null&&l.trim()||(o=d.data.prompt)!=null&&o.trim())&&a.push(`Add a prompt to the AI node "${d.data.label}" before running the flow.`);return a}function bn({open:t,onOpenChange:s,title:a,description:i,children:r}){return e.jsx(Xt,{open:t,onOpenChange:s,children:e.jsxs(Yt,{children:[e.jsx(Jt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs(Zt,{className:"fixed inset-x-4 bottom-4 top-4 z-50 mx-auto flex max-w-[min(44rem,calc(100vw-2rem))] flex-col overflow-hidden rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(12,18,33,0.985),rgba(8,13,24,0.985))] shadow-[0_36px_96px_rgba(0,0,0,0.46)] md:left-1/2 md:right-auto md:top-[8vh] md:h-[min(82vh,58rem)] md:w-[min(44rem,calc(100vw-1.25rem))] md:-translate-x-1/2 md:bottom-auto",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-white/8 px-5 py-4 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsx(es,{className:"font-display text-[1.28rem] tracking-[-0.04em] text-white",children:a}),i?e.jsx(is,{className:"mt-1 text-sm leading-6 text-white/54",children:i}):null]}),e.jsx(Gt,{asChild:!0,children:e.jsx(qi,{"aria-label":"Close workbench flow dialog"})})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 py-5",children:r})]})]})})}function Ax({title:t,description:s,kind:a,publicInputs:i,nodes:r,edges:n}){return{title:t,description:s,kind:a,publicInputs:i,graph:{nodes:r.map(lw),edges:n.map(RM)}}}function VM({flow:t,boxes:s,modelConnections:a,runs:i,onSave:r,onDelete:n,onRun:l,onChat:o}){var k,se,Le,ze,We,gt,Mt,Qt,Ds,_a,Ra,Wr,Hr,Gr,Qr,Vr,Xr,Yr,Jr,Zr,en,tn;const[d,h]=u.useState(t.title),[m,c]=u.useState(t.description),[g,x]=u.useState(t.kind),[p,f]=u.useState(t.publicInputs??[]),[b,M]=u.useState(()=>wc(t,s).nodes),[P,T]=u.useState(()=>wc(t,s).edges),[w,j]=u.useState(null),[v,y]=u.useState(!1),[E,S]=u.useState(!1),[B,N]=u.useState("overview"),[A,q]=u.useState(void 0),[W,Y]=u.useState(!1),[K,O]=u.useState(!1),[R,F]=u.useState(!1),[H,G]=u.useState(""),[$,Q]=u.useState([]),[X,ae]=u.useState(""),[Pe,Ne]=u.useState({}),[fe,V]=u.useState(!0),[Ce,L]=u.useState(null),[D,_]=u.useState("idle"),[ee,U]=u.useState(null),[te,J]=u.useState(((k=i[0])==null?void 0:k.id)??null),[ve,pe]=u.useState(null),Ee=u.useMemo(()=>JSON.stringify(Ax({title:t.title,description:t.description,kind:t.kind,publicInputs:t.publicInputs??[],nodes:t.graph.nodes.map(de=>lu(de,s)),edges:t.graph.edges.map(nw)})),[s,t]),ce=u.useRef(Ee),ue=u.useRef(Ee),Fe=u.useRef({}),ye=u.useRef(Ee),he=u.useRef(null),me=u.useRef(!1);u.useEffect(()=>{if(Ee===ue.current)return;ue.current=Ee,ce.current=Ee,ye.current=Ee,h(t.title),c(t.description),x(t.kind),f(t.publicInputs??[]);const de=wc(t,s);M(de.nodes),T(de.edges),_("idle"),U(null)},[s,t,Ee]),u.useEffect(()=>{Ne(Object.fromEntries((t.publicInputs??[]).filter(de=>de.defaultValue!==void 0).map(de=>[de.key,de.defaultValue])))},[t.publicInputs]),u.useEffect(()=>{var de;J(((de=i[0])==null?void 0:de.id)??null)},[i]),u.useEffect(()=>{M(de=>de.map(_e=>_e.data.nodeType!=="box"||!_e.data.boxId?_e:lu(lw(_e),s)))},[s]);const Ke=u.useMemo(()=>Array.from(new Set(s.map(_e=>_e.category))).map(_e=>({id:`category:${_e}`,label:_e,description:"Workbench box category"})),[s]),ge=u.useMemo(()=>{const de=H.trim().toLowerCase();return s.filter(_e=>{const Qe=de.length===0||[_e.title,_e.description,_e.category,_e.routePath??"",..._e.tags].join(" ").toLowerCase().includes(de),St=$.every(At=>At.startsWith("category:")?_e.category===At.replace("category:",""):!0);return Qe&&St})},[$,H,s]),C=u.useMemo(()=>b.find(de=>de.id===w)??null,[b,w]),ne=i[0]??null,Re=i.find(de=>de.id===te)??ne??null,at=d2({flowId:t.id,runId:te??""},{skip:!te||!R}),lt=((se=at.data)==null?void 0:se.nodeResults.find(de=>de.nodeId===ve))??null,Te=o2({flowId:t.id,runId:te??"",nodeId:ve??""},{skip:!te||!ve||!R}),qe=u.useMemo(()=>ow(b,P),[b,P]),Je=u.useMemo(()=>b.some(de=>kn(de.data.nodeType)),[b]),Ze=u.useMemo(()=>b.some(de=>de.data.nodeType==="user_input")||(p??[]).length===0,[b,p]);u.useEffect(()=>{var _e,Qe;const de=((Qe=(_e=at.data)==null?void 0:_e.nodeResults[0])==null?void 0:Qe.nodeId)??null;pe(de)},[(Le=at.data)==null?void 0:Le.nodeResults]);const re=u.useMemo(()=>!!(C&&C.data.nodeType!=="box"&&C.data.nodeType!=="box_input"),[C]),oe=u.useMemo(()=>C?P.filter(de=>de.target===C.id).flatMap(de=>{const _e=b.find(St=>St.id===de.source),Qe=(_e==null?void 0:_e.data.outputs)??[];return de.sourceHandle?Qe.filter(St=>St.key===de.sourceHandle):Qe}):[],[P,b,C]),je=u.useMemo(()=>LM(s),[s]),we=u.useMemo(()=>{if(!C||!kn(C.data.nodeType))return[];const de=new Set(C.data.enabledToolKeys??[]);return je.filter(_e=>de.has(_e.key))},[je,C]),Ie=u.useMemo(()=>Ax({title:d,description:m,kind:g,publicInputs:p,nodes:b,edges:P}),[m,P,g,b,p,d]),Se=u.useMemo(()=>JSON.stringify(Ie),[Ie]),Ge=Se!==ce.current;u.useEffect(()=>{if(Fe.current=Ie,ye.current=Se,Se===ce.current){U(null),_(de=>de==="saved"?de:"idle");return}_(de=>de==="saving"?de:"dirty")},[Se]);const Be=u.useMemo(()=>!C||!kn(C.data.nodeType)?[]:[{id:"overview",eyebrow:C.data.nodeType==="chat"?"Chat node":"Functor node",title:"Define what this node is responsible for",description:"Give the node a clear role in the flow before configuring prompts and models.",render:(de,_e)=>e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Label",description:"This is the name shown on the canvas and in debug traces.",children:e.jsx("input",{value:de.label,onChange:Qe=>_e({label:Qe.target.value}),className:mt})}),e.jsx(le,{label:"Description",description:"Explain what this node should do with the incoming flow context.",children:e.jsx("textarea",{rows:4,value:de.description,onChange:Qe=>_e({description:Qe.target.value}),className:mt})})]})},{id:"prompts",eyebrow:"Prompts",title:"Set the prompt contract",description:"Separate the main prompt from the system instruction so this node stays easier to maintain.",render:(de,_e)=>e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Prompt template",description:"This is the main instruction the node sends with the current flow input.",children:e.jsx("textarea",{rows:8,value:de.promptTemplate??de.prompt??"",onChange:Qe=>_e({promptTemplate:Qe.target.value,prompt:Qe.target.value}),className:mt})}),e.jsx(le,{label:"System prompt",description:"Use this for durable behavior and output rules that should stay consistent.",children:e.jsx("textarea",{rows:5,value:de.systemPrompt??"",onChange:Qe=>_e({systemPrompt:Qe.target.value}),className:mt})})]})},{id:"model",eyebrow:"Model",title:"Choose how this node reaches a model",description:"Pick a specific model connection or leave it on the Forge default once models are configured.",render:(de,_e)=>{var Qe,St,At;return e.jsxs(e.Fragment,{children:[a.length===0?e.jsx("div",{className:"rounded-[20px] border border-amber-400/20 bg-amber-400/10 px-4 py-3 text-sm leading-6 text-amber-100",children:"No model connection is configured yet. Open Settings > Models, add one connection, then come back here."}):null,e.jsx(le,{label:"Model connection",description:"This can stay empty if you want the node to use Forge's default configured model.",children:e.jsxs("select",{value:((Qe=de.modelConfig)==null?void 0:Qe.connectionId)??"",onChange:Nt=>{var Xs,Ys;const ss=a.find(hs=>hs.id===Nt.target.value);_e({modelConfig:{connectionId:(ss==null?void 0:ss.id)??null,provider:(ss==null?void 0:ss.provider)??null,baseUrl:(ss==null?void 0:ss.baseUrl)??null,model:(ss==null?void 0:ss.model)??"",thinking:((Xs=de.modelConfig)==null?void 0:Xs.thinking)??null,verbosity:((Ys=de.modelConfig)==null?void 0:Ys.verbosity)??null}})},className:mt,children:[e.jsx("option",{value:"",children:"Use Forge default model"}),a.map(Nt=>e.jsx("option",{value:Nt.id,children:Nt.label},Nt.id))]})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Thinking effort",description:"Optional reasoning setting for models that support it.",children:e.jsxs("select",{value:((St=de.modelConfig)==null?void 0:St.thinking)??"",onChange:Nt=>{var ss,Xs,Ys,hs,sn;return _e({modelConfig:{connectionId:((ss=de.modelConfig)==null?void 0:ss.connectionId)??null,provider:((Xs=de.modelConfig)==null?void 0:Xs.provider)??null,baseUrl:((Ys=de.modelConfig)==null?void 0:Ys.baseUrl)??null,model:((hs=de.modelConfig)==null?void 0:hs.model)??"",thinking:Nt.target.value||null,verbosity:((sn=de.modelConfig)==null?void 0:sn.verbosity)??null}})},className:mt,children:[e.jsx("option",{value:"",children:"Default"}),e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]})}),e.jsx(le,{label:"Verbosity",description:"Optional output detail setting for models that support it.",children:e.jsxs("select",{value:((At=de.modelConfig)==null?void 0:At.verbosity)??"",onChange:Nt=>{var ss,Xs,Ys,hs,sn;return _e({modelConfig:{connectionId:((ss=de.modelConfig)==null?void 0:ss.connectionId)??null,provider:((Xs=de.modelConfig)==null?void 0:Xs.provider)??null,baseUrl:((Ys=de.modelConfig)==null?void 0:Ys.baseUrl)??null,model:((hs=de.modelConfig)==null?void 0:hs.model)??"",thinking:((sn=de.modelConfig)==null?void 0:sn.thinking)??null,verbosity:Nt.target.value||null}})},className:mt,children:[e.jsx("option",{value:"",children:"Default"}),e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]})})]})]})}},{id:"contracts",eyebrow:"Contracts",title:"Define the input and output contract",description:"Give this AI node truthful port names, value types, and expectations so the graph stays readable.",render:(de,_e)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(so,{title:"Inputs",description:"Name the upstream values this AI node expects to receive.",ports:de.inputs??[],onChange:Qe=>_e({inputs:Qe}),prefix:"input"}),e.jsx(so,{title:"Outputs",description:"Describe exactly what this AI node will publish for later nodes.",ports:de.outputs??[],onChange:Qe=>_e({outputs:Qe}),prefix:"output"})]})},{id:"tools",eyebrow:"Outputs and tools",title:"Control what this node can call and publish",description:"Keep tool access tight and name any extra outputs the rest of the flow should consume.",render:(de,_e)=>e.jsxs(e.Fragment,{children:[e.jsx(le,{label:"Enabled tools",description:"Only checked tools will be available to this AI node during execution.",children:e.jsx("div",{className:"grid max-h-[18rem] gap-2 overflow-y-auto pr-1",children:je.length>0?je.map(Qe=>{const St=(de.enabledToolKeys??[]).includes(Qe.key);return e.jsxs("label",{className:"flex items-start gap-3 rounded-[16px] bg-white/[0.03] px-3 py-2 text-left",children:[e.jsx("input",{type:"checkbox",checked:St,onChange:At=>{const Nt=new Set(de.enabledToolKeys??[]);At.target.checked?Nt.add(Qe.key):Nt.delete(Qe.key),_e({enabledToolKeys:[...Nt]})}}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white",children:[e.jsx("span",{children:Qe.label}),e.jsx("span",{className:"rounded-full bg-white/[0.06] px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] text-white/48",children:Qe.accessMode.replace("_"," ")})]}),e.jsx("div",{className:"text-[12px] leading-5 text-white/46",children:Qe.description}),Qe.sources.length>0?e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Qe.sources.map(At=>e.jsx("span",{className:"rounded-full bg-white/[0.05] px-2 py-1 text-[10px] text-white/44",children:At},`${Qe.key}-${At}`))}):null,e.jsx("div",{className:"mt-1 font-mono text-[10px] text-white/32",children:Qe.key}),Qe.argsSchema?e.jsxs("details",{className:"mt-2 rounded-[14px] border border-white/8 bg-black/20 px-3 py-2",children:[e.jsx("summary",{className:"cursor-pointer text-[11px] text-white/56",children:"Preview tool arguments"}),e.jsx("pre",{className:"mt-2 overflow-auto whitespace-pre-wrap text-[10px] leading-5 text-white/44",children:JSON.stringify(Qe.argsSchema,null,2)})]}):null]})]},Qe.key)}):e.jsx("div",{className:"text-sm text-white/48",children:"No registered Forge tools are available yet."})})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(le,{label:"Enabled tool preview",description:"Collapsed by default in the node card, this is the contract the AI node can call at run time.",children:e.jsxs("details",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm text-white/70",children:we.length>0?`${we.length} tool contract${we.length===1?"":"s"}`:"No tool contract yet"}),e.jsx("pre",{className:"mt-3 overflow-auto whitespace-pre-wrap text-[11px] leading-5 text-white/58",children:JSON.stringify(we.map(Qe=>({key:Qe.key,label:Qe.label,accessMode:Qe.accessMode,sources:Qe.sources,argsSchema:Qe.argsSchema})),null,2)})]})}),e.jsx(le,{label:"Output preview",description:"This is the structure downstream nodes will see from this AI node.",children:e.jsxs("details",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm text-white/70",children:[(de.outputs??[]).length," published output",(de.outputs??[]).length===1?"":"s"]}),e.jsx("pre",{className:"mt-3 overflow-auto whitespace-pre-wrap text-[11px] leading-5 text-white/58",children:JSON.stringify(HM(de.outputs??[]),null,2)})]})})]}),e.jsx(le,{label:"Named outputs",description:"Add comma-separated output keys when later nodes should read more than the primary answer.",children:e.jsx("input",{value:(de.outputs??[]).filter(Qe=>Qe.key!=="answer").map(Qe=>Qe.key).join(", "),onChange:Qe=>_e({outputs:GM(["answer",...Qe.target.value.split(",")])}),placeholder:"summary, plan, next_steps",className:mt})}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Danger zone"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Remove this node from the graph if you no longer need it."}),e.jsxs(z,{type:"button",variant:"secondary",className:"mt-4",onClick:()=>{It(C.id),S(!1)},children:[e.jsx($t,{className:"size-4"}),"Delete node"]})]})]})}],[je,a,we,C]),xe=u.useCallback(async()=>{const de=ye.current,_e=Fe.current;if(de===ce.current)return _("saved"),!0;if(he.current)return me.current=!0,he.current;_("saving"),U(null);const Qe=r(_e).then(()=>(ce.current=de,ue.current=de,_("saved"),!0)).catch(St=>{const At=St instanceof ba||St instanceof Error?St.message:String(St);return U(At),_("error"),!1}).finally(()=>{he.current=null,me.current&&ye.current!==ce.current?(me.current=!1,xe()):me.current=!1});return he.current=Qe,Qe},[r]);u.useEffect(()=>{if(!Ge)return;const de=window.setTimeout(()=>{xe()},2e3);return()=>window.clearTimeout(de)},[Ge,xe,Se]);const Ae=u.useCallback((de,_e="overview")=>{j(de),N(_e),q(_e==="contracts"?"contracts":"overview"),S(!0)},[]),He=u.useMemo(()=>b.map(de=>({...de,data:{...de.data,onEditRequest:()=>Ae(de.id,"overview"),onContractEditRequest:()=>Ae(de.id,"contracts"),onParameterEditRequest:()=>Ae(de.id,"parameters")}})),[b,Ae]);function ot(de){w&&M(_e=>_e.map(Qe=>Qe.id===w?de(Qe):Qe))}function It(de){M(_e=>_e.filter(Qe=>Qe.id!==de)),T(_e=>_e.filter(Qe=>Qe.source!==de&&Qe.target!==de)),j(_e=>_e===de?null:_e)}async function Oe(){await xe()}async function tt(de){if(!await xe()){L("Forge could not save the latest flow changes before running. Fix the save error and try again.");return}const Qe=QM(b,P);if(Qe){L(Qe);return}if(Je&&a.length===0){L(["This flow includes an AI node, but no model is configured in Forge yet.","Open Settings > Models, add a model connection, then try again."].join(`
|
|
90
90
|
|
|
91
91
|
`));return}L(null);const St={};for(const At of p){const Nt=Pe[At.key];if(!DM(At,Nt)){L(`Flow input "${At.label}" must match the ${At.kind} type.`);return}Nt!=null&&!(typeof Nt=="string"&&Nt.trim().length===0)&&(St[At.key]=Nt)}try{de==="run"?await l({userInput:Ze?X:"",inputs:St,debug:fe}):await o({userInput:Ze?X:"",inputs:St,debug:fe}),Y(!1)}catch(At){L(WM(At))}}return e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsxs(Xe,{to:"/workbench",className:"inline-flex h-9 items-center gap-2 rounded-full bg-white/[0.05] px-3 text-sm text-white/68 transition hover:bg-white/[0.08] hover:text-white",children:[e.jsx(_n,{className:"size-4"}),"Flows"]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(Ue,{kind:"workbench",label:"Workbench Flow",compact:!0,gradient:!1}),e.jsx("div",{className:"truncate font-display text-[1.55rem] tracking-[-0.05em] text-white",children:d})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ue,{kind:og(g),label:g==="chat"?"Chat flow":"Functor flow",compact:!0,gradient:!1}),e.jsx("div",{className:Z("rounded-full border px-3 py-2 text-[12px]",D==="error"?"border-rose-300/20 bg-rose-300/10 text-rose-100":D==="saving"?"border-sky-300/20 bg-sky-300/10 text-sky-100":D==="dirty"?"border-amber-300/20 bg-amber-300/10 text-amber-100":"border-emerald-300/20 bg-emerald-300/10 text-emerald-100"),children:OM(D,ee)}),ne?e.jsxs("button",{type:"button",className:"rounded-full bg-white/[0.05] px-3 py-2 text-[12px] text-white/58 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>F(!0),children:["Latest ",ne.mode," · ",ne.status]}):null,e.jsxs(z,{type:"button",variant:"secondary",onClick:()=>Y(!0),children:[e.jsx(Ks,{className:"size-4"}),"Run"]}),e.jsxs(z,{type:"button",variant:"primary",pending:D==="saving",pendingLabel:"Saving…",onClick:()=>void Oe(),children:[e.jsx(ri,{className:"size-4"}),"Save now"]})]})]}),e.jsxs("div",{className:"relative h-[76vh] overflow-hidden rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,15,26,0.98),rgba(7,11,20,0.98))]",children:[qe.length>0?e.jsxs("div",{className:"pointer-events-none absolute left-4 top-4 z-20 max-w-[32rem] rounded-[24px] border border-amber-300/20 bg-[rgba(61,40,9,0.88)] p-4 shadow-[0_18px_48px_rgba(0,0,0,0.35)] backdrop-blur-xl",children:[e.jsxs("div",{className:"pointer-events-auto flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] text-amber-100/76",children:[e.jsx("span",{children:"Graph checks"}),e.jsx(yt,{content:"These are preflight issues Forge found in the current graph before runtime. Fixing them here should prevent brittle run failures later.",label:"Explain graph checks"})]}),e.jsx("ul",{className:"mt-3 grid gap-2 text-sm leading-6 text-amber-50",children:qe.map(de=>e.jsx("li",{className:"list-inside list-disc",children:de},de))})]}):null,e.jsx(Qo,{nodeTypes:UM,nodes:He,edges:P,onNodesChange:de=>M(_e=>Gy(de,_e)),onEdgesChange:de=>T(_e=>Hy(de,_e)),onConnect:de=>T(_e=>Wy({...de,id:`edge_${crypto.randomUUID().replaceAll("-","").slice(0,8)}`,style:{stroke:"rgba(188, 194, 255, 0.44)",strokeWidth:1.6}},_e)),onEdgeClick:(de,_e)=>{T(Qe=>Qe.filter(St=>St.id!==_e.id))},onNodeClick:(de,_e)=>{j(_e.id)},onNodeDoubleClick:(de,_e)=>{Ae(_e.id,"overview")},fitView:!0,proOptions:{hideAttribution:!0},className:"bg-transparent",children:e.jsx(Vo,{color:"rgba(255,255,255,0.055)",gap:28})}),e.jsx("div",{className:"pointer-events-none absolute right-4 bottom-4 z-20 flex flex-col gap-2",children:e.jsxs("div",{className:"pointer-events-auto flex flex-col items-end gap-2",children:[e.jsxs("button",{type:"button",className:"inline-flex h-11 items-center gap-2 rounded-full bg-[rgba(31,41,69,0.92)] px-4 text-sm font-medium text-white shadow-[0_18px_42px_rgba(0,0,0,0.35)] transition hover:bg-[rgba(42,54,88,0.96)]",onClick:()=>y(!0),children:[e.jsx(Ci,{className:"size-4"}),"Add node"]}),e.jsxs("button",{type:"button",className:"inline-flex h-11 items-center gap-2 rounded-full bg-[rgba(31,41,69,0.92)] px-4 text-sm font-medium text-white shadow-[0_18px_42px_rgba(0,0,0,0.35)] transition hover:bg-[rgba(42,54,88,0.96)]",onClick:()=>O(!0),children:[e.jsx(fo,{className:"size-4"}),"Flow settings"]}),e.jsxs("button",{type:"button",className:"inline-flex h-11 items-center gap-2 rounded-full bg-[rgba(31,41,69,0.92)] px-4 text-sm font-medium text-white shadow-[0_18px_42px_rgba(0,0,0,0.35)] transition hover:bg-[rgba(42,54,88,0.96)]",onClick:()=>Y(!0),children:[e.jsx(Ks,{className:"size-4"}),"Run flow"]}),ne?e.jsxs("button",{type:"button",className:"inline-flex h-11 items-center gap-2 rounded-full bg-[rgba(31,41,69,0.92)] px-4 text-sm font-medium text-white shadow-[0_18px_42px_rgba(0,0,0,0.35)] transition hover:bg-[rgba(42,54,88,0.96)]",onClick:()=>F(!0),children:[e.jsx(Qy,{className:"size-4"}),"Latest trace"]}):null]})})]}),e.jsx(bn,{open:v,onOpenChange:y,title:"Add node",description:"Add a Forge box, AI node, or utility node to the flow.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:[{type:"user_input",label:"User input",icon:e.jsx(eg,{className:"size-4"})},{type:"value",label:"Value",icon:e.jsx(tg,{className:"size-4"})},{type:"functor",label:"Functor",icon:e.jsx(Ht,{className:"size-4"})},{type:"chat",label:"Chat",icon:e.jsx(ii,{className:"size-4"})},{type:"merge",label:"Merge",icon:e.jsx(sg,{className:"size-4"})},{type:"template",label:"Template",icon:e.jsx(vo,{className:"size-4"})},{type:"pick_key",label:"Pick key",icon:e.jsx(ag,{className:"size-4"})},{type:"output",label:"Output",icon:e.jsx(ig,{className:"size-4"})}].map(de=>e.jsxs("button",{type:"button",className:"flex items-center gap-3 rounded-[20px] bg-white/[0.04] px-4 py-3 text-left text-white transition hover:bg-white/[0.08]",onClick:()=>{M(_e=>[..._e,Tx(de.type,_e)]),y(!1)},children:[de.icon,e.jsx("span",{children:de.label})]},de.type))}),e.jsx(di,{title:"Forge boxes",description:"",query:H,onQueryChange:G,options:Ke,selectedOptionIds:$,onSelectedOptionIdsChange:Q,resultSummary:`${ge.length} boxes`,placeholder:"Search visible Forge boxes by title, route, or category",emptyStateMessage:"No boxes match the current query."}),e.jsx("div",{className:"grid max-h-[18rem] gap-2 overflow-auto pr-1",children:ge.map(de=>e.jsxs("button",{type:"button",className:"rounded-[20px] bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.08]",onClick:()=>{M(_e=>[..._e,Tx("box",_e,de)]),y(!1)},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:de.title}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2 text-[10px] uppercase tracking-[0.14em] text-white/42",children:[e.jsxs("span",{children:[de.output.length," output",de.output.length===1?"":"s"]}),e.jsxs("span",{children:[de.tools.length," tool",de.tools.length===1?"":"s"]})]})]}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/50",children:de.description}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("div",{className:"rounded-full bg-white/[0.05] px-2.5 py-1 text-[11px] text-white/56",children:de.category}),de.routePath?e.jsx("div",{className:"rounded-full bg-white/[0.05] px-2.5 py-1 text-[11px] text-white/56",children:de.routePath}):null]})]},de.id))})]})}),C&&kn(C.data.nodeType)?e.jsx(Lt,{open:E,onOpenChange:de=>{S(de),de||q(void 0)},eyebrow:`Workbench · ${C.data.nodeType==="chat"?"Chat node":"Functor node"}`,title:C.data.label??"Edit node",description:"Configure this AI node with the same paged editor Forge uses elsewhere.",value:C.data,onChange:de=>ot(_e=>({..._e,data:de})),steps:Be,initialStepId:A,onSubmit:async()=>{S(!1),q(void 0)},submitLabel:"Done",contentClassName:"md:w-[min(60rem,calc(100vw-1.5rem))]"}):e.jsx(bn,{open:E,onOpenChange:de=>{S(de),de||N("overview")},title:(C==null?void 0:C.data.label)??"Edit node",description:"Edit the selected node without covering the graph with permanent forms.",children:C?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2 rounded-full bg-white/[0.04] p-1",children:[{id:"overview",label:"Overview"},{id:"contracts",label:"Contracts"},{id:"parameters",label:"Parameters"}].filter(de=>de.id!=="contracts"||re).filter(de=>{var _e;return de.id!=="parameters"||(((_e=C.data.params)==null?void 0:_e.length)??0)>0}).map(de=>e.jsx("button",{type:"button",className:Z("rounded-full px-3 py-2 text-sm transition",B===de.id?"bg-[rgba(192,193,255,0.18)] text-white":"text-white/58 hover:bg-white/[0.05] hover:text-white"),onClick:()=>N(de.id),children:de.label},de.id))}),B==="overview"?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("input",{value:C.data.label,onChange:de=>ot(_e=>({..._e,data:{..._e.data,label:de.target.value}})),className:mt}),e.jsx("textarea",{rows:3,value:C.data.description,onChange:de=>ot(_e=>({..._e,data:{..._e.data,description:de.target.value}})),className:mt}),C.data.nodeType==="box"||C.data.nodeType==="box_input"?e.jsxs("select",{value:C.data.boxId??"",onChange:de=>{const _e=s.find(Qe=>Qe.id===de.target.value);ot(Qe=>({...Qe,data:{...Qe.data,boxId:de.target.value,label:(_e==null?void 0:_e.title)??Qe.data.label,description:(_e==null?void 0:_e.description)??Qe.data.description,inputs:(_e==null?void 0:_e.inputs)??[],outputs:(_e==null?void 0:_e.output)??[],params:(_e==null?void 0:_e.params)??[],enabledToolKeys:((_e==null?void 0:_e.tools)??[]).map(St=>St.key)}}))},className:mt,children:[e.jsx("option",{value:"",children:"Select Forge box"}),s.map(de=>e.jsx("option",{value:de.id,children:de.title},de.id))]}):null,C.data.nodeType==="template"?e.jsx("textarea",{rows:4,value:C.data.template??"",onChange:de=>ot(_e=>({..._e,data:{..._e.data,template:de.target.value}})),placeholder:"Template string",className:mt}):null,C.data.nodeType==="pick_key"?e.jsx("input",{value:C.data.selectedKey??"",onChange:de=>ot(_e=>({..._e,data:{..._e.data,selectedKey:de.target.value}})),placeholder:"Key to select from object input",className:mt}):null,C.data.nodeType==="output"?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("select",{value:C.data.outputKey??"answer",onChange:de=>ot(_e=>({..._e,data:{..._e.data,outputKey:de.target.value}})),className:mt,children:oe.length>0?oe.map(de=>e.jsxs("option",{value:de.key,children:[de.label," (",de.key,")"]},de.key)):e.jsx("option",{value:C.data.outputKey??"answer",children:C.data.outputKey??"answer"})}),e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm leading-6 text-white/58",children:"Publish one upstream output as the flow result. If the output key is missing from the graph, Forge will flag it in graph checks."})]}):null,C.data.nodeType==="value"?e.jsxs(e.Fragment,{children:[e.jsx("select",{value:C.data.valueType??"string",onChange:de=>ot(_e=>({..._e,data:{..._e.data,valueType:de.target.value}})),className:mt,children:["string","number","boolean","null","array","object"].map(de=>e.jsx("option",{value:de,children:de},de))}),e.jsx("textarea",{rows:4,value:C.data.valueLiteral??"",onChange:de=>ot(_e=>({..._e,data:{..._e.data,valueLiteral:de.target.value}})),placeholder:"Value literal or JSON",className:mt})]}):null]}):null,B==="contracts"?re?e.jsxs("div",{className:"grid gap-4",children:[e.jsx(so,{title:"Inputs",description:"Name the values this node expects so upstream wiring stays obvious.",ports:C.data.inputs??[],onChange:de=>ot(_e=>({..._e,data:{..._e.data,inputs:de}})),prefix:"input"}),e.jsx(so,{title:"Outputs",description:"Describe exactly what this node publishes, including semantic model names.",ports:C.data.outputs??[],onChange:de=>ot(_e=>({..._e,data:{..._e.data,outputs:de}})),prefix:"output"})]}):e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm leading-6 text-white/58",children:"This node inherits its contract from the registered Forge box. Edit the box definition in the registry when the contract itself needs to change."}):null,B==="parameters"?e.jsxs("div",{className:"grid gap-3",children:[(C.data.params??[]).length===0?e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm leading-6 text-white/58",children:"This node does not expose any configurable parameters."}):null,(C.data.params??[]).map(de=>{var _e,Qe,St;return e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:de.label}),de.kind==="boolean"?e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] border border-white/10 bg-black/20 px-4 py-3 text-sm text-white",children:[e.jsx("input",{type:"checkbox",checked:!!((_e=C.data.paramValues)!=null&&_e[de.key]),onChange:At=>ot(Nt=>({...Nt,data:{...Nt.data,paramValues:{...Nt.data.paramValues??{},[de.key]:At.target.checked}}}))}),de.description??"Enabled"]}):de.kind==="array"||de.kind==="json"?e.jsx("textarea",{value:po((Qe=C.data.paramValues)==null?void 0:Qe[de.key]),onChange:At=>ot(Nt=>({...Nt,data:{...Nt.data,paramValues:{...Nt.data.paramValues??{},[de.key]:At.target.value}}})),placeholder:de.description??de.label,className:Z(mt,"min-h-[104px] resize-y")}):e.jsx("input",{type:de.kind==="number"?"number":"text",value:po((St=C.data.paramValues)==null?void 0:St[de.key]),onChange:At=>ot(Nt=>({...Nt,data:{...Nt.data,paramValues:{...Nt.data.paramValues??{},[de.key]:aw(de.kind,At.target.value)}}})),placeholder:de.description??de.label,className:mt})]},de.key)})]}):null,e.jsxs("div",{className:"flex flex-wrap justify-between gap-2 pt-2",children:[e.jsxs(z,{type:"button",variant:"secondary",onClick:()=>{It(C.id),S(!1)},children:[e.jsx($t,{className:"size-4"}),"Delete node"]}),e.jsx(z,{type:"button",variant:"primary",onClick:()=>{S(!1),N("overview")},children:"Done"})]})]}):null}),e.jsx(bn,{open:K,onOpenChange:O,title:"Flow settings",description:"Edit the flow identity and persistence without covering the graph with permanent forms.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx("input",{value:d,onChange:de=>h(de.target.value),placeholder:"Flow title",className:mt}),e.jsx("textarea",{rows:4,value:m,onChange:de=>c(de.target.value),placeholder:"Flow description",className:mt}),e.jsxs("select",{value:g,onChange:de=>x(de.target.value),className:mt,children:[e.jsx("option",{value:"functor",children:"Functor flow"}),e.jsx("option",{value:"chat",children:"Chat flow"})]}),e.jsx(qM,{inputs:p,nodes:b,onChange:f}),e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/58",children:t.id}),e.jsxs("div",{className:"flex flex-wrap justify-between gap-2 pt-2",children:[e.jsxs(z,{type:"button",variant:"secondary",onClick:async()=>{await n()},children:[e.jsx($t,{className:"size-4"}),"Delete flow"]}),e.jsxs(z,{type:"button",variant:"primary",onClick:async()=>{await Oe(),O(!1)},children:[e.jsx(ri,{className:"size-4"}),"Save settings"]})]})]})}),e.jsx(bn,{open:W,onOpenChange:de=>{Y(de),de&&L(null)},title:"Run flow",description:"Run the flow or chat with it and keep the debug trace for every node.",children:e.jsxs("div",{className:"grid gap-3",children:[Ce?e.jsx("div",{className:"rounded-[20px] border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm leading-6 text-rose-100",children:Ce}):null,!Ce&&qe.length>0?e.jsxs("div",{className:"rounded-[20px] border border-amber-400/20 bg-amber-400/10 px-4 py-3 text-sm leading-6 text-amber-100",children:[e.jsx("div",{className:"font-medium",children:"Fix these graph issues before running:"}),e.jsx("ul",{className:"mt-2 grid gap-1",children:qe.slice(0,4).map(de=>e.jsxs("li",{children:["• ",de]},de))})]}):null,!Ce&&Je&&a.length===0?e.jsx("div",{className:"rounded-[20px] border border-sky-400/20 bg-sky-400/10 px-4 py-3 text-sm leading-6 text-sky-100",children:"This flow contains AI nodes, but Forge does not have a model connection yet. Open Settings > Models, add one connection, then come back and run the flow."}):null,p.length>0?e.jsxs("div",{className:"grid gap-3 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",children:["Flow inputs",e.jsx(yt,{content:"These are the typed inputs this flow exposes through the API and the Run modal.",label:"Explain flow inputs"})]}),e.jsx("div",{className:"grid gap-3",children:p.map(de=>e.jsx(le,{label:de.label,description:de.description||"Typed input for this flow.",children:de.kind==="boolean"?e.jsxs("label",{className:"flex items-center gap-2 text-sm text-white/68",children:[e.jsx("input",{type:"checkbox",checked:!!Pe[de.key],onChange:_e=>Ne(Qe=>({...Qe,[de.key]:_e.target.checked}))}),de.label]}):de.kind==="number"?e.jsx("input",{type:"number",value:typeof Pe[de.key]=="number"?String(Pe[de.key]):"",onChange:_e=>Ne(Qe=>({...Qe,[de.key]:_e.target.value.trim().length===0?void 0:Number(_e.target.value)})),className:mt}):de.kind==="array"||de.kind==="entity_list"||de.kind==="record_list"||de.kind==="object"||de.kind==="json"||de.kind==="record"||de.kind==="context"||de.kind==="filters"||de.kind==="metrics"||de.kind==="timeline"||de.kind==="selection"||de.kind==="entity"?e.jsx("textarea",{rows:4,value:po(Pe[de.key]),onChange:_e=>{const Qe=_e.target.value;let St=Qe;if(!Qe.trim())St=void 0;else try{St=JSON.parse(Qe)}catch{St=Qe}Ne(At=>({...At,[de.key]:St}))},placeholder:'{"key":"value"}',className:mt}):e.jsx("input",{value:typeof Pe[de.key]=="string"?Pe[de.key]:"",onChange:_e=>Ne(Qe=>({...Qe,[de.key]:_e.target.value})),placeholder:de.exampleValue||de.label,className:mt})},de.key))})]}):null,Ze?e.jsx("textarea",{rows:5,value:X,onChange:de=>ae(de.target.value),placeholder:"User input",className:mt}):null,e.jsxs("label",{className:"flex items-center gap-2 text-sm text-white/64",children:[e.jsx("input",{type:"checkbox",checked:fe,onChange:de=>V(de.target.checked)}),"Return debug trace"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{type:"button",variant:"primary",onClick:()=>void tt("run"),children:[e.jsx(Ks,{className:"size-4"}),"Run"]}),e.jsxs(z,{type:"button",variant:"secondary",onClick:()=>void tt("chat"),children:[e.jsx(rg,{className:"size-4"}),"Chat"]})]}),e.jsx("div",{className:"grid gap-2 pt-2",children:i.slice(0,5).map(de=>{var _e;return e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[12px] text-white/48",children:[e.jsx("span",{children:de.mode}),e.jsx("span",{children:new Date(de.createdAt).toLocaleString()})]}),e.jsx("div",{className:"mt-2 text-sm text-white/78",children:((_e=de.result)==null?void 0:_e.primaryText)??de.error??"No output yet."})]},de.id)})})]})}),e.jsx(bn,{open:R,onOpenChange:F,title:"Run inspector",description:"Inspect whole-flow outputs and stable node-level results for any saved run.",children:Re?e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-[0.9fr_1.1fr]",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Run history"}),e.jsx("div",{className:"mt-3 grid gap-2",children:i.slice(0,12).map(de=>{var _e;return e.jsxs("button",{type:"button",className:Z("rounded-[18px] border px-4 py-3 text-left transition",te===de.id?"border-[var(--secondary)]/40 bg-[var(--secondary)]/12":"border-white/8 bg-black/20 hover:bg-white/[0.05]"),onClick:()=>J(de.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[12px] text-white/50",children:[e.jsx("span",{children:de.mode}),e.jsx("span",{children:new Date(de.createdAt).toLocaleString()})]}),e.jsx("div",{className:"mt-2 text-sm text-white/80",children:((_e=de.result)==null?void 0:_e.primaryText)??de.error??"No output yet."})]},de.id)})})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-[12px] text-white/50",children:[e.jsx("span",{children:Re.mode}),e.jsx("span",{children:new Date(Re.createdAt).toLocaleString()})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/82",children:((ze=Re.result)==null?void 0:ze.primaryText)??Re.error??"No output yet."}),(We=Re.result)!=null&&We.outputs?e.jsxs("details",{className:"mt-3 rounded-[16px] bg-black/20 p-3",children:[e.jsx("summary",{className:"cursor-pointer text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Published outputs"}),e.jsx("pre",{className:"mt-3 overflow-auto whitespace-pre-wrap text-[12px] leading-5 text-white/66",children:JSON.stringify(Re.result.outputs,null,2)})]}):null]}),(((gt=at.data)==null?void 0:gt.nodeResults)??[]).length>0?e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[0.9fr_1.1fr]",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Node results"}),e.jsx("div",{className:"mt-3 grid gap-2",children:(((Mt=at.data)==null?void 0:Mt.nodeResults)??[]).map(de=>e.jsx("button",{type:"button",className:Z("rounded-[18px] border px-4 py-3 text-left transition",ve===de.nodeId?"border-[var(--secondary)]/40 bg-[var(--secondary)]/12":"border-white/8 bg-black/20 hover:bg-white/[0.05]"),onClick:()=>pe(de.nodeId),children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:de.label}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:de.nodeType})]}),e.jsxs("div",{className:"rounded-full bg-white/[0.05] px-3 py-1 text-[11px] text-white/56",children:[Object.keys(de.outputMap).length," outputs"]})]})},de.nodeId))})]}),e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-4",children:lt||(Qt=Te.data)!=null&&Qt.nodeResult?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:(_a=((Ds=Te.data)==null?void 0:Ds.nodeResult)??lt)==null?void 0:_a.label}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:(Wr=((Ra=Te.data)==null?void 0:Ra.nodeResult)??lt)==null?void 0:Wr.nodeType})]}),e.jsxs("div",{className:"rounded-full bg-white/[0.05] px-3 py-1 text-[11px] text-white/56",children:[(((Gr=((Hr=Te.data)==null?void 0:Hr.nodeResult)??lt)==null?void 0:Gr.tools)??[]).length," tool",(((Vr=((Qr=Te.data)==null?void 0:Qr.nodeResult)??lt)==null?void 0:Vr.tools)??[]).length===1?"":"s"]})]}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsxs("details",{className:"rounded-[16px] bg-black/20 p-3",children:[e.jsx("summary",{className:"cursor-pointer text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Inputs"}),e.jsx("pre",{className:"mt-3 overflow-auto whitespace-pre-wrap text-[12px] leading-5 text-white/66",children:JSON.stringify(((Yr=((Xr=Te.data)==null?void 0:Xr.nodeResult)??lt)==null?void 0:Yr.input)??[],null,2)})]}),e.jsxs("details",{className:"rounded-[16px] bg-black/20 p-3",children:[e.jsx("summary",{className:"cursor-pointer text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Output map"}),e.jsx("pre",{className:"mt-3 overflow-auto whitespace-pre-wrap text-[12px] leading-5 text-white/66",children:JSON.stringify(((Zr=((Jr=Te.data)==null?void 0:Jr.nodeResult)??lt)==null?void 0:Zr.outputMap)??{},null,2)})]}),e.jsxs("details",{className:"rounded-[16px] bg-black/20 p-3",children:[e.jsx("summary",{className:"cursor-pointer text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Payload"}),e.jsx("pre",{className:"mt-3 overflow-auto whitespace-pre-wrap text-[12px] leading-5 text-white/66",children:JSON.stringify(((tn=((en=Te.data)==null?void 0:en.nodeResult)??lt)==null?void 0:tn.payload)??null,null,2)})]})]})]}):e.jsx("div",{className:"text-sm text-white/56",children:"Pick a node result to inspect its resolved inputs and outputs."})})]}):e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-4 text-sm text-white/56",children:at.isFetching?"Loading node results…":"This run does not have stored node results yet."})]})]})}):e.jsx("div",{className:"text-sm text-white/56",children:"Run the flow once to inspect its published outputs and node-level results here."})})]})}function XM(){const t=Us(),s=_t(),a=t.flowId??"",i=e5(),r=l2(a,{skip:a.length===0}),n=af(),[l]=w2(),[o]=m2(),[d]=v2(),[h]=h2();return r.isLoading||n.isLoading?e.jsx(Et,{eyebrow:"Workbench Flow",title:"Loading flow",description:"Preparing the Workbench graph editor."}):r.isError||n.isError||!r.data?!r.data&&!r.isError&&!n.isError?e.jsx(Bt,{eyebrow:"Workbench Flow",title:"Flow unavailable",description:"Forge could not find that flow."}):e.jsx(st,{eyebrow:"Workbench Flow",error:r.error??n.error??null}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(rt,{entityKind:r.data.flow.kind,title:r.data.flow.title,titleText:r.data.flow.title,description:r.data.flow.description||"Inspect, run, and publish this Workbench flow.",badge:r.data.flow.kind,actions:e.jsx(Bi,{entityType:"workbench_flow",entityId:r.data.flow.id})}),e.jsx(VM,{flow:r.data.flow,boxes:i,modelConnections:(n.data.settings.modelSettings.connections??[]).map(m=>({id:m.id,label:m.label,provider:m.provider,model:m.model,baseUrl:m.baseUrl})),runs:r.data.runs,onSave:async m=>{await l({flowId:a,patch:m}).unwrap()},onDelete:async()=>{await o(a).unwrap(),s("/workbench")},onRun:async m=>{await d({flowId:a,input:m}).unwrap()},onChat:async m=>{await h({flowId:a,input:m}).unwrap()}})]})}function YM(){const t=ci();return u.useEffect(()=>{const s=`${t.pathname}${t.search}${t.hash}`,a=xg({scope:"frontend_runtime",route:s}),i=n=>{a({level:"error",eventKey:"window_error",message:n.message||"Unhandled browser error",functionName:"window.onerror",details:{fileName:n.filename||null,line:n.lineno||null,column:n.colno||null,error:n.error??null}})},r=n=>{a({level:"error",eventKey:"unhandled_rejection",message:"Unhandled promise rejection",functionName:"window.onunhandledrejection",details:{reason:n.reason??null}})};return window.addEventListener("error",i),window.addEventListener("unhandledrejection",r),()=>{window.removeEventListener("error",i),window.removeEventListener("unhandledrejection",r)}},[t.hash,t.pathname,t.search]),u.useEffect(()=>{const s=`${t.pathname}${t.search}${t.hash}`;yo({level:"info",scope:"frontend_navigation",eventKey:"route_view",message:`Viewed route ${t.pathname}`,route:s,functionName:"DiagnosticsBootstrap.routeView",details:{pathname:t.pathname,search:t.search||null,hash:t.hash||null}})},[t.hash,t.pathname,t.search]),null}function JM(){function t(s,a,i,r){return e.jsx(a5,{surfaceId:s,children:r})}return e.jsxs(Z4,{children:[e.jsx(YM,{}),e.jsxs(Vy,{children:[e.jsxs(et,{element:e.jsx(PS,{}),children:[e.jsx(et,{index:!0,element:e.jsx(jd,{to:"/overview",replace:!0})}),e.jsx(et,{path:"overview",element:e.jsx(j3,{})}),e.jsx(et,{path:"life-force",element:t("life-force-index","Life Force","Action Point capacity, weekday curves, and dynamic drains.",e.jsx(gI,{}))}),e.jsx(et,{path:"goals",element:t("goals-index","Goals","Goal planning and long-horizon direction.",e.jsx(T5,{}))}),e.jsx(et,{path:"habits",element:t("habits-index","Habits","Recurring commitments, streaks, and check-ins.",e.jsx(B5,{}))}),e.jsx(et,{path:"goals/:goalId",element:t("goal-detail","Goal detail","Goal detail, progress, and linked execution context.",e.jsx(S5,{}))}),e.jsx(et,{path:"projects",element:e.jsx(B3,{})}),e.jsx(et,{path:"projects/hierarchy",element:t("project-hierarchy","Project hierarchy","Full hierarchy from goals down to subtasks.",e.jsx(R3,{}))}),e.jsx(et,{path:"projects/:projectId",element:t("project-detail","Project detail","Project detail, tasks, and execution health.",e.jsx(P3,{}))}),e.jsx(et,{path:"strategies",element:t("strategies-index","Strategies","Strategy graphs and long-range execution plans.",e.jsx(a8,{}))}),e.jsx(et,{path:"strategies/:strategyId",element:t("strategy-detail","Strategy detail","Strategy DAG detail, targets, and progress.",e.jsx(c8,{}))}),e.jsx(et,{path:"preferences",element:t("preferences-index","Preferences","Preference profiles, pairwise judgments, and model state.",e.jsx(b8,{}))}),e.jsx(et,{path:"campaigns",element:e.jsx(jd,{to:"/projects",replace:!0})}),e.jsx(et,{path:"calendar",element:t("calendar-index","Calendar","Calendar planning, timeboxes, and provider sync.",e.jsx(w5,{}))}),e.jsx(et,{path:"knowledge-graph",element:t("knowledge-graph-index","Knowledge Graph","One connected map of Forge entities and explicit relationships.",e.jsx(tI,{}))}),e.jsx(et,{path:"movement",element:t("movement-index","Movement","Movement traces, places, and trip evidence.",e.jsx(YI,{}))}),e.jsx(et,{path:"sleep",element:t("sleep-index","Sleep","Sleep sessions, health context, and recovery trends.",e.jsx(_A,{}))}),e.jsx(et,{path:"sports",element:t("sports-index","Sports","Fitness, workouts, and sports context.",e.jsx(KA,{}))}),e.jsx(et,{path:"vitals",element:t("vitals-index","Vitals","Body signals, recovery, cardio fitness, and daily HealthKit metrics.",e.jsx(tM,{}))}),e.jsx(et,{path:"psyche",element:e.jsx(P8,{})}),e.jsx(et,{path:"psyche/values",element:t("psyche-values","Psyche values","Values and linked goal context.",e.jsx(lP,{}))}),e.jsx(et,{path:"psyche/patterns",element:t("psyche-patterns","Psyche patterns","Behavior patterns and recurring loops.",e.jsx(aT,{}))}),e.jsx(et,{path:"psyche/questionnaires",element:t("psyche-questionnaires","Questionnaires","Questionnaire library and recent runs.",e.jsx(yT,{}))}),e.jsx(et,{path:"psyche/questionnaires/new",element:t("psyche-questionnaire-new","New questionnaire","Questionnaire builder workspace.",e.jsx(Wp,{}))}),e.jsx(et,{path:"psyche/questionnaires/:instrumentId",element:t("psyche-questionnaire-detail","Questionnaire detail","Questionnaire detail and scores.",e.jsx(oT,{}))}),e.jsx(et,{path:"psyche/questionnaires/:instrumentId/edit",element:t("psyche-questionnaire-edit","Edit questionnaire","Questionnaire builder workspace.",e.jsx(Wp,{}))}),e.jsx(et,{path:"psyche/questionnaires/:instrumentId/take",element:t("psyche-questionnaire-run","Take questionnaire","Questionnaire runner and answers.",e.jsx(bT,{}))}),e.jsx(et,{path:"psyche/questionnaire-runs/:runId",element:t("psyche-questionnaire-run-detail","Questionnaire run detail","Questionnaire result review.",e.jsx(dT,{}))}),e.jsx(et,{path:"psyche/self-observation",element:t("psyche-self-observation","Self observation","Self-observation notes and reflective tracking.",e.jsx(eP,{}))}),e.jsx(et,{path:"psyche/screen-time",element:t("psyche-screen-time","Screen Time","Apple-compliant device-activity patterns and reflective usage history.",e.jsx(aP,{}))}),e.jsx(et,{path:"psyche/behaviors",element:t("psyche-behaviors","Behaviors","Behavior records and linked evidence.",e.jsx(K8,{}))}),e.jsx(et,{path:"psyche/reports",element:t("psyche-reports","Reports","Trigger and reflective report review.",e.jsx(ET,{}))}),e.jsx(et,{path:"psyche/reports/:reportId",element:t("psyche-report-detail","Report detail","Detailed reflective report view.",e.jsx(AT,{}))}),e.jsx(et,{path:"psyche/goal-map",element:t("psyche-goal-map","Goal map","Goal-to-values relationship map.",e.jsx(q8,{}))}),e.jsx(et,{path:"psyche/schemas-beliefs",element:t("psyche-schemas-beliefs","Schemas and beliefs","Beliefs, schemas, and linked patterns.",e.jsx(rP,{}))}),e.jsx(et,{path:"psyche/modes",element:t("psyche-modes","Modes","Mode profiles and guides.",e.jsx(X8,{}))}),e.jsx(et,{path:"psyche/modes/guide",element:t("psyche-mode-guide","Mode guide","Guided mode session flow.",e.jsx(H8,{}))}),e.jsx(et,{path:"kanban",element:t("kanban-index","Kanban","Task board execution surface.",e.jsx(pC,{}))}),e.jsx(et,{path:"notes",element:t("notes-index","Notes","Notes, evidence, and writing surfaces.",e.jsx(r3,{}))}),e.jsx(et,{path:"wiki",element:t("wiki-index","KarpaWiki","KarpaWiki search and page navigation.",e.jsx(jx,{}))}),e.jsx(et,{path:"wiki/ingest-history",element:t("wiki-ingest-history","KarpaWiki ingest history","Ingest jobs and processing history.",e.jsx(jM,{}))}),e.jsx(et,{path:"wiki/page/:slug",element:t("wiki-page-detail","KarpaWiki page","KarpaWiki page detail and backlinks.",e.jsx(jx,{}))}),e.jsx(et,{path:"wiki/new",element:t("wiki-new","New KarpaWiki page","KarpaWiki editor for new pages.",e.jsx(Sx,{}))}),e.jsx(et,{path:"wiki/edit/:pageId",element:t("wiki-edit","Edit KarpaWiki page","KarpaWiki editor for existing pages.",e.jsx(Sx,{}))}),e.jsx(et,{path:"today",element:e.jsx(YA,{})}),e.jsx(et,{path:"workbench",element:t("workbench","Workbench","Search, organize, and launch Forge flows.",e.jsx(MM,{}))}),e.jsx(et,{path:"workbench/:flowId",element:t("workbench-flow","Workbench flow","Graph editor and runtime surface for a single flow.",e.jsx(XM,{}))}),e.jsx(et,{path:"activity",element:t("activity-index","Activity","Activity log and event history.",e.jsx(n5,{}))}),e.jsx(et,{path:"insights",element:t("insights-index","Insights","Insight review and decisions.",e.jsx(iC,{}))}),e.jsx(et,{path:"review/weekly",element:t("weekly-review","Weekly review","Weekly review workflow and closeout.",e.jsx(AM,{}))}),e.jsx(et,{path:"settings",element:t("settings-index","Settings","Operator settings and runtime configuration.",e.jsx(cP,{}))}),e.jsx(et,{path:"settings/data",element:t("settings-data","Settings data","Runtime storage, backups, exports, and recovery.",e.jsx(pP,{}))}),e.jsx(et,{path:"settings/users",element:t("settings-users","Settings users","User directory and ownership settings.",e.jsx(vA,{}))}),e.jsx(et,{path:"settings/calendar",element:t("settings-calendar","Settings calendar","Calendar provider settings and sync.",e.jsx(zP,{}))}),e.jsx(et,{path:"settings/mobile",element:t("settings-mobile","Settings mobile","Mobile companion settings and pairing.",e.jsx(HP,{}))}),null,e.jsx(et,{path:"settings/models",element:t("settings-models","Settings models","Model connections and defaults.",e.jsx(QP,{}))}),e.jsx(et,{path:"settings/agents",element:t("settings-agents","Settings agents","Agent tokens and runtime access.",e.jsx(vP,{}))}),e.jsx(et,{path:"settings/rewards",element:t("settings-rewards","Settings rewards","Rewards and XP rule settings.",e.jsx(dA,{}))}),e.jsx(et,{path:"settings/wiki",element:t("settings-wiki","KarpaWiki settings","KarpaWiki ingestion and profile settings.",e.jsx(Q3,{}))}),e.jsx(et,{path:"settings/logs",element:t("settings-logs","Settings logs","Diagnostics and event logs.",e.jsx(iA,{}))}),e.jsx(et,{path:"settings/bin",element:t("settings-bin","Settings bin","Deleted entity recovery.",e.jsx(jP,{}))}),e.jsx(et,{path:"tasks/:taskId",element:t("task-detail","Task detail","Task detail, timer, and notes.",e.jsx(qA,{}))})]}),e.jsx(et,{path:"*",element:e.jsx(jd,{to:"/overview",replace:!0})})]})]})}const ZM=new Xy({defaultOptions:{queries:{staleTime:2e4,refetchOnWindowFocus:!1}}});Yy.createRoot(document.getElementById("root")).render(e.jsx(Jy.StrictMode,{children:e.jsx(Zy,{store:mf,children:e.jsx(e0,{client:ZM,children:e.jsx(t0,{basename:T0("/forge/"),children:e.jsx(JM,{})})})})}));
|
|
92
|
-
//# sourceMappingURL=index-
|
|
92
|
+
//# sourceMappingURL=index-BuExFDtM.js.map
|