forge-openclaw-plugin 0.2.54 → 0.2.55

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.
@@ -24,7 +24,7 @@ ${o.trim()}`,author:"Forge quick capture",userId:s??null,links:[]}),onSuccess:as
24
24
  Recommendation: ${t.recommendation.trim()}`.trim()}}function YI(t){return{...BI,title:zm(t.title,t.recommendation),description:`${t.summary.trim()}
25
25
 
26
26
  Recommendation: ${t.recommendation.trim()}`.trim()}}function JI(t){return[`## ${t.title.trim()}`,"",t.summary.trim(),"","### Recommendation","",t.recommendation.trim(),t.rationale.trim()?"":null,t.rationale.trim()?"### Why this matters":null,t.rationale.trim()||null].filter(s=>!!s).join(`
27
- `)}function xp(t,s,a,i){return{kind:QI(t,s,a),task:VI(t,a,i),project:XI(t,s,a,i),goal:YI(t),noteMarkdown:JI(t)}}function ZI(t){switch(t){case"task":return{label:"Task",description:"Turn the recommendation into one concrete next move."};case"project":return{label:"Project",description:"Start a larger initiative when the insight needs a stream of work."};case"goal":return{label:"Goal",description:"Capture a new long-term direction when this changes strategy."};case"note":return{label:"Linked note",description:"Attach the recommendation as durable evidence without creating new work."}}}function e3({open:t,onOpenChange:s,insight:a,goals:i,projects:r,tasks:n,tags:l,pending:o=!1,onSubmit:d}){const m=c.useMemo(()=>rw(a,i,r),[i,a,r]),h=c.useMemo(()=>Km(a),[a]),[u,x]=c.useState(()=>xp(a,i,r,n)),[g,p]=c.useState(null),[f,b]=c.useState({});c.useEffect(()=>{t&&(x(xp(a,i,r,n)),p(null),b({}))},[i,a,t,r,n]);const A=u.task.projectId?r.find(S=>S.id===u.task.projectId)??null:null;c.useEffect(()=>{A&&u.task.goalId!==A.goalId&&x(S=>({...S,task:{...S.task,goalId:A.goalId}}))},[u.task.goalId,A]);const C=u.project.goalId?i.find(S=>S.id===u.project.goalId)??null:null,T=c.useMemo(()=>{var S,y,N;if(!h)return null;switch(h.entityType){case"goal":return((S=i.find(P=>P.id===h.entityId))==null?void 0:S.title)??"Linked goal";case"project":return((y=r.find(P=>P.id===h.entityId))==null?void 0:y.title)??"Linked project";case"task":return((N=n.find(P=>P.id===h.entityId))==null?void 0:N.title)??"Linked task";default:return`${h.entityType.replaceAll("_"," ")}`}},[i,r,h,n]),w=[{id:"kind",eyebrow:"Apply",title:"Choose what this insight should become",description:"Accept means you agree with the recommendation. Apply means you turn it into a real record right now.",render:(S,y)=>e.jsx(de,{label:"Apply as",description:"Pick the kind of record Forge should create from this recommendation.",hint:"Task is the best default when the insight points to a concrete next move.",children:e.jsx(wt,{value:S.kind,onChange:N=>y({kind:N}),options:m.map(N=>({value:N,...ZI(N)})),columns:m.length>=3?3:2})})},{id:"details",eyebrow:"Details",title:"Review the record Forge will create",description:"The fields are prefilled from the insight, but you can tighten them before saving.",render:(S,y)=>S.kind==="task"?e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Task title",error:f.title??null,children:e.jsx(ye,{value:S.task.title,onChange:N=>y({task:{...S.task,title:N.target.value}}),placeholder:"Turn the recommendation into a task"})}),e.jsx(de,{label:"Description",children:e.jsx(Ze,{value:S.task.description,onChange:N=>y({task:{...S.task,description:N.target.value}}),placeholder:"Add the operational context for this task."})}),e.jsx(de,{label:"Project",error:f.projectId??null,children:e.jsx("div",{className:"grid gap-3",children:r.map(N=>{const P=N.id===S.task.projectId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${P?"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]"}`,onClick:()=>y({task:{...S.task,projectId:N.id,goalId:N.goalId}}),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"font-medium",children:N.title}),e.jsx(We,{kind:"goal",label:N.goalTitle,compact:!0,gradient:!1})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description||"No project note attached yet."})]},N.id)})})}),e.jsx(de,{label:"Owner",error:f.owner??null,children:e.jsx(ye,{value:S.task.owner,onChange:N=>y({task:{...S.task,owner:N.target.value}}),placeholder:"Albert"})}),e.jsx(de,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(N=>{const P=S.task.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${P?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>y({task:{...S.task,tagIds:P?S.task.tagIds.filter(v=>v!==N.id):[...S.task.tagIds,N.id]}}),children:N.name},N.id)})})})]}):S.kind==="project"?e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Project title",error:f.title??null,children:e.jsx(ye,{value:S.project.title,onChange:N=>y({project:{...S.project,title:N.target.value}}),placeholder:"Turn the insight into a project"})}),e.jsx(de,{label:"Description",children:e.jsx(Ze,{value:S.project.description,onChange:N=>y({project:{...S.project,description:N.target.value}}),placeholder:"Describe the initiative this insight points to."})}),e.jsx(de,{label:"Goal",error:f.goalId??null,children:e.jsx("div",{className:"grid gap-3",children:i.map(N=>{const P=N.id===S.project.goalId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${P?"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]"}`,onClick:()=>y({project:{...S.project,goalId:N.id}}),children:[e.jsx("div",{className:"font-medium",children:N.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description||"No strategic note attached yet."})]},N.id)})})}),C?e.jsxs(ui,{children:["This project will sit under the “",C.title,"” goal."]}):null]}):S.kind==="goal"?e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Goal title",error:f.title??null,children:e.jsx(ye,{value:S.goal.title,onChange:N=>y({goal:{...S.goal,title:N.target.value}}),placeholder:"Turn the insight into a life goal"})}),e.jsx(de,{label:"Description",children:e.jsx(Ze,{value:S.goal.description,onChange:N=>y({goal:{...S.goal,description:N.target.value}}),placeholder:"Describe the strategic direction this insight suggests."})}),e.jsx(de,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(N=>{const P=S.goal.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${P?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>y({goal:{...S.goal,tagIds:P?S.goal.tagIds.filter(v=>v!==N.id):[...S.goal.tagIds,N.id]}}),children:N.name},N.id)})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Linked note",description:"This stores the insight as durable Markdown evidence on the linked entity instead of creating a new work item.",hint:T?`This note will attach to ${T}.`:void 0,children:e.jsx(Ze,{value:S.noteMarkdown,onChange:N=>y({noteMarkdown:N.target.value}),placeholder:"Write the applied note content in Markdown",className:"min-h-64"})}),T?e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white/70",children:["Linked target:"," ",e.jsx("span",{className:"font-medium text-white",children:T})]}):null]})}];return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Apply insight",title:"Turn this insight into a real record",description:"Apply should create something concrete inside Forge, not just change the status label.",value:u,onChange:x,draftPersistenceKey:"insights.apply",steps:w,submitLabel:"Apply insight",pending:o,error:g,onSubmit:async()=>{p(null),b({});try{if(u.kind==="task"){const S=Df.safeParse(u.task);if(!S.success){b(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([y,N])=>[y,N==null?void 0:N[0]]))),p("This applied task still needs a valid title, project, and owner.");return}await d({kind:"task",input:S.data}),s(!1);return}if(u.kind==="project"){const S=Lf.safeParse(u.project);if(!S.success){b(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([y,N])=>[y,N==null?void 0:N[0]]))),p("This applied project still needs a valid title and goal.");return}await d({kind:"project",input:S.data}),s(!1);return}if(u.kind==="goal"){const S=Ef.safeParse(u.goal);if(!S.success){b(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([y,N])=>[y,N==null?void 0:N[0]]))),p("This applied goal still needs a valid title and target.");return}await d({kind:"goal",input:S.data}),s(!1);return}if(!u.noteMarkdown.trim()){p("The linked note needs Markdown content before it can be saved.");return}if(!h){p("This insight is not attached to a specific entity yet, so Forge cannot place a linked note for it.");return}await d({kind:"note",input:{contentMarkdown:u.noteMarkdown.trim()}}),s(!1)}catch(S){p(S instanceof Error?S.message:"Unable to apply this insight right now.")}}})}function gp(t,s){return{originType:(t==null?void 0:t.originType)??"user",originAgentId:(t==null?void 0:t.originAgentId)??"",originLabel:(t==null?void 0:t.originLabel)??"",entityType:(s==null?void 0:s.entityType)??(t==null?void 0:t.entityType)??"",entityId:(s==null?void 0:s.entityId)??(t==null?void 0:t.entityId)??"",timeframeLabel:(t==null?void 0:t.timeframeLabel)??"This week",title:(t==null?void 0:t.title)??"",summary:(t==null?void 0:t.summary)??"",recommendation:(t==null?void 0:t.recommendation)??"",rationale:(t==null?void 0:t.rationale)??"",confidence:(t==null?void 0:t.confidence)??.72,ctaLabel:(t==null?void 0:t.ctaLabel)??"Review insight",targetKind:(s==null?void 0:s.entityType)??(t==null?void 0:t.entityType)??"general"}}function nw({open:t,onOpenChange:s,title:a="Store insight",description:i="Capture a clear observation, its recommendation, and where it belongs without dropping into a raw admin form.",eyebrow:r="Insight",pending:n=!1,submitLabel:l="Store insight",initialValue:o,lockedEntity:d,entityCandidates:m=[],onSubmit:h}){const[u,x]=c.useState(()=>gp(o,d)),[g,p]=c.useState(null);c.useEffect(()=>{t&&(x(gp(o,d)),p(null))},[o,d,t]);const f=c.useMemo(()=>{const C=new Set(["general"]);return m.forEach(T=>C.add(T.entityType)),d&&C.add(d.entityType),Array.from(C)},[m,d]),b=m.filter(C=>C.entityType===u.targetKind),A=[{id:"focus",eyebrow:"Focus",title:"Name the insight and place it in the right context",description:"Start with the main observation, then decide whether this belongs to a specific entity or should stay general.",render:(C,T)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Insight title",description:"Write the main idea as a clear headline.",labelHelp:"The title should sound like the recommendation or realization you want to remember, not like an internal database field.",children:e.jsx(ye,{value:C.title,onChange:w=>T({title:w.target.value}),placeholder:"Weekly review needs a tighter end ritual"})}),e.jsx(de,{label:"Timeframe",description:"Keep the horizon short and readable.",children:e.jsx(ye,{value:C.timeframeLabel,onChange:w=>T({timeframeLabel:w.target.value}),placeholder:"This week"})}),e.jsx(de,{label:"Where should this insight live?",description:"Use a specific entity when the insight is about one goal, project, task, or report. Keep it general when it applies to the wider system.",children:d?e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx(We,{kind:d.kind,label:d.label}),d.description?e.jsx(ui,{className:"mt-2",children:d.description}):null]}):e.jsxs(e.Fragment,{children:[e.jsx(wt,{value:C.targetKind,onChange:w=>T({targetKind:w,entityType:w==="general"?"":w,entityId:""}),options:f.map(w=>({value:w,label:w==="general"?"General insight":w==="trigger_report"?"Report":w.charAt(0).toUpperCase()+w.slice(1),description:w==="general"?"Store it in the broader insight feed.":`Attach it to a specific ${w==="trigger_report"?"report":w}.`})),columns:f.length>=3?3:2}),C.targetKind!=="general"?b.length>0?e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:b.map(w=>{const S=C.entityType===w.entityType&&C.entityId===w.entityId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${S?"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]"}`,onClick:()=>T({entityType:w.entityType,entityId:w.entityId}),children:[e.jsx(We,{kind:w.kind,label:w.label,compact:!0}),w.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:w.description}):null]},`${w.entityType}:${w.entityId}`)})}):e.jsxs(ui,{className:"mt-4",children:["No"," ",C.targetKind==="trigger_report"?"reports":`${C.targetKind}s`," ","are ready to attach here yet."]}):null]})})]})},{id:"observation",eyebrow:"Observation",title:"Capture what you are seeing clearly",description:"Keep the summary plain and useful. Add the why only if it helps the next action make sense.",render:(C,T)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Summary",description:"Describe the pattern, problem, or opportunity in plain language.",labelHelp:"Write what is actually happening, not a slogan and not a long essay.",children:e.jsx(Ze,{value:C.summary,onChange:w=>T({summary:w.target.value}),placeholder:"The weekly review loses energy because the close-out is vague, so finished work never turns into clear next moves."})}),e.jsx(de,{label:"Why this matters",description:"Optional context that helps explain the recommendation.",children:e.jsx(Ze,{value:C.rationale,onChange:w=>T({rationale:w.target.value}),placeholder:"When the close-out is loose, important wins disappear from memory and the next week starts without momentum."})})]})},{id:"move",eyebrow:"Next move",title:"Turn the insight into a recommendation",description:"Finish with the recommendation you want the user or agent to actually act on.",render:(C,T)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Recommendation",description:"Write the concrete move this insight points toward.",labelHelp:"A recommendation should be actionable. If the user read only this line, they should know what to do next.",children:e.jsx(Ze,{value:C.recommendation,onChange:w=>T({recommendation:w.target.value}),placeholder:"Add a fixed five-minute close-out block that turns finished tasks into one sentence of evidence and one next move."})}),e.jsx(de,{label:"Confidence",description:"Choose how strongly this recommendation holds up right now.",children:e.jsx(wt,{value:String(C.confidence),onChange:w=>T({confidence:Number(w)}),options:[{value:"0.55",label:"Low",description:"Useful hunch, still early."},{value:"0.72",label:"Medium",description:"Solid pattern, worth acting on."},{value:"0.88",label:"High",description:"Clear enough to trust strongly."}],columns:3})})]})}];return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:r,title:a,description:i,value:u,onChange:x,draftPersistenceKey:"insights.flow",steps:A,submitLabel:l,pending:n,error:g,onSubmit:async()=>{p(null);const C=b2.safeParse({originType:u.originType,originAgentId:u.originAgentId,originLabel:u.originLabel,entityType:u.targetKind==="general"?"":u.entityType,entityId:u.targetKind==="general"?"":u.entityId,timeframeLabel:u.timeframeLabel,title:u.title,summary:u.summary,recommendation:u.recommendation,rationale:u.rationale,confidence:u.confidence,ctaLabel:u.ctaLabel});if(!C.success){p("This insight still needs a title, a summary, and a recommendation before it can be stored.");return}try{await h(C.data),s(!1)}catch(T){p(T instanceof Error?T.message:"Unable to store this insight right now.")}}})}function t3(){var w,S,y,N;const t=ct(),s=$t(),a=jt(),i=Array.isArray(a.selectedUserIds)?a.selectedUserIds:[],{snapshot:r}=a,[n,l]=c.useState(!1),[o,d]=c.useState(null),m=Fe({queryKey:["forge-insights",...i],queryFn:()=>Ej(i)}),h=Re({mutationFn:nf,onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),u=Re({mutationFn:({insightId:P,feedbackType:v})=>hh(P,v),onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),x=Re({mutationFn:({insightId:P})=>gN(P),onMutate:async({insightId:P})=>{await t.cancelQueries({queryKey:["forge-insights"]});const v=t.getQueryData(["forge-insights"]);if(v){const H=v.insights.feed.find(j=>j.id===P);t.setQueryData(["forge-insights"],{insights:{...v.insights,feed:v.insights.feed.filter(j=>j.id!==P),openCount:(H==null?void 0:H.status)==="open"?Math.max(0,v.insights.openCount-1):v.insights.openCount}})}return{previous:v}},onError:(P,v,H)=>{H!=null&&H.previous&&t.setQueryData(["forge-insights"],H.previous)},onSettled:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),g=Re({mutationFn:async({insight:P,submission:v})=>{let H=null,j="Applied the insight.";if(v.kind==="task"){const R=await im(v.input);H=`/tasks/${R.task.id}`,j=`Created task: ${R.task.title}`}else if(v.kind==="project"){const R=await am(v.input);H=`/projects/${R.project.id}`,j=`Created project: ${R.project.title}`}else if(v.kind==="goal"){const R=await sm(v.input);H=`/goals/${R.goal.id}`,j=`Created goal: ${R.goal.title}`}else{const R=Km(P);if(!R)throw new Error("This insight is not linked to a concrete entity yet, so Forge cannot attach a linked note to it.");await wl({contentMarkdown:v.input.contentMarkdown,links:[R]}),H=yl(R.entityType,R.entityId),j="Created a linked note from the insight."}return await hh(P.id,"applied",j),{href:H}},onSuccess:async({href:P})=>{await Promise.all([t.invalidateQueries({queryKey:["forge-insights"]}),Ut(t),t.invalidateQueries({queryKey:["forge-xp-metrics"]}),t.invalidateQueries({queryKey:["forge-reward-ledger"]}),t.invalidateQueries({queryKey:["notes-index"]})]),d(null),P&&s(P)}}),p=(w=m.data)==null?void 0:w.insights,f=c.useMemo(()=>[...r.goals.slice(0,8).map(P=>({entityType:"goal",entityId:P.id,kind:"goal",label:P.title,description:P.description})),...r.projects.slice(0,8).map(P=>({entityType:"project",entityId:P.id,kind:"project",label:P.title,description:P.goalTitle})),...r.tasks.slice(0,10).map(P=>({entityType:"task",entityId:P.id,kind:"task",label:P.title,description:P.status.replaceAll("_"," ")}))],[r.goals,r.projects,r.tasks]),b=u.isPending?((S=u.variables)==null?void 0:S.insightId)??null:null,A=x.isPending?((y=x.variables)==null?void 0:y.insightId)??null:null,C=g.isPending?((N=g.variables)==null?void 0:N.insight.id)??null:null,T=r.metrics.topGoalId?r.goals.find(P=>P.id===r.metrics.topGoalId)??null:null;return m.isLoading?e.jsx(Et,{eyebrow:"Insights",title:"Loading the insight feed",description:"Pulling coaching, momentum analysis, and stored recommendations."}):m.isError||!p?e.jsx(it,{eyebrow:"Insights",error:m.error,onRetry:()=>void t.invalidateQueries({queryKey:["forge-insights"]})}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:"Insights",description:"Save useful advice from you or your agent, review what seems worth acting on, and turn the good ones into real work when the timing is right.",badge:`${p.openCount} open`,actions:e.jsx(W,{onClick:()=>l(!0),children:"Store insight"})}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Momentum analysis"}),e.jsx("div",{className:"mt-4 grid grid-cols-5 gap-2 sm:grid-cols-10",children:p.momentumHeatmap.map(P=>e.jsxs("div",{className:"rounded-[16px] bg-white/[0.04] p-3",children:[e.jsx("div",{className:"h-12 rounded-[12px]",style:{background:P.intensity>=4?"rgba(192,193,255,0.95)":P.intensity===3?"rgba(192,193,255,0.7)":P.intensity===2?"rgba(192,193,255,0.45)":P.intensity===1?"rgba(192,193,255,0.2)":"rgba(255,255,255,0.05)"}}),e.jsx("div",{className:"mt-2 text-[10px] uppercase tracking-[0.16em] text-white/40",children:P.label})]},P.id))})]}),e.jsxs(ce,{children:[e.jsxs("div",{className:"flex items-center gap-2 font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:[e.jsx("span",{children:"Execution trends"}),e.jsx(vt,{content:"The lavender series tracks completed XP by time window. The green series tracks execution pressure from focused and completed work. Read them together to see whether visible output and active work are moving in sync.",label:"Explain execution trends"})]}),e.jsx("div",{className:"mt-4 h-72 min-w-0",children:e.jsx(Fi,{width:"100%",height:"100%",minWidth:280,minHeight:288,children:e.jsxs(Er,{data:p.executionTrends,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"insight-xp",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#c0c1ff",stopOpacity:"0.8"}),e.jsx("stop",{offset:"100%",stopColor:"#c0c1ff",stopOpacity:"0.08"})]})}),e.jsx(ai,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(ii,{hide:!0}),e.jsx(Za,{dataKey:"xp",stroke:"#c0c1ff",fill:"url(#insight-xp)",strokeWidth:2}),e.jsx(Za,{dataKey:"focusScore",stroke:"#4edea3",fill:"rgba(78,222,163,0.06)",strokeWidth:2})]})})}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.04] px-3 py-2 text-sm text-white/64",children:[e.jsx("span",{className:"size-2.5 rounded-full bg-[#c0c1ff]"}),e.jsx("span",{children:"Completed XP"}),e.jsx(vt,{content:"Completed XP is the reward Forge logged for finished work in each time window. It helps you see whether things are actually getting finished, not just started.",label:"Explain completed XP"})]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.04] px-3 py-2 text-sm text-white/64",children:[e.jsx("span",{className:"size-2.5 rounded-full bg-[#4edea3]"}),e.jsx("span",{children:"Focus score"}),e.jsx(vt,{content:"Focus score is Forge's rough read of how much active execution pressure was present in each window, based on focused and completed work.",label:"Explain focus score"})]})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/54",children:"Use this chart to spot whether finished output and active deep-work pressure are rising together or starting to drift apart."})]}),e.jsxs(ce,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/60",children:"Deterministic coaching"}),e.jsx(vt,{content:"This is Forge's built-in coaching read. It looks at your overdue work, blocked work, current goal pressure, and recent evidence to produce one grounded recommendation from the actual operating record.",label:"Explain deterministic coaching"})]}),e.jsx("h2",{className:"mt-4 font-display text-4xl text-white",children:p.coaching.title}),e.jsx("p",{className:"mt-4 text-sm leading-7 text-white/60",children:"Forge turns the current state of your goals, projects, tasks, and recent evidence into one focused operating read instead of a vague motivational hint."}),e.jsxs("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Current read"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/72",children:p.coaching.summary})]}),e.jsxs("div",{className:"mt-4 rounded-[22px] bg-[radial-gradient(circle_at_top_left,rgba(192,193,255,0.14),transparent_45%),rgba(255,255,255,0.03)] p-5",children:[e.jsx("div",{className:"font-medium text-white",children:"Recommendation"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/60",children:p.coaching.recommendation}),T?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"rounded-full bg-white/[0.06] px-3 py-2 text-sm text-white/64",children:["Connected goal: ",e.jsx("span",{className:"font-medium text-white",children:T.title})]}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>s(`/goals/${T.id}`),children:"Open goal"})]}):null]})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Store insight"}),e.jsxs("div",{className:"mt-4 rounded-[22px] bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-medium text-white",children:"Capture advice without forcing it into a task too early"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/60",children:"Insights are saved suggestions from you or your agent. Use them when something feels worth remembering, but it is not ready to become a goal, project, or task yet."}),e.jsx("div",{className:"mt-4",children:e.jsx(W,{onClick:()=>l(!0),children:"Store insight"})})]})]}),e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Stored insights"}),e.jsx("div",{className:"mt-4 grid gap-3",children:p.feed.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/55",children:"No stored insights yet."}):p.feed.map(P=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:P.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:P.summary}),P.user?e.jsx("div",{className:"mt-3",children:e.jsx(ot,{user:P.user,compact:!0})}):null]}),e.jsx(I,{className:"text-white/70",children:P.status})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:P.recommendation}),e.jsxs("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:[P.originLabel??P.originType," · confidence ",Math.round(P.confidence*100),"%"]}),P.status==="applied"?e.jsx("div",{className:"mt-4 rounded-[16px] border border-emerald-400/18 bg-emerald-400/8 px-4 py-3 text-sm text-emerald-100/88",children:"This insight has already been turned into a real Forge record, so it stays here as a trace of what happened."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 text-sm text-white/52",children:P.status==="accepted"?"Accepted means this feels useful and worth keeping in view. Apply turns it into a real goal, project, task, or note when you are ready.":"Accept keeps this advice on the board. Apply turns it into a real Forge record now. Dismiss deletes it from the list."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[P.status!=="accepted"?e.jsx(W,{variant:"secondary",pending:b===P.id,onClick:()=>void u.mutateAsync({insightId:P.id,feedbackType:"accepted"}),children:"Accept"}):null,e.jsx(W,{pending:C===P.id,onClick:()=>d(P),children:"Apply"}),e.jsx(W,{variant:"ghost",pending:A===P.id,onClick:()=>void x.mutateAsync({insightId:P.id}),children:"Dismiss"})]})]})]},P.id))})]})]})]}),e.jsx(nw,{open:n,onOpenChange:l,entityCandidates:f,pending:h.isPending,onSubmit:async P=>{await h.mutateAsync(P)}}),o?e.jsx(e3,{open:!!o,onOpenChange:P=>{P||d(null)},insight:o,goals:r.goals,projects:r.projects,tasks:r.tasks,tags:r.tags,pending:g.isPending,onSubmit:async P=>{await g.mutateAsync({insight:o,submission:P})}}):null]})}function s3(t){if(typeof t=="number"&&Number.isInteger(t)&&t>0)return t;if(typeof t=="string"){const s=t.match(/(\d+)/);if(s){const a=Number.parseInt(s[1]??"",10);return Number.isInteger(a)&&a>0?a:null}}return null}function fp(t){return t.split(/\r?\n/).map(s=>s.trim()).reduce((s,a)=>{const i=a.match(/^[-*+]\s+\[([ xX])\]\s+(.+)$/);if(i)return s.push({label:i[2].trim(),completed:i[1].toLowerCase()==="x"}),s;const r=a.match(/^(?:[-*+]|\d+\.)\s+(.+)$/);return r&&s.push({label:r[1].trim(),completed:null}),s},[]).filter(s=>s.label.length>0)}function a3(t){if(t.acceptanceCriteria.length>0)return{total:t.acceptanceCriteria.length,completed:t.status==="done"?t.acceptanceCriteria.length:0,source:"acceptance_criteria",items:t.acceptanceCriteria};const s=fp(t.aiInstructions);if(s.length>0){const i=t.status==="done"?s.length:s.filter(r=>r.completed===!0).length;return{total:s.length,completed:i,source:"ai_instructions",items:s.map(r=>r.label)}}const a=fp(t.description);if(a.length>0){const i=t.status==="done"?a.length:a.filter(r=>r.completed===!0).length;return{total:a.length,completed:i,source:"description",items:a.map(r=>r.label)}}return null}function bp(t,s){return t.find(a=>a.refType===s)??null}function lw(t,s=null){var o,d,m,h,u,x,g,p,f,b,A;const a=new Set(((o=t.completionReport)==null?void 0:o.linkedGitRefIds)??[]),i=bp(t.gitRefs,"branch"),r=bp(t.gitRefs,"pull_request"),n=(s==null?void 0:s.gitContext)??null,l=(n==null?void 0:n.pullRequestNumber)??s3((r==null?void 0:r.refValue)??(r==null?void 0:r.displayTitle)??null);return{actor:(s==null?void 0:s.actor)??null,activeRun:s,stepSummary:a3(t),changedFileCount:((d=t.completionReport)==null?void 0:d.modifiedFiles.length)??0,changedFilesPreview:(((m=t.completionReport)==null?void 0:m.modifiedFiles)??[]).slice(0,2),git:{provider:((h=n==null?void 0:n.provider)==null?void 0:h.trim())||((u=i==null?void 0:i.provider)==null?void 0:u.trim())||((x=r==null?void 0:r.provider)==null?void 0:x.trim())||null,repository:((g=n==null?void 0:n.repository)==null?void 0:g.trim())||((p=i==null?void 0:i.repository)==null?void 0:p.trim())||((f=r==null?void 0:r.repository)==null?void 0:f.trim())||null,branch:((b=n==null?void 0:n.branch)==null?void 0:b.trim())||((A=i==null?void 0:i.refValue)==null?void 0:A.trim())||null,branchUrl:(n==null?void 0:n.branchUrl)??(i==null?void 0:i.url)??null,pullRequestNumber:l,pullRequestUrl:(n==null?void 0:n.pullRequestUrl)??(r==null?void 0:r.url)??null,compareUrl:(n==null?void 0:n.compareUrl)??null,linkedRefCount:a.size}}}const vs=["backlog","focus","in_progress","blocked","done"];function i3({task:t,onOpenTask:s,onEditTask:a,onLinkTask:i,onCreateTaskForIssue:r,onCreateSubtaskForTask:n,onMove:l,onDeleteTask:o,deletePendingTaskId:d,onRequestDelete:m}){const h=t.level==="issue"?{id:"create-task",label:"Create task",description:"Add a focused execution task under this issue.",icon:qc,onSelect:()=>r==null?void 0:r(t.id)}:t.level==="task"?{id:"create-subtask",label:"Create subtask",description:"Add a granular child step under this task.",icon:qc,onSelect:()=>n==null?void 0:n(t.id)}:null;return[{id:"open-task",label:"Open",description:"Jump to the work-item detail view.",icon:Es,onSelect:()=>s==null?void 0:s(t.id)},{id:"edit-task",label:"Edit",description:"Open the guided work-item editor.",icon:pi,onSelect:()=>a==null?void 0:a(t.id)},{id:"link-task",label:"Link",description:"Open the placement step to relink this work item.",icon:$s,onSelect:()=>i==null?void 0:i(t.id)},...h?[h]:[],{id:"delete-task",label:t.level==="issue"?"Delete issue":t.level==="subtask"?"Delete subtask":"Delete task",description:"Remove this work item directly from the board menu.",icon:Rt,tone:"danger",disabled:!o||d===t.id,onSelect:()=>m(t)},...vs.filter(u=>u!==t.status).map(u=>({id:`move-task-${u}`,label:`Move to ${u.replaceAll("_"," ")}`,description:"Update the workflow lane for this work item.",onSelect:()=>void l(t.id,u)}))]}function ow(t){return t.startsWith("lane:")||t.includes(":lane:")}function r3(t){var s,a;return((a=(s=t.data)==null?void 0:s.current)==null?void 0:a.type)==="lane"||ow(String(t.id))}function n3(t){var s,a;return((a=(s=t.data)==null?void 0:s.current)==null?void 0:a.type)==="trash"}function l3(t,s){const a=Math.max(0,Math.min(t.right,s.right)-Math.max(t.left,s.left)),i=Math.max(0,Math.min(t.bottom,s.bottom)-Math.max(t.top,s.top));return a*i}const o3=t=>{const s=E0(t),a=s.find(l=>{const o=t.droppableContainers.find(d=>d.id===l.id);return o?n3(o):!1});if(a)return[a];const i=s.find(l=>ow(String(l.id)));if(i)return[i];const n=t.droppableContainers.filter(l=>r3(l)).map(l=>{const o=t.droppableRects.get(l.id);if(!o)return null;const d=l3(t.collisionRect,o);return d<=0?null:{id:l.id,data:{droppableContainer:l,value:d}}}).filter(Boolean).sort((l,o)=>{var d,m;return(((d=o==null?void 0:o.data)==null?void 0:d.value)??0)-(((m=l==null?void 0:l.data)==null?void 0:m.value)??0)});return n.length>0?n:s.length>0?s:L0(t)};function d3(t,s){return s&&s.trim().length>0?s:t!=null&&t.actor?`${t.actor} session`:"Active work"}function c3(t,s){return[(t==null?void 0:t.actor)??null,s].filter(Boolean).join(" · ")}function wp(t){t.preventDefault(),t.stopPropagation()}function dw({task:t,goal:s,tags:a,activeRun:i,isSelected:r,isDragging:n=!1,isOverlay:l=!1,style:o,setNodeRef:d,dragAttributes:m,dragListeners:h,isMobile:u=!1,onSelect:x,onStartTask:g,onStopTask:p,onQuickReopen:f,onStepTask:b,onSplitTask:A,onOpenMenu:C,notesSummaryByEntity:T}){var J;const{t:w,formatDate:S}=Ot(),y=lw(t,i??null),N=y.stepSummary,P=vs[vs.indexOf(t.status)-1]??null,v=vs[vs.indexOf(t.status)+1]??null,H=Js(T,"task",t.id).count,j=t.level==="issue"?"issue":"task",R=zs(j),Q=t.level==="subtask"?"136,146,255":R.colorToken.rgb.join(", "),X=t.dueDate&&!Number.isNaN(Date.parse(t.dueDate))?S(t.dueDate):"No due date",Y=N&&N.total>0?Math.max(8,Math.round(N.completed/N.total*100)):null,z=y.git.branch,K=y.git.branchUrl,$=y.git.pullRequestNumber?`PR #${y.git.pullRequestNumber}`:null,D=y.git.pullRequestUrl;return e.jsxs("article",{ref:d,style:{...o,"--board-card-accent":Q},className:te("w-full max-w-full min-w-0 overflow-hidden rounded-[18px] p-3 shadow-[inset_0_0_0_1px_rgba(var(--board-card-accent),0.12)] transition cursor-grab active:cursor-grabbing",u&&"touch-none select-none",l&&"rotate-[0.5deg] bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.22),rgba(var(--board-card-accent),0.08))] shadow-[0_28px_80px_rgba(8,12,24,0.42),inset_0_0_0_1px_rgba(var(--board-card-accent),0.28)]",n&&!l&&"opacity-35 shadow-[inset_0_0_0_1px_rgba(var(--board-card-accent),0.08)]",r?"bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.18),rgba(var(--board-card-accent),0.06))] shadow-[0_16px_40px_rgba(8,12,24,0.32),inset_0_0_0_1px_rgba(var(--board-card-accent),0.26)]":"bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.08),rgba(255,255,255,0.03))]"),"data-dragging":n?"true":"false","data-testid":`task-card-${t.id}`,onClick:()=>x(t.id),...m,...h,children:[e.jsx("div",{className:"mb-3 h-px w-full rounded-full",style:{background:`linear-gradient(90deg, rgba(${Q}, 0.96), rgba(${Q}, 0.18))`}}),e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(We,{kind:j,label:t.level,compact:!0,size:"xs",gradient:!1,className:"shrink-0"}),e.jsx(I,{size:"xs",className:"shrink-0 text-[10px] text-[var(--tertiary)]",children:t.priority}),y.actor?e.jsxs(I,{size:"xs",className:"shrink-0 bg-cyan-400/12 text-cyan-100",children:[e.jsx(ma,{className:"mr-1 size-3"}),y.actor]}):null]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-1.5",children:[C?e.jsx("button",{type:"button","aria-label":`Open ${t.title} actions`,className:"inline-flex size-8 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white",onClick:q=>{q.preventDefault(),q.stopPropagation(),C(q,t)},children:e.jsx(Di,{className:"size-3.5"})}):null,u?e.jsxs("div",{className:"flex items-center gap-1",onClick:q=>q.stopPropagation(),children:[e.jsx("button",{type:"button","aria-label":`Move ${t.title} to the previous lane`,className:"inline-flex size-7 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white disabled:opacity-35",disabled:!P,onClick:()=>{P&&(b==null||b(t.id,"previous"))},children:e.jsx(hl,{className:"size-3.5"})}),e.jsx("button",{type:"button","aria-label":`Move ${t.title} to the next lane`,className:"inline-flex size-7 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white disabled:opacity-35",disabled:!v,onClick:()=>{v&&(b==null||b(t.id,"next"))},children:e.jsx(Sa,{className:"size-3.5"})})]}):null,i?e.jsx("button",{type:"button","aria-label":`Stop work on ${t.title}`,className:"inline-flex size-8 items-center justify-center rounded-full bg-rose-500/16 text-rose-200 transition hover:bg-rose-500/24",onClick:q=>{q.preventDefault(),q.stopPropagation(),p==null||p(i)},children:e.jsx(xg,{className:"size-3.5 fill-current"})}):t.status!=="done"?e.jsx("button",{type:"button","aria-label":`Start work on ${t.title}`,className:"inline-flex size-8 items-center justify-center rounded-full bg-[var(--primary)]/16 text-[var(--primary)] transition hover:bg-[var(--primary)]/24",onClick:q=>{q.preventDefault(),q.stopPropagation(),g==null||g(t.id)},children:e.jsx(Hs,{className:"size-4 fill-current"})}):null,(J=t.splitSuggestion)!=null&&J.shouldSplit&&A?e.jsxs("button",{type:"button","aria-label":`Split ${t.title}`,className:"inline-flex items-center gap-1 rounded-full bg-amber-400/12 px-2.5 py-1 text-[10px] font-medium tracking-[0.14em] text-amber-100 transition hover:bg-amber-400/18",onClick:q=>{q.preventDefault(),q.stopPropagation(),A(t.id)},children:[e.jsx(ad,{className:"size-3.5"}),"Split it"]}):null,e.jsxs("span",{className:"shrink-0 text-[11px] text-white/44",children:[t.points," xp"]})]})]}),e.jsx(yt,{kind:j,label:t.title,className:"max-w-full",lines:3,labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("p",{className:"mt-1.5 line-clamp-3 [overflow-wrap:anywhere] text-[12px] leading-5 text-white/62",children:t.description||w("common.executionBoard.noExecutionNote")}),N?e.jsxs("div",{className:"mt-3 rounded-[16px] border border-white/8 bg-white/[0.045] p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] text-white/58",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(lg,{className:"size-3.5 text-sky-200"}),N.total," step",N.total===1?"":"s"]}),e.jsxs("span",{className:"tabular-nums text-white/72",children:[N.completed,"/",N.total]})]}),e.jsx("div",{className:"mt-2 h-1.5 overflow-hidden rounded-full bg-white/8",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(56,189,248,0.96),rgba(125,211,252,0.62))]",style:{width:`${Y??0}%`}})}),e.jsx("div",{className:"mt-2 grid gap-1.5",children:N.items.slice(0,2).map(q=>e.jsx("div",{className:"truncate text-[11px] text-white/55",children:q},`${t.id}-${q}`))})]}):null,e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[z?K?e.jsxs("a",{href:K,target:"_blank",rel:"noreferrer",className:"inline-flex min-w-0 max-w-full items-center gap-1 rounded-full border border-sky-300/18 bg-sky-400/12 px-2.5 py-1 text-[11px] text-sky-50 transition hover:bg-sky-400/18",onClick:wp,children:[e.jsx(ua,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:z})]}):e.jsxs(I,{size:"xs",className:"min-w-0 max-w-full bg-sky-400/12 text-sky-50",children:[e.jsx(ua,{className:"mr-1 size-3"}),e.jsx("span",{className:"truncate",children:z})]}):null,$?D?e.jsxs("a",{href:D,target:"_blank",rel:"noreferrer",className:"inline-flex min-w-0 max-w-full items-center gap-1 rounded-full border border-fuchsia-300/18 bg-fuchsia-400/12 px-2.5 py-1 text-[11px] text-fuchsia-50 transition hover:bg-fuchsia-400/18",onClick:wp,children:[e.jsx(Qn,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:$})]}):e.jsxs(I,{size:"xs",className:"bg-fuchsia-400/12 text-fuchsia-50",children:[e.jsx(Qn,{className:"mr-1 size-3"}),$]}):null,y.changedFileCount>0?e.jsxs(I,{size:"xs",className:"bg-amber-400/12 text-amber-50",children:[e.jsx(kg,{className:"mr-1 size-3"}),y.changedFileCount," file",y.changedFileCount===1?"":"s"]}):null,y.git.repository?e.jsx(I,{size:"xs",className:"bg-white/8 text-white/70",children:y.git.repository}):null]}),y.changedFilesPreview.length>0?e.jsx("div",{className:"mt-2 flex min-w-0 flex-wrap gap-1.5",children:y.changedFilesPreview.map(q=>e.jsx(I,{size:"xs",wrap:!0,className:"min-w-0 max-w-full bg-white/[0.06] font-mono text-[10px] text-white/65",children:q},q))}):null,e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[s?e.jsx(We,{kind:"goal",label:s.title,compact:!0,size:"xs",wrap:!0,className:"min-w-0 max-w-full"}):null,e.jsx(ot,{user:t.user,compact:!0,size:"xs"}),e.jsx(Ks,{entityType:"task",entityId:t.id,count:H,compact:!0}),t.actionPointSummary?e.jsxs(I,{size:"xs",className:"bg-[var(--primary)]/12 text-[var(--primary)]",children:[Math.round(t.actionPointSummary.totalCostAp)," AP"]}):null,t.actionPointSummary?e.jsx(I,{size:"xs",className:"bg-white/8 text-white/72",children:t.actionPointSummary.costBand}):null,t.actionPointSummary?e.jsxs(I,{size:"xs",className:"bg-white/8 text-white/72",children:[Math.round(t.actionPointSummary.expectedDurationSeconds/3600)," h target"]}):null,t.time.totalCreditedSeconds>0?e.jsxs(I,{size:"xs",className:"bg-white/8 text-white/72",children:[Math.floor(t.time.totalCreditedSeconds/60)," min"]}):null,t.time.activeRunCount>0?e.jsxs(I,{size:"xs",className:"bg-emerald-500/12 text-emerald-200",children:[t.time.activeRunCount," live"]}):null,a.slice(0,2).map(q=>e.jsx(I,{size:"xs",className:"bg-white/8",style:{color:q.color},children:q.name},q.id))]}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 items-center justify-between gap-2 text-[11px] text-white/45",children:[e.jsxs("span",{className:"min-w-0 truncate",children:[t.effort," / ",t.energy]}),e.jsxs("div",{className:"flex min-w-0 shrink-0 items-center gap-2 text-right",children:[t.status==="done"&&f?e.jsx("button",{type:"button",className:"rounded-full bg-white/8 px-3 py-1 text-[10px] tracking-[0.16em] text-white transition hover:bg-white/12",onClick:q=>{q.preventDefault(),q.stopPropagation(),f(t.id)},children:w("common.executionBoard.reopen")}):null,e.jsx("span",{children:X})]})]})]})}function Zd(t){const{task:s,sortableId:a}=t,{attributes:i,listeners:r,setNodeRef:n,transform:l,transition:o,isDragging:d}=pl({id:a,data:{type:"task",taskId:s.id,status:s.status}});return e.jsx(dw,{...t,setNodeRef:n,dragAttributes:i,dragListeners:r,isDragging:d,isMobile:t.isMobile,onStartTask:t.onStartTask,onStopTask:t.onStopTask,onStepTask:t.onStepTask,onSplitTask:t.onSplitTask,notesSummaryByEntity:t.notesSummaryByEntity,style:{transform:xl.Transform.toString(l),transition:o}})}function cw({project:t,goal:s,isDragging:a=!1,isOverlay:i=!1,style:r,setNodeRef:n,dragAttributes:l,dragListeners:o,isMobile:d=!1,onStepProject:m,onOpenMenu:h}){const{formatDate:u}=Ot(),x=vs[vs.indexOf(t.workflowStatus)-1]??null,g=vs[vs.indexOf(t.workflowStatus)+1]??null,f=zs("project").colorToken.rgb.join(", "),b=t.workflowStatus.replaceAll("_"," "),A=t.status.replaceAll("_"," "),C=t.updatedAt&&!Number.isNaN(Date.parse(t.updatedAt))?u(t.updatedAt):"No recent update";return e.jsxs("article",{ref:n,style:{...r,"--board-card-accent":f},className:te("w-full max-w-full min-w-0 overflow-hidden rounded-[18px] p-3 shadow-[inset_0_0_0_1px_rgba(var(--board-card-accent),0.12)] transition cursor-grab active:cursor-grabbing",d&&"touch-none select-none",i&&"rotate-[0.5deg] bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.22),rgba(var(--board-card-accent),0.08))] shadow-[0_28px_80px_rgba(8,12,24,0.42),inset_0_0_0_1px_rgba(var(--board-card-accent),0.28)]",a&&!i&&"opacity-35 shadow-[inset_0_0_0_1px_rgba(var(--board-card-accent),0.08)]",!a&&!i&&"bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.08),rgba(255,255,255,0.03))]"),"data-testid":`project-card-${t.id}`,...l,...o,children:[e.jsx("div",{className:"mb-3 h-px w-full rounded-full",style:{background:`linear-gradient(90deg, rgba(${f}, 0.96), rgba(${f}, 0.18))`}}),e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"project",label:"project",compact:!0,size:"xs",gradient:!1,className:"shrink-0"}),e.jsx(I,{size:"xs",className:"shrink-0 bg-[var(--primary)]/12 text-[var(--primary)]",children:b}),e.jsx(I,{size:"xs",className:"shrink-0 bg-white/8 text-white/72",children:A})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-1.5",children:[h?e.jsx("button",{type:"button","aria-label":`Open ${t.title} actions`,className:"inline-flex size-8 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white",onClick:T=>{T.preventDefault(),T.stopPropagation(),h(T,t)},children:e.jsx(Di,{className:"size-3.5"})}):null,d?e.jsxs("div",{className:"flex items-center gap-1",onClick:T=>T.stopPropagation(),children:[e.jsx("button",{type:"button","aria-label":`Move ${t.title} to the previous lane`,className:"inline-flex size-7 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white disabled:opacity-35",disabled:!x,onClick:()=>{x&&(m==null||m(t.id,"previous"))},children:e.jsx(hl,{className:"size-3.5"})}),e.jsx("button",{type:"button","aria-label":`Move ${t.title} to the next lane`,className:"inline-flex size-7 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white disabled:opacity-35",disabled:!g,onClick:()=>{g&&(m==null||m(t.id,"next"))},children:e.jsx(Sa,{className:"size-3.5"})})]}):null]})]}),e.jsx(yt,{kind:"project",label:t.title,className:"max-w-full",lines:3,labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("p",{className:"mt-1.5 line-clamp-3 [overflow-wrap:anywhere] text-[12px] leading-5 text-white/62",children:t.description||"PRD-backed initiative spanning multiple work items."}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[s?e.jsx(We,{kind:"goal",label:s.title,compact:!0,size:"xs",wrap:!0,className:"min-w-0 max-w-full"}):null,e.jsx(ot,{user:t.user,compact:!0,size:"xs"}),(t.assignees??[]).slice(0,2).map(T=>e.jsx(ot,{user:T,compact:!0,size:"xs"},T.id)),e.jsxs(I,{size:"xs",className:"bg-[var(--primary)]/12 text-[var(--primary)]",children:[t.progress,"% progress"]}),e.jsxs(I,{size:"xs",className:"bg-white/8 text-white/72",children:[t.totalTasks," linked tasks"]})]}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 items-center justify-between gap-2 text-[11px] text-white/45",children:[e.jsx("span",{className:"min-w-0 truncate",children:t.goalTitle}),e.jsx("span",{children:C})]})]})}function ec(t){const{project:s,sortableId:a}=t,{attributes:i,listeners:r,setNodeRef:n,transform:l,transition:o,isDragging:d}=pl({id:a,data:{type:"project",projectId:s.id,status:s.workflowStatus}});return e.jsx(cw,{...t,setNodeRef:n,dragAttributes:i,dragListeners:r,isDragging:d,style:{transform:xl.Transform.toString(l),transition:o}})}function yp({droppableId:t,status:s,title:a,detail:i,count:r,dragging:n,children:l}){const{setNodeRef:o,isOver:d}=$g({id:t,data:{type:"lane",status:s}});return e.jsx("div",{ref:o,className:te("w-full max-w-full min-w-0 overflow-hidden rounded-[24px] transition",d&&"scale-[1.005]"),"data-lane-id":s,"data-testid":`kanban-lane-${s}`,"data-lane-hover":d?"true":"false",children:e.jsxs(ce,{className:te("h-full w-full max-w-full min-w-0 overflow-hidden p-3 transition-[background-color,box-shadow,border-color,transform]",n&&"border border-white/8",d?"border border-[rgba(125,211,252,0.38)] bg-[linear-gradient(180deg,rgba(125,211,252,0.12),rgba(125,211,252,0.05))] shadow-[0_18px_54px_rgba(14,165,233,0.12)]":"border border-transparent"),children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"type-label text-white/45",children:i}),e.jsx("h3",{className:"mt-1 break-words text-[1.45rem] leading-[1] text-white",children:a})]}),e.jsx("div",{className:"shrink-0 font-display text-[1.45rem] text-[var(--primary)]",children:r})]}),e.jsx("div",{className:te("grid w-full max-w-full min-w-0 min-h-48 content-start gap-2 rounded-[18px] p-2 transition",d?"bg-[rgba(125,211,252,0.08)]":"bg-white/[0.02]"),children:l})]})})}function u3({title:t,detail:s,children:a}){return e.jsxs("div",{className:"rounded-[20px] border border-cyan-300/20 bg-[linear-gradient(180deg,rgba(34,211,238,0.11),rgba(11,23,34,0.34))] p-2.5 shadow-[inset_0_0_0_1px_rgba(34,211,238,0.08)]",children:[e.jsx("div",{className:"mb-2 flex items-start justify-between gap-3 px-1",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-cyan-100/86",children:[e.jsx(ua,{className:"size-3.5"}),e.jsx("span",{className:"truncate",children:t})]}),s?e.jsx("div",{className:"mt-1 text-[11px] text-white/45",children:s}):null]})}),e.jsx("div",{className:"grid gap-2",children:a})]})}function m3({droppableId:t,title:s,detail:a}){const{setNodeRef:i,isOver:r}=$g({id:t,data:{type:"trash"}});return e.jsx("div",{ref:i,className:te("pointer-events-auto fixed right-4 top-4 z-50 w-[min(18rem,calc(100vw-2rem))] rounded-[28px] border px-5 py-4 shadow-[0_24px_80px_rgba(6,10,20,0.48)] backdrop-blur-2xl transition lg:right-6 lg:top-6",r?"border-rose-300/38 bg-[linear-gradient(180deg,rgba(244,63,94,0.28),rgba(120,24,42,0.46))] text-white scale-[1.02]":"border-white/10 bg-[linear-gradient(180deg,rgba(18,24,38,0.96),rgba(10,14,24,0.94))] text-white/84"),"data-testid":"kanban-trash-dropzone","data-trash-hover":r?"true":"false",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:te("flex size-12 items-center justify-center rounded-full border transition",r?"border-white/28 bg-white/12":"border-white/12 bg-white/6"),children:e.jsx(Rt,{className:"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/55",children:"Bin"}),e.jsx("div",{className:"mt-1 text-base font-medium text-white",children:s}),e.jsx("div",{className:"mt-1 text-sm leading-5 text-white/62",children:a})]})]})})}function uw({tasks:t,projects:s=[],activeRuns:a=[],goals:i,tags:r,selectedTaskId:n,onMove:l,onMoveProject:o,onSelectTask:d,onStartTask:m,onStopTask:h,onQuickReopenTask:u,onDeleteTask:x,onOpenProject:g,onOpenTask:p,onEditProject:f,onEditTask:b,onLinkProject:A,onLinkTask:C,onCreateIssueForProject:T,onCreateTaskForIssue:w,onCreateSubtaskForTask:S,onSplitTask:y,notesSummaryByEntity:N}){var Qe,st;const{t:P}=Ot(),v=c.useId(),H=`${v}:trash`,[j,R]=c.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(max-width: 1023px)").matches),Q=ld(od(cd,{activationConstraint:{distance:6}})),[X,Y]=c.useState(null),[z,K]=c.useState(null),[$,D]=c.useState(null),[J,q]=c.useState(null),[_,B]=c.useState(()=>typeof window>"u"?!1:window.localStorage.getItem("forge.kanban-skip-delete-confirmation")==="true"),[G,ae]=c.useState(!1),[ke,Ae]=c.useState({}),[ie,Ie]=c.useState({}),Ne={backlog:{title:P("common.executionBoard.laneBacklogTitle"),detail:P("common.executionBoard.laneBacklogDetail")},focus:{title:P("common.executionBoard.laneFocusTitle"),detail:P("common.executionBoard.laneFocusDetail")},in_progress:{title:P("common.executionBoard.laneProgressTitle"),detail:P("common.executionBoard.laneProgressDetail")},blocked:{title:P("common.executionBoard.laneBlockedTitle"),detail:P("common.executionBoard.laneBlockedDetail")},done:{title:P("common.executionBoard.laneDoneTitle"),detail:P("common.executionBoard.laneDoneDetail")}},M=c.useMemo(()=>t.map(F=>{const he=ke[F.id];return he?{...F,status:he}:F}),[ke,t]),E=c.useMemo(()=>s.map(F=>{const he=ie[F.id];return he?{...F,workflowStatus:he}:F}),[ie,s]),O=c.useMemo(()=>{const F=new Map;for(const he of a){if(he.status!=="active")continue;const we=F.get(he.taskId);(!we||he.isCurrent||he.updatedAt>we.updatedAt)&&F.set(he.taskId,he)}return F},[a]),xe=c.useMemo(()=>[...E.map(F=>({kind:"project",id:F.id,status:F.workflowStatus,project:F,goal:i.find(he=>he.id===F.goalId)})),...M.map(F=>({kind:"task",id:F.id,status:F.status,task:F,goal:i.find(he=>he.id===F.goalId),tags:F.tagIds.map(he=>r.find(we=>we.id===he)).filter(Boolean),activeRun:O.get(F.id)??null}))],[O,E,M,i,r]),V=X?xe.find(F=>F.id===X)??null:null,Se=c.useMemo(()=>{if(!z)return[];if(z.kind==="project"){const he=E.find(we=>we.id===z.entityId);return he?[{id:"open-project",label:"Open",description:"Jump to the project detail view.",icon:Es,onSelect:()=>g==null?void 0:g(he.id)},{id:"edit-project",label:"Edit",description:"Open the guided project editor.",icon:pi,onSelect:()=>f==null?void 0:f(he.id)},{id:"link-project",label:"Link",description:"Open the anchor step to relink the project to its goal.",icon:$s,onSelect:()=>A==null?void 0:A(he.id)},{id:"create-issue",label:"Create issue",description:"Break this project into a new vertical slice issue.",icon:qc,onSelect:()=>T==null?void 0:T(he.id)},...vs.filter(we=>we!==he.workflowStatus).map(we=>({id:`move-project-${we}`,label:`Move to ${we.replaceAll("_"," ")}`,description:"Update the project workflow lane without leaving the board.",onSelect:()=>void(o==null?void 0:o(he.id,we))}))]:[]}const F=M.find(he=>he.id===z.entityId);return F?i3({task:F,onOpenTask:p,onEditTask:b,onLinkTask:C,onCreateTaskForIssue:w,onCreateSubtaskForTask:S,onMove:l,onDeleteTask:x,deletePendingTaskId:J,onRequestDelete:L}):[]},[E,M,z,T,S,w,f,b,A,C,l,o,x,g,p,J,_]);function Ee(F){var we;if(F.length===0)return e.jsx("div",{className:"w-full max-w-full rounded-[18px] border border-dashed border-white/8 px-4 py-8 text-center text-sm text-white/35",children:P("common.executionBoard.emptyLane")});if(((we=F[0])==null?void 0:we.status)!=="in_progress")return F.map(Z=>Z.kind==="task"?e.jsx(Zd,{sortableId:`${v}:task:${Z.task.id}`,task:Z.task,goal:Z.goal,tags:Z.tags,activeRun:Z.activeRun,isSelected:n===Z.task.id,isMobile:j,onSelect:d,onStartTask:m,onStopTask:h,onQuickReopen:u,onStepTask:ge,onOpenMenu:ve,onSplitTask:y,notesSummaryByEntity:N},Z.task.id):e.jsx(ec,{sortableId:`${v}:project:${Z.project.id}`,project:Z.project,goal:Z.goal,isMobile:j,onStepProject:Te,onOpenMenu:Le},Z.project.id));const he=new Map;for(const Z of F){if(Z.kind!=="task"||!Z.activeRun){const et=he.get("ungrouped");et?et.items.push(Z):he.set("ungrouped",{title:"Active work",detail:"Tasks in progress without a tracked branch",items:[Z]});continue}const De=lw(Z.task,Z.activeRun),ee=[Z.activeRun.actor,De.git.repository??"",De.git.branch??""].join("::"),ze=he.get(ee);if(ze){ze.items.push(Z);continue}he.set(ee,{title:d3(Z.activeRun,De.git.branch),detail:c3(Z.activeRun,De.git.repository),items:[Z]})}return Array.from(he.entries()).map(([Z,De])=>Z==="ungrouped"?De.items.map(ee=>ee.kind==="task"?e.jsx(Zd,{sortableId:`${v}:task:${ee.task.id}`,task:ee.task,goal:ee.goal,tags:ee.tags,activeRun:ee.activeRun,isSelected:n===ee.task.id,isMobile:j,onSelect:d,onStartTask:m,onStopTask:h,onQuickReopen:u,onStepTask:ge,onOpenMenu:ve,onSplitTask:y,notesSummaryByEntity:N},ee.task.id):e.jsx(ec,{sortableId:`${v}:project:${ee.project.id}`,project:ee.project,goal:ee.goal,isMobile:j,onStepProject:Te,onOpenMenu:Le},ee.project.id)):e.jsx(u3,{title:De.title,detail:De.detail,children:De.items.map(ee=>ee.kind==="task"?e.jsx(Zd,{sortableId:`${v}:task:${ee.task.id}`,task:ee.task,goal:ee.goal,tags:ee.tags,activeRun:ee.activeRun,isSelected:n===ee.task.id,isMobile:j,onSelect:d,onStartTask:m,onStopTask:h,onQuickReopen:u,onStepTask:ge,onOpenMenu:ve,onSplitTask:y,notesSummaryByEntity:N},ee.task.id):e.jsx(ec,{sortableId:`${v}:project:${ee.project.id}`,project:ee.project,goal:ee.goal,isMobile:j,onStepProject:Te,onOpenMenu:Le},ee.project.id))},Z))}c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const F=window.matchMedia("(max-width: 1023px)"),he=we=>{R(we?we.matches:F.matches)};return he(),typeof F.addEventListener=="function"?(F.addEventListener("change",he),()=>F.removeEventListener("change",he)):(F.addListener(he),()=>F.removeListener(he))},[]),c.useEffect(()=>{if(!X){document.body.style.cursor="";return}return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=""}},[X]),c.useEffect(()=>{Ae(F=>{const he=new Set(t.map(De=>De.id));let we=!1;const Z={};for(const[De,ee]of Object.entries(F)){const ze=t.find(et=>et.id===De);if(!he.has(De)||!ze||ze.status===ee){we=!0;continue}Z[De]=ee}return we?Z:F})},[t]),c.useEffect(()=>{Ie(F=>{const he=new Set(s.map(De=>De.id));let we=!1;const Z={};for(const[De,ee]of Object.entries(F)){const ze=s.find(et=>et.id===De);if(!he.has(De)||!ze||ze.workflowStatus===ee){we=!0;continue}Z[De]=ee}return we?Z:F})},[s]);function Ce(F){var Z,De;const he=(Z=F.active.data.current)==null?void 0:Z.taskId,we=(De=F.active.data.current)==null?void 0:De.projectId;typeof he=="string"?Y(he):typeof we=="string"&&Y(we)}const qe=F=>{B(F),typeof window<"u"&&window.localStorage.setItem("forge.kanban-skip-delete-confirmation","true")},oe=async(F,he)=>{if(x){q(F.id);try{he&&qe(!0),await x(F.id),D(null),ae(!1),Ae(we=>{const Z={...we};return delete Z[F.id],Z})}finally{q(null)}}};function L(F){if(x){if(_){oe(F,!1);return}ae(!1),D(F)}}async function U(F){var be,je,pe,$e,Xe,Ue;const{active:he,over:we}=F;if(Y(null),!we||he.id===we.id)return;const Z=typeof((be=he.data.current)==null?void 0:be.taskId)=="string"?he.data.current.taskId:null,De=typeof((je=he.data.current)==null?void 0:je.projectId)=="string"?he.data.current.projectId:null,ee=(Z?xe.find(le=>le.kind==="task"&&le.id===Z):null)??(De?xe.find(le=>le.kind==="project"&&le.id===De):null);if(!ee)return;if(((pe=we.data.current)==null?void 0:pe.type)==="trash"){if(ee.kind!=="task"||!x)return;L(ee.task);return}const ze=typeof(($e=we.data.current)==null?void 0:$e.status)=="string"?we.data.current.status:null,et=typeof((Xe=we.data.current)==null?void 0:Xe.taskId)=="string"?we.data.current.taskId:null,Ve=typeof((Ue=we.data.current)==null?void 0:Ue.projectId)=="string"?we.data.current.projectId:null,re=(et?xe.find(le=>le.kind==="task"&&le.id===et):null)??(Ve?xe.find(le=>le.kind==="project"&&le.id===Ve):null),ne=ze??(re==null?void 0:re.status)??ee.status;if(!(ne===ee.status||!vs.includes(ne))){if(ee.kind==="task"){Ae(le=>({...le,[ee.task.id]:ne}));try{await l(ee.task.id,ne)}catch(le){throw Ae(Me=>{const He={...Me};return delete He[ee.task.id],He}),le}return}if(o){Ie(le=>({...le,[ee.project.id]:ne}));try{await o(ee.project.id,ne)}catch(le){throw Ie(Me=>{const He={...Me};return delete He[ee.project.id],He}),le}}}}async function ge(F,he){const we=M.find(ze=>ze.id===F);if(!we)return;const Z=vs.indexOf(we.status),De=he==="previous"?Z-1:Z+1,ee=vs[De]??null;if(!(!ee||ee===we.status)){Ae(ze=>({...ze,[we.id]:ee}));try{await l(we.id,ee)}catch(ze){throw Ae(et=>{const Ve={...et};return delete Ve[we.id],Ve}),ze}}}async function Te(F,he){const we=E.find(ze=>ze.id===F);if(!we||!o)return;const Z=vs.indexOf(we.workflowStatus),De=he==="previous"?Z-1:Z+1,ee=vs[De]??null;if(!(!ee||ee===we.workflowStatus)){Ie(ze=>({...ze,[we.id]:ee}));try{await o(we.id,ee)}catch(ze){throw Ie(et=>{const Ve={...et};return delete Ve[we.id],Ve}),ze}}}function ve(F,he){const we=F.currentTarget.getBoundingClientRect();K({kind:"task",entityId:he.id,position:{x:we.right-8,y:we.bottom+8}})}function Le(F,he){const we=F.currentTarget.getBoundingClientRect();K({kind:"project",entityId:he.id,position:{x:we.right-8,y:we.bottom+8}})}return e.jsxs(dd,{sensors:Q,collisionDetection:o3,onDragStart:Ce,onDragCancel:()=>Y(null),onDragEnd:F=>void U(F),children:[(V==null?void 0:V.kind)==="task"&&x?e.jsx(m3,{droppableId:H,title:P("common.executionBoard.deleteDropTitle"),detail:P("common.executionBoard.deleteDropDetail")}):null,e.jsx("div",{className:"w-full max-w-full min-w-0 pb-2",children:j?e.jsx("div",{className:"grid w-full max-w-full min-w-0 gap-2",children:vs.map(F=>{const he=xe.filter(we=>we.status===F);return e.jsx(Xn,{items:he.map(we=>`${v}:${we.kind}:${we.id}`),strategy:Yn,children:e.jsx(yp,{droppableId:`${v}:lane:${F}`,status:F,title:Ne[F].title,detail:Ne[F].detail,count:he.length,dragging:X!==null,children:Ee(he)})},F)})}):e.jsx("div",{className:"grid w-full min-w-0 gap-0.5 xl:grid-cols-[repeat(5,minmax(0,1fr))]",children:vs.map(F=>{const he=xe.filter(we=>we.status===F);return e.jsx(Xn,{items:he.map(we=>`${v}:${we.kind}:${we.id}`),strategy:Yn,children:e.jsx(yp,{droppableId:`${v}:lane:${F}`,status:F,title:Ne[F].title,detail:Ne[F].detail,count:he.length,dragging:X!==null,children:Ee(he)})},F)})})}),e.jsx(M0,{adjustScale:!1,dropAnimation:null,children:V?e.jsx("div",{className:"w-[20rem] max-w-[calc(100vw-2rem)]",children:V.kind==="task"?e.jsx(dw,{task:V.task,goal:V.goal,tags:V.tags,activeRun:V.activeRun,isSelected:n===V.task.id,isDragging:!0,isOverlay:!0,isMobile:j,onSelect:()=>{},onStartTask:m,onSplitTask:y,notesSummaryByEntity:N}):e.jsx(cw,{project:V.project,goal:V.goal,isDragging:!0,isOverlay:!0,isMobile:j})}):null}),e.jsx(vd,{open:z!==null,title:(z==null?void 0:z.kind)==="project"?((Qe=E.find(F=>F.id===z.entityId))==null?void 0:Qe.title)??"Project actions":((st=M.find(F=>F.id===(z==null?void 0:z.entityId)))==null?void 0:st.title)??"Work item actions",subtitle:(z==null?void 0:z.kind)==="project"?"Edit, relink, move, or break this project into issues.":"Edit, relink, move, or create the next child work item.",items:Se,position:(z==null?void 0:z.position)??null,onClose:()=>K(null)}),$?e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-[rgba(5,8,18,0.74)] p-4 backdrop-blur-xl",children:e.jsxs(ce,{className:"w-full max-w-md border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,36,0.96),rgba(9,13,22,0.98))] shadow-[0_32px_90px_rgba(5,8,18,0.58)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-1 flex size-11 shrink-0 items-center justify-center rounded-full bg-rose-500/14 text-rose-100",children:e.jsx(Rt,{className:"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-display text-[1.35rem] leading-tight text-white",children:P("common.executionBoard.deleteConfirmTitle")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/64",children:P("common.executionBoard.deleteConfirmDescription",{title:$.title})})]})]}),e.jsxs("label",{className:"mt-5 flex items-center gap-3 rounded-[18px] bg-white/[0.05] px-4 py-3 text-sm text-white/76",children:[e.jsx("input",{type:"checkbox",checked:G,onChange:F=>ae(F.target.checked),className:"size-4 rounded border-white/20 bg-transparent text-[var(--primary)]"}),e.jsx("span",{children:P("common.executionBoard.deleteConfirmCheckbox")})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-3",children:[e.jsx(W,{variant:"secondary",onClick:()=>{D(null),ae(!1)},children:P("common.executionBoard.deleteConfirmCancel")}),e.jsx(W,{className:"bg-[linear-gradient(135deg,rgba(251,113,133,0.3),rgba(190,24,93,0.26))] text-white shadow-[0_16px_36px_rgba(190,24,93,0.18)]",pending:J===$.id,pendingLabel:P("common.executionBoard.deletingTask"),onClick:()=>void oe($,G),children:P("common.executionBoard.deleteConfirmSubmit")})]})]})}):null]})}const Bl=[{to:"/projects",label:"Projects",icon:Cv},{to:"/kanban",label:"Board",icon:Sg},{to:"/projects/hierarchy",label:"Hierarchy",icon:Qr}];function tc(t,s){return s==="/projects"?t==="/projects"||/^\/projects\/[^/]+$/.test(t):t===s||t.startsWith(`${s}/`)}function Id({className:t}){const s=hi(),[a,i]=c.useState(!1),r=c.useMemo(()=>[...Bl].sort((n,l)=>l.to.length-n.to.length).find(n=>tc(s.pathname,n.to))??Bl[0],[s.pathname]);return c.useEffect(()=>{if(!a)return;const n=document.body.style.overflow,l=o=>{o.key==="Escape"&&i(!1)};return document.body.style.overflow="hidden",window.addEventListener("keydown",l),()=>{document.body.style.overflow=n,window.removeEventListener("keydown",l)}},[a]),e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:te("overflow-hidden bg-[linear-gradient(180deg,rgba(15,24,31,0.94),rgba(10,18,25,0.92))] p-2",t),children:[e.jsx("div",{className:"hidden items-center gap-3 lg:flex",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Bl.map(n=>e.jsxs(_a,{to:n.to,end:n.to==="/projects",className:({isActive:l})=>te("inline-flex items-center gap-2 whitespace-nowrap rounded-full px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",l||tc(s.pathname,n.to)?"bg-[rgba(125,211,252,0.16)] text-[#c7f0ff]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx(n.icon,{className:"size-3.5"}),e.jsx("span",{children:n.label})]},n.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsx("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center gap-3 rounded-[22px] border border-white/8 bg-[linear-gradient(180deg,rgba(19,28,42,0.96),rgba(11,17,30,0.94))] px-3.5 py-2.5 text-left shadow-[0_18px_38px_rgba(3,8,18,0.2)] transition hover:border-white/12",onClick:()=>i(!0),children:e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-2xl border border-[rgba(125,211,252,0.2)] bg-[rgba(125,211,252,0.12)]",children:e.jsx(r.icon,{className:"size-4 text-[#c7f0ff]"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[10px] uppercase tracking-[0.18em] text-white/40",children:"Project management"}),e.jsx("span",{className:"mt-0.5 block truncate text-sm font-medium text-white",children:r.label})]})]})})})]}),a&&typeof document<"u"?Qi.createPortal(e.jsxs("div",{className:"lg:hidden",children:[e.jsx("div",{className:"fixed inset-0 z-50 bg-[rgba(5,10,18,0.78)] backdrop-blur-xl"}),e.jsx("button",{type:"button","aria-label":"Close project management sections",className:"fixed inset-0 z-[51]",onClick:()=>i(!1)}),e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[52] flex items-end justify-center px-3 pt-3 sm:px-4 sm:pt-4",style:{paddingBottom:"calc(var(--forge-mobile-nav-clearance) - 0.25rem)"},children:e.jsxs("div",{className:"pointer-events-auto flex max-h-[min(34rem,calc(100dvh-var(--forge-mobile-nav-clearance)-1rem))] w-full max-w-xl min-h-0 flex-col overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.12),transparent_40%),linear-gradient(180deg,rgba(18,27,42,0.98),rgba(10,15,28,0.98))] shadow-[0_36px_110px_rgba(3,8,18,0.5)]",children:[e.jsx("div",{className:"shrink-0 border-b border-white/8 px-4 pb-2.5 pt-3 sm:px-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-white/38",children:"Forge PM"}),e.jsx("div",{className:"mt-1.5 flex min-w-0 flex-wrap items-center gap-2",children:e.jsx("div",{className:"truncate text-[1.05rem] font-semibold text-white",children:"Browse the hierarchy"})})]}),e.jsx("button",{type:"button","aria-label":"Close project management sections",className:"inline-flex size-10 shrink-0 items-center justify-center rounded-full border border-white/8 bg-white/[0.05] text-white/65 transition hover:border-white/12 hover:bg-white/[0.09] hover:text-white",onClick:()=>i(!1),children:e.jsx(Tt,{className:"size-4"})})]})}),e.jsx("div",{className:"min-h-0 overflow-y-auto p-3 overscroll-contain sm:p-4",children:e.jsx("div",{className:"grid gap-2",children:Bl.map(n=>{const l=tc(s.pathname,n.to);return e.jsx(_a,{to:n.to,end:n.to==="/projects",onClick:()=>i(!1),className:te("group flex items-center justify-between gap-3 rounded-[22px] border px-3.5 py-3 transition hover:-translate-y-[1px] hover:text-white",l?"border-[rgba(125,211,252,0.18)] bg-[rgba(125,211,252,0.12)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:border-white/12 hover:bg-white/[0.06]"),children:e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex size-10 items-center justify-center rounded-2xl border border-white/8 bg-white/[0.04]",children:e.jsx(n.icon,{className:"size-4"})}),e.jsx("span",{className:"text-sm font-medium",children:n.label})]})},n.to)})})})]})})]}),document.body):null]})}const Ma={goal:"goal:",project:"project:",tag:"tag:"},Ei={user:"user:",kind:"kind:"},h3=[{value:"project",label:"Project",searchText:"project initiative prd"},{value:"issue",label:"Issue",searchText:"issue vertical slice tracer bullet"},{value:"task",label:"Task",searchText:"task focused ai session"},{value:"subtask",label:"Subtask",searchText:"subtask child step"}];function sc(t){return t.trim().toLowerCase()}function p3(t){return t.reduce((s,a)=>(a.startsWith(Ma.goal)?s.goalIds.push(a.slice(Ma.goal.length)):a.startsWith(Ma.project)?s.projectIds.push(a.slice(Ma.project.length)):a.startsWith(Ma.tag)&&s.tagIds.push(a.slice(Ma.tag.length)),s),{goalIds:[],projectIds:[],tagIds:[]})}function x3(t){return t.reduce((s,a)=>{if(a.startsWith(Ei.user))s.userIds.push(a.slice(Ei.user.length));else if(a.startsWith(Ei.kind)){const i=a.slice(Ei.kind.length);(i==="human"||i==="bot")&&s.kinds.push(i)}return s},{userIds:[],kinds:[]})}function vp(t,s,a,i){t([]),s([]),a(""),i(["task","subtask"])}function g3(t){const s=t.trim();return s.length===0?{firstTitle:"Split task part 1",secondTitle:"Split task part 2"}:{firstTitle:`${s} - part 1`,secondTitle:`${s} - part 2`}}function f3(){var U,ge,Te,ve,Le,Qe,st;const{t}=Ot(),s=jt(),a=$t(),i=ct(),[r,n]=c.useState([]),[l,o]=c.useState([]),[d,m]=c.useState(""),[h,u]=c.useState(["task","subtask"]),[x,g]=c.useState(((ge=(U=s.snapshot.workItems)==null?void 0:U[0])==null?void 0:ge.id)??((Te=s.snapshot.tasks[0])==null?void 0:Te.id)??null),[p,f]=c.useState(null),[b,A]=c.useState(void 0),[C,T]=c.useState(null),[w,S]=c.useState(void 0),[y,N]=c.useState(null),[P,v]=c.useState(null),[H,j]=c.useState({firstTitle:"",secondTitle:"",remainingRatio:.5}),R=c.useMemo(()=>[...s.snapshot.goals.map(F=>({value:`${Ma.goal}${F.id}`,label:F.title,description:"Goal",searchText:`goal ${F.title} ${F.description??""}`,kind:"goal"})),...s.snapshot.dashboard.projects.map(F=>({value:`${Ma.project}${F.id}`,label:F.title,description:"Project",searchText:`project ${F.title} ${F.description??""} ${F.goalTitle??""}`,kind:"project"})),...s.snapshot.tags.map(F=>({value:`${Ma.tag}${F.id}`,label:F.name,description:"Tag",searchText:`tag ${F.name} ${F.color??""}`,kind:"tag"}))],[s.snapshot.dashboard.projects,s.snapshot.goals,s.snapshot.tags]),Q=c.useMemo(()=>{const F=s.snapshot.users.filter(we=>we.kind==="bot"),he=s.snapshot.users.filter(we=>we.kind==="human");return[{value:`${Ei.kind}bot`,label:"Bots",description:`${F.length} bot owner${F.length===1?"":"s"}`,searchText:`bots bot ai agents assistants ${F.map(we=>`${we.displayName} ${we.handle}`).join(" ")}`,badge:e.jsx(I,{className:"border-cyan-300/18 bg-cyan-400/12 text-cyan-50",children:"Bots"}),menuBadge:e.jsx(I,{className:"border-cyan-300/18 bg-cyan-400/12 text-cyan-50",children:"Bots"})},{value:`${Ei.kind}human`,label:"Humans",description:`${he.length} human owner${he.length===1?"":"s"}`,searchText:`humans human people operators ${he.map(we=>`${we.displayName} ${we.handle}`).join(" ")}`,badge:e.jsx(I,{className:"border-amber-300/18 bg-amber-400/12 text-amber-50",children:"Humans"}),menuBadge:e.jsx(I,{className:"border-amber-300/18 bg-amber-400/12 text-amber-50",children:"Humans"})},...s.snapshot.users.map(we=>({value:`${Ei.user}${we.id}`,label:we.displayName,description:`${we.kind}${we.handle?` · @${we.handle}`:""}`,searchText:`${we.displayName} ${we.handle} ${we.kind} ${we.description}`,badge:e.jsx(ot,{user:we,compact:!0}),menuBadge:e.jsx(ot,{user:we,compact:!0})}))]},[s.snapshot.users]),X=c.useMemo(()=>h3.map(F=>({value:F.value,label:F.label,searchText:F.searchText,badge:F.value==="subtask"?e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"}):e.jsx(We,{kind:F.kind??F.value,label:F.label,compact:!0,gradient:!1}),menuBadge:F.value==="subtask"?e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"}):e.jsx(We,{kind:F.kind??F.value,label:F.label,compact:!0,gradient:!1})})),[]),Y=c.useMemo(()=>p3(r),[r]),z=c.useMemo(()=>x3(l),[l]),K=c.useMemo(()=>sc(d),[d]),$=c.useMemo(()=>s.snapshot.workItems&&s.snapshot.workItems.length>0?s.snapshot.workItems:s.snapshot.tasks,[s.snapshot.tasks,s.snapshot.workItems]),D=c.useMemo(()=>new Map(s.snapshot.dashboard.projects.map(F=>[F.id,F])),[s.snapshot.dashboard.projects]),J=$.filter(F=>{var he;if(!h.includes(F.level))return!1;if(K.length>0){const we=F.projectId?D.get(F.projectId)??null:null;if(!sc([F.title,F.description,F.level,F.aiInstructions??"",F.executionMode??"",(we==null?void 0:we.title)??"",(we==null?void 0:we.goalTitle)??"",((he=F.user)==null?void 0:he.displayName)??"",...(F.assignees??[]).map(De=>De.displayName)].join(" ")).includes(K))return!1}if(Y.goalIds.length>0&&(F.goalId===null||!Y.goalIds.includes(F.goalId))||Y.projectIds.length>0&&(F.projectId===null||!Y.projectIds.includes(F.projectId))||Y.tagIds.length>0&&!Y.tagIds.every(we=>F.tagIds.includes(we)))return!1;if(z.userIds.length>0||z.kinds.length>0){const we=[...F.user?[F.user]:[],...F.assignees??[]],Z=we.some(ee=>z.userIds.includes(ee.id)),De=we.some(ee=>z.kinds.includes(ee.kind));if(!Z&&!De)return!1}return!0}),q=s.snapshot.dashboard.projects.filter(F=>{var he;if(!h.includes("project")||K.length>0&&!sc([F.title,F.description,F.goalTitle,F.productRequirementsDocument,((he=F.user)==null?void 0:he.displayName)??"",...(F.assignees??[]).map(Z=>Z.displayName)].join(" ")).includes(K)||Y.goalIds.length>0&&!Y.goalIds.includes(F.goalId)||Y.projectIds.length>0&&!Y.projectIds.includes(F.id))return!1;if(z.userIds.length>0||z.kinds.length>0){const we=[...F.user?[F.user]:[],...F.assignees??[]],Z=we.some(ee=>z.userIds.includes(ee.id)),De=we.some(ee=>z.kinds.includes(ee.kind));if(!Z&&!De)return!1}return!0}),_=J.length+q.length,B=q.length>0||J.length>0,G=d.trim().length>0||r.length>0||l.length>0||h.length!==2||!h.includes("task")||!h.includes("subtask"),ae=J.find(F=>F.id===x)??$.find(F=>F.id===x)??null,ke=p?s.snapshot.dashboard.projects.find(F=>F.id===p)??null:null,Ae=C?$.find(F=>F.id===C)??null:null,ie=J.filter(F=>F.status==="blocked").length,Ie=J.filter(F=>F.status==="done").length,Ne=J.filter(F=>F.status==="focus"||F.status==="in_progress").length,M=s.snapshot.activeTaskRuns.length,E=ys(s.selectedUserIds),O=P?$.find(F=>F.id===P)??null:null,xe=async()=>{await Promise.all([s.refresh(),Ut(i),i.invalidateQueries({queryKey:["project-board"]}),i.invalidateQueries({queryKey:["task-context"]})])},V=Re({mutationFn:({taskId:F,patch:he})=>s.patchTask(F,he),onSuccess:xe}),Se=Re({mutationFn:F=>rm(F),onSuccess:xe}),Ee=Re({mutationFn:lm,onSuccess:xe}),Ce=Re({mutationFn:({taskId:F,firstTitle:he,secondTitle:we,remainingRatio:Z})=>vk(F,{firstTitle:he,secondTitle:we,remainingRatio:Z}),onSuccess:async()=>{await xe(),v(null)}}),qe=(F,he)=>{f(F),A(he)},oe=(F,he)=>{T(F),N(null),S(he)},L=F=>{T(null),S(void 0),N(F)};return $.length===0&&s.snapshot.dashboard.projects.length===0?e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(nt,{title:"Kanban",description:"Move tasks across the board, start work quickly, and keep your next step visible.",badge:"0 visible tasks",actions:e.jsx(W,{size:"lg",onClick:()=>s.openStartWork(),children:"Start work"})}),e.jsx(Bt,{eyebrow:t("common.kanban.heroEyebrow"),title:t("common.kanban.emptyTitle"),description:t("common.kanban.emptyDescription"),action:e.jsx(Je,{to:"/goals",className:"inline-flex 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.kanban.emptyAction")})})]}):e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(Id,{}),e.jsx(nt,{title:"Kanban",description:"Move projects, issues, tasks, and subtasks through one shared execution board, then open the right layer when you need to inspect or edit it.",badge:`${_} visible work items`,actions:e.jsx(W,{size:"lg",onClick:()=>s.openStartWork(ae?{taskId:ae.id}:void 0),children:"Start work"})}),e.jsx(db,{children:e.jsx(ce,{className:"min-w-0 overflow-hidden",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Board"}),e.jsx("div",{className:"mt-2 text-base text-white",children:"See projects, issues, tasks, and subtasks in the same workflow lanes, with one card language and one shared board state."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Ne," ready or active"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[ie," blocked"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Ie," done"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[M," live timer",M===1?"":"s"]}),e.jsxs(I,{className:"bg-[var(--primary)]/12 text-[var(--primary)]",children:[Math.round(((ve=s.snapshot.lifeForce)==null?void 0:ve.spentTodayAp)??0)," /"," ",Math.round(((Le=s.snapshot.lifeForce)==null?void 0:Le.dailyBudgetAp)??0)," AP"]})]})]})})}),e.jsx(cb,{children:e.jsxs(ce,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"type-label text-white/40",children:"Filters"}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Use compact entity chips for goals, projects, tags, and owner scopes instead of the wide pill rows."})]}),G?e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>vp(n,o,m,u),children:"Reset"}):null]}),e.jsxs("div",{className:"mt-4 grid gap-3 xl:grid-cols-[minmax(0,1fr)_minmax(18rem,24rem)]",children:[e.jsx("div",{className:"rounded-[22px] border border-white/10 bg-black/20 px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/36"}),e.jsx("input",{value:d,onChange:F=>m(F.target.value),placeholder:"Search projects, issues, tasks, subtasks, PRDs, owners, and assignees",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"}),d.trim().length>0?e.jsx("button",{type:"button",className:"rounded-full text-white/46 transition hover:text-white",onClick:()=>m(""),"aria-label":"Clear board search",children:e.jsx(Tt,{className:"size-4"})}):null]})}),e.jsx(mt,{options:X,selectedValues:h,onChange:F=>u(F),placeholder:"Work item types",emptyMessage:"No work-item levels.",variant:"action-bar"})]}),e.jsxs("div",{className:"mt-3 grid gap-3 xl:grid-cols-[minmax(0,1.55fr)_minmax(18rem,1fr)]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Entity filters"}),e.jsx(mt,{options:R,selectedValues:r,onChange:n,placeholder:"Filter by goal, project, or tag",emptyMessage:"No matching goals, projects, or tags."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Owner filters"}),e.jsx(mt,{options:Q,selectedValues:l,onChange:o,placeholder:"Type Bo for bots, Hu for humans, or a teammate name",emptyMessage:"No matching owners."})]})]})]})}),B?e.jsx(ub,{children:e.jsx(uw,{tasks:J,projects:q,activeRuns:s.snapshot.activeTaskRuns,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:x,onMove:async(F,he)=>{await s.patchTaskStatus(F,he)},onMoveProject:async(F,he)=>{await s.patchProject(F,{workflowStatus:he})},onQuickReopenTask:async F=>{await nm(F),await xe()},onDeleteTask:async F=>{await Se.mutateAsync(F),g(he=>{var we;return he!==F?he:((we=J.find(Z=>Z.id!==F))==null?void 0:we.id)??null}),T(he=>he===F?null:he)},onStartTask:async F=>{await s.startTaskNow(F),g(F),await i.invalidateQueries({queryKey:["task-context",F]})},onStopTask:async F=>{await s.stopTaskRun(F),g(F.taskId),await i.invalidateQueries({queryKey:["task-context",F.taskId]})},onSelectTask:F=>{g(F)},onOpenProject:F=>{a(`/projects/${F}`)},onOpenTask:F=>{a(`/tasks/${F}`)},onEditProject:F=>{qe(F)},onEditTask:F=>{oe(F)},onLinkProject:F=>{qe(F,"anchor")},onLinkTask:F=>{oe(F,"anchor")},onCreateIssueForProject:F=>{const he=s.snapshot.dashboard.projects.find(we=>we.id===F)??null;he&&L({initialLevel:"issue",initialGoalId:he.goalId,initialProjectId:he.id})},onCreateTaskForIssue:F=>{const he=$.find(we=>we.id===F)??null;he&&L({initialLevel:"task",initialGoalId:he.goalId,initialProjectId:he.projectId,initialParentWorkItemId:he.id})},onCreateSubtaskForTask:F=>{const he=$.find(we=>we.id===F)??null;he&&L({initialLevel:"subtask",initialGoalId:he.goalId,initialProjectId:he.projectId,initialParentWorkItemId:he.id})},onSplitTask:F=>{const he=$.find(Z=>Z.id===F)??null;if(!he)return;const we=g3(he.title);v(F),j({firstTitle:we.firstTitle,secondTitle:we.secondTitle,remainingRatio:.5})}})}):e.jsx(Bt,{eyebrow:t("common.kanban.heroEyebrow"),title:t("common.kanban.noTasksMatch"),description:"No tasks match the current filters. Reset the filters to bring the full board back.",action:e.jsx(W,{variant:"secondary",onClick:()=>vp(n,o,m,u),children:"Reset"})}),e.jsx(fd,{open:ke!==null,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:ke,defaultUserId:(ke==null?void 0:ke.userId)??E,initialStepId:b,onOpenChange:F=>{F||(f(null),A(void 0))},onSubmit:async(F,he)=>{he&&(await s.patchProject(he,F),f(null),A(void 0))}}),e.jsx(bd,{open:Ae!==null||y!==null,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,workItems:$,tags:s.snapshot.tags,users:s.snapshot.users,editingTask:Ae,initialGoalId:y==null?void 0:y.initialGoalId,initialProjectId:y==null?void 0:y.initialProjectId,initialParentWorkItemId:y==null?void 0:y.initialParentWorkItemId,initialLevel:y==null?void 0:y.initialLevel,initialStepId:w,defaultUserId:(Ae==null?void 0:Ae.userId)??E,onRefreshEntities:s.refresh,currentCreditedSeconds:Ae==null?void 0:Ae.time.totalCreditedSeconds,onOpenChange:F=>{F||(T(null),N(null),S(void 0))},onAdjustTrackedTime:Ae?async F=>{await Ee.mutateAsync(F)}:void 0,onSubmit:async(F,he)=>{he?await V.mutateAsync({taskId:he,patch:F}):await s.createTask(F),T(null),N(null),S(void 0)}}),O?e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-[rgba(5,8,18,0.74)] p-4 backdrop-blur-xl",children:e.jsxs(ce,{className:"w-full max-w-xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,36,0.96),rgba(9,13,22,0.98))] shadow-[0_32px_90px_rgba(5,8,18,0.58)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-1 flex size-11 shrink-0 items-center justify-center rounded-full bg-amber-400/14 text-amber-100",children:e.jsx(ad,{className:"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-display text-[1.35rem] leading-tight text-white",children:"Split this task"}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/64",children:[O.title," has grown beyond its expected shape. Split the remaining work into two child tasks while keeping the original history intact."]})]})]}),e.jsxs("div",{className:"mt-5 grid gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"First task name"}),e.jsx(ye,{value:H.firstTitle,onChange:F=>j(he=>({...he,firstTitle:F.target.value}))})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Second task name"}),e.jsx(ye,{value:H.secondTitle,onChange:F=>j(he=>({...he,secondTitle:F.target.value}))})]}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm text-white/70",children:[e.jsx("span",{children:"Remaining work ratio"}),e.jsxs("span",{children:[Math.round(H.remainingRatio*100),"% / ",100-Math.round(H.remainingRatio*100),"%"]})]}),e.jsx("input",{type:"range",min:25,max:75,step:5,value:Math.round(H.remainingRatio*100),onChange:F=>j(he=>({...he,remainingRatio:Number(F.target.value)/100}))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Math.round((((Qe=O.actionPointSummary)==null?void 0:Qe.totalCostAp)??0)*H.remainingRatio)," ","AP first child"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Math.round((((st=O.actionPointSummary)==null?void 0:st.totalCostAp)??0)*(1-H.remainingRatio))," ","AP second child"]})]})]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-3",children:[e.jsx(W,{variant:"secondary",onClick:()=>{v(null)},children:"Cancel"}),e.jsx(W,{pending:Ce.isPending,disabled:H.firstTitle.trim().length===0||H.secondTitle.trim().length===0,onClick:()=>{Ce.mutateAsync({taskId:O.id,firstTitle:H.firstTitle.trim(),secondTitle:H.secondTitle.trim(),remainingRatio:H.remainingRatio})},children:"Create split tasks"})]})]})}):null]})}const b3=Math.PI*(3-Math.sqrt(5)),w3=.48;function il(t,s,a){return Math.min(a,Math.max(s,t))}function y3({positions:t,point:s}){const a=[...t.values()];if(a.length===0)return{x:.5,y:.5};let i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const p of a)i=Math.min(i,p.x),r=Math.max(r,p.x),n=Math.min(n,p.y),l=Math.max(l,p.y);const o=Math.max(r-i,0),d=Math.max(l-n,0),m=Math.max(o,d,1),h=(1-o/m)/2,u=(1-d/m)/2,x=o||1,g=d||1;return{x:il((s.x-i)/x*(o/m)+h,0,1),y:il((s.y-n)/g*(d/m)+u,0,1)}}function v3(t){let s=2166136261;for(let a=0;a<t.length;a+=1)s^=t.charCodeAt(a),s=Math.imul(s,16777619);return s>>>0}function j3({nodes:t,cache:s}){const a=new Map,i=[...t].sort((o,d)=>d.importance-o.importance||o.title.localeCompare(d.title)||o.id.localeCompare(d.id));let r=0,n=0,l=0;if(i.forEach((o,d)=>{const m=s.get(o.id);if(m){a.set(o.id,m),r+=m.x,n+=m.y,l+=1;return}const h=(v3(o.id)%1e3/1e3-.5)*.22,u=d*b3+h,x=w3*Math.sqrt(d+1),g={x:Math.cos(u)*x,y:Math.sin(u)*x};a.set(o.id,g),r+=g.x,n+=g.y,l+=1}),l>0){const o=r/l,d=n/l;a.forEach((m,h)=>{a.set(h,{x:m.x-o,y:m.y-d})})}return a}function N3(t,s){if(t.startsWith("rgb(")&&t.endsWith(")"))return t.replace("rgb(","rgba(").replace(")",`, ${s})`);if(t.startsWith("#")){const a=t.slice(1),i=a.length===3?a.split("").map(o=>`${o}${o}`).join(""):a,r=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),l=parseInt(i.slice(4,6),16);return`rgba(${r}, ${n}, ${l}, ${s})`}return t}function lr(t,s){return`rgba(${t==="structural"?"125, 211, 252":t==="contextual"?"45, 212, 191":t==="taxonomy"?"192, 132, 252":t==="workspace"?"251, 191, 36":"148, 163, 184"}, ${s})`}function jp(t,s){return!s.focusNodeId||t===s.focusNodeId?0:s.detailNodeIds.has(t)?1:s.relatedNodeIds.has(t)?2:3}function k3({nodeId:t,attributes:s,node:a,focusNodeId:i,relatedNodeIds:r,detailNodeIds:n,hoveredNodeId:l,draggedNodeId:o}){const d=i===t,m=r.has(t),h=n.has(t),u=l===t,x=o===t,g=!i||m,p=s.color;return{...s,label:d||u||x||h?a.title:"",forceLabel:d||u||x||h,highlighted:d||u||x||h,color:g?p:N3(p,.34),size:x?s.size*2:d?s.size*1.8:u?s.size*1.35:h?s.size*1.16:m?s.size*1.06:s.size,zIndex:x?4:d?3:h||u?2:1}}function S3({attributes:t,edge:s,focusNodeId:a,detailNodeIds:i,relatedNodeIds:r,hoveredNodeId:n}){const l=!!a&&(s.source===a||s.target===a),o=!!n&&(s.source===n||s.target===n),d={focusNodeId:a,detailNodeIds:i,relatedNodeIds:r},m=a?Math.max(jp(s.source,d),jp(s.target,d)):0,h=l?lr(s.family,.24):o?lr(s.family,.14):a?m<=1?lr(s.family,.09):m===2?lr(s.family,.05):lr(s.family,.016):lr(s.family,.055);return{...t,color:h,size:l?t.size*1.18:o?t.size*1.08:t.size,zIndex:l?2:o?1:0}}function Np(t,s){const a=new Set,i=new Set;for(const r of t)r.source===s?a.add(r.target):r.target===s&&a.add(r.source);for(const r of t)r.source!==s&&a.has(r.source)&&i.add(r.target),r.target!==s&&a.has(r.target)&&i.add(r.source);return i.delete(s),a.forEach(r=>i.delete(r)),{firstRing:[...a].sort(),secondRing:[...i].sort()}}function kp(t,s,a){if(!a)return t.map(()=>-1);const i=new Set(t);if(!i.has(a))return t.map(()=>-1);const r=new Map;for(const o of s){if(!i.has(o.source)||!i.has(o.target))continue;const d=r.get(o.source)??new Set;d.add(o.target),r.set(o.source,d);const m=r.get(o.target)??new Set;m.add(o.source),r.set(o.target,m)}const n=new Map([[a,0]]);let l=[a];for(;l.length>0;){const o=[];for(const d of l){const m=n.get(d);for(const h of r.get(d)??[])n.has(h)||(n.set(h,m+1),o.push(h))}l=o}return t.map(o=>n.get(o)??-1)}function I3({positions:t,focusNodeId:s,firstRingNodeIds:a,secondRingNodeIds:i,currentRatio:r}){const n=t.get(s);if(!n)return null;const l=[s,...a,...i].filter((T,w,S)=>S.indexOf(T)===w),o=l.map(T=>t.get(T)).filter(Boolean);if(o.length===0)return null;let d=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,h=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY,x=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,p=Number.POSITIVE_INFINITY,f=Number.NEGATIVE_INFINITY;for(const T of t.values())x=Math.min(x,T.x),g=Math.max(g,T.x),p=Math.min(p,T.y),f=Math.max(f,T.y);for(const T of o)d=Math.min(d,T.x),m=Math.max(m,T.x),h=Math.min(h,T.y),u=Math.max(u,T.y);const b=Math.max(m-d,u-h,.75),A=Math.max(g-x,f-p,b),C=o.length<=1?il(Math.max(r,.48),.38,.6):il(b/A*3.2,.42,Math.max(r,1.12));return{x:n.x,y:n.y,ratio:C,nodeIds:l}}function mw({positions:t,currentRatio:s=1}){const a=[...t.values()];if(a.length===0)return{x:0,y:0,ratio:s};let i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const m of a)i=Math.min(i,m.x),r=Math.max(r,m.x),n=Math.min(n,m.y),l=Math.max(l,m.y);const o=Math.max(r-i,l-n,1),d=il(o/6.4,.72,2.8);return{x:0,y:0,ratio:Math.max(s,d)}}function Sp(t){const s=iu.indexOf(t);return s>=0?s:iu.length-1}function C3(t){const s=Tr.find(a=>a.kinds.some(i=>i===t))??Tr[Tr.length-1];return{laneId:s.id,laneLabel:s.label,laneIndex:Tr.findIndex(a=>a.id===s.id)}}function Ul(){return{structural:0,contextual:0,taxonomy:0,workspace:0}}function T3(t){const s=new Map;for(const a of t){const i=s.get(a.source)??new Set;i.add(a.target),s.set(a.source,i);const r=s.get(a.target)??new Set;r.add(a.source),s.set(a.target,r)}return s}function P3(t,s){return s.strength-t.strength||t.relationKind.localeCompare(s.relationKind)||t.label.localeCompare(s.label)||t.id.localeCompare(s.id)}function hw(t){const s=new Map;for(const a of t){const i=`${a.source}→${a.target}`,r=s.get(i)??[];r.push(a),s.set(i,r)}return Array.from(s.entries()).map(([a,i])=>{const r=[...i].sort(P3),n=r[0],l=r.length,o=Math.max(...r.map(d=>d.strength))*Math.min(1.45,1+(l-1)*.12);return{id:`${a}#${n.id}`,source:n.source,target:n.target,relationKind:n.relationKind,family:n.family,label:l>1?`${n.label} +${l-1}`:n.label,strength:o,directional:n.directional,structural:n.structural,parallelCount:l,data:r}}).sort((a,i)=>a.source.localeCompare(i.source)||a.target.localeCompare(i.target)||a.id.localeCompare(i.id))}function A3(t,s){const a=hw(s),i=[...t].sort((n,l)=>{var o;return n.id.localeCompare(l.id)||((o=n.updatedAt)==null?void 0:o.localeCompare(l.updatedAt??""))||0}).map(n=>`${n.id}:${n.title}:${n.size}:${n.importance}:${n.updatedAt??""}`).join("|"),r=a.map(n=>`${n.source}:${n.target}:${n.parallelCount}:${n.label}:${n.strength.toFixed(3)}`).join("|");return`${t.length}/${a.length}/${i}::${r}`}function pw(t,s){const a=[...t].sort((o,d)=>{const m=Sp(o.entityKind)-Sp(d.entityKind);return m!==0?m:d.importance-o.importance||o.title.localeCompare(d.title)}),i=new Map,r=a.map(o=>{const{laneId:d,laneIndex:m,laneLabel:h}=C3(o.entityKind),u=i.get(m)??0;return i.set(m,u+1),{...o,layer:m,laneId:d,laneLabel:h,row:u}}),n=new Map(r.map(o=>[o.id,o])),l=s.map(o=>{const d=n.get(o.source),m=n.get(o.target),h=(d==null?void 0:d.layer)??0,u=(m==null?void 0:m.layer)??0;return{...o,secondary:u<=h||o.family!=="structural"&&o.family!=="taxonomy"}});return{nodes:r,edges:l}}function Ip(t,s,a){const i=new Map(t.map(g=>[g.id,g])),r=a?i.get(a)??null:null;if(!r)return{generatedAt:new Date().toISOString(),focusNode:null,firstRingNodes:[],neighborhoodEdges:[],familyGroups:[],relationCounts:Ul(),secondRingCounts:Ul()};const n=s.filter(g=>g.source===r.id||g.target===r.id),l=Array.from(new Set(n.flatMap(g=>g.source===r.id?[g.target]:[g.source]))),o=l.map(g=>i.get(g)??null).filter(g=>!!g),d=new Map,m=Ul(),h=Ul(),u=T3(s);for(const g of l){const p=u.get(g)??new Set;for(const f of p){if(f===r.id||l.includes(f))continue;const b=s.filter(A=>A.source===g&&A.target===f||A.target===g&&A.source===f);for(const A of b)h[A.family]+=1}}for(const g of n){const p=g.source===r.id?g.target:g.source,f=i.get(p);if(!f)continue;m[g.family]+=1;const b=d.get(g.relationKind);if(b){b.items.some(A=>A.id===f.id)||b.items.push(f);continue}d.set(g.relationKind,{relationKind:g.relationKind,family:g.family,label:LS[g.relationKind],items:[f]})}const x=new Map;for(const g of d.values()){const p=x.get(g.family);if(p){p.relations.push({...g,items:[...g.items].sort((f,b)=>f.title.localeCompare(b.title))}),p.itemCount+=g.items.length,p.relationCount+=1;continue}x.set(g.family,{family:g.family,label:DS[g.family],relationCount:1,itemCount:g.items.length,relations:[{...g,items:[...g.items].sort((f,b)=>f.title.localeCompare(b.title))}]})}return{generatedAt:new Date().toISOString(),focusNode:r,firstRingNodes:o.sort((g,p)=>g.title.localeCompare(p.title)),neighborhoodEdges:n,familyGroups:[...x.values()].map(g=>({...g,relations:g.relations.sort((p,f)=>p.label.localeCompare(f.label))})).sort((g,p)=>g.label.localeCompare(p.label)),relationCounts:m,secondRingCounts:h}}function M3(t,s){return FS(t,s)}function E3(t,s){if(!t)return new Set;const a=new Set([t]);for(const i of s)i.source===t?a.add(i.target):i.target===t&&a.add(i.source);return a}let gn=null;function L3(){if(typeof window>"u")return!1;if(window.__FORGE_ENABLE_GRAPH_DIAGNOSTICS__)return!0;try{return new URLSearchParams(window.location.search).get("graphDiagnostics")==="1"}catch{return!1}}function Cp(){typeof window>"u"||(delete window.__FORGE_KNOWLEDGE_GRAPH_DIAGNOSTICS__,delete window.__FORGE_KNOWLEDGE_GRAPH_TEST_API__)}function D3(){if(gn!==null)return gn;if(typeof document>"u")return gn=!1,!1;const t=document.createElement("canvas");return gn=!!(t.getContext("webgl2")||t.getContext("webgl")||t.getContext("experimental-webgl")),gn}function F3(t){if(!t||typeof window>"u")return"#c0c1ff";const s=getComputedStyle(document.documentElement).getPropertyValue(t).trim();return s?`rgb(${s})`:"#c0c1ff"}function _3(t,s){if(t.startsWith("rgb(")&&t.endsWith(")"))return t.replace("rgb(","rgba(").replace(")",`, ${s})`);if(t.startsWith("#")){const a=t.slice(1),i=a.length===3?a.split("").map(o=>`${o}${o}`).join(""):a,r=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),l=parseInt(i.slice(4,6),16);return`rgba(${r}, ${n}, ${l}, ${s})`}return t}function fn(t,s){t.forEachNode(a=>{const i=t.getNodeAttributes(a);Number.isFinite(i.x)&&Number.isFinite(i.y)&&s.set(a,{x:i.x,y:i.y})})}function R3(t,s,a){const i=new Pv,r=[...t].sort((l,o)=>o.importance-l.importance||l.title.localeCompare(o.title)||l.id.localeCompare(o.id)),n=j3({nodes:r,cache:a});return r.forEach(l=>{const o=n.get(l.id);i.addNode(l.id,{x:(o==null?void 0:o.x)??0,y:(o==null?void 0:o.y)??0,size:Math.max(2.5,l.size/14),color:F3(l.accentToken),label:l.title,hidden:!1,forceLabel:!1,highlighted:!1,zIndex:0,data:l})}),s.forEach(l=>{!i.hasNode(l.source)||!i.hasNode(l.target)||i.addEdgeWithKey(l.id,l.source,l.target,{size:Math.max(.8,l.strength*1.6),color:l.family==="structural"?"rgba(125, 211, 252, 0.055)":l.family==="contextual"?"rgba(45, 212, 191, 0.055)":l.family==="taxonomy"?"rgba(192, 132, 252, 0.055)":l.family==="workspace"?"rgba(251, 191, 36, 0.055)":"rgba(148, 163, 184, 0.055)",label:l.label,hidden:!1,forceLabel:!1,zIndex:0,data:l})}),i}function Tp(t){if(t.order===0)return;let s=0,a=0,i=0;if(t.forEachNode(l=>{const o=t.getNodeAttributes(l);s+=o.x,a+=o.y,i+=1}),i===0)return;const r=s/i,n=a/i;Math.abs(r)<1e-4&&Math.abs(n)<1e-4||t.updateEachNodeAttributes((l,o)=>({...o,x:o.x-r,y:o.y-n}),{attributes:["x","y"]})}function Pp(t){const s=new Map;return t.forEachNode(a=>{const i=t.getNodeAttributes(a);s.set(a,{x:i.x,y:i.y})}),s}function or(t,s){return{nodes:t.nodes().map(a=>({id:a,...t.getNodeAttributes(a)})),edges:s}}function $3(t){if(t.nodes.length===0)return{minX:-1,maxX:1,minY:-1,maxY:1};let s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const n of t.nodes)s=Math.min(s,n.x),a=Math.max(a,n.x),i=Math.min(i,n.y),r=Math.max(r,n.y);return{minX:s,maxX:a,minY:i,maxY:r}}function O3(t){const s=mw({positions:new Map(t.nodes.map(a=>[a.id,{x:a.x,y:a.y}])),currentRatio:1});return{x:s.x,y:s.y,angle:0,ratio:s.ratio}}function z3({x:t,y:s}){const a=Array.from({length:t.length},(r,n)=>({x:t[n]??0,y:s[n]??0})),i=IS(a);return i.changed?{changed:!0,offsetX:i.offset.x,offsetY:i.offset.y,x:new Float32Array(i.positions.map(r=>r.x)),y:new Float32Array(i.positions.map(r=>r.y))}:{changed:!1,offsetX:0,offsetY:0,x:new Float32Array(t),y:new Float32Array(s)}}function xw({node:t,snapshot:s,camera:a,width:i,height:r}){const n=$3(s),l=Math.max(1,n.maxX-n.minX),o=Math.max(1,n.maxY-n.minY),d=28,h=Math.min(Math.max(1,i-d*2)/l,Math.max(1,r-d*2)/o)/Math.max(a.ratio,.08);return{x:i/2+(t.x-a.x)*h,y:r/2-(t.y-a.y)*h,size:Math.max(4,t.size*h*.12)}}function K3({datasetSignature:t,focusNodeId:s,primaryFocusedNodeId:a,draggedNodeId:i,graph:r,layoutGeneration:n,sigma:l,startupPhase:o,startupInvariantSatisfied:d,simulationPhase:m,focusSources:h,focusPressure:u,centroid:x,cameraTarget:g,latestSnapshotAt:p,latestSnapshotNodeCount:f}){const b=[],A={},C={};let T=null;r.forEachNode(N=>{b.push(N);const P=l.getNodeDisplayData(N),v=r.getNodeAttributes(N),H=l.graphToViewport({x:v.x,y:v.y});A[N]={x:H.x,y:H.y,size:(P==null?void 0:P.size)??v.size},C[N]=Number((u[b.length-1]??0).toFixed(4)),N===a&&(T={x:v.x,y:v.y})});const w=hm(b.map(N=>{const P=r.getNodeAttributes(N);return{x:P.x,y:P.y}})),S=l.getCamera().getState(),y=pm({centroid:x,boundsCenter:w,camera:S});window.__FORGE_KNOWLEDGE_GRAPH_DIAGNOSTICS__={datasetSignature:t,visibleNodeIds:b,visibleNodeCount:b.length,focusedNodeId:s,primaryFocusedNodeId:a,draggedNodeId:i,layoutGeneration:n,rendererMode:"sigma",startupPhase:o,startupInvariantSatisfied:d,simulationPhase:m,focusSources:h,focusPressureByNodeId:C,graphCentroid:x,boundsCenter:w,focusedNodePosition:T,cameraTarget:g,cameraFollowError:g?{x:Number((S.x-g.x).toFixed(4)),y:Number((S.y-g.y).toFixed(4)),ratio:Number((S.ratio-g.ratio).toFixed(4))}:null,camera:S,nodeScreenPositions:A,centroidDistanceFromOrigin:y.centroidDistanceFromOrigin,boundsCenterDistanceFromOrigin:y.boundsCenterDistanceFromOrigin,cameraDistanceFromOrigin:y.cameraDistanceFromOrigin,cameraToCentroidDistance:y.cameraToCentroidDistance,latestSnapshotAt:p,latestSnapshotNodeCount:f}}function Ap({datasetSignature:t,focusNodeId:s,primaryFocusedNodeId:a,draggedNodeId:i,layoutGeneration:r,camera:n,snapshot:l,width:o,height:d,startupPhase:m,startupInvariantSatisfied:h,simulationPhase:u,focusSources:x,focusPressure:g,centroid:p,cameraTarget:f,latestSnapshotAt:b,latestSnapshotNodeCount:A}){const C=l.nodes.map(P=>P.id),T={},w={};let S=null;l.nodes.forEach((P,v)=>{T[P.id]=xw({node:P,snapshot:l,camera:n,width:o,height:d}),w[P.id]=Number((g[v]??0).toFixed(4)),P.id===a&&(S={x:P.x,y:P.y})});const y=hm(l.nodes.map(P=>({x:P.x,y:P.y}))),N=pm({centroid:p,boundsCenter:y,camera:n});window.__FORGE_KNOWLEDGE_GRAPH_DIAGNOSTICS__={datasetSignature:t,visibleNodeIds:C,visibleNodeCount:C.length,focusedNodeId:s,primaryFocusedNodeId:a,draggedNodeId:i,layoutGeneration:r,rendererMode:"fallback",startupPhase:m,startupInvariantSatisfied:h,simulationPhase:u,focusSources:x,focusPressureByNodeId:w,graphCentroid:p,boundsCenter:y,focusedNodePosition:S,cameraTarget:f,cameraFollowError:f?{x:Number((n.x-f.x).toFixed(4)),y:Number((n.y-f.y).toFixed(4)),ratio:Number((n.ratio-f.ratio).toFixed(4))}:null,camera:n,nodeScreenPositions:T,centroidDistanceFromOrigin:N.centroidDistanceFromOrigin,boundsCenterDistanceFromOrigin:N.boundsCenterDistanceFromOrigin,cameraDistanceFromOrigin:N.cameraDistanceFromOrigin,cameraToCentroidDistance:N.cameraToCentroidDistance,latestSnapshotAt:b,latestSnapshotNodeCount:A}}function Mp(t,s){if(!t)return!1;const a=t.clientWidth,i=t.clientHeight,r=t.getBoundingClientRect();return t.isConnected&&s.width>0&&s.height>0&&a>0&&i>0&&r.width>0&&r.height>0&&t.getClientRects().length>0}function q3({sigma:t,graph:s,viewportX:a,viewportY:i}){let r=null,n=Number.POSITIVE_INFINITY;return s.forEachNode(l=>{const o=s.getNodeAttributes(l),d=t.getNodeDisplayData(l);if(!d||o.hidden)return;const m=t.graphToViewport({x:o.x,y:o.y}),h=m.x-a,u=m.y-i,x=Math.hypot(h,u),g=Math.max(d.size*1.8,18);x<=g&&x<n&&(r=l,n=x)}),r}function dr(t,s){return`rgba(${t.family==="structural"?"125, 211, 252":t.family==="contextual"?"45, 212, 191":t.family==="taxonomy"?"192, 132, 252":t.family==="workspace"?"251, 191, 36":"148, 163, 184"}, ${s})`}const B3=c.forwardRef(function({nodes:s,edges:a,focusNodeId:i,physicsSettings:r,onSelectNode:n},l){jl(),ri(ne=>ne.knowledgeGraphDiagnostics.panelOpen);const o=c.useRef(null),d=c.useRef(null),m=c.useRef(null),h=c.useRef(null),u=c.useRef(new Map),x=c.useRef(new Map),g=c.useRef(new Map),p=c.useRef(n),f=c.useRef(i),b=c.useRef(null),A=c.useRef(0),C=c.useRef(null),T=c.useRef(0),w=c.useRef(!0),S=c.useRef(null),y=c.useRef(0),N=c.useRef("global"),P=c.useRef(null),v=c.useRef([]),H=c.useRef(new Float32Array(0)),j=c.useRef({x:0,y:0}),R=c.useRef("boot"),Q=c.useRef(!1),X=c.useRef(!1),Y=c.useRef(!1),z=c.useRef(null),K=c.useRef(null),$=c.useRef(0),D=c.useRef(0);c.useRef(0),c.useRef(qf("/knowledge-graph"));const[J,q]=c.useState(null),[_,B]=c.useState(null),[G,ae]=c.useState(null),[ke,Ae]=c.useState({x:0,y:0,angle:0,ratio:1}),[ie,Ie]=c.useState(null),[Ne,M]=c.useState({width:0,height:0}),O=zf(),xe=(ne=h.current)=>mw({positions:ne?Pp(ne):new Map,currentRatio:1}).ratio,V=(ne=h.current)=>({x:.5,y:.5,angle:0,ratio:xe(ne)}),Se=(ne=h.current)=>({x:0,y:0,angle:0,ratio:xe(ne)}),Ee=()=>d.current?"sigma":"fallback",Ce=c.useMemo(()=>hw(a),[a]),qe=c.useMemo(()=>A3(s,a),[a,s]),oe=c.useMemo(()=>i?Np(Ce,i):null,[i,Ce]),L=c.useMemo(()=>i?new Set([i,...(oe==null?void 0:oe.firstRing)??[]]):new Set,[i,oe]),U=c.useMemo(()=>i?new Set([i,...(oe==null?void 0:oe.firstRing)??[],...(oe==null?void 0:oe.secondRing)??[]]):new Set,[i,oe]),ge=()=>Mp(o.current,Ne),Te=({resize:ne=!1}={})=>{if(!d.current||!ge())return!1;try{return ne&&d.current.resize(),d.current.refresh(),!0}catch(be){if(be instanceof Error&&be.message.includes("Container has no width"))return!1;throw be}},ve=()=>Date.now()<T.current,Le=({level:ne,eventKey:be,message:je,details:pe,publishBackend:$e=!1})=>{},Qe=()=>d.current?{...d.current.getCamera().getState()}:{...ke},st=({rendererMode:ne})=>{if(!h.current||!b.current)return null;const be=h.current,je=be.nodes().map(Me=>{const He=be.getNodeAttributes(Me);return{id:Me,x:He.x,y:He.y}}),pe=Kf(je),$e=hm(je),Xe=Qe(),Ue=ne==="sigma"?{...Xe,x:Number((Xe.x-.5).toFixed(4)),y:Number((Xe.y-.5).toFixed(4))}:Xe,le=pm({centroid:pe,boundsCenter:$e,camera:Ue});return{datasetSignature:b.current,route:"/knowledge-graph",rendererMode:ne,startupPhase:R.current,startupInvariantSatisfied:CS(le),visibleNodeCount:je.length,focusedNodeId:f.current,primaryFocusedNodeId:P.current,graphCentroid:pe,boundsCenter:$e,camera:Xe,cameraTarget:S.current?{x:S.current.x,y:S.current.y,ratio:S.current.ratio}:null,driftMetrics:le,latestSnapshotAt:z.current,lastVerifiedAt:new Date().toISOString()}},F=(ne,{mirrorToConsole:be=!1}={})=>{},he=({rendererMode:ne,publishAnomaly:be})=>{},we=()=>{const ne=d.current?V():Se();if(d.current){d.current.getCamera().setState(ne);return}Ae(ne)},Z=ne=>{var $e;if(!h.current)return!1;const be=st({rendererMode:Ee()});if(!be)return!1;const je=be.graphCentroid.x,pe=be.graphCentroid.y;return Math.abs(je)<1e-4&&Math.abs(pe)<1e-4?!1:(Tp(h.current),fn(h.current,u.current),($e=m.current)==null||$e.postMessage({type:"recenter-graph",offsetX:je,offsetY:pe}),Ie(or(h.current,Ce)),we(),R.current="startup_corrected",Le({level:"warning",eventKey:"startup_corrected",message:"Corrected the knowledge graph startup bias back to graph-space origin.",publishBackend:!0,details:{datasetSignature:b.current}}),!0)},De=({phase:ne,allowCorrection:be,publishBackendOnFailure:je=!1})=>{if(!h.current||!b.current)return;R.current=ne;const pe=d.current?"sigma":"fallback",$e=st({rendererMode:pe});if(!$e)return;if($e.startupInvariantSatisfied){R.current="startup_verified",F({...$e},{mirrorToConsole:!0}),Le({level:"info",eventKey:"startup_verified",message:"Knowledge graph startup invariant passed.",details:{datasetSignature:$e.datasetSignature,driftMetrics:$e.driftMetrics}});return}if(Le({level:"warning",eventKey:"startup_invariant_failed",message:"Knowledge graph startup invariant failed before correction.",publishBackend:je,details:{datasetSignature:$e.datasetSignature,driftMetrics:$e.driftMetrics,centroid:$e.graphCentroid,boundsCenter:$e.boundsCenter,camera:$e.camera}}),Q.current||(Q.current=!0,!Z()))return;Te();const Ue=st({rendererMode:pe});if(Ue){if(Ue.startupInvariantSatisfied){R.current="startup_verified",F({...Ue},{mirrorToConsole:!0}),Le({level:"info",eventKey:"startup_verified_after_correction",message:"Knowledge graph startup invariant passed after correction.",details:{datasetSignature:Ue.datasetSignature,driftMetrics:Ue.driftMetrics}});return}Le({level:"error",eventKey:"startup_correction_failed",message:"Knowledge graph startup correction did not restore the origin invariant.",publishBackend:!0,details:{datasetSignature:Ue.datasetSignature,driftMetrics:Ue.driftMetrics,centroid:Ue.graphCentroid,boundsCenter:Ue.boundsCenter,camera:Ue.camera}})}},ee=()=>{var be,je,pe,$e;if(!b.current||!h.current)return;const ne=Date.now();if(!(ne-D.current<1500)){if(D.current=ne,d.current){K3({datasetSignature:b.current,focusNodeId:f.current,primaryFocusedNodeId:P.current,draggedNodeId:((be=C.current)==null?void 0:be.nodeId)??null,graph:h.current,layoutGeneration:A.current,sigma:d.current,startupPhase:R.current,startupInvariantSatisfied:((je=st({rendererMode:"sigma"}))==null?void 0:je.startupInvariantSatisfied)??!1,simulationPhase:N.current,focusSources:v.current,focusPressure:H.current,centroid:j.current,cameraTarget:S.current?{x:S.current.x,y:S.current.y,ratio:S.current.ratio}:null,latestSnapshotAt:z.current,latestSnapshotNodeCount:K.current});return}ie&&Ap({datasetSignature:b.current,focusNodeId:f.current,primaryFocusedNodeId:P.current,draggedNodeId:((pe=C.current)==null?void 0:pe.nodeId)??null,layoutGeneration:A.current,camera:ke,snapshot:ie,width:Ne.width,height:Ne.height,startupPhase:R.current,startupInvariantSatisfied:(($e=st({rendererMode:"fallback"}))==null?void 0:$e.startupInvariantSatisfied)??!1,simulationPhase:N.current,focusSources:v.current,focusPressure:H.current,centroid:j.current,cameraTarget:S.current?{x:S.current.x,y:S.current.y,ratio:S.current.ratio}:null,latestSnapshotAt:z.current,latestSnapshotNodeCount:K.current})}},ze=()=>{if(!h.current||!f.current){S.current=null;return}const ne=h.current;if(!ne.hasNode(f.current)){S.current=null;return}const be=Pp(ne),je=Np(Ce,f.current),pe=d.current?d.current.getCamera().getState().ratio:ke.ratio,$e=I3({positions:be,focusNodeId:f.current,firstRingNodeIds:je.firstRing,secondRingNodeIds:je.secondRing,currentRatio:pe}),Xe=d.current&&$e?y3({positions:be,point:{x:$e.x,y:$e.y}}):null;S.current=$e?{x:(Xe==null?void 0:Xe.x)??$e.x,y:(Xe==null?void 0:Xe.y)??$e.y,angle:0,ratio:$e.ratio,nodeIds:$e.nodeIds}:null},et=(ne=220)=>{if(!S.current)return;const be=S.current;if(d.current){const je=d.current.getCamera(),pe=je.getState(),$e=Date.now()<y.current;je.animate({x:be.x,y:be.y,ratio:$e?pe.ratio:be.ratio,angle:0},{duration:ne});return}Ae(je=>({...je,x:be.x,y:be.y,ratio:Date.now()<y.current?je.ratio:be.ratio}))};c.useEffect(()=>{p.current=n},[n]),c.useEffect(()=>{f.current=i,S.current=null},[i]),c.useEffect(()=>{Cp()},[O]),c.useEffect(()=>{if(!(!L3()||typeof window>"u"))return window.__FORGE_KNOWLEDGE_GRAPH_TEST_API__={selectNode:ne=>{var je;const be=ne?g.current.get(ne)??((je=h.current)!=null&&je.hasNode(ne)?h.current.getNodeAttribute(ne,"data")??null:null):null;p.current(be)},moveNodeBy:(ne,be,je)=>{var Ue,le;if(!((Ue=h.current)!=null&&Ue.hasNode(ne)))return;const pe=h.current.getNodeAttributes(ne),$e=pe.x+be,Xe=pe.y+je;h.current.mergeNodeAttributes(ne,{x:$e,y:Xe}),u.current.set(ne,{x:$e,y:Xe}),(le=m.current)==null||le.postMessage({type:"nudge-node",nodeId:ne,x:$e,y:Xe}),Te(),!d.current&&h.current&&Ie(or(h.current,Ce))},nudgeCameraBy:(ne,be)=>{if(d.current){const je=d.current.getCamera(),pe=je.getState();je.animate({x:pe.x+ne,y:pe.y+be,ratio:pe.ratio,angle:pe.angle},{duration:140});return}Ae(je=>({...je,x:je.x+ne,y:je.y+be}))}},()=>{delete window.__FORGE_KNOWLEDGE_GRAPH_TEST_API__}},[Ce]),c.useEffect(()=>{if(!o.current||typeof ResizeObserver>"u")return;const ne=()=>{o.current&&M({width:o.current.clientWidth,height:o.current.clientHeight})};ne();const be=new ResizeObserver(()=>{ne()});return be.observe(o.current),()=>be.disconnect()},[]),c.useImperativeHandle(l,()=>({zoomIn:()=>{if(y.current=Date.now()+1200,d.current){d.current.getCamera().animatedZoom({factor:1.25,duration:160});return}Ae(ne=>({...ne,ratio:Math.max(.08,ne.ratio*.82)}))},zoomOut:()=>{if(y.current=Date.now()+1200,d.current){d.current.getCamera().animatedUnzoom({factor:1.25,duration:160});return}Ae(ne=>({...ne,ratio:Math.min(4,ne.ratio*1.22)}))},fit:()=>{if(S.current=null,d.current){d.current.getCamera().animate(V(),{duration:220});return}ie&&Ae(O3(ie))},recenterOnFocus:()=>{ze(),S.current&&et(220)}}),[ie,Ce]),c.useEffect(()=>()=>{var ne,be,je;h.current&&fn(h.current,u.current),d.current&&b.current&&x.current.set(b.current,d.current.getCamera().getState()),(ne=m.current)==null||ne.postMessage({type:"dispose"}),(be=m.current)==null||be.terminate(),m.current=null,(je=d.current)==null||je.kill(),d.current=null,Cp()},[O]),c.useEffect(()=>{var Xe,Ue;if(!o.current||!Mp(o.current,Ne))return;if(b.current===qe&&h.current!==null){Te({resize:!0}),ee();return}R.current="boot",Q.current=!1,X.current=!1,Y.current=!1,z.current=null,K.current=null,$.current=0,S.current=null,Le({level:"info",eventKey:"graph_boot",message:"Bootstrapping a fresh knowledge graph dataset.",details:{nodeCount:s.length,edgeCount:Ce.length}}),h.current&&fn(h.current,u.current),d.current&&b.current&&x.current.set(b.current,d.current.getCamera().getState());const be=R3(s,Ce,u.current);if(Tp(be),fn(be,u.current),h.current=be,g.current=new Map(s.map(le=>[le.id,le])),b.current=qe,A.current+=1,Ie(or(be,Ce)),R.current="graph_built",Le({level:"info",eventKey:"graph_built",message:"Built and centered the knowledge graph structure.",details:{layoutGeneration:A.current}}),!D3())(Xe=d.current)==null||Xe.kill(),d.current=null,ae("WebGL is unavailable in this browser context."),Ae(Se(be)),De({phase:"graph_built",allowCorrection:!0,publishBackendOnFailure:!0});else try{if(d.current)d.current.setGraph(be),Te();else{d.current=new Tv(be,o.current,{renderEdgeLabels:!1,hideEdgesOnMove:!0,hideLabelsOnMove:!0,labelRenderedSizeThreshold:20,labelDensity:.04,labelGridCellSize:120,defaultNodeColor:"#c0c1ff",defaultEdgeColor:"rgba(125, 211, 252, 0.1)",minCameraRatio:.08,maxCameraRatio:4,autoRescale:!1,autoCenter:!1,enableEdgeEvents:!1,enableCameraPanning:!0,zIndex:!0}),Le({level:"info",eventKey:"sigma_initialized",message:"Initialized Sigma for the knowledge graph.",details:{datasetSignature:qe}}),d.current.on("clickNode",({node:Me})=>{if(ve())return;const He=g.current.get(Me)??null;p.current(He)}),d.current.on("clickStage",({event:Me})=>{if(ve())return;if(!d.current||!h.current){p.current(null);return}const He=q3({sigma:d.current,graph:h.current,viewportX:Me.x,viewportY:Me.y});if(He){p.current(g.current.get(He)??null);return}p.current(null)}),d.current.on("downNode",({node:Me,event:He,preventSigmaDefault:lt})=>{var Pe,k;if(!d.current||!((Pe=h.current)!=null&&Pe.hasNode(Me)))return;lt();const Nt=d.current.viewportToGraph({x:He.x,y:He.y}),me=h.current.getNodeAttributes(Me);C.current={nodeId:Me,offsetX:me.x-Nt.x,offsetY:me.y-Nt.y,startViewportX:He.x,startViewportY:He.y,currentX:me.x,currentY:me.y,moved:!1},w.current=d.current.getSetting("enableCameraPanning")??!0,d.current.setSetting("enableCameraPanning",!1),B(Me),q(Me),Le({level:"debug",eventKey:"drag_start",message:"Started dragging a knowledge graph node.",details:{nodeId:Me}}),(k=m.current)==null||k.postMessage({type:"drag-start",nodeId:Me})}),d.current.on("moveBody",({event:Me,preventSigmaDefault:He})=>{var k;if(!d.current||!h.current||!C.current)return;He();const lt=d.current.viewportToGraph({x:Me.x,y:Me.y});Math.hypot(Me.x-C.current.startViewportX,Me.y-C.current.startViewportY)>3&&(C.current={...C.current,moved:!0});const me=lt.x+C.current.offsetX,Pe=lt.y+C.current.offsetY;C.current={...C.current,currentX:me,currentY:Pe},h.current.mergeNodeAttributes(C.current.nodeId,{x:me,y:Pe}),u.current.set(C.current.nodeId,{x:me,y:Pe}),(k=m.current)==null||k.postMessage({type:"drag-move",nodeId:C.current.nodeId,x:me,y:Pe}),Te()});const le=()=>{var lt;if(!d.current||!C.current){C.current=null,B(null);return}const Me=C.current.nodeId,He=C.current.moved;d.current.setSetting("enableCameraPanning",w.current),(lt=m.current)==null||lt.postMessage({type:"drag-end",nodeId:Me}),Le({level:"debug",eventKey:"drag_end",message:"Released a dragged knowledge graph node.",details:{nodeId:Me,moved:He}}),C.current=null,B(null),He&&(T.current=Date.now()+220,p.current(g.current.get(Me)??null))};d.current.on("upNode",le),d.current.on("upStage",le),d.current.on("leaveStage",le),d.current.on("enterNode",({node:Me})=>{q(Me)}),d.current.on("leaveNode",()=>{q(null)}),d.current.on("afterRender",()=>{X.current||(X.current=!0,R.current="first_frame",Le({level:"info",eventKey:"first_frame",message:"Knowledge graph rendered its first frame.",details:{datasetSignature:b.current}}),De({phase:"first_frame",allowCorrection:!0,publishBackendOnFailure:!0}),he({rendererMode:"sigma",publishAnomaly:!0})),ee()})}ae(null),Ie(or(be,Ce)),d.current.getCamera().setState(V(be))}catch(le){(Ue=d.current)==null||Ue.kill(),d.current=null,ae(le instanceof Error?le.message:"Graph renderer unavailable."),Ie(or(be,Ce)),Ae(Se(be)),Le({level:"error",eventKey:"sigma_fallback",message:"Fell back from Sigma to the SVG renderer.",publishBackend:!0,details:{reason:le instanceof Error?le.message:"unknown"}}),De({phase:"graph_built",allowCorrection:!0,publishBackendOnFailure:!0})}m.current||(m.current=new Worker(new URL("/forge/assets/knowledge-graph-layout.worker-DRvzPxhP.js",import.meta.url),{type:"module"}),m.current.onmessage=le=>{var Pe;if(!h.current)return;const Me=le.data;if(Me.type==="stats"){N.current=Me.phase,P.current=Me.primaryFocusedNodeId,v.current=Me.focusSources,H.current=Me.focusPressure,j.current=Me.centroid,Y.current||(Y.current=!0,R.current="worker_started",Le({level:"info",eventKey:"worker_started",message:"Knowledge graph worker reported its first simulation stats.",details:{datasetSignature:b.current,phase:Me.phase}}),De({phase:"worker_started",allowCorrection:!0,publishBackendOnFailure:!0}));return}const He=h.current;let lt=Me.x,Nt=Me.y;if(R.current!=="startup_verified"){const k=z3({x:Me.x,y:Me.y});k.changed&&(lt=k.x,Nt=k.y,(Pe=m.current)==null||Pe.postMessage({type:"recenter-graph",offsetX:k.offsetX,offsetY:k.offsetY}),we(),Le({level:"warning",eventKey:"worker_startup_recenter",message:"Recentering worker positions during startup because the graph drifted away from origin.",details:{datasetSignature:b.current,startupPhase:R.current,offsetX:k.offsetX,offsetY:k.offsetY}}))}let me=0;if(He.updateEachNodeAttributes((k,se)=>({...se,x:lt[me],y:Nt[me++]}),{attributes:["x","y"]}),C.current&&He.hasNode(C.current.nodeId)){const k=C.current.nodeId;He.mergeNodeAttributes(k,{x:C.current.currentX,y:C.current.currentY})}fn(He,u.current),d.current?Te():Ie(or(He,Ce))});const je=be.nodes(),pe=new Map(je.map((le,Me)=>[le,Me])),$e=kp(je,Ce,i);m.current.postMessage({type:"init-graph",nodes:je.map(le=>{const Me=be.getNodeAttributes(le);return{id:le,x:Me.x,y:Me.y,size:Me.size,mass:Math.max(1,Me.data.importance/42),importance:Me.data.importance}}),edges:Ce.filter(le=>pe.has(le.source)&&pe.has(le.target)).map(le=>({source:pe.get(le.source),target:pe.get(le.target),weight:Math.max(.6,le.strength)})),focusNodeId:i,hopLevels:$e,physics:r}),Le({level:"debug",eventKey:"worker_init",message:"Posted the graph payload to the layout worker.",details:{nodeCount:je.length,edgeCount:Ce.length}})},[Ne.height,Ne.width,qe,i,s,r,Ce]),c.useEffect(()=>{if(!m.current||!h.current)return;const ne=kp(h.current.nodes(),Ce,i);m.current.postMessage({type:"set-focus",focusNodeId:i,hopLevels:ne}),i||(S.current=null)},[i,Ce]),c.useEffect(()=>{m.current&&m.current.postMessage({type:"update-physics",physics:r})},[r]),c.useEffect(()=>{},[qe,O]),c.useEffect(()=>{!d.current||!h.current||(d.current.setSetting("nodeReducer",(ne,be)=>{var pe;const je=(pe=h.current)==null?void 0:pe.getNodeAttribute(ne,"data");return k3({nodeId:ne,attributes:be,node:je,focusNodeId:i,relatedNodeIds:U,detailNodeIds:L,hoveredNodeId:J,draggedNodeId:_})}),d.current.setSetting("edgeReducer",(ne,be)=>{var pe;const je=(pe=h.current)==null?void 0:pe.getEdgeAttribute(ne,"data");return S3({attributes:be,edge:je,focusNodeId:i,detailNodeIds:L,relatedNodeIds:U,hoveredNodeId:J})}),Te())},[L,_,i,J,U]),c.useEffect(()=>{var ne,be;!ie||!b.current||Ne.width<=0||Ne.height<=0||!G&&d.current||(X.current||(X.current=!0,R.current="first_frame",Le({level:"info",eventKey:"fallback_first_frame",message:"Knowledge graph rendered its first fallback frame.",details:{datasetSignature:b.current}}),De({phase:"first_frame",allowCorrection:!0,publishBackendOnFailure:!0})),Ap({datasetSignature:b.current,focusNodeId:i,primaryFocusedNodeId:P.current,draggedNodeId:((ne=C.current)==null?void 0:ne.nodeId)??null,layoutGeneration:A.current,camera:ke,snapshot:ie,width:Ne.width,height:Ne.height,startupPhase:R.current,startupInvariantSatisfied:((be=st({rendererMode:"fallback"}))==null?void 0:be.startupInvariantSatisfied)??!1,simulationPhase:N.current,focusSources:v.current,focusPressure:H.current,centroid:j.current,cameraTarget:S.current?{x:S.current.x,y:S.current.y,ratio:S.current.ratio}:null,latestSnapshotAt:z.current,latestSnapshotNodeCount:K.current}))},[Ne.height,Ne.width,ke,G,ie,i]);const Ve=c.useMemo(()=>!ie||Ne.width<=0||Ne.height<=0?[]:ie.nodes.map(ne=>{const be=xw({node:ne,snapshot:ie,camera:ke,width:Ne.width,height:Ne.height});return{...ne,viewportX:be.x,viewportY:be.y,viewportSize:be.size}}),[Ne.height,Ne.width,ke,ie]),re=c.useMemo(()=>new Map(Ve.map(ne=>[ne.id,ne])),[Ve]);return e.jsx("div",{className:"relative h-full w-full overflow-hidden bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.1),transparent_34%),linear-gradient(180deg,rgba(7,12,23,0.98),rgba(6,11,20,0.98))]",children:e.jsx("div",{ref:o,className:"h-full w-full touch-none","aria-label":"Knowledge graph canvas",children:G&&ie?e.jsxs("svg",{className:"h-full w-full",viewBox:`0 0 ${Math.max(Ne.width,1)} ${Math.max(Ne.height,1)}`,"aria-hidden":"true",children:[e.jsx("title",{children:"Knowledge graph fallback canvas"}),e.jsx("rect",{x:"0",y:"0",width:Math.max(Ne.width,1),height:Math.max(Ne.height,1),fill:"transparent",onClick:()=>p.current(null)}),ie.edges.map(ne=>{const be=re.get(ne.source),je=re.get(ne.target);if(!be||!je)return null;const pe=!!i&&(ne.source===i||ne.target===i),$e=!!J&&(ne.source===J||ne.target===J),Xe=i?ne.source===i?0:L.has(ne.source)?1:U.has(ne.source)?2:3:0,Ue=i?ne.target===i?0:L.has(ne.target)?1:U.has(ne.target)?2:3:0,le=i?Math.max(Xe,Ue):0;return e.jsx("line",{x1:be.viewportX,y1:be.viewportY,x2:je.viewportX,y2:je.viewportY,stroke:pe?dr(ne,.24):$e?dr(ne,.14):i?le<=1?dr(ne,.09):le===2?dr(ne,.05):dr(ne,.016):dr(ne,.055),strokeWidth:pe?1.7:$e?1.3:.95},ne.id)}),Ve.map(ne=>{const be=i===ne.id,je=U.has(ne.id),pe=L.has(ne.id),$e=J===ne.id,Xe=!i||je;return e.jsxs("g",{transform:`translate(${ne.viewportX}, ${ne.viewportY})`,onMouseEnter:()=>q(ne.id),onMouseLeave:()=>q(null),onClick:Ue=>{Ue.stopPropagation();const le=g.current.get(ne.id)??null;p.current(le)},style:{cursor:"pointer"},children:[e.jsx("circle",{r:be?ne.viewportSize*1.9:$e?ne.viewportSize*1.3:pe?ne.viewportSize*1.15:je?ne.viewportSize*1.05:ne.viewportSize,fill:Xe?ne.color:_3(ne.color,.3),stroke:be?"rgba(255,255,255,0.78)":"rgba(255,255,255,0.12)",strokeWidth:be?2:1}),(be||$e||pe)&&e.jsx("text",{x:ne.viewportSize*1.5,y:4,fill:"rgba(244,247,255,0.92)",fontSize:"12",children:ne.data.title})]},ne.id)})]}):null})})}),U3=300,W3=152;function gw(t,s){return t?E3(t,s):new Set}function H3(t,s,a){const i=pw(t,s),r=gw(a,s);return i.nodes.map(n=>{const l=n.id===a,o=!a||r.has(n.id);return{id:n.id,draggable:!1,selectable:!1,position:{x:72+n.layer*U3,y:88+n.row*W3},data:{label:e.jsxs("div",{className:"min-w-[232px] rounded-[22px] border px-4 py-4 shadow-[0_24px_70px_rgba(0,0,0,0.24)] transition",style:{borderColor:l?"rgba(255,255,255,0.32)":"rgba(255,255,255,0.1)",background:l?"rgba(11,17,30,0.98)":"rgba(8,14,26,0.92)",opacity:o?1:.28},children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(We,{kind:n.entityKind,label:n.entityKind.replaceAll("_"," "),compact:!0,gradient:l})}),e.jsx("div",{className:"mt-3",children:e.jsx(yt,{kind:n.entityKind,label:n.title,className:"max-w-full",lines:2})}),n.subtitle?e.jsx("div",{className:"mt-2 text-sm leading-5 text-white/58",children:n.subtitle}):null]})},style:{background:"transparent",border:"none",padding:0}}})}function G3(t,s,a,i){const r=pw(t,s),n=gw(a,s);return r.edges.filter(l=>i||!l.secondary).map(l=>{const o=!a||n.has(l.source)||n.has(l.target);return{id:l.id,source:l.source,target:l.target,animated:!l.secondary&&l.family==="structural"&&o,markerEnd:{type:Uu.ArrowClosed,color:l.secondary?"rgba(255,255,255,0.16)":"rgba(232,242,255,0.42)"},style:{opacity:o?1:.18,stroke:l.secondary?"rgba(255,255,255,0.16)":l.family==="taxonomy"?"rgba(162,245,189,0.34)":l.family==="structural"?"rgba(232,242,255,0.4)":"rgba(192,193,255,0.24)",strokeDasharray:l.secondary?"8 6":void 0,strokeWidth:l.secondary?1:l.family==="structural"?1.7:1.2}}})}function Q3({nodes:t,edges:s,focusNodeId:a,showSecondaryEdges:i,onSelectNode:r,onOpenNode:n,onNavigateNode:l,isMobile:o}){const d=c.useMemo(()=>H3(t,s,a),[s,a,t]),m=c.useMemo(()=>G3(t,s,a,i),[s,a,t,i]),h=c.useMemo(()=>new Map(t.map(u=>[u.id,u])),[t]);return e.jsxs("div",{className:"knowledge-graph-canvas relative h-[44rem] rounded-[28px]",children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 z-10 flex gap-4 overflow-x-auto px-6 py-4",children:Tr.map(u=>e.jsx("div",{className:"min-w-[17rem] rounded-full border border-white/10 bg-[rgba(11,17,28,0.78)] px-4 py-2 text-center text-[11px] uppercase tracking-[0.16em] text-white/52 backdrop-blur",children:u.label},u.id))}),e.jsxs(id,{fitView:!0,fitViewOptions:a?{padding:.24,nodes:[{id:a}]}:{padding:.2},nodes:d,edges:m,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,attributionPosition:"bottom-left",onNodeClick:(u,x)=>{const g=h.get(x.id);g&&r(g)},onNodeDoubleClick:(u,x)=>{const g=h.get(x.id);if(g){if(o){n(g);return}l(g)}},children:[e.jsx(Bu,{showInteractive:!1}),e.jsx(rd,{gap:28,size:1,color:"rgba(255,255,255,0.05)"})]},`${a??"all"}-${i?"all":"primary"}`)]})}function V3(t){return t.trim().toLowerCase()}function mi({title:t,description:s,query:a,onQueryChange:i,onQuerySubmit:r,options:n,selectedOptionIds:l,onSelectedOptionIdsChange:o,resultSummary:d,clearLabel:m="Clear filters",submitLabel:h="Search",placeholder:u="Search title, alias, domain, source, or filter chip",emptyStateMessage:x="Keep typing to search the library or pick one of the suggested filter chips.",compact:g=!1,minimal:p=!1,hideSummary:f=!1}){const[b,A]=c.useState(!1),[C,T]=c.useState(0),w=c.useMemo(()=>l.map(v=>n.find(H=>H.id===v)).filter(Boolean),[n,l]),S=c.useMemo(()=>{const v=V3(a),H=n.filter(j=>!l.includes(j.id));return v?H.filter(j=>`${j.label} ${j.description??""} ${j.searchText??""}`.toLowerCase().includes(v)).slice(0,12):H.slice(0,12)},[n,a,l]),y=v=>{l.includes(v)||(o([...l,v]),i(""),A(!1),T(0))},N=v=>{o(l.filter(H=>H!==v))},P=()=>{i(""),o([]),T(0),A(!1)};return e.jsxs("div",{className:te("rounded-[28px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,30,42,0.92),rgba(9,15,24,0.98))] shadow-[0_30px_80px_rgba(3,8,18,0.28)]",p?"overflow-hidden rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] px-3 py-1.5 shadow-[0_18px_50px_rgba(0,0,0,0.26)] backdrop-blur":g?"rounded-[24px] p-2.5":"p-4 sm:p-5"),children:[e.jsxs("div",{className:te("flex flex-wrap items-start justify-between gap-3",p&&"hidden"),children:[e.jsxs("div",{children:[t.trim().length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:t}):null,s.trim().length>0?e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/62",children:s}):null]}),l.length>0||a.trim().length>0?e.jsx("button",{type:"button",onClick:P,className:te("rounded-full border border-white/8 bg-white/[0.04] text-white/62 transition hover:bg-white/[0.08] hover:text-white",g?"px-2.5 py-1.5 text-[11px]":"px-3 py-2 text-sm"),children:m}):null]}),e.jsxs("div",{className:te("rounded-[24px] border border-white/8 bg-white/[0.04]",p?"rounded-full border-0 bg-transparent px-0 py-0":g?"mt-1.5 rounded-[18px] px-2.5 py-2":"mt-4 px-4 py-3"),children:[w.length>0?e.jsx("div",{className:te("flex flex-wrap gap-2",p?"mb-0 mr-2 inline-flex max-w-[38%] flex-nowrap items-center gap-1 overflow-hidden":g?"mb-2":"mb-3"),children:w.map(v=>e.jsxs("span",{className:te("inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06]",p?"max-w-full shrink-0 border-white/10 bg-white/[0.08] px-2 py-0.5":g?"px-2 py-0.5":"px-2.5 py-1.5"),children:[v.badge??e.jsx("span",{className:"text-sm text-white/78",children:v.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>N(v.id),"aria-label":`Remove ${v.label}`,children:e.jsx(Tt,{className:"size-3.5"})})]},v.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:te("flex items-center",p?"gap-2 whitespace-nowrap":g?"gap-2":"gap-3"),children:[e.jsx(_t,{className:te("text-white/36",g?"size-3.5":"size-4")}),e.jsx("input",{value:a,onChange:v=>{i(v.target.value),A(!0),T(0)},onFocus:()=>A(!0),onBlur:()=>window.setTimeout(()=>A(!1),120),onKeyDown:v=>{if(v.key==="Backspace"&&!a&&l.length>0){N(l[l.length-1]);return}if(v.key==="ArrowDown"){v.preventDefault(),A(!0),T(H=>S.length===0?0:Math.min(S.length-1,H+1));return}if(v.key==="ArrowUp"){v.preventDefault(),T(H=>Math.max(0,H-1));return}if(v.key==="Escape"){A(!1);return}if(v.key==="Enter"&&r){v.preventDefault(),r(a),A(!1);return}v.key==="Enter"&&S[C]&&(v.preventDefault(),y(S[C].id))},placeholder:u,className:te("min-w-0 flex-1 bg-transparent text-white placeholder:text-white/34 focus:outline-none",p||g?"text-[12px]":"text-sm")}),p&&(l.length>0||a.trim().length>0)?e.jsx("button",{type:"button",onClick:P,className:"inline-flex size-6 items-center justify-center rounded-full border border-white/10 bg-white/[0.06] text-white/62 transition hover:text-white","aria-label":m,children:e.jsx(Tt,{className:"size-3.5"})}):null,r?e.jsx("button",{type:"button",onMouseDown:v=>v.preventDefault(),onClick:()=>{r(a),A(!1)},className:te("inline-flex items-center justify-center rounded-full border border-white/10 bg-white/[0.08] text-white/72 transition hover:bg-white/[0.14] hover:text-white",p?"size-6":g?"size-7":"size-8"),"aria-label":h,title:h,children:e.jsx(_t,{className:te(g?"size-3.5":"size-4")})}):null]}),b?e.jsx("div",{className:te("absolute top-full z-20 w-full border border-white/8 bg-[rgba(8,13,24,0.96)] shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",g?"mt-1.5 rounded-[18px] p-1.5":"mt-2 rounded-[22px] p-2"),children:S.length>0?S.map((v,H)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 text-left transition",g?"rounded-[14px] px-2.5 py-2":"rounded-[18px] px-3 py-2.5",H===C?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>T(H),onMouseDown:j=>j.preventDefault(),onClick:()=>y(v.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:te("truncate font-medium",g?"text-[12px]":"text-sm"),children:v.badge??v.label}),v.description?e.jsx("div",{className:te("mt-1 text-white/46",g?"text-[11px] leading-[1.125rem]":"text-xs leading-5"),children:v.description}):null]})},v.id)):e.jsx("div",{className:te("text-white/42",g?"px-2.5 py-2 text-[12px]":"px-3 py-2.5 text-sm"),children:x})}):null]})]}),f?null:e.jsx("div",{className:te("text-white/52",g?"mt-2 text-xs":"mt-3 text-sm"),children:d})]})}const fw=6,bw=5,ww=.92,yw=5,vw=.15,jw=2.4,Nw=2,kw=.8,Sw=3,oa={focusRepulsion:2.25,focusDiffusion:1.95,focusSpringReductionMax:.34,focusSpringReductionDiffusion:1.85,edgeSpringStrength:1,gravityStrength:1,focusShellSpacing:1};function fi(t,s,a){return Math.min(Math.max(t,s),a)}function Iw(t){return{focusRepulsion:fi((t==null?void 0:t.focusRepulsion)??oa.focusRepulsion,.6,fw),focusDiffusion:fi((t==null?void 0:t.focusDiffusion)??oa.focusDiffusion,.6,bw),focusSpringReductionMax:fi((t==null?void 0:t.focusSpringReductionMax)??oa.focusSpringReductionMax,0,ww),focusSpringReductionDiffusion:fi((t==null?void 0:t.focusSpringReductionDiffusion)??oa.focusSpringReductionDiffusion,.6,yw),edgeSpringStrength:fi((t==null?void 0:t.edgeSpringStrength)??oa.edgeSpringStrength,vw,jw),gravityStrength:fi((t==null?void 0:t.gravityStrength)??oa.gravityStrength,0,Nw),focusShellSpacing:fi((t==null?void 0:t.focusShellSpacing)??oa.focusShellSpacing,kw,Sw)}}function X3({isMobile:t,currentFocusNodeId:s,nextNodeId:a}){return a?t?s===a?{nextFocusNodeId:a,nextMobileSheetOpen:!0,shouldUpdateFocus:!1}:{nextFocusNodeId:a,nextMobileSheetOpen:!1,shouldUpdateFocus:!0}:{nextFocusNodeId:a,nextMobileSheetOpen:!1,shouldUpdateFocus:s!==a}:{nextFocusNodeId:null,nextMobileSheetOpen:!1,shouldUpdateFocus:s!==null}}const Ep="__clear__";function Y3({isMobile:t,focusNodeId:s,shellOverlayFocusNodeId:a,lastRequestedKey:i}){const r=t?null:s,n=r??Ep;return n===(a??Ep)?{action:"none",nextRequestedKey:n}:i===n?{action:"none",nextRequestedKey:n}:{action:r?"set":"clear",nextRequestedKey:n}}const Wl=2e3,ac=40,ic=2e3,Cw="forge.knowledge-graph.physics";function J3(){if(typeof window>"u")return!1;if(window.__FORGE_ENABLE_GRAPH_DIAGNOSTICS__)return!0;try{return new URLSearchParams(window.location.search).get("graphDiagnostics")==="1"}catch{return!1}}function Hl(t,s){return Array.from(new Set(t.getAll(s).flatMap(a=>a.split(",")).map(a=>a.trim()).filter(Boolean)))}function Ss(t,s,a){t.delete(s),a.forEach(i=>t.append(s,i))}function Z3(t){switch(t.entityType){case"workbench_flow":case"workbench_surface":case"wiki_space":return null;default:return yl(t.entityType,t.entityId)}}function Bs(t){return t?t.slice(0,10):""}function eC(){if(typeof window>"u")return oa;try{const t=window.localStorage.getItem(Cw);return t?Iw(JSON.parse(t)):oa}catch{return oa}}function tC(t,s,a,i,r){const n=t.find(l=>l.id===s);return n||(!s||!a?null:{id:s,displayName:a,kind:i??"human",accentColor:r??"",handle:a.toLowerCase().replace(/\s+/g,"-"),description:"",createdAt:"",updatedAt:""})}function sC({entityKinds:t,relationKinds:s,tags:a,owners:i}){return[...t.map(r=>`entity:${r}`),...s.map(r=>`relation:${r}`),...a.map(r=>`tag:${r}`),...i.map(r=>`owner:${r}`)]}function Lp(t){const s=[],a=[],i=[],r=[];for(const n of t){const[l,...o]=n.split(":"),d=o.join(":").trim();d&&(l==="entity"?s.push(d):l==="relation"?a.push(d):l==="tag"?i.push(d):l==="owner"&&r.push(d))}return{entityKinds:s,relationKinds:a,tags:i,owners:r}}class aC extends c.Component{constructor(s){super(s),this.state={error:null}}static getDerivedStateFromError(s){return{error:s}}componentDidUpdate(s){s.resetKey!==this.props.resetKey&&this.state.error!==null&&this.setState({error:null})}render(){return this.state.error?this.props.fallback(this.state.error):this.props.children}}function iC(){var he,we;const t=jt(),s=jl();ri(Z=>Z.knowledgeGraphDiagnostics);const a=ri(Z=>{var De,ee;return((ee=(De=Z.shell.knowledgeGraphOverlayFocus)==null?void 0:De.focusNode)==null?void 0:ee.id)??null}),i=$t(),[r,n]=ms(),l=c.useRef(null),o=c.useRef(null),d=c.useRef(null),m=c.useRef(null),h=c.useRef(null);c.useRef(qf("/knowledge-graph"));const[u,x]=c.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 1023px)").matches:!1),[g,p]=c.useState(!1),[f,b]=c.useState(!1),[A,C]=c.useState(!1),[T,w]=c.useState(!1),[S,y]=c.useState(""),[N,P]=c.useState(()=>eC()),H=zf(),j=({level:Z,eventKey:De,message:ee,details:ze,publishBackend:et=!1})=>{};c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const Z=window.matchMedia("(max-width: 1023px)"),De=ee=>x(ee?ee.matches:Z.matches);return De(),typeof Z.addEventListener=="function"?(Z.addEventListener("change",De),()=>Z.removeEventListener("change",De)):(Z.addListener(De),()=>Z.removeListener(De))},[]),c.useEffect(()=>{u||(p(!1),b(!1),o.current=null)},[u]),c.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Cw,JSON.stringify(N))},[N]);const R=r.toString(),Q=c.useMemo(()=>{const Z=new URLSearchParams(R),De=Z.get("view")==="hierarchy"?"hierarchy":"graph",ee=_S(Z.get("focus")),ze=ee?M3(ee.entityType,ee.entityId):null,et=Hl(Z,"entityKind"),Ve=Hl(Z,"relationKind"),re=Hl(Z,"tag"),ne=Hl(Z,"owner"),be=Z.get("q")??"",je=Z.get("updatedFrom"),pe=Z.get("updatedTo"),$e=Number(Z.get("limit")??Wl),Xe=Number.isFinite($e)?Math.max(ac,Math.min(ic,$e)):Wl;return{selectedView:De,focusNodeId:ze,selectedKinds:et,selectedRelations:Ve,selectedTags:re,selectedOwners:ne,showHierarchyCrossLinks:Z.get("cross")==="1",queryText:be,updatedFrom:je,updatedTo:pe,maxNodes:Xe}},[R]),{selectedView:X,focusNodeId:Y,selectedKinds:z,selectedRelations:K,selectedTags:$,selectedOwners:D,showHierarchyCrossLinks:J,queryText:q,updatedFrom:_,updatedTo:B,maxNodes:G}=Q;c.useEffect(()=>{y(q)},[q]);const ae=c.useMemo(()=>({q:q.trim()||null,entityKinds:[...z].sort(),relationKinds:[...K].sort(),tags:[...$].sort(),owners:[...D].sort(),updatedFrom:_,updatedTo:B,limit:G,focusNodeId:null}),[G,q,z,D,K,$,_,B]),ke=c.useMemo(()=>["forge-knowledge-graph",...t.selectedUserIds,JSON.stringify(ae)],[ae,t.selectedUserIds]),Ae=Fe({queryKey:ke,queryFn:()=>gj(t.selectedUserIds,ae),placeholderData:Z=>Z,staleTime:6e4,refetchOnWindowFocus:!1}),ie=Ae.data;c.useEffect(()=>{j({level:"info",eventKey:"route_arrival",message:"Arrived on the Knowledge Graph page.",details:{search:r.toString()}})},[]),c.useEffect(()=>{if(!Ae.isSuccess||!ie)return;const Z=JSON.stringify({q:ae.q,entityKinds:ae.entityKinds,relationKinds:ae.relationKinds,tags:ae.tags,owners:ae.owners,updatedFrom:ae.updatedFrom,updatedTo:ae.updatedTo,limit:ae.limit,nodeCount:ie.counts.nodeCount,edgeCount:ie.counts.edgeCount,filteredNodeCount:ie.counts.filteredNodeCount,limited:ie.counts.limited});h.current!==Z&&(h.current=Z,j({level:"info",eventKey:"graph_query_resolved",message:"Knowledge graph query resolved.",details:{nodeCount:ie.counts.nodeCount,edgeCount:ie.counts.edgeCount,filteredNodeCount:ie.counts.filteredNodeCount,limited:ie.counts.limited}}))},[ie,Ae.isSuccess,ae]),c.useEffect(()=>{!ie||!Y||ie.nodes.some(Z=>Z.id===Y)||(n(Z=>{const De=new URLSearchParams(Z);return De.delete("focus"),De},{replace:!0}),p(!1),o.current=null)},[Y,ie,n]),c.useEffect(()=>{if(u){if(!Y){o.current=null,p(!1);return}o.current===Y&&!g&&(p(!0),o.current=null)}},[Y,u,g]);const Ie=c.useMemo(()=>!ie||!Y?Ip([],[],null):Ip(ie.nodes,ie.edges,Y),[Y,ie]);c.useEffect(()=>{var De;const Z=Y3({isMobile:u,focusNodeId:((De=Ie.focusNode)==null?void 0:De.id)??null,shellOverlayFocusNodeId:a,lastRequestedKey:m.current});if(m.current=Z.nextRequestedKey,Z.action!=="none"){if(Z.action==="clear"){s(Fo());return}s(bS(Ie))}},[s,Ie,u,a]),c.useEffect(()=>{{d.current=null;return}},[H,Y,Ie,u]),c.useEffect(()=>()=>{s(Fo())},[s]),c.useEffect(()=>{if(!(typeof window>"u")){if(!J3()){delete window.__FORGE_KNOWLEDGE_GRAPH_PAGE_TEST__;return}return window.__FORGE_KNOWLEDGE_GRAPH_PAGE_TEST__={isMobile:u,mobileSheetOpen:g,focusNodeId:Y,selectedView:X,selectNodeById:Z=>{if(!ie)return;const De=Z?ie.nodes.find(ee=>ee.id===Z)??null:null;E(De)},activateFocusedNode:()=>{if(!Y||!ie)return;const Z=ie.nodes.find(De=>De.id===Y)??null;Z&&E(Z)}},()=>{delete window.__FORGE_KNOWLEDGE_GRAPH_PAGE_TEST__}}},[Y,u,g,X]);const Ne=Z=>{n(De=>{const ee=new URLSearchParams(De);return Z(ee),ee},{replace:!0})},M=Z=>{const De=Z.trim();y(Z),Ne(ee=>{De.length>0?ee.set("q",De):ee.delete("q")})},E=Z=>{const De=X3({isMobile:u,currentFocusNodeId:Y,nextNodeId:(Z==null?void 0:Z.id)??null});o.current=u&&De.nextMobileSheetOpen?(Z==null?void 0:Z.id)??null:null,p(De.nextMobileSheetOpen),De.shouldUpdateFocus&&(Ne(ee=>{if(!Z){ee.delete("focus");return}ee.set("focus",_o(Z.entityType,Z.entityId))}),u&&b(!1))},O=Z=>{Z.href&&i(Z.href)},xe=(Z,De)=>{P(ee=>Iw({...ee,[Z]:De}))},V=Z=>{const De=Z3(Z);De&&i(De)},Se=Z=>{Ne(De=>{De.set("view","hierarchy"),De.set("focus",_o(Z.entityType,Z.entityId))})},Ee=()=>{Ne(Z=>{["q","entityKind","relationKind","tag","owner","updatedFrom","updatedTo","focus"].forEach(De=>Z.delete(De)),Z.set("limit",String(Wl))}),C(!1)};if(Ae.isLoading&&!ie)return e.jsx(Et,{eyebrow:"Knowledge Graph",title:"Loading the Forge world model",description:"Gathering goals, projects, KarpaWiki pages, psyche entities, calendar context, and Workbench flows into one graph."});if(Ae.isError)return e.jsx(it,{eyebrow:"Knowledge Graph",error:Ae.error,onRetry:()=>void Ae.refetch()});if(!ie)return null;const Ce=new Map(ie.facets.entityKinds.map(Z=>[Z.value,Z])),qe=iu.map(Z=>{const De=zs(Z),ee=Ce.get(Z),ze=(ee==null?void 0:ee.count)??0;return{value:Z,label:(ee==null?void 0:ee.label)??De.label,description:ze===1?"1 node":`${ze} nodes`,kind:Z}}),oe=ie.facets.relationKinds.map(Z=>({value:Z.value,label:Z.label,description:`${Z.count} links`})),L=ie.facets.tags.map(Z=>({value:Z.id,label:Z.label,description:`${Z.count} linked nodes`,badge:e.jsx(We,{kind:"tag",label:Z.label,compact:!0,gradient:!1}),menuBadge:e.jsx(We,{kind:"tag",label:Z.label,compact:!0,gradient:!1})})),U=ie.facets.owners.map(Z=>{const De=tC(t.snapshot.users,Z.userId,Z.displayName,Z.kind,Z.accentColor);return{value:Z.userId,label:Z.displayName,description:`${Z.count} nodes`,badge:e.jsx(ot,{user:De,compact:!0}),menuBadge:e.jsx(ot,{user:De,compact:!0})}}),ge=[...qe.map(Z=>({id:`entity:${Z.value}`,label:Z.label,description:Z.description,searchText:`entity kind ${Z.label}`,badge:e.jsx(We,{kind:Z.kind??"note",label:Z.label,compact:!0,gradient:!1})})),...oe.map(Z=>({id:`relation:${Z.value}`,label:Z.label,description:Z.description,searchText:`relation kind ${Z.label}`})),...L.map(Z=>({id:`tag:${Z.value}`,label:Z.label,description:Z.description,searchText:`tag ${Z.label}`,badge:Z.menuBadge??Z.badge})),...U.map(Z=>({id:`owner:${Z.value}`,label:Z.label,description:Z.description,searchText:`owner ${Z.label}`,badge:Z.menuBadge??Z.badge}))],Te=sC({entityKinds:z,relationKinds:K,tags:$,owners:D}),ve=ie.counts.limited?`${ie.counts.nodeCount}/${ie.counts.filteredNodeCount} nodes`:`${ie.counts.nodeCount}n · ${ie.counts.edgeCount}e`,Le=ie.counts.limited?`${ie.counts.nodeCount} visible nodes from ${ie.counts.filteredNodeCount} filtered matches`:`${ie.counts.nodeCount} nodes and ${ie.counts.edgeCount} edges`,Qe=q.trim().length>0||z.length>0||K.length>0||$.length>0||D.length>0||!!_||!!B||G!==Wl,st=!u,F=`${X}:${ie.nodes.map(Z=>Z.id).join("|")}::${ie.edges.map(Z=>Z.id).join("|")}`;return e.jsxs("div",{className:"-mx-4 -mb-2.5 h-[calc(100dvh-var(--forge-mobile-nav-clearance)-5.25rem)] overflow-hidden lg:-mx-6 lg:-mb-3 lg:-mt-3 lg:h-[calc(100dvh-10rem)]",children:[e.jsxs("div",{className:"relative h-full bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.08),transparent_26%),linear-gradient(180deg,rgba(7,12,23,0.98),rgba(5,10,19,1))]",children:[e.jsx(aC,{resetKey:F,fallback:Z=>e.jsx("div",{className:"grid h-full place-items-center p-6 text-center",children:e.jsxs("div",{className:"grid max-w-lg gap-4 rounded-[28px] border border-[rgba(255,255,255,0.08)] bg-[rgba(8,12,22,0.92)] p-6 shadow-[0_30px_80px_rgba(0,0,0,0.36)]",children:[e.jsx("div",{className:"mx-auto flex size-12 items-center justify-center rounded-full border border-[rgba(255,255,255,0.12)] bg-[rgba(255,255,255,0.04)] text-[var(--warning)]",children:e.jsx(ml,{className:"size-5"})}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Graph renderer fallback"}),e.jsx("h2",{className:"text-lg font-semibold text-[var(--ui-ink-strong)]",children:"The graph renderer hit a display error."}),e.jsx("p",{className:"text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Switch to the hierarchy view or reset the current graph filters. The graph will recover automatically when the dataset changes."}),e.jsx("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[rgba(255,255,255,0.04)] px-4 py-3 text-left text-xs text-[var(--ui-ink-faint)]",children:Z.message})]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[e.jsxs(W,{variant:"primary",size:"sm",onClick:()=>Ne(De=>{De.set("view","hierarchy")}),children:[e.jsx(Av,{className:"size-4"}),"Open hierarchy"]}),e.jsx(W,{variant:"secondary",size:"sm",onClick:Ee,children:"Reset graph filters"})]})]})}),children:X==="graph"?e.jsx(B3,{ref:l,nodes:ie.nodes,edges:ie.edges,focusNodeId:Y,physicsSettings:N,onSelectNode:E}):e.jsx("div",{className:"h-full overflow-y-auto px-4 py-4 lg:px-6",children:e.jsx(Q3,{nodes:ie.nodes,edges:ie.edges,focusNodeId:Y,showSecondaryEdges:J,isMobile:u,onSelectNode:E,onOpenNode:E,onNavigateNode:O})})}),u?e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 z-20 px-3 pt-2 lg:hidden",children:e.jsxs("div",{className:"pointer-events-auto flex items-center gap-1.5",children:[e.jsx("div",{title:Le,className:"shrink-0 rounded-full border border-white/10 bg-[rgba(8,12,20,0.78)] px-2 py-0.5 text-[9px] uppercase tracking-[0.18em] text-white/48 backdrop-blur",children:ve}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[e.jsxs("div",{className:"flex shrink-0 rounded-full border border-white/10 bg-[rgba(8,12,20,0.78)] p-0.5 shadow-[0_14px_42px_rgba(0,0,0,0.24)] backdrop-blur",children:[e.jsx("button",{type:"button",className:`rounded-full px-2 py-1 text-[10px] transition ${X==="graph"?"bg-white/[0.14] text-white":"text-white/52 hover:text-white"}`,onClick:()=>Ne(Z=>{Z.set("view","graph")}),children:"Graph"}),e.jsx("button",{type:"button",className:`rounded-full px-2 py-1 text-[10px] transition ${X==="hierarchy"?"bg-white/[0.14] text-white":"text-white/52 hover:text-white"}`,onClick:()=>Ne(Z=>{Z.set("view","hierarchy")}),children:"Hierarchy"})]}),e.jsx(W,{variant:"secondary",size:"sm",className:"h-7 rounded-full border-white/10 bg-[rgba(8,12,20,0.78)] px-2 text-[10px] text-white/68 backdrop-blur hover:text-white",onClick:()=>w(!0),"aria-label":"Open graph appearance settings",title:"Graph appearance settings",children:e.jsx(Po,{className:"size-3"})}),e.jsxs(W,{variant:"secondary",size:"sm",className:"h-7 rounded-full border-white/10 bg-[rgba(8,12,20,0.78)] px-2 text-[10px] text-white/68 backdrop-blur hover:text-white",onClick:()=>{p(!1),b(!0)},"aria-label":"Open graph filters",children:[e.jsx(Ki,{className:"size-3"}),"Search"]})]})]})}):null,st?e.jsxs("div",{className:"pointer-events-none absolute inset-x-0 top-0 z-20 px-4 pt-3 lg:px-6",children:[e.jsxs("div",{"data-testid":"knowledge-graph-desktop-toolbar",className:"pointer-events-auto flex items-center gap-1.5",children:[e.jsx("div",{"data-testid":"knowledge-graph-count-pill",title:Le,className:"shrink-0 rounded-full border border-white/10 bg-[rgba(8,12,20,0.78)] px-2 py-0.5 text-[9px] uppercase tracking-[0.18em] text-white/48 backdrop-blur",children:ve}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(mi,{title:"",description:"",compact:!0,minimal:!0,hideSummary:!0,query:S,onQueryChange:y,onQuerySubmit:M,submitLabel:"Search graph",options:ge,selectedOptionIds:Te,onSelectedOptionIdsChange:Z=>{const De=Lp(Z);Ne(ee=>{Ss(ee,"entityKind",De.entityKinds),Ss(ee,"relationKind",De.relationKinds),Ss(ee,"tag",De.tags),Ss(ee,"owner",De.owners)})},resultSummary:"",placeholder:"Type a graph search, then press Enter or the search button"})}),e.jsxs(W,{variant:"secondary",size:"sm",className:"h-7 rounded-full border-white/10 bg-[rgba(8,12,20,0.78)] px-2 text-[10px] text-white/68 backdrop-blur hover:text-white",onClick:()=>C(Z=>!Z),children:[e.jsx(Ki,{className:"size-3"}),"Advanced"]}),Qe?e.jsx(W,{variant:"secondary",size:"sm",className:"h-7 rounded-full border-white/10 bg-[rgba(8,12,20,0.78)] px-2 text-[10px] text-white/68 backdrop-blur hover:text-white",onClick:Ee,children:"Reset"}):null]}),e.jsx(Jn,{initial:!1,children:A?e.jsx(Ts.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},transition:{duration:.18,ease:"easeOut"},className:"pointer-events-auto mt-2 ml-auto max-w-[min(54rem,calc(100%-3.5rem))] rounded-[20px] border border-white/10 bg-[rgba(8,12,20,0.88)] p-3 shadow-[0_20px_60px_rgba(0,0,0,0.32)] backdrop-blur",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.4fr)_minmax(17rem,1fr)]",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx(mt,{options:qe,selectedValues:z,onChange:Z=>Ne(De=>{Ss(De,"entityKind",Z)}),placeholder:"Filter by entity type",emptyMessage:"No entity kinds match the current graph."}),e.jsx(mt,{options:oe,selectedValues:K,onChange:Z=>Ne(De=>{Ss(De,"relationKind",Z)}),placeholder:"Filter by relation type",emptyMessage:"No relation kinds match the current graph."}),e.jsx(mt,{options:L,selectedValues:$,onChange:Z=>Ne(De=>{Ss(De,"tag",Z)}),placeholder:"Filter by tag",emptyMessage:"No tags are available in the current filtered graph."}),e.jsx(mt,{options:U,selectedValues:D,onChange:Z=>Ne(De=>{Ss(De,"owner",Z)}),placeholder:"Filter by owner",emptyMessage:"No owners match the current graph."})]}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] border border-white/10 bg-white/[0.03] p-3",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.18em] text-white/46",children:[e.jsx("span",{children:"Max nodes shown"}),e.jsx("span",{children:G})]}),e.jsx("input",{type:"range",min:ac,max:ic,step:20,value:G,onChange:Z=>Ne(De=>{De.set("limit",Z.target.value)}),className:"w-full accent-[var(--secondary)]"}),e.jsx("div",{className:"text-xs text-white/42",children:"The graph stays deterministic under the cap and focus mode redistributes the visible neighborhood around the selected node."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Updated from"}),e.jsx(ye,{type:"date",value:Bs(_),min:Bs(ie.facets.updatedAt.min),max:Bs(B??ie.facets.updatedAt.max),onChange:Z=>Ne(De=>{Z.target.value?De.set("updatedFrom",Z.target.value):De.delete("updatedFrom")})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Updated to"}),e.jsx(ye,{type:"date",value:Bs(B),min:Bs(_??ie.facets.updatedAt.min),max:Bs(ie.facets.updatedAt.max),onChange:Z=>Ne(De=>{Z.target.value?De.set("updatedTo",Z.target.value):De.delete("updatedTo")})})]})]}),X==="hierarchy"?e.jsx(W,{variant:J?"primary":"secondary",size:"sm",className:"h-8 rounded-full px-3 text-xs",onClick:()=>Ne(Z=>{J?Z.delete("cross"):Z.set("cross","1")}),children:J?"Hide cross-links":"Show cross-links"}):null]})]})}):null})]}):null,u?null:e.jsx("div",{className:"pointer-events-none absolute bottom-5 left-4 z-20 lg:left-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"pointer-events-auto flex shrink-0 rounded-full border border-white/10 bg-[rgba(8,12,20,0.82)] p-0.5 shadow-[0_14px_42px_rgba(0,0,0,0.24)] backdrop-blur",children:[e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-1.5 text-[10px] transition ${X==="graph"?"bg-white/[0.14] text-white":"text-white/52 hover:text-white"}`,onClick:()=>Ne(Z=>{Z.set("view","graph")}),children:"Graph"}),e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-1.5 text-[10px] transition ${X==="hierarchy"?"bg-white/[0.14] text-white":"text-white/52 hover:text-white"}`,onClick:()=>Ne(Z=>{Z.set("view","hierarchy")}),children:"Hierarchy"})]}),X==="graph"?e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>w(!0),title:"Graph appearance settings","aria-label":"Open graph appearance settings",children:e.jsx(Po,{className:"size-3.5"})}),e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.zoomIn()},title:"Zoom in","aria-label":"Zoom in",children:e.jsx(ds,{className:"size-3.5"})}),e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.zoomOut()},title:"Zoom out","aria-label":"Zoom out",children:e.jsx(Ig,{className:"size-3.5"})}),e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.recenterOnFocus()},disabled:!Ie.focusNode,title:"Recenter","aria-label":"Recenter",children:e.jsx(Mv,{className:"size-3.5"})}),e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.fit()},title:"Reset camera","aria-label":"Reset camera",children:e.jsx(Ev,{className:"size-3.5"})}),null]}):null]})})]}),e.jsx(pa,{open:g&&!!Ie.focusNode,onOpenChange:p,eyebrow:"Knowledge Graph",title:((he=Ie.focusNode)==null?void 0:he.title)??"Focus node",description:((we=Ie.focusNode)==null?void 0:we.subtitle)??"Inspect the selected node and move deeper into the graph.",children:e.jsx(Pf,{focus:Ie,onOpenPage:Z=>{p(!1),O(Z)},onOpenNotes:Z=>{p(!1),V(Z)},onOpenHierarchy:Z=>{p(!1),Se(Z)},onSelectNode:E,className:"border-0 bg-transparent p-0 shadow-none"})}),e.jsx(pa,{open:f,onOpenChange:b,eyebrow:"Knowledge Graph",title:"Filter graph",description:"Search the visible graph and adjust the focus cap without covering the canvas all the time.",children:e.jsxs("div",{className:"grid gap-4 pb-2",children:[e.jsx("div",{className:"rounded-[22px] border border-[var(--ui-border-subtle)] bg-[rgba(255,255,255,0.03)] p-3",children:e.jsx(mi,{title:"",description:"",compact:!0,query:S,onQueryChange:y,onQuerySubmit:M,submitLabel:"Search graph",options:ge,selectedOptionIds:Te,onSelectedOptionIdsChange:Z=>{const De=Lp(Z);Ne(ee=>{Ss(ee,"entityKind",De.entityKinds),Ss(ee,"relationKind",De.relationKinds),Ss(ee,"tag",De.tags),Ss(ee,"owner",De.owners)})},resultSummary:Le,placeholder:"Type a graph search, then press Enter or the search button"})}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx(mt,{options:qe,selectedValues:z,onChange:Z=>Ne(De=>{Ss(De,"entityKind",Z)}),placeholder:"Filter by entity type",emptyMessage:"No entity kinds match the current graph."}),e.jsx(mt,{options:oe,selectedValues:K,onChange:Z=>Ne(De=>{Ss(De,"relationKind",Z)}),placeholder:"Filter by relation type",emptyMessage:"No relation kinds match the current graph."}),e.jsx(mt,{options:L,selectedValues:$,onChange:Z=>Ne(De=>{Ss(De,"tag",Z)}),placeholder:"Filter by tag",emptyMessage:"No tags are available in the current filtered graph."}),e.jsx(mt,{options:U,selectedValues:D,onChange:Z=>Ne(De=>{Ss(De,"owner",Z)}),placeholder:"Filter by owner",emptyMessage:"No owners match the current graph."})]}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] border border-[var(--ui-border-subtle)] bg-[rgba(255,255,255,0.03)] p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.18em] text-white/46",children:[e.jsx("span",{children:"Max nodes shown"}),e.jsx("span",{children:G})]}),e.jsx("input",{type:"range",min:ac,max:ic,step:20,value:G,onChange:Z=>Ne(De=>{De.set("limit",Z.target.value)}),className:"w-full accent-[var(--secondary)]"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Updated from"}),e.jsx(ye,{type:"date",value:Bs(_),min:Bs(ie.facets.updatedAt.min),max:Bs(B??ie.facets.updatedAt.max),onChange:Z=>Ne(De=>{Z.target.value?De.set("updatedFrom",Z.target.value):De.delete("updatedFrom")})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Updated to"}),e.jsx(ye,{type:"date",value:Bs(B),min:Bs(_??ie.facets.updatedAt.min),max:Bs(ie.facets.updatedAt.max),onChange:Z=>Ne(De=>{Z.target.value?De.set("updatedTo",Z.target.value):De.delete("updatedTo")})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:Ee,children:"Reset"}),e.jsx(W,{variant:"primary",size:"sm",onClick:()=>b(!1),children:"Done"})]})]})]})}),e.jsx(Yt,{open:T,onOpenChange:w,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(es,{className:"fixed inset-x-4 top-[max(1rem,env(safe-area-inset-top))] z-50 max-h-[calc(100dvh-2rem)] overflow-y-auto rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(16,23,36,0.98),rgba(8,12,22,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.48)] md:left-1/2 md:right-auto md:w-[min(40rem,calc(100vw-3rem))] md:-translate-x-1/2",children:[e.jsx(ts,{className:"sr-only",children:"Knowledge Graph appearance settings"}),e.jsx(rs,{className:"sr-only",children:"Tune the graph focus physics and appearance response."}),e.jsxs("div",{className:"sticky top-0 z-10 flex items-start justify-between gap-4 border-b border-white/8 bg-[rgba(8,12,22,0.9)] px-5 py-4 backdrop-blur-xl",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Graph appearance"}),e.jsx("div",{className:"font-display text-2xl text-white",children:"Tune the focus field"}),e.jsx("p",{className:"max-w-xl text-sm leading-6 text-white/55",children:"Shape how strongly a focused node opens its neighborhood and how far that pressure diffuses through connected hops."})]}),e.jsx(Qt,{asChild:!0,children:e.jsx(Zi,{"aria-label":"Close graph appearance settings"})})]}),e.jsxs("div",{className:"grid gap-4 px-5 py-5",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Focused repulsion"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Push nearby nodes apart more aggressively while the focused node stays anchored."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusRepulsion.toFixed(2)})]}),e.jsx("input",{"aria-label":"Focused repulsion",type:"range",min:"0.6",max:String(fw),step:"0.05",value:N.focusRepulsion,onChange:Z=>xe("focusRepulsion",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Focus diffusion"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Extend the focus field further through multi-hop neighbors and lengthen the reversible transition."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusDiffusion.toFixed(2)})]}),e.jsx("input",{"aria-label":"Focus diffusion",type:"range",min:"0.6",max:String(bw),step:"0.05",value:N.focusDiffusion,onChange:Z=>xe("focusDiffusion",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Spring reduction max"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Reduce edge spring constants most strongly around the focused node so its local neighborhood can open more freely."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusSpringReductionMax.toFixed(2)})]}),e.jsx("input",{"aria-label":"Spring reduction max",type:"range",min:"0",max:String(ww),step:"0.02",value:N.focusSpringReductionMax,onChange:Z=>xe("focusSpringReductionMax",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Spring reduction diffusion"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Spread that spring softening progressively through first-hop, second-hop, and more distant neighborhoods."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusSpringReductionDiffusion.toFixed(2)})]}),e.jsx("input",{"aria-label":"Spring reduction diffusion",type:"range",min:"0.6",max:String(yw),step:"0.05",value:N.focusSpringReductionDiffusion,onChange:Z=>xe("focusSpringReductionDiffusion",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Edge spring strength"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Lower this to loosen graph edges globally and let neighborhoods spread instead of snapping tightly inward."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.edgeSpringStrength.toFixed(2)})]}),e.jsx("input",{"aria-label":"Edge spring strength",type:"range",min:String(vw),max:String(jw),step:"0.05",value:N.edgeSpringStrength,onChange:Z=>xe("edgeSpringStrength",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Gravity strength"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Reduce this to weaken the global inward pull that compacts the whole graph toward the middle."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.gravityStrength.toFixed(2)})]}),e.jsx("input",{"aria-label":"Gravity strength",type:"range",min:"0",max:String(Nw),step:"0.05",value:N.gravityStrength,onChange:Z=>xe("gravityStrength",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Focus shell spacing"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Increase this to push focused rings farther outward and visibly open the local structure."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusShellSpacing.toFixed(2)})]}),e.jsx("input",{"aria-label":"Focus shell spacing",type:"range",min:String(kw),max:String(Sw),step:"0.05",value:N.focusShellSpacing,onChange:Z=>xe("focusShellSpacing",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]})]}),e.jsx("div",{className:"rounded-[24px] border border-white/8 bg-[rgba(125,211,252,0.07)] px-4 py-3 text-sm leading-6 text-white/62",children:"The main cramming forces are the edge springs and the inward gravity pull. Lower edge spring strength or gravity strength to let the whole graph breathe more, then raise focus shell spacing and spring-reduction controls when you want a selected neighborhood to open dramatically."}),e.jsxs("div",{className:"flex flex-wrap justify-between gap-3",children:[e.jsx(W,{variant:"secondary",onClick:()=>P(oa),children:"Reset defaults"}),e.jsx(Qt,{asChild:!0,children:e.jsx(W,{variant:"primary",children:"Done"})})]})]})]})]})}),null]})}const Pr=20,Dp=288,fa={top:16,right:18,bottom:28,left:42},Uo=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function rC(t,s){return Uo.map((a,i)=>({weekday:i,baselineDailyAp:t.baselineDailyAp,points:t.currentCurve.map(r=>({...r,locked:i===s?r.locked:!1}))}))}function uu(t){return`${Number(t.toFixed(1))} AP`}function Da(t){return`${Number(t.toFixed(1))} AP/h`}function rc(t){const s=new Date(2026,0,1,0,t,0,0);return new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(s)}function nC(t){const s=new Date(2026,0,1,0,t,0,0);return new Intl.DateTimeFormat(void 0,{hour:"numeric"}).format(s)}function Pa(t,s,a){return Math.min(a,Math.max(s,t))}function lC(t){if(t.length<2)return 0;let s=0;for(let a=0;a<t.length-1;a+=1){const i=t[a],r=t[a+1];s+=(i.rateApPerHour+r.rateApPerHour)/2*((r.minuteOfDay-i.minuteOfDay)/60)}return s}function Fp(t,s){if(t.length===0)return 0;if(s<=t[0].minuteOfDay)return t[0].rateApPerHour;for(let a=0;a<t.length-1;a+=1){const i=t[a],r=t[a+1];if(s<=r.minuteOfDay){const n=Math.max(1,r.minuteOfDay-i.minuteOfDay),l=(s-i.minuteOfDay)/n;return i.rateApPerHour+(r.rateApPerHour-i.rateApPerHour)*l}}return t[t.length-1].rateApPerHour}function oC(t,s){const a=lC(t);if(a<=0||s<=0)return t.map(r=>({...r,rateApPerHour:0}));const i=s/a;return t.map(r=>({...r,rateApPerHour:Number((r.rateApPerHour*i).toFixed(4))}))}function dC(t,s,a){var m;if(s<=0||s>=t.length-1)return((m=t[s])==null?void 0:m.rateApPerHour)??0;const i=t[s-1],r=t[s],n=t[s+1];let l=0;for(let h=0;h<t.length-1;h+=1){if(h===s-1||h===s)continue;const u=t[h],x=t[h+1];l+=(u.rateApPerHour+x.rateApPerHour)/2*((x.minuteOfDay-u.minuteOfDay)/60)}const o=Math.max(Pr/60,(r.minuteOfDay-i.minuteOfDay)/60),d=Math.max(Pr/60,(n.minuteOfDay-r.minuteOfDay)/60);return Math.max(0,(2*(a-l)-i.rateApPerHour*o-n.rateApPerHour*d)/(o+d))}function cC(t){switch(t){case"danger":return"bg-rose-400/12 text-rose-100";case"warning":return"bg-amber-400/12 text-amber-100";case"success":return"bg-emerald-400/12 text-emerald-100";case"info":default:return"bg-sky-400/12 text-sky-100"}}function uC(t){switch(t){case"primary":return"Primary";case"secondary":return"Secondary";case"recovery":return"Recovery";case"background":default:return"Ambient"}}function Tw(t){return t.spentTodayAp>t.dailyBudgetAp?"Over budget":t.spentTodayAp<t.targetBandMinAp?"Below target band":"Inside target band"}function mC(t){return t.overloadApPerHour>0||t.instantFreeApPerHour<=0?"Recovery":t.instantCapacityApPerHour>=t.currentDrainApPerHour+4?"Deep work":"Low-friction admin"}function hC({lifeForce:t}){return e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Daily AP"}),e.jsxs("div",{className:"mt-2 font-display text-4xl text-[var(--primary)]",children:[Math.round(t.spentTodayAp),e.jsxs("span",{className:"ml-2 text-lg text-white/44",children:["/ ",Math.round(t.dailyBudgetAp)]})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:["Target band ",Math.round(t.targetBandMinAp),"-",Math.round(t.targetBandMaxAp)," AP"]}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:Tw(t)})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Instant headroom"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:t.instantFreeApPerHour.toFixed(1)}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:[Da(t.instantCapacityApPerHour)," capacity minus"," ",Da(t.currentDrainApPerHour)," load"]}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:t.overloadApPerHour>0?`${Da(t.overloadApPerHour)} overloaded`:"No overload right now"})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Fatigue buffer"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:t.fatigueBufferApPerHour.toFixed(1)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Short-term strain rises with overlap and falls with recovery."})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Forecast"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:Math.round(t.forecastAp)}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:["Planned remaining ",uu(t.plannedRemainingAp)]}),e.jsxs("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:["Remaining ",uu(t.remainingAp)]})]})]})}function pC({lifeForce:t}){return e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-6",children:t.stats.map(s=>e.jsxs(ce,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:s.label}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:["L",s.level]})]}),e.jsxs("div",{className:"mt-3 text-2xl font-semibold text-white",children:[Math.round(s.xp)," XP"]}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:s.key==="life_force"?`+${Math.round((s.costModifier-1)*100)}% daily resilience`:`${Math.round((1-s.costModifier)*100)}% cost relief`})]},s.key))})}function xC({lifeForce:t,weekday:s,points:a,baselineDailyAp:i,isDirty:r,isSaving:n,onChange:l,onReset:o,onSave:d,onWeekdayChange:m}){var Y,z;const h=c.useRef(null),[u,x]=c.useState(null),[g,p]=c.useState(720),[f,b]=c.useState(null),A=c.useMemo(()=>new Date().getDay(),[]),C=c.useMemo(()=>{const K=new Date;return K.getHours()*60+K.getMinutes()},[]),T=c.useMemo(()=>[...a].sort((K,$)=>K.minuteOfDay-$.minuteOfDay),[a]),w=c.useMemo(()=>T.map(K=>({...K,locked:s===A?K.minuteOfDay<=C:!1})),[C,T,A,s]),S=c.useMemo(()=>{const K=Math.max(t.instantCapacityApPerHour,...w.map($=>$.rateApPerHour),8);return Math.max(12,Math.ceil(K*1.25))},[t.instantCapacityApPerHour,w]),y=c.useMemo(()=>w.map(K=>({...K,label:rc(K.minuteOfDay)})),[w]),N=c.useMemo(()=>[0,240,480,720,960,1200,1440],[]),P=c.useMemo(()=>Array.from(new Set([0,Math.max(2,Math.round(S/3)),Math.max(4,Math.round(2*S/3)),S])).sort((K,$)=>K-$),[S]),v=Math.max(g,1),H=Math.max(160,v-fa.left-fa.right),j=Dp-fa.top-fa.bottom;c.useEffect(()=>{const K=()=>{var D;const $=((D=h.current)==null?void 0:D.clientWidth)??0;p($>0?$:720)};return K(),window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[]),c.useEffect(()=>{if(u===null||!h.current)return;const K=h.current,$=J=>{if(J.pointerId!==u.pointerId)return;J.preventDefault();const q=K.getBoundingClientRect(),_=Number.isFinite(J.clientX)?J.clientX:q.left+u.pointerX,B=Number.isFinite(J.clientY)?J.clientY:q.top+u.pointerY,G=Pa(_-q.left,0,q.width),ae=Pa(B-q.top,0,q.height),ke=Pa(_-q.left-fa.left,0,H),Ae=Pa(B-q.top-fa.top,0,j);l(w.map((ie,Ie)=>{if(Ie!==u.index)return{minuteOfDay:ie.minuteOfDay,rateApPerHour:ie.rateApPerHour,locked:ie.locked};if(ie.locked||Ie===0||Ie===w.length-1)return{minuteOfDay:ie.minuteOfDay,rateApPerHour:ie.rateApPerHour,locked:ie.locked};const Ne=w[Ie-1].minuteOfDay+Pr,M=w[Ie+1].minuteOfDay-Pr,E=Math.round(Pa(ke/H*1440,Ne,M)),O=w.map(Se=>({minuteOfDay:Se.minuteOfDay,rateApPerHour:Se.rateApPerHour,locked:Se.locked}));O[Ie]={...O[Ie],minuteOfDay:E};const xe=dC(O,Ie,i),V=Pa((j-Ae)/j*S,0,Math.max(0,xe));return O[Ie]={...O[Ie],rateApPerHour:Number(V.toFixed(3))},O[Ie]})),x(ie=>ie===null||ie.pointerId!==J.pointerId?ie:{...ie,pointerX:G,pointerY:ae})},D=J=>{(!J||J.pointerId===u.pointerId)&&x(null)};return window.addEventListener("pointermove",$,{passive:!1}),window.addEventListener("pointerup",D),window.addEventListener("pointercancel",D),()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",D),window.removeEventListener("pointercancel",D)}},[i,u,l,j,H,w,S]);const R=c.useMemo(()=>{if(!f)return[];const K=w[f.index]??null;return[{id:"remove-point",label:"Remove point",description:K===null?"No turn point is selected.":`Delete the turn point at ${rc(K.minuteOfDay)}.`,icon:Rt,tone:"danger",disabled:K===null||f.index===0||f.index===w.length-1,onSelect:()=>{l(w.filter(($,D)=>D!==f.index))}},{id:"flatten-point",label:"Flatten point",description:K===null?"No turn point is selected.":"Place the handle back on the interpolated segment between its neighbors.",icon:Gs,disabled:K===null||f.index===0||f.index===w.length-1,onSelect:()=>{const $=w[f.index-1],D=w[f.index+1],J=Fp([$,D],K.minuteOfDay);l(w.map((q,_)=>_===f.index?{...q,rateApPerHour:Number(J.toFixed(3))}:q))}}]},[f,l,w]),Q=c.useMemo(()=>w.map(K=>({...K,x:fa.left+K.minuteOfDay/1440*H,y:fa.top+(1-K.rateApPerHour/Math.max(1,S))*j})),[j,H,w,S]),X=u===null?null:{pointerX:u.pointerX,pointerY:u.pointerY,constrainedX:((Y=Q[u.index])==null?void 0:Y.x)??u.pointerX,constrainedY:((z=Q[u.index])==null?void 0:z.y)??u.pointerY};return e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:"overflow-hidden p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force view"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:"Instant Life Force editor"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/56",children:"One click adds a turn point. Drag future handles. Right click a handle to remove or flatten it. The ghost handle follows your finger or cursor while the real turn point stays constrained on the curve and normalized to the baseline daily AP budget."})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1 rounded-full bg-white/[0.04] p-1",children:Uo.map((K,$)=>e.jsx("button",{type:"button",className:te("rounded-full px-3 py-1.5 text-[11px] font-medium transition",s===$?"bg-[var(--primary)] text-slate-950":"text-white/60 hover:bg-white/[0.05] hover:text-white"),onClick:()=>m($),children:K},K))}),e.jsx(W,{variant:"secondary",onClick:o,children:"Reset"}),e.jsxs(W,{onClick:d,pending:n,disabled:!r,children:[e.jsx(oi,{className:"mr-2 size-4"}),"Save curve"]})]})]}),e.jsxs("div",{className:"mt-4 rounded-[24px] bg-[linear-gradient(180deg,rgba(192,193,255,0.08),rgba(192,193,255,0.02))] p-3",children:[e.jsxs("div",{ref:h,className:te("relative h-72 w-full overflow-hidden rounded-[20px] bg-[rgba(255,255,255,0.02)]",u!==null?"select-none touch-none":""),style:{touchAction:u===null?"pan-y":"none"},role:"img","aria-label":"Life Force capacity curve editor",onClick:K=>{if(u!==null||!h.current||K.target!==K.currentTarget)return;const $=h.current.getBoundingClientRect(),D=Pa(K.clientX-$.left-fa.left,0,H),J=Math.round(D/H*1440),q=w.findIndex(ke=>ke.minuteOfDay>J);if(q<=0)return;const _=w[q-1],B=w[q];if(J-_.minuteOfDay<Pr||B.minuteOfDay-J<Pr)return;const G=Fp(w,J),ae=[...w];ae.splice(q,0,{minuteOfDay:J,rateApPerHour:Number(G.toFixed(3)),locked:s===A&&J<=C}),l(ae)},children:[e.jsxs(Er,{width:v,height:Dp,data:y,margin:fa,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"life-force-chart-fill",x1:"0",x2:"0",y1:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgba(192,193,255,0.24)"}),e.jsx("stop",{offset:"100%",stopColor:"rgba(192,193,255,0.02)"})]})}),e.jsx(Fn,{vertical:!1,stroke:"rgba(255,255,255,0.08)",strokeDasharray:"3 4"}),e.jsx(ai,{dataKey:"minuteOfDay",type:"number",domain:[0,1440],ticks:N,tickFormatter:nC,tick:{fill:"rgba(255,255,255,0.48)",fontSize:10},tickLine:!1,axisLine:{stroke:"rgba(255,255,255,0.12)"},children:e.jsx(Jm,{value:"Time",position:"insideBottom",offset:-10,fill:"rgba(255,255,255,0.38)",fontSize:10})}),e.jsx(ii,{type:"number",domain:[0,S],ticks:P,tick:{fill:"rgba(255,255,255,0.48)",fontSize:10},tickLine:!1,axisLine:{stroke:"rgba(255,255,255,0.12)"},width:34,children:e.jsx(Jm,{value:"AP/h",angle:-90,position:"insideLeft",fill:"rgba(255,255,255,0.38)",fontSize:10,style:{textAnchor:"middle"}})}),e.jsx(Lr,{cursor:{stroke:"rgba(255,255,255,0.18)",strokeDasharray:"3 4"},content:({active:K,payload:$})=>{var J;const D=K?(J=$==null?void 0:$[0])==null?void 0:J.payload:null;return D?e.jsxs("div",{className:"rounded-[16px] border border-white/10 bg-[rgba(10,15,27,0.95)] px-3 py-2 text-xs text-white shadow-[0_18px_50px_rgba(4,8,18,0.3)] backdrop-blur-xl",children:[e.jsx("div",{className:"font-medium text-white",children:D.label}),e.jsx("div",{className:"mt-1 text-white/60",children:Da(D.rateApPerHour)})]}):null}}),s===A?e.jsx(Dv,{x:C,stroke:"rgba(255,255,255,0.22)",strokeDasharray:"3 4"}):null,e.jsx(Za,{type:"linear",dataKey:"rateApPerHour",stroke:"none",fill:"url(#life-force-chart-fill)",isAnimationActive:!1}),e.jsx(Cg,{type:"linear",dataKey:"rateApPerHour",stroke:"rgba(214,215,255,0.95)",strokeWidth:1.5,dot:!1,activeDot:!1,isAnimationActive:!1})]}),X?e.jsxs("svg",{className:"pointer-events-none absolute inset-0 z-[15] h-full w-full","aria-hidden":"true",children:[e.jsx("line",{x1:X.constrainedX,y1:X.constrainedY,x2:X.pointerX,y2:X.pointerY,stroke:"rgba(214,215,255,0.38)",strokeDasharray:"4 5",strokeWidth:"1.5"}),e.jsx("circle",{cx:X.pointerX,cy:X.pointerY,r:"11",fill:"rgba(214,215,255,0.12)",stroke:"rgba(214,215,255,0.34)",strokeWidth:"1.5","data-testid":"life-force-ghost-handle"}),e.jsx("circle",{cx:X.pointerX,cy:X.pointerY,r:"3.5",fill:"rgba(255,255,255,0.44)"})]}):null,Q.map((K,$)=>{const D=$===0||$===Q.length-1,J=(u==null?void 0:u.index)===$,q=D?14:16,_=D?22:28;return e.jsx("button",{type:"button","aria-label":`Turn point at ${rc(K.minuteOfDay)}`,className:te("absolute z-20 flex items-center justify-center rounded-full transition-transform duration-75",K.locked||D?"cursor-not-allowed":"cursor-grab active:cursor-grabbing",J?"scale-110":""),style:{left:K.x-_/2,top:K.y-_/2,width:_,height:_,touchAction:"none"},onPointerDown:B=>{if(B.preventDefault(),B.stopPropagation(),K.locked||D||!h.current)return;"setPointerCapture"in B.currentTarget&&B.currentTarget.setPointerCapture(B.pointerId);const G=h.current.getBoundingClientRect(),ae=Number.isFinite(B.clientX)?B.clientX:G.left+K.x,ke=Number.isFinite(B.clientY)?B.clientY:G.top+K.y;x({index:$,pointerId:B.pointerId,pointerX:Pa(ae-G.left,0,G.width),pointerY:Pa(ke-G.top,0,G.height)})},onContextMenu:B=>{B.preventDefault(),B.stopPropagation(),b({index:$,position:{x:B.clientX+6,y:B.clientY+6}})},children:e.jsx("span",{className:te("pointer-events-none inline-flex rounded-full border border-[rgba(10,15,27,0.92)] shadow-[0_0_0_1px_rgba(255,255,255,0.08),0_10px_24px_rgba(4,8,18,0.28)]",K.locked||D?"bg-white/55":"bg-white"),style:{width:q,height:q,opacity:J?.96:1}})},`${K.minuteOfDay}-${$}`)})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2 px-1 text-[11px] text-white/42",children:[e.jsxs("div",{children:["Editing ",Uo[s]," curve"]}),e.jsxs("div",{children:[Math.round(i)," AP/day baseline"]})]})]})]}),e.jsx(vd,{open:f!==null,title:"Turn point actions",subtitle:"Delete the turn point or flatten it back onto the surrounding segment.",items:R,position:(f==null?void 0:f.position)??null,onClose:()=>b(null)})]})}function gC(){return e.jsx(ce,{className:"overflow-hidden p-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force studio"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:"Edit weekday curves in the dedicated view"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/56",children:"The full weekday editor, turn-point menu, and curve calibration now live in their own page so Overview can stay fast and readable."})]}),e.jsxs(Je,{to:"/life-force",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center gap-2 overflow-hidden whitespace-nowrap rounded-[var(--radius-control)] border border-[var(--primary)]/14 bg-[var(--ui-accent-soft)] px-3 py-2 text-[13px] font-medium text-[var(--ui-ink-on-accent)] shadow-[var(--ui-shadow-soft)] transition hover:bg-[var(--ui-accent-soft-hover)]",children:[e.jsx(Vi,{className:"size-4"}),"Open Life Force studio"]})]})})}function fC({drains:t,plannedDrains:s,warnings:a,recommendations:i}){return e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ce,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Current drains"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:"What is consuming Life Force now"})]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[t.length," active"]})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:t.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:"No current drainers are active. This is a good moment to choose your next intentional action."}):t.map(r=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-base font-semibold text-white",children:r.title}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:r.why})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"text-base font-semibold text-[var(--primary)]",children:Da(r.apPerHour)}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-[0.14em] text-white/38",children:uC(r.role)})]})]})},r.id))})]}),e.jsxs(ce,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Planned drains"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:"What the rest of today is already asking from you"})]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[s.length," planned"]})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:s.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:"No future AP load has been forecast yet. The day is still open."}):s.slice(0,6).map(r=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-base font-semibold text-white",children:r.title}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:r.why})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"text-base font-semibold text-[var(--primary)]",children:uu(r.instantAp)}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-[0.14em] text-white/38",children:Da(r.apPerHour)})]})]})},r.id))})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Warnings"}),e.jsx("div",{className:"mt-4 grid gap-3",children:a.map(r=>e.jsxs("div",{className:te("rounded-[18px] px-4 py-4",cC(r.tone)),children:[e.jsx("div",{className:"text-sm font-semibold",children:r.title}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-current/80",children:r.detail})]},r.id))})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Recommendations"}),e.jsx("div",{className:"mt-4 grid gap-2",children:i.map((r,n)=>e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/66",children:r},`${r}-${n}`))})]})]})]})}function Pw({lifeForce:t,onTired:s,onOkayAgain:a,tiredPending:i,okayPending:r,feedback:n}){return e.jsxs(ce,{className:"overflow-hidden p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force now"}),e.jsxs("div",{className:"mt-2 text-2xl font-semibold text-white",children:[t.instantFreeApPerHour.toFixed(1)," AP/h free"]}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:[Math.round(t.spentTodayAp)," / ",Math.round(t.dailyBudgetAp)," AP used today"]}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:Tw(t)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(W,{variant:"secondary",onClick:s,pending:i,children:[e.jsx($u,{className:"mr-2 size-4"}),"I'm getting tired"]}),e.jsxs(W,{variant:"secondary",onClick:a,pending:r,children:[e.jsx(Ou,{className:"mr-2 size-4"}),"I'm okay again"]})]})]}),n?e.jsx("div",{className:"mt-4 rounded-[18px] bg-[var(--primary)]/10 px-4 py-3 text-sm text-white/74",children:n}):null,e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx(Vi,{className:"size-4 text-[var(--primary)]"}),"Instant capacity"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Da(t.instantCapacityApPerHour)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx(sd,{className:"size-4 text-[var(--primary)]"}),"Current load"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Da(t.currentDrainApPerHour)}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:t.overloadApPerHour>0?`${Da(t.overloadApPerHour)} overload`:"Inside instant limit"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx(Lv,{className:"size-4 text-[var(--primary)]"}),"Next move"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:t.recommendations[0]??"Favor the next clean, manageable action."}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:mC(t)})]})]})]})}function Aw({selectedUserIds:t,fallbackLifeForce:s,onRefresh:a,showEditor:i=!0}){var S,y;const r=ct(),n=new Date().getDay(),[l,o]=c.useState(n),d=Fe({queryKey:["forge-life-force",...t],queryFn:()=>Ji(t),initialData:s===void 0?void 0:{lifeForce:s,templates:Uo.map((N,P)=>({weekday:P,baselineDailyAp:s.baselineDailyAp,points:s.currentCurve.map(v=>({...v,locked:P===n?v.locked:!1}))}))}}),m=((S=d.data)==null?void 0:S.lifeForce)??s,u=(((y=d.data)==null?void 0:y.templates)??rC(m,n)).find(N=>N.weekday===l)??{weekday:l,baselineDailyAp:m.baselineDailyAp,points:m.currentCurve},[x,g]=c.useState(u.points),[p,f]=c.useState(!1),[b,A]=c.useState(null);c.useEffect(()=>{g(u.points),f(!1)},[u.points,u.weekday]);const C=Re({mutationFn:N=>xj(u.weekday,{points:oC(N,u.baselineDailyAp)},t),onSuccess:async N=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),g(N.points),f(!1)}}),T=Re({mutationFn:()=>Do({signalType:"tired"},t),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),A("Tiredness signal applied. Today’s Life Force now reflects the extra strain.")}}),w=Re({mutationFn:()=>Do({signalType:"okay_again"},t),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),A("Recovery signal applied. Instant strain has been eased for the rest of today.")}});return e.jsxs("div",{className:"grid gap-4",children:[e.jsx(hC,{lifeForce:m}),e.jsx(pC,{lifeForce:m}),e.jsx(Pw,{lifeForce:m,onTired:()=>{T.mutateAsync()},onOkayAgain:()=>{w.mutateAsync()},tiredPending:T.isPending,okayPending:w.isPending,feedback:b}),i?e.jsx(xC,{lifeForce:m,weekday:l,points:x,baselineDailyAp:u.baselineDailyAp,isDirty:p,isSaving:C.isPending,onWeekdayChange:o,onChange:N=>{g(N),f(!0)},onReset:()=>{g(u.points),f(!1)},onSave:()=>{C.mutateAsync(x)}}):e.jsx(gC,{}),e.jsx(fC,{drains:m.activeDrains,plannedDrains:m.plannedDrains,warnings:m.warnings,recommendations:m.recommendations}),m.topTaskIdsNeedingSplit.length>0?e.jsxs(ce,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-white",children:[e.jsx(ad,{className:"size-4 text-[var(--primary)]"}),"Tasks asking to be split"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:m.topTaskIdsNeedingSplit.map(N=>e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:N},N))})]}):null]})}function bC({selectedUserIds:t,fallbackLifeForce:s,onRefresh:a}){var u;const i=Array.isArray(t)?t:[],r=ct(),l=((u=Fe({queryKey:["forge-life-force",...i],queryFn:()=>Ji(i),initialData:s===void 0?void 0:{lifeForce:s,templates:[]}}).data)==null?void 0:u.lifeForce)??s;if(!l)return e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:"Not calibrated yet"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Today can still load without a Life Force snapshot, but the AP and instant headroom model is not available for this state yet."})]});const[o,d]=c.useState(null),m=Re({mutationFn:()=>Do({signalType:"tired"},i),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),d("Tiredness signal applied. Today’s headroom has been reduced.")}}),h=Re({mutationFn:()=>Do({signalType:"okay_again"},i),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),d("Recovery signal applied. Today’s headroom has been eased.")}});return e.jsx(Pw,{lifeForce:l,onTired:()=>{m.mutateAsync()},onOkayAgain:()=>{h.mutateAsync()},tiredPending:m.isPending,okayPending:h.isPending,feedback:o})}function wC(){const t=jt(),s=t.snapshot.lifeForce;return s?e.jsxs("div",{className:"grid gap-4",children:[e.jsx(nt,{title:"Life Force",titleText:"Life Force",description:"Edit weekday Action Point curves, inspect drains, and tune the capacity model without crowding the Overview surface.",badge:`${Math.round(s.spentTodayAp)} / ${Math.round(s.dailyBudgetAp)} AP`,actions:e.jsx(lu,{users:t.snapshot.users,selectedUserIds:t.selectedUserIds,onChange:t.setSelectedUserIds})}),e.jsx(Aw,{selectedUserIds:t.selectedUserIds,fallbackLifeForce:s,onRefresh:t.refresh,showEditor:!0})]}):e.jsx("div",{className:"grid gap-4",children:e.jsx(nt,{title:"Life Force",titleText:"Life Force",description:"Action Point capacity, weekday curves, and instant headroom editing live here.",badge:"Not calibrated yet"})})}function Mw({open:t,onOpenChange:s,place:a,seed:i,onSave:r}){const[n,l]=c.useState({label:(a==null?void 0:a.label)??(i==null?void 0:i.label)??"",latitude:String((a==null?void 0:a.latitude)??(i==null?void 0:i.latitude)??""),longitude:String((a==null?void 0:a.longitude)??(i==null?void 0:i.longitude)??""),radiusMeters:String((a==null?void 0:a.radiusMeters)??(i==null?void 0:i.radiusMeters)??100),categoryTags:((a==null?void 0:a.categoryTags)??(i==null?void 0:i.categoryTags)??[]).join(", ")});return c.useEffect(()=>{l({label:(a==null?void 0:a.label)??(i==null?void 0:i.label)??"",latitude:String((a==null?void 0:a.latitude)??(i==null?void 0:i.latitude)??""),longitude:String((a==null?void 0:a.longitude)??(i==null?void 0:i.longitude)??""),radiusMeters:String((a==null?void 0:a.radiusMeters)??(i==null?void 0:i.radiusMeters)??100),categoryTags:((a==null?void 0:a.categoryTags)??(i==null?void 0:i.categoryTags)??[]).join(", ")})},[a,i]),e.jsx(Yt,{open:t,onOpenChange:s,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs(es,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(32rem,calc(100vw-1.25rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ts,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:a?`Edit ${a.label}`:"New known place"}),e.jsx(rs,{className:"mt-1 text-sm text-white/58",children:"Define life landmarks once so the companion and web views can reason about stays and trips consistently."})]}),e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white",children:e.jsx(Tt,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsx(ye,{value:n.label,onChange:o=>l(d=>({...d,label:o.target.value})),placeholder:"Home, Main Office, Riverside path..."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(ye,{value:n.latitude,onChange:o=>l(d=>({...d,latitude:o.target.value})),placeholder:"Latitude"}),e.jsx(ye,{value:n.longitude,onChange:o=>l(d=>({...d,longitude:o.target.value})),placeholder:"Longitude"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[10rem_minmax(0,1fr)]",children:[e.jsx(ye,{value:n.radiusMeters,onChange:o=>l(d=>({...d,radiusMeters:o.target.value})),placeholder:"Radius meters"}),e.jsx(ye,{value:n.categoryTags,onChange:o=>l(d=>({...d,categoryTags:o.target.value})),placeholder:"home, gym, holiday, parents-house"})]})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx(W,{variant:"ghost",onClick:()=>s(!1),className:"border border-white/10 bg-white/[0.04]",children:"Cancel"}),e.jsx(W,{onClick:()=>void r({id:a==null?void 0:a.id,label:n.label,latitude:Number(n.latitude),longitude:Number(n.longitude),radiusMeters:Number(n.radiusMeters),categoryTags:n.categoryTags.split(",").map(o=>o.trim()).filter(Boolean)}).then(()=>s(!1)),children:"Save place"})]})]})]})})}const mu=1e3;function ps(t){return new Date(t).getTime()}function hu(t){return new Date(t).toISOString()}function _p(t,s){const a=ps(t.startedAt)-ps(s.startedAt);if(a!==0)return a;const i=ps(t.endedAt)-ps(s.endedAt);return i!==0?i:t.id.localeCompare(s.id)}function qm(t){return t.syncSource==="sleep overlay"}function yC(t){const s=[...t].filter(i=>ps(i.endedAt)>ps(i.startedAt)).sort((i,r)=>{const n=ps(i.startedAt)-ps(r.startedAt);if(n!==0)return n;const l=ps(i.endedAt)-ps(r.endedAt);return l!==0?l:i.id.localeCompare(r.id)});if(s.length===0)return[];const a=[];for(const i of s){const r=a.at(-1);if(!r){a.push(i);continue}const n=ps(r.endedAt);if(ps(i.startedAt)<=n+mu){const o=Math.max(n,ps(i.endedAt));a[a.length-1]={...r,id:`${r.id}__${i.id}`,endedAt:hu(o),asleepSeconds:(r.asleepSeconds??0)+(i.asleepSeconds??0)||null,timeInBedSeconds:(r.timeInBedSeconds??0)+(i.timeInBedSeconds??0)||null,sleepScore:i.sleepScore??r.sleepScore,regularityScore:i.regularityScore??r.regularityScore,efficiency:i.efficiency??r.efficiency,recoveryState:i.recoveryState??r.recoveryState};continue}a.push(i)}return a}function vC(t){const s=[];if(typeof t.asleepSeconds=="number"&&t.asleepSeconds>0){const a=t.asleepSeconds/3600;s.push(`${a.toFixed(a>=1?1:2)}h asleep`)}else if(typeof t.timeInBedSeconds=="number"&&t.timeInBedSeconds>0){const a=t.timeInBedSeconds/3600;s.push(`${a.toFixed(a>=1?1:2)}h in bed`)}return typeof t.sleepScore=="number"&&s.push(`score ${t.sleepScore}`),typeof t.regularityScore=="number"&&s.push(`regularity ${t.regularityScore}`),t.recoveryState&&s.push(t.recoveryState),s.join(" · ")||"Sleep session"}function jC(t){const s=Math.max(60,Math.round((ps(t.endedAt)-ps(t.startedAt))/1e3));return{id:`sleep-overlay-${t.id}`,boxId:`sleep-overlay-${t.id}`,kind:"stay",sourceKind:"automatic",origin:"recorded",editable:!1,isInvalid:!1,startedAt:t.startedAt,endedAt:t.endedAt,trueStartedAt:t.startedAt,trueEndedAt:t.endedAt,visibleStartedAt:t.startedAt,visibleEndedAt:t.endedAt,durationSeconds:s,laneSide:"left",connectorFromLane:"left",connectorToLane:"left",title:"Sleep",subtitle:vC(t),placeLabel:null,tags:["sleep"],syncSource:"sleep overlay",cursor:`${t.endedAt}::sleep-overlay-${t.id}`,overrideCount:0,overriddenAutomaticBoxIds:[],overriddenUserBoxIds:[],isFullyHidden:!1,rawStayIds:[],rawTripIds:[],rawPointCount:0,hasLegacyCorrections:!1,stay:null,trip:null}}function Rp(t,s,a){if(a<=s)return null;const i=hu(s),r=hu(a),n=Math.max(60,Math.round((a-s)/1e3));return{...t,id:`${t.id}::virtual-${s}-${a}`,startedAt:i,endedAt:r,trueStartedAt:i,trueEndedAt:r,visibleStartedAt:i,visibleEndedAt:r,durationSeconds:n,cursor:`${r}::${t.id}::virtual`}}function NC(t,s){let a=[...t].sort(_p);for(const i of yC(s)){const r=ps(i.startedAt),n=ps(i.endedAt),l=jC(i),o=[];let d=!1;for(const m of a){const h=ps(m.startedAt),u=ps(m.endedAt);if(u<=r||h>=n){!d&&h>=n&&(o.push(l),d=!0),o.push(m);continue}if(h<r){const x=Rp(m,h,Math.min(u,r-mu));x&&o.push(x)}if(d||(o.push(l),d=!0),u>n){const x=Rp(m,Math.max(h,n+mu),u);x&&o.push(x)}}d||o.push(l),a=o.sort(_p)}return a}const $p=24,ya=64,pu=360*60,Ew=5,nc=1,kC=104;function Xa(t){return t.trim().toLowerCase()}function rl(t){return t>=86400?`${Math.round(t/3600)}h`:t>=3600?`${(t/3600).toFixed(1)}h`:`${Math.max(1,Math.round(t/60))}m`}function ei(t){return new Intl.DateTimeFormat(void 0,{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function SC(t){return new Intl.DateTimeFormat(void 0,{day:"2-digit",month:"2-digit",year:"2-digit"}).format(new Date(t))}function IC(t){return new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:!1}).format(t)}function Br(t){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 Wo(t){if(!t.trim())return null;const s=new Date(t);return Number.isNaN(s.getTime())?null:s.toISOString()}function Ur(t){return t>=1e3?`${(t/1e3).toFixed(1)} km`:`${Math.round(t)} m`}function Ws(t){return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}).format(new Date(t))}function Op(t,s){return`${t.toFixed(3)}, ${s.toFixed(3)}`}function Gl(t,s){return`${t.toFixed(6)}, ${s.toFixed(6)}`}function zp(t){return`${Math.max(1,Math.round(t/60))} min`}function CC(t){if(t.length===0)return[];const s=Math.min(...t.map(o=>o.latitude)),a=Math.max(...t.map(o=>o.latitude)),i=Math.min(...t.map(o=>o.longitude)),r=Math.max(...t.map(o=>o.longitude)),n=Math.max(a-s,1e-4),l=Math.max(r-i,1e-4);return t.map((o,d)=>({...o,x:12+(o.longitude-i)/l*76,y:12+(1-(o.latitude-s)/n)*76,id:`${o.recordedAt??"point"}-${d}`}))}function xu(t){return!ka(t)||t.stay.place?null:{label:t.stay.label||t.title,latitude:t.stay.centerLatitude,longitude:t.stay.centerLongitude,radiusMeters:t.stay.radiusMeters,categoryTags:t.tags}}function Wi(t){var s;return t?t.kind==="stay"&&ka(t)?((s=t.stay.place)==null?void 0:s.label)??t.placeLabel??t.stay.label??null:t.placeLabel??null:null}function vo(t,s,a,i){const n=(a-t)*Math.PI/180,l=(i-s)*Math.PI/180,o=t*Math.PI/180,d=a*Math.PI/180,m=Math.sin(n/2)**2+Math.cos(o)*Math.cos(d)*Math.sin(l/2)**2;return 2*6371e3*Math.asin(Math.sqrt(m))}function TC(t){return Xa([t.label,...t.aliases].join(" "))}function Ho(t){return t.kind==="trip"&&t.trip!==null}function ka(t){return t.kind==="stay"&&t.stay!==null}function Hi(t,s,a){if(!t.trip)return{label:t.placeLabel??(s==="start"?"Known origin":"Known destination"),detail:Ws(s==="start"?t.startedAt:t.endedAt)};const i=s==="start"?t.trip.points[0]??null:t.trip.points[t.trip.points.length-1]??null,r=s==="start"?t.trip.startPlace:t.trip.endPlace,n=(a==null?void 0:a.includeCoordinates)??!0,l=a!=null&&a.useHistoryAnchorFallback&&s==="start"?"Beginning of history":null;return{label:(r==null?void 0:r.label)??l??(n&&i?Op(i.latitude,i.longitude):s==="start"?"Unknown origin":"Unknown destination"),detail:n&&i&&!r?Op(i.latitude,i.longitude):Ws(s==="start"?t.startedAt:t.endedAt)}}function PC(t){const s=t.trim().toLowerCase();return s==="travel"||s==="trip"||s==="move"}function AC(t){const s=t.title.trim().toLowerCase();return s.length===0||s==="stay"||s==="continued stay"||s==="repaired stay"?t.sourceKind==="user_defined"?t.origin==="user_invalidated"?"User invalidated movement":"User-defined missing data":"Missing data":t.title}function MC(t){const s=Wi(t),a=t.title.trim().toLowerCase(),i=a.length===0||a==="stay"||a==="continued stay"||a==="repaired stay"||a==="manual stay";return s&&i?s:t.title.trim()||s||"Stay"}function ti(t){if(qm(t))return"Sleep";if(t.kind==="missing")return AC(t);if(t.kind==="stay")return MC(t);if(t.kind==="trip"&&PC(t.title)){const s=Hi(t,"start").label,a=Hi(t,"end").label;return`${s} → ${a}`}return t.title}function Kp(t){return t==="left"?24:t==="right"?76:50}function EC(t,s,a){const i=Math.min(t,pu)/3600,r=a==="sleep overlay",n=r?144:s==="stay"?132:124,l=r?364:s==="stay"?404:328,o=n+i*44;return Math.max(n,Math.min(l,o))}function gu(t){var s;return{kind:t.kind,label:ka(t)?t.stay.label||t.title:Ho(t)&&t.trip.label||t.title,placeLabel:ka(t)?((s=t.stay.place)==null?void 0:s.label)??t.placeLabel??"":"",tagsInput:t.tags.join(", "),startedAtInput:Br(t.startedAt),endedAtInput:Br(t.endedAt)}}function lc(t,s){const a=(s==null?void 0:s.startedAt)??new Date(Date.now()-36e5).toISOString(),i=(s==null?void 0:s.endedAt)??new Date().toISOString();return{kind:t,label:t==="missing"?"User-defined missing data":t==="stay"?(s==null?void 0:s.placeLabel)||"Manual stay":"Manual move",placeLabel:(s==null?void 0:s.placeLabel)??"",tagsInput:t==="missing"?"user-defined, missing-data":t==="stay"?"user-defined, stay":"user-defined, move",startedAtInput:Br(a),endedAtInput:Br(i)}}function fu(t,s){var n,l;const a=t.tagsInput.split(",").map(o=>o.trim()).filter(Boolean),i=Wo(t.startedAtInput)??(s==null?void 0:s.startedAt)??new Date(Date.now()-3600*1e3).toISOString(),r=Wo(t.endedAtInput)??(s==null?void 0:s.endedAt)??new Date().toISOString();return{kind:t.kind,startedAt:i,endedAt:r,title:t.label.trim(),subtitle:t.kind==="missing"?"User-defined missing-data override.":"User-defined movement box.",placeLabel:t.placeLabel.trim()||null,tags:a,distanceMeters:t.kind==="trip"?Math.max(((n=s==null?void 0:s.trip)==null?void 0:n.distanceMeters)??150,150):null,averageSpeedMps:t.kind==="trip"?((l=s==null?void 0:s.trip)==null?void 0:l.averageSpeedMps)??null:null,metadata:{createdFrom:"movement-life-timeline"}}}function LC(t,s){var r,n;const a=t.kind==="stay"?((n=(r=t.stay)==null?void 0:r.label)==null?void 0:n.trim())??"":"";if(a)return a;const i=t.title.trim();return i&&i.toLowerCase()!=="stay"?i:s.trim()||"Stay"}function DC(t,s){const a=gu(t),i=s.trim();return fu({...a,label:LC(t,i),placeLabel:i},t)}function Lw(t){const s=new Date(t).getHours();return s<6?"night":s<12?"morning":s<18?"afternoon":"evening"}function Go(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function FC(t){var s,a,i;return Xa([t.kind,ti(t),t.subtitle,t.placeLabel??"",...t.tags,Go(t.startedAt),Go(t.endedAt),Lw(t.startedAt),ka(t)?((s=t.stay.place)==null?void 0:s.label)??t.stay.label:Ho(t)?[t.trip.label,t.trip.activityType,t.trip.travelMode,(a=t.trip.startPlace)==null?void 0:a.label,(i=t.trip.endPlace)==null?void 0:i.label].filter(Boolean).join(" "):t.kind==="trip"?[t.title,t.subtitle,t.placeLabel??""].filter(Boolean).join(" "):"missing data gap"].join(" "))}function _C(t){const s=new Map;s.set("kind:stay",{id:"kind:stay",label:"Stay",description:"Stationary spans and place anchors."}),s.set("kind:trip",{id:"kind:trip",label:"Move",description:"Trips and movement connectors."});for(const a of["night","morning","afternoon","evening"])s.set(`time:${a}`,{id:`time:${a}`,label:a[0].toUpperCase()+a.slice(1),description:"Filter by the segment start time."});for(const a of t){for(const i of a.tags)s.set(`tag:${i}`,{id:`tag:${i}`,label:i,description:"Movement tag"});a.placeLabel&&s.set(`place:${a.placeLabel}`,{id:`place:${a.placeLabel}`,label:a.placeLabel,description:"Matched place"})}return[...s.values()].sort((a,i)=>a.label.localeCompare(i.label))}function RC(t,s){return s.every(a=>a==="kind:stay"||a==="kind:trip"?t.kind===a.slice(5):a.startsWith("time:")?Lw(t.startedAt)===a.slice(5):a.startsWith("tag:")?t.tags.includes(a.slice(4)):a.startsWith("place:")?(t.placeLabel??"")===a.slice(6):!0)}function qp(t,s){return t&&{...t,pages:t.pages.map(a=>({...a,segments:a.segments.filter(i=>i.id!==s)}))}}function $C(t,s){const a=t+(Math.sin((t-.5)*Math.PI)+1)*.5-t,i=t-.5,n=.5+(i*(1-s*.64)+i*i*i*s*2.56);return Math.max(0,Math.min(1,n-(a-t)*s*.08))}function OC(t){return t.getHours()===0?SC(t.toISOString()):IC(t)}function zC(t,s){const a=new Date(t.endedAt).getTime(),i=new Date(t.startedAt).getTime(),r=Math.max(1,a-i),n=Math.max(0,Math.min(1,(s-i)/r));if(t.durationSeconds<=pu)return n;const l=Math.max(0,1-Math.min(1,pu/Math.max(1,t.durationSeconds)));return $C(n,l)}function KC(t,s,a){if(t.items.length===0)return null;const i=t.items[0];if(s<new Date(i.segment.startedAt).getTime())return t.historyHeaderHeight+t.leadHeight-(new Date(i.segment.startedAt).getTime()-s)/36e5*ya;for(let l=0;l<t.items.length;l+=1){const o=t.items[l],d=new Date(o.segment.startedAt).getTime(),m=new Date(o.segment.endedAt).getTime();if(s>=d&&s<=m)return o.boxTop+zC(o.segment,s)*o.displayHeight;const h=t.items[l+1]??null,u=h?new Date(h.segment.startedAt).getTime():a;if(s>m&&s<u)return o.boxBottom+(s-m)/36e5*ya}const r=t.items[t.items.length-1],n=new Date(r.segment.endedAt).getTime();return s>=n?r.boxBottom+(s-n)/36e5*ya:null}function qC(t){const s=new Date(t);s.setMinutes(0,0,0);const a=s.getTime();return a<=t?a+36e5:a}function BC(t,s){const a=[];if(t.items.length===0)return a;const i=t.items[0],r=new Date(i.segment.startedAt).getTime();for(let n=qC(r-Ew*36e5);n<=s;n+=36e5){const l=KC(t,n,s);if(l===null)continue;const o=new Date(n);a.push({y:l,label:OC(o),strong:o.getHours()===0})}return a}function UC({segments:t,viewportHeight:s,nowMs:a=Date.now()}){var g;const i=t.length>0?kC:0,r=t.length>0?ya*Ew:0;let n=i+r,l=null;const o=t.map(p=>{const f=EC(p.durationSeconds,p.kind,p.syncSource),b=new Date(p.startedAt).getTime(),A=l===null?0:Math.max(0,(b-l)/36e5)*ya;n+=A;const C=n,T=C+f;return n=T,l=new Date(p.endedAt).getTime(),{id:p.id,segment:p,gapBefore:A,displayHeight:f,boxTop:C,boxBottom:T}}),d=a+nc*36e5,m=(()=>{var b;const p=(b=t[t.length-1])==null?void 0:b.endedAt;if(!p)return ya*nc;const f=new Date(p).getTime();return Math.max(ya*nc,(d-f)/36e5*ya)})(),h=(((g=o[o.length-1])==null?void 0:g.boxBottom)??i+r)+m,u=Math.max(h,s>0?s+260:960,i+r+m),x={historyHeaderHeight:i,leadHeight:r,items:o,markers:[],rangeEndMs:d,futureTailHeight:m+Math.max(0,u-h),totalHeight:u};return{...x,markers:BC(x,d)}}function WC({layout:t,scrollTop:s,viewportHeight:a}){const i=ya*6,r=Math.max(0,s-i),n=Math.min(t.totalHeight,s+Math.max(a,ya*8)+i),l=t.markers.filter(o=>o.y>=r&&o.y<=n);return e.jsxs("div",{className:"pointer-events-none absolute inset-x-0 top-0 overflow-hidden rounded-[30px]",style:{height:`${t.totalHeight}px`},children:[e.jsx("div",{className:"absolute inset-y-0 left-0 w-18 bg-[linear-gradient(90deg,rgba(7,12,22,0.96),rgba(7,12,22,0.42),transparent)]"}),l.map((o,d)=>e.jsxs("div",{className:"absolute inset-x-0",style:{top:`${o.y}px`},children:[e.jsx("div",{className:te("border-t",o.strong?"border-white/14":"border-white/7")}),e.jsx("div",{className:te("absolute left-3 top-0 -translate-y-1/2 font-label text-[9px] tracking-[0.24em]",o.strong?"text-white/38":"text-white/22"),children:o.label})]},`timeline-grid-${d}`))]})}function HC({fromSide:t,toSide:s,height:a,emphasized:i}){const r=Kp(t),n=Kp(s),l=`M ${r} 16 C ${r} ${Math.max(40,a*.26)}, ${n} ${Math.max(70,a*.72)}, ${n} ${a-18}`;return e.jsxs("svg",{viewBox:`0 0 100 ${a}`,className:"absolute inset-x-0 top-0 h-full w-full overflow-visible",preserveAspectRatio:"none",children:[e.jsx("path",{d:l,fill:"none",stroke:i?"rgba(241,246,255,0.18)":"rgba(241,246,255,0.11)",strokeWidth:i?"1.05":"0.85",strokeDasharray:i?"3 10":"2.5 12",strokeLinecap:"round"}),e.jsx("circle",{cx:r,cy:"16",r:"1.5",fill:"rgba(255,255,255,0.26)"}),e.jsx("circle",{cx:n,cy:a-18,r:"1.5",fill:"rgba(255,255,255,0.26)"})]})}function bu({position:t}){return e.jsx("div",{className:te("absolute left-1/2 z-20 flex -translate-x-1/2 items-center justify-center",t==="top"?"-top-3":"-bottom-3"),children:e.jsx("div",{className:"h-6 w-[3px] rounded-full bg-[rgba(160,224,255,0.92)] shadow-[0_0_14px_rgba(126,229,255,0.36)]"})})}function GC({segment:t}){const s=(t==null?void 0:t.kind)==="stay"?t.placeLabel||t.title||null:(t==null?void 0:t.kind)==="trip"?Hi(t,"start",{includeCoordinates:!1,useHistoryAnchorFallback:!0}).label:null,a=s||"Beginning of time";return e.jsx("div",{className:"pointer-events-none flex justify-center px-6 py-4",children:e.jsxs("div",{className:"relative w-[min(18rem,calc(100vw-6rem))] overflow-hidden rounded-[26px] border border-[rgba(152,208,255,0.2)] bg-[linear-gradient(180deg,rgba(98,130,238,0.14),rgba(18,34,79,0.14))] shadow-[0_20px_48px_rgba(3,8,20,0.3)]",children:[e.jsx(bu,{position:"bottom"}),e.jsxs("div",{className:"relative z-10 px-5 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(I,{tone:"signal",className:"bg-white/10 text-white/78",children:"Start"}),e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.2em] text-white/28",children:"Beginning of history"})]}),e.jsx("div",{className:"mt-5 font-display text-[1.25rem] tracking-[-0.05em] text-white",children:a}),e.jsx("div",{className:"mt-2 font-label text-[10px] uppercase tracking-[0.22em] text-white/30",children:s?"Oldest loaded known stay":"Earliest known anchor"})]})]})})}function QC({segment:t,onEdit:s,onOpenDetail:a,onDefinePlace:i}){var n;const r=qm(t);return e.jsxs(ce,{className:"rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(9,14,26,0.98),rgba(5,9,19,0.95))] p-5 shadow-[0_24px_74px_rgba(0,0,0,0.34)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:r?"Sleep overlay":t.kind==="stay"?"Stay detail":t.kind==="trip"?"Move detail":"Missing data"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ti(t)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{className:r?"bg-cyan-400/14 text-cyan-100":t.sourceKind==="user_defined"?"bg-fuchsia-400/12 text-fuchsia-100":"bg-white/[0.06] text-white/70",children:r?"Virtual":t.sourceKind==="user_defined"?t.origin==="user_invalidated"?"User invalidated":"User-defined":"Automatic"}),t.overrideCount>0?e.jsxs(I,{className:"bg-amber-400/10 text-amber-100",children:["Overrides ",t.overrideCount," automatic box",t.overrideCount===1?"":"es"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{onClick:a,variant:"ghost",className:"rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/78 hover:bg-white/[0.08]",disabled:r,children:"Details"}),e.jsx(W,{onClick:s,variant:"ghost",className:"size-9 rounded-full border border-white/10 bg-white/[0.04] text-white/78 hover:bg-white/[0.08]","aria-label":"Edit movement segment",disabled:r||t.kind==="missing"||!t.editable,children:e.jsx(da,{className:"size-4"})}),e.jsx(Es,{className:"size-4 text-white/42"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Started"}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:ei(t.startedAt)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Ended"}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:ei(t.endedAt)})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{tone:"signal",children:rl(t.durationSeconds)}),Ho(t)?e.jsxs(e.Fragment,{children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Ur(t.trip.distanceMeters)}),t.trip.stops.length>0?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[t.trip.stops.length," stop",t.trip.stops.length===1?"":"s"]}):null]}):null,r?e.jsx(I,{className:"bg-cyan-400/12 text-cyan-50",children:t.subtitle}):Wi(t)?e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Wi(t)}):null]}),ka(t)&&!r?e.jsxs("div",{className:"mt-4 rounded-[18px] border border-sky-300/14 bg-sky-300/8 p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-sky-100/66",children:"Location label"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-sky-50/86",children:t.stay.place?`This stay is currently linked to ${t.stay.place.label}. Search saved places or relabel it from this stay center.`:"Search saved places for this stay, or create a new one from the stay center so later matching stays inherit it automatically."}),e.jsx("div",{className:"mt-3",children:e.jsx(W,{onClick:i,variant:"ghost",className:"rounded-full border border-sky-300/24 bg-sky-300/12 px-4 text-sky-50 hover:bg-sky-300/18",children:"Label location"})})]}):null,e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Timeline summary"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/76",children:t.kind==="stay"?r?`Sleep overlay from ${Ws(t.startedAt)} to ${Ws(t.endedAt)}. Underlying movement boxes are sliced virtually while this overlay is visible.`:`Stay block from ${Ws(t.startedAt)} to ${Ws(t.endedAt)}.`:t.kind==="trip"?`Connector from ${Hi(t,"start").label} to ${Hi(t,"end").label}.`:`No reliable movement signal reached Forge from ${Ws(t.startedAt)} to ${Ws(t.endedAt)}.`})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Projection model"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/76",children:r?"This sleep layer is visual only. Forge does not persist these split boxes; it temporarily slices the visible movement boxes around each sleep interval.":"Raw phone measurements stay immutable. Forge derives automatic boxes from that raw movement evidence, then overlays user-defined boxes on top without mutating the imported raw data."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:["Raw stays ",t.rawStayIds.length]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:["Raw trips ",t.rawTripIds.length]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:["Raw points ",t.rawPointCount]}),t.hasLegacyCorrections?e.jsx(I,{className:"bg-amber-400/10 text-amber-100",children:"Legacy corrections present"}):null]})]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-2 text-sm text-white/56",children:r?e.jsxs(e.Fragment,{children:[e.jsx(Wu,{className:"size-4 text-cyan-300"}),"Sleep overlay"]}):ka(t)?e.jsxs(e.Fragment,{children:[e.jsx(qu,{className:"size-4 text-[var(--primary)]"}),((n=t.stay.place)==null?void 0:n.label)??"No canonical place linked yet"]}):Ho(t)?e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"size-4 text-[var(--primary)]"}),t.trip.activityType||t.trip.travelMode]}):t.kind==="trip"?e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"size-4 text-[var(--primary)]"}),"Repaired movement connector"]}):e.jsxs(e.Fragment,{children:[e.jsx(_r,{className:"size-4 text-white/56"}),"Missing intervals are synthesized from long signal gaps instead of inventing fake travel."]})})]})}function Bp({title:t,points:s,averagePoint:a}){const i=CC(a?[...s,a]:s),r=a?i.length-1:i.length,n=i.slice(0,r),l=a?i[i.length-1]??null:null,o=n.map((d,m)=>`${m===0?"M":"L"} ${d.x} ${d.y}`).join(" ");return e.jsxs(ce,{className:"rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,13,25,0.95),rgba(10,17,30,0.88))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:t}),e.jsx("div",{className:"mt-2 text-sm text-white/62",children:"Relative coordinates normalized into one view so we can inspect the actual captured stay or trip geometry in one glance."}),e.jsx("div",{className:"mt-5 rounded-[24px] border border-white/8 bg-[rgba(255,255,255,0.03)] p-3",children:e.jsxs("svg",{viewBox:"0 0 100 100",className:"h-52 w-full",children:[e.jsx("rect",{x:"0",y:"0",width:"100",height:"100",rx:"18",fill:"rgba(255,255,255,0.02)"}),n.length>1?e.jsx("path",{d:o,fill:"none",stroke:"rgba(92,225,230,0.95)",strokeWidth:"1.6"}):null,n.map((d,m)=>e.jsx("circle",{cx:d.x,cy:d.y,r:m===0||m===n.length-1?2.2:1.4,fill:m===0||m===n.length-1?"#ffffff":"rgba(92,225,230,0.9)"},d.id)),l?e.jsxs(e.Fragment,{children:[e.jsx("circle",{cx:l.x,cy:l.y,r:3,fill:"rgba(255,208,88,0.95)"}),e.jsx("circle",{cx:l.x,cy:l.y,r:6,fill:"none",stroke:"rgba(255,208,88,0.48)",strokeWidth:"1",strokeDasharray:"2 2"})]}):null]})})]})}function VC({open:t,onOpenChange:s,segment:a,detail:i,loading:r,onEdit:n,onDefinePlace:l}){var h;const o=(i==null?void 0:i.segment)??a,d=(i==null?void 0:i.stayDetail)??null,m=(i==null?void 0:i.tripDetail)??null;return e.jsx(Yt,{open:t,onOpenChange:s,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs(es,{className:"fixed left-1/2 top-[6vh] z-50 max-h-[88vh] w-[min(60rem,calc(100vw-1.25rem))] -translate-x-1/2 overflow-y-auto rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ts,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:o?`${ti(o)} details`:"Movement details"}),e.jsx(rs,{className:"mt-2 text-sm leading-6 text-white/62",children:"Inspect the canonical box, the raw movement evidence behind it, and the exact coordinates Forge used to assemble this stay or trip."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o?e.jsxs(W,{onClick:n,variant:"ghost",className:"rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/78 hover:bg-white/[0.08]",disabled:!o.editable||o.kind==="missing",children:[e.jsx(da,{className:"size-4"}),"Edit"]}):null,e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white",children:e.jsx(Es,{className:"size-4 rotate-45"})})})]})]}),r?e.jsx("div",{className:"mt-6 rounded-[22px] border border-white/8 bg-white/[0.03] p-5 text-sm text-white/62",children:"Loading the canonical box detail and raw movement evidence…"}):o?e.jsxs("div",{className:"mt-6 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Started"}),e.jsx("div",{className:"mt-2 text-sm text-white",children:ei(o.startedAt)})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Ended"}),e.jsx("div",{className:"mt-2 text-sm text-white",children:ei(o.endedAt)})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Duration"}),e.jsx("div",{className:"mt-2 text-sm text-white",children:rl(o.durationSeconds)})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Raw coverage"}),e.jsxs("div",{className:"mt-2 text-sm text-white",children:[o.rawStayIds.length," stays · ",o.rawTripIds.length," trips · ",o.rawPointCount," points"]})]})]}),d?e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:"rounded-[22px] border border-sky-300/14 bg-sky-300/8 p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-sky-100/66",children:"Location label"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-sky-50/86",children:d.canonicalPlace?`This stay is linked to ${d.canonicalPlace.label}. Search a different saved place or relabel it from the stay center.`:"This stay has no saved place yet. Search known locations first, or create a new place directly from the stay center."}),e.jsx("div",{className:"mt-3",children:e.jsx(W,{onClick:l,variant:"ghost",className:"rounded-full border border-sky-300/24 bg-sky-300/12 px-4 text-sky-50 hover:bg-sky-300/18",children:"Label location"})})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsx(Bp,{title:"Stay positions",points:d.positions,averagePoint:d.averagePosition}),e.jsxs(ce,{className:"rounded-[28px] border border-white/10 bg-white/[0.03] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Stay metrics"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"text-sm text-white/78",children:["Canonical place: ",((h=d.canonicalPlace)==null?void 0:h.label)??"Not linked yet"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Average position: ",d.averagePosition?Gl(d.averagePosition.latitude,d.averagePosition.longitude):"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Radius: ",d.radiusMeters!=null?Ur(d.radiusMeters):"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Samples: ",d.sampleCount]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/10 p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Exact positions"}),e.jsx("div",{className:"mt-3 grid gap-2",children:d.positions.map((u,x)=>e.jsxs("div",{className:"text-sm text-white/74",children:[u.label??`Position ${x+1}`,": ",Gl(u.latitude,u.longitude)]},`${u.recordedAt??"stay"}-${x}`))})]})]})]})]})]}):null,m?e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsx(Bp,{title:"Travel map",points:m.positions}),e.jsxs(ce,{className:"rounded-[28px] border border-white/10 bg-white/[0.03] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Trip metrics"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"text-sm text-white/78",children:["Start position: ",m.startPosition?Gl(m.startPosition.latitude,m.startPosition.longitude):"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["End position: ",m.endPosition?Gl(m.endPosition.latitude,m.endPosition.longitude):"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Distance: ",Ur(m.totalDistanceMeters)]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Moving time: ",zp(m.movingSeconds)]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Idle time: ",zp(m.idleSeconds)]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Average speed: ",m.averageSpeedMps!=null?`${m.averageSpeedMps.toFixed(2)} m/s`:"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Max speed: ",m.maxSpeedMps!=null?`${m.maxSpeedMps.toFixed(2)} m/s`:"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Stops: ",m.stopCount]})]})]})]}):null]}):null]})]})})}function XC({open:t,onOpenChange:s,segment:a,places:i,loading:r,onSelectPlace:n,onCreatePlace:l}){const o=a?xu(a):null,[d,m]=c.useState("");c.useEffect(()=>{if(!t){m("");return}m(Wi(a)??"")},[t,a]);const h=c.useMemo(()=>{if(!o)return[];const p=Xa(d);return[...i].filter(f=>p.length===0?!0:TC(f).includes(p)).sort((f,b)=>{const A=Xa(f.label),C=Xa(b.label),T=p.length>0&&A.startsWith(p),w=p.length>0&&C.startsWith(p);if(T!==w)return T?-1:1;const S=vo(o.latitude,o.longitude,f.latitude,f.longitude),y=vo(o.latitude,o.longitude,b.latitude,b.longitude);return Math.abs(S-y)>1?S-y:f.label.localeCompare(b.label)}).slice(0,6)},[i,d,o]),u=Xa(d),x=h.some(p=>Xa(p.label)===u),g=Wi(a);return e.jsx(Yt,{open:t,onOpenChange:s,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs(es,{className:"fixed left-1/2 top-[8vh] z-50 max-h-[84vh] w-[min(38rem,calc(100vw-1.25rem))] -translate-x-1/2 overflow-y-auto rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ts,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:"Label stay location"}),e.jsx(rs,{className:"mt-2 text-sm leading-6 text-white/62",children:"Search saved locations by name first. If this stay is new, create a location from the stay center with latitude and longitude already filled in."})]}),e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close location label dialog",children:e.jsx(Tt,{className:"size-4"})})})]}),o?e.jsxs("div",{className:"mt-5 rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{tone:"signal",children:"Stay center"}),g?e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:g}):null]}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/10 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Latitude"}),e.jsx("div",{className:"mt-1 text-sm text-white/82",children:o.latitude.toFixed(6)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/10 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Longitude"}),e.jsx("div",{className:"mt-1 text-sm text-white/82",children:o.longitude.toFixed(6)})]})]})]}):e.jsx("div",{className:"mt-5 rounded-[22px] border border-amber-300/14 bg-amber-300/8 p-4 text-sm text-amber-50/86",children:"Forge can only label stays that already have a recorded stay center."}),e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsx(ye,{value:d,onChange:p=>m(p.target.value),placeholder:"Type a location name or create a new one"}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Known places"}),r?e.jsx("div",{className:"mt-3 text-sm text-white/58",children:"Loading saved places…"}):h.length>0?e.jsx("div",{className:"mt-3 grid gap-2",children:h.map(p=>{const f=o==null?null:vo(o.latitude,o.longitude,p.latitude,p.longitude);return e.jsxs("button",{type:"button",onClick:()=>void n(p).then(b=>{b&&s(!1)}),className:"rounded-[18px] border border-white/8 bg-black/10 px-4 py-3 text-left transition hover:border-[var(--primary)]/40 hover:bg-white/[0.05]",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-sm text-white",children:p.label}),f!=null?e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[Ur(f)," away"]}):null]}),p.aliases.length>0||p.categoryTags.length>0?e.jsx("div",{className:"mt-1 text-xs text-white/52",children:[...p.aliases,...p.categoryTags].join(" · ")}):null]},p.id)})}):e.jsx("div",{className:"mt-3 text-sm text-white/58",children:"No saved place matches this stay yet."})]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-2",children:[e.jsx(W,{variant:"ghost",onClick:()=>s(!1),className:"border border-white/10 bg-white/[0.04]",children:"Cancel"}),e.jsx(W,{onClick:()=>{!a||!o||l(a,x?"":d.trim())},disabled:!a||!o,children:u.length>0&&!x?`Create "${d.trim()}"`:"Create new location"})]})]})]})})}function YC({open:t,segment:s,draft:a,creating:i,saving:r,preflight:n,preflightLoading:l,onDraftChange:o,onFitMissing:d,onSave:m,onOpenChange:h}){return e.jsx(Yt,{open:t,onOpenChange:h,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs(es,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(34rem,calc(100vw-1.25rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ts,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:i?"Create movement box":"Edit movement box"}),e.jsx(rs,{className:"mt-2 text-sm leading-6 text-white/62",children:a?i?"Create a canonical user-defined stay, move, or missing-data box without mutating raw phone measurements.":`Adjust this user-defined ${a.kind} box. Automatic boxes stay immutable and can only be invalidated.`:"No segment selected."})]}),e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/72 transition hover:bg-white/[0.08]",children:e.jsx(Es,{className:"size-4 rotate-45"})})})]}),a?e.jsxs("div",{className:"mt-5 grid gap-4",children:[e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Kind",e.jsx("div",{className:"grid grid-cols-3 gap-2",children:[["stay","Stay"],["trip","Move"],["missing","Missing"]].map(([u,x])=>e.jsx(W,{type:"button",variant:"ghost",className:te("border border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]",a.kind===u?"ring-1 ring-[rgba(126,229,255,0.42)]":""),onClick:()=>o({...a,kind:u}),children:x},u))})]}),e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Label",e.jsx(ye,{value:a.label,onChange:u=>o({...a,label:u.target.value})})]}),a.kind!=="trip"?e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Place",e.jsx(ye,{value:a.placeLabel,onChange:u=>o({...a,placeLabel:u.target.value}),placeholder:"Home, Office, Riverside path..."})]}):null,e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Tags",e.jsx(ye,{value:a.tagsInput,onChange:u=>o({...a,tagsInput:u.target.value}),placeholder:"movement, social, errand"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Started",e.jsx(ye,{type:"datetime-local",value:a.startedAtInput,onChange:u=>o({...a,startedAtInput:u.target.value})})]}),e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Ended",e.jsx(ye,{type:"datetime-local",value:a.endedAtInput,onChange:u=>o({...a,endedAtInput:u.target.value})})]})]}),e.jsxs(ce,{className:"grid gap-3 border-white/10 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Overlap guidance"}),e.jsx(W,{type:"button",variant:"ghost",className:"border border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]",onClick:d,disabled:!(n!=null&&n.nearestMissingStartedAt)||!(n!=null&&n.nearestMissingEndedAt),children:"Fit Missing Time"})]}),e.jsx("div",{className:"text-sm leading-6 text-white/62",children:l?"Checking visible overlaps and missing windows…":n!=null&&n.overlapsAnything?`This box overlaps ${n.affectedAutomaticBoxIds.length} automatic and ${n.affectedUserBoxIds.length} manual boxes. Saving will fully override ${n.fullyOverriddenUserBoxIds.length} manual boxes and trim ${n.trimmedUserBoxIds.length}.`:"No overlap in the currently visible timeline window."}),e.jsxs("div",{className:"grid gap-1 text-xs text-white/50",children:[e.jsxs("div",{children:["Visible range:"," ",n!=null&&n.visibleRangeStart&&(n!=null&&n.visibleRangeEnd)?`${ei(n.visibleRangeStart)} -> ${ei(n.visibleRangeEnd)}`:"Unavailable"]}),e.jsxs("div",{children:["Suggested missing slot:"," ",n!=null&&n.nearestMissingStartedAt&&(n!=null&&n.nearestMissingEndedAt)?`${ei(n.nearestMissingStartedAt)} -> ${ei(n.nearestMissingEndedAt)}`:"No missing interval in view"]})]})]})]}):null,e.jsxs("div",{className:"mt-6 flex items-center justify-end gap-3",children:[e.jsx(Qt,{asChild:!0,children:e.jsx(W,{type:"button",variant:"ghost",className:"border border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]",children:"Cancel"})}),e.jsxs(W,{onClick:m,disabled:!a||r,children:[e.jsx(oi,{className:"size-4"}),r?"Saving…":i?"Create box":"Save changes"]})]})]})]})})}function Up({side:t,vertical:s,emphasized:a=!1}){return e.jsx("div",{className:te("absolute z-10 h-7 w-8 rounded-[12px] border bg-[linear-gradient(180deg,rgba(10,16,28,0.94),rgba(7,12,24,0.88))] shadow-[0_12px_30px_rgba(0,0,0,0.22)] backdrop-blur-sm",a?"border-[rgba(152,208,255,0.34)]":"border-white/10",t==="left"?"left-[8%]":t==="right"?"right-[8%]":"left-1/2 -translate-x-1/2",s==="top"?"top-0":"bottom-0")})}function JC({layout:t,selected:s,onToggle:a,onEdit:i,onOpenDetail:r,onDefinePlace:n}){var p,f,b,A;const{segment:l}=t,d=l.laneSide==="right"?"left":"right",m=s?d==="right"?-176:176:0,h=qm(l),u=t.displayHeight,x=l.kind==="stay"?h?"bg-[linear-gradient(180deg,rgba(39,127,173,0.28),rgba(16,51,79,0.22))] border-[rgba(138,227,255,0.28)]":"bg-[linear-gradient(180deg,rgba(98,130,238,0.22),rgba(18,34,79,0.22))] border-[rgba(152,208,255,0.24)]":"",g=l.kind==="trip"?{start:Hi(l,"start",{includeCoordinates:!1,useHistoryAnchorFallback:!0}),end:Hi(l,"end",{includeCoordinates:!1})}:null;return e.jsxs("div",{className:"absolute left-0 w-full px-6",style:{top:`${t.boxTop}px`,height:`${u}px`},children:[e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-[linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0.08),rgba(255,255,255,0.02))]"}),e.jsxs("div",{className:"relative h-full",children:[l.kind==="trip"?e.jsxs(Ts.div,{layout:!0,animate:{x:m},transition:{type:"spring",stiffness:240,damping:30},className:"absolute inset-x-0 top-0 h-full z-10",children:[g&&s?e.jsxs(e.Fragment,{children:[e.jsx(Up,{side:"center",vertical:"top",emphasized:!0}),e.jsx(Up,{side:"center",vertical:"bottom",emphasized:!0})]}):null,e.jsx(HC,{fromSide:"center",toSide:"center",height:u,emphasized:s}),e.jsxs("button",{type:"button",onClick:a,className:te("group absolute top-1/2 max-w-[min(9rem,calc(100vw-9rem))] -translate-y-1/2 rounded-[18px] border border-white/8 bg-[linear-gradient(180deg,rgba(9,14,24,0.58),rgba(8,12,22,0.42))] px-3 py-2 text-left shadow-[0_12px_24px_rgba(0,0,0,0.14)] backdrop-blur-sm transition hover:border-white/14","left-1/2 -translate-x-1/2",s?"ring-1 ring-[rgba(126,229,255,0.38)]":""),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.18em] text-white/34",children:"Move"}),e.jsx("div",{className:"text-[11px] tracking-[0.18em] text-white/44",children:rl(l.durationSeconds)})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Ur(((p=l.trip)==null?void 0:p.distanceMeters)??0)}),(((f=l.trip)==null?void 0:f.stops.length)??0)>0?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[(b=l.trip)==null?void 0:b.stops.length," stop",((A=l.trip)==null?void 0:A.stops.length)===1?"":"s"]}):null]}),e.jsxs("div",{className:"mt-2 font-label text-[9px] uppercase tracking-[0.22em] text-white/28",children:[Ws(l.startedAt)," → ",Ws(l.endedAt)]})]})]}):e.jsx(Ts.div,{layout:!0,animate:{x:m},transition:{type:"spring",stiffness:260,damping:28},className:"absolute top-0 left-1/2 z-10 w-[min(22rem,calc(100vw-5rem))] -translate-x-1/2",children:e.jsxs("button",{type:"button",onClick:a,className:te("group relative w-full overflow-hidden rounded-[30px] border text-left shadow-[0_26px_68px_rgba(3,8,20,0.42)] transition",x,s?"ring-1 ring-[rgba(126,229,255,0.42)]":"hover:border-white/22"),style:{minHeight:`${u}px`},children:[e.jsx(bu,{position:"top"}),e.jsx(bu,{position:"bottom"}),e.jsxs("div",{className:"relative z-10 flex h-full flex-col justify-between p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(I,{tone:"signal",className:"bg-white/10 text-white/82",children:h?"Sleep":"Stay"}),e.jsx("div",{className:"text-xs tracking-[0.18em] text-white/46",children:rl(l.durationSeconds)})]}),e.jsxs("div",{className:"mt-5 min-w-0",children:[e.jsx("div",{className:"truncate font-display text-[1.12rem] tracking-[-0.04em] text-white",children:ti(l)}),l.kind==="stay"&&Wi(l)&&!h?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(I,{className:"max-w-full truncate bg-white/[0.08] text-white/76",children:Wi(l)})}):h?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(I,{className:"max-w-full truncate bg-cyan-400/12 text-cyan-50",children:l.subtitle})}):null]}),e.jsx("div",{className:"mt-auto pt-8",children:e.jsxs("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-white/34",children:[Ws(l.startedAt)," → ",Ws(l.endedAt)]})})]})]})}),s?e.jsx(Ts.div,{layout:!0,initial:{opacity:0,x:d==="right"?28:-28},animate:{opacity:1,x:0},exit:{opacity:0,x:d==="right"?28:-28},className:te("absolute top-0 w-[min(22rem,calc(100vw-4rem))]",d==="right"?"right-[3%]":"left-[3%]"),children:e.jsx(QC,{segment:l,onEdit:i,onOpenDetail:r,onDefinePlace:n})}):null]})]})}function ZC({userIds:t=[]}){var He,lt,Nt;const s=ct(),a=c.useRef(null),i=c.useRef(null),r=c.useRef(!1),n=c.useRef(!1),l=c.useRef(null),[o,d]=c.useState(null),[m,h]=c.useState({}),[u,x]=c.useState(null),[g,p]=c.useState(null),[f,b]=c.useState(null),[A,C]=c.useState(null),[T,w]=c.useState(!1),[S,y]=c.useState(!1),[N,P]=c.useState(null),[v,H]=c.useState(null),[j,R]=c.useState(!1),[Q,X]=c.useState(!1),[Y,z]=c.useState(!1),[K,$]=c.useState(""),[D,J]=c.useState([]),[q,_]=c.useState(0),[B,G]=c.useState(0),ae=()=>{const me=a.current;me&&(_(me.scrollTop),G(me.clientHeight))},ke=Bc({queryKey:["forge-movement-life-timeline",...t],initialPageParam:null,queryFn:({pageParam:me})=>xh({before:me??void 0,limit:$p,userIds:t}).then(Pe=>Pe.movement),getNextPageParam:me=>me.nextCursor??void 0,retry:!1,refetchOnWindowFocus:!1}),Ae=Bc({queryKey:["forge-movement-life-timeline-data",...t],initialPageParam:null,queryFn:({pageParam:me})=>xh({before:me??void 0,includeInvalid:!0,limit:$p,userIds:t}).then(Pe=>Pe.movement),getNextPageParam:me=>me.nextCursor??void 0,retry:!1,refetchOnWindowFocus:!1}),ie=c.useMemo(()=>{var me;return((me=ke.data)==null?void 0:me.pages.flatMap(Pe=>Pe.segments))??[]},[ke.data]),Ie=c.useMemo(()=>{var me;return((me=Ae.data)==null?void 0:me.pages.flatMap(Pe=>Pe.segments))??[]},[Ae.data]),Ne=c.useMemo(()=>{var me;return((me=ke.data)==null?void 0:me.pages.reduce((Pe,k)=>Math.max(Pe,k.invalidSegmentCount??0),0))??0},[ke.data]),M=c.useMemo(()=>[...ie].reverse(),[ie]),E=c.useMemo(()=>[...Ie].reverse(),[Ie]),O=c.useMemo(()=>{var Pe;const me=new Map;for(const k of((Pe=ke.data)==null?void 0:Pe.pages)??[])for(const se of k.sleepOverlays??[])me.set(se.id,se);return[...me.values()].sort((k,se)=>new Date(k.startedAt).getTime()-new Date(se.startedAt).getTime())},[ke.data]),xe=c.useMemo(()=>NC(M,O),[M,O]),V=c.useMemo(()=>Y?xe:M,[M,xe,Y]),Se=c.useMemo(()=>xe.filter(me=>me.syncSource==="sleep overlay"),[xe]),Ee=((He=Se.at(-1))==null?void 0:He.id)??null,Ce=c.useMemo(()=>V.find(me=>me.id===f)??null,[f,V]),qe=Fe({queryKey:["forge-movement-box-detail",(Ce==null?void 0:Ce.boxId)??null,...t],queryFn:async()=>Ce!=null&&Ce.boxId?(await A1(Ce.boxId,t)).movement:null,enabled:!!(Ce!=null&&Ce.boxId)}),oe=c.useMemo(()=>M.find(me=>me.id===A)??null,[A,M]),L=Fe({queryKey:["forge-movement-places",...t],queryFn:async()=>(await hf(t)).places,retry:!1,refetchOnWindowFocus:!1}),U=c.useMemo(()=>UC({segments:V,viewportHeight:B}),[V,B]),ge=c.useMemo(()=>new Map(U.items.map(me=>[me.segment.id,me])),[U.items]),Te=(me,Pe="smooth")=>{const k=a.current,se=ge.get(me);if(!k||!se)return;const _e=Math.max(0,se.boxTop-k.clientHeight/2+se.displayHeight/2);if(typeof k.scrollTo=="function"){k.scrollTo({top:_e,behavior:Pe});return}k.scrollTop=_e};c.useEffect(()=>{j&&(!Ae.hasNextPage||Ae.isFetchingNextPage||Ae.fetchNextPage())},[j,Ae.fetchNextPage,Ae.hasNextPage,Ae.isFetchingNextPage]),c.useEffect(()=>{const me=V.at(-1);!n.current&&me&&(n.current=!0,d(me.id))},[V]),c.useEffect(()=>{if(!r.current&&V.length>0){r.current=!0,requestAnimationFrame(()=>{var Pe;const me=(Pe=V[V.length-1])==null?void 0:Pe.id;me&&Te(me,"auto"),requestAnimationFrame(()=>{ae()})});return}if(l.current&&V.length>l.current.count&&a.current){const me=l.current;l.current=null,requestAnimationFrame(()=>{const Pe=a.current;if(!Pe)return;const k=U.totalHeight-me.size;Pe.scrollTop+=k,ae()})}},[V.length,U.totalHeight,ge]),c.useEffect(()=>{if(!a.current)return;const Pe=()=>{ae()};return Pe(),window.addEventListener("resize",Pe),()=>window.removeEventListener("resize",Pe)},[]),c.useEffect(()=>{if(!o)return;const me=M.find(Pe=>Pe.id===o);me&&h(Pe=>Pe[o]?Pe:{...Pe,[o]:gu(me)})},[M,o]),c.useEffect(()=>{var me;o&&(V.some(Pe=>Pe.id===o)||d(((me=V.at(-1))==null?void 0:me.id)??null))},[V,o]),c.useEffect(()=>{if(!Y||!Ee)return;const me=V.findIndex(Pe=>Pe.id===Ee);me<0||(d(Ee),requestAnimationFrame(()=>{var k;const Pe=(k=V[me])==null?void 0:k.id;Pe&&Te(Pe)}))},[V,Ee,Y,ge]);const ve=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-movement-life-timeline"]}),s.invalidateQueries({queryKey:["forge-movement-life-timeline-data"]}),s.invalidateQueries({queryKey:["forge-movement-box-detail"]}),s.invalidateQueries({queryKey:["forge-movement-day"]}),s.invalidateQueries({queryKey:["forge-movement-month"]}),s.invalidateQueries({queryKey:["forge-movement-all-time"]}),s.invalidateQueries({queryKey:["forge-movement-places"]}),s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]})])},Le=Re({mutationFn:async me=>{const{segment:Pe,draft:k,creating:se}=me,_e=fu(k,Pe);if(se){await gh(_e,t);return}if(!Pe)throw new Error("No movement box selected.");if(Pe.sourceKind!=="user_defined")throw new Error("Automatic movement boxes are immutable. Invalidate them into missing data or create a user-defined override instead.");await fh(Pe.boxId,{..._e,metadata:{updatedFrom:"movement-life-timeline"}},t)},onSuccess:ve}),Qe=async(me,Pe)=>{if(me.kind!=="stay")throw new Error("Only stays can be linked to a saved place.");const k=DC(me,Pe.label);if(me.sourceKind==="user_defined"){await fh(me.boxId,{...k,metadata:{updatedFrom:"movement-life-timeline-place-label"}},t);return}await gh({...k,metadata:{createdFrom:"movement-life-timeline-place-label"}},t)},st=async(me,Pe)=>{if(me.rawStayIds.length===0)throw new Error("This stay has no raw stay ids to relabel.");await Promise.all(me.rawStayIds.map(k=>T1(k,{placeExternalUid:Pe.externalUid,placeLabel:Pe.label})))},F=(me,Pe)=>{const k=xu(me);if(!k)return!0;const se=vo(k.latitude,k.longitude,Pe.latitude,Pe.longitude);return se<=100||typeof window>"u"||typeof window.confirm!="function"?!0:window.confirm(`"${Pe.label}" is ${Ur(se)} away from this stay's recorded center. Link it anyway?`)},he=Re({mutationFn:async me=>{const{segment:Pe,...k}=me,se=await pf(k,t);return Pe&&ka(Pe)&&await st(Pe,se.place),se},onSuccess:ve}),we=Re({mutationFn:async me=>{const{segment:Pe,place:k}=me;if(!F(Pe,k))return{assigned:!1};if(ka(Pe))return await st(Pe,k),{assigned:!0};if(Pe.kind!=="stay")throw new Error("Only stays can be linked to a saved place.");return await Qe(Pe,k),{assigned:!0}},onSuccess:async me=>{me.assigned&&await ve()}}),Z=Re({mutationFn:async me=>{if(me.sourceKind==="user_defined"){await E1(me.boxId,t);return}await L1(me.boxId,{title:"User invalidated automatic movement",subtitle:`Overrides ${ti(me)} with missing data.`},t)},onSuccess:async(me,Pe)=>{d(k=>k===Pe.id?null:k),x(k=>k===Pe.id?null:k),s.setQueryData(["forge-movement-life-timeline",...t],k=>qp(k,Pe.id)),s.setQueryData(["forge-movement-life-timeline-data",...t],k=>qp(k,Pe.id)),await Promise.all([s.invalidateQueries({queryKey:["forge-movement-life-timeline"]}),s.invalidateQueries({queryKey:["forge-movement-life-timeline-data"]}),s.invalidateQueries({queryKey:["forge-movement-day"]}),s.invalidateQueries({queryKey:["forge-movement-month"]}),s.invalidateQueries({queryKey:["forge-movement-all-time"]}),s.invalidateQueries({queryKey:["forge-movement-selection"]}),s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]})])}}),De=c.useMemo(()=>_C(E),[E]),ee=c.useMemo(()=>{const me=Xa(K);return[...E].sort((Pe,k)=>new Date(k.endedAt).getTime()-new Date(Pe.endedAt).getTime()).filter(Pe=>(me.length===0||FC(Pe).includes(me))&&RC(Pe,D))},[E,K,D]),ze=c.useMemo(()=>E.length===0?"No movement records loaded yet.":ee.length===E.length&&K.trim().length===0&&D.length===0?`${E.length} loaded movement records visible`:`${ee.length} of ${E.length} loaded records visible`,[E.length,ee.length,K,D.length]),et=nd({count:ee.length,getScrollElement:()=>i.current,estimateSize:()=>136,overscan:8}),Ve=u?M.find(me=>me.id===u)??null:null,re=Ve?m[Ve.id]??gu(Ve):null,ne=g!==null,be=g??re,je=((lt=M[0])==null?void 0:lt.startedAt)??null,pe=((Nt=M[M.length-1])==null?void 0:Nt.endedAt)??null,$e=Fe({queryKey:["forge-movement-user-box-preflight",(Ve==null?void 0:Ve.boxId)??"create",(be==null?void 0:be.kind)??null,(be==null?void 0:be.startedAtInput)??null,(be==null?void 0:be.endedAtInput)??null,je,pe,...t],enabled:be!==null&&Wo(be.startedAtInput)!==null&&Wo(be.endedAtInput)!==null,queryFn:async()=>{if(!be)return null;const me=fu(be,Ve);return(await M1({...me,excludeBoxId:(Ve==null?void 0:Ve.sourceKind)==="user_defined"?Ve.boxId:null,rangeStart:je,rangeEnd:pe},t)).preflight}}),Xe=me=>{ka(me)&&(C(me.id),w(!0))},Ue=(me,Pe)=>{const k=xu(me);k&&(w(!1),C(me.id),P({...k,label:Pe.trim()||k.label}),H(me.id),y(!0))},le=()=>{const me=a.current;me&&(_(me.scrollTop),G(me.clientHeight),!(!ke.hasNextPage||ke.isFetchingNextPage)&&me.scrollTop<=960&&(l.current={count:V.length,size:U.totalHeight},ke.fetchNextPage()))};if(ke.isPending)return e.jsx(ls,{eyebrow:"Movement",title:"Loading life timeline",description:"Reconstructing the longer road of stays, moves, and places.",columns:1,blocks:6});if(ke.isError)return e.jsx(it,{eyebrow:"Movement",error:ke.error,onRetry:()=>void ke.refetch()});const Me=U.totalHeight;return e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(ce,{className:"overflow-hidden rounded-[34px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(88,182,255,0.08),transparent_28%),linear-gradient(180deg,rgba(4,8,17,0.99),rgba(5,9,18,0.97))] p-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3 px-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.22em] text-white/34",children:"Movement"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",onClick:()=>p(lc("stay",M.at(-1)??null)),children:[e.jsx(da,{className:"size-3.5"}),"Add box"]}),e.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",onClick:()=>z(me=>{const Pe=!me;return Pe&&Ee&&d(Ee),Pe}),children:[e.jsx(Wu,{className:"size-3.5"}),Y?"Hide sleep":"Show sleep"]}),e.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",onClick:()=>R(!0),children:[e.jsx(_r,{className:"size-3.5"}),"View data"]}),Ne>0?e.jsxs(I,{className:"bg-amber-500/10 text-amber-100",children:[Ne," invalid hidden"]}):null,e.jsxs(I,{className:"bg-white/[0.06] text-white/68",children:[V.length," visible"]})]})]}),Y&&Se.length===0?e.jsx("p",{className:"mb-3 px-1 text-sm text-amber-100/80",children:"No sleep session overlaps the currently loaded timeline range yet. Scroll further back to load older history."}):null,e.jsxs("div",{ref:a,onScroll:le,className:"relative h-[82vh] overflow-auto rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(4,7,15,0.98),rgba(6,10,18,0.96))]",children:[e.jsx(WC,{layout:U,scrollTop:q,viewportHeight:B}),e.jsxs("div",{className:"relative",style:{height:`${Me}px`},children:[U.historyHeaderHeight>0?e.jsx("div",{className:"absolute inset-x-0 top-0",style:{height:`${U.historyHeaderHeight}px`},children:e.jsx(GC,{segment:V[0]??null})}):null,U.items.map(me=>{const Pe=me.segment;return e.jsx(JC,{layout:me,selected:o===Pe.id,onToggle:()=>d(k=>k===Pe.id?null:Pe.id),onEdit:()=>{Pe.editable&&x(Pe.id)},onOpenDetail:()=>b(Pe.id),onDefinePlace:()=>Xe(Pe)},Pe.id)})]})]})]}),e.jsx(YC,{open:Ve!==null||g!==null,segment:Ve,draft:be,creating:ne,saving:Le.isPending,preflight:$e.data??null,preflightLoading:$e.isFetching,onDraftChange:me=>{if(ne){p(me);return}Ve&&h(Pe=>({...Pe,[Ve.id]:me}))},onFitMissing:()=>{const me=$e.data;if(!(me!=null&&me.nearestMissingStartedAt)||!me.nearestMissingEndedAt)return;const Pe={...be??lc("stay",Ve),startedAtInput:Br(me.nearestMissingStartedAt),endedAtInput:Br(me.nearestMissingEndedAt)};if(ne){p(Pe);return}Ve&&h(k=>({...k,[Ve.id]:Pe}))},onSave:()=>{be&&Le.mutateAsync({segment:Ve,draft:be,creating:ne},{onSuccess:()=>{x(null),p(null),Q&&(X(!1),R(!0))}})},onOpenChange:me=>{me||(x(null),p(null),Q&&(X(!1),R(!0)))}}),e.jsx(VC,{open:Ce!==null,onOpenChange:me=>{me||b(null)},segment:Ce,detail:qe.data??null,loading:qe.isFetching,onEdit:()=>{!Ce||!Ce.editable||(x(Ce.id),b(null))},onDefinePlace:()=>{Ce&&Xe(Ce)}}),e.jsx(XC,{open:T,onOpenChange:me=>{w(me),me||C(null)},segment:oe,places:L.data??[],loading:L.isFetching,onSelectPlace:async me=>oe?(await we.mutateAsync({segment:oe,place:me})).assigned:!1,onCreatePlace:(me,Pe)=>{Ue(me,Pe)}}),e.jsx(Mw,{open:S,onOpenChange:me=>{y(me),me||(P(null),H(null))},place:null,seed:N,onSave:async me=>{await he.mutateAsync({...me,segment:M.find(Pe=>Pe.id===v)??null})}}),e.jsx(pa,{open:j,onOpenChange:me=>{R(me),me||Q||($(""),J([]))},eyebrow:"Movement data",title:"View data",description:"",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(mi,{title:"",description:"",query:K,onQueryChange:$,options:De,selectedOptionIds:D,onSelectedOptionIdsChange:J,resultSummary:ze,placeholder:"Search movement labels, places, times, tags, or add time and kind filters",emptyStateMessage:"Keep typing or pick filters to narrow the movement history."}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Canonical boxes"}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/56",children:"This list shows the canonical movement boxes projected by Forge. Automatic boxes are derived from immutable raw phone measurements. User-defined boxes override the projection without mutating raw movement data."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/70",onClick:()=>{X(!0),R(!1),p(lc("stay",ee.at(-1)??null))},children:"Add box"}),e.jsx(I,{tone:"meta",children:ze}),Ne>0?e.jsxs(I,{className:"bg-amber-500/10 text-amber-100",children:[Ne," invalid hidden included"]}):null,Ae.hasNextPage?e.jsx(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/70",pending:Ae.isFetchingNextPage,pendingLabel:"Loading…",onClick:()=>void Ae.fetchNextPage(),children:"Load older"}):null]})]}),e.jsx("div",{ref:i,className:"h-[36rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:ee.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No movement record matches the current search. Clear filters or load older timeline history."}):e.jsx("div",{className:"relative w-full",style:{height:`${et.getTotalSize()}px`},children:et.getVirtualItems().map(me=>{var k;const Pe=ee[me.index];return e.jsx("div",{ref:et.measureElement,"data-index":me.index,className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${me.start}px)`},children:e.jsxs("div",{className:"flex items-start gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[e.jsx("button",{type:"button",className:"min-w-0 flex-1 text-left transition hover:opacity-100",onClick:()=>{Pe.editable&&(X(!0),R(!1),x(Pe.id))},children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[Pe.kind==="stay"?e.jsx(qu,{className:"size-3.5 shrink-0 text-[var(--primary)]"}):Pe.kind==="missing"?e.jsx(_r,{className:"size-3.5 shrink-0 text-slate-300/80"}):e.jsx(Hn,{className:"size-3.5 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-sm font-medium",children:ti(Pe)})]}),e.jsxs("div",{className:"mt-1 text-xs text-white/56",children:[Go(Pe.startedAt)," →"," ",Go(Pe.endedAt)]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-1.5",children:[e.jsx(I,{tone:Pe.kind==="trip"?"signal":"meta",children:Pe.kind==="trip"?"Move":Pe.kind==="missing"?"Missing":"Stay"}),e.jsx(I,{className:Pe.sourceKind==="user_defined"?"bg-fuchsia-400/12 text-fuchsia-100":"bg-white/[0.06] text-white/70",children:Pe.sourceKind==="user_defined"?Pe.origin==="user_invalidated"?"User invalidated":"User-defined":"Automatic"}),e.jsx(I,{tone:"meta",children:rl(Pe.durationSeconds)}),Pe.origin==="continued_stay"?e.jsx(I,{className:"bg-sky-400/10 text-sky-100",children:"Continued stay"}):null,Pe.origin==="repaired_gap"?e.jsx(I,{className:"bg-amber-400/10 text-amber-100",children:"Repaired"}):null,Pe.kind==="missing"?e.jsx(I,{className:"bg-slate-300/10 text-slate-100",children:"Missing"}):null,Pe.isInvalid?e.jsx(I,{className:"bg-amber-500/10 text-amber-100",children:"Invalid"}):null,Pe.placeLabel?e.jsx(I,{tone:"default",children:Pe.placeLabel}):null,Pe.overrideCount>0?e.jsxs(I,{className:"bg-amber-400/10 text-amber-100",children:["Overrides ",Pe.overrideCount]}):null,e.jsxs(I,{className:"bg-white/[0.06] text-white/66",children:["Raw stays ",Pe.rawStayIds.length]}),e.jsxs(I,{className:"bg-white/[0.06] text-white/66",children:["Raw trips ",Pe.rawTripIds.length]}),e.jsxs(I,{className:"bg-white/[0.06] text-white/66",children:["Raw points ",Pe.rawPointCount]}),Pe.hasLegacyCorrections?e.jsx(I,{className:"bg-amber-400/10 text-amber-100",children:"Legacy corrections"}):null]})]})}),e.jsx(W,{type:"button",variant:"ghost",size:"sm",className:te("h-8 shrink-0 rounded-full border px-2.5",Pe.sourceKind==="user_defined"?"border-rose-400/22 bg-rose-500/10 text-rose-100 hover:bg-rose-500/18":"border-amber-400/22 bg-amber-500/10 text-amber-100 hover:bg-amber-500/18"),pending:Z.isPending&&((k=Z.variables)==null?void 0:k.id)===Pe.id,pendingLabel:"",onClick:()=>{window.confirm(Pe.sourceKind==="user_defined"?`Delete ${ti(Pe)} and remove this user-defined box from every synced surface?`:`Invalidate ${ti(Pe)} into missing data and hide the automatic box everywhere?`)&&Z.mutateAsync(Pe)},children:e.jsx(Rt,{className:"size-3.5"})})]})},Pe.id)})})})]})]})})]})}function e8(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}).format(new Date(t))}function t8(t,s){const a=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${a.format(new Date(t))} - ${a.format(new Date(s))}`}function Cs(t){return t>=3600?`${(t/3600).toFixed(1)}h`:`${Math.round(t/60)}m`}function Ni(t){return t>=1e3?`${(t/1e3).toFixed(1)} km`:`${Math.round(t)} m`}function s8(t,s){return t==="distanceMeters"?Ni(s):t==="caloriesKcal"?`${Math.round(s)} kcal`:Cs(s)}function Dw(t){return t.trim().toLowerCase()}function Cd(t){const s=new Date(t).getHours();return s<6?"night":s<12?"morning":s<18?"afternoon":"evening"}function Bm(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function a8(t){const s=new Date(t);return Number.isNaN(s.getTime())?"":new Date(s.getTime()-s.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function Wp(t){return{recordedAt:a8(t.recordedAt),latitude:String(t.latitude),longitude:String(t.longitude),accuracyMeters:t.accuracyMeters!=null?String(t.accuracyMeters):"",altitudeMeters:t.altitudeMeters!=null?String(t.altitudeMeters):"",speedMps:t.speedMps!=null?String(t.speedMps):"",isStopAnchor:t.isStopAnchor}}function i8(t){return Dw([Bm(t.recordedAt),t.externalUid,t.isStopAnchor?"stop anchor stop":"path trace point",t.accuracyMeters!=null?`${Math.round(t.accuracyMeters)} meters accuracy`:"",Cd(t.recordedAt)].join(" "))}function r8(t){const s=new Map;return s.set("anchor:stop",{id:"anchor:stop",label:"Stop anchors",description:"Only the canonical pause anchors",badge:e.jsx(I,{tone:"meta",children:"Stop anchors"})}),s.set("anchor:path",{id:"anchor:path",label:"Path points",description:"Non-anchor trace points",badge:e.jsx(I,{tone:"meta",children:"Path points"})}),s.set("accuracy:precise",{id:"accuracy:precise",label:"Precise",description:"GPS accuracy below 20m",badge:e.jsx(I,{tone:"meta",children:"Precise"})}),s.set("accuracy:loose",{id:"accuracy:loose",label:"Loose accuracy",description:"GPS accuracy at or above 20m",badge:e.jsx(I,{tone:"meta",children:"Loose accuracy"})}),t.forEach(a=>{const i=Cd(a.recordedAt);s.has(`time:${i}`)||s.set(`time:${i}`,{id:`time:${i}`,label:i,description:"Recorded during this time band",badge:e.jsx(I,{tone:"meta",className:"capitalize",children:i})})}),[...s.values()]}function n8(t,s){return s.every(a=>a==="anchor:stop"?t.isStopAnchor:a==="anchor:path"?!t.isStopAnchor:a==="accuracy:precise"?t.accuracyMeters!=null&&t.accuracyMeters<20:a==="accuracy:loose"?t.accuracyMeters==null||t.accuracyMeters>=20:a.startsWith("time:")?Cd(t.recordedAt)===a.slice(5):!0)}function l8(t){if(t.length===0)return[];const s=Math.min(...t.map(o=>o.latitude)),a=Math.max(...t.map(o=>o.latitude)),i=Math.min(...t.map(o=>o.longitude)),r=Math.max(...t.map(o=>o.longitude)),n=Math.max(a-s,1e-4),l=Math.max(r-i,1e-4);return t.map(o=>({x:12+(o.longitude-i)/l*76,y:12+(1-(o.latitude-s)/n)*76}))}function o8({curve:t,startLabel:s,endLabel:a,stopLabels:i}){const r=t.map((n,l)=>`${l===0?"M":"Q"} ${n.x} ${n.y}`).join(" ");return e.jsxs(ce,{className:"overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(114,204,255,0.18),transparent_44%),linear-gradient(180deg,rgba(6,11,26,0.98),rgba(8,14,28,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Stylized trajectory"}),e.jsx(vt,{content:"This graph is a softened trip trace. It emphasizes rhythm, stops, and endpoints instead of raw GPS jitter."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/64",children:"A softened path that prioritizes rhythm, stops, and landmarks over raw map noise."})]}),e.jsxs(I,{tone:"signal",children:[s," → ",a]})]}),e.jsxs("div",{className:"mt-5 rounded-[26px] border border-white/8 bg-[rgba(255,255,255,0.03)] p-4",children:[e.jsxs("svg",{viewBox:"0 0 100 60",className:"h-48 w-full",children:[e.jsx("defs",{children:e.jsxs("filter",{id:"movementGlow",children:[e.jsx("feGaussianBlur",{stdDeviation:"1.8",result:"blur"}),e.jsxs("feMerge",{children:[e.jsx("feMergeNode",{in:"blur"}),e.jsx("feMergeNode",{in:"SourceGraphic"})]})]})}),e.jsx("path",{d:r,fill:"none",stroke:"rgba(255,255,255,0.86)",strokeWidth:"1.5",strokeDasharray:"2.8 2.8",filter:"url(#movementGlow)"}),t.map((n,l)=>e.jsx("g",{children:e.jsx("circle",{cx:n.x,cy:n.y,r:l===0||l===t.length-1?2.6:1.6,fill:l===0||l===t.length-1?"#ffffff":"rgba(170,229,255,0.96)"})},`${n.x}-${n.y}-${l}`))]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:i.map(n=>e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:n},n))})]})]})}function d8({points:t}){const s=l8(t),a=s.map((i,r)=>`${r===0?"M":"L"} ${i.x} ${i.y}`).join(" ");return e.jsxs(ce,{className:"rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,13,25,0.95),rgba(10,17,30,0.88))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Exact path"}),e.jsx(vt,{content:"This keeps the recent raw location points. Use it when you want the literal recorded trace instead of the cleaned movement graph."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/62",children:"Recent raw points preserved by the companion before long-term simplification."}),e.jsx("div",{className:"mt-5 rounded-[24px] border border-white/8 bg-[rgba(255,255,255,0.03)] p-3",children:e.jsxs("svg",{viewBox:"0 0 100 100",className:"h-52 w-full",children:[e.jsx("rect",{x:"0",y:"0",width:"100",height:"100",rx:"18",fill:"rgba(255,255,255,0.02)"}),e.jsx("path",{d:a,fill:"none",stroke:"rgba(92,225,230,0.95)",strokeWidth:"1.6"}),s.map((i,r)=>e.jsx("circle",{cx:i.x,cy:i.y,r:r===0||r===s.length-1?2:1.1,fill:r===0||r===s.length-1?"#ffffff":"rgba(92,225,230,0.9)"},`${i.x}-${i.y}-${r}`))]})})]})}function c8({point:t,draft:s}){return e.jsxs(ce,{className:"grid gap-4 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(12,18,32,0.98),rgba(8,13,24,0.98))] p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Raw datapoint"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Bm(t.recordedAt)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Raw phone measurements are immutable in product UI. To change the visible movement story, create or edit user-defined boxes in the Life Timeline instead."})]}),e.jsx(I,{tone:t.isStopAnchor?"signal":"meta",children:t.isStopAnchor?"Stop anchor":"Path point"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Recorded at"}),e.jsx(ye,{type:"datetime-local",value:s.recordedAt,disabled:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Speed (m/s)"}),e.jsx(ye,{value:s.speedMps,disabled:!0,placeholder:"Optional"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Latitude"}),e.jsx(ye,{value:s.latitude,disabled:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Longitude"}),e.jsx(ye,{value:s.longitude,disabled:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Accuracy (m)"}),e.jsx(ye,{value:s.accuracyMeters,disabled:!0,placeholder:"Optional"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Altitude (m)"}),e.jsx(ye,{value:s.altitudeMeters,disabled:!0,placeholder:"Optional"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(W,{variant:"ghost",className:te("h-10 rounded-full border px-4",s.isStopAnchor?"border-[var(--primary)] bg-[var(--primary)]/16 text-white":"border-white/10 bg-white/[0.04] text-white/64"),disabled:!0,children:[e.jsx(Hn,{className:"mr-2 size-4"}),s.isStopAnchor?"Stop anchor":"Path point"]}),e.jsxs("div",{className:"text-sm text-white/50",children:["External id: ",e.jsx("span",{className:"text-white/72",children:t.externalUid})]})]}),e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm leading-6 text-white/56",children:"This browser is read-only now. Raw points stay immutable so the web app and iPhone can both project the same repaired canonical boxes from the backend."})]})}function u8(){var oe,L,U,ge,Te;const t=jt(),s=ct(),a=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[i,r]=c.useState("life"),[n,l]=c.useState(new Date().toISOString().slice(0,10)),[o,d]=c.useState(new Date().toISOString().slice(0,7)),[m,h]=c.useState(null),[u,x]=c.useState(!1),[g,p]=c.useState(!1),[f,b]=c.useState(""),[A,C]=c.useState([]),[T,w]=c.useState(null),[S,y]=c.useState(null),[N,P]=c.useState({stayIds:[],tripIds:[]}),[v,H]=c.useState(!1),[j,R]=c.useState(null),[Q,X]=c.useState(""),[Y,z]=c.useState("distanceMeters"),K=c.useRef(null),$=Fe({queryKey:["forge-movement-day",n,...a],queryFn:async()=>(await mf({date:n,userIds:a})).movement}),D=Fe({queryKey:["forge-movement-month",o,...a],queryFn:async()=>(await w1({month:o,userIds:a})).movement}),J=Fe({queryKey:["forge-movement-all-time",...a],queryFn:async()=>(await y1(a)).movement}),q=Fe({queryKey:["forge-life-force",...a],queryFn:async()=>(await Ji(a)).lifeForce}),_=Fe({queryKey:["forge-movement-settings",...a],queryFn:async()=>(await S1(a)).settings}),B=Fe({queryKey:["forge-movement-places",...a],queryFn:async()=>(await hf(a)).places}),G=Fe({queryKey:["forge-movement-trip",m],queryFn:async()=>m?(await P1(m)).movement:null,enabled:!!m}),ae=Fe({queryKey:["forge-movement-selection",n,N.stayIds.join(","),N.tripIds.join(","),...a],queryFn:async()=>(await D1({...N,userIds:a})).movement,enabled:N.stayIds.length>0||N.tripIds.length>0}),ke=Re({mutationFn:async ve=>I1({trackingEnabled:ve},a),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-movement-settings"]}),await s.invalidateQueries({queryKey:["forge-movement-day"]})}}),Ae=Re({mutationFn:async ve=>ve.id?C1(ve.id,ve):pf(ve,a),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-movement-places"]}),await s.invalidateQueries({queryKey:["forge-movement-day"]}),await s.invalidateQueries({queryKey:["forge-movement-all-time"]})}}),ie=c.useMemo(()=>{const ve=B.data??[],Le=Q.trim().toLowerCase();return Le?ve.filter(Qe=>[Qe.label,...Qe.aliases,...Qe.categoryTags].join(" ").toLowerCase().includes(Le)):ve},[Q,B.data]),Ie=c.useMemo(()=>{var ve;return r8(((ve=G.data)==null?void 0:ve.trip.points)??[])},[(oe=G.data)==null?void 0:oe.trip.points]),Ne=c.useMemo(()=>{var Qe;const ve=((Qe=G.data)==null?void 0:Qe.trip.points)??[],Le=Dw(f);return[...ve].sort((st,F)=>new Date(F.recordedAt).getTime()-new Date(st.recordedAt).getTime()).filter(st=>(Le.length===0||i8(st).includes(Le))&&n8(st,A))},[f,A,(L=G.data)==null?void 0:L.trip.points]),M=c.useMemo(()=>{var Le;const ve=((Le=G.data)==null?void 0:Le.trip.points.length)??0;return ve===0?"No raw datapoints on this trip yet.":Ne.length===ve&&f.trim().length===0&&A.length===0?`${ve} datapoints visible`:`${Ne.length} of ${ve} datapoints visible`},[Ne.length,f,A.length,(U=G.data)==null?void 0:U.trip.points.length]),E=nd({count:Ne.length,getScrollElement:()=>K.current,estimateSize:()=>96,overscan:8}),O=Ne.find(ve=>ve.id===T)??((ge=G.data)==null?void 0:ge.trip.points.find(ve=>ve.id===T))??Ne[0]??((Te=G.data)==null?void 0:Te.trip.points[0])??null;if(c.useEffect(()=>{if(g){if(!O){w(null),y(null);return}w(O.id),y(Wp(O))}},[O,g]),c.useEffect(()=>{b(""),C([]),w(null),y(null),p(!1)},[m]),$.isLoading||D.isLoading||J.isLoading||_.isLoading||B.isLoading)return e.jsx(ls,{eyebrow:"Movement",title:"Loading movement workspace",description:"Reconstructing stays, trips, and place intelligence across Forge.",columns:2,blocks:8});if($.isError||D.isError||J.isError||_.isError||B.isError||!$.data||!D.data||!J.data||!_.data)return e.jsx(it,{eyebrow:"Movement",error:$.error??D.error??J.error??_.error??B.error??new Error("Movement data unavailable"),onRetry:()=>{$.refetch(),D.refetch(),J.refetch(),_.refetch(),B.refetch()}});const xe=$.data,V=D.data,Se=J.data,Ee=_.data,Ce=ae.data??xe.selectionAggregate,qe=xe.trips.reduce((ve,Le)=>ve+Dl(Le).totalAp,0);return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{entityKind:"project",title:"Movement",description:"Turn passive place and travel signals into a real Forge domain: day rhythm, travel arcs, known landmarks, linked work, and reflective evidence.",badge:`${xe.summary.tripCount} trips today`,actions:e.jsx("div",{className:"flex flex-wrap gap-2",children:["life","day","month","all_time"].map(ve=>e.jsx(W,{variant:"ghost",className:te("h-9 rounded-full border px-4 text-sm",i===ve?"border-[var(--primary)] bg-[var(--primary)]/16 text-white":"border-white/10 bg-white/[0.04] text-white/64"),onClick:()=>r(ve),children:ve==="all_time"?"All time":ve==="life"?"Life":ve.charAt(0).toUpperCase()+ve.slice(1)},ve))})}),e.jsxs(ce,{className:"grid gap-3 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(12,20,34,0.98),rgba(8,14,25,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:"Movement AP today"}),e.jsx("div",{className:"mt-2 text-3xl font-semibold text-white",children:St(qe)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Trips and transitions now contribute to the same Action Point ledger as work, habits, and notes."})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Typical trip drain"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-[var(--primary)]",children:xe.trips[0]?Kt(Dl(xe.trips[0]).rateApPerHour):"0 AP/h"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Movement uses a MET-like drain under the hood, translated into Forge Action Points."})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force sync"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white",children:q.data?`${Math.round(q.data.spentTodayAp??0)}/${Math.round(q.data.dailyBudgetAp??0)} AP`:"Loading..."}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:q.data?`${Kt(q.data.instantFreeApPerHour)} free right now`:"Movement can now be read against today’s live capacity."})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.65fr)_minmax(20rem,0.95fr)]",children:[e.jsx(bb,{children:e.jsxs(ce,{className:"overflow-hidden rounded-[30px] border border-white/8 bg-[radial-gradient(circle_at_top_left,rgba(107,214,255,0.16),transparent_42%),linear-gradient(180deg,rgba(10,18,35,0.98),rgba(9,15,28,0.92))]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Movement operating mode"}),e.jsx(vt,{content:"This is the passive capture state of the movement system: whether tracking is running, how much is published into Forge, and how aggressive retention is."})]}),e.jsx("div",{className:"mt-2 text-[clamp(1.05rem,1.8vw,1.35rem)] text-white",children:"Background stays and trips as structured life evidence"}),e.jsx("div",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/58",children:"The companion samples quietly while stationary, switches to denser trip capture when you move, and keeps only simplified long-term traces."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(I,{tone:"signal",children:Ee.trackingEnabled?"Tracking on":"Tracking off"}),e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/72",children:Ee.publishMode.replaceAll("_"," ")}),e.jsx(W,{variant:"ghost",className:"h-9 rounded-full border border-white/10 bg-white/[0.04] px-4",onClick:()=>ke.mutate(!Ee.trackingEnabled),children:Ee.trackingEnabled?"Pause passive capture":"Enable passive capture"})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-3",children:[e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Distance today"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Ni(xe.summary.totalDistanceMeters)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Across trips, stops, and linked place changes."})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Idle time"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.totalIdleSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Time spent settled enough to count as a real stay."})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Estimated phone time"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.estimatedScreenTimeSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Estimated from hourly Screen Time bins, not exact foreground traces."})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Known places"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:xe.summary.knownPlaceCount}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Shared between Forge and the iPhone companion."})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(148,163,184,0.12),rgba(71,85,105,0.12))] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Missing data"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.missingDurationSeconds)}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[xe.summary.missingCount," grey gap",xe.summary.missingCount===1?"":"s"," where Forge had over one hour without enough movement signal."]})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(251,191,36,0.12),rgba(16,185,129,0.08))] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Repaired gaps"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.repairedGapDurationSeconds)}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[xe.summary.repairedGapCount," inferred span",xe.summary.repairedGapCount===1?"":"s"," classified as stay or move instead of leaving blank holes in the day."]})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(56,189,248,0.12),rgba(99,102,241,0.08))] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Continued stays"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.continuedStayDurationSeconds)}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[xe.summary.continuedStayCount," short stationary span",xe.summary.continuedStayCount===1?"":"s"," carried forward so quiet home time stays continuous instead of disappearing."]})]})]})]})}),e.jsx(wb,{children:e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Selection aggregate"}),e.jsx(vt,{content:"When you select stays or trips, Forge totals their span, distance, work overlap, notes, and places here."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Select any combination of stays and trips to sum movement, time, and work evidence."}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Span"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Cs(Ce.durationSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ni(Ce.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Work overlap"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Cs(Ce.trackedWorkSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Notes"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ce.noteCount})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Estimated phone time"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Cs(Ce.estimatedScreenTimeSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Pickups"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ce.pickupCount})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Notifications"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ce.notificationCount})]})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:Ce.placeLabels.map(ve=>e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:ve},ve))}),Ce.topApps.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:Ce.topApps.map(ve=>e.jsx(I,{tone:"default",className:"bg-[rgba(114,204,255,0.12)] text-white/80",children:(ve.displayName||ve.bundleIdentifier)+" · "+Cs(ve.totalActivitySeconds)},ve.id))}):null,Ce.topCategories.length>0?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Ce.topCategories.map(ve=>e.jsx(I,{tone:"default",className:"bg-white/[0.05] text-white/64",children:ve.categoryLabel},ve.id))}):null]})})]}),i==="life"?e.jsx(yb,{children:e.jsxs("section",{className:"grid gap-3",children:[e.jsx("div",{className:"flex items-center justify-between gap-3 px-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/38",children:"Life graph"}),e.jsx(vt,{content:"This graph shows the movement road of your life: stays are blocks, moves connect them, and the hour/day lines live in the background. Click a segment for details, then use edit when you want to correct it."})]})}),e.jsx(ZC,{userIds:a})]})}):null,i==="day"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.55fr)_minmax(22rem,1fr)]",children:[e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(7,12,22,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Day strip"}),e.jsx(vt,{content:"A compressed 24-hour strip. Each segment keeps its true order and duration, but the whole day stays navigable on one line."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"A single-row timeline from 00:00 to 24:00, always compressed into one navigable strip."})]}),e.jsx(ye,{type:"date",value:n,onChange:ve=>l(ve.target.value),className:"w-[11rem]"})]}),e.jsx("div",{className:"mt-6 overflow-x-auto pb-2",children:e.jsxs("div",{className:"min-w-[52rem]",children:[e.jsx("div",{className:"mb-3 flex justify-between text-[11px] uppercase tracking-[0.18em] text-white/36",children:["00:00","06:00","12:00","18:00","24:00"].map(ve=>e.jsx("span",{children:ve},ve))}),e.jsx("div",{className:"flex h-28 items-stretch overflow-hidden rounded-[28px] border border-white/10 bg-[rgba(255,255,255,0.03)] p-2",children:xe.segments.map(ve=>{const Le=Math.max(9,ve.durationSeconds/86400*100),Qe=ve.kind==="stay"?N.stayIds.includes(ve.id):ve.kind==="trip"?N.tripIds.includes(ve.id):!1;return e.jsxs("button",{type:"button",className:te("relative flex min-w-[5.5rem] flex-col justify-between rounded-[22px] border px-3 py-2 text-left transition",ve.kind==="missing"?"border-slate-400/20 bg-[linear-gradient(180deg,rgba(148,163,184,0.18),rgba(51,65,85,0.14))] hover:border-slate-300/30 hover:bg-[rgba(148,163,184,0.14)]":Qe?"border-[rgba(171,232,255,0.5)] bg-[rgba(171,232,255,0.16)]":"border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.02))] hover:border-white/14 hover:bg-white/[0.08]"),style:{width:`${Le}%`},onClick:()=>{ve.kind!=="missing"&&P(st=>{const F=new Set(st.stayIds),he=new Set(st.tripIds);return ve.kind==="stay"?F.has(ve.id)?F.delete(ve.id):F.add(ve.id):he.has(ve.id)?he.delete(ve.id):(he.add(ve.id),h(ve.id)),{stayIds:[...F],tripIds:[...he]}})},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(I,{tone:ve.kind==="trip"?"signal":ve.kind==="missing"?"meta":"default",className:"bg-white/[0.08] text-white/82",children:ve.kind==="missing"?"gap":ve.kind}),e.jsx("span",{className:"text-[11px] text-white/46",children:Cs(ve.durationSeconds)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"line-clamp-2 text-sm font-semibold text-white",children:ve.label}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/52",children:ve.subtitle})]})]},ve.id)})})]})}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{tone:"signal",children:e8(n)}),e.jsxs(I,{tone:"default",className:"bg-white/[0.06] text-white/72",children:[xe.summary.tripCount," trips"]}),e.jsxs(I,{tone:"default",className:"bg-white/[0.06] text-white/72",children:[xe.summary.stayCount," stays"]}),e.jsxs(I,{tone:"meta",children:[xe.summary.missingCount," gaps"]})]})]}),e.jsx("div",{className:"grid gap-4",children:G.data?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Selected trip"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsx(W,{variant:"ghost",className:"h-9 rounded-full border border-white/10 bg-white/[0.04] px-4",onClick:()=>x(ve=>!ve),children:u?"Stylized graph":"Exact path"})})]}),u?e.jsx(d8,{points:G.data.trip.points}):e.jsx(o8,{curve:G.data.stylizedPath.curve,startLabel:G.data.stylizedPath.startLabel,endLabel:G.data.stylizedPath.endLabel,stopLabels:G.data.stylizedPath.stops.map(ve=>ve.label)}),e.jsxs(ce,{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Trip context"}),(()=>{const ve=Dl(G.data.trip);return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{tone:"signal",children:Ni(G.data.trip.distanceMeters)}),e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:G.data.trip.activityType||G.data.trip.travelMode}),e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:Cs(G.data.trip.durationSeconds)}),e.jsx(I,{tone:"default",className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:Kt(ve.rateApPerHour)}),e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:St(ve.totalAp)})]})})})(),e.jsx("div",{className:"mt-4 text-sm leading-6 text-white/58",children:t8(G.data.trip.startedAt,G.data.trip.endedAt)}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Hourly estimate"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Cs(G.data.trip.estimatedScreenTimeSeconds)})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Pickups"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:G.data.trip.pickupCount})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Notifications"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:G.data.trip.notificationCount})]})]}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/48",children:"Derived from Screen Time hourly bins, not exact foreground traces."}),G.data.trip.topApps.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:G.data.trip.topApps.map(ve=>e.jsx(I,{tone:"default",className:"bg-[rgba(114,204,255,0.12)] text-white/80",children:(ve.displayName||ve.bundleIdentifier)+" · "+Cs(ve.totalActivitySeconds)},ve.id))}):null,G.data.trip.topCategories.length>0?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:G.data.trip.topCategories.map(ve=>e.jsx(I,{tone:"default",className:"bg-white/[0.05] text-white/64",children:ve.categoryLabel},ve.id))}):null]})]}):e.jsx(ce,{className:"rounded-[30px] border border-dashed border-white/12 bg-white/[0.03] p-6 text-white/58",children:"Select a trip segment to open the stylized trajectory card and exact path toggle."})})]}):null,i==="month"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.4fr)_minmax(18rem,0.85fr)]",children:[e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(9,15,28,0.97),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Month view"}),e.jsx(vt,{content:"This chart stays quantitative. Switch the metric to compare daily distance, moving time, idle time, or calories across the month."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Switch the Y-axis between motion, idle time, and energy without losing the same monthly frame."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ye,{type:"month",value:o,onChange:ve=>d(ve.target.value),className:"w-[10.5rem]"}),["distanceMeters","movingSeconds","idleSeconds","caloriesKcal"].map(ve=>e.jsx(W,{variant:"ghost",className:te("h-9 rounded-full border px-4 text-sm",Y===ve?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/10 bg-white/[0.04] text-white/62"),onClick:()=>z(ve),children:ve==="distanceMeters"?"Distance":ve==="movingSeconds"?"Moving":ve==="idleSeconds"?"Idle":"Calories"},ve))]})]}),e.jsx("div",{className:"mt-6 h-[24rem]",children:e.jsx(Fi,{width:"100%",height:"100%",children:e.jsxs(Er,{data:V.days,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"movementMonthFill",x1:"0",x2:"0",y1:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgba(110,220,255,0.7)"}),e.jsx("stop",{offset:"100%",stopColor:"rgba(110,220,255,0.05)"})]})}),e.jsx(Fn,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(ai,{dataKey:"dateKey",tick:{fill:"rgba(255,255,255,0.46)",fontSize:11},axisLine:!1,tickLine:!1}),e.jsx(ii,{tick:{fill:"rgba(255,255,255,0.46)",fontSize:11},axisLine:!1,tickLine:!1}),e.jsx(Lr,{contentStyle:{background:"rgba(7,12,24,0.94)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:16},formatter:ve=>s8(Y,Number(ve))}),e.jsx(Za,{type:"monotone",dataKey:Y,stroke:"rgba(126,233,255,0.95)",fill:"url(#movementMonthFill)",strokeWidth:2.4})]})})})]}),e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Month totals"}),e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Ni(V.totals.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Moving time"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Cs(V.totals.movingSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Settled time"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Cs(V.totals.idleSeconds)})]})]})]})]}):null,i==="all_time"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.35fr)_minmax(20rem,0.95fr)]",children:[e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(8,13,25,0.97),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Trips"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:Se.summary.tripCount})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Known places"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:Se.summary.knownPlaceCount})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:Ni(Se.summary.totalDistanceMeters)})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Countries"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:Se.summary.visitedCountries})]})]}),e.jsx("div",{className:"mt-6 grid gap-3 sm:grid-cols-2",children:Se.recentTrips.map(ve=>e.jsx("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4 text-left transition hover:bg-white/[0.06]",onClick:()=>{r("day"),h(ve.id)},children:(()=>{const Le=Dl({startedAt:ve.startedAt,endedAt:new Date(new Date(ve.startedAt).getTime()+36e5).toISOString(),expectedMet:2});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Recent travel"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ve.label||"Untitled trip"}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[Ni(ve.distanceMeters)," · ",ve.activityType||"travel"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(I,{tone:"default",className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:Kt(Le.rateApPerHour)})})]})})()},ve.id))})]}),e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Place categories"}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:Se.categoryBreakdown.map(ve=>e.jsxs(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:[ve.tag," · ",ve.count]},ve.tag))})]})]}):null,e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.25fr)_minmax(22rem,0.95fr)]",children:[e.jsx(vb,{children:e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(8,14,28,0.96),rgba(9,15,28,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Known places"}),e.jsx(vt,{content:"Known places turn raw stationary spans into named contexts like home, work, gym, nature, or any custom place tag you want Forge to remember."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"These landmarks anchor stays, travel XP, and contextual reasoning in both Forge and the companion. Seeded tags like home, workplace, gym, holiday, grocery, or nature matter for downstream calculations, but place tags stay open-ended."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:Q,onChange:ve=>X(ve.target.value),placeholder:"Search places",className:"w-[11rem]"}),e.jsx(W,{onClick:()=>{R(null),H(!0)},children:"Add place"})]})]}),e.jsx("div",{className:"mt-5 grid gap-3",children:ie.map(ve=>e.jsxs("button",{type:"button",className:"flex items-start justify-between gap-3 rounded-[24px] border border-white/8 bg-white/[0.03] p-4 text-left transition hover:bg-white/[0.06]",onClick:()=>{R(ve),H(!0)},children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg text-white",children:ve.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[ve.latitude.toFixed(4),", ",ve.longitude.toFixed(4)," · radius ",Math.round(ve.radiusMeters)," m"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:ve.categoryTags.map(Le=>e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:Le},Le))})]}),e.jsx(da,{className:"mt-1 size-4 text-white/42"})]},ve.id))})]})}),e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Movement help"}),e.jsx(vt,{content:"Most movement surfaces on this page have help buttons. Use them to understand the graph, the day strip, the month chart, and the place system without keeping a large prose block on screen."})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Use the small help icons across this page for graph explanations, timeline semantics, and metric meanings."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Life graph"}),e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Day strip"}),e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Month chart"}),e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Known places"}),e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Selection aggregate"})]})]})]}),G.data?e.jsx(pa,{open:g,onOpenChange:ve=>{p(ve),ve||(b(""),C([]),w(null),y(null))},eyebrow:"Movement data",title:G.data.trip.label||"Trip datapoints",description:"Inspect the raw datapoints behind this trip. Raw measurements are read-only here; visible movement corrections now happen through canonical user-defined boxes.",children:e.jsx(jb,{children:e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,24rem)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(mi,{title:"Datapoint browser",description:"Search raw points by time band, anchor status, or accuracy before opening the point editor.",query:f,onQueryChange:b,options:Ie,selectedOptionIds:A,onSelectedOptionIdsChange:C,resultSummary:M,placeholder:"Search timestamps, accuracy, point ids, or filter chips",emptyStateMessage:"Keep typing or pick a time/quality chip to narrow the trip datapoints."}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Raw datapoints"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a point to correct or delete it."})]}),e.jsx(I,{tone:"meta",children:M})]}),e.jsx("div",{ref:K,className:"h-[34rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:Ne.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No datapoint matches the current search. Clear some filters or search by time, anchor type, or accuracy."}):e.jsx("div",{className:"relative w-full",style:{height:`${E.getTotalSize()}px`},children:E.getVirtualItems().map(ve=>{const Le=Ne[ve.index];return e.jsx("div",{className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${ve.start}px)`},children:e.jsxs("button",{type:"button",className:te("grid w-full gap-3 rounded-[20px] border px-4 py-3 text-left transition",T===Le.id?"border-[rgba(171,232,255,0.34)] bg-[rgba(171,232,255,0.12)]":"border-white/8 bg-white/[0.04] hover:bg-white/[0.07]"),onClick:()=>{w(Le.id),y(Wp(Le))},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Fa,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:Bm(Le.recordedAt)})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[Le.latitude.toFixed(5),", ",Le.longitude.toFixed(5)]})]}),e.jsx(I,{tone:Le.isStopAnchor?"signal":"meta",children:Le.isStopAnchor?"Stop anchor":"Path point"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(I,{tone:"meta",className:"capitalize",children:Cd(Le.recordedAt)}),Le.accuracyMeters!=null?e.jsxs(I,{tone:"meta",children:[Math.round(Le.accuracyMeters)," m accuracy"]}):null,Le.speedMps!=null?e.jsxs(I,{tone:"meta",children:[Le.speedMps.toFixed(1)," m/s"]}):null]})]})},Le.id)})})})]})]}),O&&S?e.jsx(c8,{point:O,draft:S}):e.jsx(ce,{className:"rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] p-6 text-white/56",children:"Pick a datapoint to inspect its raw measurement details. To correct what the user sees, use canonical user-defined movement boxes in the Life Timeline."})]})})}):null,e.jsx(Mw,{open:v,onOpenChange:H,place:j,onSave:async ve=>{await Ae.mutateAsync(ve)}})]})}function m8(t){return t.trim().toLowerCase()}function h8(t,s){return t.includes(s)?t:[...t,s]}function p8({entityOptions:t,selectedEntityValues:s,onSelectedEntityValuesChange:a,selectedTextTerms:i,onSelectedTextTermsChange:r,placeholder:n="Filter by linked entity or add free text"}){const[l,o]=c.useState(""),[d,m]=c.useState(!1),[h,u]=c.useState(0),x=m8(l),g=c.useMemo(()=>s.map(w=>t.find(S=>S.value===w)).filter(Boolean),[t,s]),p=c.useMemo(()=>{const w=t.filter(S=>!s.includes(S.value));return x?w.filter(S=>`${S.label} ${S.description??""} ${S.searchText??""}`.toLowerCase().includes(x)).slice(0,8):w.slice(0,8)},[t,x,s]),f=l.trim().length>0&&!i.includes(l.trim()),b=w=>{a(h8(s,w)),o(""),u(0),m(!1)},A=(w=l)=>{const S=w.trim();!S||i.includes(S)||(r([...i,S]),o(""),u(0),m(!1))},C=w=>{a(s.filter(S=>S!==w))},T=w=>{r(i.filter(S=>S!==w))};return e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-[11px] uppercase tracking-[0.16em] text-white/40",children:[e.jsx("span",{children:"Search hints: entity chips match linked records, free-text chips match note body or author."}),e.jsx("button",{type:"button",onClick:()=>A(),disabled:!f,className:"rounded-full border border-white/8 bg-white/[0.04] px-2.5 py-1 text-[10px] tracking-[0.14em] text-white/62 transition hover:bg-white/[0.08] hover:text-white disabled:cursor-not-allowed disabled:opacity-40",children:"Free text"})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,28,48,0.88),rgba(10,14,26,0.98))] px-4 py-3 shadow-[0_24px_70px_rgba(3,8,18,0.2)]",children:[g.length>0||i.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[g.map(w=>e.jsxs("span",{className:"inline-flex max-w-full items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[w.kind?e.jsx(We,{kind:w.kind,label:w.label,compact:!0,gradient:!1,className:"max-w-[16rem]"}):e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:w.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>C(w.value),"aria-label":`Remove ${w.label}`,children:e.jsx(Tt,{className:"size-3.5"})})]},w.value)),i.map(w=>e.jsxs("span",{className:"inline-flex max-w-full items-center gap-2 rounded-full border border-cyan-300/16 bg-cyan-400/10 px-2.5 py-1.5 text-sm text-cyan-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Zm,{className:"size-3.5"}),e.jsx("span",{className:"max-w-[16rem] truncate",children:w})]}),e.jsx("button",{type:"button",className:"rounded-full text-cyan-100/70 transition hover:text-white",onClick:()=>T(w),"aria-label":`Remove free-text filter ${w}`,children:e.jsx(Tt,{className:"size-3.5"})})]},w))]}):null,i.length>1?e.jsx("div",{className:"mb-3 text-xs text-white/42",children:"Free-text chips are combined with OR."}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/34"}),e.jsx("input",{value:l,onChange:w=>{o(w.target.value),m(!0),u(0)},onFocus:()=>m(!0),onBlur:()=>{window.setTimeout(()=>m(!1),120)},onKeyDown:w=>{if(w.key==="Backspace"&&!l){if(i.length>0){T(i[i.length-1]);return}s.length>0&&C(s[s.length-1]);return}if(w.key==="ArrowDown"){w.preventDefault(),m(!0),u(y=>p.length===0?0:Math.min(p.length-1,y+1));return}if(w.key==="ArrowUp"){w.preventDefault(),u(y=>Math.max(0,y-1));return}if(w.key==="Escape"){m(!1);return}if(w.key!=="Enter")return;w.preventDefault();const S=p[h];if(S){b(S.value);return}A()},placeholder:n,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),d?e.jsxs("div",{className:"absolute top-full z-20 mt-2 w-full rounded-[22px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:[p.map((w,S)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",S===h?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>u(S),onMouseDown:y=>y.preventDefault(),onClick:()=>b(w.value),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:w.kind?e.jsx(We,{kind:w.kind,label:w.label,compact:!0,gradient:!1}):w.label}),w.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:w.description}):null]})},w.value)),f?e.jsxs("button",{type:"button",className:"mt-1 flex w-full items-center gap-2 rounded-[18px] px-3 py-2.5 text-left text-sm text-cyan-100 transition hover:bg-white/[0.06]",onMouseDown:w=>w.preventDefault(),onClick:()=>A(),children:[e.jsx(Zm,{className:"size-4"}),e.jsxs("span",{className:"truncate",children:['Add free text "',l.trim(),'"']})]}):null,p.length===0&&!f?e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:"Keep typing to find a linked entity, or press Enter to add a free-text badge."}):null]}):null]})]})]})}const x8=new Set(["goal","project","task","strategy","habit","tag","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","trigger_report"]);function Fw(t){return x8.has(t)}function Fs(t,s){return`${t}:${s}`}function Ql(t){const s=t.indexOf(":");if(s<=0||s>=t.length-1)return null;const a=t.slice(0,s);return Fw(a)?{entityType:a,entityId:t.slice(s+1)}:null}function Hp(t){return t!==null}function Gp(t){const s=t.getAll("linkedTo"),a=t.get("entityType"),i=t.get("entityId");return a&&i&&Fw(a)&&s.unshift(Fs(a,i)),Array.from(new Set(s.map(r=>r.trim()).filter(Boolean)))}function g8(t){return Array.from(new Set(t.getAll("textTerms").map(s=>s.trim()).filter(Boolean)))}function f8(t){return js(t.getAll("tags"))}function bn(t,s=[]){return{contentMarkdown:(t==null?void 0:t.contentMarkdown)??"",author:(t==null?void 0:t.author)??"",linkedValues:(t==null?void 0:t.links.map(a=>Fs(a.entityType,a.entityId)))??s,tags:js((t==null?void 0:t.tags)??[]),destroyAtInput:Yb((t==null?void 0:t.destroyAt)??null),destroyDelayValue:"",destroyDelayUnit:"days"}}function b8(t){return[...t].sort((s,a)=>s.label.localeCompare(a.label))}function Qp(t){return qo(t.destroyAtInput)??Jb(t.destroyDelayValue,t.destroyDelayUnit)}function w8(){var V,Se,Ee,Ce,qe,oe,L;const t=$t(),s=ct(),a=jt(),[i,r]=ms(),[n,l]=c.useState(()=>Gp(i)),[o,d]=c.useState(()=>f8(i)),[m,h]=c.useState(()=>g8(i)),[u,x]=c.useState(i.get("author")??""),[g,p]=c.useState(i.get("updatedFrom")??""),[f,b]=c.useState(i.get("updatedTo")??""),[A,C]=c.useState(!1),[T,w]=c.useState(()=>bn(null,Gp(i))),[S,y]=c.useState(null),[N,P]=c.useState(null),[v,H]=c.useState(null),j=Fe({queryKey:["forge-psyche-values"],queryFn:Vs}),R=Fe({queryKey:["forge-psyche-patterns"],queryFn:Oa}),Q=Fe({queryKey:["forge-psyche-behaviors"],queryFn:Xs}),X=Fe({queryKey:["forge-psyche-beliefs"],queryFn:Ca}),Y=Fe({queryKey:["forge-psyche-modes"],queryFn:za}),z=Fe({queryKey:["forge-psyche-reports"],queryFn:xi}),K=Array.isArray(a.selectedUserIds)?a.selectedUserIds:[],$=Fe({queryKey:["forge-life-force",...K],queryFn:async()=>(await Ji(K)).lifeForce});c.useEffect(()=>{const U=new URLSearchParams;for(const ge of n)U.append("linkedTo",ge);for(const ge of o)U.append("tags",ge);for(const ge of m)U.append("textTerms",ge);u.trim()&&U.set("author",u.trim()),g&&U.set("updatedFrom",g),f&&U.set("updatedTo",f),r(U,{replace:!0})},[u,n,o,m,r,g,f]);const D=c.useMemo(()=>{var ge,Te,ve,Le,Qe,st;const U=[...a.snapshot.goals.map(F=>({value:Fs("goal",F.id),label:F.title,description:ut(F.description,F.user,"Goal"),searchText:dt([F.title,F.description],F),kind:Xt("goal")??void 0})),...a.snapshot.dashboard.projects.map(F=>({value:Fs("project",F.id),label:F.title,description:ut(`${F.description}${F.description?" · ":""}${F.goalTitle}`,F.user,F.goalTitle),searchText:dt([F.title,F.description,F.goalTitle],F),kind:Xt("project")??void 0})),...a.snapshot.tasks.map(F=>({value:Fs("task",F.id),label:F.title,description:ut(`${F.description}${F.description?" · ":""}${F.owner}`,F.user,F.owner),searchText:dt([F.title,F.description,F.owner],F),kind:Xt("task")??void 0})),...a.snapshot.strategies.map(F=>({value:Fs("strategy",F.id),label:F.title,description:ut(F.overview,F.user,"Strategy"),searchText:dt([F.title,F.overview,F.endStateDescription],F),kind:Xt("strategy")??void 0})),...a.snapshot.habits.map(F=>({value:Fs("habit",F.id),label:F.title,description:ut(F.description,F.user,"Habit"),searchText:dt([F.title,F.description],F),kind:Xt("habit")??void 0})),...a.snapshot.tags.map(F=>({value:Fs("tag",F.id),label:F.name,description:ut(F.description,F.user,F.kind),searchText:dt([F.name,F.kind,F.description],F),kind:Xt("tag")??void 0})),...(((ge=j.data)==null?void 0:ge.values)??[]).map(F=>({value:Fs("psyche_value",F.id),label:F.title,description:ut(F.description,F.user,"Psyche value"),searchText:dt([F.title,F.description,F.valuedDirection],F),kind:Xt("psyche_value")??void 0})),...(((Te=R.data)==null?void 0:Te.patterns)??[]).map(F=>({value:Fs("behavior_pattern",F.id),label:F.title,description:ut(F.description,F.user,"Behavior pattern"),searchText:dt([F.title,F.description,F.targetBehavior],F),kind:Xt("behavior_pattern")??void 0})),...(((ve=Q.data)==null?void 0:ve.behaviors)??[]).map(F=>({value:Fs("behavior",F.id),label:F.title,description:ut(F.description,F.user,"Behavior"),searchText:dt([F.title,F.description,F.kind],F),kind:Xt("behavior")??void 0})),...(((Le=X.data)==null?void 0:Le.beliefs)??[]).map(F=>({value:Fs("belief_entry",F.id),label:F.statement,description:ut(F.flexibleAlternative||F.originNote,F.user,"Belief"),searchText:dt([F.statement,F.flexibleAlternative,F.originNote],F),kind:Xt("belief_entry")??void 0})),...(((Qe=Y.data)==null?void 0:Qe.modes)??[]).map(F=>({value:Fs("mode_profile",F.id),label:F.title,description:ut(F.archetype||F.family,F.user,"Mode"),searchText:dt([F.title,F.archetype,F.family,F.persona],F),kind:Xt("mode_profile")??void 0})),...(((st=z.data)==null?void 0:st.reports)??[]).map(F=>({value:Fs("trigger_report",F.id),label:F.title,description:ut(F.eventSituation,F.user,"Trigger report"),searchText:dt([F.title,F.eventSituation,F.customEventType??""],F),kind:Xt("trigger_report")??void 0}))];return b8(U)},[(V=Q.data)==null?void 0:V.behaviors,(Se=X.data)==null?void 0:Se.beliefs,(Ee=Y.data)==null?void 0:Ee.modes,(Ce=R.data)==null?void 0:Ce.patterns,(qe=z.data)==null?void 0:qe.reports,a.snapshot.dashboard.projects,a.snapshot.goals,a.snapshot.habits,a.snapshot.strategies,a.snapshot.tags,a.snapshot.tasks,(oe=j.data)==null?void 0:oe.values]),J=c.useMemo(()=>D.map(U=>{const ge=Ql(U.value);return{value:U.value,label:U.label,description:U.description,searchText:U.searchText,kind:U.kind,entityType:(ge==null?void 0:ge.entityType)??"goal",entityId:(ge==null?void 0:ge.entityId)??""}}),[D]),q=c.useMemo(()=>n.map(U=>Ql(U)).filter(Boolean),[n]),_=Fe({queryKey:["notes-index",n.join("|"),o.join("|"),m.join("|"),u.trim(),g,f],queryFn:()=>tf({linkedTo:q,tags:o,textTerms:m,author:u.trim()||void 0,updatedFrom:g||void 0,updatedTo:f||void 0,limit:200})}),B=async()=>{await Promise.all([s.invalidateQueries({queryKey:["notes-index"]}),Ut(s)])},G=Re({mutationFn:async U=>wl({contentMarkdown:U.contentMarkdown.trim(),author:U.author.trim()||null,tags:js(U.tags),destroyAt:Qp(U),links:U.linkedValues.map(ge=>Ql(ge)).filter(Hp).map(ge=>({entityType:ge.entityType,entityId:ge.entityId}))}),onSuccess:async()=>{w(bn(null,n)),C(!1),await B()}}),ae=Re({mutationFn:async({noteId:U,draft:ge})=>Zn(U,{contentMarkdown:ge.contentMarkdown.trim(),author:ge.author.trim()||null,tags:js(ge.tags),destroyAt:Qp(ge),links:ge.linkedValues.map(Te=>Ql(Te)).filter(Hp).map(Te=>({entityType:Te.entityType,entityId:Te.entityId}))}),onSuccess:async()=>{y(null),P(null),await B()}}),ke=Re({mutationFn:U=>em(U),onSuccess:B}),Ae=((L=_.data)==null?void 0:L.notes)??[],ie=new Date().toISOString().slice(0,10),Ne=Ae.filter(U=>U.createdAt.slice(0,10)===ie).length*Fl().totalAp,M=v?Ae.find(U=>U.id===v.noteId)??null:null,E=M?jh(M):null,O=E?ci(E.entityType,E.entityId):null,xe=c.useMemo(()=>M?[{id:"open-linked",label:"Open linked record",description:O?"Jump back into the main entity this note is attached to.":"This note has no navigable linked record yet.",icon:Es,disabled:!O,onSelect:()=>{O&&t(O.includes("#")?O:`${O}#notes`)}},{id:"edit-note",label:"Edit note",description:"Update the Markdown body, note tags, expiry, or connected entity links.",icon:pi,onSelect:()=>{y(M.id),P(bn(M))}},{id:"delete-note",label:"Delete note",description:"Soft-delete this note from the main workspace.",icon:Rt,tone:"danger",disabled:ke.isPending,onSelect:()=>{ke.mutateAsync(M.id)}}]:[],[O,M,ke,t]);return _.isError?e.jsx(it,{eyebrow:"Notes",error:_.error,onRetry:()=>void _.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:"Notes",titleText:"Notes",description:"Notes are first-class Markdown entities in Forge. Search them by linked records, note tags, date, or free text, then create durable or ephemeral notes that stay connected to the rest of the graph.",badge:`${Ae.length} visible`,actions:e.jsxs(W,{onClick:()=>{w(bn(null,n)),C(!0)},children:[e.jsx(ds,{className:"size-4"}),"New note"]})}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(ce,{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:"Quick note default"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:St(Fl().totalAp)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Standalone notes count as a tiny Action Point impulse unless a richer active work context already covers them."})]}),e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Notes created today"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:St(Ne)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Visible notes created today in this workspace at the default quick note cost."})]}),e.jsxs(ce,{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:$.data?`${St($.data.spentTodayAp)} / ${St($.data.dailyBudgetAp)}`:"Loading..."}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Notes participate in the same Action Point ledger as tasks, habits, movement, and calendar work."})]}),e.jsxs(ce,{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:$.data?Kt($.data.instantFreeApPerHour):"Loading..."}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Useful when deciding whether to just capture a quick note or stay inside a heavier work stream."})]})]}),e.jsx(Nb,{children:e.jsxs(ce,{className:"grid gap-4",children:[e.jsx(p8,{entityOptions:J,selectedEntityValues:n,onSelectedEntityValuesChange:l,selectedTextTerms:m,onSelectedTextTermsChange:h}),e.jsx(Oi,{value:o,onChange:d,placeholder:"Filter by memory tag or custom note tag"}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(12rem,0.38fr)_minmax(12rem,0.38fr)]",children:[e.jsx(ye,{value:u,onChange:U=>x(U.target.value),placeholder:"Filter by author"}),e.jsx(ye,{type:"date",value:g,onChange:U=>p(U.target.value)}),e.jsx(ye,{type:"date",value:f,onChange:U=>b(U.target.value)})]})]})}),A?e.jsx(kb,{children:e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"New note"}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/58",children:["Notes are independent Markdown entities. Link them to one or more real records, add memory-system or custom tags, and optionally make them ephemeral with an automatic destroy time. Standalone notes default to"," ",St(Fl().totalAp),"."]})]}),e.jsx(W,{variant:"ghost",onClick:()=>{C(!1),w(bn(null,n))},children:"Cancel"})]}),e.jsx(Ze,{value:T.contentMarkdown,onChange:U=>w(ge=>({...ge,contentMarkdown:U.target.value})),className:"min-h-[16rem]",placeholder:"Write the note in Markdown. This can be as short as a handoff line or as long as a wiki page."}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]",children:[e.jsx(ye,{value:T.author,onChange:U=>w(ge=>({...ge,author:U.target.value})),placeholder:"Optional author"}),e.jsx(mt,{options:D,selectedValues:T.linkedValues,onChange:U=>w(ge=>({...ge,linkedValues:U})),placeholder:"Link this note to strategies, goals, projects, tasks, habits, or human/bot-owned records",emptyMessage:"No matching entities found yet."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(Oi,{value:T.tags,onChange:U=>w(ge=>({...ge,tags:U}))}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Ephemeral auto-destroy"}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/48",children:"Set an exact destroy time or a relative delay. Leaving both blank keeps the note durable."})]}),e.jsx(ye,{type:"datetime-local",value:T.destroyAtInput,onChange:U=>w(ge=>({...ge,destroyAtInput:U.target.value}))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ye,{type:"number",min:"1",value:T.destroyDelayValue,onChange:U=>w(ge=>({...ge,destroyDelayValue:U.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:T.destroyDelayUnit,onChange:U=>w(ge=>({...ge,destroyDelayUnit:U.target.value})),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Preview"}),e.jsx("div",{className:"mt-3",children:T.contentMarkdown.trim()?e.jsx(Rs,{markdown:T.contentMarkdown}):e.jsx("div",{className:"text-sm text-white/42",children:"Markdown preview appears here."})})]}),e.jsx("div",{className:"flex flex-wrap justify-end gap-2",children:e.jsx(W,{pending:G.isPending,pendingLabel:"Saving",disabled:T.contentMarkdown.trim().length===0||T.linkedValues.length===0,onClick:()=>void G.mutateAsync(T),children:"Save note"})})]})}):null,_.isLoading?e.jsx(ce,{className:"text-sm text-white/58",children:"Loading notes…"}):Ae.length===0?e.jsx(Bt,{eyebrow:"Notes",title:"No matching notes yet",description:"Try broader linked-entity filters, remove a date bound, or add the first durable note from the button above."}):e.jsx(Sb,{children:e.jsx("div",{className:"grid gap-3",children:Ae.map(U=>{const ge=jh(U),Te=ge?ci(ge.entityType,ge.entityId):null,ve=S===U.id&&N!==null;return e.jsxs(ce,{className:"min-w-0 overflow-hidden p-5",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:[(U.author??"Unknown author").toString()," •"," ",new Date(U.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-[var(--primary)]/12 text-[var(--primary)]",wrap:!0,children:[St(Fl().totalAp)," ","quick note"]}),U.links.map(Le=>e.jsxs(I,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[Ea(Le.entityType),Le.anchorKey?` · ${$n(Le.anchorKey)}`:""]},`${U.id}-${Le.entityType}-${Le.entityId}-${Le.anchorKey??""}`)),(U.tags??[]).map(Le=>e.jsx(I,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:Le},`${U.id}-tag-${Le}`)),U.destroyAt?e.jsxs(I,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(U.destroyAt).toLocaleString()]}):null]})]}),e.jsx("button",{type:"button",className:"rounded-full border border-white/8 bg-white/[0.04] p-2 text-white/58 transition hover:bg-white/[0.08] hover:text-white",onClick:Le=>{Le.preventDefault(),Le.stopPropagation();const Qe=Le.currentTarget.getBoundingClientRect();H({noteId:U.id,position:{x:Qe.right-8,y:Qe.bottom+8}})},"aria-label":`Open actions for note ${U.id}`,children:e.jsx(Di,{className:"size-4"})})]}),ve?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(Ze,{value:N.contentMarkdown,onChange:Le=>P(Qe=>Qe&&{...Qe,contentMarkdown:Le.target.value}),className:"min-h-[14rem]"}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]",children:[e.jsx(ye,{value:N.author,onChange:Le=>P(Qe=>Qe&&{...Qe,author:Le.target.value}),placeholder:"Optional author"}),e.jsx(mt,{options:D,selectedValues:N.linkedValues,onChange:Le=>P(Qe=>Qe&&{...Qe,linkedValues:Le}),placeholder:"Update the linked entities",emptyMessage:"No matching entities found yet."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(Oi,{value:N.tags,onChange:Le=>P(Qe=>Qe&&{...Qe,tags:Le})}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Ephemeral auto-destroy"}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/48",children:"Set an exact destroy time or a relative delay. Leaving both blank keeps the note durable."})]}),e.jsx(ye,{type:"datetime-local",value:N.destroyAtInput,onChange:Le=>P(Qe=>Qe&&{...Qe,destroyAtInput:Le.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ye,{type:"number",min:"1",value:N.destroyDelayValue,onChange:Le=>P(Qe=>Qe&&{...Qe,destroyDelayValue:Le.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:N.destroyDelayUnit,onChange:Le=>P(Qe=>Qe&&{...Qe,destroyDelayUnit:Le.target.value}),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Preview"}),e.jsx("div",{className:"mt-3",children:N.contentMarkdown.trim()?e.jsx(Rs,{markdown:N.contentMarkdown}):e.jsx("div",{className:"text-sm text-white/42",children:"No content yet."})})]}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx(W,{variant:"ghost",onClick:()=>{y(null),P(null)},children:"Cancel"}),e.jsx(W,{pending:ae.isPending,pendingLabel:"Saving",disabled:N.contentMarkdown.trim().length===0||N.linkedValues.length===0,onClick:()=>void ae.mutateAsync({noteId:U.id,draft:N}),children:"Save changes"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"mt-4 w-full text-left",onClick:()=>{Te&&t(Te.includes("#")?Te:`${Te}#notes`)},disabled:!Te,children:e.jsx(Rs,{markdown:U.contentMarkdown,className:"line-clamp-none"})}),Te?e.jsx("div",{className:"mt-4 inline-flex text-xs uppercase tracking-[0.16em] text-[var(--secondary)]",children:"Open linked record"}):null]})]},U.id)})})}),e.jsx(vd,{open:!!v,title:"Note actions",subtitle:M?M.contentPlain.slice(0,80)||"Markdown note":void 0,items:xe,position:(v==null?void 0:v.position)??null,onClose:()=>H(null)})]})}const Vl={lg:1280,md:996,sm:768,xs:480},wu={lg:12,md:10,sm:6,xs:4,xxs:2},y8="forge.surface-layout.v3";function _w(t){return`${y8}.${t}`}function yu(t,s,a){return Math.min(Math.max(t,s),a)}function v8(t){return t>=Vl.lg?"lg":t>=Vl.md?"md":t>=Vl.sm?"sm":t>=Vl.xs?"xs":"xxs"}function j8(t,s){const a=wu[s];if(s==="lg")return yu(t.defaultWidth,t.minWidth??1,Math.min(t.maxWidth??a,a));const i=Math.round(t.defaultWidth/wu.lg*a);return yu(Math.max(t.minWidth??1,i||(t.minWidth??1)),t.minWidth??1,Math.min(t.maxWidth??a,a))}function N8(t){return{hidden:t.defaultHidden??!1,fullWidth:t.defaultFullWidth??!1,titleVisible:t.defaultTitleVisible??!0,descriptionVisible:t.defaultDescriptionVisible??!0}}function vu(t,s){const a=[...s.filter(i=>i.defaultPlacement==="top"),...s.filter(i=>i.defaultPlacement!=="top")];return{surfaceId:t,order:a.map(i=>i.id),widgets:Object.fromEntries(s.map(i=>[i.id,N8(i)])),updatedAt:new Date(0).toISOString()}}function oc(t,s,a){const i=vu(t,s),r=new Set(s.map(d=>d.id)),n=((a==null?void 0:a.order)??[]).filter(d=>r.has(d)),l=i.order.filter(d=>!n.includes(d)),o=Object.fromEntries(s.map(d=>{var h,u,x,g,p;const m=(h=a==null?void 0:a.widgets)==null?void 0:h[d.id];return[d.id,{...i.widgets[d.id],hidden:(m==null?void 0:m.hidden)??((u=i.widgets[d.id])==null?void 0:u.hidden)??!1,fullWidth:(m==null?void 0:m.fullWidth)??((x=i.widgets[d.id])==null?void 0:x.fullWidth)??!1,titleVisible:(m==null?void 0:m.titleVisible)??((g=i.widgets[d.id])==null?void 0:g.titleVisible)??!0,descriptionVisible:(m==null?void 0:m.descriptionVisible)??((p=i.widgets[d.id])==null?void 0:p.descriptionVisible)??!0}]}));return{surfaceId:t,order:[...n,...l],widgets:o,updatedAt:typeof(a==null?void 0:a.updatedAt)=="string"?a.updatedAt:i.updatedAt}}function k8(t,s){const a=new Map(s.order.map((i,r)=>[i,r]));return[...t].sort((i,r)=>{const n=a.get(i.id)??Number.MAX_SAFE_INTEGER,l=a.get(r.id)??Number.MAX_SAFE_INTEGER;return n!==l?n-l:i.id.localeCompare(r.id)})}function S8(t,s,a){const i=t.indexOf(s);if(i===-1)return t;const r=yu(a,0,t.length-1);if(i===r)return t;const n=[...t];return n.splice(i,1),n.splice(r,0,s),n}function dc(t){if(typeof window>"u")return null;try{const s=window.localStorage.getItem(_w(t));return s?JSON.parse(s):null}catch{return null}}function cc(t){if(!(typeof window>"u"))try{window.localStorage.setItem(_w(t.surfaceId),JSON.stringify(t))}catch{}}const I8=500;function Vp(t,s){return t.surfaceId===s.surfaceId&&JSON.stringify(t.order)===JSON.stringify(s.order)&&JSON.stringify(t.widgets)===JSON.stringify(s.widgets)}function C8({definition:t,preferences:s,editing:a,width:i,children:r}){const n=i<=4;return t.surfaceChrome==="none"?e.jsx("div",{"data-surface-card":"true",className:te("min-w-0",a&&"rounded-[28px] ring-1 ring-white/8 ring-inset"),children:r}):e.jsxs(ce,{"data-surface-card":"true",className:te("surface-grid-card flex min-w-0 flex-col gap-3 overflow-visible p-4 md:p-5",a&&"ring-1 ring-white/8"),children:[s.titleVisible||s.descriptionVisible&&t.description?e.jsxs("div",{className:"min-w-0",children:[s.titleVisible?e.jsx("div",{className:"truncate text-[0.72rem] font-semibold uppercase tracking-[0.16em] text-white/40",children:t.title}):null,s.descriptionVisible&&t.description&&!n?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/52",children:t.description}):null]}):null,e.jsx("div",{className:"min-h-0 flex-1",children:r})]})}function T8({widget:t,preferences:s,index:a,total:i,onMove:r,onToggleHidden:n,onToggleFullWidth:l}){const o=pl({id:t.id});return e.jsxs("div",{ref:o.setNodeRef,style:{transform:xl.Transform.toString(o.transform),transition:o.transition},className:"flex min-w-0 items-center gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[e.jsx("button",{type:"button",className:"inline-flex size-8 shrink-0 items-center justify-center rounded-full bg-white/[0.05] text-white/50 transition hover:bg-white/[0.08] hover:text-white","aria-label":`Drag ${t.title}`,...o.attributes,...o.listeners,children:e.jsx(ul,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:t.title}),t.description?e.jsx("div",{className:"truncate text-[12px] text-white/48",children:t.description}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx("button",{type:"button",className:"inline-flex size-8 items-center justify-center rounded-full bg-white/[0.05] text-white/60 transition hover:bg-white/[0.08] hover:text-white disabled:opacity-40",onClick:()=>r(a-1),disabled:a===0,"aria-label":`Move ${t.title} up`,children:e.jsx(_v,{className:"size-3.5"})}),e.jsx("button",{type:"button",className:"inline-flex size-8 items-center justify-center rounded-full bg-white/[0.05] text-white/60 transition hover:bg-white/[0.08] hover:text-white disabled:opacity-40",onClick:()=>r(a+1),disabled:a===i-1,"aria-label":`Move ${t.title} down`,children:e.jsx(Rv,{className:"size-3.5"})}),e.jsxs("button",{type:"button",className:te("inline-flex h-8 items-center gap-2 rounded-full px-3 text-[12px] transition",s.fullWidth?"bg-[var(--primary)] text-slate-950":"bg-white/[0.05] text-white/72 hover:bg-white/[0.08] hover:text-white"),onClick:l,children:[s.fullWidth?e.jsx($v,{className:"size-3.5"}):e.jsx(Ov,{className:"size-3.5"}),s.fullWidth?"Normal width":"Full width"]}),t.removable!==!1?e.jsxs("button",{type:"button",className:"inline-flex h-8 items-center gap-2 rounded-full bg-white/[0.05] px-3 text-[12px] text-white/72 transition hover:bg-white/[0.08] hover:text-white",onClick:n,children:[e.jsx(Pg,{className:"size-3.5"}),"Hide"]}):null]})]})}function P8({surfaceId:t,widgets:s,defaultEditing:a=!1,actions:i,normalizeLayout:r}){var Y;const n=c.useMemo(()=>JSON.stringify(s.map(z=>({id:z.id,defaultWidth:z.defaultWidth,defaultHidden:z.defaultHidden,defaultPlacement:z.defaultPlacement,defaultFullWidth:z.defaultFullWidth,defaultTitleVisible:z.defaultTitleVisible,defaultDescriptionVisible:z.defaultDescriptionVisible}))),[s]),l=c.useMemo(()=>{const z=vu(t,s);return r?r(z):z},[r,t,n]),o=z=>r?r(z):z,[d,m]=c.useState(a),[h,u]=c.useState(1280),[x,g]=c.useState(()=>o(oc(t,s,dc(t)??l))),p=c.useRef(null),f=c.useRef(!1),b=c.useRef(o(oc(t,s,dc(t)??l))),A=c.useRef(null),C=ld(od(cd,{activationConstraint:{distance:6}})),T=Fe({queryKey:["forge-surface-layout",t],queryFn:()=>i1(t)}),w=Re({mutationFn:z=>r1(t,{order:z.order,widgets:z.widgets})}),S=Re({mutationFn:()=>n1(t)});c.useEffect(()=>{var K;const z=o(oc(t,s,((K=T.data)==null?void 0:K.layout)??dc(t)??l));g($=>Vp($,z)?$:z),cc(z),b.current=z,f.current=!0},[l,(Y=T.data)==null?void 0:Y.layout,r,t,n,s]),c.useEffect(()=>{const z=A.current;if(!z||typeof ResizeObserver>"u")return;const K=new ResizeObserver($=>{var J;const D=((J=$[0])==null?void 0:J.contentRect.width)??z.clientWidth;u(Math.max(320,Math.round(D)))});return K.observe(z),u(Math.max(320,Math.round(z.clientWidth||1280))),()=>K.disconnect()},[]),c.useEffect(()=>{if(f.current&&!Vp(x,b.current))return cc(x),p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{const z=x;w.mutateAsync(z).then(()=>{b.current=z})},I8),()=>{p.current!==null&&window.clearTimeout(p.current)}},[x,w,t]);const y=v8(h),N=wu[y],P=c.useMemo(()=>k8(s,x),[x,s]),v=P.filter(z=>{var K;return!((K=x.widgets[z.id])!=null&&K.hidden)}),H=P.filter(z=>{var K;return(K=x.widgets[z.id])==null?void 0:K.hidden});function j(z,K){g($=>o({...$,widgets:{...$.widgets,[z]:{...$.widgets[z],...K}}}))}function R(z,K){g($=>o({...$,order:S8($.order,z,K)}))}function Q(z){const{active:K,over:$}=z;!$||K.id===$.id||g(D=>{const J=D.order.indexOf(String(K.id)),q=D.order.indexOf(String($.id));return J===-1||q===-1?D:o({...D,order:Vu(D.order,J,q)})})}function X(){const z=o(vu(t,s));g(z),cc(z),b.current=z,S.mutateAsync()}return e.jsxs("div",{className:"grid gap-4",children:[d?e.jsx(dd,{sensors:C,collisionDetection:Qu,onDragEnd:Q,children:e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Visible boxes"}),e.jsx(Xn,{items:v.map(z=>z.id),strategy:Yn,children:e.jsx("div",{className:"grid gap-2",children:v.map((z,K)=>{const $=x.widgets[z.id]??{hidden:!1,fullWidth:!1,titleVisible:!0,descriptionVisible:!0};return e.jsx(T8,{widget:z,preferences:$,index:K,total:v.length,onMove:D=>R(z.id,D),onToggleHidden:()=>j(z.id,{hidden:!0}),onToggleFullWidth:()=>j(z.id,{fullWidth:!$.fullWidth})},z.id)})})}),H.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"pt-2 text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Hidden boxes"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:H.map(z=>e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.06] px-3 py-2 text-sm text-white/76 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>j(z.id,{hidden:!1}),children:z.title},z.id))})]}):null]})}):null,e.jsxs("div",{ref:A,className:"relative",children:[e.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 flex max-w-[calc(100%-1.5rem)] flex-wrap items-center justify-end gap-1.5",children:e.jsxs("div",{className:"pointer-events-auto flex flex-wrap items-center justify-end gap-1.5",children:[i,d?e.jsxs(W,{type:"button",size:"sm",variant:"secondary",className:"h-8 rounded-full border-white/10 bg-[rgba(30,39,69,0.82)] px-2.5 text-[12px] text-white/78 backdrop-blur-xl hover:bg-[rgba(37,47,81,0.94)] hover:text-white",onClick:X,children:[e.jsx(Tg,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Reset"})]}):null,e.jsxs(W,{type:"button",size:"sm",variant:d?"primary":"secondary",className:te("h-8 rounded-full px-2.5 text-[12px] backdrop-blur-xl",d?"bg-[var(--primary)] text-slate-950 hover:opacity-95":"border-white/10 bg-[rgba(30,39,69,0.82)] text-white/78 hover:bg-[rgba(37,47,81,0.94)] hover:text-white"),onClick:()=>m(z=>!z),children:[e.jsx(Fv,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:d?"Done":"Layout"})]})]})}),e.jsx("div",{className:"surface-flow-grid",style:{display:"grid",gap:"16px",gridTemplateColumns:`repeat(${N}, minmax(0, 1fr))`,alignItems:"start"},children:v.map(z=>{const K=x.widgets[z.id]??{hidden:!1,fullWidth:!1,titleVisible:!0,descriptionVisible:!0},$=K.fullWidth?N:Math.min(j8(z,y),N);return e.jsx("div",{style:{gridColumn:`span ${$} / span ${$}`},children:e.jsx(C8,{definition:z,preferences:K,editing:d,width:$,children:e.jsx(X5,{boxId:z.workbenchBoxId??`surface:${t}:${z.id}`,surfaceId:t,children:z.render({compact:$<=4,width:$,editing:d,preferences:K})})})},z.id)})})]})]})}function Td({surfaceId:t,baseWidgets:s,actions:a,normalizeLayout:i}){return e.jsx(P8,{surfaceId:t,widgets:s,normalizeLayout:i,actions:e.jsxs(e.Fragment,{children:[a,e.jsxs(Je,{to:`/workbench?surface=${encodeURIComponent(t)}`,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-white/10 bg-[rgba(32,40,70,0.78)] px-2.5 text-[12px] font-medium text-white/78 backdrop-blur-xl transition hover:border-white/16 hover:bg-[rgba(40,49,82,0.9)] hover:text-white",children:[e.jsx(og,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Workbench"})]})]})})}function Rw({eyebrow:t,title:s,description:a,items:i,tone:r="core",className:n}){return e.jsxs("section",{className:te("min-w-0 overflow-hidden rounded-[28px] border border-white/6 shadow-[0_20px_54px_rgba(4,8,18,0.24)]",r==="core"?"bg-[linear-gradient(180deg,rgba(22,28,46,0.98),rgba(12,17,30,0.95))]":"bg-[linear-gradient(180deg,rgba(16,29,33,0.98),rgba(12,22,27,0.95))]",n),children:[e.jsxs("div",{className:te("grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:px-5",r==="core"?"bg-[radial-gradient(circle_at_top_right,rgba(192,193,255,0.12),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]":"bg-[radial-gradient(circle_at_top_right,rgba(110,231,183,0.1),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]"),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:te("font-label text-[11px] uppercase tracking-[0.2em]",r==="core"?"text-[var(--secondary)]":"text-[rgba(110,231,183,0.82)]"),children:t}),e.jsx("h2",{className:"mt-2 max-w-3xl font-display text-[clamp(1.35rem,2vw,1.9rem)] leading-none text-white",children:s}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:a})]}),e.jsx("div",{className:"grid min-w-0 gap-2 sm:grid-cols-3",children:i.slice(0,3).map(l=>l.href?e.jsxs(Je,{to:l.href,className:te("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm transition hover:bg-white/[0.08]",r==="core"?"bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.025))]":"bg-[linear-gradient(180deg,rgba(110,231,183,0.08),rgba(255,255,255,0.02))]"),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-1.5 min-w-0 font-medium text-white",children:l.title})]},l.id):e.jsxs("div",{className:te("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm",r==="core"?"bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.025))]":"bg-[linear-gradient(180deg,rgba(110,231,183,0.08),rgba(255,255,255,0.02))]"),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-1.5 min-w-0 font-medium text-white",children:l.title})]},l.id))})]}),e.jsx("div",{className:"grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-2 lg:px-5",children:i.map((l,o)=>{const d=te("group flex min-h-[13.5rem] min-w-0 flex-col overflow-hidden rounded-[24px] border border-white/7 p-0 transition hover:-translate-y-0.5 hover:shadow-[0_22px_46px_rgba(3,8,18,0.28)] sm:min-h-[15.5rem]",r==="core"?"bg-[linear-gradient(180deg,rgba(19,26,42,0.98),rgba(11,16,28,0.96))] hover:border-white/12 hover:bg-[linear-gradient(180deg,rgba(24,31,50,0.98),rgba(13,19,33,0.97))]":"bg-[linear-gradient(180deg,rgba(17,29,32,0.98),rgba(9,18,22,0.97))] hover:border-white/12 hover:bg-[linear-gradient(180deg,rgba(21,36,40,0.98),rgba(11,22,27,0.97))]"),m=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:te("flex min-w-0 flex-1 flex-col p-4",r==="core"?"bg-[radial-gradient(circle_at_top_left,rgba(192,193,255,0.1),transparent_28%),linear-gradient(180deg,rgba(255,255,255,0.025),rgba(255,255,255,0))]":"bg-[radial-gradient(circle_at_top_left,rgba(110,231,183,0.08),transparent_28%),linear-gradient(180deg,rgba(255,255,255,0.025),rgba(255,255,255,0))]"),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-2.5 min-w-0 font-display text-[1.25rem] leading-tight text-white sm:text-[1.4rem]",children:l.title})]}),l.badge?e.jsx(I,{wrap:!0,className:"max-w-[10rem] shrink-0 self-start bg-white/[0.08] text-white/72",children:l.badge}):null]}),e.jsx("div",{className:"mt-2.5 text-sm leading-6 text-white/60",children:l.detail}),e.jsx("div",{className:"flex-1"})]}),l.href?e.jsx("div",{className:"border-t border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0.01))] px-4 py-3",children:e.jsxs("div",{className:"inline-flex min-h-10 min-w-0 max-w-full items-center gap-2 rounded-full border border-white/8 bg-white/[0.05] px-4 text-sm text-white/68 transition group-hover:border-white/14 group-hover:bg-white/[0.08] group-hover:text-white",children:[l.actionLabel??"Open",e.jsx(ha,{className:"size-3.5"})]})}):null]});return e.jsx(Ts.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.22,delay:.04*o,ease:"easeOut"},children:l.href?e.jsx(Je,{to:l.href,className:d,children:m}):e.jsx("div",{className:d,children:m})},l.id)})})]})}function A8(t){const s=["summary","body-signals","signals"],a=[...t.order];let i=!1;for(const d of s)a.includes(d)||(a.push(d),i=!0);const r=a.indexOf("summary"),n=a.indexOf("body-signals"),l=a.indexOf("signals");if(r===-1||n===-1||l===-1)return i?{...t,order:a}:t;if(r<n&&n<l&&!i)return t;for(const d of s){const m=a.indexOf(d);m!==-1&&a.splice(m,1)}const o=a.indexOf("goals");return a.splice(o===-1?0:o,0,...s),{...t,order:a}}function M8(t=new Date){const s=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${s}-${a}-${i}`}function Xl(t){if(t>=3600){const s=t/3600;return s>=10||Number.isInteger(s)?`${Math.round(s)}h`:`${s.toFixed(1)}h`}return`${Math.max(1,Math.round(t/60))}m`}function E8(t){return t>=1e3?`${(t/1e3).toFixed(1)} km`:`${Math.round(t)} m`}function L8(t){if(!t)return[];const s=new Map;for(const a of t.segments){if(a.kind!=="stay"||a.durationSeconds<=0)continue;const i=a.label.trim()||"Unlabeled stay";s.set(i,(s.get(i)??0)+a.durationSeconds)}return[...s.entries()].map(([a,i])=>({label:a,seconds:i})).sort((a,i)=>i.seconds-a.seconds).slice(0,3)}function D8(t){return t?["restingHeartRate","heartRateVariabilitySDNN","vo2Max","oxygenSaturation"].map(a=>t.metrics.find(i=>i.metric===a)).filter(a=>!!a).slice(0,3):[]}function F8(t){if(t.latestValue==null)return"No reading";const s=t.unit==="steps"||t.unit==="flights"||t.unit==="kcal"||t.unit==="min"?0:1;return`${t.latestValue.toLocaleString(void 0,{maximumFractionDigits:s,minimumFractionDigits:s===0||t.latestValue>=100?0:1})} ${t.unit}`}function _8(){var R,Q;const{t}=Ot(),s=jt(),a=s.snapshot,i=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],r=M8(),n=Fe({queryKey:["forge-overview-sleep",...i],queryFn:async()=>(await tm(i)).sleep})??{},l=Fe({queryKey:["forge-overview-fitness",...i],queryFn:async()=>(await cf(i)).fitness})??{},o=Fe({queryKey:["forge-overview-movement-day",r,...i],queryFn:async()=>(await mf({date:r,userIds:i})).movement})??{},d=Fe({queryKey:["forge-overview-vitals",...i],queryFn:async()=>(await uf(i)).vitals})??{},m=a.dashboard.milestoneRewards.find(X=>!X.completed)??a.dashboard.milestoneRewards[0]??null,h=a.overview.topTasks[0]??null,u=a.overview.dueHabits[0]??null,x=a.overview.neglectedGoals[0]??null,g=a.overview.recentEvidence[0]??null,p=new Map(a.projects.map(X=>[X.id,X])),f=a.metrics.momentumScore>=80?"Strong":a.metrics.momentumScore>=60?"Steady":"Needs attention",b=((R=n.data)==null?void 0:R.summary)??null,A=((Q=l.data)==null?void 0:Q.summary)??null,C=o.data,T=d.data??null,w=D8(T??void 0),S=L8(C),y=b!==null||A!==null||T!==null,N=C!==void 0&&(C.summary.tripCount>0||C.summary.stayCount>0||C.summary.totalMovingSeconds>0||S.length>0),P=a.lifeForce!==void 0||a.overview.activeGoals.length>0||a.overview.projects.length>0||a.overview.topTasks.length>0||a.overview.recentEvidence.length>0||a.overview.dueHabits.length>0||a.overview.neglectedGoals.length>0||n.isLoading||l.isLoading||o.isLoading||d.isLoading||y||N,v=a.lifeForce?[{label:"Life Force",value:`${Math.round(a.lifeForce.spentTodayAp)} / ${Math.round(a.lifeForce.dailyBudgetAp)} AP`,detail:`Remaining ${St(a.lifeForce.remainingAp)}`},{label:"Momentum",value:`${a.metrics.momentumScore}`,detail:`${f} · ${a.metrics.streakDays} day streak`},{label:"Instant",value:Kt(a.lifeForce.instantFreeApPerHour),detail:a.lifeForce.overloadApPerHour>0?`${Kt(a.lifeForce.overloadApPerHour)} overload`:"Headroom right now"},{label:"Level",value:`L${a.metrics.level}`,detail:`${a.metrics.currentLevelXp} XP in level`},{label:"Weekly XP",value:`${a.metrics.weeklyXp}`,detail:`${a.metrics.totalXp} total XP`}]:[{label:"Level",value:`L${a.metrics.level}`,detail:`${a.metrics.currentLevelXp} XP in level`},{label:"Weekly XP",value:`${a.metrics.weeklyXp}`,detail:`${a.metrics.totalXp} total XP`},{label:"Momentum",value:`${a.metrics.momentumScore}`,detail:`${f} · ${a.metrics.streakDays} day streak`}];function H(X){return X.entityType==="goal"?`/goals/${X.entityId}`:X.entityType==="project"?`/projects/${X.entityId}`:X.entityType==="task"?`/tasks/${X.entityId}`:X.entityType==="habit"?"/habits":X.entityType==="task_run"&&typeof X.metadata.taskId=="string"?`/tasks/${X.metadata.taskId}`:`/activity?eventId=${X.id}`}if(!P)return e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsx(nt,{title:"Overview",titleText:"Overview",description:"See your main goals, active projects, top tasks, and recent activity in one place.",badge:"0 live signals"}),e.jsx(Bt,{eyebrow:t("common.overview.heroEyebrow"),title:t("common.overview.emptyTitle"),description:t("common.overview.emptyDescription"),action:e.jsx(Je,{to:"/goals",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium whitespace-nowrap text-slate-950 transition hover:opacity-90",children:t("common.overview.emptyAction")})})]});const j=[{id:"hero",title:"Overview",description:"The route header stays movable like any other surface block.",defaultWidth:12,defaultHeight:2,removable:!1,minHeight:2,maxHeight:3,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(nt,{title:"Overview",titleText:"Overview",description:`${f}. Life Force, momentum, XP, goals, active projects, and top tasks all start here.`,badge:`Momentum ${a.metrics.momentumScore}`})},{id:"summary",title:"Momentum summary",description:"Smaller titles and denser metrics free space for the widgets themselves.",defaultWidth:12,defaultHeight:4,minWidth:6,render:({compact:X})=>e.jsxs("div",{className:"grid h-full gap-3 xl:grid-cols-[minmax(0,1.4fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Momentum summary"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:"Core live metrics"}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/56",children:"Life Force, momentum, XP, and instant headroom stay grouped here so the title bar can stay clean."})]}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:f})]}),e.jsx("div",{className:te("mt-4 grid gap-3",X?"grid-cols-2":"sm:grid-cols-2 xl:grid-cols-5"),children:v.map(Y=>e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-white/40",children:Y.label}),e.jsx("div",{className:"mt-1 text-lg font-semibold text-white",children:Y.value}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/54",children:Y.detail})]},Y.label))})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Goal needing attention"}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:(x==null?void 0:x.risk)??"stable"})]}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:(x==null?void 0:x.title)??"No goal is drifting hard right now"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(x==null?void 0:x.summary)??`Only ${a.overview.strategicHeader.overdueTasks} overdue task${a.overview.strategicHeader.overdueTasks===1?"":"s"} are slowing the system.`})]})]})},{id:"life-force",title:"Life Force",description:"Dynamic Action Points, the editable capacity curve, current drains, and stat growth all live here.",defaultWidth:12,defaultHeight:7,minWidth:6,render:()=>a.lifeForce?e.jsx(Aw,{selectedUserIds:i,fallbackLifeForce:a.lifeForce,onRefresh:s.refresh,showEditor:!1}):e.jsx(ce,{className:"rounded-[24px] border-white/8 bg-white/[0.04] p-5 text-sm leading-6 text-white/60",children:"Life Force is not configured for this user yet. Once a profile exists, the full capacity curve, drains, and recommendations will appear here."})},{id:"body-signals",title:"Life, health, movement",description:"Health imports and movement context make the overview feel like a real daily operating page.",defaultWidth:12,defaultHeight:4,minWidth:6,render:()=>e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-3",children:[e.jsxs(ce,{className:"rounded-[24px] border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Life Force"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:a.lifeForce?`${Math.round(a.lifeForce.remainingAp)} AP remaining`:"No Life Force profile yet"})]}),a.lifeForce?e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:Kt(a.lifeForce.instantFreeApPerHour)}):null]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:a.lifeForce?`${Math.round(a.lifeForce.spentTodayAp)} / ${Math.round(a.lifeForce.dailyBudgetAp)} AP spent today. Remaining ${St(a.lifeForce.remainingAp)} with ${Kt(a.lifeForce.currentDrainApPerHour)} current drain.`:"Once Life Force is configured, this block will show today's budget, remaining headroom, and live drain."})]}),e.jsxs(ce,{className:"rounded-[24px] border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Body signals"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:y?"Recovery, training, and vitals":"No health data yet"})]}),T?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[T.summary.metricCount," metrics"]}):null]}),n.isLoading||l.isLoading||d.isLoading?e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Loading recent sleep, workout, and body-signal metrics…"}):y?e.jsxs("div",{className:"mt-3 grid gap-2 text-sm text-white/72",children:[b?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:"Average sleep"}),e.jsx("span",{className:"font-medium text-white",children:Xl(b.averageSleepSeconds)})]}):null,b?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:"Sleep score"}),e.jsx("span",{className:"font-medium text-white",children:Math.round(b.averageSleepScore)})]}):null,A?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:"Exercise"}),e.jsxs("span",{className:"font-medium text-white",children:[Math.round(A.exerciseMinutes)," min"]})]}):null,A?e.jsx("div",{className:"text-xs leading-5 text-white/54",children:A.topWorkoutType?`${A.topWorkoutType} is the top workout type right now.`:"Workout imports are available when Apple Health or habit-generated sessions exist."}):null,w.length>0?e.jsx("div",{className:"mt-1 grid gap-2",children:w.map(X=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-[14px] border border-white/8 bg-white/[0.03] px-3 py-2",children:[e.jsx("span",{children:X.label}),e.jsx("span",{className:"font-medium text-white",children:F8(X)})]},X.metric))}):null]}):e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Sleep, workout, and vitals summaries appear here as soon as Forge has recent HealthKit records."})]}),e.jsxs(ce,{className:"rounded-[24px] border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Movement"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:N?"Today's place balance":"No movement timeline yet"})]}),N?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Xl((C==null?void 0:C.summary.totalMovingSeconds)??0)," moving"]}):null]}),o.isLoading?e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Loading today's stays, trips, and place balance…"}):N?e.jsxs("div",{className:"mt-3 grid gap-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[S.map(X=>e.jsxs(I,{className:"bg-white/[0.08] text-white/78",children:[Xl(X.seconds)," at ",X.label]},X.label)),((C==null?void 0:C.summary.totalMovingSeconds)??0)>0?e.jsxs(I,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[Xl((C==null?void 0:C.summary.totalMovingSeconds)??0)," moving"]}):null]}),e.jsxs("div",{className:"text-sm leading-6 text-white/58",children:[(C==null?void 0:C.summary.tripCount)??0," trip",((C==null?void 0:C.summary.tripCount)??0)===1?"":"s"," and"," ",E8((C==null?void 0:C.summary.totalDistanceMeters)??0)," tracked today."]})]}):e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Movement summaries appear here once the companion has synced stays, trips, or known places."})]})]})},{id:"signals",title:"Action signals",description:"Direct links to the next things worth opening.",defaultWidth:7,defaultHeight:4,minWidth:4,render:()=>e.jsx(Rw,{eyebrow:"Actions",title:"Open what matters now",description:"These cards stay compact by default so the page can fit more live context at once.",items:[{id:"top-task",label:h?"Top task":u?"Due habit":"Recovery lane",title:(h==null?void 0:h.title)??(u==null?void 0:u.title)??"Get a real task moving",detail:(h==null?void 0:h.description)||(u==null?void 0:u.description)||"There is no single top task yet, so use this surface to choose one clean next move.",badge:h?`${h.points} xp`:u?`${u.rewardXp} xp`:`${a.metrics.weeklyXp} weekly xp`,href:h?`/tasks/${h.id}`:u?"/habits":"/today",actionLabel:h?"Open task":u?"Open habits":"Open today"},{id:"reward",label:"Next reward",title:(m==null?void 0:m.title)??"Keep the streak alive",detail:(m==null?void 0:m.progressLabel)??`Level ${a.metrics.level} is active. ${a.metrics.weeklyXp} weekly XP is already logged.`,badge:(m==null?void 0:m.rewardLabel)??`${a.metrics.comboMultiplier.toFixed(2)}x combo`,href:"/today",actionLabel:"Open today"},{id:"recent-activity",label:"Recent activity",title:g?kd(g):"No recent evidence",detail:g?Sd(g):"The next work closeout or note will appear here.",badge:(g==null?void 0:g.source)??"activity",href:g?H(g):"/activity",actionLabel:"Open"}]})},{id:"goals",title:"Goals",description:"Long-range direction stays visible without taking over the whole page.",defaultWidth:8,defaultHeight:5,minWidth:4,render:({compact:X})=>e.jsx("div",{className:"grid gap-3",children:a.overview.activeGoals.slice(0,X?2:4).map(Y=>{var z;return e.jsxs(Je,{to:`/goals/${Y.id}`,className:"rounded-[20px] bg-white/[0.04] p-4 transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx(We,{kind:"goal",label:((z=Y.tags[0])==null?void 0:z.name)??Y.horizon,compact:!0,gradient:!1}),e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:[Y.progress,"%"]})]}),e.jsx("div",{className:"mt-3",children:e.jsx(yt,{kind:"goal",label:Y.title,variant:"heading",size:X?"md":"lg",lines:2,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"})}),X?null:e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:Y.description}),e.jsx("div",{className:"mt-3",children:e.jsx(xa,{value:Y.progress})}),e.jsx("div",{className:"mt-3",children:e.jsx(Ks,{entityType:"goal",entityId:Y.id,count:Js(a.dashboard.notesSummaryByEntity,"goal",Y.id).count})})]},Y.id)})})},{id:"pipeline",title:"Projects, habits, tasks",description:"Execution blocks can shrink while keeping the useful subtitles visible.",defaultWidth:12,defaultHeight:5,minWidth:6,render:({compact:X})=>e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-3",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Projects"}),a.overview.projects.slice(0,X?3:4).map(Y=>{var z;return e.jsxs(Je,{to:`/projects/${Y.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex min-w-0 items-center 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:Y.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:((z=p.get(Y.id))==null?void 0:z.status)??"active"})]}),e.jsxs(I,{wrap:!0,className:"max-w-[7rem] shrink-0",children:[Y.earnedPoints," xp"]})]}),X?null:e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:Y.description})]},Y.id)})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Due habits"}),a.overview.dueHabits.slice(0,X?3:4).map(Y=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:e.jsxs("div",{className:"flex min-w-0 items-center 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:Y.title}),X?null:e.jsx("div",{className:"mt-1 text-sm text-white/56",children:Y.description})]}),e.jsxs(I,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[Y.rewardXp," xp"]})]})},Y.id))]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Top tasks"}),a.overview.topTasks.slice(0,X?3:4).map(Y=>e.jsx(Je,{to:`/tasks/${Y.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex min-w-0 items-center 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:Y.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:Y.status.replaceAll("_"," ")})]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Y.points," xp"]})]})},Y.id))]})]})},{id:"time",title:"Clock",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:X})=>e.jsx(Nl,{compact:X})},{id:"weather",title:"Weather",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:X})=>e.jsx(Il,{compact:X})},{id:"mini-calendar",title:"Mini calendar",description:"Optional utility widget.",defaultWidth:4,defaultHeight:3,defaultHidden:!0,render:({compact:X})=>e.jsx(kl,{compact:X})},{id:"spotify",title:"Spotify",description:"Optional utility widget.",defaultWidth:4,defaultHeight:2,defaultHidden:!0,render:()=>e.jsx(Sl,{surfaceId:"overview"})},{id:"quick-capture",title:"Quick capture",description:"Save a standalone note or wiki draft from any dashboard.",defaultWidth:5,defaultHeight:3,defaultHidden:!0,render:({compact:X})=>{var Y;return e.jsx(Cl,{compact:X,defaultUserId:i[0]??((Y=a.users[0])==null?void 0:Y.id)??null})}}];return e.jsx(Td,{surfaceId:"overview",baseWidgets:j,normalizeLayout:A8})}const R8=[10,15,30,45,60];function Xp(){return{mode:"add",minutes:15,note:""}}function $w({open:t,onOpenChange:s,entityType:a,entityId:i,targetLabel:r,currentCreditedSeconds:n,pending:l=!1,onSubmit:o}){const[d,m]=c.useState(Xp),[h,u]=c.useState(null);c.useEffect(()=>{t&&(m(Xp()),u(null))},[t]);const x=Fe({queryKey:["forge-xp-metrics"],queryFn:ff,enabled:t}),g=c.useMemo(()=>{var T;const b=(T=x.data)==null?void 0:T.metrics.rules.find(w=>w.code==="task_run_progress"),A=Math.max(1,Number((b==null?void 0:b.config.intervalMinutes)??10)),C=Number((b==null?void 0:b.config.fixedXp)??4);return{intervalMinutes:A,fixedXp:C,intervalSeconds:A*60}},[x.data]),p=c.useMemo(()=>{const b=Math.max(0,Math.trunc(d.minutes||0)),A=d.mode==="add"?b:-b,C=Math.max(0,Math.floor(n/60)),T=A>=0?A:-Math.min(Math.abs(A),C),w=Math.max(0,n+T*60),S=Math.floor(Math.max(0,n)/g.intervalSeconds),N=Math.floor(w/g.intervalSeconds)-S;return{requestedDeltaMinutes:A,appliedDeltaMinutes:T,nextCreditedSeconds:w,bucketDelta:N,xpDelta:N*g.fixedXp,maxRemovableMinutes:C}},[g.fixedXp,g.intervalSeconds,n,d.minutes,d.mode]),f=[{id:"adjustment",eyebrow:a==="task"?"Task work":"Project work",title:`Adjust tracked work for ${r}`,description:"Use this for retrospective minute corrections. Forge will add or remove tracked minutes and adjust progress XP automatically when a reward bucket is crossed.",render:(b,A)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Mode",labelHelp:"Add minutes when work happened off-timer. Remove minutes when the tracked total needs a correction.",children:e.jsx(wt,{value:b.mode,onChange:C=>A({mode:C}),options:[{value:"add",label:"Add minutes",description:"Record extra work that already happened."},{value:"remove",label:"Remove minutes",description:"Correct tracked time without deleting the work history."}]})}),e.jsx(de,{label:"Minutes",description:`Currently tracked: ${Math.floor(n/60)} minutes.`,hint:b.mode==="remove"?`You can remove up to ${p.maxRemovableMinutes} whole minutes from the current credited total.`:void 0,children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(ye,{type:"number",min:1,className:"w-36",value:b.minutes,onChange:C=>A({minutes:Number(C.target.value)||0})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:R8.map(C=>e.jsxs(W,{type:"button",variant:b.minutes===C?"primary":"secondary",onClick:()=>A({minutes:C}),children:[C," min"]},C))})]})}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Preview"}),e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Applied minutes"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[p.appliedDeltaMinutes>0?"+":"",p.appliedDeltaMinutes]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"XP delta"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[p.xpDelta>0?"+":"",p.xpDelta]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"New tracked total"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[Math.floor(p.nextCreditedSeconds/60)," min"]})]})]}),e.jsxs("div",{className:"mt-3 text-sm leading-6 text-white/58",children:["Reward cadence: ",g.fixedXp," XP every"," ",g.intervalMinutes," credited minutes."," ",p.bucketDelta===0?"This change does not cross a reward bucket.":`This change crosses ${Math.abs(p.bucketDelta)} reward bucket${Math.abs(p.bucketDelta)===1?"":"s"}.`]})]}),e.jsx(de,{label:"Note",description:"Optional context for why this correction is being added. The note stays attached to the adjustment metadata.",children:e.jsx(Ze,{className:"min-h-28",value:b.note,onChange:C=>A({note:C.target.value}),placeholder:"Captured the review session that happened away from the live timer."})})]})}];return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:a==="task"?"Adjust task work":"Adjust project work",title:`Adjust work for ${r}`,description:"Add or remove tracked minutes without creating a live task run.",value:d,onChange:m,draftPersistenceKey:`work-adjustment.${a}.${i}`,steps:f,submitLabel:"Save adjustment",pending:l,pendingLabel:"Saving adjustment...",error:h,onSubmit:async()=>{var T;u(null);const b=Math.max(0,Math.trunc(d.minutes||0)),A=d.mode==="add"?b:-b,C=y2.safeParse({entityType:a,entityId:i,deltaMinutes:A,note:d.note});if(!C.success){u(((T=C.error.issues[0])==null?void 0:T.message)??"Enter a valid minute adjustment.");return}try{await o({entityType:a,entityId:i,deltaMinutes:C.data.deltaMinutes,note:C.data.note||void 0}),s(!1)}catch(w){u(w instanceof Error?w.message:"Could not save the work adjustment right now.")}}})}const Ow={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function $8(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean)}function uc(t,s){const a=$8(t);if(a.length===0)return!1;const i=s.join(" ").toLowerCase();return a.some(r=>i.includes(r))}function O8(t){return t.allowWorkBlockKinds.length>0||t.allowCalendarIds.length>0||t.allowEventTypes.length>0||t.allowEventKeywords.length>0||t.allowAvailability.length>0}function z8(t,s){return t??s??Ow}function zw(t){const s=t.rules??Ow,i=(t.at??new Date).getTime(),r=t.overview,n=(r==null?void 0:r.workBlockInstances.filter(x=>{const g=new Date(x.startAt).getTime(),p=new Date(x.endAt).getTime();return g<=i&&i<p}))??[],l=(r==null?void 0:r.events.filter(x=>{if(x.deletedAt)return!1;const g=new Date(x.startAt).getTime(),p=new Date(x.endAt).getTime();return g<=i&&i<p}))??[],o=[],d=n.some(x=>s.blockWorkBlockKinds.includes(x.kind))||l.some(x=>(x.calendarId?s.blockCalendarIds.includes(x.calendarId):!1)||s.blockEventTypes.includes(x.eventType)||s.blockAvailability.includes(x.availability)||uc(s.blockEventKeywords,[x.title,x.description,x.location,...x.categories]));d&&(n.some(x=>s.blockWorkBlockKinds.includes(x.kind))&&o.push("The current work block is marked as blocked."),l.some(x=>x.calendarId?s.blockCalendarIds.includes(x.calendarId):!1)&&o.push("The active calendar belongs to a blocked calendar source."),l.some(x=>s.blockEventTypes.includes(x.eventType))&&o.push("The active calendar event type is blocked."),l.some(x=>s.blockAvailability.includes(x.availability))&&o.push("The active calendar availability is blocked."),l.some(x=>uc(s.blockEventKeywords,[x.title,x.description,x.location,...x.categories]))&&o.push("The active calendar event matches a blocked keyword."));const m=O8(s),h=n.some(x=>s.allowWorkBlockKinds.includes(x.kind))||l.some(x=>(x.calendarId?s.allowCalendarIds.includes(x.calendarId):!1)||s.allowEventTypes.includes(x.eventType)||s.allowAvailability.includes(x.availability)||uc(s.allowEventKeywords,[x.title,x.description,x.location,...x.categories]));!d&&m&&!h&&o.push("The current calendar context does not match the allowed rules yet.");const u=[...n.map(x=>`${x.title} (${x.kind.replaceAll("_"," ")})`),...l.map(x=>x.title)];return o.length>0?{blocked:!0,label:"Blocked right now",tone:"blocked",conflicts:o,context:u}:u.length>0?{blocked:!1,label:"Allowed right now",tone:"allowed",conflicts:[],context:u}:{blocked:!1,label:m?"Waiting for an allowed calendar context":"No live calendar conflict right now",tone:m?"waiting":"allowed",conflicts:[],context:[]}}function K8(t,s){return z8(t.schedulingRules,s)}function q8(t){return!!(t&&t.startsWith("campaign:"))}function B8(){var _;const{t}=Ot(),s=jt(),a=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],i=Qs(),r=$t(),n=ct(),[l,o]=c.useState(!1),[d,m]=c.useState(!1),[h,u]=c.useState(!1),[x]=c.useState(()=>{const B=new Date,G=new Date(B);G.setHours(0,0,0,0);const ae=new Date(B);return ae.setHours(23,59,59,999),{from:G.toISOString(),to:ae.toISOString()}}),g=ys(a),p=s.snapshot.dashboard.projects.find(B=>B.id===i.projectId)??null,f=p?s.snapshot.goals.find(B=>B.id===p.goalId)??null:null,b=p?s.snapshot.tasks.filter(B=>B.projectId===p.id||!B.projectId&&B.goalId===p.goalId):[],A=new Set(b.map(B=>B.id)),C=p?s.snapshot.activity.filter(B=>B.entityId===p.goalId||B.entityId===p.id||A.has(B.entityId)||B.entityType==="task_run"&&typeof B.metadata.taskId=="string"&&A.has(B.metadata.taskId)):[],T=q8(i.projectId),w=Fe({queryKey:["project-board",i.projectId],queryFn:()=>VN(i.projectId),enabled:!!i.projectId&&!T}),S=Fe({queryKey:["project-calendar-overview",i.projectId,x.from,x.to,...a],queryFn:()=>Or({...x,userIds:a}),enabled:!!i.projectId&&!T}),y=Re({mutationFn:B=>nm(B),onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]})])}}),N=Re({mutationFn:lm,onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]}),n.invalidateQueries({queryKey:["forge-xp-metrics"]}),n.invalidateQueries({queryKey:["forge-reward-ledger"]}),n.invalidateQueries({queryKey:["forge-operator-context"]})])}}),P=Re({mutationFn:B=>wf(i.projectId,{status:B}),onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]}),n.invalidateQueries({queryKey:["forge-xp-metrics"]}),n.invalidateQueries({queryKey:["forge-reward-ledger"]}),n.invalidateQueries({queryKey:["forge-operator-context"]})])}}),v=Re({mutationFn:()=>fk(i.projectId),onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]})]),r("/projects")}}),H=Re({mutationFn:B=>rm(B),onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]}),n.invalidateQueries({queryKey:["task-context"]})])}}),j=w.data??(p&&f?{project:p,goal:f,tasks:b,activity:C}:void 0),R=s.snapshot.dashboard.projects.find(B=>B.id===i.projectId)??null;if(w.isError&&!T)return e.jsx(it,{eyebrow:t("common.projectDetail.errorEyebrow"),error:w.error,onRetry:()=>void w.refetch()});if(!j)return e.jsx(ls,{});const Q=j.tasks.find(B=>B.status==="focus"||B.status==="in_progress")??j.tasks[0]??null,X=j.tasks.find(B=>B.status==="blocked")??j.tasks.find(B=>B.status==="backlog")??null;j.activity[0];const Y="notesSummaryByEntity"in j?j.notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,z=P.isPending||v.isPending,K=zw({rules:j.project.schedulingRules,overview:(_=S.data)==null?void 0:_.calendar}),$=s.snapshot.strategies.filter(B=>B.targetGoalIds.includes(j.goal.id)),D=s.snapshot.strategies.filter(B=>B.targetProjectIds.includes(j.project.id)),J=async B=>{await P.mutateAsync(B)},q=async()=>{window.confirm(t("common.projectDetail.deleteProjectConfirm",{title:j.project.title}))&&await v.mutateAsync()};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Id,{}),e.jsx(nt,{entityKind:"project",title:e.jsx(yt,{kind:"project",label:j.project.title,variant:"heading",size:"lg"}),titleText:j.project.title,description:j.project.description?e.jsx(Rs,{markdown:j.project.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):"No project description yet.",badge:e.jsx(We,{kind:"goal",label:j.goal.title,compact:!0,gradient:!1}),actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Nd,{userId:g,domain:"projects",entityType:"project",entityId:j.project.id,label:j.project.title,description:j.project.description}),e.jsx(er,{entityType:"project",entityId:j.project.id})]})}),j.project.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(ot,{user:j.project.user}),j.project.assignees&&j.project.assignees.length>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-white/35",children:"Assigned with"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:j.project.assignees.map(B=>e.jsx(ot,{user:B,compact:!0},B.id))})]}):null]}):null,j.project.productRequirementsDocument?e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Product requirements document"}),e.jsx("div",{className:"mt-3",children:e.jsx(Rs,{markdown:j.project.productRequirementsDocument,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"})})]}):null,$.length>0||D.length>0?e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Strategy stack"}),e.jsxs("div",{className:"mt-3 grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/42",children:"Goal-level strategies"}),$.length===0?e.jsx("div",{className:"text-sm text-white/48",children:"No goal-level strategies linked yet."}):$.map(B=>e.jsxs(Je,{to:`/strategies/${B.id}`,className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:B.title}),e.jsx("div",{className:"mt-1 text-xs text-white/48",children:B.overview||B.endStateDescription})]},B.id))]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/42",children:"Project-level strategies"}),D.length===0?e.jsx("div",{className:"text-sm text-white/48",children:"No lower-level strategies linked yet."}):D.map(B=>e.jsxs(Je,{to:`/strategies/${B.id}`,className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:B.title}),e.jsx("div",{className:"mt-1 text-xs text-white/48",children:B.overview||B.endStateDescription})]},B.id))]})]})]}):null,T?e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.projectDetail.compatibility")}),e.jsx("p",{className:"mt-3 text-sm leading-7 text-white/60",children:t("common.projectDetail.compatibilityDescription")})]}):null,e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(W,{onClick:()=>m(!0),children:t("common.projectDetail.addTask")}),T?null:e.jsx(W,{variant:"secondary",onClick:()=>u(!0),children:"Adjust work"}),T?null:e.jsx(W,{variant:"secondary",onClick:()=>o(!0),children:t("common.projectDetail.editProject")}),!T&&j.project.status==="active"?e.jsx(W,{variant:"secondary",pending:z&&P.variables==="paused",pendingLabel:t("common.projectDetail.suspending"),onClick:()=>void J("paused"),children:t("common.projectDetail.suspendProject")}):null,!T&&j.project.status!=="completed"?e.jsx(W,{pending:z&&P.variables==="completed",pendingLabel:t("common.projectDetail.finishing"),onClick:()=>void J("completed"),children:t("common.projectDetail.finishProject")}):null,!T&&j.project.status!=="active"?e.jsx(W,{variant:"secondary",pending:z&&P.variables==="active",pendingLabel:t("common.projectDetail.restarting"),onClick:()=>void J("active"),children:t("common.projectDetail.restartProject")}):null,T?null:e.jsx(W,{variant:"ghost",pending:v.isPending,pendingLabel:t("common.projectDetail.deleting"),onClick:()=>void q(),children:t("common.projectDetail.deleteProject")}),e.jsx(Je,{to:`/goals/${j.goal.id}`,children:e.jsx(W,{variant:"ghost",children:t("common.projectDetail.openGoal")})})]}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1fr)_22rem]",children:[e.jsxs(ce,{children:[e.jsxs("div",{className:"flex flex-wrap 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/45",children:t("common.projectDetail.commandEyebrow")}),e.jsx("h2",{className:"mt-2 font-display text-[clamp(1.35rem,2vw,1.9rem)] text-white",children:t("common.projectDetail.commandTitle")}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:t("common.projectDetail.commandDescription")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(We,{kind:"project",compact:!0,gradient:!1}),e.jsx(We,{kind:"goal",label:j.goal.title,compact:!0,gradient:!1})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:[e.jsxs(Je,{to:Q?`/tasks/${Q.id}`:`/projects/${j.project.id}`,className:"rounded-[20px] bg-white/[0.04] p-4 transition hover:bg-white/[0.08]",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.projectDetail.signalNext")}),Q?e.jsx(We,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(Q==null?void 0:Q.title)??t("common.projectDetail.noNextTask")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(Q==null?void 0:Q.description)||t("common.projectDetail.noNextTaskDetail")})]}),e.jsxs(Je,{to:X?`/tasks/${X.id}`:`/projects/${j.project.id}`,className:"rounded-[20px] bg-white/[0.04] p-4 transition hover:bg-white/[0.08]",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.projectDetail.signalRisk")}),X?e.jsx(We,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(X==null?void 0:X.title)??t("common.projectDetail.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(X==null?void 0:X.description)||t("common.projectDetail.noRiskDetail")})]})]})]}),e.jsxs(ce,{className:"h-fit min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.projectDetail.sectionHealth")}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.projectStatus.${j.project.status}`)}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:j.project.momentumLabel}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(j.project.time.totalCreditedSeconds/60)," min tracked"]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",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.projectDetail.fieldProgress")}),e.jsxs("div",{className:"mt-2 font-display text-xl text-white",children:[j.project.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.projectDetail.fieldMomentum")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:j.project.momentumLabel})]}),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.projectDetail.fieldStatus")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:t(`common.enums.projectStatus.${j.project.status}`)})]}),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:"Live tasks"}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:j.tasks.filter(B=>B.status==="focus"||B.status==="in_progress").length})]})]})]})]}),T?null:e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1fr)_22rem]",children:[e.jsx(qb,{title:"Project scheduling defaults",subtitle:"Define the calendar contexts where work from this project is allowed or blocked. Tasks can inherit these defaults or override them.",initialRules:j.project.schedulingRules,saveLabel:"Save project scheduling",onSave:async({schedulingRules:B})=>{await s.patchProject(j.project.id,{schedulingRules:B}),await n.invalidateQueries({queryKey:["project-board",i.projectId]}),await n.invalidateQueries({queryKey:["project-calendar-overview",i.projectId]})}}),e.jsxs(ce,{className:"h-fit min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar status"}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:K.tone==="blocked"?"bg-rose-500/14 text-rose-100":K.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:K.label}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:"Project defaults"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"These rules act as the default calendar gate for every task in the project unless a task sets its own override."}),K.context.length>0?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Current context"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:K.context.map(B=>e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:B},B))})]}):null,K.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:K.conflicts.map(B=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:B},B))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(Je,{to:"/calendar",children:e.jsx(W,{variant:"secondary",children:"Open calendar workspace"})})})]})]}),e.jsx(uw,{tasks:j.tasks,activeRuns:s.snapshot.activeTaskRuns,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:Y,selectedTaskId:null,onMove:async(B,G)=>{await s.patchTaskStatus(B,G),await n.invalidateQueries({queryKey:["project-board",i.projectId]})},onSelectTask:B=>r(`/tasks/${B}`),onStopTask:async B=>{await s.stopTaskRun(B),await n.invalidateQueries({queryKey:["project-board",i.projectId]}),await n.invalidateQueries({queryKey:["task-context",B.taskId]})},onQuickReopenTask:async B=>{await y.mutateAsync(B)},onDeleteTask:async B=>{await H.mutateAsync(B)}}),T?null:e.jsx(jd,{entityType:"project",entityId:j.project.id,title:"Project notes",description:"Keep rollout notes, checkpoints, and cross-task context attached to the project itself.",invalidateQueryKeys:[["project-board",i.projectId]]}),e.jsxs(ce,{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.projectDetail.sectionEvidence")}),e.jsx("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:j.activity.slice(0,6).map(B=>e.jsxs(Je,{to:Ra(B)??`/activity?eventId=${B.id}`,className:"rounded-[18px] bg-white/[0.04] p-4 transition hover:bg-white/[0.08]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:kd(B)}),e.jsx(I,{children:B.source})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Sd(B)})]},B.id))})]}),e.jsx(fd,{open:l,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:R,defaultUserId:(R==null?void 0:R.userId)??g,onOpenChange:o,onSubmit:async(B,G)=>{G&&(await s.patchProject(G,B),await n.invalidateQueries({queryKey:["project-board",i.projectId]}))}}),e.jsx(bd,{open:d,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,workItems:s.snapshot.workItems,tags:s.snapshot.tags,users:s.snapshot.users,editingTask:null,initialProjectId:T?null:j.project.id,defaultUserId:j.project.userId??g,onRefreshEntities:s.refresh,onOpenChange:m,onSubmit:async(B,G)=>{G?await s.patchTask(G,B):await s.createTask(B),await n.invalidateQueries({queryKey:["project-board",i.projectId]})}}),T?null:e.jsx($w,{open:h,onOpenChange:u,entityType:"project",entityId:j.project.id,targetLabel:j.project.title,currentCreditedSeconds:j.project.time.totalCreditedSeconds,pending:N.isPending,onSubmit:async B=>{await N.mutateAsync(B)}})]})}const Li={user:"user:",kind:"kind:"},Kw=["goal","strategy","project","issue","task","subtask"],wn=[...Kw],yn=["active","paused","completed","backlog","focus","in_progress","blocked","done"];function Ii(t){return t.trim().toLowerCase()}function U8(t){return t.reduce((s,a)=>{if(a.startsWith(Li.user))s.userIds.push(a.slice(Li.user.length));else if(a.startsWith(Li.kind)){const i=a.slice(Li.kind.length);(i==="human"||i==="bot")&&s.kinds.push(i)}return s},{userIds:[],kinds:[]})}function W8(t,s){return`${s}:${Ii(t)}`}function H8(t){const s=t.trim();return s.length===0?[]:["any",...Kw].map(a=>({id:W8(s,a),query:s,kind:a}))}function G8(t){switch(t){case"done":case"completed":return 1;case"in_progress":case"active":return .66;case"focus":return .45;case"blocked":return .5;case"paused":return .28;default:return .08}}function vn(t,s){const a=t.replace(/\s+/g," ").trim();return a.length===0?s:a}function Nr(t){const s=(t.children??[]).map(Nr);if(t.kind==="project")return{...t,children:s,progressPercent:t.progressPercent,progressLabel:t.progressLabel??(typeof t.progressPercent=="number"?`${t.progressPercent}% complete`:null)};if(s.length>0){const i=s.map(r=>r.progressPercent).filter(r=>typeof r=="number");if(i.length>0){const r=Math.round(i.reduce((n,l)=>n+l,0)/i.length);return{...t,children:s,progressPercent:r,progressLabel:`${s.length} child item${s.length===1?"":"s"}`}}}const a=Math.round(G8(t.statusLabel)*100);return{...t,children:s,progressPercent:a,progressLabel:t.statusLabel?t.statusLabel.replaceAll("_"," "):null}}function Yp(t){const{goals:s,strategies:a,projects:i,workItems:r,tagNameById:n}=t,l=new Map,o=new Map,d=new Map;for(const u of r)if(u.parentWorkItemId){const x=l.get(u.parentWorkItemId)??[];x.push(u),l.set(u.parentWorkItemId,x)}else if(u.level==="issue"&&u.projectId){const x=o.get(u.projectId)??[];x.push(u),o.set(u.projectId,x)}else if(u.projectId){const x=d.get(u.projectId)??[];x.push(u),d.set(u.projectId,x)}const m=u=>{var x;return Nr({id:`${u.level}:${u.id}`,entityId:u.id,kind:u.level,label:u.title,description:vn(u.description,u.level==="issue"?"Vertical slice issue":u.level==="subtask"?"Granular child step":"Focused AI session task"),searchText:Ii([u.title,u.description,u.aiInstructions,u.executionMode??"",u.status,((x=u.user)==null?void 0:x.displayName)??"",...(u.assignees??[]).map(g=>g.displayName),...u.tagIds.map(g=>n.get(g)??"")].join(" ")),href:`/tasks/${u.id}`,statusLabel:u.status,executionMode:u.executionMode,goalId:u.goalId,projectId:u.projectId,tagIds:u.tagIds,user:u.user,assignees:u.assignees??[],linkedUserIds:[...u.user?[u.user.id]:[],...u.assigneeUserIds??[]],progressPercent:null,progressLabel:null,children:(l.get(u.id)??[]).map(m)})},h=u=>{var g;const x=a.filter(p=>p.targetProjectIds.includes(u.id));return Nr({id:`project:${u.id}`,entityId:u.id,kind:"project",label:u.title,description:vn(u.description||u.productRequirementsDocument,"PRD-backed initiative"),searchText:Ii([u.title,u.description,u.productRequirementsDocument,u.goalTitle,u.workflowStatus,u.status,((g=u.user)==null?void 0:g.displayName)??"",...(u.assignees??[]).map(p=>p.displayName)].join(" ")),href:`/projects/${u.id}`,statusLabel:u.workflowStatus,executionMode:null,goalId:u.goalId,projectId:u.id,tagIds:[],user:u.user,assignees:u.assignees??[],linkedUserIds:[...u.user?[u.user.id]:[],...u.assigneeUserIds??[]],progressPercent:u.progress,progressLabel:`${u.completedTaskCount}/${u.totalTasks} done`,children:[...x.map(p=>{var f;return Nr({id:`strategy:${p.id}`,entityId:p.id,kind:"strategy",label:p.title,description:vn(p.overview||p.endStateDescription,"Execution strategy"),searchText:Ii([p.title,p.overview,p.endStateDescription,p.status,((f=p.user)==null?void 0:f.displayName)??""].join(" ")),href:`/strategies/${p.id}`,statusLabel:p.status,executionMode:null,goalId:u.goalId,projectId:u.id,tagIds:[],user:p.user,assignees:[],linkedUserIds:p.user?[p.user.id]:[],progressPercent:null,progressLabel:null,children:[]})}),...(o.get(u.id)??[]).map(m),...(d.get(u.id)??[]).map(m)]})};return s.map(u=>{var C,T;const x=i.filter(w=>w.goalId===u.id),g=a.filter(w=>w.targetGoalIds.includes(u.id)),p=new Map(g.map(w=>[w.id,[]])),f=new Set;for(const w of x){const S=g.find(y=>y.targetProjectIds.includes(w.id));S&&((C=p.get(S.id))==null||C.push(w),f.add(w.id))}const b=g.map(w=>{var S;return Nr({id:`strategy:${w.id}`,entityId:w.id,kind:"strategy",label:w.title,description:vn(w.overview||w.endStateDescription,"High-level strategy"),searchText:Ii([w.title,w.overview,w.endStateDescription,w.status,((S=w.user)==null?void 0:S.displayName)??""].join(" ")),href:`/strategies/${w.id}`,statusLabel:w.status,executionMode:null,goalId:u.id,projectId:null,tagIds:[],user:w.user,assignees:[],linkedUserIds:w.user?[w.user.id]:[],progressPercent:null,progressLabel:null,children:(p.get(w.id)??[]).map(h)})}),A=x.filter(w=>!f.has(w.id)).map(h);return Nr({id:`goal:${u.id}`,entityId:u.id,kind:"goal",label:u.title,description:vn(u.description,"Strategic goal"),searchText:Ii([u.title,u.description,u.status,((T=u.user)==null?void 0:T.displayName)??""].join(" ")),href:`/goals/${u.id}`,statusLabel:u.status,executionMode:null,goalId:u.id,projectId:null,tagIds:u.tagIds,user:u.user,assignees:[],linkedUserIds:u.user?[u.user.id]:[],progressPercent:null,progressLabel:null,children:[...b,...A]})})}function qw(t){return t.reduce((s,a)=>s+1+qw(a.children??[]),0)}function Q8(t,s){return t.searchText.includes(Ii(s.query))&&(s.kind==="any"||s.kind===t.kind)}function Bw(t,s,a=!1){const{clauses:i,statusFilters:r,ownerUserIds:n,ownerKinds:l,selectedUserIds:o}=s,d=i.length===0||i.some(f=>Q8(t,f)),m=r.length===0||t.statusLabel!==null&&r.includes(t.statusLabel),h=n.length===0&&o.length===0?!0:[...n,...o].some(f=>t.linkedUserIds.includes(f)),u=l.length===0||[t.user,...t.assignees].some(f=>f&&l.includes(f.kind)),x=m&&h&&u,g=i.length===0||a||d,p=(t.children??[]).map(f=>Bw(f,s,a||x&&d)).filter(f=>f!==null);return x&&g||p.length>0?{...t,children:p}:null}function Uw(t,s){return t.flatMap(a=>{const i=Uw(a.children??[],s);return s.includes(a.kind)?[{...a,children:i}]:i})}function V8(t){switch(t){case"goal":return"bg-amber-400/12 text-amber-100";case"strategy":return"bg-cyan-400/12 text-cyan-100";case"project":return"bg-sky-400/12 text-sky-100";case"issue":return"bg-orange-400/12 text-orange-100";case"subtask":return"border-indigo-300/18 bg-indigo-400/12 text-indigo-100";default:return"bg-indigo-400/12 text-indigo-100"}}function mc(t){switch(t){case"done":case"completed":return"bg-emerald-400/12 text-emerald-100";case"blocked":return"bg-rose-400/12 text-rose-100";case"in_progress":case"active":return"bg-sky-400/12 text-sky-100";case"focus":return"bg-violet-400/12 text-violet-100";default:return"bg-white/[0.08] text-white/70"}}function Jp(t){return t==="any"?e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:"Any"}):t==="subtask"?e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"}):e.jsx(We,{kind:t==="issue"?"issue":t,label:t,compact:!0,gradient:!1})}function X8({query:t,onQueryChange:s,clauses:a,onClausesChange:i,resultSummary:r}){const[n,l]=c.useState(!1),[o,d]=c.useState(0),m=c.useMemo(()=>H8(t).filter(x=>!a.some(g=>g.id===x.id)),[a,t]),h=x=>{i([...a,x]),s(""),d(0),l(!1)},u=x=>{i(a.filter(g=>g.id!==x))};return e.jsx("div",{className:"grid gap-3",children:e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,28,48,0.9),rgba(10,14,26,0.98))] p-4 shadow-[0_30px_80px_rgba(3,8,18,0.28)] sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Hierarchy search"}),e.jsxs("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/62",children:["Build OR clauses like ",e.jsx("span",{className:"text-white",children:'Goal + "MD"'})," or ",e.jsx("span",{className:"text-white",children:'Any + "Happy"'}),". Matching ancestors keep their branches visible so you can explore the hierarchy, not lose it."]})]}),a.length>0||t.trim().length>0?e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{s(""),i([]),d(0),l(!1)},children:"Clear search"}):null]}),e.jsxs("div",{className:"mt-4 rounded-[24px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[a.length>0?e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:a.map(x=>e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[Jp(x.kind),e.jsxs("span",{className:"max-w-[14rem] truncate text-sm text-white/78",children:['"',x.query,'"']}),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>u(x.id),"aria-label":`Remove ${x.kind} ${x.query}`,children:e.jsx(Tt,{className:"size-3.5"})})]},x.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/36"}),e.jsx("input",{value:t,onChange:x=>{s(x.target.value),l(!0),d(0)},onFocus:()=>l(!0),onBlur:()=>{window.setTimeout(()=>l(!1),120)},onKeyDown:x=>{if(x.key==="Backspace"&&!t&&a.length>0){u(a[a.length-1].id);return}if(x.key==="ArrowDown"){x.preventDefault(),l(!0),d(g=>m.length===0?0:Math.min(m.length-1,g+1));return}if(x.key==="ArrowUp"){x.preventDefault(),d(g=>Math.max(0,g-1));return}if(x.key==="Escape"){l(!1);return}x.key==="Enter"&&m[o]&&(x.preventDefault(),h(m[o]))},placeholder:'Type text, then pick a clause like Goal + "MD" or Any + "Happy"',className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),n?e.jsx("div",{className:"absolute top-full z-20 mt-2 w-full rounded-[22px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:m.length>0?m.map((x,g)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",g===o?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>d(g),onMouseDown:p=>p.preventDefault(),onClick:()=>h(x),children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Jp(x.kind),e.jsxs("span",{className:"truncate text-sm font-medium text-white",children:['"',x.query,'"']})]}),e.jsxs("div",{className:"mt-1 text-xs leading-5 text-white/46",children:["Match ",x.kind==="any"?"any visible hierarchy node":`${x.kind} nodes`," that mention this text."]})]})},x.id)):e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:"Type a word or phrase to create a new OR clause."})}):null]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/52",children:r})]})})}function Y8(){const t=jt(),s=c.useRef(null),[a,i]=c.useState(""),[r,n]=c.useState([]),[l,o]=c.useState([]),[d,m]=c.useState([...yn]),[h,u]=c.useState(wn),x=Fe({queryKey:["work-items-hierarchy",...t.selectedUserIds],queryFn:()=>XN({userIds:t.selectedUserIds})}),g=c.useMemo(()=>{const N=t.snapshot.users.filter(v=>v.kind==="bot"),P=t.snapshot.users.filter(v=>v.kind==="human");return[{value:`${Li.kind}bot`,label:"Bots",description:`${N.length} bot collaborators`,searchText:`bots bot ai agents assistants ${N.map(v=>`${v.displayName} ${v.handle}`).join(" ")}`,badge:e.jsx(I,{className:"border-cyan-300/18 bg-cyan-400/12 text-cyan-50",children:"Bots"}),menuBadge:e.jsx(I,{className:"border-cyan-300/18 bg-cyan-400/12 text-cyan-50",children:"Bots"})},{value:`${Li.kind}human`,label:"Humans",description:`${P.length} human collaborators`,searchText:`humans human people operators ${P.map(v=>`${v.displayName} ${v.handle}`).join(" ")}`,badge:e.jsx(I,{className:"border-amber-300/18 bg-amber-400/12 text-amber-50",children:"Humans"}),menuBadge:e.jsx(I,{className:"border-amber-300/18 bg-amber-400/12 text-amber-50",children:"Humans"})},...t.snapshot.users.map(v=>({value:`${Li.user}${v.id}`,label:v.displayName,description:`${v.kind}${v.handle?` · @${v.handle}`:""}`,searchText:`${v.displayName} ${v.handle} ${v.kind} ${v.description}`,badge:e.jsx(ot,{user:v,compact:!0}),menuBadge:e.jsx(ot,{user:v,compact:!0})}))]},[t.snapshot.users]),p=c.useMemo(()=>[{value:"goal",label:"Goal",searchText:"goal direction objective",kind:"goal"},{value:"strategy",label:"Strategy",searchText:"strategy plan sequencing",kind:"strategy"},{value:"project",label:"Project",searchText:"project initiative prd",kind:"project"},{value:"issue",label:"Issue",searchText:"issue vertical slice tracer bullet",kind:"issue"},{value:"task",label:"Task",searchText:"task execution ai session",kind:"task"},{value:"subtask",label:"Subtask",searchText:"subtask child step",badge:e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"}),menuBadge:e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"})}],[]),f=c.useMemo(()=>[{value:"active",label:"Active",searchText:"active in progress live"},{value:"paused",label:"Paused",searchText:"paused suspended"},{value:"completed",label:"Completed",searchText:"completed finished"},{value:"backlog",label:"Backlog",searchText:"backlog queued"},{value:"focus",label:"Focus",searchText:"focus ready"},{value:"in_progress",label:"In progress",searchText:"in progress active doing"},{value:"blocked",label:"Blocked",searchText:"blocked stuck"},{value:"done",label:"Done",searchText:"done complete finished"}].map(N=>({...N,badge:e.jsx(I,{className:mc(N.value),children:N.label}),menuBadge:e.jsx(I,{className:mc(N.value),children:N.label})})),[]),b=c.useMemo(()=>new Map(t.snapshot.tags.map(N=>[N.id,N.name])),[t.snapshot.tags]),A=c.useMemo(()=>x.data?Yp({...x.data,tagNameById:b}):Yp({goals:t.snapshot.goals,strategies:t.snapshot.strategies,projects:t.snapshot.dashboard.projects,tagNameById:b,workItems:t.snapshot.workItems&&t.snapshot.workItems.length>0?t.snapshot.workItems:t.snapshot.tasks}),[x.data,t.snapshot,b]),C=a.trim().length>0||r.length>0||l.length>0||d.length!==yn.length||yn.some(N=>!d.includes(N))||h.length!==wn.length||wn.some(N=>!h.includes(N)),T=c.useMemo(()=>U8(l),[l]),w=c.useMemo(()=>{const N=A.map(P=>Bw(P,{clauses:r,statusFilters:d,ownerUserIds:T.userIds,ownerKinds:T.kinds,selectedUserIds:t.selectedUserIds})).filter(P=>P!==null);return Uw(N,h)},[A,T.kinds,T.userIds,r,d,t.selectedUserIds,h]),S=c.useMemo(()=>qw(w),[w]),y=`${r.length>0?`${r.length} OR clause${r.length===1?"":"s"} active`:"Search across the full hierarchy"} · ${S} visible node${S===1?"":"s"}.`;return x.isLoading&&A.length===0?e.jsx(Et,{eyebrow:"Hierarchy",title:"Building Forge hierarchy",description:"Loading goals, strategies, projects, issues, tasks, and subtasks into the compact hierarchy view."}):x.isError&&A.length===0?e.jsx(it,{eyebrow:"Hierarchy",error:x.error,onRetry:()=>void x.refetch()}):e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Id,{}),e.jsx(nt,{title:"Hierarchy",description:"Explore the full Forge stack from goal to subtask in one compact operational tree, with both strategy layers visible and the same control surfaces as the board.",badge:`${S} visible nodes`}),e.jsxs(ce,{className:"min-w-0 overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(16,23,38,0.92),rgba(9,14,24,0.98))]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 border-b border-white/8 px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Hierarchy controls"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:"Filter across goals, projects, tags, humans, bots, and work-item types, then expand or collapse the full tree without losing the hierarchy context."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{var N,P;return(P=(N=s.current)==null?void 0:N.openAll)==null?void 0:P.call(N)},children:"Expand all"}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{var N,P;return(P=(N=s.current)==null?void 0:N.closeAll)==null?void 0:P.call(N)},children:"Collapse all"}),C?e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{i(""),n([]),o([]),m([...yn]),u(wn)},children:"Reset"}):null]})]}),e.jsxs("div",{className:"grid gap-4 px-5 py-5",children:[e.jsx(X8,{query:a,onQueryChange:i,clauses:r,onClausesChange:n,resultSummary:y}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsx(mt,{options:f,selectedValues:d,onChange:N=>m(N),placeholder:"Visible states",emptyMessage:"No states available.",variant:"action-bar"}),e.jsx(mt,{options:p,selectedValues:h,onChange:N=>u(N),placeholder:"Visible levels",emptyMessage:"No hierarchy levels.",className:"min-w-0",variant:"action-bar"}),e.jsx(mt,{options:g,selectedValues:l,onChange:o,placeholder:"Filter by human, bot, or collaborator",emptyMessage:"No matching collaborators."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[w.length," top-level nodes"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[S," visible nodes"]}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:h.join(" + ")})]})]})]}),w.length===0?e.jsx(Bt,{eyebrow:"Hierarchy",title:"No hierarchy nodes match the current filters",description:"Clear some filters or broaden the search to bring the full planning ladder back into view.",action:e.jsx(W,{variant:"secondary",onClick:()=>{i(""),n([]),o([]),m([...yn]),u(wn)},children:"Reset hierarchy filters"})}):e.jsxs(ce,{className:"min-w-0 overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(13,20,31,0.96),rgba(9,15,24,0.98))] p-0",children:[e.jsxs("div",{className:"grid grid-cols-[minmax(0,1.8fr)_auto_auto_auto] gap-3 border-b border-white/8 px-5 py-3 text-[11px] uppercase tracking-[0.18em] text-white/38",children:[e.jsx("div",{children:"Name"}),e.jsx("div",{className:"hidden lg:block",children:"State"}),e.jsx("div",{className:"hidden xl:block",children:"People"}),e.jsx("div",{className:"hidden lg:block",children:"Progress"})]}),e.jsx("div",{className:"p-2",children:e.jsx(zv,{ref:s,data:w,width:"100%",height:760,rowHeight:64,overscanCount:10,childrenAccessor:N=>N.children??null,openByDefault:!0,paddingTop:8,paddingBottom:8,disableDrag:!0,className:"text-sm",children:({node:N,style:P})=>{const v=N.data.kind==="subtask"?"task":N.data.kind,H=zs(v),j=H.colorToken.rgb.join(", ");return e.jsx("div",{style:P,className:"px-2 py-1.5",children:e.jsxs("div",{className:te("grid min-w-0 items-center gap-3 rounded-[16px] border border-white/8 px-3 py-2 transition hover:border-white/14 hover:bg-white/[0.05]","grid-cols-[minmax(0,1.8fr)_auto] lg:grid-cols-[minmax(0,1.8fr)_auto_auto] xl:grid-cols-[minmax(0,1.8fr)_auto_auto_auto]"),style:{marginLeft:`${N.level*14}px`,background:`linear-gradient(180deg, rgba(${j}, 0.07), rgba(255,255,255,0.02))`},children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("button",{type:"button",className:"inline-flex size-7 shrink-0 items-center justify-center rounded-full bg-white/[0.06] text-white/62 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>N.toggle(),disabled:N.isLeaf,"aria-label":N.isOpen?`Collapse ${N.data.label}`:`Expand ${N.data.label}`,children:N.isLeaf?e.jsx("span",{className:"size-2 rounded-full bg-white/22"}):N.isOpen?e.jsx(Sa,{className:"size-4"}):e.jsx(Hu,{className:"size-4"})}),e.jsx("span",{className:te("inline-flex size-9 shrink-0 items-center justify-center rounded-[12px] border",H.subtleBadgeClassName),children:e.jsx(H.icon,{className:te("size-4",H.iconClassName)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:V8(N.data.kind),children:N.data.kind}),N.data.executionMode?e.jsx(I,{className:N.data.executionMode==="afk"?"bg-emerald-400/12 text-emerald-100":"bg-amber-400/12 text-amber-100",children:N.data.executionMode.toUpperCase()}):null,e.jsx("div",{className:"truncate text-[13px] font-medium text-white",children:N.data.label})]}),e.jsx("div",{className:"mt-0.5 truncate text-[11px] leading-5 text-white/46",children:N.data.description})]})]}),e.jsx("div",{className:"hidden lg:flex justify-end",children:e.jsx(I,{className:mc(N.data.statusLabel),children:N.data.statusLabel?N.data.statusLabel.replaceAll("_"," "):"linked"})}),e.jsxs("div",{className:"hidden xl:flex items-center justify-end gap-2",children:[N.data.user?e.jsx(ot,{user:N.data.user,compact:!0}):null,N.data.assignees.length>0?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:["+",N.data.assignees.length]}):null]}),e.jsxs("div",{className:"hidden lg:flex min-w-[11rem] items-center justify-end gap-3",children:[e.jsxs("div",{className:"min-w-[7.5rem]",children:[e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full",style:{width:`${N.data.progressPercent??0}%`,background:`linear-gradient(90deg, rgba(${j}, 0.96), rgba(${j}, 0.72))`}})}),e.jsx("div",{className:"mt-1 text-[11px] text-white/44",children:N.data.progressLabel??`${N.data.progressPercent??0}% complete`})]}),N.data.href?e.jsx(Je,{to:N.data.href,className:"rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] uppercase tracking-[0.16em] text-white/72 transition hover:border-white/18 hover:bg-white/[0.08] hover:text-white",children:"Open"}):e.jsx("span",{className:"w-[3.75rem]"})]})]})})}})})]})]})}function J8({children:t,columns:s="single",className:a}){return e.jsx("section",{className:te("grid gap-4",s==="two"&&"lg:grid-cols-2",s==="sidebar"&&"xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",a),children:t})}function Z8(t){return t.trim().toLowerCase()}function Zp(t,s=!1){switch(t.kind){case"goal":return e.jsx(We,{kind:"goal",label:t.label,compact:!0,gradient:!1});case"task":return e.jsx(We,{kind:"task",label:t.label,compact:!0,gradient:!1});case"tag":return e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:t.label});case"status":return e.jsx(I,{className:"bg-[rgba(192,193,255,0.12)] text-white/84",children:t.label});case"type":return e.jsx(I,{className:"bg-[rgba(86,170,255,0.12)] text-white/84",children:t.label});case"user":return e.jsx(I,{className:"bg-[rgba(110,231,183,0.12)] text-white/84",children:t.label});default:return t.label}}function eT({query:t,onQueryChange:s,options:a,selectedOptionIds:i,onSelectedOptionIdsChange:r,resultSummary:n}){const[l,o]=c.useState(!1),[d,m]=c.useState(0),h=c.useMemo(()=>i.map(b=>a.find(A=>A.id===b)).filter(Boolean),[a,i]),u=Z8(t),x=c.useMemo(()=>{const b=a.filter(A=>!i.includes(A.id));return u?b.filter(A=>`${A.label} ${A.description??""} ${A.searchText??""}`.toLowerCase().includes(u)).slice(0,10):b.slice(0,10)},[u,a,i]),g=b=>{i.includes(b)||(r([...i,b]),s(""),m(0),o(!1))},p=b=>{r(i.filter(A=>A!==b))},f=()=>{s(""),r([]),m(0),o(!1)};return e.jsx("div",{className:"grid gap-3",children:e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,28,48,0.9),rgba(10,14,26,0.98))] p-4 shadow-[0_30px_80px_rgba(3,8,18,0.28)] sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Project search"}),e.jsx("div",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/62",children:"Search with free text, then pin matching goals, tasks, tags, human users, bot users, statuses, or project-type chips as you narrow the list."})]}),t.trim().length>0||i.length>0?e.jsx("button",{type:"button",onClick:f,className:"rounded-full border border-white/8 bg-white/[0.04] px-3 py-2 text-sm text-white/62 transition hover:bg-white/[0.08] hover:text-white",children:"Clear search"}):null]}),e.jsxs("div",{className:"mt-4 rounded-[24px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[h.length>0?e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:h.map(b=>e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[Zp(b,!0),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>p(b.id),"aria-label":`Remove ${b.label}`,children:e.jsx(Tt,{className:"size-3.5"})})]},b.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/36"}),e.jsx("input",{value:t,onChange:b=>{s(b.target.value),o(!0),m(0)},onFocus:()=>o(!0),onBlur:()=>{window.setTimeout(()=>o(!1),120)},onKeyDown:b=>{if(b.key==="Backspace"&&!t&&i.length>0){p(i[i.length-1]);return}if(b.key==="ArrowDown"){b.preventDefault(),o(!0),m(A=>x.length===0?0:Math.min(x.length-1,A+1));return}if(b.key==="ArrowUp"){b.preventDefault(),m(A=>Math.max(0,A-1));return}if(b.key==="Escape"){o(!1);return}b.key==="Enter"&&x[d]&&(b.preventDefault(),g(x[d].id))},placeholder:"Type a project, goal, task, human, bot, user, or tag",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),l?e.jsx("div",{className:"absolute top-full z-20 mt-2 w-full rounded-[22px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:x.length>0?x.map((b,A)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",A===d?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>m(A),onMouseDown:C=>C.preventDefault(),onClick:()=>g(b.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:Zp(b)}),b.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:b.description}):null]})},b.id)):e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:"Keep typing to search by free text, or select a suggested goal, task, human or bot owner, tag, status, or type chip when it appears."})}):null]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/52",children:n})]})})}const tT={execution:"Execution",value:"Value",category:"Category"};function sT(t){return t.trim().toLowerCase()}function aT(){const t=jt(),[s,a]=c.useState("active"),[i,r]=c.useState(""),[n,l]=c.useState([]),[o,d]=c.useState(null),m=c.useMemo(()=>$m(t.snapshot.dashboard.projects),[t.snapshot.dashboard.projects]),h=c.useMemo(()=>{const w=new Map(t.snapshot.dashboard.goals.map(P=>[P.id,P])),S=new Map(t.snapshot.tags.map(P=>[P.id,P])),y=new Map(t.snapshot.users.map(P=>[P.id,P])),N=new Map;for(const P of t.snapshot.tasks){if(!P.projectId)continue;const v=N.get(P.projectId)??[];v.push(P),N.set(P.projectId,v)}return new Map(t.snapshot.dashboard.projects.map(P=>{const v=w.get(P.goalId)??null,H=N.get(P.id)??[],j=P.userId?y.get(P.userId)??null:null,R=new Map;for(const Y of(v==null?void 0:v.tags)??[])R.set(Y.id,{id:Y.id,name:Y.name,kind:Y.kind});for(const Y of H)for(const z of Y.tagIds){const K=S.get(z);K&&R.set(K.id,{id:K.id,name:K.name,kind:K.kind})}const Q=Array.from(new Set(Array.from(R.values()).map(Y=>Y.kind))),X=[P.title,P.description,P.goalTitle,(j==null?void 0:j.displayName)??"",(j==null?void 0:j.handle)??"",(j==null?void 0:j.kind)??"",(v==null?void 0:v.description)??"",P.nextTaskTitle??"",P.momentumLabel,P.status,H.map(Y=>Y.title).join(" "),Array.from(R.values()).map(Y=>`${Y.name} ${Y.kind}`).join(" ")].join(" ").toLowerCase();return[P.id,{tagIds:Array.from(R.keys()),tags:Array.from(R.values()),taskIds:H.map(Y=>Y.id),typeKeys:Q,userId:P.userId,searchText:X}]}))},[t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks,t.snapshot.users]),u=c.useMemo(()=>{var j,R,Q,X,Y;const w=new Map,S=new Map,y=new Map,N=new Map,P=new Map,v=new Map,H=new Map;for(const z of t.snapshot.dashboard.projects){const K=h.get(z.id);if(K){S.has(z.goalId)||S.set(z.goalId,new Set),S.get(z.goalId).add(z.id),P.has(z.status)||P.set(z.status,new Set),P.get(z.status).add(z.id);for(const $ of K.taskIds)y.has($)||y.set($,new Set),y.get($).add(z.id);for(const $ of K.tags)N.has($.id)||N.set($.id,new Set),N.get($.id).add(z.id);for(const $ of K.typeKeys)v.has($)||v.set($,new Set),v.get($).add(z.id);K.userId&&(H.has(K.userId)||H.set(K.userId,new Set),H.get(K.userId).add(z.id))}}for(const z of t.snapshot.dashboard.goals){const K=((j=S.get(z.id))==null?void 0:j.size)??0;K!==0&&w.set(`goal:${z.id}`,{id:`goal:${z.id}`,kind:"goal",value:z.id,label:z.title,description:ut(`${K} project${K===1?"":"s"} linked to this goal`,z.user,`${K} project${K===1?"":"s"} linked to this goal`),searchText:dt([z.title,z.description],z)})}for(const z of t.snapshot.tasks){const K=((R=y.get(z.id))==null?void 0:R.size)??0;K!==0&&w.set(`task:${z.id}`,{id:`task:${z.id}`,kind:"task",value:z.id,label:z.title,description:ut(`${K} project${K===1?"":"s"} linked to this task`,z.user,`${K} project${K===1?"":"s"} linked to this task`),searchText:dt([z.title,z.description],z)})}for(const z of t.snapshot.tags){const K=((Q=N.get(z.id))==null?void 0:Q.size)??0;K!==0&&w.set(`tag:${z.id}`,{id:`tag:${z.id}`,kind:"tag",value:z.id,label:z.name,description:ut(`${K} project${K===1?"":"s"} touching this tag`,z.user,`${K} project${K===1?"":"s"} touching this tag`),searchText:dt([z.name,z.kind,z.description],z)})}for(const[z,K]of Object.entries(m))z==="all"||K===0||w.set(`status:${z}`,{id:`status:${z}`,kind:"status",value:z,label:z==="paused"?"Suspended":z==="completed"?"Finished":"Active",description:`${K} project${K===1?"":"s"} currently ${z==="paused"?"suspended":z==="completed"?"finished":"active"}`,searchText:`${z} ${z==="paused"?"suspended":""} ${z==="completed"?"finished":""}`});for(const[z,K]of Object.entries(tT)){const $=((X=v.get(z))==null?void 0:X.size)??0;$!==0&&w.set(`type:${z}`,{id:`type:${z}`,kind:"type",value:z,label:K,description:`${$} project${$===1?"":"s"} linked to ${K.toLowerCase()} tags`,searchText:`${K} ${z} project type`})}for(const z of t.snapshot.users){const K=((Y=H.get(z.id))==null?void 0:Y.size)??0;K!==0&&w.set(`user:${z.id}`,{id:`user:${z.id}`,kind:"user",value:z.id,label:z.displayName,description:`${K} project${K===1?"":"s"} owned by this ${z.kind}`,searchText:`${z.displayName} ${z.handle} ${z.kind} ${z.description}`})}return Array.from(w.values()).sort((z,K)=>z.label.localeCompare(K.label))},[m,h,t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks,t.snapshot.users]),x=c.useMemo(()=>n.map(w=>u.find(S=>S.id===w)).filter(Boolean),[u,n]),g=c.useMemo(()=>{const w=sT(i);return Om(t.snapshot.dashboard.projects,s).filter(S=>{const y=h.get(S.id);return!y||!x.every(P=>{switch(P.kind){case"goal":return S.goalId===P.value;case"task":return y.taskIds.includes(P.value);case"tag":return y.tagIds.includes(P.value);case"status":return S.status===P.value;case"type":return y.typeKeys.includes(P.value);case"user":return y.userId===P.value;default:return!0}})?!1:w?y.searchText.includes(w):!0})},[s,h,i,x,t.snapshot.dashboard.projects]),p=s==="all"?m.all:m[s],b=i.trim().length>0||n.length>0?`${g.length} matching project${g.length===1?"":"s"} in the current collection view`:`${p} project${p===1?"":"s"} in ${s==="all"?"all project states":s==="paused"?"the suspended view":s==="completed"?"the finished view":"the active view"}`,A=async w=>{d(w);try{await t.patchProject(w,{status:"active"})}finally{d(null)}},C=e.jsx(J8,{columns:"two",className:"2xl:grid-cols-3",children:g.map(w=>{const S=Js(t.snapshot.dashboard.notesSummaryByEntity,"project",w.id),y=h.get(w.id),N=(y==null?void 0:y.tags.slice(0,3))??[];return e.jsxs(ce,{className:"flex h-full flex-col transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"goal",label:w.goalTitle,compact:!0}),e.jsx(ot,{user:w.user,compact:!0})]}),e.jsx(I,{className:w.status==="completed"?"text-emerald-300":w.status==="paused"?"text-amber-300":"text-[var(--primary)]",children:w.status==="paused"?"Suspended":w.status==="completed"?"Finished":"Active"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Je,{to:`/projects/${w.id}`,className:"transition hover:opacity-90",children:e.jsx(yt,{kind:"project",label:w.title,variant:"heading",size:"xl",lines:2})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:w.description}),N.length>0?e.jsx(ew,{className:"mt-4",children:N.map(P=>e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:P.name},P.id))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(xa,{value:w.progress,tone:w.status==="completed"?"secondary":"primary"})}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Active"}),e.jsx("div",{className:"mt-2 text-white",children:w.activeTaskCount})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Completed"}),e.jsx("div",{className:"mt-2 text-white",children:w.completedTaskCount})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"XP"}),e.jsx("div",{className:"mt-2 text-white",children:w.earnedPoints})]})]}),e.jsx("div",{className:"mt-5 text-[11px] uppercase tracking-[0.16em] text-white/40",children:w.nextTaskTitle?`Next move: ${w.nextTaskTitle}`:"Ready for the next task"}),e.jsx("div",{className:"mt-4",children:e.jsx(Ks,{entityType:"project",entityId:w.id,count:S.count})}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 pt-1",children:[e.jsx(Je,{to:`/projects/${w.id}`,children:e.jsx(W,{variant:"ghost",children:"Open project"})}),s!=="active"&&w.status!=="active"?e.jsx(W,{variant:"secondary",pending:o===w.id,pendingLabel:"Restarting…",onClick:()=>void A(w.id),children:"Restart"}):null]})]},w.id)})}),T=[{id:"hero",title:"Projects",description:"Route header",defaultWidth:12,defaultHeight:2,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(Ib,{children:e.jsx(nt,{entityKind:"project",title:e.jsx(yt,{kind:"project",label:"Projects",variant:"heading",size:"lg"}),titleText:"Projects",description:"Projects are the concrete paths that move a life goal forward.",badge:`${t.snapshot.dashboard.projects.length} total projects`})})},{id:"search-results",title:"Search and results",description:"Search stays grouped with its live result set.",defaultWidth:8,defaultHeight:6,minWidth:6,render:({compact:w})=>e.jsx(Cb,{children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(eT,{query:i,onQueryChange:r,options:u,selectedOptionIds:n,onSelectedOptionIdsChange:l,resultSummary:b}),e.jsx(Rm,{value:s,counts:m,onChange:a}),g.length===0?e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"No matching projects"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Nothing in this project collection matches the current search and chips."})]}):w?e.jsx("div",{className:"grid gap-3",children:g.slice(0,5).map(S=>e.jsx(Je,{to:`/projects/${S.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex items-center 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:S.title}),e.jsx("div",{className:"text-sm text-white/54",children:S.goalTitle})]}),e.jsxs(I,{className:"shrink-0 bg-white/[0.08] text-white/72",children:[S.earnedPoints," xp"]})]})},S.id))}):C]})})},{id:"summary",title:"Collection summary",description:"Counts and spotlight cards.",defaultWidth:4,defaultHeight:5,minWidth:4,render:()=>{const w=g[0]??t.snapshot.dashboard.projects[0]??null;return e.jsx(Tb,{children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-1",children:[e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Active"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:m.active})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Finished"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:m.completed})]})]}),w?e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Spotlight"}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:w.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:w.description}),e.jsx("div",{className:"mt-3",children:e.jsx(xa,{value:w.progress})})]}):null]})})}}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Id,{}),t.snapshot.dashboard.projects.length===0?e.jsx(Bt,{eyebrow:"Projects",title:"No projects in flight",description:"Create the first practical path under a life goal so execution, kanban, and evidence all have a concrete home.",action:e.jsx(Je,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-white/[0.08] px-4 py-3 text-sm whitespace-nowrap text-white transition hover:bg-white/[0.12]",children:"Open goals"})}):e.jsx(Td,{surfaceId:"projects",baseWidgets:T})]})}const Yl=[{to:"/settings",label:"General",icon:Po},{to:"/settings/data",label:"Data",icon:_r},{to:"/settings/users",label:"Users",icon:Ku},{to:"/settings/calendar",label:"Calendar",icon:cs},{to:"/settings/mobile",label:"Mobile",icon:Kv},{to:"/settings/models",label:"Models",icon:qv},{to:"/settings/agents",label:"Agents",icon:ma},{to:"/settings/wiki",label:"KarpaWiki",icon:ed},{to:"/settings/logs",label:"Logs",icon:Bv},{to:"/settings/rewards",label:"Rewards",icon:Uv},{to:"/settings/bin",label:"Bin",icon:Uc}];function hc(t,s){return s==="/settings"?t==="/settings":t===s||t.startsWith(`${s}/`)}function ga({className:t}){const s=hi(),[a,i]=c.useState(!1),r=c.useMemo(()=>[...Yl].sort((n,l)=>l.to.length-n.to.length).find(n=>hc(s.pathname,n.to))??Yl[0],[s.pathname]);return c.useEffect(()=>{if(!a)return;const n=document.body.style.overflow,l=document.body.style.touchAction,o=d=>{d.key==="Escape"&&i(!1)};return document.body.style.overflow="hidden",document.body.style.touchAction="none",window.addEventListener("keydown",o),()=>{document.body.style.overflow=n,document.body.style.touchAction=l,window.removeEventListener("keydown",o)}},[a]),e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:te("surface-shell-panel overflow-hidden p-2",t),children:[e.jsx("div",{className:"hidden items-center gap-3 lg:flex",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Yl.map(n=>e.jsxs(_a,{to:n.to,end:n.to==="/settings",className:({isActive:l})=>te("inline-flex items-center gap-2 whitespace-nowrap rounded-full px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",l||hc(s.pathname,n.to)?"border border-[var(--primary)]/14 bg-[var(--ui-accent-soft)] text-[var(--primary)]":"border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-soft)] hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)] hover:text-[var(--ui-ink-strong)]"),children:[e.jsx(n.icon,{className:"size-3.5"}),e.jsx("span",{children:n.label})]},n.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsxs("button",{type:"button",className:"surface-shell-panel inline-flex min-w-0 flex-1 items-center justify-between gap-3 rounded-[22px] border px-3.5 py-2.5 text-left transition hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)]",onClick:()=>i(!0),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-2xl border border-[var(--primary)]/20 bg-[var(--primary)]/12",children:e.jsx(r.icon,{className:"size-4 text-[var(--primary)]"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[10px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Settings section"}),e.jsx("span",{className:"mt-0.5 block truncate text-sm font-medium text-[var(--ui-ink-strong)]",children:r.label})]})]}),e.jsx("span",{className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Browse"})]})})]}),a&&typeof document<"u"?Qi.createPortal(e.jsxs("div",{className:"lg:hidden",children:[e.jsx("div",{className:"surface-overlay fixed inset-0 z-50 backdrop-blur-xl"}),e.jsx("button",{type:"button","aria-label":"Close settings sections",className:"fixed inset-0 z-[51]",onClick:()=>i(!1)}),e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[52] flex items-end justify-center px-3 pt-3 sm:px-4 sm:pt-4",style:{paddingLeft:"max(0.75rem, calc(var(--forge-safe-area-left) + 0.75rem))",paddingRight:"max(0.75rem, calc(var(--forge-safe-area-right) + 0.75rem))",paddingTop:"max(0.75rem, calc(env(safe-area-inset-top) + 0.75rem))",paddingBottom:"calc(var(--forge-mobile-nav-clearance) - 0.25rem)"},children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Settings sections",className:"surface-modal-panel pointer-events-auto flex max-h-[min(34rem,calc(100dvh-var(--forge-mobile-nav-clearance)-1rem))] w-full max-w-xl min-h-0 flex-col overflow-hidden rounded-[30px] border",children:[e.jsx("div",{className:"shrink-0 border-b border-[var(--ui-border-subtle)] px-4 pb-3 pt-4 sm:px-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-[var(--ui-ink-faint)]",children:"Settings"}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("div",{className:"truncate text-base font-semibold text-[var(--ui-ink-strong)]",children:"Tune Forge"}),e.jsx("span",{className:"rounded-full border border-[var(--primary)]/20 bg-[var(--primary)]/12 px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[var(--primary)]",children:r.label})]}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-soft)]",children:"Jump between users, calendar, models, rewards, and more."})]}),e.jsx("button",{type:"button","aria-label":"Close settings sections",className:"inline-flex size-10 shrink-0 items-center justify-center rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-soft)] transition hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)] hover:text-[var(--ui-ink-strong)]",onClick:()=>i(!1),children:e.jsx(Tt,{className:"size-4"})})]})}),e.jsx("div",{className:"min-h-0 overflow-y-auto p-3 overscroll-contain sm:p-4",children:e.jsx("div",{className:"grid gap-2",children:Yl.map(n=>{const l=hc(s.pathname,n.to);return e.jsxs(_a,{to:n.to,end:n.to==="/settings",onClick:()=>i(!1),className:te("group flex items-center justify-between gap-3 rounded-[22px] border px-3.5 py-3 transition-[transform,border-color,background-color,color] duration-150 hover:-translate-y-[1px] hover:text-white",l?"border-[var(--primary)]/18 bg-[var(--ui-accent-soft)] text-[var(--ui-ink-strong)]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-medium)] hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)]"),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:te("flex size-10 shrink-0 items-center justify-center rounded-2xl border transition",l?"border-[var(--primary)]/18 bg-[var(--primary)]/14 text-[var(--primary)]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-soft)] group-hover:border-[var(--ui-border-strong)] group-hover:text-[var(--ui-ink-strong)]"),children:e.jsx(n.icon,{className:"size-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-semibold text-[var(--ui-ink-strong)]",children:n.label}),e.jsx("span",{className:"mt-0.5 block text-[10px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Forge settings"})]})]}),e.jsx("span",{className:te("rounded-full px-2.5 py-1 text-[10px] uppercase tracking-[0.16em]",l?"bg-[var(--primary)]/16 text-[var(--primary)]":"bg-[var(--ui-surface-1)] text-[var(--ui-ink-faint)]"),children:l?"Current":"Open"})]},n.to)})})})]})})]}),document.body):null]})}const Ww=[{value:"gpt-5.4",label:"GPT-5.4",description:"Highest quality drafting for long, connected wiki pages."},{value:"gpt-5.4-mini",label:"GPT-5.4 mini",description:"Balanced speed and quality for regular ingest jobs."},{value:"gpt-5.4-nano",label:"GPT-5.4 nano",description:"Fastest and cheapest option for smaller imports."}];Ww[1].value;const iT="medium",rT="medium";function nT(t){const s=t==null?void 0:t.reasoningEffort;return s==="none"||s==="low"||s==="medium"||s==="high"||s==="xhigh"?s:iT}function lT(t){const s=t==null?void 0:t.verbosity;return s==="low"||s==="medium"||s==="high"?s:rT}function ex(t){var a;return{model:((a=Ww.find(i=>i.value===t.model))==null?void 0:a.label)??t.model,reasoning:nT(t.metadata),verbosity:lT(t.metadata),hasKey:!!t.secretId}}function oT(){var z,K;const t=ct(),[s,a]=c.useState(""),[i,r]=c.useState(""),[n,l]=c.useState("personal"),[o,d]=c.useState("Fast wiki search"),[m,h]=c.useState("text-embedding-3-small"),[u,x]=c.useState("https://api.openai.com/v1"),[g,p]=c.useState(""),[f,b]=c.useState("1200"),[A,C]=c.useState("200"),T=Fe({queryKey:["forge-wiki-settings"],queryFn:pd}),w=Fe({queryKey:["forge-settings"],queryFn:Xr}),S=async()=>{await Promise.all([t.invalidateQueries({queryKey:["forge-wiki-settings"]}),t.invalidateQueries({queryKey:["forge-wiki-pages"]}),t.invalidateQueries({queryKey:["forge-wiki-page"]}),t.invalidateQueries({queryKey:["forge-wiki-search"]})])},y=Re({mutationFn:()=>Yj({label:s.trim(),description:i.trim(),visibility:n}),onSuccess:async()=>{a(""),r(""),l("personal"),await S()}}),N=Re({mutationFn:()=>oN({label:o.trim(),model:m.trim(),baseUrl:u.trim(),apiKey:g.trim()||void 0,chunkSize:Number(f),chunkOverlap:Number(A)}),onSuccess:async()=>{p(""),await S()}}),P=Re({mutationFn:({kind:$,profileId:D})=>dN($,D),onSuccess:S}),v=Re({mutationFn:()=>nN(),onSuccess:S}),H=Re({mutationFn:()=>lN(),onSuccess:S});if(T.isLoading)return e.jsx(Et,{eyebrow:"KarpaWiki settings",title:"Loading KarpaWiki controls",description:"Fetching spaces and profile configuration for KarpaWiki."});if(T.isError)return e.jsx(it,{eyebrow:"KarpaWiki settings",error:T.error,onRetry:()=>void T.refetch()});const j=(z=T.data)==null?void 0:z.settings;if(!j)return e.jsx(it,{eyebrow:"KarpaWiki settings",error:new Error("Forge returned an empty KarpaWiki settings payload."),onRetry:()=>void T.refetch()});const R=j.llmProfiles.find($=>$.enabled)??j.llmProfiles[0]??null,Q=R?ex(R):null,X="Canonical knowledge lives in SQLite notes, with Forge maintaining metadata, links, search, and optional embedding indexes in the database. Text search and entity-linked search work without embeddings, while semantic search stays additive and profile-driven. Ingest jobs can create pages and media assets now, with room for richer OCR, transcription, and multimodal compilation later.",Y=(K=w.data)==null?void 0:K.settings.modelSettings.forgeAgent.wiki;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(nt,{eyebrow:"SQLite memory",title:"KarpaWiki Settings",titleText:"KarpaWiki Settings",description:"Configure SQLite-backed spaces, parse models, and embedding profiles for the KarpaWiki memory system.",badge:`${j.spaces.length} spaces · ${j.embeddingProfiles.length} embedding profiles`,actions:e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"secondary",pending:v.isPending,pendingLabel:"Syncing",onClick:()=>void v.mutateAsync(),children:"Refresh indexes"}),e.jsx(W,{pending:H.isPending,pendingLabel:"Reindexing",onClick:()=>void H.mutateAsync(),disabled:j.embeddingProfiles.length===0,children:"Reindex embeddings"})]})}),e.jsx(ga,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Auto-ingest model"}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"KarpaWiki ingest now reads its credentials and model slot from the dedicated Models settings page instead of owning the OpenAI setup flow here."})]})}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.8fr)_minmax(24rem,0.9fr)]",children:[e.jsxs("div",{className:"grid gap-5 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(22,32,49,0.9),rgba(12,18,31,0.9))] p-6",children:[e.jsxs("div",{className:"flex 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:"Current profile"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:(Y==null?void 0:Y.connectionLabel)??(R==null?void 0:R.label)??"No external KarpaWiki model selected"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:Y!=null&&Y.connectionLabel?"Forge now resolves wiki ingest through the selected Models connection and syncs the managed wiki profile automatically.":"Pick a Models connection when you want Forge wiki ingest to run through the OpenAI API or a local compatible endpoint."})]}),e.jsx(Je,{to:"/settings/models",className:"inline-flex min-h-11 items-center rounded-[16px] bg-white/[0.08] px-4 py-3 text-sm text-white transition hover:bg-white/[0.12]",children:"Open model settings"})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Model"}),e.jsx("div",{className:"mt-2 text-white",children:(Y==null?void 0:Y.model)??(Q==null?void 0:Q.model)??"Not set"})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Provider"}),e.jsx("div",{className:"mt-2 text-white",children:(Y==null?void 0:Y.connectionLabel)??"Not set"})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Endpoint"}),e.jsx("div",{className:"mt-2 flex items-center gap-2 text-white",children:(Y==null?void 0:Y.baseUrl)??(R==null?void 0:R.baseUrl)??"Not set"})]})]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[28px] border border-white/8 bg-white/[0.03] p-6",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Supported controls"}),e.jsxs("div",{className:"text-sm leading-6 text-white/58",children:["OpenAI API and local compatible endpoints are configured under Settings ","->"," Models. OpenAI Codex OAuth lives there as a chat agent path, while Wiki keeps the SQLite memory controls here and consumes the selected ingest model slot."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:["GPT-5.4","GPT-5.4 mini","GPT-5.4 nano"].map($=>e.jsx(I,{className:"bg-white/[0.06] text-white/78",children:$},$))}),e.jsxs(Je,{to:"/settings/models",className:"inline-flex min-h-11 items-center rounded-[16px] bg-white/[0.08] px-4 py-3 text-sm text-white transition hover:bg-white/[0.12]",children:["Open model settings",e.jsx(Es,{className:"ml-2 size-4"})]})]})]}),e.jsxs("div",{className:"grid gap-3",children:[j.llmProfiles.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-5 text-sm leading-6 text-white/58",children:"No LLM profile yet. Set up OpenAI once, test it, and Forge will use it for wiki auto-ingest."}):null,j.llmProfiles.map($=>{const D=ex($);return e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-white",children:$.label}),e.jsxs("div",{className:"mt-1 text-xs text-white/46",children:[D.model," · thinking ",D.reasoning," · verbosity ",D.verbosity]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{type:"button",className:"rounded-full p-2 text-white/48 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>void P.mutateAsync({kind:"llm",profileId:$.id}),children:e.jsx(Rt,{className:"size-4"})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-white/58",children:[e.jsx(I,{className:"bg-white/[0.06] text-white/76",children:$.baseUrl}),e.jsx(I,{className:"bg-white/[0.06] text-white/76",children:D.hasKey?"key saved":"key missing"})]})]},$.id)})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wv,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm text-white",children:"Spaces"}),e.jsx(vt,{content:X,label:"Explain the wiki operating model"})]}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"Personal and shared wiki spaces map to explicit SQLite namespaces."})]})]}),e.jsx("div",{className:"grid gap-3",children:j.spaces.map($=>e.jsxs("div",{className:"grid gap-1 rounded-[18px] 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:"text-white",children:$.label}),e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/42",children:$.visibility})]}),e.jsx("div",{className:"text-xs text-white/46",children:$.slug}),e.jsx("div",{className:"text-sm text-white/60",children:$.description||"No description yet."})]},$.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsx(ye,{value:s,onChange:$=>a($.target.value),placeholder:"New space label"}),e.jsx(ye,{value:i,onChange:$=>r($.target.value),placeholder:"Description"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:n,onChange:$=>l($.target.value),children:[e.jsx("option",{value:"personal",children:"Personal"}),e.jsx("option",{value:"shared",children:"Shared"})]}),e.jsx(W,{pending:y.isPending,pendingLabel:"Creating",disabled:!s.trim(),onClick:()=>void y.mutateAsync(),children:"Create space"})]})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Hv,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Embedding profiles"}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"Semantic search stays opt-in. The recommended starter is fast and cheap, with heading-aware chunking for agent memory retrieval."})]})]}),e.jsx("div",{className:"grid gap-3",children:j.embeddingProfiles.map($=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] 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:"text-white",children:$.label}),e.jsx("button",{type:"button",className:"rounded-full p-2 text-white/48 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>void P.mutateAsync({kind:"embedding",profileId:$.id}),children:e.jsx(Rt,{className:"size-4"})})]}),e.jsxs("div",{className:"text-xs text-white/46",children:[$.model," · ",$.baseUrl]}),e.jsxs("div",{className:"text-sm text-white/60",children:["chunkSize ",$.chunkSize," · overlap"," ",$.chunkOverlap]})]},$.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsx(ye,{value:o,onChange:$=>d($.target.value),placeholder:"Profile label"}),e.jsx(ye,{value:m,onChange:$=>h($.target.value),placeholder:"Model"}),e.jsx(ye,{value:u,onChange:$=>x($.target.value),placeholder:"Base URL"}),e.jsx(ye,{value:g,onChange:$=>p($.target.value),placeholder:"API key (optional)",type:"password"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsx(ye,{value:f,onChange:$=>b($.target.value),placeholder:"Chunk size",type:"number"}),e.jsx(ye,{value:A,onChange:$=>C($.target.value),placeholder:"Chunk overlap",type:"number"})]}),e.jsx(W,{pending:N.isPending,pendingLabel:"Saving",disabled:!o.trim()||!m.trim(),onClick:()=>void N.mutateAsync(),children:"Save embedding profile"})]})]})]})]})]})}function Um(t){return[{id:"title",label:"Strategy title is set",satisfied:t.title.trim().length>0},{id:"graph",label:"Graph contains at least one linked project or task",satisfied:t.graph.nodes.length>0},{id:"targets",label:"At least one target goal or project is selected",satisfied:t.targetGoalIds.length>0||t.targetProjectIds.length>0},{id:"narrative",label:"The plan already names an overview or end state",satisfied:t.overview.trim().length>0||t.endStateDescription.trim().length>0}]}function Hw(t){return Um(t).every(s=>s.satisfied)}function Wm(t){return[{id:"coverage",label:"Agreed work moving",value:t.planCoverageScore,detail:`${t.startedNodeCount}/${t.totalNodeCount} agreed steps have started or finished.`},{id:"order",label:"Order respected",value:t.sequencingScore,detail:`${t.outOfOrderNodeIds.length} step${t.outOfOrderNodeIds.length===1?"":"s"} started before prerequisites were complete.`},{id:"scope",label:"Scope held",value:t.scopeDisciplineScore,detail:`${t.offPlanEntityCount} unagreed item${t.offPlanEntityCount===1?"":"s"} are inside the strategy scope, ${t.offPlanActiveEntityCount} still active.`},{id:"satisfaction",label:"End-state satisfaction",value:t.qualityScore,detail:`${t.targetProgressScore}% target progress with ${t.blockedNodeIds.length} blocked step${t.blockedNodeIds.length===1?"":"s"}.`}]}function dT(t){return t.trim().toLowerCase()}function kr(t,s){return t.includes(s)?t.filter(a=>a!==s):[...t,s]}function tx(t,s){return t.some(a=>a.entityType===s.entityType&&a.entityId===s.entityId)?t.filter(a=>!(a.entityType===s.entityType&&a.entityId===s.entityId)):[...t,s]}function sx(t,s){if(t.length!==s.length)return!1;const a=new Set(s);return t.every(i=>a.has(i))}function Qo(t="project",s){return{id:`strategy_node_${Math.random().toString(36).slice(2,10)}`,entityType:t,entityId:"",branchLabel:"",notes:"",dependencyMode:"after_previous",customPredecessorIds:[],...s}}function cT(t){const s=new Map(t.graph.nodes.map(o=>[o.id,o])),a=new Map(t.graph.nodes.map(o=>[o.id,0])),i=new Map,r=new Map(t.graph.nodes.map((o,d)=>[o.id,d]));for(const o of t.graph.nodes)i.set(o.id,[]);for(const o of t.graph.edges)a.set(o.to,(a.get(o.to)??0)+1),i.set(o.from,[...i.get(o.from)??[],o.to]);const n=t.graph.nodes.filter(o=>(a.get(o.id)??0)===0).sort((o,d)=>(r.get(o.id)??0)-(r.get(d.id)??0)).map(o=>o.id),l=[];for(;n.length>0;){n.sort((m,h)=>(r.get(m)??0)-(r.get(h)??0));const o=n.shift();if(!o)continue;const d=s.get(o);if(d){l.push(d);for(const m of i.get(o)??[]){const h=(a.get(m)??0)-1;a.set(m,h),h===0&&n.push(m)}}}return l.length===t.graph.nodes.length?l:t.graph.nodes}function uT(t){const s=new Map;for(const i of t.graph.nodes)s.set(i.id,[]);for(const i of t.graph.edges)s.set(i.to,[...s.get(i.to)??[],i.from]);const a=cT(t);return{title:t.title,overview:t.overview,endStateDescription:t.endStateDescription,status:t.status,userId:t.userId??null,targetGoalIds:t.targetGoalIds,targetProjectIds:t.targetProjectIds,linkedEntities:t.linkedEntities,nodes:a.map((i,r)=>{const n=s.get(i.id)??[],l=a[r-1],o=l?s.get(l.id)??[]:[];let d="custom";return n.length===0?d="start":l&&sx(n,[l.id])?d="after_previous":l&&n.length>0&&sx(n,o)&&(d="parallel_with_previous"),Qo(i.entityType,{id:i.id,entityId:i.entityId,branchLabel:i.branchLabel,notes:i.notes,dependencyMode:d,customPredecessorIds:n})})}}function Gw(t){const s=new Map,a=new Set;for(const[i,r]of t.entries()){const n=t[i-1];let l;switch(r.dependencyMode){case"after_previous":l=n?[n.id]:[];break;case"parallel_with_previous":l=n?[...s.get(n.id)??[]]:[];break;case"custom":l=r.customPredecessorIds.filter(o=>a.has(o));break;case"start":default:l=[];break}s.set(r.id,l),a.add(r.id)}return s}function ax(t){const s=Gw(t),a=new Set,i=new Set;function r(n){if(i.has(n))return!0;if(a.has(n))return!1;a.add(n),i.add(n);for(const l of s.get(n)??[])if(r(l))return!0;return i.delete(n),!1}return t.some(n=>r(n.id))}const ix={title:"",overview:"",endStateDescription:"",status:"active",userId:null,targetGoalIds:[],targetProjectIds:[],linkedEntities:[],nodes:[Qo("project",{dependencyMode:"start"})]};function cr(t,s){const a=s[0];return{title:"",description:"",goalId:(a==null?void 0:a.goalId)??"",projectId:(a==null?void 0:a.id)??"",userId:(a==null?void 0:a.userId)??t,priority:"medium",effort:"deep",energy:"steady",points:60}}function mT(t,s,a){const i=Gw(t.nodes),r=new Set(t.nodes.filter(n=>n.entityId).map(n=>n.id));return{nodes:t.nodes.filter(n=>n.entityId).map(n=>{var l,o;return{id:n.id,entityType:n.entityType,entityId:n.entityId,title:n.entityType==="project"?((l=s.get(n.entityId))==null?void 0:l.title)??n.entityId:((o=a.get(n.entityId))==null?void 0:o.title)??n.entityId,branchLabel:n.branchLabel.trim(),notes:n.notes.trim()}}),edges:t.nodes.flatMap(n=>r.has(n.id)?(i.get(n.id)??[]).filter(l=>r.has(l)).map(l=>({from:l,to:n.id,label:"",condition:""})):[])}}function rx(t){return((t==null?void 0:t.progress)??0)/100}function hT(t){switch(t==null?void 0:t.status){case"done":return 1;case"in_progress":return .66;case"focus":return .5;case"blocked":return .25;default:return 0}}function pT(t){const{draft:s,graph:a,goals:i,projects:r,projectsById:n,tasks:l,tasksById:o}=t,d=new Map(a.nodes.map(D=>[D.id,D.entityType==="project"?rx(n.get(D.entityId)):hT(o.get(D.entityId))])),m=new Map;for(const D of a.nodes)m.set(D.id,[]);for(const D of a.edges)m.set(D.to,[...m.get(D.to)??[],D.from]);const h=a.nodes.filter(D=>(d.get(D.id)??0)>=1).map(D=>D.id),u=a.nodes.filter(D=>(d.get(D.id)??0)>0).map(D=>D.id),x=a.nodes.filter(D=>{var J,q;return D.entityType==="project"?((J=n.get(D.entityId))==null?void 0:J.status)==="paused":((q=o.get(D.entityId))==null?void 0:q.status)==="blocked"}).map(D=>D.id),g=a.nodes.filter(D=>(d.get(D.id)??0)<=0?!1:(m.get(D.id)??[]).some(q=>(d.get(q)??0)<1)).map(D=>D.id),p=a.nodes.filter(D=>(d.get(D.id)??0)>=1?!1:(m.get(D.id)??[]).every(q=>(d.get(q)??0)>=1)).map(D=>D.id),f=new Map(i.map(D=>[D.id,D])),b=s.targetGoalIds.map(D=>{var q;const J=l.filter(_=>_.goalId===D);return J.length===0?((q=f.get(D))==null?void 0:q.status)==="completed"?1:0:J.filter(_=>_.status==="done").length/J.length}),A=s.targetProjectIds.map(D=>rx(n.get(D))),C=[...b,...A],T=a.nodes.length===0?0:a.nodes.reduce((D,J)=>D+(d.get(J.id)??0),0)/a.nodes.length,w=C.length===0?T:C.reduce((D,J)=>D+J,0)/C.length,S=new Set(a.nodes.filter(D=>D.entityType==="project").map(D=>D.entityId)),y=new Set(a.nodes.filter(D=>D.entityType==="task").map(D=>D.entityId)),N=new Set,P=new Set,v=new Set;for(const D of s.targetProjectIds){const J=r.find(q=>q.id===D);if(J&&!S.has(J.id)&&J.status!=="completed"){const q=`project:${J.id}`;N.add(q),P.add(q)}for(const q of l.filter(_=>_.projectId===D))if(!y.has(q.id)&&["focus","in_progress","done","blocked"].includes(q.status)){const _=`task:${q.id}`;N.add(_),q.status==="done"?v.add(_):P.add(_)}}for(const D of s.targetGoalIds)for(const J of l.filter(q=>q.goalId===D))if(!y.has(J.id)&&["focus","in_progress","done","blocked"].includes(J.status)){const q=`task:${J.id}`;N.add(q),J.status==="done"?v.add(q):P.add(q)}const H=Math.max(1,a.nodes.length),j=N.size,R=x.length/H,Q=Math.max(0,Math.min(100,Math.round(T*100))),X=Math.max(0,Math.min(100,Math.round(100-g.length/H*100))),Y=Math.max(0,Math.min(100,Math.round(100-j/H*100))),z=Math.max(0,Math.min(100,Math.round(Math.max(0,Math.min(1,w*.8+(1-R)*.2))*100))),K=Math.max(0,Math.min(100,Math.round(w*100)));return{alignmentScore:Math.max(0,Math.min(100,Math.round(Q*.35+X*.3+Y*.2+z*.15))),planCoverageScore:Q,sequencingScore:X,scopeDisciplineScore:Y,qualityScore:z,targetProgressScore:K,completedNodeCount:h.length,startedNodeCount:u.length,readyNodeCount:p.length,totalNodeCount:H,completedTargetCount:C.filter(D=>D>=1).length,totalTargetCount:C.length,offPlanEntityCount:j,offPlanActiveEntityCount:P.size,offPlanCompletedEntityCount:v.size,activeNodeIds:p.slice(0,8),nextNodeIds:p.slice(0,5),blockedNodeIds:x,outOfOrderNodeIds:g}}function xT({node:t,index:s,total:a,projectsById:i,tasksById:r,usersById:n,allNodes:l,onUpdate:o,onRemove:d}){const{attributes:m,listeners:h,setNodeRef:u,transform:x,transition:g,isDragging:p}=pl({id:t.id}),f=t.entityType==="project"?i.get(t.entityId):r.get(t.entityId),b=f&&"userId"in f&&f.userId?n.get(f.userId)??f.user??null:null,A=l.slice(0,s);return e.jsxs("div",{ref:u,style:{transform:xl.Transform.toString(x),transition:g},className:te("min-w-0 overflow-hidden rounded-[24px] border border-white/8 bg-[rgba(8,14,26,0.8)] p-4 shadow-[0_24px_60px_rgba(0,0,0,0.2)]",p&&"opacity-70"),children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("button",{type:"button",className:"mt-1 rounded-full bg-white/[0.06] p-2 text-white/58 transition hover:bg-white/[0.1] hover:text-white",...m,...h,children:e.jsx(ul,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/76",children:["Step ",s+1]}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:t.entityType}),f?e.jsx(We,{kind:t.entityType,label:f.title,compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-3 text-base font-medium text-white",children:(f==null?void 0:f.title)||"Select an entity for this step"}),e.jsx("div",{className:"mt-2 break-words text-sm leading-6 text-white/54",children:t.notes||(f&&"description"in f?f.description:"")||"Add an optional note if this phase needs intent or setup context."}),b?e.jsx("div",{className:"mt-3",children:e.jsx(ot,{user:b,compact:!0})}):null]})]}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"w-full sm:w-auto",disabled:a===1,onClick:()=>d(t.id),children:[e.jsx(Rt,{className:"size-4"}),"Remove"]})]}),e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsx(de,{label:"Relationship to the flow",labelHelp:"Keep the sequence mostly linear in the form. Use parallel when this step should open beside the previous one, or custom only when the dependency is special.",children:e.jsx(wt,{value:t.dependencyMode,columns:2,onChange:C=>o(t.id,{dependencyMode:C}),options:[{value:"start",label:"Start here",description:"This step opens immediately."},{value:"after_previous",label:"After previous",description:"Use the prior step as the gate."},{value:"parallel_with_previous",label:"Parallel with previous",description:"Open beside the prior branch."},{value:"custom",label:"Custom dependency",description:"Pick earlier steps manually."}]})}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(de,{label:"Branch label",children:e.jsx(ye,{value:t.branchLabel,onChange:C=>o(t.id,{branchLabel:C.target.value}),placeholder:"Core path, fallback lane, support branch"})}),e.jsx(de,{label:"Step note",children:e.jsx(Ze,{value:t.notes,onChange:C=>o(t.id,{notes:C.target.value}),placeholder:"Explain what has to be true before or after this step."})})]})]}),t.dependencyMode==="custom"?e.jsxs("div",{className:"mt-4 rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Depends on"}),e.jsx("div",{className:"mt-3 grid gap-2",children:A.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No earlier steps available yet."}):A.map(C=>{const T=C.entityType==="project"?i.get(C.entityId):r.get(C.entityId);return e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:(T==null?void 0:T.title)||`Step ${l.indexOf(C)+1}`}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/52",children:C.branchLabel||C.entityType})]}),e.jsx("input",{type:"checkbox",checked:t.customPredecessorIds.includes(C.id),onChange:()=>o(t.id,{customPredecessorIds:kr(t.customPredecessorIds,C.id)})})]},C.id)})})]}):null]})}function Qw({open:t,pending:s=!1,editingStrategy:a,goals:i,projects:r,tasks:n,habits:l,strategies:o,users:d,defaultUserId:m=null,initialStepId:h,onOpenChange:u,onSubmit:x}){const[g,p]=c.useState(ix),[f,b]=c.useState(""),[A,C]=c.useState(""),[T,w]=c.useState(""),[S,y]=c.useState(null),[N,P]=c.useState([]),[v,H]=c.useState(cr(m,r)),[j,R]=c.useState(!1),[Q,X]=c.useState(null),[Y,z]=c.useState(!1);c.useEffect(()=>{var se,_e,Be;if(!t)return;const k=a?uT(a):{...ix,userId:m,nodes:[Qo("project",{dependencyMode:"start"})]};p(k),b(""),C(""),w(""),P([]),R(!1),H(cr(m,r).projectId&&k.targetProjectIds[0]?{...cr(m,r),goalId:((se=r.find(Ge=>Ge.id===k.targetProjectIds[0]))==null?void 0:se.goalId)??"",projectId:k.targetProjectIds[0]??((_e=r[0])==null?void 0:_e.id)??"",userId:((Be=r.find(Ge=>Ge.id===k.targetProjectIds[0]))==null?void 0:Be.userId)??m}:cr(m,r)),X(null),y(null)},[m,a,t,r]);const K=c.useDeferredValue(f),$=c.useDeferredValue(A),D=c.useDeferredValue(T),J=c.useMemo(()=>{const k=new Set(N.map(se=>se.id));return[...N,...n.filter(se=>!k.has(se.id))]},[N,n]),q=c.useMemo(()=>new Map(i.map(k=>[k.id,k])),[i]),_=c.useMemo(()=>new Map(r.map(k=>[k.id,k])),[r]),B=c.useMemo(()=>new Map(J.map(k=>[k.id,k])),[J]),G=c.useMemo(()=>new Map(d.map(k=>[k.id,k])),[d]),ae=d.find(k=>k.id===m)??null,ke=d.find(k=>k.id===g.userId)??ae,Ae=(k,se,_e)=>{const Be=dT(k);return Be.length===0||dt(se,_e).includes(Be)},ie=c.useMemo(()=>i.filter(k=>Ae($,[k.title,k.description],k.user)),[$,i]),Ie=c.useMemo(()=>i.filter(k=>Ae(K,[k.title,k.description],k.user)),[i,K]),Ne=c.useMemo(()=>r.filter(k=>Ae(K,[k.title,k.description,k.goalTitle,k.status],k.user)),[K,r]),M=c.useMemo(()=>r.filter(k=>Ae($,[k.title,k.description,k.goalTitle,k.status],k.user)),[$,r]),E=c.useMemo(()=>J.filter(k=>Ae($,[k.title,k.description,k.owner,k.status],k.user)),[J,$]),O=c.useMemo(()=>l.filter(k=>Ae($,[k.title,k.description,k.frequency,k.status],k.user)),[$,l]),xe=c.useMemo(()=>o.filter(k=>k.id!==(a==null?void 0:a.id)&&Ae($,[k.title,k.overview,k.endStateDescription,k.status],k.user)),[$,a==null?void 0:a.id,o]),V=c.useMemo(()=>[...ie.map(se=>({key:`goal:${se.id}`,entityType:"goal",entityId:se.id,label:se.title,description:ut(se.description,se.user,"Goal"),user:se.user??null})),...M.map(se=>({key:`project:${se.id}`,entityType:"project",entityId:se.id,label:se.title,description:ut(`${se.goalTitle}${se.goalTitle?" · ":""}${se.status}`,se.user,`Project · ${se.goalTitle}`),user:se.user??null})),...E.map(se=>({key:`task:${se.id}`,entityType:"task",entityId:se.id,label:se.title,description:ut(`${se.status} · ${se.owner}`,se.user,`Task · ${se.owner}`),user:se.user??null})),...O.map(se=>({key:`habit:${se.id}`,entityType:"habit",entityId:se.id,label:se.title,description:ut(se.description,se.user,"Habit"),user:se.user??null})),...xe.map(se=>({key:`strategy:${se.id}`,entityType:"strategy",entityId:se.id,label:se.title,description:ut(se.overview,se.user,"Strategy"),user:se.user??null}))].sort((se,_e)=>se.label.localeCompare(_e.label)),[ie,O,M,xe,E]),Se=c.useMemo(()=>mT(g,_,B),[g,_,B]),Ee=c.useMemo(()=>pT({draft:g,graph:Se,goals:i,projects:r,projectsById:_,tasks:J,tasksById:B}),[J,g,Se,i,r,_,B]),Ce=c.useMemo(()=>[...Um({title:g.title,overview:g.overview,endStateDescription:g.endStateDescription,targetGoalIds:g.targetGoalIds,targetProjectIds:g.targetProjectIds,graph:Se}),{id:"acyclic",label:"Graph stays directed and non-looping",satisfied:!ax(g.nodes)}],[g.endStateDescription,g.nodes,g.overview,g.targetGoalIds,g.targetProjectIds,g.title,Se]),qe=c.useMemo(()=>Hw({title:g.title,overview:g.overview,endStateDescription:g.endStateDescription,targetGoalIds:g.targetGoalIds,targetProjectIds:g.targetProjectIds,graph:Se}),[g.endStateDescription,g.overview,g.targetGoalIds,g.targetProjectIds,g.title,Se]),oe=c.useMemo(()=>Wm(Ee),[Ee]),L=c.useMemo(()=>{if(!g.title.trim())return"Strategy title is required.";if(g.nodes.length===0)return"Add at least one project or task step.";const k=new Set;for(const se of g.nodes){if(!se.entityId)return"Every step needs a linked project or task.";const _e=`${se.entityType}:${se.entityId}`;if(k.has(_e))return"Each project or task should appear only once in the sequence.";k.add(_e)}return ax(g.nodes)?"Strategy graph must stay directed and non-loopy.":null},[g.nodes,g.title]),U=k=>k==="sequence"?S??L??(qe?null:"This can still be saved as a draft. Add the target plus the overview or end state later, then lock it as the contract from the strategy detail page."):null,ge=c.useMemo(()=>i.filter(k=>Ae(D,[k.title,k.description],k.user)),[i,D]),Te=c.useMemo(()=>r.filter(k=>Ae(D,[k.title,k.description,k.goalTitle,k.status],k.user)),[r,D]),ve=c.useMemo(()=>J.filter(k=>Ae(D,[k.title,k.description,k.owner,k.status],k.user)),[J,D]),Le=c.useMemo(()=>new Set(g.targetGoalIds),[g.targetGoalIds]),Qe=c.useMemo(()=>new Set(g.targetProjectIds),[g.targetProjectIds]),st=c.useMemo(()=>new Set(g.nodes.map(k=>`${k.entityType}:${k.entityId}`)),[g.nodes]),F=c.useMemo(()=>g.targetGoalIds.map(k=>q.get(k)).filter(k=>!!k),[g.targetGoalIds,q]),he=c.useMemo(()=>g.targetProjectIds.map(k=>_.get(k)).filter(k=>!!k),[g.targetProjectIds,_]),we=c.useMemo(()=>Te.filter(k=>Qe.has(k.id)||Le.has(k.goalId)),[Te,Le,Qe]),Z=c.useMemo(()=>ve.filter(k=>Qe.has(k.projectId??"")||Le.has(k.goalId??"")),[ve,Le,Qe]),De=c.useMemo(()=>Ie.slice(0,8),[Ie]),ee=c.useMemo(()=>Ne.slice(0,8),[Ne]),ze=c.useMemo(()=>V.slice(0,12),[V]),et=c.useMemo(()=>ge.slice(0,6),[ge]),Ve=c.useMemo(()=>Te.slice(0,8),[Te]),re=c.useMemo(()=>ve.slice(0,10),[ve]),ne=c.useMemo(()=>we.slice(0,4),[we]),be=c.useMemo(()=>Z.slice(0,6),[Z]),je=c.useMemo(()=>{if(!v.goalId)return r;const k=r.filter(se=>se.goalId===v.goalId);return k.length>0?k:r},[v.goalId,r]),pe=D.length>0,$e=et.length>0||Ve.length>0||re.length>0,Xe=(k,se)=>{p(_e=>({..._e,nodes:_e.nodes.map(Be=>Be.id===k?{...Be,...se}:Be)}))},Ue=(k,se)=>{g.nodes.some(_e=>_e.entityType===k&&_e.entityId===se)||p(_e=>({..._e,nodes:[..._e.nodes,Qo(k,{entityId:se,dependencyMode:_e.nodes.length===0?"start":"after_previous"})]}))},le=k=>{p(se=>{const _e=se.nodes.filter(Be=>Be.id!==k);return{...se,nodes:_e.map((Be,Ge)=>({...Be,dependencyMode:Ge===0&&Be.dependencyMode==="after_previous"?"start":Be.dependencyMode,customPredecessorIds:Be.customPredecessorIds.filter(gt=>gt!==k)}))}})},Me=ld(od(cd,{activationConstraint:{distance:6}})),He=k=>{!k.over||k.active.id===k.over.id||p(se=>{const _e=se.nodes.findIndex(Ge=>Ge.id===k.active.id),Be=se.nodes.findIndex(Ge=>{var gt;return Ge.id===((gt=k.over)==null?void 0:gt.id)});return _e<0||Be<0?se:{...se,nodes:Vu(se.nodes,_e,Be)}})},lt=()=>{const k=T.trim(),se=g.targetProjectIds.map(Ge=>_.get(Ge)).find(Ge=>!!Ge)??_.get(v.projectId)??r[0]??null,_e=(se==null?void 0:se.goalId)??g.targetGoalIds[0]??"",Be=r.find(Ge=>Ge.goalId===_e&&(se?Ge.id===se.id:!0))??r.find(Ge=>Ge.goalId===_e)??se;H(Ge=>({...cr(m,r),title:k||Ge.title,description:Ge.description,goalId:_e,projectId:(Be==null?void 0:Be.id)??Ge.projectId,userId:(Be==null?void 0:Be.userId)??Ge.userId??m})),X(null),R(!0)},Nt=async()=>{const k=_.get(v.projectId);if(!v.title.trim()){X("Task title is required.");return}if(!k){X("Pick a project for the new task.");return}z(!0),X(null);try{const se=G.get(v.userId??k.userId??"")??k.user??ke??ae,_e=(await im({title:v.title.trim(),description:v.description.trim(),level:"task",owner:(se==null?void 0:se.displayName)??"Albert",userId:v.userId??k.userId??g.userId,assigneeUserIds:[],goalId:k.goalId,projectId:k.id,parentWorkItemId:null,priority:v.priority,status:"focus",effort:v.effort,energy:v.energy,dueDate:"",points:v.points,plannedDurationSeconds:86400,aiInstructions:"",executionMode:null,acceptanceCriteria:[],blockerLinks:[],completionReport:null,gitRefs:[],tagIds:[],notes:[]})).task;P(Be=>[_e,...Be]),Ue("task",_e.id),H({...cr(m,r),goalId:k.goalId,projectId:k.id,userId:_e.userId??k.userId??g.userId}),w(""),R(!1)}catch(se){X(se instanceof Error?se.message:"Task creation failed.")}finally{z(!1)}},me=async()=>{if(L){y(L);return}try{await x({title:g.title.trim(),overview:g.overview.trim(),endStateDescription:g.endStateDescription.trim(),status:g.status,userId:g.userId,targetGoalIds:g.targetGoalIds,targetProjectIds:g.targetProjectIds,linkedEntities:g.linkedEntities,graph:Se},a==null?void 0:a.id),y(null),u(!1)}catch(k){y(k instanceof Error?k.message:"Strategy save failed.")}},Pe=[{id:"foundation",eyebrow:"Foundation",title:"Set the owner and the strategic frame",description:"Start with who owns the strategy, what the plan is called, and whether this should open as active, paused, or already landed.",render:(k,se)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(16rem,0.8fr)]",children:[e.jsx(de,{label:"Strategy title",children:e.jsx(ye,{value:k.title,onChange:_e=>se({title:_e.target.value}),placeholder:"Land the multi-user planning system"})}),e.jsx(de,{label:"Status",children:e.jsx(wt,{value:k.status,onChange:_e=>se({status:_e}),options:[{value:"active",label:"Active",description:"Use this when the plan should drive work now."},{value:"paused",label:"Paused",description:"Keep the strategy visible without active pressure."},{value:"completed",label:"Completed",description:"The end state is already landed."}]})})]}),e.jsx(Zs,{value:k.userId,users:d,onChange:_e=>se({userId:_e}),label:"Owner user",defaultLabel:Ys(ae),help:"Strategies can belong to a human or a bot even when the sequence spans multiple owners."}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(135deg,rgba(192,193,255,0.16),rgba(125,211,252,0.08))] px-5 py-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Live posture"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"strategy",label:k.title.trim()||"Untitled strategy",compact:!0,gradient:!1}),e.jsx(I,{className:"bg-white/[0.12] text-white/86",children:k.status}),ke?e.jsx(ot,{user:ke,compact:!0}):null]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"This flow is built to keep strategy creation as guided as the other major entities in Forge: clear questions first, then a focused sequence stage at the end."})]})]})},{id:"objective",eyebrow:"Objective",title:"Define the objective and the end targets",description:"Capture what this strategy is coordinating, what done looks like, and which goals or projects are the real targets.",render:(k,se)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(de,{label:"Overview",children:e.jsx(Ze,{value:k.overview,onChange:_e=>se({overview:_e.target.value}),placeholder:"Explain what this strategy is coordinating and why it matters right now."})}),e.jsx(de,{label:"End state",children:e.jsx(Ze,{value:k.endStateDescription,onChange:_e=>se({endStateDescription:_e.target.value}),placeholder:"Describe what reality should look like when this strategy lands."})})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,28,44,0.9),rgba(12,17,30,0.88))] px-5 py-5",children:[e.jsx(de,{label:"Search goals or projects",description:"Keep this page search-first. Add only the targets that truly define what this strategy is trying to land.",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(_t,{className:"size-4 text-white/42"}),e.jsx(ye,{className:"border-none bg-transparent px-0 py-0",value:f,onChange:_e=>b(_e.target.value),placeholder:"Search goals, projects, owners, humans, or bots"})]})}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected goals"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:F.length===0?e.jsx(I,{className:"bg-white/[0.08] text-white/62",children:"No target goals yet"}):F.map(_e=>e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white transition hover:bg-[rgba(192,193,255,0.2)]",onClick:()=>se({targetGoalIds:kr(k.targetGoalIds,_e.id)}),children:[e.jsx(We,{kind:"goal",label:_e.title,compact:!0,gradient:!1}),e.jsx("span",{children:"Remove"})]},_e.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected projects"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:he.length===0?e.jsx(I,{className:"bg-white/[0.08] text-white/62",children:"No target projects yet"}):he.map(_e=>e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white transition hover:bg-[rgba(192,193,255,0.2)]",onClick:()=>se({targetProjectIds:kr(k.targetProjectIds,_e.id)}),children:[e.jsx(We,{kind:"project",label:_e.title,compact:!0,gradient:!1}),e.jsx("span",{children:"Remove"})]},_e.id))})]})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-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:"Goal matches"}),K?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Ie.length," found"]}):null]}),e.jsx("div",{className:"mt-3 grid gap-3",children:K?De.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No goals match this search yet."}):De.map(_e=>{const Be=k.targetGoalIds.includes(_e.id);return e.jsxs("button",{type:"button",className:te("rounded-[22px] border px-4 py-4 text-left transition",Be?"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]"),onClick:()=>se({targetGoalIds:kr(k.targetGoalIds,_e.id)}),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx(yt,{kind:"goal",label:_e.title,className:"max-w-full min-w-0"}),e.jsx(ot,{user:_e.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:_e.description||"No strategic note attached yet."})]},_e.id)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search for the goal this strategy is meant to land."})})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-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:"Project matches"}),K?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Ne.length," found"]}):null]}),e.jsx("div",{className:"mt-3 grid gap-3",children:K?ee.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No projects match this search yet."}):ee.map(_e=>{const Be=k.targetProjectIds.includes(_e.id);return e.jsxs("button",{type:"button",className:te("rounded-[22px] border px-4 py-4 text-left transition",Be?"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]"),onClick:()=>se({targetProjectIds:kr(k.targetProjectIds,_e.id)}),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx(yt,{kind:"project",label:_e.title,className:"max-w-full min-w-0",showIcon:!1}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:_e.goalTitle}),e.jsx(ot,{user:_e.user,compact:!0})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:_e.description||"No project summary attached yet."})]},_e.id)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search for the concrete project this strategy should land or organize."})})]})]})]})},{id:"context",eyebrow:"Context",title:"Keep the right supporting entities in view",description:"Linked entities stay visible in the strategy context without becoming part of the main execution sequence.",render:(k,se)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Search supporting context",description:"Search across goals, projects, tasks, habits, and other strategies.",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(_t,{className:"size-4 text-white/42"}),e.jsx(ye,{className:"border-none bg-transparent px-0 py-0",value:A,onChange:_e=>C(_e.target.value),placeholder:"Search by title, owner, @handle, human, or bot"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.linkedEntities.length===0?e.jsx(I,{className:"bg-white/[0.08] text-white/62",children:"No extra linked context yet"}):k.linkedEntities.map(_e=>{const Be=V.find(Ge=>Ge.entityType===_e.entityType&&Ge.entityId===_e.entityId);return e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white/82 transition hover:bg-[rgba(192,193,255,0.22)]",onClick:()=>se({linkedEntities:k.linkedEntities.filter(Ge=>!(Ge.entityType===_e.entityType&&Ge.entityId===_e.entityId))}),children:[e.jsx($s,{className:"mr-1 size-3.5"}),(Be==null?void 0:Be.label)??`${_e.entityType}:${_e.entityId}`,e.jsx("span",{children:"Remove"})]},`${_e.entityType}:${_e.entityId}`)})}),e.jsx("div",{className:"grid gap-3",children:$?ze.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No supporting entities match this search yet."}):ze.map(_e=>{const Be=k.linkedEntities.some(Ge=>Ge.entityType===_e.entityType&&Ge.entityId===_e.entityId);return e.jsxs("label",{className:te("flex items-start justify-between gap-3 rounded-[20px] border px-4 py-4",Be?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)]":"border-white/8 bg-white/[0.04]"),children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:_e.entityType,label:_e.label,compact:!0,gradient:!1}),_e.user?e.jsx(ot,{user:_e.user,compact:!0}):null]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:_e.description})]}),e.jsx("input",{type:"checkbox",checked:Be,onChange:()=>se({linkedEntities:tx(k.linkedEntities,{entityType:_e.entityType,entityId:_e.entityId})})})]},_e.key)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search when you want to pull another entity into the background context. This keeps the page focused instead of dumping every record into one long list."})})]})},{id:"sequence",eyebrow:"Sequence",title:"Build the execution sequence",description:"Search, add steps, and create missing tasks.",render:()=>e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,28,44,0.9),rgba(12,17,30,0.88))] px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Search and add"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Search goals, projects, tasks, humans, and bots."})]}),e.jsxs(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[g.nodes.length," planned steps"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(_t,{className:"size-4 text-white/42"}),e.jsx(ye,{className:"border-none bg-transparent px-0 py-0",value:T,onChange:k=>w(k.target.value),placeholder:"Search goals, projects, tasks, owners, humans, or bots"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs(W,{type:"button",className:"w-full justify-start",variant:"secondary",onClick:lt,children:[e.jsx(ds,{className:"size-4"}),"Create new task"]}),j?e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"New task"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Add the task and place it in the sequence."})]}),e.jsx(W,{type:"button",variant:"secondary",className:"w-full sm:w-auto",onClick:()=>{R(!1),X(null)},children:"Close"})]}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(de,{label:"Task title",children:e.jsx(ye,{value:v.title,onChange:k=>H(se=>({...se,title:k.target.value})),placeholder:"Draft the shared strategy hierarchy view"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(de,{label:"Goal",children:e.jsxs("select",{value:v.goalId,onChange:k=>{const se=k.target.value,_e=r.find(Be=>Be.goalId===se)??null;H(Be=>({...Be,goalId:se,projectId:(_e==null?void 0:_e.id)??"",userId:(_e==null?void 0:_e.userId)??Be.userId??m}))},className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"",children:"Select goal"}),i.map(k=>e.jsx("option",{value:k.id,children:k.title},k.id))]})}),e.jsx(de,{label:"Project",children:e.jsxs("select",{value:v.projectId,onChange:k=>H(se=>{var _e,Be;return{...se,projectId:k.target.value,goalId:((_e=_.get(k.target.value))==null?void 0:_e.goalId)??se.goalId,userId:((Be=_.get(k.target.value))==null?void 0:Be.userId)??se.userId}}),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"",children:"Select project"}),je.map(k=>e.jsx("option",{value:k.id,children:k.title},k.id))]})})]}),e.jsx(de,{label:"Notes",children:e.jsx(Ze,{value:v.description,onChange:k=>H(se=>({...se,description:k.target.value})),placeholder:"Optional detail or acceptance note."})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(de,{label:"Priority",children:e.jsxs("select",{value:v.priority,onChange:k=>H(se=>({...se,priority:k.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"critical",children:"Critical"})]})}),e.jsx(de,{label:"Points",children:e.jsx(ye,{type:"number",value:v.points,onChange:k=>H(se=>({...se,points:Number(k.target.value)||0}))})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(de,{label:"Effort",children:e.jsxs("select",{value:v.effort,onChange:k=>H(se=>({...se,effort:k.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"light",children:"Light"}),e.jsx("option",{value:"deep",children:"Deep"}),e.jsx("option",{value:"extended",children:"Extended"})]})}),e.jsx(de,{label:"Energy",children:e.jsxs("select",{value:v.energy,onChange:k=>H(se=>({...se,energy:k.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"calm",children:"Calm"}),e.jsx("option",{value:"steady",children:"Steady"}),e.jsx("option",{value:"intense",children:"Intense"})]})})]}),Q?e.jsx("div",{className:"rounded-[18px] border border-rose-400/20 bg-rose-500/[0.08] px-4 py-3 text-sm text-rose-100/90",children:Q}):null,e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx(W,{type:"button",variant:"secondary",className:"w-full sm:w-auto",onClick:()=>{R(!1),X(null)},children:"Cancel"}),e.jsxs(W,{type:"button",className:"w-full sm:w-auto",pending:Y,pendingLabel:"Creating task",onClick:()=>void Nt(),children:[e.jsx(ds,{className:"size-4"}),"Create task"]})]})]})]}):null,pe?$e?e.jsxs("div",{className:"grid gap-3",children:[et.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Goals"}):null,et.map(k=>{const se=g.targetGoalIds.includes(k.id),_e=g.linkedEntities.some(Be=>Be.entityType==="goal"&&Be.entityId===k.id);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"goal",label:k.title,compact:!0,gradient:!1}),e.jsx(ot,{user:k.user,compact:!0})]}),k.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",onClick:()=>p(Be=>({...Be,targetGoalIds:kr(Be.targetGoalIds,k.id)})),children:se?"Targeted":"Add target"}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:"secondary",onClick:()=>p(Be=>({...Be,linkedEntities:tx(Be.linkedEntities,{entityType:"goal",entityId:k.id})})),children:_e?"Unlink":"Link"})]})]})},k.id)}),Ve.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Projects"}):null,Ve.map(k=>{const se=st.has(`project:${k.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"project",label:k.title,compact:!0,gradient:!1}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:k.goalTitle}),e.jsx(ot,{user:k.user,compact:!0})]}),k.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description}):null]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",disabled:se,onClick:()=>Ue("project",k.id),children:se?"In sequence":"Add step"})]})},`sequence-project:${k.id}`)}),re.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Tasks"}):null,re.map(k=>{const se=st.has(`task:${k.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"task",label:k.title,compact:!0,gradient:!1}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:k.status}),e.jsx(ot,{user:k.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description||`${k.owner} · ${k.projectId}`})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",disabled:se,onClick:()=>Ue("task",k.id),children:se?"In sequence":"Add step"})]})},`sequence-task:${k.id}`)})]}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No goals, projects, or tasks match this search."}):ne.length>0||be.length>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Suggested from targets"}),ne.map(k=>{const se=st.has(`project:${k.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"project",label:k.title,compact:!0,gradient:!1}),e.jsx(ot,{user:k.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description||k.goalTitle})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",disabled:se,onClick:()=>Ue("project",k.id),children:se?"In sequence":"Add step"})]})},`suggested-project:${k.id}`)}),be.map(k=>{const se=st.has(`task:${k.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"task",label:k.title,compact:!0,gradient:!1}),e.jsx(ot,{user:k.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description||`${k.owner} · ${k.status}`})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",disabled:se,onClick:()=>Ue("task",k.id),children:se?"In sequence":"Add step"})]})},`suggested-task:${k.id}`)})]}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Type to search."})]})]}),e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sequence"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Keep the flow mostly linear here. When a step should open beside the previous one, switch it to parallel. Use custom only for special joins."})]}),e.jsxs(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[g.nodes.length," planned steps"]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[g.targetGoalIds.map(k=>{const se=q.get(k);return se?e.jsx(We,{kind:"goal",label:se.title,compact:!0,gradient:!1},k):null}),g.targetProjectIds.map(k=>{const se=_.get(k);return se?e.jsx(We,{kind:"project",label:se.title,compact:!0,gradient:!1},k):null})]})]}),e.jsx(dd,{sensors:Me,collisionDetection:Qu,onDragEnd:He,children:e.jsx(Xn,{items:g.nodes.map(k=>k.id),strategy:Yn,children:e.jsx("div",{className:"grid gap-3",children:g.nodes.map((k,se)=>e.jsx(xT,{node:k,index:se,total:g.nodes.length,projectsById:_,tasksById:B,usersById:G,allNodes:g.nodes,onUpdate:Xe,onRemove:le},k.id))})})})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Contract readiness"}),e.jsx("div",{className:"mt-3 grid gap-2",children:Ce.map(k=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[14px] bg-white/[0.03] px-3 py-2",children:[e.jsx("div",{className:"text-sm text-white/62",children:k.label}),e.jsx(I,{className:k.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:k.satisfied?"Ready":"Missing"})]},k.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Alignment preview"}),e.jsx("div",{className:"mt-3 grid gap-3",children:oe.map(k=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm text-white/60",children:[e.jsx("span",{children:k.label}),e.jsxs("span",{children:[k.value,"%"]})]}),e.jsx(xa,{value:k.value,className:"mt-2"})]},k.id))})]})]})]})}];return e.jsx(Lt,{open:t,onOpenChange:u,eyebrow:"Strategy",title:a?"Edit strategy":"Create strategy",description:"Strategies connect goals, projects, and tasks into a guided multi-step plan with a focused sequence builder at the end.",value:g,onChange:p,draftPersistenceKey:a?`strategy.${a.id}`:"strategy.new",steps:Pe,initialStepId:h,contentClassName:"lg:h-[min(56rem,calc(100vh-1rem))] lg:w-[min(78rem,calc(100vw-1.5rem))]",submitLabel:a?qe?"Save strategy":"Save draft":qe?"Create strategy":"Create draft",pending:s,pendingLabel:"Saving strategy",resolveError:U,onSubmit:me})}function gT(t){return t.trim().toLowerCase()}function fT(){const t=jt(),s=$t(),a=ct(),[i,r]=ms(),[n,l]=c.useState(!1),[o,d]=c.useState(null),[m,h]=c.useState(""),u=ys(t.selectedUserIds);c.useEffect(()=>{i.get("create")==="1"&&(d(null),l(!0),r(T=>{const w=new URLSearchParams(T);return w.delete("create"),w},{replace:!0}))},[i,r]);const x=async()=>{await a.invalidateQueries({queryKey:["strategy-detail"]}),await t.refresh()},g=Re({mutationFn:async({input:T,strategyId:w})=>w?(await Qc(w,T)).strategy:(await U1(T)).strategy,onSuccess:async()=>{await x()}}),p=Re({mutationFn:async T=>gf(T),onSuccess:async()=>{await x()}}),f=c.useMemo(()=>new Map(t.snapshot.goals.map(T=>[T.id,T])),[t.snapshot.goals]),b=c.useMemo(()=>new Map(t.snapshot.dashboard.projects.map(T=>[T.id,T])),[t.snapshot.dashboard.projects]),A=c.useMemo(()=>new Map(t.snapshot.tasks.map(T=>[T.id,T])),[t.snapshot.tasks]),C=c.useMemo(()=>{const T=gT(m);return T?t.snapshot.strategies.filter(w=>{var P,v,H;const S=w.targetGoalIds.map(j=>{var R;return((R=f.get(j))==null?void 0:R.title)??""}).join(" "),y=w.targetProjectIds.map(j=>{var R;return((R=b.get(j))==null?void 0:R.title)??""}).join(" "),N=w.graph.nodes.map(j=>{var R,Q;return j.entityType==="project"?((R=b.get(j.entityId))==null?void 0:R.title)??"":((Q=A.get(j.entityId))==null?void 0:Q.title)??""}).join(" ");return[w.title,w.overview,w.endStateDescription,w.status,((P=w.user)==null?void 0:P.displayName)??"",((v=w.user)==null?void 0:v.handle)??"",((H=w.user)==null?void 0:H.kind)??"",S,y,N].join(" ").toLowerCase().includes(T)}):t.snapshot.strategies},[f,b,m,t.snapshot.strategies,A]);return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:"Strategies",titleText:"Strategies",description:"Strategies connect human and bot work into a directed plan, with explicit end goals, ownership, and live alignment metrics.",badge:`${t.snapshot.strategies.length} strategies`,actions:e.jsxs(W,{onClick:()=>{d(null),l(!0)},children:[e.jsx(ds,{className:"size-4"}),"New strategy"]})}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:m,onChange:T=>h(T.target.value),placeholder:"Search strategy title, target, graph node, human, or bot"})]}),e.jsx("div",{className:"text-sm text-white/56",children:"Search includes owners, target goals/projects, and graph nodes so cross-user plans stay discoverable."})]}),C.length===0?e.jsx(Bt,{eyebrow:"Strategies",title:"No strategies in this scope",description:"Create a strategy to connect projects and tasks into a non-looping execution plan across human and bot actors.",action:e.jsx(W,{onClick:()=>{d(null),l(!0)},children:"Create strategy"})}):e.jsx("div",{className:"grid gap-4",children:C.map(T=>{const w=T.graph.nodes.filter(y=>T.metrics.activeNodeIds.includes(y.id)),S=Wm(T.metrics);return e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("button",{type:"button",className:"text-left",onClick:()=>s(`/strategies/${T.id}`),children:[e.jsx("div",{className:"font-display text-2xl text-white",children:T.title}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:T.overview||T.endStateDescription})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ot,{user:T.user}),e.jsx(I,{className:T.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:T.isLocked?"Contract locked":"Editable draft"}),e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:T.status}),e.jsxs(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[T.metrics.alignmentScore,"% aligned"]})]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Graph progress"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[T.metrics.startedNodeCount,"/",T.metrics.totalNodeCount]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[T.metrics.completedNodeCount," completed"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Ready branches"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:T.metrics.readyNodeCount}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Nodes whose prerequisites are already satisfied."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"End targets"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[T.metrics.completedTargetCount,"/",T.metrics.totalTargetCount||0]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[T.metrics.targetProgressScore,"% target progress"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Sequencing"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[T.metrics.sequencingScore,"%"]})]})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(16rem,0.8fr)]",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Active next nodes"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:w.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No currently open branch."}):w.map(y=>e.jsx(I,{className:"bg-white/[0.08] text-white/80",children:y.title},y.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Alignment breakdown"}),e.jsx("div",{className:"mt-3 grid gap-2 text-sm text-white/58",children:S.map(y=>e.jsxs("div",{children:[y.label," ",y.value,"%"]},y.id))})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-end justify-end gap-2",children:[T.isLocked?null:e.jsxs(W,{variant:"secondary",onClick:()=>{d(T),l(!0)},children:[e.jsx(pi,{className:"size-4"}),"Edit"]}),e.jsxs(W,{variant:"secondary",pending:p.isPending&&p.variables===T.id,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${T.title}"?`)&&p.mutateAsync(T.id)},children:[e.jsx(Rt,{className:"size-4"}),"Delete"]}),e.jsx(W,{onClick:()=>s(`/strategies/${T.id}`),children:"Open strategy"})]})]})]},T.id)})}),e.jsx(Qw,{open:n,pending:g.isPending,editingStrategy:o,goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,habits:t.snapshot.habits,strategies:t.snapshot.strategies,users:t.snapshot.users,defaultUserId:u,onOpenChange:l,onSubmit:async(T,w)=>{await g.mutateAsync({input:T,strategyId:w})}})]})}function Vw(t){const s=new Map;for(const r of t.nodes)s.set(r.id,[]);for(const r of t.edges)s.set(r.to,[...s.get(r.to)??[],r.from]);const a=new Map,i=r=>{const n=a.get(r);if(n!==void 0)return n;const l=s.get(r)??[],o=l.length===0?0:Math.max(...l.map(d=>i(d)))+1;return a.set(r,o),o};for(const r of t.nodes)i(r.id);return a}function bT(t){const s=Vw(t),a=new Map;for(const i of t.nodes){const r=s.get(i.id)??0;a.set(r,[...a.get(r)??[],i.id])}return Array.from(a.entries()).sort((i,r)=>i[0]-r[0]).map(([i,r])=>({level:i,nodeIds:r}))}function wT(t,s){const a=Vw(t.graph),i=new Map;for(const r of t.graph.nodes){const n=a.get(r.id)??0;i.set(n,[...i.get(n)??[],r.id])}return t.graph.nodes.map(r=>{const n=a.get(r.id)??0,l=(i.get(n)??[]).indexOf(r.id),o=t.metrics.activeNodeIds.includes(r.id),d=t.metrics.blockedNodeIds.includes(r.id),m=t.metrics.outOfOrderNodeIds.includes(r.id),h=!o&&!d&&!m,u=(s==null?void 0:s.get(r.id))??null;let x="border-white/10 bg-[rgba(8,14,26,0.92)]";return o?x="border-emerald-400/30 bg-emerald-500/[0.08]":d?x="border-rose-400/28 bg-rose-500/[0.08]":m?x="border-amber-400/28 bg-amber-500/[0.08]":t.metrics.completedNodeCount>0&&(x="border-sky-400/20 bg-sky-500/[0.05]"),{id:r.id,position:{x:72+n*308,y:56+l*168},draggable:!1,selectable:!1,data:{label:e.jsxs("div",{className:`min-w-[220px] rounded-[22px] border px-4 py-4 shadow-[0_24px_70px_rgba(0,0,0,0.24)] ${x}`,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:r.entityType}),o?e.jsx(I,{className:"bg-emerald-500/12 text-emerald-200",children:"Active"}):null,d?e.jsx(I,{className:"bg-rose-500/12 text-rose-200",children:"Blocked"}):null,m?e.jsx(I,{className:"bg-amber-500/12 text-amber-200",children:"Out of order"}):null,h&&!d&&!m?e.jsx(I,{className:"bg-sky-500/12 text-sky-200",children:"In plan"}):null]}),e.jsx("div",{className:"mt-3 text-base font-medium leading-6 text-white",children:r.title}),r.branchLabel?e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/45",children:r.branchLabel}):null,r.notes?e.jsx("div",{className:"mt-2 text-sm leading-5 text-white/56",children:r.notes}):null,u?e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-xs text-white/52",children:[e.jsx("span",{className:"inline-block size-2.5 rounded-full",style:{backgroundColor:u.color}}),e.jsx("span",{children:u.label})]}):null]})},style:{background:"transparent",border:"none",padding:0}}})}function yT(t){return t.graph.edges.map(s=>{const a=t.metrics.activeNodeIds.includes(s.to),i=t.metrics.blockedNodeIds.includes(s.to),r=t.metrics.outOfOrderNodeIds.includes(s.to);let n="rgba(255,255,255,0.3)";return a?n="#4ade80":i?n="#fb7185":r&&(n="#f59e0b"),{id:`${s.from}->${s.to}`,source:s.from,target:s.to,label:s.label||void 0,animated:a,markerEnd:{type:Uu.ArrowClosed,color:n},style:{stroke:n,strokeWidth:a?2.4:1.5},labelStyle:{fill:"rgba(255,255,255,0.56)",fontSize:11,fontWeight:600}}})}function vT({strategy:t,ownerByNodeId:s,heightClassName:a="h-[540px]"}){const i=c.useMemo(()=>wT(t,s),[s,t]),r=c.useMemo(()=>yT(t),[t]);return e.jsx("div",{className:`${a} rounded-[24px] bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.08),transparent_32%),radial-gradient(circle_at_bottom_right,rgba(244,185,122,0.10),transparent_38%),linear-gradient(180deg,rgba(6,10,20,0.97),rgba(8,14,26,0.94))]`,children:e.jsxs(id,{fitView:!0,nodes:i,edges:r,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,attributionPosition:"bottom-left",children:[e.jsx(Bu,{showInteractive:!1}),e.jsx(rd,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})}function jT(t,s){const a=t.metrics.activeNodeIds.includes(s),i=t.metrics.blockedNodeIds.includes(s),r=t.metrics.outOfOrderNodeIds.includes(s);return i?{label:"Blocked",className:"bg-rose-500/12 text-rose-200"}:r?{label:"Out of order",className:"bg-amber-500/12 text-amber-200"}:a?{label:"Ready now",className:"bg-emerald-500/12 text-emerald-200"}:{label:"In plan",className:"bg-sky-500/12 text-sky-200"}}function NT({strategy:t,projectsById:s,tasksById:a,className:i}){const r=c.useMemo(()=>bT(t.graph),[t.graph]),n=c.useMemo(()=>{const d=new Map;for(const m of t.graph.nodes)d.set(m.id,[]);for(const m of t.graph.edges)d.set(m.to,[...d.get(m.to)??[],m.from]);return d},[t.graph]),[l,o]=c.useState([]);return e.jsxs("div",{className:i??"grid gap-3",children:[r.map(d=>{const m=l.includes(d.level),h=d.level===0?"Launch phase":`Phase ${d.level+1}`,u=d.nodeIds.length>1;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 px-4 py-4",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-3 text-left",onClick:()=>o(x=>m?x.filter(g=>g!==d.level):[...x,d.level]),children:[e.jsx("span",{className:"rounded-full bg-white/[0.06] p-2 text-white/72",children:m?e.jsx(Hu,{className:"size-4"}):e.jsx(Sa,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:h}),e.jsx("div",{className:"mt-1 text-sm text-white/60",children:u?"These branches can progress in parallel once the previous phase is complete.":"This phase advances as one focused step in the strategy."})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/76",children:[d.nodeIds.length," node",d.nodeIds.length===1?"":"s"]}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:u?e.jsxs(e.Fragment,{children:[e.jsx(Gv,{className:"mr-1 size-3.5"}),"Parallel"]}):e.jsxs(e.Fragment,{children:[e.jsx(Sg,{className:"mr-1 size-3.5"}),"Sequential"]})})]})]}),m?null:e.jsx("div",{className:"grid gap-3 border-t border-white/8 px-4 py-4 lg:grid-cols-2",children:d.nodeIds.map(x=>{var T,w,S;const g=t.graph.nodes.find(y=>y.id===x);if(!g)return null;const p=g.entityType==="project"?s.get(g.entityId):a.get(g.entityId),f=g.entityType==="project"?`/projects/${g.entityId}`:`/tasks/${g.entityId}`,b=g.entityType==="project"?(T=s.get(g.entityId))==null?void 0:T.user:(w=a.get(g.entityId))==null?void 0:w.user,A=((S=n.get(g.id))==null?void 0:S.map(y=>{var N;return((N=t.graph.nodes.find(P=>P.id===y))==null?void 0:N.title)??y}))??[],C=jT(t,g.id);return e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-[rgba(8,14,26,0.76)] 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:"flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:g.entityType}),e.jsx(I,{className:C.className,children:C.label})]}),e.jsx(Je,{to:f,className:"mt-3 block text-lg font-medium text-white transition hover:text-[var(--primary)]",children:g.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:g.notes||("description"in(p??{})?p==null?void 0:p.description:"")||"No extra step note attached yet."})]}),e.jsx(ot,{user:b,compact:!0})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[g.branchLabel?e.jsx(I,{className:"bg-[rgba(192,193,255,0.12)] text-white/82",children:g.branchLabel}):null,A.length===0?e.jsx(I,{className:"bg-emerald-500/10 text-emerald-200",children:"Start node"}):A.map(y=>e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:["Depends on ",y]},`${g.id}:${y}`))]})]},g.id)})})]},d.level)}),r.length===0?e.jsx("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm text-white/56",children:"No phases mapped yet."}):null]})}function kT(){var P;const t=jt(),{strategyId:s}=Qs(),a=$t(),i=ct(),[r,n]=c.useState(!1),[l,o]=c.useState(),d=ys(t.selectedUserIds),m=t.snapshot.strategies.find(v=>v.id===s)??null,h=Fe({queryKey:["strategy-detail",s],queryFn:async()=>(await W1(s)).strategy,enabled:!!(s&&!m)}),u=m??h.data??null,x=async()=>{await Promise.all([i.invalidateQueries({queryKey:["strategy-detail",s]}),t.refresh()])},g=Re({mutationFn:async({input:v,currentStrategyId:H})=>(await Qc(H,v)).strategy,onSuccess:x}),p=Re({mutationFn:async v=>gf(v),onSuccess:async()=>{await x(),a("/strategies")}}),f=Re({mutationFn:async v=>(await Qc(s,{isLocked:v,lockedByUserId:v?d??(u==null?void 0:u.userId)??"user_operator":null})).strategy,onSuccess:x}),b=c.useMemo(()=>new Map(t.snapshot.goals.map(v=>[v.id,v])),[t.snapshot.goals]),A=c.useMemo(()=>new Map(t.snapshot.dashboard.projects.map(v=>[v.id,v])),[t.snapshot.dashboard.projects]),C=c.useMemo(()=>new Map(t.snapshot.tasks.map(v=>[v.id,v])),[t.snapshot.tasks]),T=c.useMemo(()=>u?new Map(u.graph.nodes.map(v=>{var j,R;const H=v.entityType==="project"?(j=A.get(v.entityId))==null?void 0:j.user:(R=C.get(v.entityId))==null?void 0:R.user;return[v.id,H?{label:`${H.displayName} (${H.kind})`,color:H.accentColor}:null]})):new Map,[A,u,C]),w=u??{title:"",overview:"",endStateDescription:"",targetGoalIds:[],targetProjectIds:[],graph:{nodes:[],edges:[]}},S=c.useMemo(()=>Um(w),[w]),y=c.useMemo(()=>Hw(w),[w]),N=c.useMemo(()=>Wm((u==null?void 0:u.metrics)??{planCoverageScore:0,sequencingScore:0,scopeDisciplineScore:0,qualityScore:0,targetProgressScore:0,startedNodeCount:0,totalNodeCount:1,offPlanEntityCount:0,offPlanActiveEntityCount:0,blockedNodeIds:[],outOfOrderNodeIds:[]}),[u==null?void 0:u.metrics]);return h.isLoading&&!u?e.jsx(Et,{eyebrow:"Strategy",title:"Loading strategy",description:"Resolving the directed plan, targets, and current alignment."}):h.isError?e.jsx(it,{eyebrow:"Strategy",error:h.error,onRetry:()=>void h.refetch()}):u?e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:u.title,titleText:u.title,description:u.overview||u.endStateDescription,badge:`${u.metrics.alignmentScore}% aligned`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Nd,{userId:d,domain:"strategies",entityType:"strategy",entityId:u.id,label:u.title,description:u.overview||u.endStateDescription}),e.jsx(er,{entityType:"strategy",entityId:u.id}),u.isLocked?null:e.jsx(W,{variant:"secondary",onClick:()=>{o(void 0),n(!0)},children:"Edit strategy"}),e.jsx(W,{variant:"secondary",disabled:!u.isLocked&&!y,pending:f.isPending,pendingLabel:u.isLocked?"Unlocking contract":"Locking contract",onClick:()=>{f.mutateAsync(!u.isLocked)},children:u.isLocked?"Unlock contract":"Lock as contract"}),e.jsx(W,{variant:"secondary",pending:p.isPending,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${u.title}"?`)&&p.mutateAsync(u.id)},children:"Delete"})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ot,{user:u.user}),e.jsx(I,{className:u.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:u.isLocked?"Contract locked":"Editable draft"}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:u.status}),e.jsxs(I,{className:"bg-white/[0.08] text-white/76",children:[u.graph.nodes.length," nodes"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/76",children:[u.graph.edges.length," edges"]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.15fr)_minmax(18rem,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End state"}),e.jsx("div",{className:"text-sm leading-7 text-white/64",children:u.endStateDescription||"No end-state description yet."})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Directed execution graph"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"The graph is the contract surface for this strategy. It shows which branches are available now, where work is blocked, and whether any node is moving out of sequence."})]}),u.isLocked?null:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",onClick:()=>{o("sequence"),n(!0)},children:"Refine sequence"}),e.jsx(W,{onClick:()=>{o("sequence"),n(!0)},children:"Add parallel work"})]})]}),e.jsx(vT,{strategy:u,ownerByNodeId:T}),e.jsx(NT,{strategy:u,projectsById:A,tasksById:C})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Contract state"}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:u.isLocked?"This strategy is currently locked as a contract. The graph, targets, and descriptive plan stay frozen until you explicitly unlock it.":"This strategy is still a draft. Agents and users can keep refining the plan until you lock it."}),u.isLocked?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs("span",{children:["Locked by"," ",((P=u.lockedByUser)==null?void 0:P.displayName)??"Unknown user"]}),u.lockedAt?e.jsxs("span",{children:["· ",new Date(u.lockedAt).toLocaleString()]}):null]}):null,u.isLocked?null:e.jsx("div",{className:"mt-4 grid gap-2",children:S.map(v=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[14px] bg-white/[0.03] px-3 py-2",children:[e.jsx("div",{className:"text-sm text-white/64",children:v.label}),e.jsx(I,{className:v.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:v.satisfied?"Ready":"Missing"})]},v.id))})]}),!u.isLocked&&!y?e.jsx("div",{className:"rounded-[18px] border border-amber-400/18 bg-amber-500/[0.08] px-4 py-3 text-sm leading-6 text-amber-100/86",children:"Add a target goal or project plus an overview or end state before locking this draft as the execution contract."}):null,u.isLocked?null:e.jsx("div",{className:"mt-4 text-xs leading-5 text-white/46",children:"Drafts may stay incomplete while humans and agents negotiate the plan. Only the lock action requires the contract checks to pass."})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Alignment metrics"}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/56",children:"Alignment score"}),e.jsxs("div",{className:"mt-2 font-display text-3xl text-[var(--primary)]",children:[u.metrics.alignmentScore,"%"]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/48",children:[u.metrics.startedNodeCount,"/",u.metrics.totalNodeCount," planned nodes started,"," ",u.metrics.completedNodeCount," completed,"," ",u.metrics.readyNodeCount," ready now."]})]}),N.map(v=>e.jsxs("div",{className:"rounded-[18px] 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:"text-sm text-white/56",children:v.label}),e.jsxs("div",{className:"text-sm font-medium text-white",children:[v.value,"%"]})]}),e.jsx(xa,{value:v.value,className:"mt-3"}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/48",children:v.detail})]},v.id))]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End targets"}),u.targetGoalIds.map(v=>{const H=b.get(v);return H?e.jsx(Je,{to:`/goals/${H.id}`,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{children:["Goal: ",H.title]}),e.jsx(ot,{user:H.user,compact:!0})]})},H.id):null}),u.targetProjectIds.map(v=>{const H=A.get(v);return H?e.jsx(Je,{to:`/projects/${H.id}`,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{children:["Project: ",H.title]}),e.jsx(ot,{user:H.user,compact:!0})]})},H.id):null}),u.targetGoalIds.length===0&&u.targetProjectIds.length===0?e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:"No end targets linked yet."}):null]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked entities"}),u.linkedEntities.length===0?e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:"No additional linked entities."}):u.linkedEntities.map(v=>{var R,Q,X,Y,z,K,$;const H=ci(v.entityType,v.entityId),j=v.entityType==="goal"?(R=b.get(v.entityId))==null?void 0:R.title:v.entityType==="project"?(Q=A.get(v.entityId))==null?void 0:Q.title:v.entityType==="task"?(X=C.get(v.entityId))==null?void 0:X.title:`${v.entityType}:${v.entityId}`;return H?e.jsx(Je,{to:H,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:j}),e.jsx(ot,{user:v.entityType==="goal"?(Y=b.get(v.entityId))==null?void 0:Y.user:v.entityType==="project"?(z=A.get(v.entityId))==null?void 0:z.user:v.entityType==="task"?(K=C.get(v.entityId))==null?void 0:K.user:v.entityType==="strategy"?($=t.snapshot.strategies.find(D=>D.id===v.entityId))==null?void 0:$.user:null,compact:!0})]})},`${v.entityType}:${v.entityId}`):e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:j},`${v.entityType}:${v.entityId}`)})]})]})]}),e.jsx(Qw,{open:r,pending:g.isPending,editingStrategy:u,goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,habits:t.snapshot.habits,strategies:t.snapshot.strategies,users:t.snapshot.users,defaultUserId:d,initialStepId:l,onOpenChange:v=>{n(v),v||o(void 0)},onSubmit:async v=>{await g.mutateAsync({input:v,currentStrategyId:u.id})}})]}):e.jsx(it,{eyebrow:"Strategy",error:new Error("Strategy not found."),onRetry:()=>a("/strategies")})}const Xw=[{id:"overview",label:"Overview",icon:Lu},{id:"map",label:"Map",icon:fg},{id:"table",label:"Table",icon:Qv},{id:"history",label:"History",icon:Ag},{id:"contexts",label:"Contexts",icon:Ki},{id:"concepts",label:"Concepts",icon:Wt}],ST=new Set(["projects","tasks","strategies","habits"]),Jl=[{value:"projects",label:"Projects",description:"Goals and projects already living in Forge.",mode:"forge"},{value:"tasks",label:"Tasks",description:"Execution-level work choices inside Forge.",mode:"forge"},{value:"strategies",label:"Strategies",description:"Plan shapes and sequencing choices in Forge.",mode:"forge"},{value:"habits",label:"Habits",description:"Recurring behaviors and routines from Forge.",mode:"forge"},{value:"activities",label:"Activities",description:"Movement, leisure, and social setting concepts.",mode:"concept"},{value:"food",label:"Food",description:"Cuisine, meal mood, and drink preferences.",mode:"concept"},{value:"places",label:"Places",description:"Living environments, venues, and trip shapes.",mode:"concept"},{value:"countries",label:"Countries",description:"Country-level attraction and lifestyle fit.",mode:"concept"},{value:"fashion",label:"Fashion",description:"Silhouette, material, and palette preferences.",mode:"concept"},{value:"people",label:"People",description:"Presence, body-type, and conversation preferences.",mode:"concept"},{value:"media",label:"Media",description:"Film, reading, and music taste.",mode:"concept"},{value:"tools",label:"Tools",description:"Workflow and capture preferences.",mode:"concept"},{value:"custom",label:"Custom",description:"General-purpose concept libraries you control.",mode:"concept"}],ju={novelty:"Novelty",simplicity:"Simplicity",rigor:"Rigor",aesthetics:"Aesthetics",depth:"Depth",structure:"Structure",familiarity:"Familiarity",surprise:"Surprise"},Zl={novelty:0,simplicity:0,rigor:0,aesthetics:0,depth:0,structure:0,familiarity:0,surprise:0},nx={liked:"bg-emerald-500/12 text-emerald-200",disliked:"bg-rose-500/12 text-rose-200",uncertain:"bg-white/[0.08] text-white/70",vetoed:"bg-rose-500/15 text-rose-100",bookmarked:"bg-sky-500/12 text-sky-200",favorite:"bg-amber-500/12 text-amber-200",must_have:"bg-indigo-500/15 text-indigo-100",neutral:"bg-white/[0.08] text-white/70"},IT=[{signalType:"favorite",label:"Favorite"},{signalType:"must_have",label:"Must-have"},{signalType:"bookmark",label:"Bookmark"},{signalType:"compare_later",label:"Later"},{signalType:"neutral",label:"Neutral"},{signalType:"veto",label:"Veto"}];function eo(t){return t.trim().toLowerCase()}function Ar(t){return`${Math.round(t*100)}%`}function CT(t){return[...t.goals.map(s=>({entityType:"goal",entityId:s.id,domain:"projects",label:s.title,description:s.description,user:s.user,href:`/goals/${s.id}`,searchText:dt([s.title,s.description,s.status,s.horizon],s)})),...t.dashboard.projects.map(s=>({entityType:"project",entityId:s.id,domain:"projects",label:s.title,description:s.description,user:s.user,href:`/projects/${s.id}`,searchText:dt([s.title,s.description,s.status,s.goalTitle],s)})),...t.tasks.map(s=>({entityType:"task",entityId:s.id,domain:"tasks",label:s.title,description:s.description,user:s.user,href:`/tasks/${s.id}`,searchText:dt([s.title,s.description,s.status,s.priority,s.owner],s)})),...t.strategies.map(s=>({entityType:"strategy",entityId:s.id,domain:"strategies",label:s.title,description:s.overview||s.endStateDescription,user:s.user,href:`/strategies/${s.id}`,searchText:dt([s.title,s.overview,s.endStateDescription,s.status],s)})),...t.habits.map(s=>({entityType:"habit",entityId:s.id,domain:"habits",label:s.title,description:s.description,user:s.user,href:null,searchText:dt([s.title,s.description,s.status,s.frequency],s)}))]}function TT(t,s){return!t||!s?null:t==="goal"?`/goals/${s}`:t==="project"?`/projects/${s}`:t==="task"?`/tasks/${s}`:t==="strategy"?`/strategies/${s}`:null}function to(t){return t.manualStatus??t.status}function PT(t){return t&&Xw.some(s=>s.id===t)?t:"overview"}function AT(t){return t.summary.totalItems<2?{title:"Forge does not know enough yet.",description:"Start the game so Forge can ask a few clean comparisons and build a real preference model."}:t.summary.averageConfidence<.28?{title:"Forge has a rough sketch, not a stable read.",description:"There is some signal, but the model still needs more rounds before its preferences are trustworthy."}:{title:"This is what Forge currently thinks.",description:"The summary below is the current best model for this user, this domain, and the active context."}}function MT({summary:t}){const s=Math.max(-1,Math.min(1,t.leaning)),a=(s+1)/2*100;return e.jsxs("div",{className:"grid gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-white/56",children:[e.jsx("span",{children:ju[t.dimensionId]}),e.jsxs("span",{children:[t.movement>.08?"Rising":t.movement<-.08?"Falling":"Stable"," ","· ",Ar(t.confidence)]})]}),e.jsxs("div",{className:"relative h-2 rounded-full bg-white/[0.08]",children:[e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/10"}),e.jsx("div",{className:te("absolute top-1/2 size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border border-white/12",s>=0?"bg-emerald-300":"bg-rose-300"),style:{left:`${a}%`}})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.12em] text-white/38",children:[e.jsxs("span",{children:[s>=0?"Leans toward":"Leans away from"," ",ju[t.dimensionId].toLowerCase()]}),e.jsxs("span",{children:["Context ",Ar(t.contextSensitivity)]})]})]})}function lx({title:t,description:s,sideLabel:a,onClick:i}){return e.jsxs("button",{type:"button",className:"grid min-h-[220px] gap-4 rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.07),rgba(255,255,255,0.03))] p-5 text-left transition hover:border-[var(--primary)]/40 hover:bg-[linear-gradient(180deg,rgba(192,193,255,0.14),rgba(255,255,255,0.05))]",onClick:i,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:a}),e.jsx("div",{className:"font-display text-3xl text-white",children:t}),e.jsx("div",{className:"max-w-[36ch] text-sm leading-6 text-white/56",children:s||"Choose the one that feels more right."}),e.jsx("div",{className:"mt-auto text-sm text-[var(--primary)]",children:"Click this card"})]})}function ET(){var He,lt,Nt,me,Pe;const t=jt(),s=ct(),[a,i]=ms(),[r,n]=c.useState(""),[l,o]=c.useState(""),[d,m]=c.useState(""),[h,u]=c.useState(""),[x,g]=c.useState(""),[p,f]=c.useState({open:!1,phase:"domain",domain:a.get("domain")??"projects"}),[b,A]=c.useState(null),[C,T]=c.useState(!1),[w,S]=c.useState(null),[y,N]=c.useState({label:"",description:"",tags:"",manualStatus:"",manualScore:"",confidenceLock:"",bookmarked:!1,compareLater:!1,frozen:!1,featureWeights:{novelty:"0",simplicity:"0",rigor:"0",aesthetics:"0",depth:"0",structure:"0",familiarity:"0",surprise:"0"}}),[P,v]=c.useState({label:"",description:"",tags:""}),[H,j]=c.useState({name:"",description:"",shareMode:"blended",decayDays:"90"}),[R,Q]=c.useState({title:"",description:""}),[X,Y]=c.useState({}),[z,K]=c.useState(null),[$,D]=c.useState({title:"",description:""}),[J,q]=c.useState(null),[_,B]=c.useState({label:"",description:"",tags:""}),G=a.get("userId")??ys(t.selectedUserIds)??((He=t.snapshot.users[0])==null?void 0:He.id)??null,ae=a.get("domain")??"projects",ke=PT(a.get("tab")),Ae=a.get("contextId"),ie=a.get("focusItem"),Ie=c.useMemo(()=>t.snapshot.users.find(k=>k.id===G)??null,[G,t.snapshot.users]),Ne=c.useMemo(()=>CT(t.snapshot),[t.snapshot]),M=Fe({queryKey:["forge-preferences",G,ae,Ae],queryFn:async()=>(await ch({userId:G??void 0,domain:ae,contextId:Ae??void 0})).workspace,enabled:!!G}),E=Fe({queryKey:["forge-preferences-game",G,p.domain,Ae],queryFn:async()=>(await ch({userId:G??void 0,domain:p.domain,contextId:Ae??void 0})).workspace,enabled:!!G&&p.open}),O=M.data??null,xe=p.domain===ae?O:E.data??null;c.useEffect(()=>{var se;if(!O)return;const k=ie&&O.scores.some(_e=>_e.itemId===ie)?ie:((se=O.scores[0])==null?void 0:se.itemId)??null;S(_e=>_e&&O.scores.some(Be=>Be.itemId===_e)?_e:k)},[ie,O]);const V=c.useMemo(()=>{if(!O)return[];const k=eo(r);return k?O.scores.filter(se=>{var _e,Be,Ge;return[((_e=se.item)==null?void 0:_e.label)??"",((Be=se.item)==null?void 0:Be.description)??"",((Ge=se.item)==null?void 0:Ge.tags.join(" "))??"",se.status,se.manualStatus??"",se.dominantDimensions.join(" "),se.explanation.join(" ")].join(" ").toLowerCase().includes(k)}):O.scores},[r,O]),Se=V.find(k=>k.itemId===w)??(O==null?void 0:O.scores.find(k=>k.itemId===w))??V[0]??(O==null?void 0:O.scores[0])??null;c.useEffect(()=>{var k,se,_e,Be,Ge,gt,Mt,Vt,Os,qa,Ba;Se&&N({label:((k=Se.item)==null?void 0:k.label)??"",description:((se=Se.item)==null?void 0:se.description)??"",tags:((_e=Se.item)==null?void 0:_e.tags.join(", "))??"",manualStatus:Se.manualStatus??"",manualScore:typeof Se.manualScore=="number"?String(Se.manualScore):"",confidenceLock:typeof Se.confidenceLock=="number"?String(Se.confidenceLock):"",bookmarked:Se.bookmarked,compareLater:Se.compareLater,frozen:Se.frozen,featureWeights:{novelty:String(((Be=Se.item)==null?void 0:Be.featureWeights.novelty)??0),simplicity:String(((Ge=Se.item)==null?void 0:Ge.featureWeights.simplicity)??0),rigor:String(((gt=Se.item)==null?void 0:gt.featureWeights.rigor)??0),aesthetics:String(((Mt=Se.item)==null?void 0:Mt.featureWeights.aesthetics)??0),depth:String(((Vt=Se.item)==null?void 0:Vt.featureWeights.depth)??0),structure:String(((Os=Se.item)==null?void 0:Os.featureWeights.structure)??0),familiarity:String(((qa=Se.item)==null?void 0:qa.featureWeights.familiarity)??0),surprise:String(((Ba=Se.item)==null?void 0:Ba.featureWeights.surprise)??0)}})},[Se]);const Ee=c.useMemo(()=>{const k=eo(l);return Ne.filter(se=>se.domain===ae).filter(se=>k?se.searchText.includes(k):!0).slice(0,12)},[Ne,l,ae]),Ce=c.useMemo(()=>{const k=ke==="concepts"?O:xe??O,se=(k==null?void 0:k.catalogs)??[],_e=eo(d);return _e?se.filter(Be=>[Be.title,Be.description,Be.source,...Be.items.flatMap(Ge=>[Ge.label,Ge.description,Ge.tags.join(" ")])].join(" ").toLowerCase().includes(_e)):se},[xe,d,ke,O]),qe=async()=>{await s.invalidateQueries({queryKey:["forge-preferences"]}),await s.invalidateQueries({queryKey:["forge-preferences-game"]})},oe=Re({mutationFn:Hc,onSuccess:qe}),L=Re({mutationFn:Cj,onSuccess:async({item:k})=>{await qe(),v({label:"",description:"",tags:""}),S(k.id)}}),U=Re({mutationFn:bj,onSuccess:async()=>{await qe(),Q({title:"",description:""}),i(k=>{const se=new URLSearchParams(k);return se.set("tab","concepts"),se})}}),ge=Re({mutationFn:({catalogId:k,patch:se})=>wj(k,se),onSuccess:async()=>{await qe(),K(null)}}),Te=Re({mutationFn:yj,onSuccess:qe}),ve=Re({mutationFn:vj,onSuccess:async()=>{await qe()}}),Le=Re({mutationFn:({catalogItemId:k,patch:se})=>jj(k,se),onSuccess:async()=>{await qe(),q(null)}}),Qe=Re({mutationFn:Nj,onSuccess:qe}),st=Re({mutationFn:fj,onSuccess:async()=>{await qe(),f(k=>({...k,phase:"play"}))}}),F=Re({mutationFn:Pj,onSuccess:qe}),he=Re({mutationFn:Aj,onSuccess:qe}),we=Re({mutationFn:async()=>{!(Se!=null&&Se.item)||!G||!O||(await Tj(Se.item.id,{label:y.label,description:y.description,tags:y.tags.split(",").map(k=>k.trim()).filter(Boolean),featureWeights:Object.fromEntries(Object.keys(Zl).map(k=>[k,Number(y.featureWeights[k]||0)]))}),await Mj(Se.item.id,{userId:G,domain:ae,contextId:O.selectedContext.id,manualStatus:y.manualStatus||null,manualScore:y.manualScore.trim().length>0?Number(y.manualScore):null,confidenceLock:y.confidenceLock.trim().length>0?Number(y.confidenceLock):null,bookmarked:y.bookmarked,compareLater:y.compareLater,frozen:y.frozen}))},onSuccess:qe}),Z=Re({mutationFn:kj,onSuccess:async({context:k})=>{await qe(),j({name:"",description:"",shareMode:"blended",decayDays:"90"}),i(se=>{const _e=new URLSearchParams(se);return _e.set("contextId",k.id),_e.set("tab","contexts"),_e})}}),De=Re({mutationFn:Ij,onSuccess:async()=>{await qe(),u(""),g("")}}),ee=Re({mutationFn:({contextId:k,patch:se})=>Sj(k,se),onSuccess:qe}),ze=k=>{i(se=>{const _e=new URLSearchParams(se);for(const[Be,Ge]of Object.entries(k))Ge?_e.set(Be,Ge):_e.delete(Be);return _e})},et=(k=ae)=>{A(null),f({open:!0,phase:"domain",domain:k})},Ve=async k=>{if(!G)return;A(null),T(!0);const se=Ne.filter(Ge=>{var gt;return Ge.domain===k&&((gt=Ge.user)==null?void 0:gt.id)===G}),_e=Ne.filter(Ge=>Ge.domain===k),Be=(se.length>0?se:_e).slice(0,12);if(Be.length<2){A("Forge needs at least two matching records in this domain before it can start the game."),T(!1),f(Ge=>({...Ge,phase:"domain"}));return}try{ze({domain:k,tab:"overview",contextId:null,focusItem:null}),await Promise.all(Be.map(Ge=>Hc({userId:G,domain:k,entityType:Ge.entityType,entityId:Ge.entityId,label:Ge.label,description:Ge.description,tags:[]}))),await qe(),f({open:!0,phase:"play",domain:k})}catch(Ge){A(Ge instanceof Error?Ge.message:"Forge could not start the game."),f(gt=>({...gt,phase:"domain"}))}finally{T(!1)}},re=async(k,se)=>{if(G){A(null),ze({domain:k,tab:"overview",contextId:null,focusItem:null});try{await st.mutateAsync({userId:G,domain:k,contextId:Ae??void 0,catalogId:se}),f({open:!0,phase:"play",domain:k})}catch(_e){A(_e instanceof Error?_e.message:"Forge could not start the game.")}}},ne=async k=>{if(ST.has(k)){await Ve(k);return}A(null),f({open:!0,phase:"catalog",domain:k})},be=async(k,se=1)=>{if(!G||!(xe!=null&&xe.compare.nextPair))return;const _e=xe.compare.nextPair;await F.mutateAsync({userId:G,domain:p.domain,contextId:xe.selectedContext.id,leftItemId:_e.left.id,rightItemId:_e.right.id,outcome:k,strength:se})},je=async(k,se)=>{!G||!xe||await he.mutateAsync({userId:G,domain:p.domain,contextId:xe.selectedContext.id,itemId:k,signalType:se,strength:1})};if(!G)return e.jsx(Bt,{eyebrow:"Preferences",title:"No Forge user available",description:"Forge needs at least one human or bot user before it can learn preferences."});if(M.isLoading&&!O)return e.jsx(Et,{eyebrow:"Preferences",title:"Loading preference model",description:"Reconstructing current scores, uncertainty, and concept libraries."});if(M.isError)return e.jsx(it,{eyebrow:"Preferences",error:M.error,onRetry:()=>void M.refetch()});if(!O)return null;const pe=[...O.dimensions].sort((k,se)=>se.confidence-k.confidence).slice(0,6),$e=O.scores.filter(k=>to(k)==="liked"||to(k)==="favorite").slice(0,4),Xe=O.scores.filter(k=>k.uncertainty>=.5).slice(0,4),Ue=AT(O),le=TT(((lt=Se==null?void 0:Se.item)==null?void 0:lt.sourceEntityType)??null,((Nt=Se==null?void 0:Se.item)==null?void 0:Nt.sourceEntityId)??null),Me=(xe==null?void 0:xe.compare.nextPair)??null;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:"Preferences",titleText:"Preferences",description:"Forge keeps an explicit, editable model of what one user prefers in one domain. The first job of this page is to show what Forge currently knows.",badge:`${O.summary.totalItems} items · ${Ar(O.summary.averageConfidence)} confidence`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{className:"min-w-[10rem]",onClick:()=>et(),children:"Start the game"}),e.jsx(W,{variant:"secondary",onClick:()=>void qe(),children:"Refresh model"})]})}),e.jsx(ks,{}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Active user"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("select",{value:G,onChange:k=>ze({userId:k.target.value,contextId:null,focusItem:null}),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:t.snapshot.users.map(k=>e.jsxs("option",{value:k.id,children:[k.displayName," · ",k.kind]},k.id))}),e.jsx(ot,{user:Ie}),e.jsx("div",{className:"text-sm text-white/54",children:os(Ie)})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Domain"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Jl.map(k=>e.jsx("button",{type:"button",className:te("rounded-full border px-3 py-2 text-sm transition",k.value===ae?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"),onClick:()=>ze({domain:k.value,contextId:null,focusItem:null}),children:k.label},k.value))}),e.jsx("div",{className:"text-sm text-white/48",children:(me=Jl.find(k=>k.value===ae))==null?void 0:me.description})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/50",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:O.selectedContext.name}),e.jsx("span",{children:O.selectedContext.shareMode}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[O.compare.pendingCount," queued comparisons"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[O.libraries.totalCatalogItems," concept items ready"]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Xw.map(k=>e.jsxs("button",{type:"button",className:te("inline-flex items-center gap-2 rounded-full border px-3 py-2 text-sm transition",k.id===ke?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"),onClick:()=>ze({tab:k.id}),children:[e.jsx(k.icon,{className:"size-4"}),k.label]},k.id))}),ke==="overview"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_360px]",children:[e.jsxs(ce,{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"What Forge knows"}),e.jsx("div",{className:"font-display text-3xl text-white",children:Ue.title}),e.jsx("div",{className:"max-w-[70ch] text-sm leading-6 text-white/58",children:Ue.description})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[{label:"Known items",value:O.summary.totalItems,detail:"Items inside this domain"},{label:"Confidence",value:Ar(O.summary.averageConfidence),detail:"Average certainty"},{label:"Unknowns",value:O.summary.uncertainCount,detail:"Need more rounds"},{label:"Libraries",value:O.libraries.totalCatalogItems,detail:"Seeded concepts ready"}].map(k=>e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:k.label}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:k.value}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:k.detail})]},k.label))}),e.jsx("div",{className:"grid gap-4 lg:grid-cols-2",children:pe.map(k=>e.jsx(MT,{summary:k},k.dimensionId))})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Next move"}),e.jsx("div",{className:"font-display text-2xl text-white",children:"Start the game"}),e.jsx("div",{className:"text-sm leading-6 text-white/58",children:"Forge will ask a small number of pairwise questions. You choose a domain, Forge supplies the candidates, and the model tightens from there."}),e.jsx(W,{className:"w-full",onClick:()=>et(),children:"Start the game"}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:[e.jsxs("div",{children:["Current queue: ",O.compare.pendingCount," comparison",O.compare.pendingCount===1?"":"s"]}),e.jsxs("div",{children:["Active context: ",O.selectedContext.name]}),e.jsxs("div",{children:["Library coverage: ",O.libraries.seededCatalogCount," ","seeded lists and ",O.libraries.customCatalogCount," ","custom lists"]})]})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_360px]",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Preference map"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Green drifts positive, red drifts negative, and low opacity still means uncertainty."})]}),e.jsx(Je,{to:"?tab=map",className:"text-sm text-[var(--primary)]",children:"Open full map"})]}),e.jsxs("div",{className:"relative min-h-[340px] overflow-hidden rounded-[24px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(87,196,138,0.18),transparent_35%),radial-gradient(circle_at_bottom_right,rgba(255,104,130,0.14),transparent_30%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0.01))]",children:[e.jsx("div",{className:"absolute inset-x-0 top-1/2 h-px bg-white/8"}),e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/8"}),O.map.map(k=>e.jsx("button",{type:"button",className:te("absolute -translate-x-1/2 -translate-y-1/2 rounded-full border px-2 py-1 text-[11px] shadow-[0_10px_25px_rgba(5,8,16,0.32)] transition hover:scale-[1.04]",k.itemId===(Se==null?void 0:Se.itemId)?"border-white/30 bg-white/16 text-white":k.score>=0?"border-emerald-300/30 bg-emerald-500/14 text-emerald-100":"border-rose-300/30 bg-rose-500/14 text-rose-100"),style:{left:`${50+k.x*30}%`,top:`${50-k.y*30}%`,opacity:.55+k.confidence*.45},onClick:()=>S(k.itemId),children:k.label},k.itemId))]})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Best read so far"}),e.jsx("div",{className:"grid gap-2",children:$e.length>0?$e.map(k=>{var se;return e.jsxs("button",{type:"button",className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>{S(k.itemId),ze({focusItem:k.itemId})},children:[e.jsx("div",{className:"font-medium text-white",children:((se=k.item)==null?void 0:se.label)??k.itemId}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:k.explanation[0]||"Forge has positive evidence here."})]},k.itemId)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:"No clear positives yet. A few comparison rounds will change that."})}),e.jsxs("div",{className:"border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Biggest unknowns"}),e.jsx("div",{className:"mt-3 grid gap-2",children:Xe.length>0?Xe.map(k=>{var se;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:[e.jsx("div",{className:"font-medium text-white",children:((se=k.item)==null?void 0:se.label)??k.itemId}),e.jsxs("div",{className:"mt-1",children:["Uncertainty ",Ar(k.uncertainty)]})]},k.itemId)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:"The current unknown list is short."})})]})]})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Bring in Forge records"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Search goals, projects, tasks, strategies, or habits across human and bot users, then send them straight into this model."})]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[Ee.length," visible"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:l,onChange:k=>o(k.target.value),placeholder:"Search across owners, handles, user kind, title, and description"})]}),e.jsx("div",{className:"grid gap-2",children:Ee.map(k=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium text-white",children:k.label}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:k.entityType}),k.user?e.jsx(ot,{user:k.user,compact:!0}):null]}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:k.description||"No description yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[k.href?e.jsx(Je,{to:k.href,children:e.jsx(W,{variant:"ghost",size:"sm",children:"Open"})}):null,e.jsx(W,{variant:"secondary",size:"sm",pending:oe.isPending,pendingLabel:"Adding",onClick:()=>void oe.mutateAsync({userId:G,domain:ae,entityType:k.entityType,entityId:k.entityId,label:k.label,description:k.description,tags:[]}),children:"Add to model"})]})]},`${k.entityType}-${k.entityId}`))})]})]}):null,ke==="map"?e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Full map"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Click a point to inspect why Forge believes it belongs there."})]}),e.jsxs("div",{className:"text-sm text-white/52",children:[O.map.length," plotted items"]})]}),e.jsxs("div",{className:"relative min-h-[520px] overflow-hidden rounded-[24px] border border-white/8 bg-[radial-gradient(circle_at_20%_20%,rgba(87,196,138,0.2),transparent_25%),radial-gradient(circle_at_80%_80%,rgba(255,104,130,0.2),transparent_26%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0.01))]",children:[e.jsx("div",{className:"absolute inset-x-0 top-1/2 h-px bg-white/8"}),e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/8"}),O.map.map(k=>e.jsx("button",{type:"button",className:te("absolute -translate-x-1/2 -translate-y-1/2 rounded-full border px-3 py-1 text-xs transition hover:scale-[1.04]",k.itemId===(Se==null?void 0:Se.itemId)?"border-white/30 bg-white/16 text-white":k.score>=0?"border-emerald-300/30 bg-emerald-500/14 text-emerald-100":"border-rose-300/30 bg-rose-500/14 text-rose-100"),style:{left:`${50+k.x*34}%`,top:`${50-k.y*34}%`,opacity:.45+k.confidence*.55},onClick:()=>{S(k.itemId),ze({focusItem:k.itemId})},children:k.label},k.itemId))]})]}):null,ke==="table"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_380px]",children:[e.jsxs(ce,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:r,onChange:k=>n(k.target.value),placeholder:"Search learned items, explanations, tags, or dominant dimensions"})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full text-left text-sm",children:[e.jsx("thead",{className:"text-[11px] uppercase tracking-[0.14em] text-white/38",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"Item"}),e.jsx("th",{className:"px-3 py-2",children:"Score"}),e.jsx("th",{className:"px-3 py-2",children:"Confidence"}),e.jsx("th",{className:"px-3 py-2",children:"Status"}),e.jsx("th",{className:"px-3 py-2",children:"Evidence"})]})}),e.jsx("tbody",{children:V.map(k=>{var se,_e;return e.jsxs("tr",{className:te("cursor-pointer border-t border-white/6 transition hover:bg-white/[0.04]",k.itemId===(Se==null?void 0:Se.itemId)?"bg-white/[0.05]":""),onClick:()=>{S(k.itemId),ze({focusItem:k.itemId})},children:[e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"font-medium text-white",children:((se=k.item)==null?void 0:se.label)??k.itemId}),e.jsx("div",{className:"text-xs text-white/48",children:(((_e=k.item)==null?void 0:_e.tags)??[]).join(" · ")})]}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:k.latentScore.toFixed(2)}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:Ar(k.confidence)}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(I,{className:nx[to(k)],children:to(k)})}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:k.evidenceCount})]},k.itemId)})})]})})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Item editor"}),Se!=null&&Se.item?e.jsxs(e.Fragment,{children:[e.jsx(ye,{value:y.label,onChange:k=>N(se=>({...se,label:k.target.value})),placeholder:"Item label"}),e.jsx(Ze,{value:y.description,onChange:k=>N(se=>({...se,description:k.target.value})),className:"min-h-24",placeholder:"Item description"}),e.jsx(ye,{value:y.tags,onChange:k=>N(se=>({...se,tags:k.target.value})),placeholder:"comma, separated, tags"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("select",{value:y.manualStatus,onChange:k=>N(se=>({...se,manualStatus:k.target.value})),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Inferred status"}),Object.keys(nx).map(k=>e.jsx("option",{value:k,children:k},k))]}),e.jsx(ye,{value:y.manualScore,onChange:k=>N(se=>({...se,manualScore:k.target.value})),placeholder:"Manual score"}),e.jsx(ye,{value:y.confidenceLock,onChange:k=>N(se=>({...se,confidenceLock:k.target.value})),placeholder:"Confidence lock 0-1"})]}),e.jsx("div",{className:"grid gap-2",children:Object.keys(Zl).map(k=>e.jsxs("div",{className:"grid grid-cols-[110px_minmax(0,1fr)] items-center gap-3",children:[e.jsx("div",{className:"text-sm text-white/56",children:ju[k]}),e.jsx(ye,{value:y.featureWeights[k],onChange:se=>N(_e=>({..._e,featureWeights:{..._e.featureWeights,[k]:se.target.value}}))})]},k))}),e.jsx("div",{className:"grid gap-2 text-sm text-white/58",children:[["bookmarked","Bookmarked"],["compareLater","Compare later"],["frozen","Frozen"]].map(([k,se])=>e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:y[k],onChange:_e=>N(Be=>({...Be,[k]:_e.target.checked}))}),e.jsx("span",{children:se})]},k))}),e.jsx(W,{pending:we.isPending,pendingLabel:"Saving item",onClick:()=>void we.mutateAsync(),children:"Save item model"}),le?e.jsx(Je,{className:"text-sm text-[var(--primary)]",to:le,children:"Open linked entity"}):null]}):e.jsx("div",{className:"text-sm text-white/52",children:"Select a row to inspect or edit it."}),e.jsxs("div",{className:"mt-3 border-t border-white/8 pt-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Add custom item"}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsx(ye,{value:P.label,onChange:k=>v(se=>({...se,label:k.target.value})),placeholder:"Custom item label"}),e.jsx(Ze,{value:P.description,onChange:k=>v(se=>({...se,description:k.target.value})),className:"min-h-24",placeholder:"What is this preference item?"}),e.jsx(ye,{value:P.tags,onChange:k=>v(se=>({...se,tags:k.target.value})),placeholder:"comma, separated, tags"}),e.jsx(W,{disabled:!P.label.trim(),pending:L.isPending,pendingLabel:"Creating item",onClick:()=>void L.mutateAsync({userId:G,domain:ae,label:P.label,description:P.description,tags:P.tags.split(",").map(k=>k.trim()).filter(Boolean),featureWeights:Zl,queueForCompare:!0}),children:"Create custom item"})]})]})]})]}):null,ke==="history"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-3",children:[e.jsxs(ce,{className:"grid gap-3 xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Recent pairwise judgments"}),e.jsx("div",{className:"grid gap-2",children:O.history.judgments.slice(0,12).map(k=>{var Be,Ge,gt,Mt;const se=((Ge=(Be=O.scores.find(Vt=>Vt.itemId===k.leftItemId))==null?void 0:Be.item)==null?void 0:Ge.label)??k.leftItemId,_e=((Mt=(gt=O.scores.find(Vt=>Vt.itemId===k.rightItemId))==null?void 0:gt.item)==null?void 0:Mt.label)??k.rightItemId;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/58",children:[e.jsxs("div",{className:"font-medium text-white",children:[se," vs ",_e]}),e.jsxs("div",{className:"mt-1",children:["Outcome ",k.outcome," · strength"," ",k.strength," ·"," ",new Date(k.createdAt).toLocaleString()]})]},k.id)})})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Signals and snapshots"}),e.jsx("div",{className:"grid gap-2",children:O.history.signals.slice(0,8).map(k=>{var _e,Be;const se=((Be=(_e=O.scores.find(Ge=>Ge.itemId===k.itemId))==null?void 0:_e.item)==null?void 0:Be.label)??k.itemId;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-2 text-sm text-white/58",children:[se," · ",k.signalType," ·"," ",new Date(k.createdAt).toLocaleString()]},k.id)})}),e.jsx("div",{className:"grid gap-2",children:O.history.snapshots.slice(0,5).map(k=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-2 text-sm text-white/58",children:["Snapshot ",new Date(k.createdAt).toLocaleString()]},k.id))}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:["Stale items: ",O.history.staleItemIds.length," · Flipped items: ",O.history.flippedItemIds.length]})]})]}):null,ke==="contexts"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_360px]",children:[e.jsx("div",{className:"grid gap-4",children:O.contexts.map(k=>e.jsxs(ce,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-2xl text-white",children:k.name}),e.jsx("div",{className:"text-sm text-white/54",children:k.description||"No description yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[k.isDefault?e.jsx(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Default"}):null,e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:k.shareMode}),k.active?null:e.jsx(I,{className:"bg-amber-500/12 text-amber-200",children:"Inactive"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[e.jsx(ye,{value:k.name,onChange:se=>void ee.mutateAsync({contextId:k.id,patch:{name:se.target.value}}),placeholder:"Context name"}),e.jsxs("select",{value:k.shareMode,onChange:se=>void ee.mutateAsync({contextId:k.id,patch:{shareMode:se.target.value}}),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"shared",children:"shared"}),e.jsx("option",{value:"blended",children:"blended"}),e.jsx("option",{value:"isolated",children:"isolated"})]}),e.jsx(ye,{value:String(k.decayDays),onChange:se=>void ee.mutateAsync({contextId:k.id,patch:{decayDays:Number(se.target.value||90)}}),placeholder:"Decay days"}),e.jsx(W,{variant:"secondary",onClick:()=>ze({contextId:k.id,tab:"overview"}),children:"Open context"})]}),e.jsx(Ze,{value:k.description,onChange:se=>void ee.mutateAsync({contextId:k.id,patch:{description:se.target.value}}),className:"min-h-20"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",onClick:()=>void ee.mutateAsync({contextId:k.id,patch:{active:!k.active}}),children:k.active?"Deactivate":"Activate"}),k.isDefault?null:e.jsx(W,{variant:"secondary",onClick:()=>void ee.mutateAsync({contextId:k.id,patch:{isDefault:!0}}),children:"Make default"})]})]},k.id))}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Create context"}),e.jsx(ye,{value:H.name,onChange:k=>j(se=>({...se,name:k.target.value})),placeholder:"Context name"}),e.jsx(Ze,{value:H.description,onChange:k=>j(se=>({...se,description:k.target.value})),className:"min-h-24",placeholder:"What changes in this context?"}),e.jsxs("select",{value:H.shareMode,onChange:k=>j(se=>({...se,shareMode:k.target.value})),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"blended",children:"blended"}),e.jsx("option",{value:"shared",children:"shared"}),e.jsx("option",{value:"isolated",children:"isolated"})]}),e.jsx(ye,{value:H.decayDays,onChange:k=>j(se=>({...se,decayDays:k.target.value})),placeholder:"Decay days"}),e.jsx(W,{disabled:!H.name.trim(),pending:Z.isPending,pendingLabel:"Creating context",onClick:()=>void Z.mutateAsync({userId:G,domain:ae,name:H.name,description:H.description,shareMode:H.shareMode,decayDays:Number(H.decayDays||90),active:!0,isDefault:!1}),children:"Create context"})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Merge contexts"}),e.jsxs("select",{value:h,onChange:k=>u(k.target.value),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Source context"}),O.contexts.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id))]}),e.jsxs("select",{value:x,onChange:k=>g(k.target.value),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Target context"}),O.contexts.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id))]}),e.jsx(W,{pending:De.isPending,pendingLabel:"Merging",disabled:!h||!x||h===x,onClick:()=>void De.mutateAsync({sourceContextId:h,targetContextId:x}),children:"Merge into target"})]})]})]}):null,ke==="concepts"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_380px]",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Concept libraries"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"These are the lists Forge can use when you start the game in a concept domain. Seeded lists are editable, and custom lists are fully yours."})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-4",children:[["Lists",O.libraries.totalCatalogs],["Concepts",O.libraries.totalCatalogItems],["Seeded",O.libraries.seededCatalogCount],["Custom",O.libraries.customCatalogCount]].map(([k,se])=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:k}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:se})]},k))}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:d,onChange:k=>m(k.target.value),placeholder:"Search lists, concepts, tags, and seeded domains"})]})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Create concept list"}),e.jsx(ye,{value:R.title,onChange:k=>Q(se=>({...se,title:k.target.value})),placeholder:"List title"}),e.jsx(Ze,{value:R.description,onChange:k=>Q(se=>({...se,description:k.target.value})),className:"min-h-24",placeholder:"What should this list help compare?"}),e.jsx(W,{disabled:!R.title.trim(),pending:U.isPending,pendingLabel:"Creating list",onClick:()=>void U.mutateAsync({userId:G,domain:ae,title:R.title,description:R.description}),children:"Create list"})]})]}),e.jsx("div",{className:"grid gap-4",children:Ce.map(k=>{const se=X[k.id]??{label:"",description:"",tags:""},_e=k.items.filter(Be=>d.trim()?[Be.label,Be.description,Be.tags.join(" ")].join(" ").toLowerCase().includes(eo(d)):!0);return e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:z===k.id?e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ye,{value:$.title,onChange:Be=>D(Ge=>({...Ge,title:Be.target.value}))}),e.jsx(Ze,{value:$.description,onChange:Be=>D(Ge=>({...Ge,description:Be.target.value})),className:"min-h-24"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"font-display text-2xl text-white",children:k.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:k.source}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[k.items.length," items"]})]}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:k.description||"No description yet."})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>void re(ae,k.id),children:"Start from this list"}),z===k.id?e.jsxs(e.Fragment,{children:[e.jsx(W,{size:"sm",pending:ge.isPending,pendingLabel:"Saving",onClick:()=>void ge.mutateAsync({catalogId:k.id,patch:{title:$.title,description:$.description}}),children:"Save"}),e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>K(null),children:"Cancel"})]}):e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>{K(k.id),D({title:k.title,description:k.description})},children:"Edit list"}),e.jsx(W,{variant:"ghost",size:"sm",pending:Te.isPending,pendingLabel:"Deleting",onClick:()=>void Te.mutateAsync(k.id),children:"Delete list"})]})]}),e.jsx("div",{className:"grid gap-2",children:_e.map(Be=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:J===Be.id?e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ye,{value:_.label,onChange:Ge=>B(gt=>({...gt,label:Ge.target.value}))}),e.jsx(Ze,{value:_.description,onChange:Ge=>B(gt=>({...gt,description:Ge.target.value})),className:"min-h-20"}),e.jsx(ye,{value:_.tags,onChange:Ge=>B(gt=>({...gt,tags:Ge.target.value})),placeholder:"comma, separated, tags"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{size:"sm",pending:Le.isPending,pendingLabel:"Saving",onClick:()=>void Le.mutateAsync({catalogItemId:Be.id,patch:{label:_.label,description:_.description,tags:_.tags.split(",").map(Ge=>Ge.trim()).filter(Boolean)}}),children:"Save concept"}),e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>q(null),children:"Cancel"})]})]}):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-medium text-white",children:Be.label}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:Be.description||"No description yet."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Be.tags.map(Ge=>e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:Ge},`${Be.id}-${Ge}`))})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>{q(Be.id),B({label:Be.label,description:Be.description,tags:Be.tags.join(", ")})},children:"Edit"}),e.jsxs(W,{variant:"ghost",size:"sm",pending:Qe.isPending,pendingLabel:"Deleting",onClick:()=>void Qe.mutateAsync(Be.id),children:[e.jsx(Rt,{className:"mr-1 size-4"}),"Delete"]})]})]})},Be.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] border border-white/8 bg-white/[0.02] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/68",children:[e.jsx(ds,{className:"size-4"}),"Add concept to ",k.title]}),e.jsx(ye,{value:se.label,onChange:Be=>Y(Ge=>({...Ge,[k.id]:{...se,label:Be.target.value}})),placeholder:"Concept label"}),e.jsx(Ze,{value:se.description,onChange:Be=>Y(Ge=>({...Ge,[k.id]:{...se,description:Be.target.value}})),className:"min-h-20",placeholder:"Short description"}),e.jsx(ye,{value:se.tags,onChange:Be=>Y(Ge=>({...Ge,[k.id]:{...se,tags:Be.target.value}})),placeholder:"comma, separated, tags"}),e.jsx(W,{disabled:!se.label.trim(),pending:ve.isPending,pendingLabel:"Adding",onClick:()=>void ve.mutateAsync({catalogId:k.id,label:se.label,description:se.description,tags:se.tags.split(",").map(Be=>Be.trim()).filter(Boolean),featureWeights:Zl}).then(()=>Y(Be=>({...Be,[k.id]:{label:"",description:"",tags:""}}))),children:"Add concept"})]})]},k.id)})})]}):null]}),e.jsx(Yt,{open:p.open,onOpenChange:k=>{k||A(null),f(se=>({...se,open:k}))},children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.74)] backdrop-blur-xl"}),e.jsxs(es,{className:"fixed inset-x-4 bottom-4 top-4 z-50 overflow-y-auto rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(17,24,39,0.98),rgba(10,14,24,0.98))] shadow-[0_30px_90px_rgba(3,8,18,0.45)] md:inset-x-10 lg:left-1/2 lg:right-auto lg:w-[min(72rem,calc(100vw-3rem))] lg:-translate-x-1/2",children:[e.jsx(ts,{className:"sr-only",children:"Preference game"}),e.jsx(rs,{className:"sr-only",children:"Start comparison rounds from a Forge domain or concept list."}),e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between gap-4 border-b border-white/8 bg-[rgba(10,14,24,0.92)] px-5 py-4 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Preference game"}),e.jsx("div",{className:"mt-1 font-display text-2xl text-white",children:p.phase==="domain"?"Choose a domain":p.phase==="catalog"?"Choose a concept list":"Pick the better fit"})]}),e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Close preference game",className:"rounded-full bg-white/6 p-2 text-white/65 transition hover:bg-white/10 hover:text-white",children:e.jsx(Tt,{className:"size-4"})})})]}),e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[b?e.jsx("div",{className:"rounded-[18px] border border-rose-400/25 bg-rose-500/10 px-4 py-3 text-sm text-rose-100",children:b}):null,p.phase==="domain"?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:Jl.map(k=>e.jsxs("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.04] px-5 py-5 text-left transition hover:border-[var(--primary)]/30 hover:bg-[var(--primary)]/10",onClick:()=>void ne(k.value),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:k.label}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:k.mode==="forge"?"Forge":"Concept"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:k.description})]},k.value))}):null,p.phase==="catalog"?e.jsxs("div",{className:"grid gap-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Pick the concept list Forge should draw from. You do not need to assemble the items yourself."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:d,onChange:k=>m(k.target.value),placeholder:"Search concept lists"})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:Ce.length>0?Ce.map(k=>e.jsxs("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.04] px-5 py-5 text-left transition hover:border-[var(--primary)]/30 hover:bg-[var(--primary)]/10",onClick:()=>void re(p.domain,k.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:k.title}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[k.items.length," items"]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:k.description||"No description yet."})]},k.id)):e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] px-5 py-6 text-sm text-white/58",children:"No concept list matches that search yet."})})]}):null,p.phase==="play"?e.jsx("div",{className:"grid gap-5",children:C||E.isLoading?e.jsx(Et,{eyebrow:"Preference game",title:"Preparing the next round",description:"Forge is lining up comparison candidates."}):Me?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/52",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:((Pe=Jl.find(k=>k.value===p.domain))==null?void 0:Pe.label)??p.domain}),e.jsx("span",{children:xe==null?void 0:xe.selectedContext.name}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[(xe==null?void 0:xe.compare.pendingCount)??0," ","queued comparisons"]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(lx,{title:Me.left.label,description:Me.left.description,sideLabel:"Left",onClick:()=>void be("left",1)}),e.jsx(lx,{title:Me.right.label,description:Me.right.description,sideLabel:"Right",onClick:()=>void be("right",1)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{onClick:()=>void be("left",1),children:"Left"}),e.jsx(W,{onClick:()=>void be("right",1),children:"Right"}),e.jsx(W,{variant:"secondary",onClick:()=>void be("left",1.75),children:"Strong left"}),e.jsx(W,{variant:"secondary",onClick:()=>void be("right",1.75),children:"Strong right"}),e.jsx(W,{variant:"secondary",onClick:()=>void be("tie",1),children:"Tie"}),e.jsx(W,{variant:"secondary",onClick:()=>void be("skip",1),children:"Skip"})]}),e.jsx("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-4 lg:grid-cols-2",children:[Me.left,Me.right].map(k=>e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:k.label}),e.jsx("div",{className:"text-sm text-white/56",children:"Quick signals"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:IT.map(se=>e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>void je(k.id,se.signalType),children:se.label},`${k.id}-${se.signalType}`))})]},k.id))})]}):e.jsx(Bt,{eyebrow:"Preference game",title:"No pair is ready yet",description:"Forge needs more items in this domain before it can keep asking comparisons."})}):null]})]})]})})]})}function ur(t,s,a){return`${s}:${t}:${a}`}function Hm(t,s,a){return Math.min(Math.max(t,s),a)}function Gm(t,s,a){return Math.min(a,Math.max(1,Math.ceil(t.trim().length/s)))}function LT(t,{compact:s}){const a=Gm(t,s?13:14,4),r=(s?114:156)+(a-1)*(s?12:18)+Math.min(24,Math.max(0,t.trim().length-18))*(s?.7:1);return Hm(r,s?118:164,s?154:210)}function DT(t,{compact:s}){const a=Gm(t,s?11:13,3),r=(s?40:48)+(a-1)*(s?6:8)+Math.min(s?18:26,Math.max(0,t.trim().length-(s?12:16)))*(s?.45:.55);return Hm(r,s?42:50,s?56:68)}function jn(t,{compact:s,emphasis:a=!1}){const r=Gm(t,s?16:a?22:20,a?3:2);return{width:Hm((s?a?184:152:a?224:176)+Math.min(t.length,48)*(s?1.8:2.15),s?a?188:156:a?228:184,s?a?248:208:a?300:244),height:r===1?s?64:70:r===2?s?82:92:s?98:110}}function ox(t){if(t.kind==="goal"||t.kind==="value"||t.kind==="ghost"){const s=t.radius??(t.kind==="goal"?76:34);return{halfWidth:s,halfHeight:s}}return{halfWidth:(t.width??146)/2,halfHeight:(t.height??58)/2}}function FT(t,{compact:s}){const a=t.map(n=>({...n,homeX:n.x,homeY:n.y,locked:n.kind==="goal"||n.kind==="ghost"})),i=s?28:40,r=s?.08:.06;for(let n=0;n<180;n+=1){for(const l of a)l.locked||(l.x+=(l.homeX-l.x)*r,l.y+=(l.homeY-l.y)*r);for(let l=0;l<a.length;l+=1)for(let o=l+1;o<a.length;o+=1){const d=a[l],m=a[o],h=ox(d),u=ox(m),x=m.x-d.x,g=m.y-d.y,p=h.halfWidth+u.halfWidth+i-Math.abs(x),f=h.halfHeight+u.halfHeight+i-Math.abs(g);if(p<=0||f<=0)continue;const b=p<f?"x":"y",A=Math.sign(b==="x"?x||o-l||1:g||o-l||1),C=(b==="x"?p:f)/(d.locked||m.locked?1:2);d.locked||(b==="x"?d.x-=A*C:d.y-=A*C),m.locked||(b==="x"?m.x+=A*C:m.y+=A*C)}}return a.map(({homeX:n,homeY:l,locked:o,...d})=>d)}function _T(){return{nodes:[{id:"ghost_goal_north",kind:"ghost",x:-250,y:-20,radius:68,label:"First goal",meta:"Goal",href:"/goals"},{id:"ghost_goal_center",kind:"ghost",x:0,y:34,radius:74,label:"Life goals",meta:"Goal",href:"/goals"},{id:"ghost_goal_south",kind:"ghost",x:250,y:-10,radius:68,label:"Direction",meta:"Goal",href:"/goals"}],edges:[],fields:[],inspectors:{ghost_goal_center:{id:"ghost_goal_center",eyebrow:"Goals",title:"Add the first life goal",summary:"The graph is already laid out. Once a goal exists, values, reports, beliefs, and behaviors will start orbiting it instead of staying fragmented.",href:"/goals",ctaLabel:"Open life goals",tone:"sky",entityKind:"goal",chips:["Goals","Values","Reports"],stats:["0 goals mapped yet"]}},defaultSelectedId:"ghost_goal_center"}}function Yw(t,{compact:s=!1}={}){var m;if(t.length===0)return _T();const a=[],i=[],r=[],n={},l=s?560:840,o=-((t.length-1)*l)/2;t.forEach((h,u)=>{const x=o+u*l,g=u%2===0?92:146,p=h.linkedBehaviors.length+h.linkedBeliefs.length+h.linkedReports.length+h.linkedHabits.length,f=`goal:${h.goal.id}`;a.push({id:f,kind:"goal",x,y:g,radius:LT(h.goal.title,{compact:s}),tone:"amber",label:h.goal.title,href:`/goals/${h.goal.id}`}),n[f]={id:f,eyebrow:"Goal",title:h.goal.title,summary:h.goal.description,href:`/goals/${h.goal.id}`,ctaLabel:"Open goal",tone:"amber",entityKind:"goal",chips:h.linkedValues.slice(0,4).map(j=>j.title),stats:[`${h.linkedValues.length} linked value${h.linkedValues.length===1?"":"s"}`,`${h.linkedProjects.length} live project${h.linkedProjects.length===1?"":"s"}`,`${h.linkedHabits.length} linked habit${h.linkedHabits.length===1?"":"s"}`,`${p} friction signal${p===1?"":"s"}`]},p>0&&r.push({id:`field:${h.goal.id}`,x:x+18,y:g+20,radiusX:s?144:176,radiusY:s?104:132,tone:"rose",opacity:Math.min(.42,.14+p*.04)});const b=s?208:282;h.linkedValues.slice(0,s?4:5).forEach((j,R)=>{const Q=(-95+R*(s?78:64))*(Math.PI/180),X=DT(j.title,{compact:s}),Y=x+Math.cos(Q)*b,z=g+Math.sin(Q)*b,K=ur(h.goal.id,"value",j.id);a.push({id:K,kind:"value",x:Y,y:z,radius:X,tone:"mint",label:j.title,meta:`${j.linkedGoalIds.length} goal${j.linkedGoalIds.length===1?"":"s"}`,href:`/psyche/values?focus=${j.id}#values-atlas`}),i.push({id:`${f}->${K}`,from:f,to:K,tone:"mint",strength:"medium"}),n[K]={id:K,eyebrow:"Value",title:j.title,summary:j.valuedDirection||j.whyItMatters||j.description,href:`/psyche/values?focus=${j.id}#values-atlas`,ctaLabel:"Open values",tone:"mint",entityKind:"value",chips:j.committedActions.slice(0,3),stats:[`${j.linkedProjectIds.length} linked project${j.linkedProjectIds.length===1?"":"s"}`,`${j.linkedTaskIds.length} linked task${j.linkedTaskIds.length===1?"":"s"}`]}});const A=h.linkedProjects.slice(0,s?2:3).map(j=>({project:j,size:jn(j.title,{compact:s,emphasis:!0})})),C=s?24:30;let w=-(A.reduce((j,R)=>j+R.size.width,0)+Math.max(0,A.length-1)*C)/2;A.forEach(({project:j,size:R},Q)=>{const X=ur(h.goal.id,"project",j.id),Y=x+w+R.width/2,z=g-(s?330:434)-Q*(s?16:20);w+=R.width+C,a.push({id:X,kind:"project",x:Y,y:z,width:R.width,height:R.height,tone:"sky",label:j.title,meta:"Project",href:`/projects/${j.id}`}),i.push({id:`${f}->${X}`,from:f,to:X,tone:"sky",strength:"medium"}),n[X]={id:X,eyebrow:"Project",title:j.title,summary:j.description,href:`/projects/${j.id}`,ctaLabel:"Open project",tone:"sky",entityKind:"project",chips:[j.status,j.goalTitle],stats:[`${j.progress}% progress`,`${j.activeTaskCount} active task${j.activeTaskCount===1?"":"s"}`]}}),h.linkedHabits.slice(0,s?2:3).forEach((j,R)=>{const Q=ur(h.goal.id,"habit",j.id),X=jn(j.title,{compact:s}),Y=x-(s?44:58),z=g+(s?228:294)+R*(s?92:104);a.push({id:Q,kind:"habit",x:Y,y:z,width:X.width,height:X.height,tone:"mint",label:j.title,meta:j.polarity,href:"/habits"}),i.push({id:`${f}->${Q}`,from:f,to:Q,tone:"mint",strength:j.dueToday?"high":"medium"}),n[Q]={id:Q,eyebrow:"Habit",title:j.title,summary:j.description||"Recurring operating record connected directly to this goal field.",href:"/habits",ctaLabel:"Open habits",tone:"mint",entityKind:"habit",chips:[j.polarity,j.frequency,j.dueToday?"due today":"checked in"],stats:[`${j.streakCount} streak`,`${j.rewardXp}/${j.penaltyXp} xp flow`]}});let S=g+(s?132:156);h.linkedBehaviors.slice(0,s?2:3).forEach(j=>{const R=ur(h.goal.id,"behavior",j.id),Q=jn(j.title,{compact:s}),X=x-(s?272:352);a.push({id:R,kind:"behavior",x:X,y:S,width:Q.width,height:Q.height,tone:"orange",label:j.title,meta:j.kind,href:`/psyche/behaviors?focus=${j.id}#behavior-columns`}),i.push({id:`${f}->${R}`,from:f,to:R,tone:"orange",dashed:j.kind!=="committed",strength:j.kind==="committed"?"medium":"low"}),n[R]={id:R,eyebrow:"Behavior",title:j.title,summary:j.replacementMove||j.description||j.urgeStory,href:`/psyche/behaviors?focus=${j.id}#behavior-columns`,ctaLabel:"Open behaviors",tone:"orange",entityKind:"behavior",chips:[j.kind,...j.commonCues.slice(0,2)],stats:[j.shortTermPayoff?"Short-term payoff mapped":"Payoff still to map",j.longTermCost?"Long-term cost mapped":"Cost still to map"]},S+=Q.height+(s?18:22)});let y=g+(s?8:10);h.linkedBeliefs.slice(0,s?2:3).forEach(j=>{const R=ur(h.goal.id,"belief",j.id),Q=jn(j.statement,{compact:s,emphasis:!0}),X=x+(s?278:362);a.push({id:R,kind:"belief",x:X,y,width:Q.width,height:Q.height,tone:"violet",label:j.statement,meta:"belief",href:`/psyche/schemas-beliefs?focus=${j.id}`}),i.push({id:`${f}->${R}`,from:f,to:R,tone:"violet",dashed:!0,strength:"low"}),n[R]={id:R,eyebrow:"Belief",title:j.statement,summary:j.flexibleAlternative||j.originNote||"Belief script attached to this part of the map.",href:`/psyche/schemas-beliefs?focus=${j.id}`,ctaLabel:"Open beliefs",tone:"violet",entityKind:"belief",chips:[j.beliefType,`${j.confidence}% grip`],stats:[`${j.linkedBehaviorIds.length} linked behavior${j.linkedBehaviorIds.length===1?"":"s"}`,`${j.linkedReportIds.length} linked report${j.linkedReportIds.length===1?"":"s"}`]},y+=Q.height+(s?18:22)});const N=h.linkedReports.slice(0,s?2:3).map(j=>({report:j,size:jn(j.title,{compact:s})})),P=s?20:26;let H=-(N.reduce((j,R)=>j+R.size.width,0)+Math.max(0,N.length-1)*P)/2;N.forEach(({report:j,size:R})=>{const Q=ur(h.goal.id,"report",j.id),X=x+H+R.width/2,Y=g+(s?332:430);H+=R.width+P,a.push({id:Q,kind:"report",x:X,y:Y,width:R.width,height:R.height,tone:"blue",label:j.title,meta:j.status,href:`/psyche/reports/${j.id}`}),i.push({id:`${f}->${Q}`,from:f,to:Q,tone:"sky",strength:"medium"}),n[Q]={id:Q,eyebrow:"Report",title:j.title,summary:j.eventSituation||j.customEventType||"Reflective chain linked into this goal.",href:`/psyche/reports/${j.id}`,ctaLabel:"Open report",tone:"blue",entityKind:"report",chips:[j.status,...j.nextMoves.slice(0,2)],stats:[`${j.emotions.length} emotion${j.emotions.length===1?"":"s"}`,`${j.behaviors.length} move${j.behaviors.length===1?"":"s"}`]}})});const d=((m=a[0])==null?void 0:m.id)??"ghost_goal_center";return{nodes:FT(a,{compact:s}),edges:i,fields:r,inspectors:n,defaultSelectedId:d}}const bi={mint:"rgba(110,231,183,0.64)",sky:"rgba(125,211,252,0.66)",violet:"rgba(196,181,253,0.72)",rose:"rgba(251,113,133,0.68)",amber:"rgba(251,191,36,0.68)",orange:"rgba(251,146,60,0.72)",blue:"rgba(96,165,250,0.72)",slate:"rgba(148,163,184,0.52)"},pc={mint:"rgba(16,185,129,0.18)",sky:"rgba(56,189,248,0.18)",violet:"rgba(167,139,250,0.18)",rose:"rgba(251,113,133,0.18)",amber:"rgba(251,191,36,0.18)",orange:"rgba(251,146,60,0.18)",blue:"rgba(96,165,250,0.18)",slate:"rgba(148,163,184,0.12)"},wi={mint:"rgba(209,250,229,0.98)",sky:"rgba(224,242,254,0.98)",violet:"rgba(237,233,254,0.98)",rose:"rgba(255,228,230,0.98)",amber:"rgba(254,243,199,0.98)",orange:"rgba(255,237,213,0.98)",blue:"rgba(219,234,254,0.98)",slate:"rgba(241,245,249,0.9)"};function Jw(t){switch(t){case"goal":case"value":case"behavior":case"belief":case"report":case"project":case"habit":return t;default:return null}}function RT(t){if(t.tone)return t.tone;switch(t.kind){case"goal":return"amber";case"value":return"mint";case"belief":return"violet";case"behavior":return"orange";case"project":return"sky";case"habit":return"mint";case"report":return"blue";default:return"slate"}}function $T(t){if(t.kind==="ghost")return t.meta??null;const s=Jw(t.kind);return s?zs(s).label:t.meta??null}function xc(t,s,a){return Math.min(Math.max(t,s),a)}function so(t,s,a=3){const i=t.trim().split(/\s+/),r=[];let n="";for(let d=0;d<i.length;d+=1){const m=i[d],h=n?`${n} ${m}`:m;if(h.length>s&&n){if(r.push(n),r.length>=a-1){n=[m,...i.slice(d+1)].join(" ");break}n=m}else n=h}n&&r.push(n);const l=r.slice(0,a),o=l.length-1;return o>=0&&l[o].length>s&&(l[o]=`${l[o].slice(0,Math.max(1,s-1)).trimEnd()}…`),l}function OT(t,s){if(t.length===0&&s.length===0)return{minX:-360,maxX:360,minY:-240,maxY:240};let a=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const l of t){const o=l.kind==="goal"||l.kind==="value"||l.kind==="ghost"?l.radius??32:(l.width??124)/2,d=l.kind==="goal"||l.kind==="value"||l.kind==="ghost"?l.radius??32:(l.height??56)/2,m=l.meta&&(l.kind==="goal"||l.kind==="ghost")?48:0;a=Math.min(a,l.x-o),i=Math.max(i,l.x+o),r=Math.min(r,l.y-d-m),n=Math.max(n,l.y+d)}for(const l of s)a=Math.min(a,l.x-l.radiusX),i=Math.max(i,l.x+l.radiusX),r=Math.min(r,l.y-l.radiusY),n=Math.max(n,l.y+l.radiusY);return{minX:a,maxX:i,minY:r,maxY:n}}function dx(t){return{x:t.x,y:t.y}}function zT(t){if(t.kind==="goal"){const s=t.radius??112;return so(t.label,Math.max(14,Math.floor(s/7.2)),4)}if(t.kind==="value"||t.kind==="ghost"){const s=t.radius??40;return so(t.label,Math.max(12,Math.floor(s/3)),3)}return t.kind==="project"?so(t.label,Math.max(18,Math.floor((t.width??220)/10)),3):so(t.label,Math.max(16,Math.floor((t.width??180)/10.5)),2)}function KT(t){switch(t){case"goal":return"amber";case"project":return"sky";case"value":return"mint";case"behavior":return"orange";case"belief":return"violet";case"report":return"blue";default:return"slate"}}function Zw({nodes:t,edges:s,fields:a=[],title:i,hint:r,action:n,legend:l,selectedNodeId:o,onSelectNode:d,minHeightClassName:m="min-h-[34rem] lg:min-h-[44rem]",compact:h=!1,testId:u}){const x=c.useRef(null),g=$t(),[p,f]=c.useState({width:0,height:0}),[b,A]=c.useState({scale:1,x:0,y:0}),[C,T]=c.useState(null),w=c.useRef(null),S=c.useRef({scale:1,x:0,y:0}),y=c.useRef(new Map),N=c.useRef(null),P=c.useRef(0),v=c.useRef(!1),H=c.useMemo(()=>new Map(t.map(_=>[_.id,_])),[t]),j=c.useMemo(()=>OT(t,a),[a,t]),R=p.width>0&&p.width<640;c.useEffect(()=>{if(!x.current||typeof ResizeObserver>"u")return;const _=new ResizeObserver(B=>{const G=B[0];f({width:G.contentRect.width,height:G.contentRect.height})});return _.observe(x.current),()=>_.disconnect()},[]);const Q=c.useCallback(()=>{if(!p.width||!p.height)return;const _=R?132:h?140:190,B=Math.max(j.maxX-j.minX,1),G=Math.max(j.maxY-j.minY,1),ae=xc(Math.min(p.width/(B+_),p.height/(G+_)),R?.24:h?.4:.46,R?.76:h?1.04:1.18),ke=(j.minX+j.maxX)/2,Ae=(j.minY+j.maxY)/2;A({scale:ae,x:p.width/2-ke*ae,y:p.height/2-Ae*ae})},[j.maxX,j.maxY,j.minX,j.minY,h,p.height,p.width,R]);c.useEffect(()=>{S.current=b},[b]),c.useEffect(()=>{v.current||Q()},[Q]);const X=c.useCallback((_,B,G)=>{const ae=xc(_,.28,1.9);A(ke=>{if(B==null||G==null)return{...ke,scale:ae};const Ae=(B-ke.x)/ke.scale,ie=(G-ke.y)/ke.scale;return{scale:ae,x:B-Ae*ae,y:G-ie*ae}})},[]),Y=c.useCallback(()=>{const _=[...y.current.values()];if(_.length<2){N.current=null;return}const[B,G]=_,ae=Math.hypot(G.x-B.x,G.y-B.y);if(!Number.isFinite(ae)||ae<=0){N.current=null;return}const ke=S.current;N.current={startDistance:ae,startScale:ke.scale,startViewportX:ke.x,startViewportY:ke.y,startMidpointX:(B.x+G.x)/2,startMidpointY:(B.y+G.y)/2}},[]),z=_=>{var ae;_.preventDefault();const B=(ae=x.current)==null?void 0:ae.getBoundingClientRect();if(!B)return;v.current=!0;const G=_.deltaY<0?1.1:.9;X(b.scale*G,_.clientX-B.left,_.clientY-B.top)},K=_=>{var ke;const B=(ke=x.current)==null?void 0:ke.getBoundingClientRect(),G=_.clientX-((B==null?void 0:B.left)??0),ae=_.clientY-((B==null?void 0:B.top)??0);if(y.current.set(_.pointerId,{x:G,y:ae}),y.current.size===1){const Ae=S.current;w.current={pointerId:_.pointerId,originX:Ae.x,originY:Ae.y,startX:G,startY:ae}}else w.current=null,Y();_.currentTarget.setPointerCapture(_.pointerId)},$=_=>{var ie;const B=(ie=x.current)==null?void 0:ie.getBoundingClientRect(),G=_.clientX-((B==null?void 0:B.left)??0),ae=_.clientY-((B==null?void 0:B.top)??0);if(y.current.has(_.pointerId)&&y.current.set(_.pointerId,{x:G,y:ae}),N.current&&y.current.size>=2){const[Ie,Ne]=[...y.current.values()],M=Math.hypot(Ne.x-Ie.x,Ne.y-Ie.y);if(Number.isFinite(M)&&M>0){v.current=!0,P.current=Date.now()+240;const E=(Ie.x+Ne.x)/2,O=(Ie.y+Ne.y)/2,xe=N.current,V=xc(xe.startScale*M/xe.startDistance,.24,1.42),Se=(xe.startMidpointX-xe.startViewportX)/xe.startScale,Ee=(xe.startMidpointY-xe.startViewportY)/xe.startScale;A({scale:V,x:E-Se*V,y:O-Ee*V})}return}if(!w.current||w.current.pointerId!==_.pointerId||y.current.size!==1)return;v.current=!0;const ke=G-w.current.startX,Ae=ae-w.current.startY;(Math.abs(ke)>3||Math.abs(Ae)>3)&&(P.current=Date.now()+240),A(Ie=>{var Ne,M;return{...Ie,x:(((Ne=w.current)==null?void 0:Ne.originX)??Ie.x)+ke,y:(((M=w.current)==null?void 0:M.originY)??Ie.y)+Ae}})},D=_=>{if(y.current.delete(_.pointerId),y.current.size<2&&(N.current=null),y.current.size===1){const[B,G]=[...y.current.entries()][0]??[];if(B!=null&&G){const ae=S.current;w.current={pointerId:B,originX:ae.x,originY:ae.y,startX:G.x,startY:G.y}}}else w.current=null;_.currentTarget.hasPointerCapture(_.pointerId)&&_.currentTarget.releasePointerCapture(_.pointerId)},J=C??o??null,q=c.useCallback(_=>{Date.now()<P.current||(d==null||d(_.id),_.href&&g(_.href))},[g,d]);return e.jsxs("section",{"data-testid":u,className:te("overflow-hidden rounded-[32px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.12),transparent_32%),linear-gradient(180deg,rgba(11,18,31,0.985),rgba(7,12,23,0.98))] shadow-[0_26px_90px_rgba(2,6,16,0.38)]","px-3 py-3 sm:px-4 sm:py-4 lg:px-5 lg:py-5"),children:[e.jsxs("div",{className:"mb-3 flex min-w-0 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-[rgba(125,211,252,0.82)]",children:"Gravity well"}),e.jsx("h2",{className:te("mt-2 font-display leading-none text-white",h?"text-[clamp(1.25rem,2vw,1.7rem)]":"text-[clamp(1.45rem,2.8vw,2.3rem)]"),children:i}),r?e.jsx("p",{className:"mt-1.5 max-w-3xl text-sm leading-6 text-white/54",children:R?"Select a node, pan the field, and open the full map when you need the wider structure.":r}):null]}),e.jsx("div",{className:"flex min-w-0 flex-wrap items-center justify-end gap-2",children:n})]}),e.jsxs("div",{ref:x,className:te("group relative overflow-hidden rounded-[30px] border border-white/6 bg-[radial-gradient(circle_at_center,rgba(255,255,255,0.04),transparent_46%)] touch-none",m),style:{touchAction:"none"},onWheel:z,onPointerDown:K,onPointerMove:$,onPointerUp:D,onPointerCancel:D,children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(110,231,183,0.06),transparent_28%),radial-gradient(circle_at_20%_20%,rgba(196,181,253,0.08),transparent_24%),linear-gradient(180deg,rgba(255,255,255,0.015),rgba(4,8,18,0.24))]"}),e.jsxs("div",{className:"absolute left-3 top-3 z-10 inline-flex max-w-[calc(100%-7rem)] items-center gap-2 rounded-full border border-white/8 bg-[rgba(8,14,25,0.78)] px-2.5 py-1.5 text-[11px] uppercase tracking-[0.18em] text-white/42 backdrop-blur-xl sm:left-4 sm:top-4 sm:max-w-none sm:px-3",onPointerDown:_=>_.stopPropagation(),children:[e.jsx(Vv,{className:"size-3.5"}),R?"Drag or pinch":"Drag to pan, scroll to zoom"]}),e.jsxs("div",{className:"absolute right-3 top-3 z-10 flex max-w-[calc(100%-1.5rem)] flex-wrap items-center justify-end gap-1.5 sm:right-4 sm:top-4 sm:max-w-none sm:gap-2",onPointerDown:_=>_.stopPropagation(),children:[e.jsx(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom in",onClick:()=>{v.current=!0,X(b.scale*1.12,p.width-96,72)},children:e.jsx(ds,{className:"size-4"})}),e.jsx(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom out",onClick:()=>{v.current=!0,X(b.scale*.88,p.width-96,72)},children:e.jsx(Ig,{className:"size-4"})}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:min-w-[4.75rem] sm:px-3","aria-label":"Fit graph",onClick:()=>{v.current=!0,Q()},children:[e.jsx(Xv,{className:"size-4"}),R?null:"Fit"]}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:min-w-[5.5rem] sm:px-3","aria-label":"Reset graph",onClick:()=>{v.current=!1,Q()},children:[e.jsx(Tg,{className:"size-4"}),R?null:"Reset"]})]}),l&&l.length>0&&!R?e.jsx("div",{className:"absolute bottom-4 left-4 z-10 flex flex-wrap items-center gap-2 rounded-[24px] border border-white/8 bg-[rgba(8,14,25,0.76)] px-3 py-2 text-xs text-white/58 backdrop-blur-xl",children:l.map(_=>{const B=_.kind?KT(_.kind):_.tone??"slate",G=_.kind?zs(_.kind).icon:null;return e.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap rounded-full bg-white/[0.04] px-2.5 py-1.5",children:[G?e.jsx(G,{className:"size-3.5",color:wi[B],strokeWidth:2.1}):e.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:bi[B]}}),_.label]},_.label)})}):null,e.jsxs("svg",{className:"relative z-[1] h-full w-full",viewBox:`0 0 ${p.width||1200} ${p.height||760}`,role:"img","aria-label":i,children:[e.jsx("defs",{children:e.jsx("filter",{id:"forge-graph-blur",children:e.jsx("feGaussianBlur",{stdDeviation:"34"})})}),e.jsxs("g",{transform:`translate(${b.x} ${b.y}) scale(${b.scale})`,children:[a.map(_=>e.jsx("ellipse",{cx:_.x,cy:_.y,rx:_.radiusX,ry:_.radiusY,fill:pc[_.tone??"rose"],opacity:_.opacity??.42,filter:"url(#forge-graph-blur)"},_.id)),t.filter(_=>_.kind==="goal"||_.kind==="ghost").map(_=>{const B=_.radius??76;return e.jsx("g",{opacity:_.kind==="ghost"?.28:.55,children:[B+74,B+124].map((G,ae)=>e.jsx("circle",{cx:_.x,cy:_.y,r:G,fill:"none",stroke:ae===0?"rgba(255,255,255,0.08)":"rgba(255,255,255,0.045)",strokeDasharray:ae===0?"0":"10 10"},`${_.id}-ring-${G}`))},`${_.id}-orbital-lanes`)}),s.map(_=>{const B=H.get(_.from),G=H.get(_.to);if(!B||!G)return null;const ae=dx(B),ke=dx(G),Ae=(ae.x+ke.x)/2,ie=(ae.y+ke.y)/2,Ie=Math.max(24,Math.abs(ae.x-ke.x)*.08),Ne=Ae,M=ie-Ie;return e.jsx("path",{d:`M ${ae.x} ${ae.y} Q ${Ne} ${M} ${ke.x} ${ke.y}`,fill:"none",stroke:bi[_.tone??"slate"],strokeWidth:_.strength==="high"?3:_.strength==="medium"?2.2:1.6,strokeDasharray:_.dashed?"8 8":void 0,opacity:J&&_.from!==J&&_.to!==J?.18:.62},_.id)}),t.map(_=>{_.id;const B=C===_.id,G=J===_.id,ae=RT(_),ke=$T(_),Ae=zT(_),ie=Jw(_.kind),Ie=ie?zs(ie).icon:null;if(_.kind==="goal"||_.kind==="value"||_.kind==="ghost"){const L=_.radius??(_.kind==="goal"?76:34),U=ke?_.y-L-(_.kind==="goal"?18:10):null,ge=_.kind==="goal"?20:14.5,Te=_.kind==="goal"?28:16,ve=_.kind==="goal"?_.y-L*.34:_.kind==="value"?_.y-L*.3:_.y-L*.2,Le=_.kind==="goal"?_.y+L*.2:_.y+10;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{T(_.id),d==null||d(_.id)},onPointerLeave:()=>T(Qe=>Qe===_.id?null:Qe),onFocus:()=>d==null?void 0:d(_.id),onClick:()=>q(_),onKeyDown:Qe=>{(Qe.key==="Enter"||Qe.key===" ")&&(Qe.preventDefault(),q(_))},className:"cursor-pointer outline-none",children:[e.jsx("circle",{cx:_.x,cy:_.y,r:L+(G?14:0),fill:G?`${bi[ae]}22`:"transparent",stroke:G?bi[ae]:"transparent",opacity:B?.98:.9}),e.jsx("circle",{cx:_.x,cy:_.y,r:L+(B?2:0),fill:_.kind==="ghost"?"rgba(255,255,255,0.03)":pc[ae],stroke:_.kind==="ghost"?"rgba(255,255,255,0.18)":bi[ae],strokeDasharray:_.kind==="ghost"?"8 8":void 0,strokeWidth:G?2.8:1.6}),ke?e.jsx("text",{x:_.x,y:U??_.y-12,textAnchor:"middle",fontSize:_.kind==="goal"?"11.5":"10.5",fill:_.kind==="ghost"?"rgba(255,255,255,0.62)":wi[ae],style:{letterSpacing:"0.18em",textTransform:"uppercase"},children:ke}):null,Ie?e.jsx(Ie,{x:_.x-Te/2,y:ve-Te/2,width:Te,height:Te,color:wi[ae],strokeWidth:2.1}):null,Ae.map((Qe,st)=>e.jsx("text",{x:_.x,y:Le+st*ge-(Ae.length-1)*ge/2,textAnchor:"middle",fontSize:_.kind==="goal"?21:12.8,fontWeight:_.kind==="goal"?600:500,fill:_.kind==="ghost"?"rgba(255,255,255,0.92)":wi[ae],children:Qe},`${_.id}-${Qe}-${st}`))]},_.id)}const Ne=_.width??146,M=_.height??58,E=_.x-Ne/2,O=_.y-M/2,xe=_.kind==="project"?14:13,V=E+14,Se=O+13,Ee=O+22,Ce=ke?O+M*.65:O+M*.56,qe=_.kind==="project"?16:15,oe=_.kind==="project"?14.2:13.2;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{T(_.id),d==null||d(_.id)},onPointerLeave:()=>T(L=>L===_.id?null:L),onFocus:()=>d==null?void 0:d(_.id),onClick:()=>q(_),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),q(_))},className:"cursor-pointer outline-none",children:[e.jsx("rect",{x:E-(G?6:0),y:O-(G?6:0),rx:"28",ry:"28",width:Ne+(G?12:0),height:M+(G?12:0),fill:G?`${bi[ae]}22`:"transparent"}),e.jsx("rect",{x:E-(B?2:0),y:O-(B?2:0),rx:"22",ry:"22",width:Ne+(B?4:0),height:M+(B?4:0),fill:pc[ae],stroke:bi[ae],strokeWidth:G?2.3:1.3}),Ie?e.jsx(Ie,{x:V,y:Se,width:xe,height:xe,color:wi[ae],strokeWidth:2.1}):null,ke?e.jsx("text",{x:V+xe+8,y:Ee,textAnchor:"start",fontSize:"9.5",fill:wi[ae],style:{letterSpacing:"0.16em",textTransform:"uppercase",opacity:.82},children:ke}):null,Ae.map((L,U)=>e.jsx("text",{x:_.x,y:Ce+U*qe-(Ae.length-1)*qe/2,textAnchor:"middle",fontSize:oe,fontWeight:600,fill:wi[ae],children:L},`${_.id}-${L}-${U}`))]},_.id)})]})]})]})]})}const cx={intent:"trigger_report",linkedGoalId:"",linkedProjectId:"",linkedTaskId:""};function qT({open:t,onOpenChange:s}){const a=$t(),i=jt(),[r,n]=c.useState(cx),l=[{id:"intent",eyebrow:"Reflect",title:"What do you want to reflect on?",description:"Choose the entrypoint first. Forge will route you into the right guided flow instead of dropping you into a generic form.",render:(d,m)=>e.jsx(wt,{columns:3,value:d.intent,onChange:h=>m({intent:h}),options:[{value:"trigger_report",label:"A situation",description:"Start a Spark-to-Pivot report about something that happened."},{value:"behavior",label:"A behavior",description:"Trace an away move, committed action, or recovery path."},{value:"belief",label:"A belief script",description:"Capture or refine the belief beneath the reaction."},{value:"pattern",label:"A recurring pattern",description:"Map the loop, payoff, cost, and better response."},{value:"value",label:"A blocked value",description:"Clarify which value is being challenged or needs support."},{value:"execution_tension",label:"A goal tension",description:"Reflect on a goal, project, or task that carries friction."}]})},{id:"placement",eyebrow:"Placement",title:"Attach the reflection to the wider system",description:"This keeps the reflection connected to values, behaviors, and live work instead of becoming an isolated note.",render:(d,m)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(de,{label:"Goal / project / task tension",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(We,{kind:"goal",label:"Goal",compact:!0,gradient:!1}),e.jsx(We,{kind:"project",label:"Project",compact:!0,gradient:!1}),e.jsx(We,{kind:"task",label:"Task",compact:!0,gradient:!1})]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:d.linkedGoalId,onChange:h=>m({linkedGoalId:h.target.value}),children:[e.jsx("option",{value:"",children:"No goal selected"}),i.snapshot.goals.map(h=>e.jsxs("option",{value:h.id,children:["Goal · ",h.title]},h.id))]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:d.linkedProjectId,onChange:h=>m({linkedProjectId:h.target.value}),children:[e.jsx("option",{value:"",children:"No project selected"}),i.snapshot.dashboard.projects.map(h=>e.jsxs("option",{value:h.id,children:["Project · ",h.title]},h.id))]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:d.linkedTaskId,onChange:h=>m({linkedTaskId:h.target.value}),children:[e.jsx("option",{value:"",children:"No task selected"}),i.snapshot.tasks.slice(0,40).map(h=>e.jsxs("option",{value:h.id,children:["Task · ",h.title]},h.id))]})]})})})}],o=async()=>{const d=new URLSearchParams({create:"1",intent:r.intent});switch(r.linkedGoalId&&d.set("goalId",r.linkedGoalId),r.linkedProjectId&&d.set("projectId",r.linkedProjectId),r.linkedTaskId&&d.set("taskId",r.linkedTaskId),r.intent){case"behavior":a(`/psyche/behaviors?${d.toString()}`);break;case"belief":a(`/psyche/schemas-beliefs?${d.toString()}`);break;case"pattern":a(`/psyche/patterns?${d.toString()}`);break;case"value":a(`/psyche/values?${d.toString()}`);break;case"execution_tension":case"trigger_report":default:a(`/psyche/reports?${d.toString()}`);break}s(!1),n(cx)};return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Reflect",title:"Start from the right reflective doorway",description:"Choose what you want to reflect on first. Forge will take you into the right guided flow instead of leaving you in a generic form.",value:r,onChange:n,draftPersistenceKey:"psyche.reflect.launcher",steps:l,submitLabel:"Open guided reflection",onSubmit:o})}function gc({to:t,children:s,className:a}){return e.jsx(Je,{to:t,className:"group block transition-transform duration-[var(--motion-medium)] ease-[var(--ease-standard)] hover:-translate-y-0.5 focus-visible:outline-none",children:e.jsx(ce,{className:te("transition-[transform,box-shadow,background,border-color] duration-[var(--motion-medium)] ease-[var(--ease-standard)] group-hover:border-[var(--ui-border-strong)] group-hover:bg-[var(--ui-surface-hover)] group-hover:shadow-[var(--card-shadow-hover)] group-focus-visible:shadow-[var(--card-shadow-hover)]",a),children:s})})}function BT(){var T,w;const t=jt(),[s,a]=ms(),[i,r]=c.useState(s.get("reflect")==="1"),[n,l]=c.useState(null),o=Fe({queryKey:["forge-psyche-overview"],queryFn:md}),d=Fe({queryKey:["forge-psyche-questionnaires-hub"],queryFn:()=>Xg()}),m=(T=o.data)==null?void 0:T.overview,h=c.useMemo(()=>m?t.snapshot.goals.slice(0,3).map(S=>{const y=m.values.filter(R=>R.linkedGoalIds.includes(S.id)),N=t.snapshot.dashboard.projects.filter(R=>R.goalId===S.id),P=t.snapshot.habits.filter(R=>R.linkedGoalIds.includes(S.id)||R.linkedValueIds.some(Q=>y.some(X=>X.id===Q))),v=m.reports.filter(R=>R.linkedGoalIds.includes(S.id)),H=m.behaviors.filter(R=>R.linkedValueIds.some(Q=>y.some(X=>X.id===Q))),j=m.beliefs.filter(R=>R.linkedValueIds.some(Q=>y.some(X=>X.id===Q)));return{goal:S,linkedValues:y,linkedProjects:N,linkedHabits:P,linkedReports:v,linkedBehaviors:H,linkedBeliefs:j}}):[],[m,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits]),u=c.useMemo(()=>Yw(h,{compact:!0}),[h]);if(c.useEffect(()=>{l(u.defaultSelectedId)},[u.defaultSelectedId]),o.isLoading)return e.jsx(ls,{});if(o.isError||!m)return e.jsx(it,{eyebrow:"Psyche",error:o.error,onRetry:()=>void o.refetch()});const x=u.inspectors[n??u.defaultSelectedId]??u.inspectors[u.defaultSelectedId],g=m.patterns[0]??null,p=m.reports[0]??null,f=[...((w=d.data)==null?void 0:w.instruments)??[]].sort((S,y)=>{const N=S.latestRunAt?new Date(S.latestRunAt).getTime():0;return(y.latestRunAt?new Date(y.latestRunAt).getTime():0)-N})[0]??null,b="Values, patterns, behaviors, beliefs, habits, and reports in one live field.",A=e.jsx(Je,{to:"/psyche/goal-map",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center rounded-full bg-white/[0.08] px-4 py-2 text-sm whitespace-nowrap text-white transition hover:bg-white/[0.12]",children:"Open goal map"}),C=[{id:"hero",title:"Psyche",description:"Top route composition",defaultWidth:12,defaultHeight:1,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(nt,{title:"Psyche",titleText:"Psyche",description:b,actions:A})},{id:"sections",title:"Psyche sections",description:"Section switcher",defaultWidth:12,defaultHeight:1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(ks,{})},{id:"field",title:"Live field",description:"Graph and inspector stay as movable widgets.",defaultWidth:8,defaultHeight:5,minWidth:6,render:()=>e.jsx(Zw,{testId:"psyche-hub-graph",compact:!0,title:"Reflective pulse and live entity field",hint:"Select any goal, value, habit, belief, behavior, project, or report.",nodes:u.nodes,edges:u.edges,fields:u.fields,selectedNodeId:n,onSelectNode:l,minHeightClassName:"min-h-[20rem] sm:min-h-[24rem] lg:min-h-[34rem]",legend:[{label:"Goals",kind:"goal"},{label:"Values",kind:"value"},{label:"Habits",kind:"habit"},{label:"Behaviors",kind:"behavior"}],action:e.jsxs(e.Fragment,{children:[e.jsx(Je,{to:"/psyche/goal-map",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center rounded-[var(--radius-control)] bg-white/8 px-4 py-2 text-sm font-medium whitespace-nowrap text-white transition hover:bg-white/12",children:"Open goal map"}),e.jsx(W,{size:"sm",className:"min-w-0 sm:min-w-[6.5rem]",onClick:()=>r(!0),children:"Reflect"})]})})},{id:"inspector",title:"Inspector",description:"Selected-node inspector widget.",defaultWidth:4,defaultHeight:5,minWidth:4,render:()=>e.jsxs(ce,{className:"h-full min-w-0",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:x.entityKind?e.jsx(We,{kind:x.entityKind,compact:!0,gradient:!1,iconOnly:!0}):e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:x.eyebrow})}),e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:x.entityKind?e.jsx(yt,{kind:x.entityKind,label:x.title,variant:"heading",size:"lg",showKind:!1}):e.jsx("h2",{className:"font-display text-[clamp(1.25rem,2.2vw,1.8rem)] leading-none text-white",children:x.title})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:x.summary}),x.chips.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:x.chips.map(S=>e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:S},S))}):null,x.stats.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:x.stats.map(S=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/68",children:S},S))}):null,e.jsx("div",{className:"mt-5",children:e.jsx(Je,{to:x.href,className:te("inline-flex min-h-11 w-full items-center justify-center rounded-[var(--radius-control)] px-4 py-2.5 text-sm font-medium whitespace-nowrap shadow-[0_12px_30px_rgba(192,193,255,0.08)]",x.entityKind?_n(x.entityKind,!0):"bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] text-white"),children:x.ctaLabel})})]})},{id:"actions",title:"Open threads",description:"Action and pulse cards.",defaultWidth:12,defaultHeight:3,render:()=>e.jsxs("div",{className:"grid min-w-0 gap-4 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsxs(gc,{to:"/psyche/behaviors",className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,29,32,0.96),rgba(11,21,23,0.94))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[rgba(110,231,183,0.82)]",children:"Best next reflective move"}),e.jsx("div",{className:"mt-3 font-display text-[clamp(1.45rem,2.2vw,2rem)] leading-none text-white",children:(g==null?void 0:g.preferredResponse)||"Map the active loop, then name the committed move that brings you back."}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:(g==null?void 0:g.targetBehavior)||"When the loop is explicit, the return path stops feeling abstract."})]}),e.jsxs(gc,{to:p?`/psyche/reports/${p.id}`:"/psyche/reports",className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(24,19,37,0.96),rgba(13,12,22,0.94))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-violet-100/72",children:"Open threads"}),e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Insights"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:m.openInsights})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Notes"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:m.openNotes})]})]})]})]})},{id:"questionnaires",title:"Questionnaire pulse",description:"Recent questionnaire state.",defaultWidth:12,defaultHeight:2,render:()=>{var S;return e.jsxs(gc,{to:f!=null&&f.latestRunId?`/psyche/questionnaire-runs/${f.latestRunId}`:"/psyche/questionnaires",className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,31,39,0.97),rgba(10,18,24,0.95))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-sky-100/72",children:"Questionnaire pulse"}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-display text-[clamp(1.4rem,2.2vw,2rem)] leading-none text-white",children:(f==null?void 0:f.title)??"Questionnaire library ready"}),e.jsxs(I,{className:"bg-white/[0.08] text-white/78",children:[(((S=d.data)==null?void 0:S.instruments)??[]).length," available"]})]})]})}}];return e.jsxs("div",{className:"grid min-w-0 gap-4 overflow-x-clip",children:[e.jsx(Td,{surfaceId:"psyche",baseWidgets:C}),e.jsx(qT,{open:i,onOpenChange:S=>{r(S);const y=new URLSearchParams(s);y.delete("reflect"),a(y,{replace:!0})}})]})}function $a({eyebrow:t,title:s,description:a,titleHelp:i,tone:r="default",children:n,className:l}){const o={default:"bg-[linear-gradient(180deg,rgba(17,24,35,0.96),rgba(11,16,24,0.94))]",mint:"bg-[radial-gradient(circle_at_top_left,rgba(110,231,183,0.14),transparent_42%),linear-gradient(180deg,rgba(14,28,31,0.96),rgba(10,20,24,0.94))]",sky:"bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.14),transparent_42%),linear-gradient(180deg,rgba(16,25,34,0.96),rgba(10,17,24,0.94))]",violet:"bg-[radial-gradient(circle_at_top_left,rgba(196,181,253,0.14),transparent_42%),linear-gradient(180deg,rgba(20,19,35,0.96),rgba(12,13,24,0.94))]",rose:"bg-[radial-gradient(circle_at_top_left,rgba(251,113,133,0.14),transparent_42%),linear-gradient(180deg,rgba(31,18,24,0.96),rgba(18,11,16,0.94))]",amber:"bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.14),transparent_42%),linear-gradient(180deg,rgba(32,24,16,0.96),rgba(20,15,10,0.94))]"};return e.jsxs("section",{className:te("min-w-0 overflow-hidden rounded-[30px] border border-white/8 px-4 py-5 shadow-[0_24px_70px_rgba(4,8,18,0.28)] sm:px-5 lg:px-6",o[r],l),children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsxs("div",{className:"mt-3 flex min-w-0 items-start gap-2",children:[e.jsx("h2",{className:"min-w-0 font-display text-[clamp(1.8rem,3.2vw,3rem)] leading-none text-white",children:s}),i?e.jsx(vt,{content:i,label:`Explain ${s.toLowerCase()}`,className:"mt-1 shrink-0"}):null]}),a?e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/60",children:a}):null,e.jsx("div",{className:"mt-5 min-w-0",children:n})]})}function UT({entries:t}){const s={away:"border-rose-400/20 bg-[rgba(251,113,133,0.08)]",committed:"border-emerald-400/20 bg-[rgba(110,231,183,0.08)]",recovery:"border-amber-400/20 bg-[rgba(251,191,36,0.08)]"};return e.jsx("div",{className:"grid gap-3 lg:grid-cols-3",children:t.map(a=>e.jsxs(Je,{to:a.href,className:`rounded-[22px] border px-4 py-4 transition hover:-translate-y-0.5 ${s[a.tone]}`,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:a.tone}),e.jsx("div",{className:"mt-2 font-medium text-white",children:a.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:a.summary}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 text-sm text-white/54",children:["Open",e.jsx(ha,{className:"size-3.5"})]})]},a.id))})}const WT={maladaptive:"Maladaptive schema",adaptive:"Adaptive schema"},HT={maladaptive:"A recurring pressure pattern that can distort how you interpret situations or respond.",adaptive:"A stable healthy belief pattern you want to strengthen and rely on."},GT={disconnection_rejection:"Disconnection & rejection",impaired_autonomy:"Autonomy & competence",other_directedness:"Boundaries & mutuality",overvigilance_inhibition:"Standards & inhibition",healthy_selfhood:"Healthy selfhood"};function Pd(t){return WT[t]}function Kn(t){return HT[t]}function Qm(t){return GT[t]??t.replaceAll("_"," ")}function Wr(t){return t==="adaptive"?{sectionTone:"border-emerald-400/14 bg-[linear-gradient(180deg,rgba(26,53,48,0.72),rgba(10,18,30,0.92))]",sectionEyebrow:"text-emerald-200/84",cardTone:"border-emerald-400/14 bg-[linear-gradient(180deg,rgba(28,63,56,0.44),rgba(14,24,36,0.92))]",badgeTone:"border-emerald-300/18 bg-[linear-gradient(135deg,rgba(16,185,129,0.18),rgba(56,189,248,0.12))] text-emerald-50",subtleBadgeTone:"border-emerald-300/12 bg-[rgba(16,185,129,0.1)] text-emerald-100/88",countLabel:"support links",linkSummary:"linked strengthening belief",emptyCopy:"No adaptive schema is linked yet. Add one when you want to capture the healthier pattern you are building from."}:{sectionTone:"border-fuchsia-400/14 bg-[linear-gradient(180deg,rgba(44,28,58,0.72),rgba(10,18,30,0.92))]",sectionEyebrow:"text-fuchsia-200/84",cardTone:"border-violet-400/14 bg-[linear-gradient(180deg,rgba(48,33,68,0.44),rgba(14,18,34,0.92))]",badgeTone:"border-rose-300/18 bg-[linear-gradient(135deg,rgba(244,63,94,0.16),rgba(168,85,247,0.12))] text-rose-50",subtleBadgeTone:"border-rose-300/12 bg-[rgba(244,63,94,0.1)] text-rose-100/88",countLabel:"linked records",linkSummary:"linked belief",emptyCopy:"No maladaptive schema is linked yet. Add one when you want to capture the recurring old pattern clearly."}}function ux(t){return t.trim().toLowerCase()}function ey(t,s){const a=ux(s);return[t.id,t.slug,t.title].some(i=>ux(i)===a)}function Hr(t,s){return s.find(a=>ey(a,t))??null}function ty(t,s){const a=t.filter(i=>!ey(s,i));return a.length===t.length?[...a,s.id]:a}function ni({label:t,schemaType:s,compact:a=!1,showType:i=!1,className:r}){const n=Wr(s);return e.jsxs("span",{className:te("inline-flex max-w-full min-w-0 items-center gap-2 rounded-full border px-3 py-1.5 text-sm leading-tight shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]",a?"min-h-8":"min-h-9",n.badgeTone,r),children:[i?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/58",children:Pd(s)}):null,e.jsx("span",{className:"min-w-0 break-words whitespace-normal",children:t})]})}function Ns(t,s,a,i){t.setQueryData(s,r=>{const n=(r==null?void 0:r[a])??[];return n.some(l=>l.id===i.id)?r:{...r??{},[a]:[i,...n]}})}const pt=Ke().trim(),qt=pt.min(1),QT=tt(qt).transform(t=>Array.from(new Set(t))),Ka=Ke().trim().min(1).nullable().optional(),mx=ft({title:qt,description:pt,valuedDirection:qt,whyItMatters:pt,linkedGoalIds:tt(Ke()).default([]),linkedProjectIds:tt(Ke()).default([]),linkedTaskIds:tt(Ke()).default([]),committedActions:tt(pt).default([]),userId:Ka}),hx=ft({title:qt,description:pt,targetBehavior:qt,cueContexts:tt(pt).default([]),shortTermPayoff:pt,longTermCost:pt,preferredResponse:qt,linkedValueIds:tt(Ke()).default([]),linkedSchemaLabels:QT.default([]),linkedModeIds:tt(Ke()).default([]),linkedBeliefIds:tt(Ke()).default([]),userId:Ka}),px=ft({kind:Ft(["away","committed","recovery"]),title:qt,description:pt,commonCues:tt(pt).default([]),urgeStory:pt,shortTermPayoff:pt,longTermCost:pt,replacementMove:pt,repairPlan:pt,linkedPatternIds:tt(Ke()).default([]),linkedValueIds:tt(Ke()).default([]),linkedSchemaIds:tt(Ke()).default([]),linkedModeIds:tt(Ke()).default([]),userId:Ka}),xx=ft({schemaId:Ke().nullable(),statement:qt,beliefType:Ft(["absolute","conditional"]),originNote:pt,confidence:Ru().int().min(0).max(100),evidenceFor:tt(pt).default([]),evidenceAgainst:tt(pt).default([]),flexibleAlternative:pt,linkedValueIds:tt(Ke()).default([]),linkedBehaviorIds:tt(Ke()).default([]),linkedModeIds:tt(Ke()).default([]),linkedReportIds:tt(Ke()).default([]),userId:Ka}),gx=ft({family:Ft(["coping","child","critic_parent","healthy_adult","happy_child"]),archetype:pt,title:qt,persona:pt,imagery:pt,symbolicForm:pt,facialExpression:pt,fear:pt,burden:pt,protectiveJob:pt,originContext:pt,firstAppearanceAt:Ke().trim().nullable(),linkedPatternIds:tt(Ke()).default([]),linkedBehaviorIds:tt(Ke()).default([]),linkedValueIds:tt(Ke()).default([]),userId:Ka}),VT=ft({summary:qt,answers:tt(ft({questionKey:qt,value:qt})).min(1),userId:Ka});ft({label:qt,description:pt,userId:Ka});ft({label:qt,description:pt,category:pt,userId:Ka});const XT=ft({id:qt,emotionDefinitionId:Ke().nullable(),label:qt,intensity:Ru().int().min(0).max(100),note:pt}),YT=ft({id:qt,text:qt,parentMode:pt,criticMode:pt,beliefId:Ke().nullable()}),JT=ft({id:qt,text:qt,mode:pt,behaviorId:Ke().nullable()}),ZT=ft({id:qt,stage:qt,modeId:Ke().nullable(),label:qt,note:pt}),Nu=ft({title:qt,status:Ft(["draft","reviewed","integrated"]).default("draft"),eventTypeId:Ke().nullable(),customEventType:pt,eventSituation:qt,occurredAt:Ke().trim().nullable(),emotions:tt(XT).default([]),thoughts:tt(YT).default([]),behaviors:tt(JT).default([]),consequences:ft({selfShortTerm:tt(pt).default([]),selfLongTerm:tt(pt).default([]),othersShortTerm:tt(pt).default([]),othersLongTerm:tt(pt).default([])}),linkedPatternIds:tt(Ke()).default([]),linkedValueIds:tt(Ke()).default([]),linkedGoalIds:tt(Ke()).default([]),linkedProjectIds:tt(Ke()).default([]),linkedTaskIds:tt(Ke()).default([]),linkedBehaviorIds:tt(Ke()).default([]),linkedBeliefIds:tt(Ke()).default([]),linkedModeIds:tt(Ke()).default([]),modeOverlays:tt(pt).default([]),schemaLinks:tt(pt).default([]),modeTimeline:tt(ZT).default([]),nextMoves:tt(pt).default([]),userId:Ka}),Nn={kind:"away",title:"",description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:null};function eP(t){return{kind:t.kind,title:t.title,description:t.description,commonCues:t.commonCues,urgeStory:t.urgeStory,shortTermPayoff:t.shortTermPayoff,longTermCost:t.longTermCost,replacementMove:t.replacementMove,repairPlan:t.repairPlan,linkedPatternIds:t.linkedPatternIds,linkedValueIds:t.linkedValueIds,linkedSchemaIds:t.linkedSchemaIds,linkedModeIds:t.linkedModeIds,userId:t.userId??null}}const fx={away:"Away moves",committed:"Committed actions",recovery:"Recovery moves"};function tP(){var J,q,_,B,G,ae,ke,Ae,ie,Ie,Ne;const t=jt(),s=ct(),[a,i]=ms(),[r,n]=c.useState(!1),[l,o]=c.useState(null),[d,m]=c.useState(Nn),[h,u]=c.useState(null),x=Fe({queryKey:["forge-psyche-behaviors"],queryFn:Xs}),g=Fe({queryKey:["forge-psyche-patterns"],queryFn:Oa}),p=Fe({queryKey:["forge-psyche-values"],queryFn:Vs}),f=Fe({queryKey:["forge-psyche-schema-catalog"],queryFn:fl}),b=Fe({queryKey:["forge-psyche-modes"],queryFn:za}),A=((J=x.data)==null?void 0:J.behaviors)??[],C=((q=g.data)==null?void 0:q.patterns)??[],T=((_=p.data)==null?void 0:_.values)??[],w=((B=f.data)==null?void 0:B.schemas)??[],S=((G=b.data)==null?void 0:G.modes)??[],y=ys(t.selectedUserIds),N=a.get("focus"),P=t.snapshot.dashboard.notesSummaryByEntity;Zr(N),c.useEffect(()=>{if(a.get("create")==="1"){n(!0),o(null),m({...Nn,userId:y});const M=new URLSearchParams(a);M.delete("create"),i(M,{replace:!0})}},[y,a,i]);const v=Re({mutationFn:async M=>{const E=px.parse(M);return l?Uj(l.id,E):hd(E)},onSuccess:async()=>{n(!1),o(null),m({...Nn,userId:y}),u(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-behaviors"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),H=C.map(M=>({value:M.id,label:Dt(M.title,M.user),description:ut(M.preferredResponse||M.targetBehavior,M.user),searchText:dt([M.title,M.preferredResponse,M.targetBehavior,M.description],M),kind:"pattern"})),j=T.map(M=>({value:M.id,label:Dt(M.title,M.user),description:ut(M.valuedDirection,M.user),searchText:dt([M.title,M.valuedDirection,M.description],M),kind:"value"})),R=w.map(M=>({value:M.id,label:M.title,description:`${M.description} ${Qm(M.family)}`,searchText:`${M.slug} ${M.family} ${M.schemaType}`,badge:e.jsx(ni,{label:M.title,schemaType:M.schemaType,compact:!0}),menuBadge:e.jsx(ni,{label:M.title,schemaType:M.schemaType,compact:!0})})),Q=S.map(M=>({value:M.id,label:Dt(M.title,M.user),description:ut(M.archetype||M.family,M.user),searchText:dt([M.title,M.archetype,M.family,M.persona],M),kind:"mode"})),X=async M=>{const{pattern:E}=await Ju({title:M,description:"",targetBehavior:M,cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[],userId:d.userId});return Ns(s,["forge-psyche-patterns"],"patterns",E),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:E.id,label:E.title,description:E.preferredResponse||E.targetBehavior,kind:"pattern"}},Y=async M=>{const{value:E}=await Vr({title:M,description:"",valuedDirection:M,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:d.userId});return Ns(s,["forge-psyche-values"],"values",E),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:E.id,label:E.title,description:E.valuedDirection,kind:"value"}},z=async M=>{const{mode:E}=await bl({family:"coping",archetype:"",title:M,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:d.userId});return Ns(s,["forge-psyche-modes"],"modes",E),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:E.id,label:E.title,description:E.archetype||E.family,kind:"mode"}},K=[{id:"behavior",eyebrow:"Behavior",title:"Describe the move or urge in plain language",description:"Start with the behavior itself so the map reads like something you can instantly recognize in real life.",render:(M,E)=>e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:M.userId??null,users:t.snapshot.users,onChange:O=>E({userId:O}),defaultLabel:Ys(t.snapshot.users.find(O=>O.id===y)??null,"Choose behavior owner"),help:"Behaviors can belong to a human or bot user while still linking across shared patterns, schemas, and modes."}),e.jsx(de,{label:"Behavior title",children:e.jsx(ye,{value:M.title,onChange:O=>E({title:O.target.value}),placeholder:"Scroll to numb the impact"})}),e.jsx(de,{label:"What does the move look like?",children:e.jsx(Ze,{value:M.description,onChange:O=>E({description:O.target.value}),placeholder:"Describe the move the way you would recognize it in the moment, not in therapist shorthand."})})]})},{id:"context",eyebrow:"Context",title:"Capture the cue, the pull, and the immediate payoff",description:"Make the move readable as a real pattern instead of a label.",render:(M,E)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Common cues",children:e.jsx(Ze,{value:M.commonCues.join(`
27
+ `)}function xp(t,s,a,i){return{kind:QI(t,s,a),task:VI(t,a,i),project:XI(t,s,a,i),goal:YI(t),noteMarkdown:JI(t)}}function ZI(t){switch(t){case"task":return{label:"Task",description:"Turn the recommendation into one concrete next move."};case"project":return{label:"Project",description:"Start a larger initiative when the insight needs a stream of work."};case"goal":return{label:"Goal",description:"Capture a new long-term direction when this changes strategy."};case"note":return{label:"Linked note",description:"Attach the recommendation as durable evidence without creating new work."}}}function e3({open:t,onOpenChange:s,insight:a,goals:i,projects:r,tasks:n,tags:l,pending:o=!1,onSubmit:d}){const m=c.useMemo(()=>rw(a,i,r),[i,a,r]),h=c.useMemo(()=>Km(a),[a]),[u,x]=c.useState(()=>xp(a,i,r,n)),[g,p]=c.useState(null),[f,b]=c.useState({});c.useEffect(()=>{t&&(x(xp(a,i,r,n)),p(null),b({}))},[i,a,t,r,n]);const A=u.task.projectId?r.find(S=>S.id===u.task.projectId)??null:null;c.useEffect(()=>{A&&u.task.goalId!==A.goalId&&x(S=>({...S,task:{...S.task,goalId:A.goalId}}))},[u.task.goalId,A]);const C=u.project.goalId?i.find(S=>S.id===u.project.goalId)??null:null,T=c.useMemo(()=>{var S,y,N;if(!h)return null;switch(h.entityType){case"goal":return((S=i.find(P=>P.id===h.entityId))==null?void 0:S.title)??"Linked goal";case"project":return((y=r.find(P=>P.id===h.entityId))==null?void 0:y.title)??"Linked project";case"task":return((N=n.find(P=>P.id===h.entityId))==null?void 0:N.title)??"Linked task";default:return`${h.entityType.replaceAll("_"," ")}`}},[i,r,h,n]),w=[{id:"kind",eyebrow:"Apply",title:"Choose what this insight should become",description:"Accept means you agree with the recommendation. Apply means you turn it into a real record right now.",render:(S,y)=>e.jsx(de,{label:"Apply as",description:"Pick the kind of record Forge should create from this recommendation.",hint:"Task is the best default when the insight points to a concrete next move.",children:e.jsx(wt,{value:S.kind,onChange:N=>y({kind:N}),options:m.map(N=>({value:N,...ZI(N)})),columns:m.length>=3?3:2})})},{id:"details",eyebrow:"Details",title:"Review the record Forge will create",description:"The fields are prefilled from the insight, but you can tighten them before saving.",render:(S,y)=>S.kind==="task"?e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Task title",error:f.title??null,children:e.jsx(ye,{value:S.task.title,onChange:N=>y({task:{...S.task,title:N.target.value}}),placeholder:"Turn the recommendation into a task"})}),e.jsx(de,{label:"Description",children:e.jsx(Ze,{value:S.task.description,onChange:N=>y({task:{...S.task,description:N.target.value}}),placeholder:"Add the operational context for this task."})}),e.jsx(de,{label:"Project",error:f.projectId??null,children:e.jsx("div",{className:"grid gap-3",children:r.map(N=>{const P=N.id===S.task.projectId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${P?"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]"}`,onClick:()=>y({task:{...S.task,projectId:N.id,goalId:N.goalId}}),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"font-medium",children:N.title}),e.jsx(We,{kind:"goal",label:N.goalTitle,compact:!0,gradient:!1})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description||"No project note attached yet."})]},N.id)})})}),e.jsx(de,{label:"Owner",error:f.owner??null,children:e.jsx(ye,{value:S.task.owner,onChange:N=>y({task:{...S.task,owner:N.target.value}}),placeholder:"Albert"})}),e.jsx(de,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(N=>{const P=S.task.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${P?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>y({task:{...S.task,tagIds:P?S.task.tagIds.filter(v=>v!==N.id):[...S.task.tagIds,N.id]}}),children:N.name},N.id)})})})]}):S.kind==="project"?e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Project title",error:f.title??null,children:e.jsx(ye,{value:S.project.title,onChange:N=>y({project:{...S.project,title:N.target.value}}),placeholder:"Turn the insight into a project"})}),e.jsx(de,{label:"Description",children:e.jsx(Ze,{value:S.project.description,onChange:N=>y({project:{...S.project,description:N.target.value}}),placeholder:"Describe the initiative this insight points to."})}),e.jsx(de,{label:"Goal",error:f.goalId??null,children:e.jsx("div",{className:"grid gap-3",children:i.map(N=>{const P=N.id===S.project.goalId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${P?"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]"}`,onClick:()=>y({project:{...S.project,goalId:N.id}}),children:[e.jsx("div",{className:"font-medium",children:N.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description||"No strategic note attached yet."})]},N.id)})})}),C?e.jsxs(ui,{children:["This project will sit under the “",C.title,"” goal."]}):null]}):S.kind==="goal"?e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Goal title",error:f.title??null,children:e.jsx(ye,{value:S.goal.title,onChange:N=>y({goal:{...S.goal,title:N.target.value}}),placeholder:"Turn the insight into a life goal"})}),e.jsx(de,{label:"Description",children:e.jsx(Ze,{value:S.goal.description,onChange:N=>y({goal:{...S.goal,description:N.target.value}}),placeholder:"Describe the strategic direction this insight suggests."})}),e.jsx(de,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(N=>{const P=S.goal.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${P?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>y({goal:{...S.goal,tagIds:P?S.goal.tagIds.filter(v=>v!==N.id):[...S.goal.tagIds,N.id]}}),children:N.name},N.id)})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Linked note",description:"This stores the insight as durable Markdown evidence on the linked entity instead of creating a new work item.",hint:T?`This note will attach to ${T}.`:void 0,children:e.jsx(Ze,{value:S.noteMarkdown,onChange:N=>y({noteMarkdown:N.target.value}),placeholder:"Write the applied note content in Markdown",className:"min-h-64"})}),T?e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white/70",children:["Linked target:"," ",e.jsx("span",{className:"font-medium text-white",children:T})]}):null]})}];return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Apply insight",title:"Turn this insight into a real record",description:"Apply should create something concrete inside Forge, not just change the status label.",value:u,onChange:x,draftPersistenceKey:"insights.apply",steps:w,submitLabel:"Apply insight",pending:o,error:g,onSubmit:async()=>{p(null),b({});try{if(u.kind==="task"){const S=Df.safeParse(u.task);if(!S.success){b(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([y,N])=>[y,N==null?void 0:N[0]]))),p("This applied task still needs a valid title, project, and owner.");return}await d({kind:"task",input:S.data}),s(!1);return}if(u.kind==="project"){const S=Lf.safeParse(u.project);if(!S.success){b(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([y,N])=>[y,N==null?void 0:N[0]]))),p("This applied project still needs a valid title and goal.");return}await d({kind:"project",input:S.data}),s(!1);return}if(u.kind==="goal"){const S=Ef.safeParse(u.goal);if(!S.success){b(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([y,N])=>[y,N==null?void 0:N[0]]))),p("This applied goal still needs a valid title and target.");return}await d({kind:"goal",input:S.data}),s(!1);return}if(!u.noteMarkdown.trim()){p("The linked note needs Markdown content before it can be saved.");return}if(!h){p("This insight is not attached to a specific entity yet, so Forge cannot place a linked note for it.");return}await d({kind:"note",input:{contentMarkdown:u.noteMarkdown.trim()}}),s(!1)}catch(S){p(S instanceof Error?S.message:"Unable to apply this insight right now.")}}})}function gp(t,s){return{originType:(t==null?void 0:t.originType)??"user",originAgentId:(t==null?void 0:t.originAgentId)??"",originLabel:(t==null?void 0:t.originLabel)??"",entityType:(s==null?void 0:s.entityType)??(t==null?void 0:t.entityType)??"",entityId:(s==null?void 0:s.entityId)??(t==null?void 0:t.entityId)??"",timeframeLabel:(t==null?void 0:t.timeframeLabel)??"This week",title:(t==null?void 0:t.title)??"",summary:(t==null?void 0:t.summary)??"",recommendation:(t==null?void 0:t.recommendation)??"",rationale:(t==null?void 0:t.rationale)??"",confidence:(t==null?void 0:t.confidence)??.72,ctaLabel:(t==null?void 0:t.ctaLabel)??"Review insight",targetKind:(s==null?void 0:s.entityType)??(t==null?void 0:t.entityType)??"general"}}function nw({open:t,onOpenChange:s,title:a="Store insight",description:i="Capture a clear observation, its recommendation, and where it belongs without dropping into a raw admin form.",eyebrow:r="Insight",pending:n=!1,submitLabel:l="Store insight",initialValue:o,lockedEntity:d,entityCandidates:m=[],onSubmit:h}){const[u,x]=c.useState(()=>gp(o,d)),[g,p]=c.useState(null);c.useEffect(()=>{t&&(x(gp(o,d)),p(null))},[o,d,t]);const f=c.useMemo(()=>{const C=new Set(["general"]);return m.forEach(T=>C.add(T.entityType)),d&&C.add(d.entityType),Array.from(C)},[m,d]),b=m.filter(C=>C.entityType===u.targetKind),A=[{id:"focus",eyebrow:"Focus",title:"Name the insight and place it in the right context",description:"Start with the main observation, then decide whether this belongs to a specific entity or should stay general.",render:(C,T)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Insight title",description:"Write the main idea as a clear headline.",labelHelp:"The title should sound like the recommendation or realization you want to remember, not like an internal database field.",children:e.jsx(ye,{value:C.title,onChange:w=>T({title:w.target.value}),placeholder:"Weekly review needs a tighter end ritual"})}),e.jsx(de,{label:"Timeframe",description:"Keep the horizon short and readable.",children:e.jsx(ye,{value:C.timeframeLabel,onChange:w=>T({timeframeLabel:w.target.value}),placeholder:"This week"})}),e.jsx(de,{label:"Where should this insight live?",description:"Use a specific entity when the insight is about one goal, project, task, or report. Keep it general when it applies to the wider system.",children:d?e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx(We,{kind:d.kind,label:d.label}),d.description?e.jsx(ui,{className:"mt-2",children:d.description}):null]}):e.jsxs(e.Fragment,{children:[e.jsx(wt,{value:C.targetKind,onChange:w=>T({targetKind:w,entityType:w==="general"?"":w,entityId:""}),options:f.map(w=>({value:w,label:w==="general"?"General insight":w==="trigger_report"?"Report":w.charAt(0).toUpperCase()+w.slice(1),description:w==="general"?"Store it in the broader insight feed.":`Attach it to a specific ${w==="trigger_report"?"report":w}.`})),columns:f.length>=3?3:2}),C.targetKind!=="general"?b.length>0?e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:b.map(w=>{const S=C.entityType===w.entityType&&C.entityId===w.entityId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${S?"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]"}`,onClick:()=>T({entityType:w.entityType,entityId:w.entityId}),children:[e.jsx(We,{kind:w.kind,label:w.label,compact:!0}),w.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:w.description}):null]},`${w.entityType}:${w.entityId}`)})}):e.jsxs(ui,{className:"mt-4",children:["No"," ",C.targetKind==="trigger_report"?"reports":`${C.targetKind}s`," ","are ready to attach here yet."]}):null]})})]})},{id:"observation",eyebrow:"Observation",title:"Capture what you are seeing clearly",description:"Keep the summary plain and useful. Add the why only if it helps the next action make sense.",render:(C,T)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Summary",description:"Describe the pattern, problem, or opportunity in plain language.",labelHelp:"Write what is actually happening, not a slogan and not a long essay.",children:e.jsx(Ze,{value:C.summary,onChange:w=>T({summary:w.target.value}),placeholder:"The weekly review loses energy because the close-out is vague, so finished work never turns into clear next moves."})}),e.jsx(de,{label:"Why this matters",description:"Optional context that helps explain the recommendation.",children:e.jsx(Ze,{value:C.rationale,onChange:w=>T({rationale:w.target.value}),placeholder:"When the close-out is loose, important wins disappear from memory and the next week starts without momentum."})})]})},{id:"move",eyebrow:"Next move",title:"Turn the insight into a recommendation",description:"Finish with the recommendation you want the user or agent to actually act on.",render:(C,T)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Recommendation",description:"Write the concrete move this insight points toward.",labelHelp:"A recommendation should be actionable. If the user read only this line, they should know what to do next.",children:e.jsx(Ze,{value:C.recommendation,onChange:w=>T({recommendation:w.target.value}),placeholder:"Add a fixed five-minute close-out block that turns finished tasks into one sentence of evidence and one next move."})}),e.jsx(de,{label:"Confidence",description:"Choose how strongly this recommendation holds up right now.",children:e.jsx(wt,{value:String(C.confidence),onChange:w=>T({confidence:Number(w)}),options:[{value:"0.55",label:"Low",description:"Useful hunch, still early."},{value:"0.72",label:"Medium",description:"Solid pattern, worth acting on."},{value:"0.88",label:"High",description:"Clear enough to trust strongly."}],columns:3})})]})}];return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:r,title:a,description:i,value:u,onChange:x,draftPersistenceKey:"insights.flow",steps:A,submitLabel:l,pending:n,error:g,onSubmit:async()=>{p(null);const C=b2.safeParse({originType:u.originType,originAgentId:u.originAgentId,originLabel:u.originLabel,entityType:u.targetKind==="general"?"":u.entityType,entityId:u.targetKind==="general"?"":u.entityId,timeframeLabel:u.timeframeLabel,title:u.title,summary:u.summary,recommendation:u.recommendation,rationale:u.rationale,confidence:u.confidence,ctaLabel:u.ctaLabel});if(!C.success){p("This insight still needs a title, a summary, and a recommendation before it can be stored.");return}try{await h(C.data),s(!1)}catch(T){p(T instanceof Error?T.message:"Unable to store this insight right now.")}}})}function t3(){var w,S,y,N;const t=ct(),s=$t(),a=jt(),i=Array.isArray(a.selectedUserIds)?a.selectedUserIds:[],{snapshot:r}=a,[n,l]=c.useState(!1),[o,d]=c.useState(null),m=Fe({queryKey:["forge-insights",...i],queryFn:()=>Ej(i)}),h=Re({mutationFn:nf,onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),u=Re({mutationFn:({insightId:P,feedbackType:v})=>hh(P,v),onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),x=Re({mutationFn:({insightId:P})=>gN(P),onMutate:async({insightId:P})=>{await t.cancelQueries({queryKey:["forge-insights"]});const v=t.getQueryData(["forge-insights"]);if(v){const H=v.insights.feed.find(j=>j.id===P);t.setQueryData(["forge-insights"],{insights:{...v.insights,feed:v.insights.feed.filter(j=>j.id!==P),openCount:(H==null?void 0:H.status)==="open"?Math.max(0,v.insights.openCount-1):v.insights.openCount}})}return{previous:v}},onError:(P,v,H)=>{H!=null&&H.previous&&t.setQueryData(["forge-insights"],H.previous)},onSettled:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),g=Re({mutationFn:async({insight:P,submission:v})=>{let H=null,j="Applied the insight.";if(v.kind==="task"){const R=await im(v.input);H=`/tasks/${R.task.id}`,j=`Created task: ${R.task.title}`}else if(v.kind==="project"){const R=await am(v.input);H=`/projects/${R.project.id}`,j=`Created project: ${R.project.title}`}else if(v.kind==="goal"){const R=await sm(v.input);H=`/goals/${R.goal.id}`,j=`Created goal: ${R.goal.title}`}else{const R=Km(P);if(!R)throw new Error("This insight is not linked to a concrete entity yet, so Forge cannot attach a linked note to it.");await wl({contentMarkdown:v.input.contentMarkdown,links:[R]}),H=yl(R.entityType,R.entityId),j="Created a linked note from the insight."}return await hh(P.id,"applied",j),{href:H}},onSuccess:async({href:P})=>{await Promise.all([t.invalidateQueries({queryKey:["forge-insights"]}),Ut(t),t.invalidateQueries({queryKey:["forge-xp-metrics"]}),t.invalidateQueries({queryKey:["forge-reward-ledger"]}),t.invalidateQueries({queryKey:["notes-index"]})]),d(null),P&&s(P)}}),p=(w=m.data)==null?void 0:w.insights,f=c.useMemo(()=>[...r.goals.slice(0,8).map(P=>({entityType:"goal",entityId:P.id,kind:"goal",label:P.title,description:P.description})),...r.projects.slice(0,8).map(P=>({entityType:"project",entityId:P.id,kind:"project",label:P.title,description:P.goalTitle})),...r.tasks.slice(0,10).map(P=>({entityType:"task",entityId:P.id,kind:"task",label:P.title,description:P.status.replaceAll("_"," ")}))],[r.goals,r.projects,r.tasks]),b=u.isPending?((S=u.variables)==null?void 0:S.insightId)??null:null,A=x.isPending?((y=x.variables)==null?void 0:y.insightId)??null:null,C=g.isPending?((N=g.variables)==null?void 0:N.insight.id)??null:null,T=r.metrics.topGoalId?r.goals.find(P=>P.id===r.metrics.topGoalId)??null:null;return m.isLoading?e.jsx(Et,{eyebrow:"Insights",title:"Loading the insight feed",description:"Pulling coaching, momentum analysis, and stored recommendations."}):m.isError||!p?e.jsx(it,{eyebrow:"Insights",error:m.error,onRetry:()=>void t.invalidateQueries({queryKey:["forge-insights"]})}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:"Insights",description:"Save useful advice from you or your agent, review what seems worth acting on, and turn the good ones into real work when the timing is right.",badge:`${p.openCount} open`,actions:e.jsx(W,{onClick:()=>l(!0),children:"Store insight"})}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Momentum analysis"}),e.jsx("div",{className:"mt-4 grid grid-cols-5 gap-2 sm:grid-cols-10",children:p.momentumHeatmap.map(P=>e.jsxs("div",{className:"rounded-[16px] bg-white/[0.04] p-3",children:[e.jsx("div",{className:"h-12 rounded-[12px]",style:{background:P.intensity>=4?"rgba(192,193,255,0.95)":P.intensity===3?"rgba(192,193,255,0.7)":P.intensity===2?"rgba(192,193,255,0.45)":P.intensity===1?"rgba(192,193,255,0.2)":"rgba(255,255,255,0.05)"}}),e.jsx("div",{className:"mt-2 text-[10px] uppercase tracking-[0.16em] text-white/40",children:P.label})]},P.id))})]}),e.jsxs(ce,{children:[e.jsxs("div",{className:"flex items-center gap-2 font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:[e.jsx("span",{children:"Execution trends"}),e.jsx(vt,{content:"The lavender series tracks completed XP by time window. The green series tracks execution pressure from focused and completed work. Read them together to see whether visible output and active work are moving in sync.",label:"Explain execution trends"})]}),e.jsx("div",{className:"mt-4 h-72 min-w-0",children:e.jsx(Fi,{width:"100%",height:"100%",minWidth:280,minHeight:288,children:e.jsxs(Er,{data:p.executionTrends,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"insight-xp",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#c0c1ff",stopOpacity:"0.8"}),e.jsx("stop",{offset:"100%",stopColor:"#c0c1ff",stopOpacity:"0.08"})]})}),e.jsx(ai,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(ii,{hide:!0}),e.jsx(Za,{dataKey:"xp",stroke:"#c0c1ff",fill:"url(#insight-xp)",strokeWidth:2}),e.jsx(Za,{dataKey:"focusScore",stroke:"#4edea3",fill:"rgba(78,222,163,0.06)",strokeWidth:2})]})})}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.04] px-3 py-2 text-sm text-white/64",children:[e.jsx("span",{className:"size-2.5 rounded-full bg-[#c0c1ff]"}),e.jsx("span",{children:"Completed XP"}),e.jsx(vt,{content:"Completed XP is the reward Forge logged for finished work in each time window. It helps you see whether things are actually getting finished, not just started.",label:"Explain completed XP"})]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.04] px-3 py-2 text-sm text-white/64",children:[e.jsx("span",{className:"size-2.5 rounded-full bg-[#4edea3]"}),e.jsx("span",{children:"Focus score"}),e.jsx(vt,{content:"Focus score is Forge's rough read of how much active execution pressure was present in each window, based on focused and completed work.",label:"Explain focus score"})]})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/54",children:"Use this chart to spot whether finished output and active deep-work pressure are rising together or starting to drift apart."})]}),e.jsxs(ce,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/60",children:"Deterministic coaching"}),e.jsx(vt,{content:"This is Forge's built-in coaching read. It looks at your overdue work, blocked work, current goal pressure, and recent evidence to produce one grounded recommendation from the actual operating record.",label:"Explain deterministic coaching"})]}),e.jsx("h2",{className:"mt-4 font-display text-4xl text-white",children:p.coaching.title}),e.jsx("p",{className:"mt-4 text-sm leading-7 text-white/60",children:"Forge turns the current state of your goals, projects, tasks, and recent evidence into one focused operating read instead of a vague motivational hint."}),e.jsxs("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Current read"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/72",children:p.coaching.summary})]}),e.jsxs("div",{className:"mt-4 rounded-[22px] bg-[radial-gradient(circle_at_top_left,rgba(192,193,255,0.14),transparent_45%),rgba(255,255,255,0.03)] p-5",children:[e.jsx("div",{className:"font-medium text-white",children:"Recommendation"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/60",children:p.coaching.recommendation}),T?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"rounded-full bg-white/[0.06] px-3 py-2 text-sm text-white/64",children:["Connected goal: ",e.jsx("span",{className:"font-medium text-white",children:T.title})]}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>s(`/goals/${T.id}`),children:"Open goal"})]}):null]})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Store insight"}),e.jsxs("div",{className:"mt-4 rounded-[22px] bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-medium text-white",children:"Capture advice without forcing it into a task too early"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/60",children:"Insights are saved suggestions from you or your agent. Use them when something feels worth remembering, but it is not ready to become a goal, project, or task yet."}),e.jsx("div",{className:"mt-4",children:e.jsx(W,{onClick:()=>l(!0),children:"Store insight"})})]})]}),e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Stored insights"}),e.jsx("div",{className:"mt-4 grid gap-3",children:p.feed.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/55",children:"No stored insights yet."}):p.feed.map(P=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:P.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:P.summary}),P.user?e.jsx("div",{className:"mt-3",children:e.jsx(ot,{user:P.user,compact:!0})}):null]}),e.jsx(I,{className:"text-white/70",children:P.status})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:P.recommendation}),e.jsxs("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:[P.originLabel??P.originType," · confidence ",Math.round(P.confidence*100),"%"]}),P.status==="applied"?e.jsx("div",{className:"mt-4 rounded-[16px] border border-emerald-400/18 bg-emerald-400/8 px-4 py-3 text-sm text-emerald-100/88",children:"This insight has already been turned into a real Forge record, so it stays here as a trace of what happened."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 text-sm text-white/52",children:P.status==="accepted"?"Accepted means this feels useful and worth keeping in view. Apply turns it into a real goal, project, task, or note when you are ready.":"Accept keeps this advice on the board. Apply turns it into a real Forge record now. Dismiss deletes it from the list."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[P.status!=="accepted"?e.jsx(W,{variant:"secondary",pending:b===P.id,onClick:()=>void u.mutateAsync({insightId:P.id,feedbackType:"accepted"}),children:"Accept"}):null,e.jsx(W,{pending:C===P.id,onClick:()=>d(P),children:"Apply"}),e.jsx(W,{variant:"ghost",pending:A===P.id,onClick:()=>void x.mutateAsync({insightId:P.id}),children:"Dismiss"})]})]})]},P.id))})]})]})]}),e.jsx(nw,{open:n,onOpenChange:l,entityCandidates:f,pending:h.isPending,onSubmit:async P=>{await h.mutateAsync(P)}}),o?e.jsx(e3,{open:!!o,onOpenChange:P=>{P||d(null)},insight:o,goals:r.goals,projects:r.projects,tasks:r.tasks,tags:r.tags,pending:g.isPending,onSubmit:async P=>{await g.mutateAsync({insight:o,submission:P})}}):null]})}function s3(t){if(typeof t=="number"&&Number.isInteger(t)&&t>0)return t;if(typeof t=="string"){const s=t.match(/(\d+)/);if(s){const a=Number.parseInt(s[1]??"",10);return Number.isInteger(a)&&a>0?a:null}}return null}function fp(t){return t.split(/\r?\n/).map(s=>s.trim()).reduce((s,a)=>{const i=a.match(/^[-*+]\s+\[([ xX])\]\s+(.+)$/);if(i)return s.push({label:i[2].trim(),completed:i[1].toLowerCase()==="x"}),s;const r=a.match(/^(?:[-*+]|\d+\.)\s+(.+)$/);return r&&s.push({label:r[1].trim(),completed:null}),s},[]).filter(s=>s.label.length>0)}function a3(t){if(t.acceptanceCriteria.length>0)return{total:t.acceptanceCriteria.length,completed:t.status==="done"?t.acceptanceCriteria.length:0,source:"acceptance_criteria",items:t.acceptanceCriteria};const s=fp(t.aiInstructions);if(s.length>0){const i=t.status==="done"?s.length:s.filter(r=>r.completed===!0).length;return{total:s.length,completed:i,source:"ai_instructions",items:s.map(r=>r.label)}}const a=fp(t.description);if(a.length>0){const i=t.status==="done"?a.length:a.filter(r=>r.completed===!0).length;return{total:a.length,completed:i,source:"description",items:a.map(r=>r.label)}}return null}function bp(t,s){return t.find(a=>a.refType===s)??null}function lw(t,s=null){var o,d,m,h,u,x,g,p,f,b,A;const a=new Set(((o=t.completionReport)==null?void 0:o.linkedGitRefIds)??[]),i=bp(t.gitRefs,"branch"),r=bp(t.gitRefs,"pull_request"),n=(s==null?void 0:s.gitContext)??null,l=(n==null?void 0:n.pullRequestNumber)??s3((r==null?void 0:r.refValue)??(r==null?void 0:r.displayTitle)??null);return{actor:(s==null?void 0:s.actor)??null,activeRun:s,stepSummary:a3(t),changedFileCount:((d=t.completionReport)==null?void 0:d.modifiedFiles.length)??0,changedFilesPreview:(((m=t.completionReport)==null?void 0:m.modifiedFiles)??[]).slice(0,2),git:{provider:((h=n==null?void 0:n.provider)==null?void 0:h.trim())||((u=i==null?void 0:i.provider)==null?void 0:u.trim())||((x=r==null?void 0:r.provider)==null?void 0:x.trim())||null,repository:((g=n==null?void 0:n.repository)==null?void 0:g.trim())||((p=i==null?void 0:i.repository)==null?void 0:p.trim())||((f=r==null?void 0:r.repository)==null?void 0:f.trim())||null,branch:((b=n==null?void 0:n.branch)==null?void 0:b.trim())||((A=i==null?void 0:i.refValue)==null?void 0:A.trim())||null,branchUrl:(n==null?void 0:n.branchUrl)??(i==null?void 0:i.url)??null,pullRequestNumber:l,pullRequestUrl:(n==null?void 0:n.pullRequestUrl)??(r==null?void 0:r.url)??null,compareUrl:(n==null?void 0:n.compareUrl)??null,linkedRefCount:a.size}}}const vs=["backlog","focus","in_progress","blocked","done"];function i3({task:t,onOpenTask:s,onEditTask:a,onLinkTask:i,onCreateTaskForIssue:r,onCreateSubtaskForTask:n,onMove:l,onDeleteTask:o,deletePendingTaskId:d,onRequestDelete:m}){const h=t.level==="issue"?{id:"create-task",label:"Create task",description:"Add a focused execution task under this issue.",icon:qc,onSelect:()=>r==null?void 0:r(t.id)}:t.level==="task"?{id:"create-subtask",label:"Create subtask",description:"Add a granular child step under this task.",icon:qc,onSelect:()=>n==null?void 0:n(t.id)}:null;return[{id:"open-task",label:"Open",description:"Jump to the work-item detail view.",icon:Es,onSelect:()=>s==null?void 0:s(t.id)},{id:"edit-task",label:"Edit",description:"Open the guided work-item editor.",icon:pi,onSelect:()=>a==null?void 0:a(t.id)},{id:"link-task",label:"Link",description:"Open the placement step to relink this work item.",icon:$s,onSelect:()=>i==null?void 0:i(t.id)},...h?[h]:[],{id:"delete-task",label:t.level==="issue"?"Delete issue":t.level==="subtask"?"Delete subtask":"Delete task",description:"Remove this work item directly from the board menu.",icon:Rt,tone:"danger",disabled:!o||d===t.id,onSelect:()=>m(t)},...vs.filter(u=>u!==t.status).map(u=>({id:`move-task-${u}`,label:`Move to ${u.replaceAll("_"," ")}`,description:"Update the workflow lane for this work item.",onSelect:()=>void l(t.id,u)}))]}function ow(t){return t.startsWith("lane:")||t.includes(":lane:")}function r3(t){var s,a;return((a=(s=t.data)==null?void 0:s.current)==null?void 0:a.type)==="lane"||ow(String(t.id))}function n3(t){var s,a;return((a=(s=t.data)==null?void 0:s.current)==null?void 0:a.type)==="trash"}function l3(t,s){const a=Math.max(0,Math.min(t.right,s.right)-Math.max(t.left,s.left)),i=Math.max(0,Math.min(t.bottom,s.bottom)-Math.max(t.top,s.top));return a*i}const o3=t=>{const s=E0(t),a=s.find(l=>{const o=t.droppableContainers.find(d=>d.id===l.id);return o?n3(o):!1});if(a)return[a];const i=s.find(l=>ow(String(l.id)));if(i)return[i];const n=t.droppableContainers.filter(l=>r3(l)).map(l=>{const o=t.droppableRects.get(l.id);if(!o)return null;const d=l3(t.collisionRect,o);return d<=0?null:{id:l.id,data:{droppableContainer:l,value:d}}}).filter(Boolean).sort((l,o)=>{var d,m;return(((d=o==null?void 0:o.data)==null?void 0:d.value)??0)-(((m=l==null?void 0:l.data)==null?void 0:m.value)??0)});return n.length>0?n:s.length>0?s:L0(t)};function d3(t,s){return s&&s.trim().length>0?s:t!=null&&t.actor?`${t.actor} session`:"Active work"}function c3(t,s){return[(t==null?void 0:t.actor)??null,s].filter(Boolean).join(" · ")}function wp(t){t.preventDefault(),t.stopPropagation()}function dw({task:t,goal:s,tags:a,activeRun:i,isSelected:r,isDragging:n=!1,isOverlay:l=!1,style:o,setNodeRef:d,dragAttributes:m,dragListeners:h,isMobile:u=!1,onSelect:x,onStartTask:g,onStopTask:p,onQuickReopen:f,onStepTask:b,onSplitTask:A,onOpenMenu:C,notesSummaryByEntity:T}){var J;const{t:w,formatDate:S}=Ot(),y=lw(t,i??null),N=y.stepSummary,P=vs[vs.indexOf(t.status)-1]??null,v=vs[vs.indexOf(t.status)+1]??null,H=Js(T,"task",t.id).count,j=t.level==="issue"?"issue":"task",R=zs(j),Q=t.level==="subtask"?"136,146,255":R.colorToken.rgb.join(", "),X=t.dueDate&&!Number.isNaN(Date.parse(t.dueDate))?S(t.dueDate):"No due date",Y=N&&N.total>0?Math.max(8,Math.round(N.completed/N.total*100)):null,z=y.git.branch,K=y.git.branchUrl,$=y.git.pullRequestNumber?`PR #${y.git.pullRequestNumber}`:null,D=y.git.pullRequestUrl;return e.jsxs("article",{ref:d,style:{...o,"--board-card-accent":Q},className:te("w-full max-w-full min-w-0 overflow-hidden rounded-[18px] p-3 shadow-[inset_0_0_0_1px_rgba(var(--board-card-accent),0.12)] transition cursor-grab active:cursor-grabbing",u&&"touch-none select-none",l&&"rotate-[0.5deg] bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.22),rgba(var(--board-card-accent),0.08))] shadow-[0_28px_80px_rgba(8,12,24,0.42),inset_0_0_0_1px_rgba(var(--board-card-accent),0.28)]",n&&!l&&"opacity-35 shadow-[inset_0_0_0_1px_rgba(var(--board-card-accent),0.08)]",r?"bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.18),rgba(var(--board-card-accent),0.06))] shadow-[0_16px_40px_rgba(8,12,24,0.32),inset_0_0_0_1px_rgba(var(--board-card-accent),0.26)]":"bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.08),rgba(255,255,255,0.03))]"),"data-dragging":n?"true":"false","data-testid":`task-card-${t.id}`,onClick:()=>x(t.id),...m,...h,children:[e.jsx("div",{className:"mb-3 h-px w-full rounded-full",style:{background:`linear-gradient(90deg, rgba(${Q}, 0.96), rgba(${Q}, 0.18))`}}),e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(We,{kind:j,label:t.level,compact:!0,size:"xs",gradient:!1,className:"shrink-0"}),e.jsx(I,{size:"xs",className:"shrink-0 text-[10px] text-[var(--tertiary)]",children:t.priority}),y.actor?e.jsxs(I,{size:"xs",className:"shrink-0 bg-cyan-400/12 text-cyan-100",children:[e.jsx(ma,{className:"mr-1 size-3"}),y.actor]}):null]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-1.5",children:[C?e.jsx("button",{type:"button","aria-label":`Open ${t.title} actions`,className:"inline-flex size-8 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white",onClick:q=>{q.preventDefault(),q.stopPropagation(),C(q,t)},children:e.jsx(Di,{className:"size-3.5"})}):null,u?e.jsxs("div",{className:"flex items-center gap-1",onClick:q=>q.stopPropagation(),children:[e.jsx("button",{type:"button","aria-label":`Move ${t.title} to the previous lane`,className:"inline-flex size-7 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white disabled:opacity-35",disabled:!P,onClick:()=>{P&&(b==null||b(t.id,"previous"))},children:e.jsx(hl,{className:"size-3.5"})}),e.jsx("button",{type:"button","aria-label":`Move ${t.title} to the next lane`,className:"inline-flex size-7 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white disabled:opacity-35",disabled:!v,onClick:()=>{v&&(b==null||b(t.id,"next"))},children:e.jsx(Sa,{className:"size-3.5"})})]}):null,i?e.jsx("button",{type:"button","aria-label":`Stop work on ${t.title}`,className:"inline-flex size-8 items-center justify-center rounded-full bg-rose-500/16 text-rose-200 transition hover:bg-rose-500/24",onClick:q=>{q.preventDefault(),q.stopPropagation(),p==null||p(i)},children:e.jsx(xg,{className:"size-3.5 fill-current"})}):t.status!=="done"?e.jsx("button",{type:"button","aria-label":`Start work on ${t.title}`,className:"inline-flex size-8 items-center justify-center rounded-full bg-[var(--primary)]/16 text-[var(--primary)] transition hover:bg-[var(--primary)]/24",onClick:q=>{q.preventDefault(),q.stopPropagation(),g==null||g(t.id)},children:e.jsx(Hs,{className:"size-4 fill-current"})}):null,(J=t.splitSuggestion)!=null&&J.shouldSplit&&A?e.jsxs("button",{type:"button","aria-label":`Split ${t.title}`,className:"inline-flex items-center gap-1 rounded-full bg-amber-400/12 px-2.5 py-1 text-[10px] font-medium tracking-[0.14em] text-amber-100 transition hover:bg-amber-400/18",onClick:q=>{q.preventDefault(),q.stopPropagation(),A(t.id)},children:[e.jsx(ad,{className:"size-3.5"}),"Split it"]}):null,e.jsxs("span",{className:"shrink-0 text-[11px] text-white/44",children:[t.points," xp"]})]})]}),e.jsx(yt,{kind:j,label:t.title,className:"max-w-full",lines:3,labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("p",{className:"mt-1.5 line-clamp-3 [overflow-wrap:anywhere] text-[12px] leading-5 text-white/62",children:t.description||w("common.executionBoard.noExecutionNote")}),N?e.jsxs("div",{className:"mt-3 rounded-[16px] border border-white/8 bg-white/[0.045] p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] text-white/58",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(lg,{className:"size-3.5 text-sky-200"}),N.total," step",N.total===1?"":"s"]}),e.jsxs("span",{className:"tabular-nums text-white/72",children:[N.completed,"/",N.total]})]}),e.jsx("div",{className:"mt-2 h-1.5 overflow-hidden rounded-full bg-white/8",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(56,189,248,0.96),rgba(125,211,252,0.62))]",style:{width:`${Y??0}%`}})}),e.jsx("div",{className:"mt-2 grid gap-1.5",children:N.items.slice(0,2).map(q=>e.jsx("div",{className:"truncate text-[11px] text-white/55",children:q},`${t.id}-${q}`))})]}):null,e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[z?K?e.jsxs("a",{href:K,target:"_blank",rel:"noreferrer",className:"inline-flex min-w-0 max-w-full items-center gap-1 rounded-full border border-sky-300/18 bg-sky-400/12 px-2.5 py-1 text-[11px] text-sky-50 transition hover:bg-sky-400/18",onClick:wp,children:[e.jsx(ua,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:z})]}):e.jsxs(I,{size:"xs",className:"min-w-0 max-w-full bg-sky-400/12 text-sky-50",children:[e.jsx(ua,{className:"mr-1 size-3"}),e.jsx("span",{className:"truncate",children:z})]}):null,$?D?e.jsxs("a",{href:D,target:"_blank",rel:"noreferrer",className:"inline-flex min-w-0 max-w-full items-center gap-1 rounded-full border border-fuchsia-300/18 bg-fuchsia-400/12 px-2.5 py-1 text-[11px] text-fuchsia-50 transition hover:bg-fuchsia-400/18",onClick:wp,children:[e.jsx(Qn,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:$})]}):e.jsxs(I,{size:"xs",className:"bg-fuchsia-400/12 text-fuchsia-50",children:[e.jsx(Qn,{className:"mr-1 size-3"}),$]}):null,y.changedFileCount>0?e.jsxs(I,{size:"xs",className:"bg-amber-400/12 text-amber-50",children:[e.jsx(kg,{className:"mr-1 size-3"}),y.changedFileCount," file",y.changedFileCount===1?"":"s"]}):null,y.git.repository?e.jsx(I,{size:"xs",className:"bg-white/8 text-white/70",children:y.git.repository}):null]}),y.changedFilesPreview.length>0?e.jsx("div",{className:"mt-2 flex min-w-0 flex-wrap gap-1.5",children:y.changedFilesPreview.map(q=>e.jsx(I,{size:"xs",wrap:!0,className:"min-w-0 max-w-full bg-white/[0.06] font-mono text-[10px] text-white/65",children:q},q))}):null,e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[s?e.jsx(We,{kind:"goal",label:s.title,compact:!0,size:"xs",wrap:!0,className:"min-w-0 max-w-full"}):null,e.jsx(ot,{user:t.user,compact:!0,size:"xs"}),e.jsx(Ks,{entityType:"task",entityId:t.id,count:H,compact:!0}),t.actionPointSummary?e.jsxs(I,{size:"xs",className:"bg-[var(--primary)]/12 text-[var(--primary)]",children:[Math.round(t.actionPointSummary.totalCostAp)," AP"]}):null,t.actionPointSummary?e.jsx(I,{size:"xs",className:"bg-white/8 text-white/72",children:t.actionPointSummary.costBand}):null,t.actionPointSummary?e.jsxs(I,{size:"xs",className:"bg-white/8 text-white/72",children:[Math.round(t.actionPointSummary.expectedDurationSeconds/3600)," h target"]}):null,t.time.totalCreditedSeconds>0?e.jsxs(I,{size:"xs",className:"bg-white/8 text-white/72",children:[Math.floor(t.time.totalCreditedSeconds/60)," min"]}):null,t.time.activeRunCount>0?e.jsxs(I,{size:"xs",className:"bg-emerald-500/12 text-emerald-200",children:[t.time.activeRunCount," live"]}):null,a.slice(0,2).map(q=>e.jsx(I,{size:"xs",className:"bg-white/8",style:{color:q.color},children:q.name},q.id))]}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 items-center justify-between gap-2 text-[11px] text-white/45",children:[e.jsxs("span",{className:"min-w-0 truncate",children:[t.effort," / ",t.energy]}),e.jsxs("div",{className:"flex min-w-0 shrink-0 items-center gap-2 text-right",children:[t.status==="done"&&f?e.jsx("button",{type:"button",className:"rounded-full bg-white/8 px-3 py-1 text-[10px] tracking-[0.16em] text-white transition hover:bg-white/12",onClick:q=>{q.preventDefault(),q.stopPropagation(),f(t.id)},children:w("common.executionBoard.reopen")}):null,e.jsx("span",{children:X})]})]})]})}function Zd(t){const{task:s,sortableId:a}=t,{attributes:i,listeners:r,setNodeRef:n,transform:l,transition:o,isDragging:d}=pl({id:a,data:{type:"task",taskId:s.id,status:s.status}});return e.jsx(dw,{...t,setNodeRef:n,dragAttributes:i,dragListeners:r,isDragging:d,isMobile:t.isMobile,onStartTask:t.onStartTask,onStopTask:t.onStopTask,onStepTask:t.onStepTask,onSplitTask:t.onSplitTask,notesSummaryByEntity:t.notesSummaryByEntity,style:{transform:xl.Transform.toString(l),transition:o}})}function cw({project:t,goal:s,isDragging:a=!1,isOverlay:i=!1,style:r,setNodeRef:n,dragAttributes:l,dragListeners:o,isMobile:d=!1,onStepProject:m,onOpenMenu:h}){const{formatDate:u}=Ot(),x=vs[vs.indexOf(t.workflowStatus)-1]??null,g=vs[vs.indexOf(t.workflowStatus)+1]??null,f=zs("project").colorToken.rgb.join(", "),b=t.workflowStatus.replaceAll("_"," "),A=t.status.replaceAll("_"," "),C=t.updatedAt&&!Number.isNaN(Date.parse(t.updatedAt))?u(t.updatedAt):"No recent update";return e.jsxs("article",{ref:n,style:{...r,"--board-card-accent":f},className:te("w-full max-w-full min-w-0 overflow-hidden rounded-[18px] p-3 shadow-[inset_0_0_0_1px_rgba(var(--board-card-accent),0.12)] transition cursor-grab active:cursor-grabbing",d&&"touch-none select-none",i&&"rotate-[0.5deg] bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.22),rgba(var(--board-card-accent),0.08))] shadow-[0_28px_80px_rgba(8,12,24,0.42),inset_0_0_0_1px_rgba(var(--board-card-accent),0.28)]",a&&!i&&"opacity-35 shadow-[inset_0_0_0_1px_rgba(var(--board-card-accent),0.08)]",!a&&!i&&"bg-[linear-gradient(180deg,rgba(var(--board-card-accent),0.08),rgba(255,255,255,0.03))]"),"data-testid":`project-card-${t.id}`,...l,...o,children:[e.jsx("div",{className:"mb-3 h-px w-full rounded-full",style:{background:`linear-gradient(90deg, rgba(${f}, 0.96), rgba(${f}, 0.18))`}}),e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"project",label:"project",compact:!0,size:"xs",gradient:!1,className:"shrink-0"}),e.jsx(I,{size:"xs",className:"shrink-0 bg-[var(--primary)]/12 text-[var(--primary)]",children:b}),e.jsx(I,{size:"xs",className:"shrink-0 bg-white/8 text-white/72",children:A})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-1.5",children:[h?e.jsx("button",{type:"button","aria-label":`Open ${t.title} actions`,className:"inline-flex size-8 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white",onClick:T=>{T.preventDefault(),T.stopPropagation(),h(T,t)},children:e.jsx(Di,{className:"size-3.5"})}):null,d?e.jsxs("div",{className:"flex items-center gap-1",onClick:T=>T.stopPropagation(),children:[e.jsx("button",{type:"button","aria-label":`Move ${t.title} to the previous lane`,className:"inline-flex size-7 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white disabled:opacity-35",disabled:!x,onClick:()=>{x&&(m==null||m(t.id,"previous"))},children:e.jsx(hl,{className:"size-3.5"})}),e.jsx("button",{type:"button","aria-label":`Move ${t.title} to the next lane`,className:"inline-flex size-7 items-center justify-center rounded-full bg-white/8 text-white/62 transition hover:bg-white/12 hover:text-white disabled:opacity-35",disabled:!g,onClick:()=>{g&&(m==null||m(t.id,"next"))},children:e.jsx(Sa,{className:"size-3.5"})})]}):null]})]}),e.jsx(yt,{kind:"project",label:t.title,className:"max-w-full",lines:3,labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("p",{className:"mt-1.5 line-clamp-3 [overflow-wrap:anywhere] text-[12px] leading-5 text-white/62",children:t.description||"PRD-backed initiative spanning multiple work items."}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[s?e.jsx(We,{kind:"goal",label:s.title,compact:!0,size:"xs",wrap:!0,className:"min-w-0 max-w-full"}):null,e.jsx(ot,{user:t.user,compact:!0,size:"xs"}),(t.assignees??[]).slice(0,2).map(T=>e.jsx(ot,{user:T,compact:!0,size:"xs"},T.id)),e.jsxs(I,{size:"xs",className:"bg-[var(--primary)]/12 text-[var(--primary)]",children:[t.progress,"% progress"]}),e.jsxs(I,{size:"xs",className:"bg-white/8 text-white/72",children:[t.totalTasks," linked tasks"]})]}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 items-center justify-between gap-2 text-[11px] text-white/45",children:[e.jsx("span",{className:"min-w-0 truncate",children:t.goalTitle}),e.jsx("span",{children:C})]})]})}function ec(t){const{project:s,sortableId:a}=t,{attributes:i,listeners:r,setNodeRef:n,transform:l,transition:o,isDragging:d}=pl({id:a,data:{type:"project",projectId:s.id,status:s.workflowStatus}});return e.jsx(cw,{...t,setNodeRef:n,dragAttributes:i,dragListeners:r,isDragging:d,style:{transform:xl.Transform.toString(l),transition:o}})}function yp({droppableId:t,status:s,title:a,detail:i,count:r,dragging:n,children:l}){const{setNodeRef:o,isOver:d}=$g({id:t,data:{type:"lane",status:s}});return e.jsx("div",{ref:o,className:te("w-full max-w-full min-w-0 overflow-hidden rounded-[24px] transition",d&&"scale-[1.005]"),"data-lane-id":s,"data-testid":`kanban-lane-${s}`,"data-lane-hover":d?"true":"false",children:e.jsxs(ce,{className:te("h-full w-full max-w-full min-w-0 overflow-hidden p-3 transition-[background-color,box-shadow,border-color,transform]",n&&"border border-white/8",d?"border border-[rgba(125,211,252,0.38)] bg-[linear-gradient(180deg,rgba(125,211,252,0.12),rgba(125,211,252,0.05))] shadow-[0_18px_54px_rgba(14,165,233,0.12)]":"border border-transparent"),children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"type-label text-white/45",children:i}),e.jsx("h3",{className:"mt-1 break-words text-[1.45rem] leading-[1] text-white",children:a})]}),e.jsx("div",{className:"shrink-0 font-display text-[1.45rem] text-[var(--primary)]",children:r})]}),e.jsx("div",{className:te("grid w-full max-w-full min-w-0 min-h-48 content-start gap-2 rounded-[18px] p-2 transition",d?"bg-[rgba(125,211,252,0.08)]":"bg-white/[0.02]"),children:l})]})})}function u3({title:t,detail:s,children:a}){return e.jsxs("div",{className:"rounded-[20px] border border-cyan-300/20 bg-[linear-gradient(180deg,rgba(34,211,238,0.11),rgba(11,23,34,0.34))] p-2.5 shadow-[inset_0_0_0_1px_rgba(34,211,238,0.08)]",children:[e.jsx("div",{className:"mb-2 flex items-start justify-between gap-3 px-1",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-cyan-100/86",children:[e.jsx(ua,{className:"size-3.5"}),e.jsx("span",{className:"truncate",children:t})]}),s?e.jsx("div",{className:"mt-1 text-[11px] text-white/45",children:s}):null]})}),e.jsx("div",{className:"grid gap-2",children:a})]})}function m3({droppableId:t,title:s,detail:a}){const{setNodeRef:i,isOver:r}=$g({id:t,data:{type:"trash"}});return e.jsx("div",{ref:i,className:te("pointer-events-auto fixed right-4 top-4 z-50 w-[min(18rem,calc(100vw-2rem))] rounded-[28px] border px-5 py-4 shadow-[0_24px_80px_rgba(6,10,20,0.48)] backdrop-blur-2xl transition lg:right-6 lg:top-6",r?"border-rose-300/38 bg-[linear-gradient(180deg,rgba(244,63,94,0.28),rgba(120,24,42,0.46))] text-white scale-[1.02]":"border-white/10 bg-[linear-gradient(180deg,rgba(18,24,38,0.96),rgba(10,14,24,0.94))] text-white/84"),"data-testid":"kanban-trash-dropzone","data-trash-hover":r?"true":"false",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:te("flex size-12 items-center justify-center rounded-full border transition",r?"border-white/28 bg-white/12":"border-white/12 bg-white/6"),children:e.jsx(Rt,{className:"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/55",children:"Bin"}),e.jsx("div",{className:"mt-1 text-base font-medium text-white",children:s}),e.jsx("div",{className:"mt-1 text-sm leading-5 text-white/62",children:a})]})]})})}function uw({tasks:t,projects:s=[],activeRuns:a=[],goals:i,tags:r,selectedTaskId:n,onMove:l,onMoveProject:o,onSelectTask:d,onStartTask:m,onStopTask:h,onQuickReopenTask:u,onDeleteTask:x,onOpenProject:g,onOpenTask:p,onEditProject:f,onEditTask:b,onLinkProject:A,onLinkTask:C,onCreateIssueForProject:T,onCreateTaskForIssue:w,onCreateSubtaskForTask:S,onSplitTask:y,notesSummaryByEntity:N}){var Qe,st;const{t:P}=Ot(),v=c.useId(),H=`${v}:trash`,[j,R]=c.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(max-width: 1023px)").matches),Q=ld(od(cd,{activationConstraint:{distance:6}})),[X,Y]=c.useState(null),[z,K]=c.useState(null),[$,D]=c.useState(null),[J,q]=c.useState(null),[_,B]=c.useState(()=>typeof window>"u"?!1:window.localStorage.getItem("forge.kanban-skip-delete-confirmation")==="true"),[G,ae]=c.useState(!1),[ke,Ae]=c.useState({}),[ie,Ie]=c.useState({}),Ne={backlog:{title:P("common.executionBoard.laneBacklogTitle"),detail:P("common.executionBoard.laneBacklogDetail")},focus:{title:P("common.executionBoard.laneFocusTitle"),detail:P("common.executionBoard.laneFocusDetail")},in_progress:{title:P("common.executionBoard.laneProgressTitle"),detail:P("common.executionBoard.laneProgressDetail")},blocked:{title:P("common.executionBoard.laneBlockedTitle"),detail:P("common.executionBoard.laneBlockedDetail")},done:{title:P("common.executionBoard.laneDoneTitle"),detail:P("common.executionBoard.laneDoneDetail")}},M=c.useMemo(()=>t.map(F=>{const he=ke[F.id];return he?{...F,status:he}:F}),[ke,t]),E=c.useMemo(()=>s.map(F=>{const he=ie[F.id];return he?{...F,workflowStatus:he}:F}),[ie,s]),O=c.useMemo(()=>{const F=new Map;for(const he of a){if(he.status!=="active")continue;const we=F.get(he.taskId);(!we||he.isCurrent||he.updatedAt>we.updatedAt)&&F.set(he.taskId,he)}return F},[a]),xe=c.useMemo(()=>[...E.map(F=>({kind:"project",id:F.id,status:F.workflowStatus,project:F,goal:i.find(he=>he.id===F.goalId)})),...M.map(F=>({kind:"task",id:F.id,status:F.status,task:F,goal:i.find(he=>he.id===F.goalId),tags:F.tagIds.map(he=>r.find(we=>we.id===he)).filter(Boolean),activeRun:O.get(F.id)??null}))],[O,E,M,i,r]),V=X?xe.find(F=>F.id===X)??null:null,Se=c.useMemo(()=>{if(!z)return[];if(z.kind==="project"){const he=E.find(we=>we.id===z.entityId);return he?[{id:"open-project",label:"Open",description:"Jump to the project detail view.",icon:Es,onSelect:()=>g==null?void 0:g(he.id)},{id:"edit-project",label:"Edit",description:"Open the guided project editor.",icon:pi,onSelect:()=>f==null?void 0:f(he.id)},{id:"link-project",label:"Link",description:"Open the anchor step to relink the project to its goal.",icon:$s,onSelect:()=>A==null?void 0:A(he.id)},{id:"create-issue",label:"Create issue",description:"Break this project into a new vertical slice issue.",icon:qc,onSelect:()=>T==null?void 0:T(he.id)},...vs.filter(we=>we!==he.workflowStatus).map(we=>({id:`move-project-${we}`,label:`Move to ${we.replaceAll("_"," ")}`,description:"Update the project workflow lane without leaving the board.",onSelect:()=>void(o==null?void 0:o(he.id,we))}))]:[]}const F=M.find(he=>he.id===z.entityId);return F?i3({task:F,onOpenTask:p,onEditTask:b,onLinkTask:C,onCreateTaskForIssue:w,onCreateSubtaskForTask:S,onMove:l,onDeleteTask:x,deletePendingTaskId:J,onRequestDelete:L}):[]},[E,M,z,T,S,w,f,b,A,C,l,o,x,g,p,J,_]);function Ee(F){var we;if(F.length===0)return e.jsx("div",{className:"w-full max-w-full rounded-[18px] border border-dashed border-white/8 px-4 py-8 text-center text-sm text-white/35",children:P("common.executionBoard.emptyLane")});if(((we=F[0])==null?void 0:we.status)!=="in_progress")return F.map(Z=>Z.kind==="task"?e.jsx(Zd,{sortableId:`${v}:task:${Z.task.id}`,task:Z.task,goal:Z.goal,tags:Z.tags,activeRun:Z.activeRun,isSelected:n===Z.task.id,isMobile:j,onSelect:d,onStartTask:m,onStopTask:h,onQuickReopen:u,onStepTask:ge,onOpenMenu:ve,onSplitTask:y,notesSummaryByEntity:N},Z.task.id):e.jsx(ec,{sortableId:`${v}:project:${Z.project.id}`,project:Z.project,goal:Z.goal,isMobile:j,onStepProject:Te,onOpenMenu:Le},Z.project.id));const he=new Map;for(const Z of F){if(Z.kind!=="task"||!Z.activeRun){const et=he.get("ungrouped");et?et.items.push(Z):he.set("ungrouped",{title:"Active work",detail:"Tasks in progress without a tracked branch",items:[Z]});continue}const De=lw(Z.task,Z.activeRun),ee=[Z.activeRun.actor,De.git.repository??"",De.git.branch??""].join("::"),ze=he.get(ee);if(ze){ze.items.push(Z);continue}he.set(ee,{title:d3(Z.activeRun,De.git.branch),detail:c3(Z.activeRun,De.git.repository),items:[Z]})}return Array.from(he.entries()).map(([Z,De])=>Z==="ungrouped"?De.items.map(ee=>ee.kind==="task"?e.jsx(Zd,{sortableId:`${v}:task:${ee.task.id}`,task:ee.task,goal:ee.goal,tags:ee.tags,activeRun:ee.activeRun,isSelected:n===ee.task.id,isMobile:j,onSelect:d,onStartTask:m,onStopTask:h,onQuickReopen:u,onStepTask:ge,onOpenMenu:ve,onSplitTask:y,notesSummaryByEntity:N},ee.task.id):e.jsx(ec,{sortableId:`${v}:project:${ee.project.id}`,project:ee.project,goal:ee.goal,isMobile:j,onStepProject:Te,onOpenMenu:Le},ee.project.id)):e.jsx(u3,{title:De.title,detail:De.detail,children:De.items.map(ee=>ee.kind==="task"?e.jsx(Zd,{sortableId:`${v}:task:${ee.task.id}`,task:ee.task,goal:ee.goal,tags:ee.tags,activeRun:ee.activeRun,isSelected:n===ee.task.id,isMobile:j,onSelect:d,onStartTask:m,onStopTask:h,onQuickReopen:u,onStepTask:ge,onOpenMenu:ve,onSplitTask:y,notesSummaryByEntity:N},ee.task.id):e.jsx(ec,{sortableId:`${v}:project:${ee.project.id}`,project:ee.project,goal:ee.goal,isMobile:j,onStepProject:Te,onOpenMenu:Le},ee.project.id))},Z))}c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const F=window.matchMedia("(max-width: 1023px)"),he=we=>{R(we?we.matches:F.matches)};return he(),typeof F.addEventListener=="function"?(F.addEventListener("change",he),()=>F.removeEventListener("change",he)):(F.addListener(he),()=>F.removeListener(he))},[]),c.useEffect(()=>{if(!X){document.body.style.cursor="";return}return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=""}},[X]),c.useEffect(()=>{Ae(F=>{const he=new Set(t.map(De=>De.id));let we=!1;const Z={};for(const[De,ee]of Object.entries(F)){const ze=t.find(et=>et.id===De);if(!he.has(De)||!ze||ze.status===ee){we=!0;continue}Z[De]=ee}return we?Z:F})},[t]),c.useEffect(()=>{Ie(F=>{const he=new Set(s.map(De=>De.id));let we=!1;const Z={};for(const[De,ee]of Object.entries(F)){const ze=s.find(et=>et.id===De);if(!he.has(De)||!ze||ze.workflowStatus===ee){we=!0;continue}Z[De]=ee}return we?Z:F})},[s]);function Ce(F){var Z,De;const he=(Z=F.active.data.current)==null?void 0:Z.taskId,we=(De=F.active.data.current)==null?void 0:De.projectId;typeof he=="string"?Y(he):typeof we=="string"&&Y(we)}const qe=F=>{B(F),typeof window<"u"&&window.localStorage.setItem("forge.kanban-skip-delete-confirmation","true")},oe=async(F,he)=>{if(x){q(F.id);try{he&&qe(!0),await x(F.id),D(null),ae(!1),Ae(we=>{const Z={...we};return delete Z[F.id],Z})}finally{q(null)}}};function L(F){if(x){if(_){oe(F,!1);return}ae(!1),D(F)}}async function U(F){var be,je,pe,$e,Xe,Ue;const{active:he,over:we}=F;if(Y(null),!we||he.id===we.id)return;const Z=typeof((be=he.data.current)==null?void 0:be.taskId)=="string"?he.data.current.taskId:null,De=typeof((je=he.data.current)==null?void 0:je.projectId)=="string"?he.data.current.projectId:null,ee=(Z?xe.find(le=>le.kind==="task"&&le.id===Z):null)??(De?xe.find(le=>le.kind==="project"&&le.id===De):null);if(!ee)return;if(((pe=we.data.current)==null?void 0:pe.type)==="trash"){if(ee.kind!=="task"||!x)return;L(ee.task);return}const ze=typeof(($e=we.data.current)==null?void 0:$e.status)=="string"?we.data.current.status:null,et=typeof((Xe=we.data.current)==null?void 0:Xe.taskId)=="string"?we.data.current.taskId:null,Ve=typeof((Ue=we.data.current)==null?void 0:Ue.projectId)=="string"?we.data.current.projectId:null,re=(et?xe.find(le=>le.kind==="task"&&le.id===et):null)??(Ve?xe.find(le=>le.kind==="project"&&le.id===Ve):null),ne=ze??(re==null?void 0:re.status)??ee.status;if(!(ne===ee.status||!vs.includes(ne))){if(ee.kind==="task"){Ae(le=>({...le,[ee.task.id]:ne}));try{await l(ee.task.id,ne)}catch(le){throw Ae(Me=>{const He={...Me};return delete He[ee.task.id],He}),le}return}if(o){Ie(le=>({...le,[ee.project.id]:ne}));try{await o(ee.project.id,ne)}catch(le){throw Ie(Me=>{const He={...Me};return delete He[ee.project.id],He}),le}}}}async function ge(F,he){const we=M.find(ze=>ze.id===F);if(!we)return;const Z=vs.indexOf(we.status),De=he==="previous"?Z-1:Z+1,ee=vs[De]??null;if(!(!ee||ee===we.status)){Ae(ze=>({...ze,[we.id]:ee}));try{await l(we.id,ee)}catch(ze){throw Ae(et=>{const Ve={...et};return delete Ve[we.id],Ve}),ze}}}async function Te(F,he){const we=E.find(ze=>ze.id===F);if(!we||!o)return;const Z=vs.indexOf(we.workflowStatus),De=he==="previous"?Z-1:Z+1,ee=vs[De]??null;if(!(!ee||ee===we.workflowStatus)){Ie(ze=>({...ze,[we.id]:ee}));try{await o(we.id,ee)}catch(ze){throw Ie(et=>{const Ve={...et};return delete Ve[we.id],Ve}),ze}}}function ve(F,he){const we=F.currentTarget.getBoundingClientRect();K({kind:"task",entityId:he.id,position:{x:we.right-8,y:we.bottom+8}})}function Le(F,he){const we=F.currentTarget.getBoundingClientRect();K({kind:"project",entityId:he.id,position:{x:we.right-8,y:we.bottom+8}})}return e.jsxs(dd,{sensors:Q,collisionDetection:o3,onDragStart:Ce,onDragCancel:()=>Y(null),onDragEnd:F=>void U(F),children:[(V==null?void 0:V.kind)==="task"&&x?e.jsx(m3,{droppableId:H,title:P("common.executionBoard.deleteDropTitle"),detail:P("common.executionBoard.deleteDropDetail")}):null,e.jsx("div",{className:"w-full max-w-full min-w-0 pb-2",children:j?e.jsx("div",{className:"grid w-full max-w-full min-w-0 gap-2",children:vs.map(F=>{const he=xe.filter(we=>we.status===F);return e.jsx(Xn,{items:he.map(we=>`${v}:${we.kind}:${we.id}`),strategy:Yn,children:e.jsx(yp,{droppableId:`${v}:lane:${F}`,status:F,title:Ne[F].title,detail:Ne[F].detail,count:he.length,dragging:X!==null,children:Ee(he)})},F)})}):e.jsx("div",{className:"grid w-full min-w-0 gap-0.5 xl:grid-cols-[repeat(5,minmax(0,1fr))]",children:vs.map(F=>{const he=xe.filter(we=>we.status===F);return e.jsx(Xn,{items:he.map(we=>`${v}:${we.kind}:${we.id}`),strategy:Yn,children:e.jsx(yp,{droppableId:`${v}:lane:${F}`,status:F,title:Ne[F].title,detail:Ne[F].detail,count:he.length,dragging:X!==null,children:Ee(he)})},F)})})}),e.jsx(M0,{adjustScale:!1,dropAnimation:null,children:V?e.jsx("div",{className:"w-[20rem] max-w-[calc(100vw-2rem)]",children:V.kind==="task"?e.jsx(dw,{task:V.task,goal:V.goal,tags:V.tags,activeRun:V.activeRun,isSelected:n===V.task.id,isDragging:!0,isOverlay:!0,isMobile:j,onSelect:()=>{},onStartTask:m,onSplitTask:y,notesSummaryByEntity:N}):e.jsx(cw,{project:V.project,goal:V.goal,isDragging:!0,isOverlay:!0,isMobile:j})}):null}),e.jsx(vd,{open:z!==null,title:(z==null?void 0:z.kind)==="project"?((Qe=E.find(F=>F.id===z.entityId))==null?void 0:Qe.title)??"Project actions":((st=M.find(F=>F.id===(z==null?void 0:z.entityId)))==null?void 0:st.title)??"Work item actions",subtitle:(z==null?void 0:z.kind)==="project"?"Edit, relink, move, or break this project into issues.":"Edit, relink, move, or create the next child work item.",items:Se,position:(z==null?void 0:z.position)??null,onClose:()=>K(null)}),$?e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-[rgba(5,8,18,0.74)] p-4 backdrop-blur-xl",children:e.jsxs(ce,{className:"w-full max-w-md border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,36,0.96),rgba(9,13,22,0.98))] shadow-[0_32px_90px_rgba(5,8,18,0.58)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-1 flex size-11 shrink-0 items-center justify-center rounded-full bg-rose-500/14 text-rose-100",children:e.jsx(Rt,{className:"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-display text-[1.35rem] leading-tight text-white",children:P("common.executionBoard.deleteConfirmTitle")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/64",children:P("common.executionBoard.deleteConfirmDescription",{title:$.title})})]})]}),e.jsxs("label",{className:"mt-5 flex items-center gap-3 rounded-[18px] bg-white/[0.05] px-4 py-3 text-sm text-white/76",children:[e.jsx("input",{type:"checkbox",checked:G,onChange:F=>ae(F.target.checked),className:"size-4 rounded border-white/20 bg-transparent text-[var(--primary)]"}),e.jsx("span",{children:P("common.executionBoard.deleteConfirmCheckbox")})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-3",children:[e.jsx(W,{variant:"secondary",onClick:()=>{D(null),ae(!1)},children:P("common.executionBoard.deleteConfirmCancel")}),e.jsx(W,{className:"bg-[linear-gradient(135deg,rgba(251,113,133,0.3),rgba(190,24,93,0.26))] text-white shadow-[0_16px_36px_rgba(190,24,93,0.18)]",pending:J===$.id,pendingLabel:P("common.executionBoard.deletingTask"),onClick:()=>void oe($,G),children:P("common.executionBoard.deleteConfirmSubmit")})]})]})}):null]})}const Bl=[{to:"/projects",label:"Projects",icon:Cv},{to:"/kanban",label:"Board",icon:Sg},{to:"/projects/hierarchy",label:"Hierarchy",icon:Qr}];function tc(t,s){return s==="/projects"?t==="/projects"||/^\/projects\/[^/]+$/.test(t):t===s||t.startsWith(`${s}/`)}function Id({className:t}){const s=hi(),[a,i]=c.useState(!1),r=c.useMemo(()=>[...Bl].sort((n,l)=>l.to.length-n.to.length).find(n=>tc(s.pathname,n.to))??Bl[0],[s.pathname]);return c.useEffect(()=>{if(!a)return;const n=document.body.style.overflow,l=o=>{o.key==="Escape"&&i(!1)};return document.body.style.overflow="hidden",window.addEventListener("keydown",l),()=>{document.body.style.overflow=n,window.removeEventListener("keydown",l)}},[a]),e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:te("overflow-hidden bg-[linear-gradient(180deg,rgba(15,24,31,0.94),rgba(10,18,25,0.92))] p-2",t),children:[e.jsx("div",{className:"hidden items-center gap-3 lg:flex",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Bl.map(n=>e.jsxs(_a,{to:n.to,end:n.to==="/projects",className:({isActive:l})=>te("inline-flex items-center gap-2 whitespace-nowrap rounded-full px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",l||tc(s.pathname,n.to)?"bg-[rgba(125,211,252,0.16)] text-[#c7f0ff]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx(n.icon,{className:"size-3.5"}),e.jsx("span",{children:n.label})]},n.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsx("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center gap-3 rounded-[22px] border border-white/8 bg-[linear-gradient(180deg,rgba(19,28,42,0.96),rgba(11,17,30,0.94))] px-3.5 py-2.5 text-left shadow-[0_18px_38px_rgba(3,8,18,0.2)] transition hover:border-white/12",onClick:()=>i(!0),children:e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-2xl border border-[rgba(125,211,252,0.2)] bg-[rgba(125,211,252,0.12)]",children:e.jsx(r.icon,{className:"size-4 text-[#c7f0ff]"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[10px] uppercase tracking-[0.18em] text-white/40",children:"Project management"}),e.jsx("span",{className:"mt-0.5 block truncate text-sm font-medium text-white",children:r.label})]})]})})})]}),a&&typeof document<"u"?Qi.createPortal(e.jsxs("div",{className:"lg:hidden",children:[e.jsx("div",{className:"fixed inset-0 z-50 bg-[rgba(5,10,18,0.78)] backdrop-blur-xl"}),e.jsx("button",{type:"button","aria-label":"Close project management sections",className:"fixed inset-0 z-[51]",onClick:()=>i(!1)}),e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[52] flex items-end justify-center px-3 pt-3 sm:px-4 sm:pt-4",style:{paddingBottom:"calc(var(--forge-mobile-nav-clearance) - 0.25rem)"},children:e.jsxs("div",{className:"pointer-events-auto flex max-h-[min(34rem,calc(100dvh-var(--forge-mobile-nav-clearance)-1rem))] w-full max-w-xl min-h-0 flex-col overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.12),transparent_40%),linear-gradient(180deg,rgba(18,27,42,0.98),rgba(10,15,28,0.98))] shadow-[0_36px_110px_rgba(3,8,18,0.5)]",children:[e.jsx("div",{className:"shrink-0 border-b border-white/8 px-4 pb-2.5 pt-3 sm:px-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-white/38",children:"Forge PM"}),e.jsx("div",{className:"mt-1.5 flex min-w-0 flex-wrap items-center gap-2",children:e.jsx("div",{className:"truncate text-[1.05rem] font-semibold text-white",children:"Browse the hierarchy"})})]}),e.jsx("button",{type:"button","aria-label":"Close project management sections",className:"inline-flex size-10 shrink-0 items-center justify-center rounded-full border border-white/8 bg-white/[0.05] text-white/65 transition hover:border-white/12 hover:bg-white/[0.09] hover:text-white",onClick:()=>i(!1),children:e.jsx(Tt,{className:"size-4"})})]})}),e.jsx("div",{className:"min-h-0 overflow-y-auto p-3 overscroll-contain sm:p-4",children:e.jsx("div",{className:"grid gap-2",children:Bl.map(n=>{const l=tc(s.pathname,n.to);return e.jsx(_a,{to:n.to,end:n.to==="/projects",onClick:()=>i(!1),className:te("group flex items-center justify-between gap-3 rounded-[22px] border px-3.5 py-3 transition hover:-translate-y-[1px] hover:text-white",l?"border-[rgba(125,211,252,0.18)] bg-[rgba(125,211,252,0.12)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:border-white/12 hover:bg-white/[0.06]"),children:e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex size-10 items-center justify-center rounded-2xl border border-white/8 bg-white/[0.04]",children:e.jsx(n.icon,{className:"size-4"})}),e.jsx("span",{className:"text-sm font-medium",children:n.label})]})},n.to)})})})]})})]}),document.body):null]})}const Ma={goal:"goal:",project:"project:",tag:"tag:"},Ei={user:"user:",kind:"kind:"},h3=[{value:"project",label:"Project",searchText:"project initiative prd"},{value:"issue",label:"Issue",searchText:"issue vertical slice tracer bullet"},{value:"task",label:"Task",searchText:"task focused ai session"},{value:"subtask",label:"Subtask",searchText:"subtask child step"}];function sc(t){return t.trim().toLowerCase()}function p3(t){return t.reduce((s,a)=>(a.startsWith(Ma.goal)?s.goalIds.push(a.slice(Ma.goal.length)):a.startsWith(Ma.project)?s.projectIds.push(a.slice(Ma.project.length)):a.startsWith(Ma.tag)&&s.tagIds.push(a.slice(Ma.tag.length)),s),{goalIds:[],projectIds:[],tagIds:[]})}function x3(t){return t.reduce((s,a)=>{if(a.startsWith(Ei.user))s.userIds.push(a.slice(Ei.user.length));else if(a.startsWith(Ei.kind)){const i=a.slice(Ei.kind.length);(i==="human"||i==="bot")&&s.kinds.push(i)}return s},{userIds:[],kinds:[]})}function vp(t,s,a,i){t([]),s([]),a(""),i(["task","subtask"])}function g3(t){const s=t.trim();return s.length===0?{firstTitle:"Split task part 1",secondTitle:"Split task part 2"}:{firstTitle:`${s} - part 1`,secondTitle:`${s} - part 2`}}function f3(){var U,ge,Te,ve,Le,Qe,st;const{t}=Ot(),s=jt(),a=$t(),i=ct(),[r,n]=c.useState([]),[l,o]=c.useState([]),[d,m]=c.useState(""),[h,u]=c.useState(["task","subtask"]),[x,g]=c.useState(((ge=(U=s.snapshot.workItems)==null?void 0:U[0])==null?void 0:ge.id)??((Te=s.snapshot.tasks[0])==null?void 0:Te.id)??null),[p,f]=c.useState(null),[b,A]=c.useState(void 0),[C,T]=c.useState(null),[w,S]=c.useState(void 0),[y,N]=c.useState(null),[P,v]=c.useState(null),[H,j]=c.useState({firstTitle:"",secondTitle:"",remainingRatio:.5}),R=c.useMemo(()=>[...s.snapshot.goals.map(F=>({value:`${Ma.goal}${F.id}`,label:F.title,description:"Goal",searchText:`goal ${F.title} ${F.description??""}`,kind:"goal"})),...s.snapshot.dashboard.projects.map(F=>({value:`${Ma.project}${F.id}`,label:F.title,description:"Project",searchText:`project ${F.title} ${F.description??""} ${F.goalTitle??""}`,kind:"project"})),...s.snapshot.tags.map(F=>({value:`${Ma.tag}${F.id}`,label:F.name,description:"Tag",searchText:`tag ${F.name} ${F.color??""}`,kind:"tag"}))],[s.snapshot.dashboard.projects,s.snapshot.goals,s.snapshot.tags]),Q=c.useMemo(()=>{const F=s.snapshot.users.filter(we=>we.kind==="bot"),he=s.snapshot.users.filter(we=>we.kind==="human");return[{value:`${Ei.kind}bot`,label:"Bots",description:`${F.length} bot owner${F.length===1?"":"s"}`,searchText:`bots bot ai agents assistants ${F.map(we=>`${we.displayName} ${we.handle}`).join(" ")}`,badge:e.jsx(I,{className:"border-cyan-300/18 bg-cyan-400/12 text-cyan-50",children:"Bots"}),menuBadge:e.jsx(I,{className:"border-cyan-300/18 bg-cyan-400/12 text-cyan-50",children:"Bots"})},{value:`${Ei.kind}human`,label:"Humans",description:`${he.length} human owner${he.length===1?"":"s"}`,searchText:`humans human people operators ${he.map(we=>`${we.displayName} ${we.handle}`).join(" ")}`,badge:e.jsx(I,{className:"border-amber-300/18 bg-amber-400/12 text-amber-50",children:"Humans"}),menuBadge:e.jsx(I,{className:"border-amber-300/18 bg-amber-400/12 text-amber-50",children:"Humans"})},...s.snapshot.users.map(we=>({value:`${Ei.user}${we.id}`,label:we.displayName,description:`${we.kind}${we.handle?` · @${we.handle}`:""}`,searchText:`${we.displayName} ${we.handle} ${we.kind} ${we.description}`,badge:e.jsx(ot,{user:we,compact:!0}),menuBadge:e.jsx(ot,{user:we,compact:!0})}))]},[s.snapshot.users]),X=c.useMemo(()=>h3.map(F=>({value:F.value,label:F.label,searchText:F.searchText,badge:F.value==="subtask"?e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"}):e.jsx(We,{kind:F.kind??F.value,label:F.label,compact:!0,gradient:!1}),menuBadge:F.value==="subtask"?e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"}):e.jsx(We,{kind:F.kind??F.value,label:F.label,compact:!0,gradient:!1})})),[]),Y=c.useMemo(()=>p3(r),[r]),z=c.useMemo(()=>x3(l),[l]),K=c.useMemo(()=>sc(d),[d]),$=c.useMemo(()=>s.snapshot.workItems&&s.snapshot.workItems.length>0?s.snapshot.workItems:s.snapshot.tasks,[s.snapshot.tasks,s.snapshot.workItems]),D=c.useMemo(()=>new Map(s.snapshot.dashboard.projects.map(F=>[F.id,F])),[s.snapshot.dashboard.projects]),J=$.filter(F=>{var he;if(!h.includes(F.level))return!1;if(K.length>0){const we=F.projectId?D.get(F.projectId)??null:null;if(!sc([F.title,F.description,F.level,F.aiInstructions??"",F.executionMode??"",(we==null?void 0:we.title)??"",(we==null?void 0:we.goalTitle)??"",((he=F.user)==null?void 0:he.displayName)??"",...(F.assignees??[]).map(De=>De.displayName)].join(" ")).includes(K))return!1}if(Y.goalIds.length>0&&(F.goalId===null||!Y.goalIds.includes(F.goalId))||Y.projectIds.length>0&&(F.projectId===null||!Y.projectIds.includes(F.projectId))||Y.tagIds.length>0&&!Y.tagIds.every(we=>F.tagIds.includes(we)))return!1;if(z.userIds.length>0||z.kinds.length>0){const we=[...F.user?[F.user]:[],...F.assignees??[]],Z=we.some(ee=>z.userIds.includes(ee.id)),De=we.some(ee=>z.kinds.includes(ee.kind));if(!Z&&!De)return!1}return!0}),q=s.snapshot.dashboard.projects.filter(F=>{var he;if(!h.includes("project")||K.length>0&&!sc([F.title,F.description,F.goalTitle,F.productRequirementsDocument,((he=F.user)==null?void 0:he.displayName)??"",...(F.assignees??[]).map(Z=>Z.displayName)].join(" ")).includes(K)||Y.goalIds.length>0&&!Y.goalIds.includes(F.goalId)||Y.projectIds.length>0&&!Y.projectIds.includes(F.id))return!1;if(z.userIds.length>0||z.kinds.length>0){const we=[...F.user?[F.user]:[],...F.assignees??[]],Z=we.some(ee=>z.userIds.includes(ee.id)),De=we.some(ee=>z.kinds.includes(ee.kind));if(!Z&&!De)return!1}return!0}),_=J.length+q.length,B=q.length>0||J.length>0,G=d.trim().length>0||r.length>0||l.length>0||h.length!==2||!h.includes("task")||!h.includes("subtask"),ae=J.find(F=>F.id===x)??$.find(F=>F.id===x)??null,ke=p?s.snapshot.dashboard.projects.find(F=>F.id===p)??null:null,Ae=C?$.find(F=>F.id===C)??null:null,ie=J.filter(F=>F.status==="blocked").length,Ie=J.filter(F=>F.status==="done").length,Ne=J.filter(F=>F.status==="focus"||F.status==="in_progress").length,M=s.snapshot.activeTaskRuns.length,E=ys(s.selectedUserIds),O=P?$.find(F=>F.id===P)??null:null,xe=async()=>{await Promise.all([s.refresh(),Ut(i),i.invalidateQueries({queryKey:["project-board"]}),i.invalidateQueries({queryKey:["task-context"]})])},V=Re({mutationFn:({taskId:F,patch:he})=>s.patchTask(F,he),onSuccess:xe}),Se=Re({mutationFn:F=>rm(F),onSuccess:xe}),Ee=Re({mutationFn:lm,onSuccess:xe}),Ce=Re({mutationFn:({taskId:F,firstTitle:he,secondTitle:we,remainingRatio:Z})=>vk(F,{firstTitle:he,secondTitle:we,remainingRatio:Z}),onSuccess:async()=>{await xe(),v(null)}}),qe=(F,he)=>{f(F),A(he)},oe=(F,he)=>{T(F),N(null),S(he)},L=F=>{T(null),S(void 0),N(F)};return $.length===0&&s.snapshot.dashboard.projects.length===0?e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(nt,{title:"Kanban",description:"Move tasks across the board, start work quickly, and keep your next step visible.",badge:"0 visible tasks",actions:e.jsx(W,{size:"lg",onClick:()=>s.openStartWork(),children:"Start work"})}),e.jsx(Bt,{eyebrow:t("common.kanban.heroEyebrow"),title:t("common.kanban.emptyTitle"),description:t("common.kanban.emptyDescription"),action:e.jsx(Je,{to:"/goals",className:"inline-flex 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.kanban.emptyAction")})})]}):e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(Id,{}),e.jsx(nt,{title:"Kanban",description:"Move projects, issues, tasks, and subtasks through one shared execution board, then open the right layer when you need to inspect or edit it.",badge:`${_} visible work items`,actions:e.jsx(W,{size:"lg",onClick:()=>s.openStartWork(ae?{taskId:ae.id}:void 0),children:"Start work"})}),e.jsx(db,{children:e.jsx(ce,{className:"min-w-0 overflow-hidden",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Board"}),e.jsx("div",{className:"mt-2 text-base text-white",children:"See projects, issues, tasks, and subtasks in the same workflow lanes, with one card language and one shared board state."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Ne," ready or active"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[ie," blocked"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Ie," done"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[M," live timer",M===1?"":"s"]}),e.jsxs(I,{className:"bg-[var(--primary)]/12 text-[var(--primary)]",children:[Math.round(((ve=s.snapshot.lifeForce)==null?void 0:ve.spentTodayAp)??0)," /"," ",Math.round(((Le=s.snapshot.lifeForce)==null?void 0:Le.dailyBudgetAp)??0)," AP"]})]})]})})}),e.jsx(cb,{children:e.jsxs(ce,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"type-label text-white/40",children:"Filters"}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Use compact entity chips for goals, projects, tags, and owner scopes instead of the wide pill rows."})]}),G?e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>vp(n,o,m,u),children:"Reset"}):null]}),e.jsxs("div",{className:"mt-4 grid gap-3 xl:grid-cols-[minmax(0,1fr)_minmax(18rem,24rem)]",children:[e.jsx("div",{className:"rounded-[22px] border border-white/10 bg-black/20 px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/36"}),e.jsx("input",{value:d,onChange:F=>m(F.target.value),placeholder:"Search projects, issues, tasks, subtasks, PRDs, owners, and assignees",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"}),d.trim().length>0?e.jsx("button",{type:"button",className:"rounded-full text-white/46 transition hover:text-white",onClick:()=>m(""),"aria-label":"Clear board search",children:e.jsx(Tt,{className:"size-4"})}):null]})}),e.jsx(mt,{options:X,selectedValues:h,onChange:F=>u(F),placeholder:"Work item types",emptyMessage:"No work-item levels.",variant:"action-bar"})]}),e.jsxs("div",{className:"mt-3 grid gap-3 xl:grid-cols-[minmax(0,1.55fr)_minmax(18rem,1fr)]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Entity filters"}),e.jsx(mt,{options:R,selectedValues:r,onChange:n,placeholder:"Filter by goal, project, or tag",emptyMessage:"No matching goals, projects, or tags."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Owner filters"}),e.jsx(mt,{options:Q,selectedValues:l,onChange:o,placeholder:"Type Bo for bots, Hu for humans, or a teammate name",emptyMessage:"No matching owners."})]})]})]})}),B?e.jsx(ub,{children:e.jsx(uw,{tasks:J,projects:q,activeRuns:s.snapshot.activeTaskRuns,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:x,onMove:async(F,he)=>{await s.patchTaskStatus(F,he)},onMoveProject:async(F,he)=>{await s.patchProject(F,{workflowStatus:he})},onQuickReopenTask:async F=>{await nm(F),await xe()},onDeleteTask:async F=>{await Se.mutateAsync(F),g(he=>{var we;return he!==F?he:((we=J.find(Z=>Z.id!==F))==null?void 0:we.id)??null}),T(he=>he===F?null:he)},onStartTask:async F=>{await s.startTaskNow(F),g(F),await i.invalidateQueries({queryKey:["task-context",F]})},onStopTask:async F=>{await s.stopTaskRun(F),g(F.taskId),await i.invalidateQueries({queryKey:["task-context",F.taskId]})},onSelectTask:F=>{g(F)},onOpenProject:F=>{a(`/projects/${F}`)},onOpenTask:F=>{a(`/tasks/${F}`)},onEditProject:F=>{qe(F)},onEditTask:F=>{oe(F)},onLinkProject:F=>{qe(F,"anchor")},onLinkTask:F=>{oe(F,"anchor")},onCreateIssueForProject:F=>{const he=s.snapshot.dashboard.projects.find(we=>we.id===F)??null;he&&L({initialLevel:"issue",initialGoalId:he.goalId,initialProjectId:he.id})},onCreateTaskForIssue:F=>{const he=$.find(we=>we.id===F)??null;he&&L({initialLevel:"task",initialGoalId:he.goalId,initialProjectId:he.projectId,initialParentWorkItemId:he.id})},onCreateSubtaskForTask:F=>{const he=$.find(we=>we.id===F)??null;he&&L({initialLevel:"subtask",initialGoalId:he.goalId,initialProjectId:he.projectId,initialParentWorkItemId:he.id})},onSplitTask:F=>{const he=$.find(Z=>Z.id===F)??null;if(!he)return;const we=g3(he.title);v(F),j({firstTitle:we.firstTitle,secondTitle:we.secondTitle,remainingRatio:.5})}})}):e.jsx(Bt,{eyebrow:t("common.kanban.heroEyebrow"),title:t("common.kanban.noTasksMatch"),description:"No tasks match the current filters. Reset the filters to bring the full board back.",action:e.jsx(W,{variant:"secondary",onClick:()=>vp(n,o,m,u),children:"Reset"})}),e.jsx(fd,{open:ke!==null,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:ke,defaultUserId:(ke==null?void 0:ke.userId)??E,initialStepId:b,onOpenChange:F=>{F||(f(null),A(void 0))},onSubmit:async(F,he)=>{he&&(await s.patchProject(he,F),f(null),A(void 0))}}),e.jsx(bd,{open:Ae!==null||y!==null,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,workItems:$,tags:s.snapshot.tags,users:s.snapshot.users,editingTask:Ae,initialGoalId:y==null?void 0:y.initialGoalId,initialProjectId:y==null?void 0:y.initialProjectId,initialParentWorkItemId:y==null?void 0:y.initialParentWorkItemId,initialLevel:y==null?void 0:y.initialLevel,initialStepId:w,defaultUserId:(Ae==null?void 0:Ae.userId)??E,onRefreshEntities:s.refresh,currentCreditedSeconds:Ae==null?void 0:Ae.time.totalCreditedSeconds,onOpenChange:F=>{F||(T(null),N(null),S(void 0))},onAdjustTrackedTime:Ae?async F=>{await Ee.mutateAsync(F)}:void 0,onSubmit:async(F,he)=>{he?await V.mutateAsync({taskId:he,patch:F}):await s.createTask(F),T(null),N(null),S(void 0)}}),O?e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-[rgba(5,8,18,0.74)] p-4 backdrop-blur-xl",children:e.jsxs(ce,{className:"w-full max-w-xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,36,0.96),rgba(9,13,22,0.98))] shadow-[0_32px_90px_rgba(5,8,18,0.58)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-1 flex size-11 shrink-0 items-center justify-center rounded-full bg-amber-400/14 text-amber-100",children:e.jsx(ad,{className:"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-display text-[1.35rem] leading-tight text-white",children:"Split this task"}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/64",children:[O.title," has grown beyond its expected shape. Split the remaining work into two child tasks while keeping the original history intact."]})]})]}),e.jsxs("div",{className:"mt-5 grid gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"First task name"}),e.jsx(ye,{value:H.firstTitle,onChange:F=>j(he=>({...he,firstTitle:F.target.value}))})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Second task name"}),e.jsx(ye,{value:H.secondTitle,onChange:F=>j(he=>({...he,secondTitle:F.target.value}))})]}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm text-white/70",children:[e.jsx("span",{children:"Remaining work ratio"}),e.jsxs("span",{children:[Math.round(H.remainingRatio*100),"% / ",100-Math.round(H.remainingRatio*100),"%"]})]}),e.jsx("input",{type:"range",min:25,max:75,step:5,value:Math.round(H.remainingRatio*100),onChange:F=>j(he=>({...he,remainingRatio:Number(F.target.value)/100}))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Math.round((((Qe=O.actionPointSummary)==null?void 0:Qe.totalCostAp)??0)*H.remainingRatio)," ","AP first child"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Math.round((((st=O.actionPointSummary)==null?void 0:st.totalCostAp)??0)*(1-H.remainingRatio))," ","AP second child"]})]})]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-3",children:[e.jsx(W,{variant:"secondary",onClick:()=>{v(null)},children:"Cancel"}),e.jsx(W,{pending:Ce.isPending,disabled:H.firstTitle.trim().length===0||H.secondTitle.trim().length===0,onClick:()=>{Ce.mutateAsync({taskId:O.id,firstTitle:H.firstTitle.trim(),secondTitle:H.secondTitle.trim(),remainingRatio:H.remainingRatio})},children:"Create split tasks"})]})]})}):null]})}const b3=Math.PI*(3-Math.sqrt(5)),w3=.48;function il(t,s,a){return Math.min(a,Math.max(s,t))}function y3({positions:t,point:s}){const a=[...t.values()];if(a.length===0)return{x:.5,y:.5};let i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const p of a)i=Math.min(i,p.x),r=Math.max(r,p.x),n=Math.min(n,p.y),l=Math.max(l,p.y);const o=Math.max(r-i,0),d=Math.max(l-n,0),m=Math.max(o,d,1),h=(1-o/m)/2,u=(1-d/m)/2,x=o||1,g=d||1;return{x:il((s.x-i)/x*(o/m)+h,0,1),y:il((s.y-n)/g*(d/m)+u,0,1)}}function v3(t){let s=2166136261;for(let a=0;a<t.length;a+=1)s^=t.charCodeAt(a),s=Math.imul(s,16777619);return s>>>0}function j3({nodes:t,cache:s}){const a=new Map,i=[...t].sort((o,d)=>d.importance-o.importance||o.title.localeCompare(d.title)||o.id.localeCompare(d.id));let r=0,n=0,l=0;if(i.forEach((o,d)=>{const m=s.get(o.id);if(m){a.set(o.id,m),r+=m.x,n+=m.y,l+=1;return}const h=(v3(o.id)%1e3/1e3-.5)*.22,u=d*b3+h,x=w3*Math.sqrt(d+1),g={x:Math.cos(u)*x,y:Math.sin(u)*x};a.set(o.id,g),r+=g.x,n+=g.y,l+=1}),l>0){const o=r/l,d=n/l;a.forEach((m,h)=>{a.set(h,{x:m.x-o,y:m.y-d})})}return a}function N3(t,s){if(t.startsWith("rgb(")&&t.endsWith(")"))return t.replace("rgb(","rgba(").replace(")",`, ${s})`);if(t.startsWith("#")){const a=t.slice(1),i=a.length===3?a.split("").map(o=>`${o}${o}`).join(""):a,r=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),l=parseInt(i.slice(4,6),16);return`rgba(${r}, ${n}, ${l}, ${s})`}return t}function lr(t,s){return`rgba(${t==="structural"?"125, 211, 252":t==="contextual"?"45, 212, 191":t==="taxonomy"?"192, 132, 252":t==="workspace"?"251, 191, 36":"148, 163, 184"}, ${s})`}function jp(t,s){return!s.focusNodeId||t===s.focusNodeId?0:s.detailNodeIds.has(t)?1:s.relatedNodeIds.has(t)?2:3}function k3({nodeId:t,attributes:s,node:a,focusNodeId:i,relatedNodeIds:r,detailNodeIds:n,hoveredNodeId:l,draggedNodeId:o}){const d=i===t,m=r.has(t),h=n.has(t),u=l===t,x=o===t,g=!i||m,p=s.color;return{...s,label:d||u||x||h?a.title:"",forceLabel:d||u||x||h,highlighted:d||u||x||h,color:g?p:N3(p,.34),size:x?s.size*2:d?s.size*1.8:u?s.size*1.35:h?s.size*1.16:m?s.size*1.06:s.size,zIndex:x?4:d?3:h||u?2:1}}function S3({attributes:t,edge:s,focusNodeId:a,detailNodeIds:i,relatedNodeIds:r,hoveredNodeId:n}){const l=!!a&&(s.source===a||s.target===a),o=!!n&&(s.source===n||s.target===n),d={focusNodeId:a,detailNodeIds:i,relatedNodeIds:r},m=a?Math.max(jp(s.source,d),jp(s.target,d)):0,h=l?lr(s.family,.24):o?lr(s.family,.14):a?m<=1?lr(s.family,.09):m===2?lr(s.family,.05):lr(s.family,.016):lr(s.family,.055);return{...t,color:h,size:l?t.size*1.18:o?t.size*1.08:t.size,zIndex:l?2:o?1:0}}function Np(t,s){const a=new Set,i=new Set;for(const r of t)r.source===s?a.add(r.target):r.target===s&&a.add(r.source);for(const r of t)r.source!==s&&a.has(r.source)&&i.add(r.target),r.target!==s&&a.has(r.target)&&i.add(r.source);return i.delete(s),a.forEach(r=>i.delete(r)),{firstRing:[...a].sort(),secondRing:[...i].sort()}}function kp(t,s,a){if(!a)return t.map(()=>-1);const i=new Set(t);if(!i.has(a))return t.map(()=>-1);const r=new Map;for(const o of s){if(!i.has(o.source)||!i.has(o.target))continue;const d=r.get(o.source)??new Set;d.add(o.target),r.set(o.source,d);const m=r.get(o.target)??new Set;m.add(o.source),r.set(o.target,m)}const n=new Map([[a,0]]);let l=[a];for(;l.length>0;){const o=[];for(const d of l){const m=n.get(d);for(const h of r.get(d)??[])n.has(h)||(n.set(h,m+1),o.push(h))}l=o}return t.map(o=>n.get(o)??-1)}function I3({positions:t,focusNodeId:s,firstRingNodeIds:a,secondRingNodeIds:i,currentRatio:r}){const n=t.get(s);if(!n)return null;const l=[s,...a,...i].filter((T,w,S)=>S.indexOf(T)===w),o=l.map(T=>t.get(T)).filter(Boolean);if(o.length===0)return null;let d=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,h=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY,x=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,p=Number.POSITIVE_INFINITY,f=Number.NEGATIVE_INFINITY;for(const T of t.values())x=Math.min(x,T.x),g=Math.max(g,T.x),p=Math.min(p,T.y),f=Math.max(f,T.y);for(const T of o)d=Math.min(d,T.x),m=Math.max(m,T.x),h=Math.min(h,T.y),u=Math.max(u,T.y);const b=Math.max(m-d,u-h,.75),A=Math.max(g-x,f-p,b),C=o.length<=1?il(Math.max(r,.48),.38,.6):il(b/A*3.2,.42,Math.max(r,1.12));return{x:n.x,y:n.y,ratio:C,nodeIds:l}}function mw({positions:t,currentRatio:s=1}){const a=[...t.values()];if(a.length===0)return{x:0,y:0,ratio:s};let i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const m of a)i=Math.min(i,m.x),r=Math.max(r,m.x),n=Math.min(n,m.y),l=Math.max(l,m.y);const o=Math.max(r-i,l-n,1),d=il(o/6.4,.72,2.8);return{x:0,y:0,ratio:Math.max(s,d)}}function Sp(t){const s=iu.indexOf(t);return s>=0?s:iu.length-1}function C3(t){const s=Tr.find(a=>a.kinds.some(i=>i===t))??Tr[Tr.length-1];return{laneId:s.id,laneLabel:s.label,laneIndex:Tr.findIndex(a=>a.id===s.id)}}function Ul(){return{structural:0,contextual:0,taxonomy:0,workspace:0}}function T3(t){const s=new Map;for(const a of t){const i=s.get(a.source)??new Set;i.add(a.target),s.set(a.source,i);const r=s.get(a.target)??new Set;r.add(a.source),s.set(a.target,r)}return s}function P3(t,s){return s.strength-t.strength||t.relationKind.localeCompare(s.relationKind)||t.label.localeCompare(s.label)||t.id.localeCompare(s.id)}function hw(t){const s=new Map;for(const a of t){const i=`${a.source}→${a.target}`,r=s.get(i)??[];r.push(a),s.set(i,r)}return Array.from(s.entries()).map(([a,i])=>{const r=[...i].sort(P3),n=r[0],l=r.length,o=Math.max(...r.map(d=>d.strength))*Math.min(1.45,1+(l-1)*.12);return{id:`${a}#${n.id}`,source:n.source,target:n.target,relationKind:n.relationKind,family:n.family,label:l>1?`${n.label} +${l-1}`:n.label,strength:o,directional:n.directional,structural:n.structural,parallelCount:l,data:r}}).sort((a,i)=>a.source.localeCompare(i.source)||a.target.localeCompare(i.target)||a.id.localeCompare(i.id))}function A3(t,s){const a=hw(s),i=[...t].sort((n,l)=>{var o;return n.id.localeCompare(l.id)||((o=n.updatedAt)==null?void 0:o.localeCompare(l.updatedAt??""))||0}).map(n=>`${n.id}:${n.title}:${n.size}:${n.importance}:${n.updatedAt??""}`).join("|"),r=a.map(n=>`${n.source}:${n.target}:${n.parallelCount}:${n.label}:${n.strength.toFixed(3)}`).join("|");return`${t.length}/${a.length}/${i}::${r}`}function pw(t,s){const a=[...t].sort((o,d)=>{const m=Sp(o.entityKind)-Sp(d.entityKind);return m!==0?m:d.importance-o.importance||o.title.localeCompare(d.title)}),i=new Map,r=a.map(o=>{const{laneId:d,laneIndex:m,laneLabel:h}=C3(o.entityKind),u=i.get(m)??0;return i.set(m,u+1),{...o,layer:m,laneId:d,laneLabel:h,row:u}}),n=new Map(r.map(o=>[o.id,o])),l=s.map(o=>{const d=n.get(o.source),m=n.get(o.target),h=(d==null?void 0:d.layer)??0,u=(m==null?void 0:m.layer)??0;return{...o,secondary:u<=h||o.family!=="structural"&&o.family!=="taxonomy"}});return{nodes:r,edges:l}}function Ip(t,s,a){const i=new Map(t.map(g=>[g.id,g])),r=a?i.get(a)??null:null;if(!r)return{generatedAt:new Date().toISOString(),focusNode:null,firstRingNodes:[],neighborhoodEdges:[],familyGroups:[],relationCounts:Ul(),secondRingCounts:Ul()};const n=s.filter(g=>g.source===r.id||g.target===r.id),l=Array.from(new Set(n.flatMap(g=>g.source===r.id?[g.target]:[g.source]))),o=l.map(g=>i.get(g)??null).filter(g=>!!g),d=new Map,m=Ul(),h=Ul(),u=T3(s);for(const g of l){const p=u.get(g)??new Set;for(const f of p){if(f===r.id||l.includes(f))continue;const b=s.filter(A=>A.source===g&&A.target===f||A.target===g&&A.source===f);for(const A of b)h[A.family]+=1}}for(const g of n){const p=g.source===r.id?g.target:g.source,f=i.get(p);if(!f)continue;m[g.family]+=1;const b=d.get(g.relationKind);if(b){b.items.some(A=>A.id===f.id)||b.items.push(f);continue}d.set(g.relationKind,{relationKind:g.relationKind,family:g.family,label:LS[g.relationKind],items:[f]})}const x=new Map;for(const g of d.values()){const p=x.get(g.family);if(p){p.relations.push({...g,items:[...g.items].sort((f,b)=>f.title.localeCompare(b.title))}),p.itemCount+=g.items.length,p.relationCount+=1;continue}x.set(g.family,{family:g.family,label:DS[g.family],relationCount:1,itemCount:g.items.length,relations:[{...g,items:[...g.items].sort((f,b)=>f.title.localeCompare(b.title))}]})}return{generatedAt:new Date().toISOString(),focusNode:r,firstRingNodes:o.sort((g,p)=>g.title.localeCompare(p.title)),neighborhoodEdges:n,familyGroups:[...x.values()].map(g=>({...g,relations:g.relations.sort((p,f)=>p.label.localeCompare(f.label))})).sort((g,p)=>g.label.localeCompare(p.label)),relationCounts:m,secondRingCounts:h}}function M3(t,s){return FS(t,s)}function E3(t,s){if(!t)return new Set;const a=new Set([t]);for(const i of s)i.source===t?a.add(i.target):i.target===t&&a.add(i.source);return a}let gn=null;function L3(){if(typeof window>"u")return!1;if(window.__FORGE_ENABLE_GRAPH_DIAGNOSTICS__)return!0;try{return new URLSearchParams(window.location.search).get("graphDiagnostics")==="1"}catch{return!1}}function Cp(){typeof window>"u"||(delete window.__FORGE_KNOWLEDGE_GRAPH_DIAGNOSTICS__,delete window.__FORGE_KNOWLEDGE_GRAPH_TEST_API__)}function D3(){if(gn!==null)return gn;if(typeof document>"u")return gn=!1,!1;const t=document.createElement("canvas");return gn=!!(t.getContext("webgl2")||t.getContext("webgl")||t.getContext("experimental-webgl")),gn}function F3(t){if(!t||typeof window>"u")return"#c0c1ff";const s=getComputedStyle(document.documentElement).getPropertyValue(t).trim();return s?`rgb(${s})`:"#c0c1ff"}function _3(t,s){if(t.startsWith("rgb(")&&t.endsWith(")"))return t.replace("rgb(","rgba(").replace(")",`, ${s})`);if(t.startsWith("#")){const a=t.slice(1),i=a.length===3?a.split("").map(o=>`${o}${o}`).join(""):a,r=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),l=parseInt(i.slice(4,6),16);return`rgba(${r}, ${n}, ${l}, ${s})`}return t}function fn(t,s){t.forEachNode(a=>{const i=t.getNodeAttributes(a);Number.isFinite(i.x)&&Number.isFinite(i.y)&&s.set(a,{x:i.x,y:i.y})})}function R3(t,s,a){const i=new Pv,r=[...t].sort((l,o)=>o.importance-l.importance||l.title.localeCompare(o.title)||l.id.localeCompare(o.id)),n=j3({nodes:r,cache:a});return r.forEach(l=>{const o=n.get(l.id);i.addNode(l.id,{x:(o==null?void 0:o.x)??0,y:(o==null?void 0:o.y)??0,size:Math.max(2.5,l.size/14),color:F3(l.accentToken),label:l.title,hidden:!1,forceLabel:!1,highlighted:!1,zIndex:0,data:l})}),s.forEach(l=>{!i.hasNode(l.source)||!i.hasNode(l.target)||i.addEdgeWithKey(l.id,l.source,l.target,{size:Math.max(.8,l.strength*1.6),color:l.family==="structural"?"rgba(125, 211, 252, 0.055)":l.family==="contextual"?"rgba(45, 212, 191, 0.055)":l.family==="taxonomy"?"rgba(192, 132, 252, 0.055)":l.family==="workspace"?"rgba(251, 191, 36, 0.055)":"rgba(148, 163, 184, 0.055)",label:l.label,hidden:!1,forceLabel:!1,zIndex:0,data:l})}),i}function Tp(t){if(t.order===0)return;let s=0,a=0,i=0;if(t.forEachNode(l=>{const o=t.getNodeAttributes(l);s+=o.x,a+=o.y,i+=1}),i===0)return;const r=s/i,n=a/i;Math.abs(r)<1e-4&&Math.abs(n)<1e-4||t.updateEachNodeAttributes((l,o)=>({...o,x:o.x-r,y:o.y-n}),{attributes:["x","y"]})}function Pp(t){const s=new Map;return t.forEachNode(a=>{const i=t.getNodeAttributes(a);s.set(a,{x:i.x,y:i.y})}),s}function or(t,s){return{nodes:t.nodes().map(a=>({id:a,...t.getNodeAttributes(a)})),edges:s}}function $3(t){if(t.nodes.length===0)return{minX:-1,maxX:1,minY:-1,maxY:1};let s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const n of t.nodes)s=Math.min(s,n.x),a=Math.max(a,n.x),i=Math.min(i,n.y),r=Math.max(r,n.y);return{minX:s,maxX:a,minY:i,maxY:r}}function O3(t){const s=mw({positions:new Map(t.nodes.map(a=>[a.id,{x:a.x,y:a.y}])),currentRatio:1});return{x:s.x,y:s.y,angle:0,ratio:s.ratio}}function z3({x:t,y:s}){const a=Array.from({length:t.length},(r,n)=>({x:t[n]??0,y:s[n]??0})),i=IS(a);return i.changed?{changed:!0,offsetX:i.offset.x,offsetY:i.offset.y,x:new Float32Array(i.positions.map(r=>r.x)),y:new Float32Array(i.positions.map(r=>r.y))}:{changed:!1,offsetX:0,offsetY:0,x:new Float32Array(t),y:new Float32Array(s)}}function xw({node:t,snapshot:s,camera:a,width:i,height:r}){const n=$3(s),l=Math.max(1,n.maxX-n.minX),o=Math.max(1,n.maxY-n.minY),d=28,h=Math.min(Math.max(1,i-d*2)/l,Math.max(1,r-d*2)/o)/Math.max(a.ratio,.08);return{x:i/2+(t.x-a.x)*h,y:r/2-(t.y-a.y)*h,size:Math.max(4,t.size*h*.12)}}function K3({datasetSignature:t,focusNodeId:s,primaryFocusedNodeId:a,draggedNodeId:i,graph:r,layoutGeneration:n,sigma:l,startupPhase:o,startupInvariantSatisfied:d,simulationPhase:m,focusSources:h,focusPressure:u,centroid:x,cameraTarget:g,latestSnapshotAt:p,latestSnapshotNodeCount:f}){const b=[],A={},C={};let T=null;r.forEachNode(N=>{b.push(N);const P=l.getNodeDisplayData(N),v=r.getNodeAttributes(N),H=l.graphToViewport({x:v.x,y:v.y});A[N]={x:H.x,y:H.y,size:(P==null?void 0:P.size)??v.size},C[N]=Number((u[b.length-1]??0).toFixed(4)),N===a&&(T={x:v.x,y:v.y})});const w=hm(b.map(N=>{const P=r.getNodeAttributes(N);return{x:P.x,y:P.y}})),S=l.getCamera().getState(),y=pm({centroid:x,boundsCenter:w,camera:S});window.__FORGE_KNOWLEDGE_GRAPH_DIAGNOSTICS__={datasetSignature:t,visibleNodeIds:b,visibleNodeCount:b.length,focusedNodeId:s,primaryFocusedNodeId:a,draggedNodeId:i,layoutGeneration:n,rendererMode:"sigma",startupPhase:o,startupInvariantSatisfied:d,simulationPhase:m,focusSources:h,focusPressureByNodeId:C,graphCentroid:x,boundsCenter:w,focusedNodePosition:T,cameraTarget:g,cameraFollowError:g?{x:Number((S.x-g.x).toFixed(4)),y:Number((S.y-g.y).toFixed(4)),ratio:Number((S.ratio-g.ratio).toFixed(4))}:null,camera:S,nodeScreenPositions:A,centroidDistanceFromOrigin:y.centroidDistanceFromOrigin,boundsCenterDistanceFromOrigin:y.boundsCenterDistanceFromOrigin,cameraDistanceFromOrigin:y.cameraDistanceFromOrigin,cameraToCentroidDistance:y.cameraToCentroidDistance,latestSnapshotAt:p,latestSnapshotNodeCount:f}}function Ap({datasetSignature:t,focusNodeId:s,primaryFocusedNodeId:a,draggedNodeId:i,layoutGeneration:r,camera:n,snapshot:l,width:o,height:d,startupPhase:m,startupInvariantSatisfied:h,simulationPhase:u,focusSources:x,focusPressure:g,centroid:p,cameraTarget:f,latestSnapshotAt:b,latestSnapshotNodeCount:A}){const C=l.nodes.map(P=>P.id),T={},w={};let S=null;l.nodes.forEach((P,v)=>{T[P.id]=xw({node:P,snapshot:l,camera:n,width:o,height:d}),w[P.id]=Number((g[v]??0).toFixed(4)),P.id===a&&(S={x:P.x,y:P.y})});const y=hm(l.nodes.map(P=>({x:P.x,y:P.y}))),N=pm({centroid:p,boundsCenter:y,camera:n});window.__FORGE_KNOWLEDGE_GRAPH_DIAGNOSTICS__={datasetSignature:t,visibleNodeIds:C,visibleNodeCount:C.length,focusedNodeId:s,primaryFocusedNodeId:a,draggedNodeId:i,layoutGeneration:r,rendererMode:"fallback",startupPhase:m,startupInvariantSatisfied:h,simulationPhase:u,focusSources:x,focusPressureByNodeId:w,graphCentroid:p,boundsCenter:y,focusedNodePosition:S,cameraTarget:f,cameraFollowError:f?{x:Number((n.x-f.x).toFixed(4)),y:Number((n.y-f.y).toFixed(4)),ratio:Number((n.ratio-f.ratio).toFixed(4))}:null,camera:n,nodeScreenPositions:T,centroidDistanceFromOrigin:N.centroidDistanceFromOrigin,boundsCenterDistanceFromOrigin:N.boundsCenterDistanceFromOrigin,cameraDistanceFromOrigin:N.cameraDistanceFromOrigin,cameraToCentroidDistance:N.cameraToCentroidDistance,latestSnapshotAt:b,latestSnapshotNodeCount:A}}function Mp(t,s){if(!t)return!1;const a=t.clientWidth,i=t.clientHeight,r=t.getBoundingClientRect();return t.isConnected&&s.width>0&&s.height>0&&a>0&&i>0&&r.width>0&&r.height>0&&t.getClientRects().length>0}function q3({sigma:t,graph:s,viewportX:a,viewportY:i}){let r=null,n=Number.POSITIVE_INFINITY;return s.forEachNode(l=>{const o=s.getNodeAttributes(l),d=t.getNodeDisplayData(l);if(!d||o.hidden)return;const m=t.graphToViewport({x:o.x,y:o.y}),h=m.x-a,u=m.y-i,x=Math.hypot(h,u),g=Math.max(d.size*1.8,18);x<=g&&x<n&&(r=l,n=x)}),r}function dr(t,s){return`rgba(${t.family==="structural"?"125, 211, 252":t.family==="contextual"?"45, 212, 191":t.family==="taxonomy"?"192, 132, 252":t.family==="workspace"?"251, 191, 36":"148, 163, 184"}, ${s})`}const B3=c.forwardRef(function({nodes:s,edges:a,focusNodeId:i,physicsSettings:r,onSelectNode:n},l){jl(),ri(ne=>ne.knowledgeGraphDiagnostics.panelOpen);const o=c.useRef(null),d=c.useRef(null),m=c.useRef(null),h=c.useRef(null),u=c.useRef(new Map),x=c.useRef(new Map),g=c.useRef(new Map),p=c.useRef(n),f=c.useRef(i),b=c.useRef(null),A=c.useRef(0),C=c.useRef(null),T=c.useRef(0),w=c.useRef(!0),S=c.useRef(null),y=c.useRef(0),N=c.useRef("global"),P=c.useRef(null),v=c.useRef([]),H=c.useRef(new Float32Array(0)),j=c.useRef({x:0,y:0}),R=c.useRef("boot"),Q=c.useRef(!1),X=c.useRef(!1),Y=c.useRef(!1),z=c.useRef(null),K=c.useRef(null),$=c.useRef(0),D=c.useRef(0);c.useRef(0),c.useRef(qf("/knowledge-graph"));const[J,q]=c.useState(null),[_,B]=c.useState(null),[G,ae]=c.useState(null),[ke,Ae]=c.useState({x:0,y:0,angle:0,ratio:1}),[ie,Ie]=c.useState(null),[Ne,M]=c.useState({width:0,height:0}),O=zf(),xe=(ne=h.current)=>mw({positions:ne?Pp(ne):new Map,currentRatio:1}).ratio,V=(ne=h.current)=>({x:.5,y:.5,angle:0,ratio:xe(ne)}),Se=(ne=h.current)=>({x:0,y:0,angle:0,ratio:xe(ne)}),Ee=()=>d.current?"sigma":"fallback",Ce=c.useMemo(()=>hw(a),[a]),qe=c.useMemo(()=>A3(s,a),[a,s]),oe=c.useMemo(()=>i?Np(Ce,i):null,[i,Ce]),L=c.useMemo(()=>i?new Set([i,...(oe==null?void 0:oe.firstRing)??[]]):new Set,[i,oe]),U=c.useMemo(()=>i?new Set([i,...(oe==null?void 0:oe.firstRing)??[],...(oe==null?void 0:oe.secondRing)??[]]):new Set,[i,oe]),ge=()=>Mp(o.current,Ne),Te=({resize:ne=!1}={})=>{if(!d.current||!ge())return!1;try{return ne&&d.current.resize(),d.current.refresh(),!0}catch(be){if(be instanceof Error&&be.message.includes("Container has no width"))return!1;throw be}},ve=()=>Date.now()<T.current,Le=({level:ne,eventKey:be,message:je,details:pe,publishBackend:$e=!1})=>{},Qe=()=>d.current?{...d.current.getCamera().getState()}:{...ke},st=({rendererMode:ne})=>{if(!h.current||!b.current)return null;const be=h.current,je=be.nodes().map(Me=>{const He=be.getNodeAttributes(Me);return{id:Me,x:He.x,y:He.y}}),pe=Kf(je),$e=hm(je),Xe=Qe(),Ue=ne==="sigma"?{...Xe,x:Number((Xe.x-.5).toFixed(4)),y:Number((Xe.y-.5).toFixed(4))}:Xe,le=pm({centroid:pe,boundsCenter:$e,camera:Ue});return{datasetSignature:b.current,route:"/knowledge-graph",rendererMode:ne,startupPhase:R.current,startupInvariantSatisfied:CS(le),visibleNodeCount:je.length,focusedNodeId:f.current,primaryFocusedNodeId:P.current,graphCentroid:pe,boundsCenter:$e,camera:Xe,cameraTarget:S.current?{x:S.current.x,y:S.current.y,ratio:S.current.ratio}:null,driftMetrics:le,latestSnapshotAt:z.current,lastVerifiedAt:new Date().toISOString()}},F=(ne,{mirrorToConsole:be=!1}={})=>{},he=({rendererMode:ne,publishAnomaly:be})=>{},we=()=>{const ne=d.current?V():Se();if(d.current){d.current.getCamera().setState(ne);return}Ae(ne)},Z=ne=>{var $e;if(!h.current)return!1;const be=st({rendererMode:Ee()});if(!be)return!1;const je=be.graphCentroid.x,pe=be.graphCentroid.y;return Math.abs(je)<1e-4&&Math.abs(pe)<1e-4?!1:(Tp(h.current),fn(h.current,u.current),($e=m.current)==null||$e.postMessage({type:"recenter-graph",offsetX:je,offsetY:pe}),Ie(or(h.current,Ce)),we(),R.current="startup_corrected",Le({level:"warning",eventKey:"startup_corrected",message:"Corrected the knowledge graph startup bias back to graph-space origin.",publishBackend:!0,details:{datasetSignature:b.current}}),!0)},De=({phase:ne,allowCorrection:be,publishBackendOnFailure:je=!1})=>{if(!h.current||!b.current)return;R.current=ne;const pe=d.current?"sigma":"fallback",$e=st({rendererMode:pe});if(!$e)return;if($e.startupInvariantSatisfied){R.current="startup_verified",F({...$e},{mirrorToConsole:!0}),Le({level:"info",eventKey:"startup_verified",message:"Knowledge graph startup invariant passed.",details:{datasetSignature:$e.datasetSignature,driftMetrics:$e.driftMetrics}});return}if(Le({level:"warning",eventKey:"startup_invariant_failed",message:"Knowledge graph startup invariant failed before correction.",publishBackend:je,details:{datasetSignature:$e.datasetSignature,driftMetrics:$e.driftMetrics,centroid:$e.graphCentroid,boundsCenter:$e.boundsCenter,camera:$e.camera}}),Q.current||(Q.current=!0,!Z()))return;Te();const Ue=st({rendererMode:pe});if(Ue){if(Ue.startupInvariantSatisfied){R.current="startup_verified",F({...Ue},{mirrorToConsole:!0}),Le({level:"info",eventKey:"startup_verified_after_correction",message:"Knowledge graph startup invariant passed after correction.",details:{datasetSignature:Ue.datasetSignature,driftMetrics:Ue.driftMetrics}});return}Le({level:"error",eventKey:"startup_correction_failed",message:"Knowledge graph startup correction did not restore the origin invariant.",publishBackend:!0,details:{datasetSignature:Ue.datasetSignature,driftMetrics:Ue.driftMetrics,centroid:Ue.graphCentroid,boundsCenter:Ue.boundsCenter,camera:Ue.camera}})}},ee=()=>{var be,je,pe,$e;if(!b.current||!h.current)return;const ne=Date.now();if(!(ne-D.current<1500)){if(D.current=ne,d.current){K3({datasetSignature:b.current,focusNodeId:f.current,primaryFocusedNodeId:P.current,draggedNodeId:((be=C.current)==null?void 0:be.nodeId)??null,graph:h.current,layoutGeneration:A.current,sigma:d.current,startupPhase:R.current,startupInvariantSatisfied:((je=st({rendererMode:"sigma"}))==null?void 0:je.startupInvariantSatisfied)??!1,simulationPhase:N.current,focusSources:v.current,focusPressure:H.current,centroid:j.current,cameraTarget:S.current?{x:S.current.x,y:S.current.y,ratio:S.current.ratio}:null,latestSnapshotAt:z.current,latestSnapshotNodeCount:K.current});return}ie&&Ap({datasetSignature:b.current,focusNodeId:f.current,primaryFocusedNodeId:P.current,draggedNodeId:((pe=C.current)==null?void 0:pe.nodeId)??null,layoutGeneration:A.current,camera:ke,snapshot:ie,width:Ne.width,height:Ne.height,startupPhase:R.current,startupInvariantSatisfied:(($e=st({rendererMode:"fallback"}))==null?void 0:$e.startupInvariantSatisfied)??!1,simulationPhase:N.current,focusSources:v.current,focusPressure:H.current,centroid:j.current,cameraTarget:S.current?{x:S.current.x,y:S.current.y,ratio:S.current.ratio}:null,latestSnapshotAt:z.current,latestSnapshotNodeCount:K.current})}},ze=()=>{if(!h.current||!f.current){S.current=null;return}const ne=h.current;if(!ne.hasNode(f.current)){S.current=null;return}const be=Pp(ne),je=Np(Ce,f.current),pe=d.current?d.current.getCamera().getState().ratio:ke.ratio,$e=I3({positions:be,focusNodeId:f.current,firstRingNodeIds:je.firstRing,secondRingNodeIds:je.secondRing,currentRatio:pe}),Xe=d.current&&$e?y3({positions:be,point:{x:$e.x,y:$e.y}}):null;S.current=$e?{x:(Xe==null?void 0:Xe.x)??$e.x,y:(Xe==null?void 0:Xe.y)??$e.y,angle:0,ratio:$e.ratio,nodeIds:$e.nodeIds}:null},et=(ne=220)=>{if(!S.current)return;const be=S.current;if(d.current){const je=d.current.getCamera(),pe=je.getState(),$e=Date.now()<y.current;je.animate({x:be.x,y:be.y,ratio:$e?pe.ratio:be.ratio,angle:0},{duration:ne});return}Ae(je=>({...je,x:be.x,y:be.y,ratio:Date.now()<y.current?je.ratio:be.ratio}))};c.useEffect(()=>{p.current=n},[n]),c.useEffect(()=>{f.current=i,S.current=null},[i]),c.useEffect(()=>{Cp()},[O]),c.useEffect(()=>{if(!(!L3()||typeof window>"u"))return window.__FORGE_KNOWLEDGE_GRAPH_TEST_API__={selectNode:ne=>{var je;const be=ne?g.current.get(ne)??((je=h.current)!=null&&je.hasNode(ne)?h.current.getNodeAttribute(ne,"data")??null:null):null;p.current(be)},moveNodeBy:(ne,be,je)=>{var Ue,le;if(!((Ue=h.current)!=null&&Ue.hasNode(ne)))return;const pe=h.current.getNodeAttributes(ne),$e=pe.x+be,Xe=pe.y+je;h.current.mergeNodeAttributes(ne,{x:$e,y:Xe}),u.current.set(ne,{x:$e,y:Xe}),(le=m.current)==null||le.postMessage({type:"nudge-node",nodeId:ne,x:$e,y:Xe}),Te(),!d.current&&h.current&&Ie(or(h.current,Ce))},nudgeCameraBy:(ne,be)=>{if(d.current){const je=d.current.getCamera(),pe=je.getState();je.animate({x:pe.x+ne,y:pe.y+be,ratio:pe.ratio,angle:pe.angle},{duration:140});return}Ae(je=>({...je,x:je.x+ne,y:je.y+be}))}},()=>{delete window.__FORGE_KNOWLEDGE_GRAPH_TEST_API__}},[Ce]),c.useEffect(()=>{if(!o.current||typeof ResizeObserver>"u")return;const ne=()=>{o.current&&M({width:o.current.clientWidth,height:o.current.clientHeight})};ne();const be=new ResizeObserver(()=>{ne()});return be.observe(o.current),()=>be.disconnect()},[]),c.useImperativeHandle(l,()=>({zoomIn:()=>{if(y.current=Date.now()+1200,d.current){d.current.getCamera().animatedZoom({factor:1.25,duration:160});return}Ae(ne=>({...ne,ratio:Math.max(.08,ne.ratio*.82)}))},zoomOut:()=>{if(y.current=Date.now()+1200,d.current){d.current.getCamera().animatedUnzoom({factor:1.25,duration:160});return}Ae(ne=>({...ne,ratio:Math.min(4,ne.ratio*1.22)}))},fit:()=>{if(S.current=null,d.current){d.current.getCamera().animate(V(),{duration:220});return}ie&&Ae(O3(ie))},recenterOnFocus:()=>{ze(),S.current&&et(220)}}),[ie,Ce]),c.useEffect(()=>()=>{var ne,be,je;h.current&&fn(h.current,u.current),d.current&&b.current&&x.current.set(b.current,d.current.getCamera().getState()),(ne=m.current)==null||ne.postMessage({type:"dispose"}),(be=m.current)==null||be.terminate(),m.current=null,(je=d.current)==null||je.kill(),d.current=null,Cp()},[O]),c.useEffect(()=>{var Xe,Ue;if(!o.current||!Mp(o.current,Ne))return;if(b.current===qe&&h.current!==null){Te({resize:!0}),ee();return}R.current="boot",Q.current=!1,X.current=!1,Y.current=!1,z.current=null,K.current=null,$.current=0,S.current=null,Le({level:"info",eventKey:"graph_boot",message:"Bootstrapping a fresh knowledge graph dataset.",details:{nodeCount:s.length,edgeCount:Ce.length}}),h.current&&fn(h.current,u.current),d.current&&b.current&&x.current.set(b.current,d.current.getCamera().getState());const be=R3(s,Ce,u.current);if(Tp(be),fn(be,u.current),h.current=be,g.current=new Map(s.map(le=>[le.id,le])),b.current=qe,A.current+=1,Ie(or(be,Ce)),R.current="graph_built",Le({level:"info",eventKey:"graph_built",message:"Built and centered the knowledge graph structure.",details:{layoutGeneration:A.current}}),!D3())(Xe=d.current)==null||Xe.kill(),d.current=null,ae("WebGL is unavailable in this browser context."),Ae(Se(be)),De({phase:"graph_built",allowCorrection:!0,publishBackendOnFailure:!0});else try{if(d.current)d.current.setGraph(be),Te();else{d.current=new Tv(be,o.current,{renderEdgeLabels:!1,hideEdgesOnMove:!0,hideLabelsOnMove:!0,labelRenderedSizeThreshold:20,labelDensity:.04,labelGridCellSize:120,defaultNodeColor:"#c0c1ff",defaultEdgeColor:"rgba(125, 211, 252, 0.1)",minCameraRatio:.08,maxCameraRatio:4,autoRescale:!1,autoCenter:!1,enableEdgeEvents:!1,enableCameraPanning:!0,zIndex:!0}),Le({level:"info",eventKey:"sigma_initialized",message:"Initialized Sigma for the knowledge graph.",details:{datasetSignature:qe}}),d.current.on("clickNode",({node:Me})=>{if(ve())return;const He=g.current.get(Me)??null;p.current(He)}),d.current.on("clickStage",({event:Me})=>{if(ve())return;if(!d.current||!h.current){p.current(null);return}const He=q3({sigma:d.current,graph:h.current,viewportX:Me.x,viewportY:Me.y});if(He){p.current(g.current.get(He)??null);return}p.current(null)}),d.current.on("downNode",({node:Me,event:He,preventSigmaDefault:lt})=>{var Pe,k;if(!d.current||!((Pe=h.current)!=null&&Pe.hasNode(Me)))return;lt();const Nt=d.current.viewportToGraph({x:He.x,y:He.y}),me=h.current.getNodeAttributes(Me);C.current={nodeId:Me,offsetX:me.x-Nt.x,offsetY:me.y-Nt.y,startViewportX:He.x,startViewportY:He.y,currentX:me.x,currentY:me.y,moved:!1},w.current=d.current.getSetting("enableCameraPanning")??!0,d.current.setSetting("enableCameraPanning",!1),B(Me),q(Me),Le({level:"debug",eventKey:"drag_start",message:"Started dragging a knowledge graph node.",details:{nodeId:Me}}),(k=m.current)==null||k.postMessage({type:"drag-start",nodeId:Me})}),d.current.on("moveBody",({event:Me,preventSigmaDefault:He})=>{var k;if(!d.current||!h.current||!C.current)return;He();const lt=d.current.viewportToGraph({x:Me.x,y:Me.y});Math.hypot(Me.x-C.current.startViewportX,Me.y-C.current.startViewportY)>3&&(C.current={...C.current,moved:!0});const me=lt.x+C.current.offsetX,Pe=lt.y+C.current.offsetY;C.current={...C.current,currentX:me,currentY:Pe},h.current.mergeNodeAttributes(C.current.nodeId,{x:me,y:Pe}),u.current.set(C.current.nodeId,{x:me,y:Pe}),(k=m.current)==null||k.postMessage({type:"drag-move",nodeId:C.current.nodeId,x:me,y:Pe}),Te()});const le=()=>{var lt;if(!d.current||!C.current){C.current=null,B(null);return}const Me=C.current.nodeId,He=C.current.moved;d.current.setSetting("enableCameraPanning",w.current),(lt=m.current)==null||lt.postMessage({type:"drag-end",nodeId:Me}),Le({level:"debug",eventKey:"drag_end",message:"Released a dragged knowledge graph node.",details:{nodeId:Me,moved:He}}),C.current=null,B(null),He&&(T.current=Date.now()+220,p.current(g.current.get(Me)??null))};d.current.on("upNode",le),d.current.on("upStage",le),d.current.on("leaveStage",le),d.current.on("enterNode",({node:Me})=>{q(Me)}),d.current.on("leaveNode",()=>{q(null)}),d.current.on("afterRender",()=>{X.current||(X.current=!0,R.current="first_frame",Le({level:"info",eventKey:"first_frame",message:"Knowledge graph rendered its first frame.",details:{datasetSignature:b.current}}),De({phase:"first_frame",allowCorrection:!0,publishBackendOnFailure:!0}),he({rendererMode:"sigma",publishAnomaly:!0})),ee()})}ae(null),Ie(or(be,Ce)),d.current.getCamera().setState(V(be))}catch(le){(Ue=d.current)==null||Ue.kill(),d.current=null,ae(le instanceof Error?le.message:"Graph renderer unavailable."),Ie(or(be,Ce)),Ae(Se(be)),Le({level:"error",eventKey:"sigma_fallback",message:"Fell back from Sigma to the SVG renderer.",publishBackend:!0,details:{reason:le instanceof Error?le.message:"unknown"}}),De({phase:"graph_built",allowCorrection:!0,publishBackendOnFailure:!0})}m.current||(m.current=new Worker(new URL("/forge/assets/knowledge-graph-layout.worker-DRvzPxhP.js",import.meta.url),{type:"module"}),m.current.onmessage=le=>{var Pe;if(!h.current)return;const Me=le.data;if(Me.type==="stats"){N.current=Me.phase,P.current=Me.primaryFocusedNodeId,v.current=Me.focusSources,H.current=Me.focusPressure,j.current=Me.centroid,Y.current||(Y.current=!0,R.current="worker_started",Le({level:"info",eventKey:"worker_started",message:"Knowledge graph worker reported its first simulation stats.",details:{datasetSignature:b.current,phase:Me.phase}}),De({phase:"worker_started",allowCorrection:!0,publishBackendOnFailure:!0}));return}const He=h.current;let lt=Me.x,Nt=Me.y;if(R.current!=="startup_verified"){const k=z3({x:Me.x,y:Me.y});k.changed&&(lt=k.x,Nt=k.y,(Pe=m.current)==null||Pe.postMessage({type:"recenter-graph",offsetX:k.offsetX,offsetY:k.offsetY}),we(),Le({level:"warning",eventKey:"worker_startup_recenter",message:"Recentering worker positions during startup because the graph drifted away from origin.",details:{datasetSignature:b.current,startupPhase:R.current,offsetX:k.offsetX,offsetY:k.offsetY}}))}let me=0;if(He.updateEachNodeAttributes((k,se)=>({...se,x:lt[me],y:Nt[me++]}),{attributes:["x","y"]}),C.current&&He.hasNode(C.current.nodeId)){const k=C.current.nodeId;He.mergeNodeAttributes(k,{x:C.current.currentX,y:C.current.currentY})}fn(He,u.current),d.current?Te():Ie(or(He,Ce))});const je=be.nodes(),pe=new Map(je.map((le,Me)=>[le,Me])),$e=kp(je,Ce,i);m.current.postMessage({type:"init-graph",nodes:je.map(le=>{const Me=be.getNodeAttributes(le);return{id:le,x:Me.x,y:Me.y,size:Me.size,mass:Math.max(1,Me.data.importance/42),importance:Me.data.importance}}),edges:Ce.filter(le=>pe.has(le.source)&&pe.has(le.target)).map(le=>({source:pe.get(le.source),target:pe.get(le.target),weight:Math.max(.6,le.strength)})),focusNodeId:i,hopLevels:$e,physics:r}),Le({level:"debug",eventKey:"worker_init",message:"Posted the graph payload to the layout worker.",details:{nodeCount:je.length,edgeCount:Ce.length}})},[Ne.height,Ne.width,qe,i,s,r,Ce]),c.useEffect(()=>{if(!m.current||!h.current)return;const ne=kp(h.current.nodes(),Ce,i);m.current.postMessage({type:"set-focus",focusNodeId:i,hopLevels:ne}),i||(S.current=null)},[i,Ce]),c.useEffect(()=>{m.current&&m.current.postMessage({type:"update-physics",physics:r})},[r]),c.useEffect(()=>{},[qe,O]),c.useEffect(()=>{!d.current||!h.current||(d.current.setSetting("nodeReducer",(ne,be)=>{var pe;const je=(pe=h.current)==null?void 0:pe.getNodeAttribute(ne,"data");return k3({nodeId:ne,attributes:be,node:je,focusNodeId:i,relatedNodeIds:U,detailNodeIds:L,hoveredNodeId:J,draggedNodeId:_})}),d.current.setSetting("edgeReducer",(ne,be)=>{var pe;const je=(pe=h.current)==null?void 0:pe.getEdgeAttribute(ne,"data");return S3({attributes:be,edge:je,focusNodeId:i,detailNodeIds:L,relatedNodeIds:U,hoveredNodeId:J})}),Te())},[L,_,i,J,U]),c.useEffect(()=>{var ne,be;!ie||!b.current||Ne.width<=0||Ne.height<=0||!G&&d.current||(X.current||(X.current=!0,R.current="first_frame",Le({level:"info",eventKey:"fallback_first_frame",message:"Knowledge graph rendered its first fallback frame.",details:{datasetSignature:b.current}}),De({phase:"first_frame",allowCorrection:!0,publishBackendOnFailure:!0})),Ap({datasetSignature:b.current,focusNodeId:i,primaryFocusedNodeId:P.current,draggedNodeId:((ne=C.current)==null?void 0:ne.nodeId)??null,layoutGeneration:A.current,camera:ke,snapshot:ie,width:Ne.width,height:Ne.height,startupPhase:R.current,startupInvariantSatisfied:((be=st({rendererMode:"fallback"}))==null?void 0:be.startupInvariantSatisfied)??!1,simulationPhase:N.current,focusSources:v.current,focusPressure:H.current,centroid:j.current,cameraTarget:S.current?{x:S.current.x,y:S.current.y,ratio:S.current.ratio}:null,latestSnapshotAt:z.current,latestSnapshotNodeCount:K.current}))},[Ne.height,Ne.width,ke,G,ie,i]);const Ve=c.useMemo(()=>!ie||Ne.width<=0||Ne.height<=0?[]:ie.nodes.map(ne=>{const be=xw({node:ne,snapshot:ie,camera:ke,width:Ne.width,height:Ne.height});return{...ne,viewportX:be.x,viewportY:be.y,viewportSize:be.size}}),[Ne.height,Ne.width,ke,ie]),re=c.useMemo(()=>new Map(Ve.map(ne=>[ne.id,ne])),[Ve]);return e.jsx("div",{className:"relative h-full w-full overflow-hidden bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.1),transparent_34%),linear-gradient(180deg,rgba(7,12,23,0.98),rgba(6,11,20,0.98))]",children:e.jsx("div",{ref:o,className:"h-full w-full touch-none","aria-label":"Knowledge graph canvas",children:G&&ie?e.jsxs("svg",{className:"h-full w-full",viewBox:`0 0 ${Math.max(Ne.width,1)} ${Math.max(Ne.height,1)}`,"aria-hidden":"true",children:[e.jsx("title",{children:"Knowledge graph fallback canvas"}),e.jsx("rect",{x:"0",y:"0",width:Math.max(Ne.width,1),height:Math.max(Ne.height,1),fill:"transparent",onClick:()=>p.current(null)}),ie.edges.map(ne=>{const be=re.get(ne.source),je=re.get(ne.target);if(!be||!je)return null;const pe=!!i&&(ne.source===i||ne.target===i),$e=!!J&&(ne.source===J||ne.target===J),Xe=i?ne.source===i?0:L.has(ne.source)?1:U.has(ne.source)?2:3:0,Ue=i?ne.target===i?0:L.has(ne.target)?1:U.has(ne.target)?2:3:0,le=i?Math.max(Xe,Ue):0;return e.jsx("line",{x1:be.viewportX,y1:be.viewportY,x2:je.viewportX,y2:je.viewportY,stroke:pe?dr(ne,.24):$e?dr(ne,.14):i?le<=1?dr(ne,.09):le===2?dr(ne,.05):dr(ne,.016):dr(ne,.055),strokeWidth:pe?1.7:$e?1.3:.95},ne.id)}),Ve.map(ne=>{const be=i===ne.id,je=U.has(ne.id),pe=L.has(ne.id),$e=J===ne.id,Xe=!i||je;return e.jsxs("g",{transform:`translate(${ne.viewportX}, ${ne.viewportY})`,onMouseEnter:()=>q(ne.id),onMouseLeave:()=>q(null),onClick:Ue=>{Ue.stopPropagation();const le=g.current.get(ne.id)??null;p.current(le)},style:{cursor:"pointer"},children:[e.jsx("circle",{r:be?ne.viewportSize*1.9:$e?ne.viewportSize*1.3:pe?ne.viewportSize*1.15:je?ne.viewportSize*1.05:ne.viewportSize,fill:Xe?ne.color:_3(ne.color,.3),stroke:be?"rgba(255,255,255,0.78)":"rgba(255,255,255,0.12)",strokeWidth:be?2:1}),(be||$e||pe)&&e.jsx("text",{x:ne.viewportSize*1.5,y:4,fill:"rgba(244,247,255,0.92)",fontSize:"12",children:ne.data.title})]},ne.id)})]}):null})})}),U3=300,W3=152;function gw(t,s){return t?E3(t,s):new Set}function H3(t,s,a){const i=pw(t,s),r=gw(a,s);return i.nodes.map(n=>{const l=n.id===a,o=!a||r.has(n.id);return{id:n.id,draggable:!1,selectable:!1,position:{x:72+n.layer*U3,y:88+n.row*W3},data:{label:e.jsxs("div",{className:"min-w-[232px] rounded-[22px] border px-4 py-4 shadow-[0_24px_70px_rgba(0,0,0,0.24)] transition",style:{borderColor:l?"rgba(255,255,255,0.32)":"rgba(255,255,255,0.1)",background:l?"rgba(11,17,30,0.98)":"rgba(8,14,26,0.92)",opacity:o?1:.28},children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(We,{kind:n.entityKind,label:n.entityKind.replaceAll("_"," "),compact:!0,gradient:l})}),e.jsx("div",{className:"mt-3",children:e.jsx(yt,{kind:n.entityKind,label:n.title,className:"max-w-full",lines:2})}),n.subtitle?e.jsx("div",{className:"mt-2 text-sm leading-5 text-white/58",children:n.subtitle}):null]})},style:{background:"transparent",border:"none",padding:0}}})}function G3(t,s,a,i){const r=pw(t,s),n=gw(a,s);return r.edges.filter(l=>i||!l.secondary).map(l=>{const o=!a||n.has(l.source)||n.has(l.target);return{id:l.id,source:l.source,target:l.target,animated:!l.secondary&&l.family==="structural"&&o,markerEnd:{type:Uu.ArrowClosed,color:l.secondary?"rgba(255,255,255,0.16)":"rgba(232,242,255,0.42)"},style:{opacity:o?1:.18,stroke:l.secondary?"rgba(255,255,255,0.16)":l.family==="taxonomy"?"rgba(162,245,189,0.34)":l.family==="structural"?"rgba(232,242,255,0.4)":"rgba(192,193,255,0.24)",strokeDasharray:l.secondary?"8 6":void 0,strokeWidth:l.secondary?1:l.family==="structural"?1.7:1.2}}})}function Q3({nodes:t,edges:s,focusNodeId:a,showSecondaryEdges:i,onSelectNode:r,onOpenNode:n,onNavigateNode:l,isMobile:o}){const d=c.useMemo(()=>H3(t,s,a),[s,a,t]),m=c.useMemo(()=>G3(t,s,a,i),[s,a,t,i]),h=c.useMemo(()=>new Map(t.map(u=>[u.id,u])),[t]);return e.jsxs("div",{className:"knowledge-graph-canvas relative h-[44rem] rounded-[28px]",children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 z-10 flex gap-4 overflow-x-auto px-6 py-4",children:Tr.map(u=>e.jsx("div",{className:"min-w-[17rem] rounded-full border border-white/10 bg-[rgba(11,17,28,0.78)] px-4 py-2 text-center text-[11px] uppercase tracking-[0.16em] text-white/52 backdrop-blur",children:u.label},u.id))}),e.jsxs(id,{fitView:!0,fitViewOptions:a?{padding:.24,nodes:[{id:a}]}:{padding:.2},nodes:d,edges:m,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,attributionPosition:"bottom-left",onNodeClick:(u,x)=>{const g=h.get(x.id);g&&r(g)},onNodeDoubleClick:(u,x)=>{const g=h.get(x.id);if(g){if(o){n(g);return}l(g)}},children:[e.jsx(Bu,{showInteractive:!1}),e.jsx(rd,{gap:28,size:1,color:"rgba(255,255,255,0.05)"})]},`${a??"all"}-${i?"all":"primary"}`)]})}function V3(t){return t.trim().toLowerCase()}function mi({title:t,description:s,query:a,onQueryChange:i,onQuerySubmit:r,options:n,selectedOptionIds:l,onSelectedOptionIdsChange:o,resultSummary:d,clearLabel:m="Clear filters",submitLabel:h="Search",placeholder:u="Search title, alias, domain, source, or filter chip",emptyStateMessage:x="Keep typing to search the library or pick one of the suggested filter chips.",compact:g=!1,minimal:p=!1,hideSummary:f=!1}){const[b,A]=c.useState(!1),[C,T]=c.useState(0),w=c.useMemo(()=>l.map(v=>n.find(H=>H.id===v)).filter(Boolean),[n,l]),S=c.useMemo(()=>{const v=V3(a),H=n.filter(j=>!l.includes(j.id));return v?H.filter(j=>`${j.label} ${j.description??""} ${j.searchText??""}`.toLowerCase().includes(v)).slice(0,12):H.slice(0,12)},[n,a,l]),y=v=>{l.includes(v)||(o([...l,v]),i(""),A(!1),T(0))},N=v=>{o(l.filter(H=>H!==v))},P=()=>{i(""),o([]),T(0),A(!1)};return e.jsxs("div",{className:te("rounded-[28px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,30,42,0.92),rgba(9,15,24,0.98))] shadow-[0_30px_80px_rgba(3,8,18,0.28)]",p?"overflow-hidden rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] px-3 py-1.5 shadow-[0_18px_50px_rgba(0,0,0,0.26)] backdrop-blur":g?"rounded-[24px] p-2.5":"p-4 sm:p-5"),children:[e.jsxs("div",{className:te("flex flex-wrap items-start justify-between gap-3",p&&"hidden"),children:[e.jsxs("div",{children:[t.trim().length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:t}):null,s.trim().length>0?e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/62",children:s}):null]}),l.length>0||a.trim().length>0?e.jsx("button",{type:"button",onClick:P,className:te("rounded-full border border-white/8 bg-white/[0.04] text-white/62 transition hover:bg-white/[0.08] hover:text-white",g?"px-2.5 py-1.5 text-[11px]":"px-3 py-2 text-sm"),children:m}):null]}),e.jsxs("div",{className:te("rounded-[24px] border border-white/8 bg-white/[0.04]",p?"rounded-full border-0 bg-transparent px-0 py-0":g?"mt-1.5 rounded-[18px] px-2.5 py-2":"mt-4 px-4 py-3"),children:[w.length>0?e.jsx("div",{className:te("flex flex-wrap gap-2",p?"mb-0 mr-2 inline-flex max-w-[38%] flex-nowrap items-center gap-1 overflow-hidden":g?"mb-2":"mb-3"),children:w.map(v=>e.jsxs("span",{className:te("inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06]",p?"max-w-full shrink-0 border-white/10 bg-white/[0.08] px-2 py-0.5":g?"px-2 py-0.5":"px-2.5 py-1.5"),children:[v.badge??e.jsx("span",{className:"text-sm text-white/78",children:v.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>N(v.id),"aria-label":`Remove ${v.label}`,children:e.jsx(Tt,{className:"size-3.5"})})]},v.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:te("flex items-center",p?"gap-2 whitespace-nowrap":g?"gap-2":"gap-3"),children:[e.jsx(_t,{className:te("text-white/36",g?"size-3.5":"size-4")}),e.jsx("input",{value:a,onChange:v=>{i(v.target.value),A(!0),T(0)},onFocus:()=>A(!0),onBlur:()=>window.setTimeout(()=>A(!1),120),onKeyDown:v=>{if(v.key==="Backspace"&&!a&&l.length>0){N(l[l.length-1]);return}if(v.key==="ArrowDown"){v.preventDefault(),A(!0),T(H=>S.length===0?0:Math.min(S.length-1,H+1));return}if(v.key==="ArrowUp"){v.preventDefault(),T(H=>Math.max(0,H-1));return}if(v.key==="Escape"){A(!1);return}if(v.key==="Enter"&&r){v.preventDefault(),r(a),A(!1);return}v.key==="Enter"&&S[C]&&(v.preventDefault(),y(S[C].id))},placeholder:u,className:te("min-w-0 flex-1 bg-transparent text-white placeholder:text-white/34 focus:outline-none",p||g?"text-[12px]":"text-sm")}),p&&(l.length>0||a.trim().length>0)?e.jsx("button",{type:"button",onClick:P,className:"inline-flex size-6 items-center justify-center rounded-full border border-white/10 bg-white/[0.06] text-white/62 transition hover:text-white","aria-label":m,children:e.jsx(Tt,{className:"size-3.5"})}):null,r?e.jsx("button",{type:"button",onMouseDown:v=>v.preventDefault(),onClick:()=>{r(a),A(!1)},className:te("inline-flex items-center justify-center rounded-full border border-white/10 bg-white/[0.08] text-white/72 transition hover:bg-white/[0.14] hover:text-white",p?"size-6":g?"size-7":"size-8"),"aria-label":h,title:h,children:e.jsx(_t,{className:te(g?"size-3.5":"size-4")})}):null]}),b?e.jsx("div",{className:te("absolute top-full z-20 w-full border border-white/8 bg-[rgba(8,13,24,0.96)] shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",g?"mt-1.5 rounded-[18px] p-1.5":"mt-2 rounded-[22px] p-2"),children:S.length>0?S.map((v,H)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 text-left transition",g?"rounded-[14px] px-2.5 py-2":"rounded-[18px] px-3 py-2.5",H===C?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>T(H),onMouseDown:j=>j.preventDefault(),onClick:()=>y(v.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:te("truncate font-medium",g?"text-[12px]":"text-sm"),children:v.badge??v.label}),v.description?e.jsx("div",{className:te("mt-1 text-white/46",g?"text-[11px] leading-[1.125rem]":"text-xs leading-5"),children:v.description}):null]})},v.id)):e.jsx("div",{className:te("text-white/42",g?"px-2.5 py-2 text-[12px]":"px-3 py-2.5 text-sm"),children:x})}):null]})]}),f?null:e.jsx("div",{className:te("text-white/52",g?"mt-2 text-xs":"mt-3 text-sm"),children:d})]})}const fw=6,bw=5,ww=.92,yw=5,vw=.15,jw=2.4,Nw=2,kw=.8,Sw=3,oa={focusRepulsion:2.25,focusDiffusion:1.95,focusSpringReductionMax:.34,focusSpringReductionDiffusion:1.85,edgeSpringStrength:1,gravityStrength:1,focusShellSpacing:1};function fi(t,s,a){return Math.min(Math.max(t,s),a)}function Iw(t){return{focusRepulsion:fi((t==null?void 0:t.focusRepulsion)??oa.focusRepulsion,.6,fw),focusDiffusion:fi((t==null?void 0:t.focusDiffusion)??oa.focusDiffusion,.6,bw),focusSpringReductionMax:fi((t==null?void 0:t.focusSpringReductionMax)??oa.focusSpringReductionMax,0,ww),focusSpringReductionDiffusion:fi((t==null?void 0:t.focusSpringReductionDiffusion)??oa.focusSpringReductionDiffusion,.6,yw),edgeSpringStrength:fi((t==null?void 0:t.edgeSpringStrength)??oa.edgeSpringStrength,vw,jw),gravityStrength:fi((t==null?void 0:t.gravityStrength)??oa.gravityStrength,0,Nw),focusShellSpacing:fi((t==null?void 0:t.focusShellSpacing)??oa.focusShellSpacing,kw,Sw)}}function X3({isMobile:t,currentFocusNodeId:s,nextNodeId:a}){return a?t?s===a?{nextFocusNodeId:a,nextMobileSheetOpen:!0,shouldUpdateFocus:!1}:{nextFocusNodeId:a,nextMobileSheetOpen:!1,shouldUpdateFocus:!0}:{nextFocusNodeId:a,nextMobileSheetOpen:!1,shouldUpdateFocus:s!==a}:{nextFocusNodeId:null,nextMobileSheetOpen:!1,shouldUpdateFocus:s!==null}}const Ep="__clear__";function Y3({isMobile:t,focusNodeId:s,shellOverlayFocusNodeId:a,lastRequestedKey:i}){const r=t?null:s,n=r??Ep;return n===(a??Ep)?{action:"none",nextRequestedKey:n}:i===n?{action:"none",nextRequestedKey:n}:{action:r?"set":"clear",nextRequestedKey:n}}const Wl=2e3,ac=40,ic=2e3,Cw="forge.knowledge-graph.physics";function J3(){if(typeof window>"u")return!1;if(window.__FORGE_ENABLE_GRAPH_DIAGNOSTICS__)return!0;try{return new URLSearchParams(window.location.search).get("graphDiagnostics")==="1"}catch{return!1}}function Hl(t,s){return Array.from(new Set(t.getAll(s).flatMap(a=>a.split(",")).map(a=>a.trim()).filter(Boolean)))}function Ss(t,s,a){t.delete(s),a.forEach(i=>t.append(s,i))}function Z3(t){switch(t.entityType){case"workbench_flow":case"workbench_surface":case"wiki_space":return null;default:return yl(t.entityType,t.entityId)}}function Bs(t){return t?t.slice(0,10):""}function eC(){if(typeof window>"u")return oa;try{const t=window.localStorage.getItem(Cw);return t?Iw(JSON.parse(t)):oa}catch{return oa}}function tC(t,s,a,i,r){const n=t.find(l=>l.id===s);return n||(!s||!a?null:{id:s,displayName:a,kind:i??"human",accentColor:r??"",handle:a.toLowerCase().replace(/\s+/g,"-"),description:"",createdAt:"",updatedAt:""})}function sC({entityKinds:t,relationKinds:s,tags:a,owners:i}){return[...t.map(r=>`entity:${r}`),...s.map(r=>`relation:${r}`),...a.map(r=>`tag:${r}`),...i.map(r=>`owner:${r}`)]}function Lp(t){const s=[],a=[],i=[],r=[];for(const n of t){const[l,...o]=n.split(":"),d=o.join(":").trim();d&&(l==="entity"?s.push(d):l==="relation"?a.push(d):l==="tag"?i.push(d):l==="owner"&&r.push(d))}return{entityKinds:s,relationKinds:a,tags:i,owners:r}}class aC extends c.Component{constructor(s){super(s),this.state={error:null}}static getDerivedStateFromError(s){return{error:s}}componentDidUpdate(s){s.resetKey!==this.props.resetKey&&this.state.error!==null&&this.setState({error:null})}render(){return this.state.error?this.props.fallback(this.state.error):this.props.children}}function iC(){var he,we;const t=jt(),s=jl();ri(Z=>Z.knowledgeGraphDiagnostics);const a=ri(Z=>{var De,ee;return((ee=(De=Z.shell.knowledgeGraphOverlayFocus)==null?void 0:De.focusNode)==null?void 0:ee.id)??null}),i=$t(),[r,n]=ms(),l=c.useRef(null),o=c.useRef(null),d=c.useRef(null),m=c.useRef(null),h=c.useRef(null);c.useRef(qf("/knowledge-graph"));const[u,x]=c.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 1023px)").matches:!1),[g,p]=c.useState(!1),[f,b]=c.useState(!1),[A,C]=c.useState(!1),[T,w]=c.useState(!1),[S,y]=c.useState(""),[N,P]=c.useState(()=>eC()),H=zf(),j=({level:Z,eventKey:De,message:ee,details:ze,publishBackend:et=!1})=>{};c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const Z=window.matchMedia("(max-width: 1023px)"),De=ee=>x(ee?ee.matches:Z.matches);return De(),typeof Z.addEventListener=="function"?(Z.addEventListener("change",De),()=>Z.removeEventListener("change",De)):(Z.addListener(De),()=>Z.removeListener(De))},[]),c.useEffect(()=>{u||(p(!1),b(!1),o.current=null)},[u]),c.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Cw,JSON.stringify(N))},[N]);const R=r.toString(),Q=c.useMemo(()=>{const Z=new URLSearchParams(R),De=Z.get("view")==="hierarchy"?"hierarchy":"graph",ee=_S(Z.get("focus")),ze=ee?M3(ee.entityType,ee.entityId):null,et=Hl(Z,"entityKind"),Ve=Hl(Z,"relationKind"),re=Hl(Z,"tag"),ne=Hl(Z,"owner"),be=Z.get("q")??"",je=Z.get("updatedFrom"),pe=Z.get("updatedTo"),$e=Number(Z.get("limit")??Wl),Xe=Number.isFinite($e)?Math.max(ac,Math.min(ic,$e)):Wl;return{selectedView:De,focusNodeId:ze,selectedKinds:et,selectedRelations:Ve,selectedTags:re,selectedOwners:ne,showHierarchyCrossLinks:Z.get("cross")==="1",queryText:be,updatedFrom:je,updatedTo:pe,maxNodes:Xe}},[R]),{selectedView:X,focusNodeId:Y,selectedKinds:z,selectedRelations:K,selectedTags:$,selectedOwners:D,showHierarchyCrossLinks:J,queryText:q,updatedFrom:_,updatedTo:B,maxNodes:G}=Q;c.useEffect(()=>{y(q)},[q]);const ae=c.useMemo(()=>({q:q.trim()||null,entityKinds:[...z].sort(),relationKinds:[...K].sort(),tags:[...$].sort(),owners:[...D].sort(),updatedFrom:_,updatedTo:B,limit:G,focusNodeId:null}),[G,q,z,D,K,$,_,B]),ke=c.useMemo(()=>["forge-knowledge-graph",...t.selectedUserIds,JSON.stringify(ae)],[ae,t.selectedUserIds]),Ae=Fe({queryKey:ke,queryFn:()=>gj(t.selectedUserIds,ae),placeholderData:Z=>Z,staleTime:6e4,refetchOnWindowFocus:!1}),ie=Ae.data;c.useEffect(()=>{j({level:"info",eventKey:"route_arrival",message:"Arrived on the Knowledge Graph page.",details:{search:r.toString()}})},[]),c.useEffect(()=>{if(!Ae.isSuccess||!ie)return;const Z=JSON.stringify({q:ae.q,entityKinds:ae.entityKinds,relationKinds:ae.relationKinds,tags:ae.tags,owners:ae.owners,updatedFrom:ae.updatedFrom,updatedTo:ae.updatedTo,limit:ae.limit,nodeCount:ie.counts.nodeCount,edgeCount:ie.counts.edgeCount,filteredNodeCount:ie.counts.filteredNodeCount,limited:ie.counts.limited});h.current!==Z&&(h.current=Z,j({level:"info",eventKey:"graph_query_resolved",message:"Knowledge graph query resolved.",details:{nodeCount:ie.counts.nodeCount,edgeCount:ie.counts.edgeCount,filteredNodeCount:ie.counts.filteredNodeCount,limited:ie.counts.limited}}))},[ie,Ae.isSuccess,ae]),c.useEffect(()=>{!ie||!Y||ie.nodes.some(Z=>Z.id===Y)||(n(Z=>{const De=new URLSearchParams(Z);return De.delete("focus"),De},{replace:!0}),p(!1),o.current=null)},[Y,ie,n]),c.useEffect(()=>{if(u){if(!Y){o.current=null,p(!1);return}o.current===Y&&!g&&(p(!0),o.current=null)}},[Y,u,g]);const Ie=c.useMemo(()=>!ie||!Y?Ip([],[],null):Ip(ie.nodes,ie.edges,Y),[Y,ie]);c.useEffect(()=>{var De;const Z=Y3({isMobile:u,focusNodeId:((De=Ie.focusNode)==null?void 0:De.id)??null,shellOverlayFocusNodeId:a,lastRequestedKey:m.current});if(m.current=Z.nextRequestedKey,Z.action!=="none"){if(Z.action==="clear"){s(Fo());return}s(bS(Ie))}},[s,Ie,u,a]),c.useEffect(()=>{{d.current=null;return}},[H,Y,Ie,u]),c.useEffect(()=>()=>{s(Fo())},[s]),c.useEffect(()=>{if(!(typeof window>"u")){if(!J3()){delete window.__FORGE_KNOWLEDGE_GRAPH_PAGE_TEST__;return}return window.__FORGE_KNOWLEDGE_GRAPH_PAGE_TEST__={isMobile:u,mobileSheetOpen:g,focusNodeId:Y,selectedView:X,selectNodeById:Z=>{if(!ie)return;const De=Z?ie.nodes.find(ee=>ee.id===Z)??null:null;E(De)},activateFocusedNode:()=>{if(!Y||!ie)return;const Z=ie.nodes.find(De=>De.id===Y)??null;Z&&E(Z)}},()=>{delete window.__FORGE_KNOWLEDGE_GRAPH_PAGE_TEST__}}},[Y,u,g,X]);const Ne=Z=>{n(De=>{const ee=new URLSearchParams(De);return Z(ee),ee},{replace:!0})},M=Z=>{const De=Z.trim();y(Z),Ne(ee=>{De.length>0?ee.set("q",De):ee.delete("q")})},E=Z=>{const De=X3({isMobile:u,currentFocusNodeId:Y,nextNodeId:(Z==null?void 0:Z.id)??null});o.current=u&&De.nextMobileSheetOpen?(Z==null?void 0:Z.id)??null:null,p(De.nextMobileSheetOpen),De.shouldUpdateFocus&&(Ne(ee=>{if(!Z){ee.delete("focus");return}ee.set("focus",_o(Z.entityType,Z.entityId))}),u&&b(!1))},O=Z=>{Z.href&&i(Z.href)},xe=(Z,De)=>{P(ee=>Iw({...ee,[Z]:De}))},V=Z=>{const De=Z3(Z);De&&i(De)},Se=Z=>{Ne(De=>{De.set("view","hierarchy"),De.set("focus",_o(Z.entityType,Z.entityId))})},Ee=()=>{Ne(Z=>{["q","entityKind","relationKind","tag","owner","updatedFrom","updatedTo","focus"].forEach(De=>Z.delete(De)),Z.set("limit",String(Wl))}),C(!1)};if(Ae.isLoading&&!ie)return e.jsx(Et,{eyebrow:"Knowledge Graph",title:"Loading the Forge world model",description:"Gathering goals, projects, KarpaWiki pages, psyche entities, calendar context, and Workbench flows into one graph."});if(Ae.isError)return e.jsx(it,{eyebrow:"Knowledge Graph",error:Ae.error,onRetry:()=>void Ae.refetch()});if(!ie)return null;const Ce=new Map(ie.facets.entityKinds.map(Z=>[Z.value,Z])),qe=iu.map(Z=>{const De=zs(Z),ee=Ce.get(Z),ze=(ee==null?void 0:ee.count)??0;return{value:Z,label:(ee==null?void 0:ee.label)??De.label,description:ze===1?"1 node":`${ze} nodes`,kind:Z}}),oe=ie.facets.relationKinds.map(Z=>({value:Z.value,label:Z.label,description:`${Z.count} links`})),L=ie.facets.tags.map(Z=>({value:Z.id,label:Z.label,description:`${Z.count} linked nodes`,badge:e.jsx(We,{kind:"tag",label:Z.label,compact:!0,gradient:!1}),menuBadge:e.jsx(We,{kind:"tag",label:Z.label,compact:!0,gradient:!1})})),U=ie.facets.owners.map(Z=>{const De=tC(t.snapshot.users,Z.userId,Z.displayName,Z.kind,Z.accentColor);return{value:Z.userId,label:Z.displayName,description:`${Z.count} nodes`,badge:e.jsx(ot,{user:De,compact:!0}),menuBadge:e.jsx(ot,{user:De,compact:!0})}}),ge=[...qe.map(Z=>({id:`entity:${Z.value}`,label:Z.label,description:Z.description,searchText:`entity kind ${Z.label}`,badge:e.jsx(We,{kind:Z.kind??"note",label:Z.label,compact:!0,gradient:!1})})),...oe.map(Z=>({id:`relation:${Z.value}`,label:Z.label,description:Z.description,searchText:`relation kind ${Z.label}`})),...L.map(Z=>({id:`tag:${Z.value}`,label:Z.label,description:Z.description,searchText:`tag ${Z.label}`,badge:Z.menuBadge??Z.badge})),...U.map(Z=>({id:`owner:${Z.value}`,label:Z.label,description:Z.description,searchText:`owner ${Z.label}`,badge:Z.menuBadge??Z.badge}))],Te=sC({entityKinds:z,relationKinds:K,tags:$,owners:D}),ve=ie.counts.limited?`${ie.counts.nodeCount}/${ie.counts.filteredNodeCount} nodes`:`${ie.counts.nodeCount}n · ${ie.counts.edgeCount}e`,Le=ie.counts.limited?`${ie.counts.nodeCount} visible nodes from ${ie.counts.filteredNodeCount} filtered matches`:`${ie.counts.nodeCount} nodes and ${ie.counts.edgeCount} edges`,Qe=q.trim().length>0||z.length>0||K.length>0||$.length>0||D.length>0||!!_||!!B||G!==Wl,st=!u,F=`${X}:${ie.nodes.map(Z=>Z.id).join("|")}::${ie.edges.map(Z=>Z.id).join("|")}`;return e.jsxs("div",{className:"-mx-4 -mb-2.5 h-[calc(100dvh-var(--forge-mobile-nav-clearance)-5.25rem)] overflow-hidden lg:-mx-6 lg:-mb-3 lg:-mt-3 lg:h-[calc(100dvh-10rem)]",children:[e.jsxs("div",{className:"relative h-full bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.08),transparent_26%),linear-gradient(180deg,rgba(7,12,23,0.98),rgba(5,10,19,1))]",children:[e.jsx(aC,{resetKey:F,fallback:Z=>e.jsx("div",{className:"grid h-full place-items-center p-6 text-center",children:e.jsxs("div",{className:"grid max-w-lg gap-4 rounded-[28px] border border-[rgba(255,255,255,0.08)] bg-[rgba(8,12,22,0.92)] p-6 shadow-[0_30px_80px_rgba(0,0,0,0.36)]",children:[e.jsx("div",{className:"mx-auto flex size-12 items-center justify-center rounded-full border border-[rgba(255,255,255,0.12)] bg-[rgba(255,255,255,0.04)] text-[var(--warning)]",children:e.jsx(ml,{className:"size-5"})}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Graph renderer fallback"}),e.jsx("h2",{className:"text-lg font-semibold text-[var(--ui-ink-strong)]",children:"The graph renderer hit a display error."}),e.jsx("p",{className:"text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Switch to the hierarchy view or reset the current graph filters. The graph will recover automatically when the dataset changes."}),e.jsx("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[rgba(255,255,255,0.04)] px-4 py-3 text-left text-xs text-[var(--ui-ink-faint)]",children:Z.message})]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[e.jsxs(W,{variant:"primary",size:"sm",onClick:()=>Ne(De=>{De.set("view","hierarchy")}),children:[e.jsx(Av,{className:"size-4"}),"Open hierarchy"]}),e.jsx(W,{variant:"secondary",size:"sm",onClick:Ee,children:"Reset graph filters"})]})]})}),children:X==="graph"?e.jsx(B3,{ref:l,nodes:ie.nodes,edges:ie.edges,focusNodeId:Y,physicsSettings:N,onSelectNode:E}):e.jsx("div",{className:"h-full overflow-y-auto px-4 py-4 lg:px-6",children:e.jsx(Q3,{nodes:ie.nodes,edges:ie.edges,focusNodeId:Y,showSecondaryEdges:J,isMobile:u,onSelectNode:E,onOpenNode:E,onNavigateNode:O})})}),u?e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 z-20 px-3 pt-2 lg:hidden",children:e.jsxs("div",{className:"pointer-events-auto flex items-center gap-1.5",children:[e.jsx("div",{title:Le,className:"shrink-0 rounded-full border border-white/10 bg-[rgba(8,12,20,0.78)] px-2 py-0.5 text-[9px] uppercase tracking-[0.18em] text-white/48 backdrop-blur",children:ve}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[e.jsxs("div",{className:"flex shrink-0 rounded-full border border-white/10 bg-[rgba(8,12,20,0.78)] p-0.5 shadow-[0_14px_42px_rgba(0,0,0,0.24)] backdrop-blur",children:[e.jsx("button",{type:"button",className:`rounded-full px-2 py-1 text-[10px] transition ${X==="graph"?"bg-white/[0.14] text-white":"text-white/52 hover:text-white"}`,onClick:()=>Ne(Z=>{Z.set("view","graph")}),children:"Graph"}),e.jsx("button",{type:"button",className:`rounded-full px-2 py-1 text-[10px] transition ${X==="hierarchy"?"bg-white/[0.14] text-white":"text-white/52 hover:text-white"}`,onClick:()=>Ne(Z=>{Z.set("view","hierarchy")}),children:"Hierarchy"})]}),e.jsx(W,{variant:"secondary",size:"sm",className:"h-7 rounded-full border-white/10 bg-[rgba(8,12,20,0.78)] px-2 text-[10px] text-white/68 backdrop-blur hover:text-white",onClick:()=>w(!0),"aria-label":"Open graph appearance settings",title:"Graph appearance settings",children:e.jsx(Po,{className:"size-3"})}),e.jsxs(W,{variant:"secondary",size:"sm",className:"h-7 rounded-full border-white/10 bg-[rgba(8,12,20,0.78)] px-2 text-[10px] text-white/68 backdrop-blur hover:text-white",onClick:()=>{p(!1),b(!0)},"aria-label":"Open graph filters",children:[e.jsx(Ki,{className:"size-3"}),"Search"]})]})]})}):null,st?e.jsxs("div",{className:"pointer-events-none absolute inset-x-0 top-0 z-20 px-4 pt-3 lg:px-6",children:[e.jsxs("div",{"data-testid":"knowledge-graph-desktop-toolbar",className:"pointer-events-auto flex items-center gap-1.5",children:[e.jsx("div",{"data-testid":"knowledge-graph-count-pill",title:Le,className:"shrink-0 rounded-full border border-white/10 bg-[rgba(8,12,20,0.78)] px-2 py-0.5 text-[9px] uppercase tracking-[0.18em] text-white/48 backdrop-blur",children:ve}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(mi,{title:"",description:"",compact:!0,minimal:!0,hideSummary:!0,query:S,onQueryChange:y,onQuerySubmit:M,submitLabel:"Search graph",options:ge,selectedOptionIds:Te,onSelectedOptionIdsChange:Z=>{const De=Lp(Z);Ne(ee=>{Ss(ee,"entityKind",De.entityKinds),Ss(ee,"relationKind",De.relationKinds),Ss(ee,"tag",De.tags),Ss(ee,"owner",De.owners)})},resultSummary:"",placeholder:"Type a graph search, then press Enter or the search button"})}),e.jsxs(W,{variant:"secondary",size:"sm",className:"h-7 rounded-full border-white/10 bg-[rgba(8,12,20,0.78)] px-2 text-[10px] text-white/68 backdrop-blur hover:text-white",onClick:()=>C(Z=>!Z),children:[e.jsx(Ki,{className:"size-3"}),"Advanced"]}),Qe?e.jsx(W,{variant:"secondary",size:"sm",className:"h-7 rounded-full border-white/10 bg-[rgba(8,12,20,0.78)] px-2 text-[10px] text-white/68 backdrop-blur hover:text-white",onClick:Ee,children:"Reset"}):null]}),e.jsx(Jn,{initial:!1,children:A?e.jsx(Ts.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},transition:{duration:.18,ease:"easeOut"},className:"pointer-events-auto mt-2 ml-auto max-w-[min(54rem,calc(100%-3.5rem))] rounded-[20px] border border-white/10 bg-[rgba(8,12,20,0.88)] p-3 shadow-[0_20px_60px_rgba(0,0,0,0.32)] backdrop-blur",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.4fr)_minmax(17rem,1fr)]",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx(mt,{options:qe,selectedValues:z,onChange:Z=>Ne(De=>{Ss(De,"entityKind",Z)}),placeholder:"Filter by entity type",emptyMessage:"No entity kinds match the current graph."}),e.jsx(mt,{options:oe,selectedValues:K,onChange:Z=>Ne(De=>{Ss(De,"relationKind",Z)}),placeholder:"Filter by relation type",emptyMessage:"No relation kinds match the current graph."}),e.jsx(mt,{options:L,selectedValues:$,onChange:Z=>Ne(De=>{Ss(De,"tag",Z)}),placeholder:"Filter by tag",emptyMessage:"No tags are available in the current filtered graph."}),e.jsx(mt,{options:U,selectedValues:D,onChange:Z=>Ne(De=>{Ss(De,"owner",Z)}),placeholder:"Filter by owner",emptyMessage:"No owners match the current graph."})]}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] border border-white/10 bg-white/[0.03] p-3",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.18em] text-white/46",children:[e.jsx("span",{children:"Max nodes shown"}),e.jsx("span",{children:G})]}),e.jsx("input",{type:"range",min:ac,max:ic,step:20,value:G,onChange:Z=>Ne(De=>{De.set("limit",Z.target.value)}),className:"w-full accent-[var(--secondary)]"}),e.jsx("div",{className:"text-xs text-white/42",children:"The graph stays deterministic under the cap and focus mode redistributes the visible neighborhood around the selected node."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Updated from"}),e.jsx(ye,{type:"date",value:Bs(_),min:Bs(ie.facets.updatedAt.min),max:Bs(B??ie.facets.updatedAt.max),onChange:Z=>Ne(De=>{Z.target.value?De.set("updatedFrom",Z.target.value):De.delete("updatedFrom")})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Updated to"}),e.jsx(ye,{type:"date",value:Bs(B),min:Bs(_??ie.facets.updatedAt.min),max:Bs(ie.facets.updatedAt.max),onChange:Z=>Ne(De=>{Z.target.value?De.set("updatedTo",Z.target.value):De.delete("updatedTo")})})]})]}),X==="hierarchy"?e.jsx(W,{variant:J?"primary":"secondary",size:"sm",className:"h-8 rounded-full px-3 text-xs",onClick:()=>Ne(Z=>{J?Z.delete("cross"):Z.set("cross","1")}),children:J?"Hide cross-links":"Show cross-links"}):null]})]})}):null})]}):null,u?null:e.jsx("div",{className:"pointer-events-none absolute bottom-5 left-4 z-20 lg:left-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"pointer-events-auto flex shrink-0 rounded-full border border-white/10 bg-[rgba(8,12,20,0.82)] p-0.5 shadow-[0_14px_42px_rgba(0,0,0,0.24)] backdrop-blur",children:[e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-1.5 text-[10px] transition ${X==="graph"?"bg-white/[0.14] text-white":"text-white/52 hover:text-white"}`,onClick:()=>Ne(Z=>{Z.set("view","graph")}),children:"Graph"}),e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-1.5 text-[10px] transition ${X==="hierarchy"?"bg-white/[0.14] text-white":"text-white/52 hover:text-white"}`,onClick:()=>Ne(Z=>{Z.set("view","hierarchy")}),children:"Hierarchy"})]}),X==="graph"?e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>w(!0),title:"Graph appearance settings","aria-label":"Open graph appearance settings",children:e.jsx(Po,{className:"size-3.5"})}),e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.zoomIn()},title:"Zoom in","aria-label":"Zoom in",children:e.jsx(ds,{className:"size-3.5"})}),e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.zoomOut()},title:"Zoom out","aria-label":"Zoom out",children:e.jsx(Ig,{className:"size-3.5"})}),e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.recenterOnFocus()},disabled:!Ie.focusNode,title:"Recenter","aria-label":"Recenter",children:e.jsx(Mv,{className:"size-3.5"})}),e.jsx(W,{variant:"secondary",size:"sm",className:"pointer-events-auto size-8 rounded-full border-white/10 bg-[rgba(8,12,20,0.82)] p-0 text-white/72 backdrop-blur hover:text-white",onClick:()=>{var Z;return(Z=l.current)==null?void 0:Z.fit()},title:"Reset camera","aria-label":"Reset camera",children:e.jsx(Ev,{className:"size-3.5"})}),null]}):null]})})]}),e.jsx(pa,{open:g&&!!Ie.focusNode,onOpenChange:p,eyebrow:"Knowledge Graph",title:((he=Ie.focusNode)==null?void 0:he.title)??"Focus node",description:((we=Ie.focusNode)==null?void 0:we.subtitle)??"Inspect the selected node and move deeper into the graph.",children:e.jsx(Pf,{focus:Ie,onOpenPage:Z=>{p(!1),O(Z)},onOpenNotes:Z=>{p(!1),V(Z)},onOpenHierarchy:Z=>{p(!1),Se(Z)},onSelectNode:E,className:"border-0 bg-transparent p-0 shadow-none"})}),e.jsx(pa,{open:f,onOpenChange:b,eyebrow:"Knowledge Graph",title:"Filter graph",description:"Search the visible graph and adjust the focus cap without covering the canvas all the time.",children:e.jsxs("div",{className:"grid gap-4 pb-2",children:[e.jsx("div",{className:"rounded-[22px] border border-[var(--ui-border-subtle)] bg-[rgba(255,255,255,0.03)] p-3",children:e.jsx(mi,{title:"",description:"",compact:!0,query:S,onQueryChange:y,onQuerySubmit:M,submitLabel:"Search graph",options:ge,selectedOptionIds:Te,onSelectedOptionIdsChange:Z=>{const De=Lp(Z);Ne(ee=>{Ss(ee,"entityKind",De.entityKinds),Ss(ee,"relationKind",De.relationKinds),Ss(ee,"tag",De.tags),Ss(ee,"owner",De.owners)})},resultSummary:Le,placeholder:"Type a graph search, then press Enter or the search button"})}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx(mt,{options:qe,selectedValues:z,onChange:Z=>Ne(De=>{Ss(De,"entityKind",Z)}),placeholder:"Filter by entity type",emptyMessage:"No entity kinds match the current graph."}),e.jsx(mt,{options:oe,selectedValues:K,onChange:Z=>Ne(De=>{Ss(De,"relationKind",Z)}),placeholder:"Filter by relation type",emptyMessage:"No relation kinds match the current graph."}),e.jsx(mt,{options:L,selectedValues:$,onChange:Z=>Ne(De=>{Ss(De,"tag",Z)}),placeholder:"Filter by tag",emptyMessage:"No tags are available in the current filtered graph."}),e.jsx(mt,{options:U,selectedValues:D,onChange:Z=>Ne(De=>{Ss(De,"owner",Z)}),placeholder:"Filter by owner",emptyMessage:"No owners match the current graph."})]}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] border border-[var(--ui-border-subtle)] bg-[rgba(255,255,255,0.03)] p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.18em] text-white/46",children:[e.jsx("span",{children:"Max nodes shown"}),e.jsx("span",{children:G})]}),e.jsx("input",{type:"range",min:ac,max:ic,step:20,value:G,onChange:Z=>Ne(De=>{De.set("limit",Z.target.value)}),className:"w-full accent-[var(--secondary)]"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Updated from"}),e.jsx(ye,{type:"date",value:Bs(_),min:Bs(ie.facets.updatedAt.min),max:Bs(B??ie.facets.updatedAt.max),onChange:Z=>Ne(De=>{Z.target.value?De.set("updatedFrom",Z.target.value):De.delete("updatedFrom")})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Updated to"}),e.jsx(ye,{type:"date",value:Bs(B),min:Bs(_??ie.facets.updatedAt.min),max:Bs(ie.facets.updatedAt.max),onChange:Z=>Ne(De=>{Z.target.value?De.set("updatedTo",Z.target.value):De.delete("updatedTo")})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:Ee,children:"Reset"}),e.jsx(W,{variant:"primary",size:"sm",onClick:()=>b(!1),children:"Done"})]})]})]})}),e.jsx(Yt,{open:T,onOpenChange:w,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(es,{className:"fixed inset-x-4 top-[max(1rem,env(safe-area-inset-top))] z-50 max-h-[calc(100dvh-2rem)] overflow-y-auto rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(16,23,36,0.98),rgba(8,12,22,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.48)] md:left-1/2 md:right-auto md:w-[min(40rem,calc(100vw-3rem))] md:-translate-x-1/2",children:[e.jsx(ts,{className:"sr-only",children:"Knowledge Graph appearance settings"}),e.jsx(rs,{className:"sr-only",children:"Tune the graph focus physics and appearance response."}),e.jsxs("div",{className:"sticky top-0 z-10 flex items-start justify-between gap-4 border-b border-white/8 bg-[rgba(8,12,22,0.9)] px-5 py-4 backdrop-blur-xl",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Graph appearance"}),e.jsx("div",{className:"font-display text-2xl text-white",children:"Tune the focus field"}),e.jsx("p",{className:"max-w-xl text-sm leading-6 text-white/55",children:"Shape how strongly a focused node opens its neighborhood and how far that pressure diffuses through connected hops."})]}),e.jsx(Qt,{asChild:!0,children:e.jsx(Zi,{"aria-label":"Close graph appearance settings"})})]}),e.jsxs("div",{className:"grid gap-4 px-5 py-5",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Focused repulsion"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Push nearby nodes apart more aggressively while the focused node stays anchored."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusRepulsion.toFixed(2)})]}),e.jsx("input",{"aria-label":"Focused repulsion",type:"range",min:"0.6",max:String(fw),step:"0.05",value:N.focusRepulsion,onChange:Z=>xe("focusRepulsion",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Focus diffusion"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Extend the focus field further through multi-hop neighbors and lengthen the reversible transition."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusDiffusion.toFixed(2)})]}),e.jsx("input",{"aria-label":"Focus diffusion",type:"range",min:"0.6",max:String(bw),step:"0.05",value:N.focusDiffusion,onChange:Z=>xe("focusDiffusion",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Spring reduction max"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Reduce edge spring constants most strongly around the focused node so its local neighborhood can open more freely."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusSpringReductionMax.toFixed(2)})]}),e.jsx("input",{"aria-label":"Spring reduction max",type:"range",min:"0",max:String(ww),step:"0.02",value:N.focusSpringReductionMax,onChange:Z=>xe("focusSpringReductionMax",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Spring reduction diffusion"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Spread that spring softening progressively through first-hop, second-hop, and more distant neighborhoods."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusSpringReductionDiffusion.toFixed(2)})]}),e.jsx("input",{"aria-label":"Spring reduction diffusion",type:"range",min:"0.6",max:String(yw),step:"0.05",value:N.focusSpringReductionDiffusion,onChange:Z=>xe("focusSpringReductionDiffusion",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Edge spring strength"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Lower this to loosen graph edges globally and let neighborhoods spread instead of snapping tightly inward."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.edgeSpringStrength.toFixed(2)})]}),e.jsx("input",{"aria-label":"Edge spring strength",type:"range",min:String(vw),max:String(jw),step:"0.05",value:N.edgeSpringStrength,onChange:Z=>xe("edgeSpringStrength",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Gravity strength"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Reduce this to weaken the global inward pull that compacts the whole graph toward the middle."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.gravityStrength.toFixed(2)})]}),e.jsx("input",{"aria-label":"Gravity strength",type:"range",min:"0",max:String(Nw),step:"0.05",value:N.gravityStrength,onChange:Z=>xe("gravityStrength",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]}),e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/10 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:"text-sm font-medium text-white",children:"Focus shell spacing"}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Increase this to push focused rings farther outward and visibly open the local structure."})]}),e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-xs text-white/72",children:N.focusShellSpacing.toFixed(2)})]}),e.jsx("input",{"aria-label":"Focus shell spacing",type:"range",min:String(kw),max:String(Sw),step:"0.05",value:N.focusShellSpacing,onChange:Z=>xe("focusShellSpacing",Number(Z.target.value)),className:"w-full accent-[var(--secondary)]"})]})]}),e.jsx("div",{className:"rounded-[24px] border border-white/8 bg-[rgba(125,211,252,0.07)] px-4 py-3 text-sm leading-6 text-white/62",children:"The main cramming forces are the edge springs and the inward gravity pull. Lower edge spring strength or gravity strength to let the whole graph breathe more, then raise focus shell spacing and spring-reduction controls when you want a selected neighborhood to open dramatically."}),e.jsxs("div",{className:"flex flex-wrap justify-between gap-3",children:[e.jsx(W,{variant:"secondary",onClick:()=>P(oa),children:"Reset defaults"}),e.jsx(Qt,{asChild:!0,children:e.jsx(W,{variant:"primary",children:"Done"})})]})]})]})]})}),null]})}const Pr=20,Dp=288,fa={top:16,right:18,bottom:28,left:42},Uo=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function rC(t,s){return Uo.map((a,i)=>({weekday:i,baselineDailyAp:t.baselineDailyAp,points:t.currentCurve.map(r=>({...r,locked:i===s?r.locked:!1}))}))}function uu(t){return`${Number(t.toFixed(1))} AP`}function Da(t){return`${Number(t.toFixed(1))} AP/h`}function rc(t){const s=new Date(2026,0,1,0,t,0,0);return new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(s)}function nC(t){const s=new Date(2026,0,1,0,t,0,0);return new Intl.DateTimeFormat(void 0,{hour:"numeric"}).format(s)}function Pa(t,s,a){return Math.min(a,Math.max(s,t))}function lC(t){if(t.length<2)return 0;let s=0;for(let a=0;a<t.length-1;a+=1){const i=t[a],r=t[a+1];s+=(i.rateApPerHour+r.rateApPerHour)/2*((r.minuteOfDay-i.minuteOfDay)/60)}return s}function Fp(t,s){if(t.length===0)return 0;if(s<=t[0].minuteOfDay)return t[0].rateApPerHour;for(let a=0;a<t.length-1;a+=1){const i=t[a],r=t[a+1];if(s<=r.minuteOfDay){const n=Math.max(1,r.minuteOfDay-i.minuteOfDay),l=(s-i.minuteOfDay)/n;return i.rateApPerHour+(r.rateApPerHour-i.rateApPerHour)*l}}return t[t.length-1].rateApPerHour}function oC(t,s){const a=lC(t);if(a<=0||s<=0)return t.map(r=>({...r,rateApPerHour:0}));const i=s/a;return t.map(r=>({...r,rateApPerHour:Number((r.rateApPerHour*i).toFixed(4))}))}function dC(t,s,a){var m;if(s<=0||s>=t.length-1)return((m=t[s])==null?void 0:m.rateApPerHour)??0;const i=t[s-1],r=t[s],n=t[s+1];let l=0;for(let h=0;h<t.length-1;h+=1){if(h===s-1||h===s)continue;const u=t[h],x=t[h+1];l+=(u.rateApPerHour+x.rateApPerHour)/2*((x.minuteOfDay-u.minuteOfDay)/60)}const o=Math.max(Pr/60,(r.minuteOfDay-i.minuteOfDay)/60),d=Math.max(Pr/60,(n.minuteOfDay-r.minuteOfDay)/60);return Math.max(0,(2*(a-l)-i.rateApPerHour*o-n.rateApPerHour*d)/(o+d))}function cC(t){switch(t){case"danger":return"bg-rose-400/12 text-rose-100";case"warning":return"bg-amber-400/12 text-amber-100";case"success":return"bg-emerald-400/12 text-emerald-100";case"info":default:return"bg-sky-400/12 text-sky-100"}}function uC(t){switch(t){case"primary":return"Primary";case"secondary":return"Secondary";case"recovery":return"Recovery";case"background":default:return"Ambient"}}function Tw(t){return t.spentTodayAp>t.dailyBudgetAp?"Over budget":t.spentTodayAp<t.targetBandMinAp?"Below target band":"Inside target band"}function mC(t){return t.overloadApPerHour>0||t.instantFreeApPerHour<=0?"Recovery":t.instantCapacityApPerHour>=t.currentDrainApPerHour+4?"Deep work":"Low-friction admin"}function hC({lifeForce:t}){return e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Daily AP"}),e.jsxs("div",{className:"mt-2 font-display text-4xl text-[var(--primary)]",children:[Math.round(t.spentTodayAp),e.jsxs("span",{className:"ml-2 text-lg text-white/44",children:["/ ",Math.round(t.dailyBudgetAp)]})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:["Target band ",Math.round(t.targetBandMinAp),"-",Math.round(t.targetBandMaxAp)," AP"]}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:Tw(t)})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Instant headroom"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:t.instantFreeApPerHour.toFixed(1)}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:[Da(t.instantCapacityApPerHour)," capacity minus"," ",Da(t.currentDrainApPerHour)," load"]}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:t.overloadApPerHour>0?`${Da(t.overloadApPerHour)} overloaded`:"No overload right now"})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Fatigue buffer"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:t.fatigueBufferApPerHour.toFixed(1)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Short-term strain rises with overlap and falls with recovery."})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Forecast"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:Math.round(t.forecastAp)}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:["Planned remaining ",uu(t.plannedRemainingAp)]}),e.jsxs("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:["Remaining ",uu(t.remainingAp)]})]})]})}function pC({lifeForce:t}){return e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-6",children:t.stats.map(s=>e.jsxs(ce,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:s.label}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:["L",s.level]})]}),e.jsxs("div",{className:"mt-3 text-2xl font-semibold text-white",children:[Math.round(s.xp)," XP"]}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:s.key==="life_force"?`+${Math.round((s.costModifier-1)*100)}% daily resilience`:`${Math.round((1-s.costModifier)*100)}% cost relief`})]},s.key))})}function xC({lifeForce:t,weekday:s,points:a,baselineDailyAp:i,isDirty:r,isSaving:n,onChange:l,onReset:o,onSave:d,onWeekdayChange:m}){var Y,z;const h=c.useRef(null),[u,x]=c.useState(null),[g,p]=c.useState(720),[f,b]=c.useState(null),A=c.useMemo(()=>new Date().getDay(),[]),C=c.useMemo(()=>{const K=new Date;return K.getHours()*60+K.getMinutes()},[]),T=c.useMemo(()=>[...a].sort((K,$)=>K.minuteOfDay-$.minuteOfDay),[a]),w=c.useMemo(()=>T.map(K=>({...K,locked:s===A?K.minuteOfDay<=C:!1})),[C,T,A,s]),S=c.useMemo(()=>{const K=Math.max(t.instantCapacityApPerHour,...w.map($=>$.rateApPerHour),8);return Math.max(12,Math.ceil(K*1.25))},[t.instantCapacityApPerHour,w]),y=c.useMemo(()=>w.map(K=>({...K,label:rc(K.minuteOfDay)})),[w]),N=c.useMemo(()=>[0,240,480,720,960,1200,1440],[]),P=c.useMemo(()=>Array.from(new Set([0,Math.max(2,Math.round(S/3)),Math.max(4,Math.round(2*S/3)),S])).sort((K,$)=>K-$),[S]),v=Math.max(g,1),H=Math.max(160,v-fa.left-fa.right),j=Dp-fa.top-fa.bottom;c.useEffect(()=>{const K=()=>{var D;const $=((D=h.current)==null?void 0:D.clientWidth)??0;p($>0?$:720)};return K(),window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[]),c.useEffect(()=>{if(u===null||!h.current)return;const K=h.current,$=J=>{if(J.pointerId!==u.pointerId)return;J.preventDefault();const q=K.getBoundingClientRect(),_=Number.isFinite(J.clientX)?J.clientX:q.left+u.pointerX,B=Number.isFinite(J.clientY)?J.clientY:q.top+u.pointerY,G=Pa(_-q.left,0,q.width),ae=Pa(B-q.top,0,q.height),ke=Pa(_-q.left-fa.left,0,H),Ae=Pa(B-q.top-fa.top,0,j);l(w.map((ie,Ie)=>{if(Ie!==u.index)return{minuteOfDay:ie.minuteOfDay,rateApPerHour:ie.rateApPerHour,locked:ie.locked};if(ie.locked||Ie===0||Ie===w.length-1)return{minuteOfDay:ie.minuteOfDay,rateApPerHour:ie.rateApPerHour,locked:ie.locked};const Ne=w[Ie-1].minuteOfDay+Pr,M=w[Ie+1].minuteOfDay-Pr,E=Math.round(Pa(ke/H*1440,Ne,M)),O=w.map(Se=>({minuteOfDay:Se.minuteOfDay,rateApPerHour:Se.rateApPerHour,locked:Se.locked}));O[Ie]={...O[Ie],minuteOfDay:E};const xe=dC(O,Ie,i),V=Pa((j-Ae)/j*S,0,Math.max(0,xe));return O[Ie]={...O[Ie],rateApPerHour:Number(V.toFixed(3))},O[Ie]})),x(ie=>ie===null||ie.pointerId!==J.pointerId?ie:{...ie,pointerX:G,pointerY:ae})},D=J=>{(!J||J.pointerId===u.pointerId)&&x(null)};return window.addEventListener("pointermove",$,{passive:!1}),window.addEventListener("pointerup",D),window.addEventListener("pointercancel",D),()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",D),window.removeEventListener("pointercancel",D)}},[i,u,l,j,H,w,S]);const R=c.useMemo(()=>{if(!f)return[];const K=w[f.index]??null;return[{id:"remove-point",label:"Remove point",description:K===null?"No turn point is selected.":`Delete the turn point at ${rc(K.minuteOfDay)}.`,icon:Rt,tone:"danger",disabled:K===null||f.index===0||f.index===w.length-1,onSelect:()=>{l(w.filter(($,D)=>D!==f.index))}},{id:"flatten-point",label:"Flatten point",description:K===null?"No turn point is selected.":"Place the handle back on the interpolated segment between its neighbors.",icon:Gs,disabled:K===null||f.index===0||f.index===w.length-1,onSelect:()=>{const $=w[f.index-1],D=w[f.index+1],J=Fp([$,D],K.minuteOfDay);l(w.map((q,_)=>_===f.index?{...q,rateApPerHour:Number(J.toFixed(3))}:q))}}]},[f,l,w]),Q=c.useMemo(()=>w.map(K=>({...K,x:fa.left+K.minuteOfDay/1440*H,y:fa.top+(1-K.rateApPerHour/Math.max(1,S))*j})),[j,H,w,S]),X=u===null?null:{pointerX:u.pointerX,pointerY:u.pointerY,constrainedX:((Y=Q[u.index])==null?void 0:Y.x)??u.pointerX,constrainedY:((z=Q[u.index])==null?void 0:z.y)??u.pointerY};return e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:"overflow-hidden p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force view"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:"Instant Life Force editor"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/56",children:"One click adds a turn point. Drag future handles. Right click a handle to remove or flatten it. The ghost handle follows your finger or cursor while the real turn point stays constrained on the curve and normalized to the baseline daily AP budget."})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1 rounded-full bg-white/[0.04] p-1",children:Uo.map((K,$)=>e.jsx("button",{type:"button",className:te("rounded-full px-3 py-1.5 text-[11px] font-medium transition",s===$?"bg-[var(--primary)] text-slate-950":"text-white/60 hover:bg-white/[0.05] hover:text-white"),onClick:()=>m($),children:K},K))}),e.jsx(W,{variant:"secondary",onClick:o,children:"Reset"}),e.jsxs(W,{onClick:d,pending:n,disabled:!r,children:[e.jsx(oi,{className:"mr-2 size-4"}),"Save curve"]})]})]}),e.jsxs("div",{className:"mt-4 rounded-[24px] bg-[linear-gradient(180deg,rgba(192,193,255,0.08),rgba(192,193,255,0.02))] p-3",children:[e.jsxs("div",{ref:h,className:te("relative h-72 w-full overflow-hidden rounded-[20px] bg-[rgba(255,255,255,0.02)]",u!==null?"select-none touch-none":""),style:{touchAction:u===null?"pan-y":"none"},role:"img","aria-label":"Life Force capacity curve editor",onClick:K=>{if(u!==null||!h.current||K.target!==K.currentTarget)return;const $=h.current.getBoundingClientRect(),D=Pa(K.clientX-$.left-fa.left,0,H),J=Math.round(D/H*1440),q=w.findIndex(ke=>ke.minuteOfDay>J);if(q<=0)return;const _=w[q-1],B=w[q];if(J-_.minuteOfDay<Pr||B.minuteOfDay-J<Pr)return;const G=Fp(w,J),ae=[...w];ae.splice(q,0,{minuteOfDay:J,rateApPerHour:Number(G.toFixed(3)),locked:s===A&&J<=C}),l(ae)},children:[e.jsxs(Er,{width:v,height:Dp,data:y,margin:fa,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"life-force-chart-fill",x1:"0",x2:"0",y1:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgba(192,193,255,0.24)"}),e.jsx("stop",{offset:"100%",stopColor:"rgba(192,193,255,0.02)"})]})}),e.jsx(Fn,{vertical:!1,stroke:"rgba(255,255,255,0.08)",strokeDasharray:"3 4"}),e.jsx(ai,{dataKey:"minuteOfDay",type:"number",domain:[0,1440],ticks:N,tickFormatter:nC,tick:{fill:"rgba(255,255,255,0.48)",fontSize:10},tickLine:!1,axisLine:{stroke:"rgba(255,255,255,0.12)"},children:e.jsx(Jm,{value:"Time",position:"insideBottom",offset:-10,fill:"rgba(255,255,255,0.38)",fontSize:10})}),e.jsx(ii,{type:"number",domain:[0,S],ticks:P,tick:{fill:"rgba(255,255,255,0.48)",fontSize:10},tickLine:!1,axisLine:{stroke:"rgba(255,255,255,0.12)"},width:34,children:e.jsx(Jm,{value:"AP/h",angle:-90,position:"insideLeft",fill:"rgba(255,255,255,0.38)",fontSize:10,style:{textAnchor:"middle"}})}),e.jsx(Lr,{cursor:{stroke:"rgba(255,255,255,0.18)",strokeDasharray:"3 4"},content:({active:K,payload:$})=>{var J;const D=K?(J=$==null?void 0:$[0])==null?void 0:J.payload:null;return D?e.jsxs("div",{className:"rounded-[16px] border border-white/10 bg-[rgba(10,15,27,0.95)] px-3 py-2 text-xs text-white shadow-[0_18px_50px_rgba(4,8,18,0.3)] backdrop-blur-xl",children:[e.jsx("div",{className:"font-medium text-white",children:D.label}),e.jsx("div",{className:"mt-1 text-white/60",children:Da(D.rateApPerHour)})]}):null}}),s===A?e.jsx(Dv,{x:C,stroke:"rgba(255,255,255,0.22)",strokeDasharray:"3 4"}):null,e.jsx(Za,{type:"linear",dataKey:"rateApPerHour",stroke:"none",fill:"url(#life-force-chart-fill)",isAnimationActive:!1}),e.jsx(Cg,{type:"linear",dataKey:"rateApPerHour",stroke:"rgba(214,215,255,0.95)",strokeWidth:1.5,dot:!1,activeDot:!1,isAnimationActive:!1})]}),X?e.jsxs("svg",{className:"pointer-events-none absolute inset-0 z-[15] h-full w-full","aria-hidden":"true",children:[e.jsx("line",{x1:X.constrainedX,y1:X.constrainedY,x2:X.pointerX,y2:X.pointerY,stroke:"rgba(214,215,255,0.38)",strokeDasharray:"4 5",strokeWidth:"1.5"}),e.jsx("circle",{cx:X.pointerX,cy:X.pointerY,r:"11",fill:"rgba(214,215,255,0.12)",stroke:"rgba(214,215,255,0.34)",strokeWidth:"1.5","data-testid":"life-force-ghost-handle"}),e.jsx("circle",{cx:X.pointerX,cy:X.pointerY,r:"3.5",fill:"rgba(255,255,255,0.44)"})]}):null,Q.map((K,$)=>{const D=$===0||$===Q.length-1,J=(u==null?void 0:u.index)===$,q=D?14:16,_=D?22:28;return e.jsx("button",{type:"button","aria-label":`Turn point at ${rc(K.minuteOfDay)}`,className:te("absolute z-20 flex items-center justify-center rounded-full transition-transform duration-75",K.locked||D?"cursor-not-allowed":"cursor-grab active:cursor-grabbing",J?"scale-110":""),style:{left:K.x-_/2,top:K.y-_/2,width:_,height:_,touchAction:"none"},onPointerDown:B=>{if(B.preventDefault(),B.stopPropagation(),K.locked||D||!h.current)return;"setPointerCapture"in B.currentTarget&&B.currentTarget.setPointerCapture(B.pointerId);const G=h.current.getBoundingClientRect(),ae=Number.isFinite(B.clientX)?B.clientX:G.left+K.x,ke=Number.isFinite(B.clientY)?B.clientY:G.top+K.y;x({index:$,pointerId:B.pointerId,pointerX:Pa(ae-G.left,0,G.width),pointerY:Pa(ke-G.top,0,G.height)})},onContextMenu:B=>{B.preventDefault(),B.stopPropagation(),b({index:$,position:{x:B.clientX+6,y:B.clientY+6}})},children:e.jsx("span",{className:te("pointer-events-none inline-flex rounded-full border border-[rgba(10,15,27,0.92)] shadow-[0_0_0_1px_rgba(255,255,255,0.08),0_10px_24px_rgba(4,8,18,0.28)]",K.locked||D?"bg-white/55":"bg-white"),style:{width:q,height:q,opacity:J?.96:1}})},`${K.minuteOfDay}-${$}`)})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2 px-1 text-[11px] text-white/42",children:[e.jsxs("div",{children:["Editing ",Uo[s]," curve"]}),e.jsxs("div",{children:[Math.round(i)," AP/day baseline"]})]})]})]}),e.jsx(vd,{open:f!==null,title:"Turn point actions",subtitle:"Delete the turn point or flatten it back onto the surrounding segment.",items:R,position:(f==null?void 0:f.position)??null,onClose:()=>b(null)})]})}function gC(){return e.jsx(ce,{className:"overflow-hidden p-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force studio"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:"Edit weekday curves in the dedicated view"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/56",children:"The full weekday editor, turn-point menu, and curve calibration now live in their own page so Overview can stay fast and readable."})]}),e.jsxs(Je,{to:"/life-force",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center gap-2 overflow-hidden whitespace-nowrap rounded-[var(--radius-control)] border border-[var(--primary)]/14 bg-[var(--ui-accent-soft)] px-3 py-2 text-[13px] font-medium text-[var(--ui-ink-on-accent)] shadow-[var(--ui-shadow-soft)] transition hover:bg-[var(--ui-accent-soft-hover)]",children:[e.jsx(Vi,{className:"size-4"}),"Open Life Force studio"]})]})})}function fC({drains:t,plannedDrains:s,warnings:a,recommendations:i}){return e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ce,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Current drains"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:"What is consuming Life Force now"})]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[t.length," active"]})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:t.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:"No current drainers are active. This is a good moment to choose your next intentional action."}):t.map(r=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-base font-semibold text-white",children:r.title}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:r.why})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"text-base font-semibold text-[var(--primary)]",children:Da(r.apPerHour)}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-[0.14em] text-white/38",children:uC(r.role)})]})]})},r.id))})]}),e.jsxs(ce,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Planned drains"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:"What the rest of today is already asking from you"})]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[s.length," planned"]})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:s.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:"No future AP load has been forecast yet. The day is still open."}):s.slice(0,6).map(r=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-base font-semibold text-white",children:r.title}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:r.why})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"text-base font-semibold text-[var(--primary)]",children:uu(r.instantAp)}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-[0.14em] text-white/38",children:Da(r.apPerHour)})]})]})},r.id))})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Warnings"}),e.jsx("div",{className:"mt-4 grid gap-3",children:a.map(r=>e.jsxs("div",{className:te("rounded-[18px] px-4 py-4",cC(r.tone)),children:[e.jsx("div",{className:"text-sm font-semibold",children:r.title}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-current/80",children:r.detail})]},r.id))})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Recommendations"}),e.jsx("div",{className:"mt-4 grid gap-2",children:i.map((r,n)=>e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/66",children:r},`${r}-${n}`))})]})]})]})}function Pw({lifeForce:t,onTired:s,onOkayAgain:a,tiredPending:i,okayPending:r,feedback:n}){return e.jsxs(ce,{className:"overflow-hidden p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force now"}),e.jsxs("div",{className:"mt-2 text-2xl font-semibold text-white",children:[t.instantFreeApPerHour.toFixed(1)," AP/h free"]}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:[Math.round(t.spentTodayAp)," / ",Math.round(t.dailyBudgetAp)," AP used today"]}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:Tw(t)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(W,{variant:"secondary",onClick:s,pending:i,children:[e.jsx($u,{className:"mr-2 size-4"}),"I'm getting tired"]}),e.jsxs(W,{variant:"secondary",onClick:a,pending:r,children:[e.jsx(Ou,{className:"mr-2 size-4"}),"I'm okay again"]})]})]}),n?e.jsx("div",{className:"mt-4 rounded-[18px] bg-[var(--primary)]/10 px-4 py-3 text-sm text-white/74",children:n}):null,e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx(Vi,{className:"size-4 text-[var(--primary)]"}),"Instant capacity"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Da(t.instantCapacityApPerHour)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx(sd,{className:"size-4 text-[var(--primary)]"}),"Current load"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Da(t.currentDrainApPerHour)}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:t.overloadApPerHour>0?`${Da(t.overloadApPerHour)} overload`:"Inside instant limit"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx(Lv,{className:"size-4 text-[var(--primary)]"}),"Next move"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:t.recommendations[0]??"Favor the next clean, manageable action."}),e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.14em] text-white/38",children:mC(t)})]})]})]})}function Aw({selectedUserIds:t,fallbackLifeForce:s,onRefresh:a,showEditor:i=!0}){var S,y;const r=ct(),n=new Date().getDay(),[l,o]=c.useState(n),d=Fe({queryKey:["forge-life-force",...t],queryFn:()=>Ji(t),initialData:s===void 0?void 0:{lifeForce:s,templates:Uo.map((N,P)=>({weekday:P,baselineDailyAp:s.baselineDailyAp,points:s.currentCurve.map(v=>({...v,locked:P===n?v.locked:!1}))}))}}),m=((S=d.data)==null?void 0:S.lifeForce)??s,u=(((y=d.data)==null?void 0:y.templates)??rC(m,n)).find(N=>N.weekday===l)??{weekday:l,baselineDailyAp:m.baselineDailyAp,points:m.currentCurve},[x,g]=c.useState(u.points),[p,f]=c.useState(!1),[b,A]=c.useState(null);c.useEffect(()=>{g(u.points),f(!1)},[u.points,u.weekday]);const C=Re({mutationFn:N=>xj(u.weekday,{points:oC(N,u.baselineDailyAp)},t),onSuccess:async N=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),g(N.points),f(!1)}}),T=Re({mutationFn:()=>Do({signalType:"tired"},t),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),A("Tiredness signal applied. Today’s Life Force now reflects the extra strain.")}}),w=Re({mutationFn:()=>Do({signalType:"okay_again"},t),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),A("Recovery signal applied. Instant strain has been eased for the rest of today.")}});return e.jsxs("div",{className:"grid gap-4",children:[e.jsx(hC,{lifeForce:m}),e.jsx(pC,{lifeForce:m}),e.jsx(Pw,{lifeForce:m,onTired:()=>{T.mutateAsync()},onOkayAgain:()=>{w.mutateAsync()},tiredPending:T.isPending,okayPending:w.isPending,feedback:b}),i?e.jsx(xC,{lifeForce:m,weekday:l,points:x,baselineDailyAp:u.baselineDailyAp,isDirty:p,isSaving:C.isPending,onWeekdayChange:o,onChange:N=>{g(N),f(!0)},onReset:()=>{g(u.points),f(!1)},onSave:()=>{C.mutateAsync(x)}}):e.jsx(gC,{}),e.jsx(fC,{drains:m.activeDrains,plannedDrains:m.plannedDrains,warnings:m.warnings,recommendations:m.recommendations}),m.topTaskIdsNeedingSplit.length>0?e.jsxs(ce,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-white",children:[e.jsx(ad,{className:"size-4 text-[var(--primary)]"}),"Tasks asking to be split"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:m.topTaskIdsNeedingSplit.map(N=>e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:N},N))})]}):null]})}function bC({selectedUserIds:t,fallbackLifeForce:s,onRefresh:a}){var u;const i=Array.isArray(t)?t:[],r=ct(),l=((u=Fe({queryKey:["forge-life-force",...i],queryFn:()=>Ji(i),initialData:s===void 0?void 0:{lifeForce:s,templates:[]}}).data)==null?void 0:u.lifeForce)??s;if(!l)return e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:"Not calibrated yet"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Today can still load without a Life Force snapshot, but the AP and instant headroom model is not available for this state yet."})]});const[o,d]=c.useState(null),m=Re({mutationFn:()=>Do({signalType:"tired"},i),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),d("Tiredness signal applied. Today’s headroom has been reduced.")}}),h=Re({mutationFn:()=>Do({signalType:"okay_again"},i),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-life-force"]}),await Ut(r),a&&await a(),d("Recovery signal applied. Today’s headroom has been eased.")}});return e.jsx(Pw,{lifeForce:l,onTired:()=>{m.mutateAsync()},onOkayAgain:()=>{h.mutateAsync()},tiredPending:m.isPending,okayPending:h.isPending,feedback:o})}function wC(){const t=jt(),s=t.snapshot.lifeForce;return s?e.jsxs("div",{className:"grid gap-4",children:[e.jsx(nt,{title:"Life Force",titleText:"Life Force",description:"Edit weekday Action Point curves, inspect drains, and tune the capacity model without crowding the Overview surface.",badge:`${Math.round(s.spentTodayAp)} / ${Math.round(s.dailyBudgetAp)} AP`,actions:e.jsx(lu,{users:t.snapshot.users,selectedUserIds:t.selectedUserIds,onChange:t.setSelectedUserIds})}),e.jsx(Aw,{selectedUserIds:t.selectedUserIds,fallbackLifeForce:s,onRefresh:t.refresh,showEditor:!0})]}):e.jsx("div",{className:"grid gap-4",children:e.jsx(nt,{title:"Life Force",titleText:"Life Force",description:"Action Point capacity, weekday curves, and instant headroom editing live here.",badge:"Not calibrated yet"})})}function Mw({open:t,onOpenChange:s,place:a,seed:i,onSave:r}){const[n,l]=c.useState({label:(a==null?void 0:a.label)??(i==null?void 0:i.label)??"",latitude:String((a==null?void 0:a.latitude)??(i==null?void 0:i.latitude)??""),longitude:String((a==null?void 0:a.longitude)??(i==null?void 0:i.longitude)??""),radiusMeters:String((a==null?void 0:a.radiusMeters)??(i==null?void 0:i.radiusMeters)??100),categoryTags:((a==null?void 0:a.categoryTags)??(i==null?void 0:i.categoryTags)??[]).join(", ")});return c.useEffect(()=>{l({label:(a==null?void 0:a.label)??(i==null?void 0:i.label)??"",latitude:String((a==null?void 0:a.latitude)??(i==null?void 0:i.latitude)??""),longitude:String((a==null?void 0:a.longitude)??(i==null?void 0:i.longitude)??""),radiusMeters:String((a==null?void 0:a.radiusMeters)??(i==null?void 0:i.radiusMeters)??100),categoryTags:((a==null?void 0:a.categoryTags)??(i==null?void 0:i.categoryTags)??[]).join(", ")})},[a,i]),e.jsx(Yt,{open:t,onOpenChange:s,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs(es,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(32rem,calc(100vw-1.25rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ts,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:a?`Edit ${a.label}`:"New known place"}),e.jsx(rs,{className:"mt-1 text-sm text-white/58",children:"Define life landmarks once so the companion and web views can reason about stays and trips consistently."})]}),e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white",children:e.jsx(Tt,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsx(ye,{value:n.label,onChange:o=>l(d=>({...d,label:o.target.value})),placeholder:"Home, Main Office, Riverside path..."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(ye,{value:n.latitude,onChange:o=>l(d=>({...d,latitude:o.target.value})),placeholder:"Latitude"}),e.jsx(ye,{value:n.longitude,onChange:o=>l(d=>({...d,longitude:o.target.value})),placeholder:"Longitude"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[10rem_minmax(0,1fr)]",children:[e.jsx(ye,{value:n.radiusMeters,onChange:o=>l(d=>({...d,radiusMeters:o.target.value})),placeholder:"Radius meters"}),e.jsx(ye,{value:n.categoryTags,onChange:o=>l(d=>({...d,categoryTags:o.target.value})),placeholder:"home, gym, holiday, parents-house"})]})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx(W,{variant:"ghost",onClick:()=>s(!1),className:"border border-white/10 bg-white/[0.04]",children:"Cancel"}),e.jsx(W,{onClick:()=>void r({id:a==null?void 0:a.id,label:n.label,latitude:Number(n.latitude),longitude:Number(n.longitude),radiusMeters:Number(n.radiusMeters),categoryTags:n.categoryTags.split(",").map(o=>o.trim()).filter(Boolean)}).then(()=>s(!1)),children:"Save place"})]})]})]})})}const mu=1e3;function ps(t){return new Date(t).getTime()}function hu(t){return new Date(t).toISOString()}function _p(t,s){const a=ps(t.startedAt)-ps(s.startedAt);if(a!==0)return a;const i=ps(t.endedAt)-ps(s.endedAt);return i!==0?i:t.id.localeCompare(s.id)}function qm(t){return t.syncSource==="sleep overlay"}function yC(t){const s=[...t].filter(i=>ps(i.endedAt)>ps(i.startedAt)).sort((i,r)=>{const n=ps(i.startedAt)-ps(r.startedAt);if(n!==0)return n;const l=ps(i.endedAt)-ps(r.endedAt);return l!==0?l:i.id.localeCompare(r.id)});if(s.length===0)return[];const a=[];for(const i of s){const r=a.at(-1);if(!r){a.push(i);continue}const n=ps(r.endedAt);if(ps(i.startedAt)<=n+mu){const o=Math.max(n,ps(i.endedAt));a[a.length-1]={...r,id:`${r.id}__${i.id}`,endedAt:hu(o),asleepSeconds:(r.asleepSeconds??0)+(i.asleepSeconds??0)||null,timeInBedSeconds:(r.timeInBedSeconds??0)+(i.timeInBedSeconds??0)||null,sleepScore:i.sleepScore??r.sleepScore,regularityScore:i.regularityScore??r.regularityScore,efficiency:i.efficiency??r.efficiency,recoveryState:i.recoveryState??r.recoveryState};continue}a.push(i)}return a}function vC(t){const s=[];if(typeof t.asleepSeconds=="number"&&t.asleepSeconds>0){const a=t.asleepSeconds/3600;s.push(`${a.toFixed(a>=1?1:2)}h asleep`)}else if(typeof t.timeInBedSeconds=="number"&&t.timeInBedSeconds>0){const a=t.timeInBedSeconds/3600;s.push(`${a.toFixed(a>=1?1:2)}h in bed`)}return typeof t.sleepScore=="number"&&s.push(`score ${t.sleepScore}`),typeof t.regularityScore=="number"&&s.push(`regularity ${t.regularityScore}`),t.recoveryState&&s.push(t.recoveryState),s.join(" · ")||"Sleep session"}function jC(t){const s=Math.max(60,Math.round((ps(t.endedAt)-ps(t.startedAt))/1e3));return{id:`sleep-overlay-${t.id}`,boxId:`sleep-overlay-${t.id}`,kind:"stay",sourceKind:"automatic",origin:"recorded",editable:!1,isInvalid:!1,startedAt:t.startedAt,endedAt:t.endedAt,trueStartedAt:t.startedAt,trueEndedAt:t.endedAt,visibleStartedAt:t.startedAt,visibleEndedAt:t.endedAt,durationSeconds:s,laneSide:"left",connectorFromLane:"left",connectorToLane:"left",title:"Sleep",subtitle:vC(t),placeLabel:null,tags:["sleep"],syncSource:"sleep overlay",cursor:`${t.endedAt}::sleep-overlay-${t.id}`,overrideCount:0,overriddenAutomaticBoxIds:[],overriddenUserBoxIds:[],isFullyHidden:!1,rawStayIds:[],rawTripIds:[],rawPointCount:0,hasLegacyCorrections:!1,stay:null,trip:null}}function Rp(t,s,a){if(a<=s)return null;const i=hu(s),r=hu(a),n=Math.max(60,Math.round((a-s)/1e3));return{...t,id:`${t.id}::virtual-${s}-${a}`,startedAt:i,endedAt:r,trueStartedAt:i,trueEndedAt:r,visibleStartedAt:i,visibleEndedAt:r,durationSeconds:n,cursor:`${r}::${t.id}::virtual`}}function NC(t,s){let a=[...t].sort(_p);for(const i of yC(s)){const r=ps(i.startedAt),n=ps(i.endedAt),l=jC(i),o=[];let d=!1;for(const m of a){const h=ps(m.startedAt),u=ps(m.endedAt);if(u<=r||h>=n){!d&&h>=n&&(o.push(l),d=!0),o.push(m);continue}if(h<r){const x=Rp(m,h,Math.min(u,r-mu));x&&o.push(x)}if(d||(o.push(l),d=!0),u>n){const x=Rp(m,Math.max(h,n+mu),u);x&&o.push(x)}}d||o.push(l),a=o.sort(_p)}return a}const $p=24,ya=64,pu=360*60,Ew=5,nc=1,kC=104;function Xa(t){return t.trim().toLowerCase()}function rl(t){return t>=86400?`${Math.round(t/3600)}h`:t>=3600?`${(t/3600).toFixed(1)}h`:`${Math.max(1,Math.round(t/60))}m`}function ei(t){return new Intl.DateTimeFormat(void 0,{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function SC(t){return new Intl.DateTimeFormat(void 0,{day:"2-digit",month:"2-digit",year:"2-digit"}).format(new Date(t))}function IC(t){return new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:!1}).format(t)}function Br(t){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 Wo(t){if(!t.trim())return null;const s=new Date(t);return Number.isNaN(s.getTime())?null:s.toISOString()}function Ur(t){return t>=1e3?`${(t/1e3).toFixed(1)} km`:`${Math.round(t)} m`}function Ws(t){return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}).format(new Date(t))}function Op(t,s){return`${t.toFixed(3)}, ${s.toFixed(3)}`}function Gl(t,s){return`${t.toFixed(6)}, ${s.toFixed(6)}`}function zp(t){return`${Math.max(1,Math.round(t/60))} min`}function CC(t){if(t.length===0)return[];const s=Math.min(...t.map(o=>o.latitude)),a=Math.max(...t.map(o=>o.latitude)),i=Math.min(...t.map(o=>o.longitude)),r=Math.max(...t.map(o=>o.longitude)),n=Math.max(a-s,1e-4),l=Math.max(r-i,1e-4);return t.map((o,d)=>({...o,x:12+(o.longitude-i)/l*76,y:12+(1-(o.latitude-s)/n)*76,id:`${o.recordedAt??"point"}-${d}`}))}function xu(t){return!ka(t)||t.stay.place?null:{label:t.stay.label||t.title,latitude:t.stay.centerLatitude,longitude:t.stay.centerLongitude,radiusMeters:t.stay.radiusMeters,categoryTags:t.tags}}function Wi(t){var s;return t?t.kind==="stay"&&ka(t)?((s=t.stay.place)==null?void 0:s.label)??t.placeLabel??t.stay.label??null:t.placeLabel??null:null}function vo(t,s,a,i){const n=(a-t)*Math.PI/180,l=(i-s)*Math.PI/180,o=t*Math.PI/180,d=a*Math.PI/180,m=Math.sin(n/2)**2+Math.cos(o)*Math.cos(d)*Math.sin(l/2)**2;return 2*6371e3*Math.asin(Math.sqrt(m))}function TC(t){return Xa([t.label,...t.aliases].join(" "))}function Ho(t){return t.kind==="trip"&&t.trip!==null}function ka(t){return t.kind==="stay"&&t.stay!==null}function Hi(t,s,a){if(!t.trip)return{label:t.placeLabel??(s==="start"?"Known origin":"Known destination"),detail:Ws(s==="start"?t.startedAt:t.endedAt)};const i=s==="start"?t.trip.points[0]??null:t.trip.points[t.trip.points.length-1]??null,r=s==="start"?t.trip.startPlace:t.trip.endPlace,n=(a==null?void 0:a.includeCoordinates)??!0,l=a!=null&&a.useHistoryAnchorFallback&&s==="start"?"Beginning of history":null;return{label:(r==null?void 0:r.label)??l??(n&&i?Op(i.latitude,i.longitude):s==="start"?"Unknown origin":"Unknown destination"),detail:n&&i&&!r?Op(i.latitude,i.longitude):Ws(s==="start"?t.startedAt:t.endedAt)}}function PC(t){const s=t.trim().toLowerCase();return s==="travel"||s==="trip"||s==="move"}function AC(t){const s=t.title.trim().toLowerCase();return s.length===0||s==="stay"||s==="continued stay"||s==="repaired stay"?t.sourceKind==="user_defined"?t.origin==="user_invalidated"?"User invalidated movement":"User-defined missing data":"Missing data":t.title}function MC(t){const s=Wi(t),a=t.title.trim().toLowerCase(),i=a.length===0||a==="stay"||a==="continued stay"||a==="repaired stay"||a==="manual stay";return s&&i?s:t.title.trim()||s||"Stay"}function ti(t){if(qm(t))return"Sleep";if(t.kind==="missing")return AC(t);if(t.kind==="stay")return MC(t);if(t.kind==="trip"&&PC(t.title)){const s=Hi(t,"start").label,a=Hi(t,"end").label;return`${s} → ${a}`}return t.title}function Kp(t){return t==="left"?24:t==="right"?76:50}function EC(t,s,a){const i=Math.min(t,pu)/3600,r=a==="sleep overlay",n=r?144:s==="stay"?132:124,l=r?364:s==="stay"?404:328,o=n+i*44;return Math.max(n,Math.min(l,o))}function gu(t){var s;return{kind:t.kind,label:ka(t)?t.stay.label||t.title:Ho(t)&&t.trip.label||t.title,placeLabel:ka(t)?((s=t.stay.place)==null?void 0:s.label)??t.placeLabel??"":"",tagsInput:t.tags.join(", "),startedAtInput:Br(t.startedAt),endedAtInput:Br(t.endedAt)}}function lc(t,s){const a=(s==null?void 0:s.startedAt)??new Date(Date.now()-36e5).toISOString(),i=(s==null?void 0:s.endedAt)??new Date().toISOString();return{kind:t,label:t==="missing"?"User-defined missing data":t==="stay"?(s==null?void 0:s.placeLabel)||"Manual stay":"Manual move",placeLabel:(s==null?void 0:s.placeLabel)??"",tagsInput:t==="missing"?"user-defined, missing-data":t==="stay"?"user-defined, stay":"user-defined, move",startedAtInput:Br(a),endedAtInput:Br(i)}}function fu(t,s){var n,l;const a=t.tagsInput.split(",").map(o=>o.trim()).filter(Boolean),i=Wo(t.startedAtInput)??(s==null?void 0:s.startedAt)??new Date(Date.now()-3600*1e3).toISOString(),r=Wo(t.endedAtInput)??(s==null?void 0:s.endedAt)??new Date().toISOString();return{kind:t.kind,startedAt:i,endedAt:r,title:t.label.trim(),subtitle:t.kind==="missing"?"User-defined missing-data override.":"User-defined movement box.",placeLabel:t.placeLabel.trim()||null,tags:a,distanceMeters:t.kind==="trip"?Math.max(((n=s==null?void 0:s.trip)==null?void 0:n.distanceMeters)??150,150):null,averageSpeedMps:t.kind==="trip"?((l=s==null?void 0:s.trip)==null?void 0:l.averageSpeedMps)??null:null,metadata:{createdFrom:"movement-life-timeline"}}}function LC(t,s){var r,n;const a=t.kind==="stay"?((n=(r=t.stay)==null?void 0:r.label)==null?void 0:n.trim())??"":"";if(a)return a;const i=t.title.trim();return i&&i.toLowerCase()!=="stay"?i:s.trim()||"Stay"}function DC(t,s){const a=gu(t),i=s.trim();return fu({...a,label:LC(t,i),placeLabel:i},t)}function Lw(t){const s=new Date(t).getHours();return s<6?"night":s<12?"morning":s<18?"afternoon":"evening"}function Go(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function FC(t){var s,a,i;return Xa([t.kind,ti(t),t.subtitle,t.placeLabel??"",...t.tags,Go(t.startedAt),Go(t.endedAt),Lw(t.startedAt),ka(t)?((s=t.stay.place)==null?void 0:s.label)??t.stay.label:Ho(t)?[t.trip.label,t.trip.activityType,t.trip.travelMode,(a=t.trip.startPlace)==null?void 0:a.label,(i=t.trip.endPlace)==null?void 0:i.label].filter(Boolean).join(" "):t.kind==="trip"?[t.title,t.subtitle,t.placeLabel??""].filter(Boolean).join(" "):"missing data gap"].join(" "))}function _C(t){const s=new Map;s.set("kind:stay",{id:"kind:stay",label:"Stay",description:"Stationary spans and place anchors."}),s.set("kind:trip",{id:"kind:trip",label:"Move",description:"Trips and movement connectors."});for(const a of["night","morning","afternoon","evening"])s.set(`time:${a}`,{id:`time:${a}`,label:a[0].toUpperCase()+a.slice(1),description:"Filter by the segment start time."});for(const a of t){for(const i of a.tags)s.set(`tag:${i}`,{id:`tag:${i}`,label:i,description:"Movement tag"});a.placeLabel&&s.set(`place:${a.placeLabel}`,{id:`place:${a.placeLabel}`,label:a.placeLabel,description:"Matched place"})}return[...s.values()].sort((a,i)=>a.label.localeCompare(i.label))}function RC(t,s){return s.every(a=>a==="kind:stay"||a==="kind:trip"?t.kind===a.slice(5):a.startsWith("time:")?Lw(t.startedAt)===a.slice(5):a.startsWith("tag:")?t.tags.includes(a.slice(4)):a.startsWith("place:")?(t.placeLabel??"")===a.slice(6):!0)}function qp(t,s){return t&&{...t,pages:t.pages.map(a=>({...a,segments:a.segments.filter(i=>i.id!==s)}))}}function $C(t,s){const a=t+(Math.sin((t-.5)*Math.PI)+1)*.5-t,i=t-.5,n=.5+(i*(1-s*.64)+i*i*i*s*2.56);return Math.max(0,Math.min(1,n-(a-t)*s*.08))}function OC(t){return t.getHours()===0?SC(t.toISOString()):IC(t)}function zC(t,s){const a=new Date(t.endedAt).getTime(),i=new Date(t.startedAt).getTime(),r=Math.max(1,a-i),n=Math.max(0,Math.min(1,(s-i)/r));if(t.durationSeconds<=pu)return n;const l=Math.max(0,1-Math.min(1,pu/Math.max(1,t.durationSeconds)));return $C(n,l)}function KC(t,s,a){if(t.items.length===0)return null;const i=t.items[0];if(s<new Date(i.segment.startedAt).getTime())return t.historyHeaderHeight+t.leadHeight-(new Date(i.segment.startedAt).getTime()-s)/36e5*ya;for(let l=0;l<t.items.length;l+=1){const o=t.items[l],d=new Date(o.segment.startedAt).getTime(),m=new Date(o.segment.endedAt).getTime();if(s>=d&&s<=m)return o.boxTop+zC(o.segment,s)*o.displayHeight;const h=t.items[l+1]??null,u=h?new Date(h.segment.startedAt).getTime():a;if(s>m&&s<u)return o.boxBottom+(s-m)/36e5*ya}const r=t.items[t.items.length-1],n=new Date(r.segment.endedAt).getTime();return s>=n?r.boxBottom+(s-n)/36e5*ya:null}function qC(t){const s=new Date(t);s.setMinutes(0,0,0);const a=s.getTime();return a<=t?a+36e5:a}function BC(t,s){const a=[];if(t.items.length===0)return a;const i=t.items[0],r=new Date(i.segment.startedAt).getTime();for(let n=qC(r-Ew*36e5);n<=s;n+=36e5){const l=KC(t,n,s);if(l===null)continue;const o=new Date(n);a.push({y:l,label:OC(o),strong:o.getHours()===0})}return a}function UC({segments:t,viewportHeight:s,nowMs:a=Date.now()}){var g;const i=t.length>0?kC:0,r=t.length>0?ya*Ew:0;let n=i+r,l=null;const o=t.map(p=>{const f=EC(p.durationSeconds,p.kind,p.syncSource),b=new Date(p.startedAt).getTime(),A=l===null?0:Math.max(0,(b-l)/36e5)*ya;n+=A;const C=n,T=C+f;return n=T,l=new Date(p.endedAt).getTime(),{id:p.id,segment:p,gapBefore:A,displayHeight:f,boxTop:C,boxBottom:T}}),d=a+nc*36e5,m=(()=>{var b;const p=(b=t[t.length-1])==null?void 0:b.endedAt;if(!p)return ya*nc;const f=new Date(p).getTime();return Math.max(ya*nc,(d-f)/36e5*ya)})(),h=(((g=o[o.length-1])==null?void 0:g.boxBottom)??i+r)+m,u=Math.max(h,s>0?s+260:960,i+r+m),x={historyHeaderHeight:i,leadHeight:r,items:o,markers:[],rangeEndMs:d,futureTailHeight:m+Math.max(0,u-h),totalHeight:u};return{...x,markers:BC(x,d)}}function WC({layout:t,scrollTop:s,viewportHeight:a}){const i=ya*6,r=Math.max(0,s-i),n=Math.min(t.totalHeight,s+Math.max(a,ya*8)+i),l=t.markers.filter(o=>o.y>=r&&o.y<=n);return e.jsxs("div",{className:"pointer-events-none absolute inset-x-0 top-0 overflow-hidden rounded-[30px]",style:{height:`${t.totalHeight}px`},children:[e.jsx("div",{className:"absolute inset-y-0 left-0 w-18 bg-[linear-gradient(90deg,rgba(7,12,22,0.96),rgba(7,12,22,0.42),transparent)]"}),l.map((o,d)=>e.jsxs("div",{className:"absolute inset-x-0",style:{top:`${o.y}px`},children:[e.jsx("div",{className:te("border-t",o.strong?"border-white/14":"border-white/7")}),e.jsx("div",{className:te("absolute left-3 top-0 -translate-y-1/2 font-label text-[9px] tracking-[0.24em]",o.strong?"text-white/38":"text-white/22"),children:o.label})]},`timeline-grid-${d}`))]})}function HC({fromSide:t,toSide:s,height:a,emphasized:i}){const r=Kp(t),n=Kp(s),l=`M ${r} 16 C ${r} ${Math.max(40,a*.26)}, ${n} ${Math.max(70,a*.72)}, ${n} ${a-18}`;return e.jsxs("svg",{viewBox:`0 0 100 ${a}`,className:"absolute inset-x-0 top-0 h-full w-full overflow-visible",preserveAspectRatio:"none",children:[e.jsx("path",{d:l,fill:"none",stroke:i?"rgba(241,246,255,0.18)":"rgba(241,246,255,0.11)",strokeWidth:i?"1.05":"0.85",strokeDasharray:i?"3 10":"2.5 12",strokeLinecap:"round"}),e.jsx("circle",{cx:r,cy:"16",r:"1.5",fill:"rgba(255,255,255,0.26)"}),e.jsx("circle",{cx:n,cy:a-18,r:"1.5",fill:"rgba(255,255,255,0.26)"})]})}function bu({position:t}){return e.jsx("div",{className:te("absolute left-1/2 z-20 flex -translate-x-1/2 items-center justify-center",t==="top"?"-top-3":"-bottom-3"),children:e.jsx("div",{className:"h-6 w-[3px] rounded-full bg-[rgba(160,224,255,0.92)] shadow-[0_0_14px_rgba(126,229,255,0.36)]"})})}function GC({segment:t}){const s=(t==null?void 0:t.kind)==="stay"?t.placeLabel||t.title||null:(t==null?void 0:t.kind)==="trip"?Hi(t,"start",{includeCoordinates:!1,useHistoryAnchorFallback:!0}).label:null,a=s||"Beginning of time";return e.jsx("div",{className:"pointer-events-none flex justify-center px-6 py-4",children:e.jsxs("div",{className:"relative w-[min(18rem,calc(100vw-6rem))] overflow-hidden rounded-[26px] border border-[rgba(152,208,255,0.2)] bg-[linear-gradient(180deg,rgba(98,130,238,0.14),rgba(18,34,79,0.14))] shadow-[0_20px_48px_rgba(3,8,20,0.3)]",children:[e.jsx(bu,{position:"bottom"}),e.jsxs("div",{className:"relative z-10 px-5 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(I,{tone:"signal",className:"bg-white/10 text-white/78",children:"Start"}),e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.2em] text-white/28",children:"Beginning of history"})]}),e.jsx("div",{className:"mt-5 font-display text-[1.25rem] tracking-[-0.05em] text-white",children:a}),e.jsx("div",{className:"mt-2 font-label text-[10px] uppercase tracking-[0.22em] text-white/30",children:s?"Oldest loaded known stay":"Earliest known anchor"})]})]})})}function QC({segment:t,onEdit:s,onOpenDetail:a,onDefinePlace:i}){var n;const r=qm(t);return e.jsxs(ce,{className:"rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(9,14,26,0.98),rgba(5,9,19,0.95))] p-5 shadow-[0_24px_74px_rgba(0,0,0,0.34)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:r?"Sleep overlay":t.kind==="stay"?"Stay detail":t.kind==="trip"?"Move detail":"Missing data"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ti(t)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{className:r?"bg-cyan-400/14 text-cyan-100":t.sourceKind==="user_defined"?"bg-fuchsia-400/12 text-fuchsia-100":"bg-white/[0.06] text-white/70",children:r?"Virtual":t.sourceKind==="user_defined"?t.origin==="user_invalidated"?"User invalidated":"User-defined":"Automatic"}),t.overrideCount>0?e.jsxs(I,{className:"bg-amber-400/10 text-amber-100",children:["Overrides ",t.overrideCount," automatic box",t.overrideCount===1?"":"es"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{onClick:a,variant:"ghost",className:"rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/78 hover:bg-white/[0.08]",disabled:r,children:"Details"}),e.jsx(W,{onClick:s,variant:"ghost",className:"size-9 rounded-full border border-white/10 bg-white/[0.04] text-white/78 hover:bg-white/[0.08]","aria-label":"Edit movement segment",disabled:r||t.kind==="missing"||!t.editable,children:e.jsx(da,{className:"size-4"})}),e.jsx(Es,{className:"size-4 text-white/42"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Started"}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:ei(t.startedAt)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Ended"}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:ei(t.endedAt)})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{tone:"signal",children:rl(t.durationSeconds)}),Ho(t)?e.jsxs(e.Fragment,{children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Ur(t.trip.distanceMeters)}),t.trip.stops.length>0?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[t.trip.stops.length," stop",t.trip.stops.length===1?"":"s"]}):null]}):null,r?e.jsx(I,{className:"bg-cyan-400/12 text-cyan-50",children:t.subtitle}):Wi(t)?e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Wi(t)}):null]}),ka(t)&&!r?e.jsxs("div",{className:"mt-4 rounded-[18px] border border-sky-300/14 bg-sky-300/8 p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-sky-100/66",children:"Location label"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-sky-50/86",children:t.stay.place?`This stay is currently linked to ${t.stay.place.label}. Search saved places or relabel it from this stay center.`:"Search saved places for this stay, or create a new one from the stay center so later matching stays inherit it automatically."}),e.jsx("div",{className:"mt-3",children:e.jsx(W,{onClick:i,variant:"ghost",className:"rounded-full border border-sky-300/24 bg-sky-300/12 px-4 text-sky-50 hover:bg-sky-300/18",children:"Label location"})})]}):null,e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Timeline summary"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/76",children:t.kind==="stay"?r?`Sleep overlay from ${Ws(t.startedAt)} to ${Ws(t.endedAt)}. Underlying movement boxes are sliced virtually while this overlay is visible.`:`Stay block from ${Ws(t.startedAt)} to ${Ws(t.endedAt)}.`:t.kind==="trip"?`Connector from ${Hi(t,"start").label} to ${Hi(t,"end").label}.`:`No reliable movement signal reached Forge from ${Ws(t.startedAt)} to ${Ws(t.endedAt)}.`})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Projection model"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/76",children:r?"This sleep layer is visual only. Forge does not persist these split boxes; it temporarily slices the visible movement boxes around each sleep interval.":"Raw phone measurements stay immutable. Forge derives automatic boxes from that raw movement evidence, then overlays user-defined boxes on top without mutating the imported raw data."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:["Raw stays ",t.rawStayIds.length]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:["Raw trips ",t.rawTripIds.length]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:["Raw points ",t.rawPointCount]}),t.hasLegacyCorrections?e.jsx(I,{className:"bg-amber-400/10 text-amber-100",children:"Legacy corrections present"}):null]})]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-2 text-sm text-white/56",children:r?e.jsxs(e.Fragment,{children:[e.jsx(Wu,{className:"size-4 text-cyan-300"}),"Sleep overlay"]}):ka(t)?e.jsxs(e.Fragment,{children:[e.jsx(qu,{className:"size-4 text-[var(--primary)]"}),((n=t.stay.place)==null?void 0:n.label)??"No canonical place linked yet"]}):Ho(t)?e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"size-4 text-[var(--primary)]"}),t.trip.activityType||t.trip.travelMode]}):t.kind==="trip"?e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"size-4 text-[var(--primary)]"}),"Repaired movement connector"]}):e.jsxs(e.Fragment,{children:[e.jsx(_r,{className:"size-4 text-white/56"}),"Missing intervals are synthesized from long signal gaps instead of inventing fake travel."]})})]})}function Bp({title:t,points:s,averagePoint:a}){const i=CC(a?[...s,a]:s),r=a?i.length-1:i.length,n=i.slice(0,r),l=a?i[i.length-1]??null:null,o=n.map((d,m)=>`${m===0?"M":"L"} ${d.x} ${d.y}`).join(" ");return e.jsxs(ce,{className:"rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,13,25,0.95),rgba(10,17,30,0.88))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:t}),e.jsx("div",{className:"mt-2 text-sm text-white/62",children:"Relative coordinates normalized into one view so we can inspect the actual captured stay or trip geometry in one glance."}),e.jsx("div",{className:"mt-5 rounded-[24px] border border-white/8 bg-[rgba(255,255,255,0.03)] p-3",children:e.jsxs("svg",{viewBox:"0 0 100 100",className:"h-52 w-full",children:[e.jsx("rect",{x:"0",y:"0",width:"100",height:"100",rx:"18",fill:"rgba(255,255,255,0.02)"}),n.length>1?e.jsx("path",{d:o,fill:"none",stroke:"rgba(92,225,230,0.95)",strokeWidth:"1.6"}):null,n.map((d,m)=>e.jsx("circle",{cx:d.x,cy:d.y,r:m===0||m===n.length-1?2.2:1.4,fill:m===0||m===n.length-1?"#ffffff":"rgba(92,225,230,0.9)"},d.id)),l?e.jsxs(e.Fragment,{children:[e.jsx("circle",{cx:l.x,cy:l.y,r:3,fill:"rgba(255,208,88,0.95)"}),e.jsx("circle",{cx:l.x,cy:l.y,r:6,fill:"none",stroke:"rgba(255,208,88,0.48)",strokeWidth:"1",strokeDasharray:"2 2"})]}):null]})})]})}function VC({open:t,onOpenChange:s,segment:a,detail:i,loading:r,onEdit:n,onDefinePlace:l}){var h;const o=(i==null?void 0:i.segment)??a,d=(i==null?void 0:i.stayDetail)??null,m=(i==null?void 0:i.tripDetail)??null;return e.jsx(Yt,{open:t,onOpenChange:s,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs(es,{className:"fixed left-1/2 top-[6vh] z-50 max-h-[88vh] w-[min(60rem,calc(100vw-1.25rem))] -translate-x-1/2 overflow-y-auto rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ts,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:o?`${ti(o)} details`:"Movement details"}),e.jsx(rs,{className:"mt-2 text-sm leading-6 text-white/62",children:"Inspect the canonical box, the raw movement evidence behind it, and the exact coordinates Forge used to assemble this stay or trip."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o?e.jsxs(W,{onClick:n,variant:"ghost",className:"rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/78 hover:bg-white/[0.08]",disabled:!o.editable||o.kind==="missing",children:[e.jsx(da,{className:"size-4"}),"Edit"]}):null,e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white",children:e.jsx(Es,{className:"size-4 rotate-45"})})})]})]}),r?e.jsx("div",{className:"mt-6 rounded-[22px] border border-white/8 bg-white/[0.03] p-5 text-sm text-white/62",children:"Loading the canonical box detail and raw movement evidence…"}):o?e.jsxs("div",{className:"mt-6 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Started"}),e.jsx("div",{className:"mt-2 text-sm text-white",children:ei(o.startedAt)})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Ended"}),e.jsx("div",{className:"mt-2 text-sm text-white",children:ei(o.endedAt)})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Duration"}),e.jsx("div",{className:"mt-2 text-sm text-white",children:rl(o.durationSeconds)})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Raw coverage"}),e.jsxs("div",{className:"mt-2 text-sm text-white",children:[o.rawStayIds.length," stays · ",o.rawTripIds.length," trips · ",o.rawPointCount," points"]})]})]}),d?e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:"rounded-[22px] border border-sky-300/14 bg-sky-300/8 p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-sky-100/66",children:"Location label"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-sky-50/86",children:d.canonicalPlace?`This stay is linked to ${d.canonicalPlace.label}. Search a different saved place or relabel it from the stay center.`:"This stay has no saved place yet. Search known locations first, or create a new place directly from the stay center."}),e.jsx("div",{className:"mt-3",children:e.jsx(W,{onClick:l,variant:"ghost",className:"rounded-full border border-sky-300/24 bg-sky-300/12 px-4 text-sky-50 hover:bg-sky-300/18",children:"Label location"})})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsx(Bp,{title:"Stay positions",points:d.positions,averagePoint:d.averagePosition}),e.jsxs(ce,{className:"rounded-[28px] border border-white/10 bg-white/[0.03] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Stay metrics"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"text-sm text-white/78",children:["Canonical place: ",((h=d.canonicalPlace)==null?void 0:h.label)??"Not linked yet"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Average position: ",d.averagePosition?Gl(d.averagePosition.latitude,d.averagePosition.longitude):"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Radius: ",d.radiusMeters!=null?Ur(d.radiusMeters):"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Samples: ",d.sampleCount]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/10 p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Exact positions"}),e.jsx("div",{className:"mt-3 grid gap-2",children:d.positions.map((u,x)=>e.jsxs("div",{className:"text-sm text-white/74",children:[u.label??`Position ${x+1}`,": ",Gl(u.latitude,u.longitude)]},`${u.recordedAt??"stay"}-${x}`))})]})]})]})]})]}):null,m?e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsx(Bp,{title:"Travel map",points:m.positions}),e.jsxs(ce,{className:"rounded-[28px] border border-white/10 bg-white/[0.03] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Trip metrics"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"text-sm text-white/78",children:["Start position: ",m.startPosition?Gl(m.startPosition.latitude,m.startPosition.longitude):"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["End position: ",m.endPosition?Gl(m.endPosition.latitude,m.endPosition.longitude):"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Distance: ",Ur(m.totalDistanceMeters)]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Moving time: ",zp(m.movingSeconds)]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Idle time: ",zp(m.idleSeconds)]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Average speed: ",m.averageSpeedMps!=null?`${m.averageSpeedMps.toFixed(2)} m/s`:"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Max speed: ",m.maxSpeedMps!=null?`${m.maxSpeedMps.toFixed(2)} m/s`:"Unavailable"]}),e.jsxs("div",{className:"text-sm text-white/78",children:["Stops: ",m.stopCount]})]})]})]}):null]}):null]})]})})}function XC({open:t,onOpenChange:s,segment:a,places:i,loading:r,onSelectPlace:n,onCreatePlace:l}){const o=a?xu(a):null,[d,m]=c.useState("");c.useEffect(()=>{if(!t){m("");return}m(Wi(a)??"")},[t,a]);const h=c.useMemo(()=>{if(!o)return[];const p=Xa(d);return[...i].filter(f=>p.length===0?!0:TC(f).includes(p)).sort((f,b)=>{const A=Xa(f.label),C=Xa(b.label),T=p.length>0&&A.startsWith(p),w=p.length>0&&C.startsWith(p);if(T!==w)return T?-1:1;const S=vo(o.latitude,o.longitude,f.latitude,f.longitude),y=vo(o.latitude,o.longitude,b.latitude,b.longitude);return Math.abs(S-y)>1?S-y:f.label.localeCompare(b.label)}).slice(0,6)},[i,d,o]),u=Xa(d),x=h.some(p=>Xa(p.label)===u),g=Wi(a);return e.jsx(Yt,{open:t,onOpenChange:s,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs(es,{className:"fixed left-1/2 top-[8vh] z-50 max-h-[84vh] w-[min(38rem,calc(100vw-1.25rem))] -translate-x-1/2 overflow-y-auto rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ts,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:"Label stay location"}),e.jsx(rs,{className:"mt-2 text-sm leading-6 text-white/62",children:"Search saved locations by name first. If this stay is new, create a location from the stay center with latitude and longitude already filled in."})]}),e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close location label dialog",children:e.jsx(Tt,{className:"size-4"})})})]}),o?e.jsxs("div",{className:"mt-5 rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{tone:"signal",children:"Stay center"}),g?e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:g}):null]}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/10 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Latitude"}),e.jsx("div",{className:"mt-1 text-sm text-white/82",children:o.latitude.toFixed(6)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/10 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Longitude"}),e.jsx("div",{className:"mt-1 text-sm text-white/82",children:o.longitude.toFixed(6)})]})]})]}):e.jsx("div",{className:"mt-5 rounded-[22px] border border-amber-300/14 bg-amber-300/8 p-4 text-sm text-amber-50/86",children:"Forge can only label stays that already have a recorded stay center."}),e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsx(ye,{value:d,onChange:p=>m(p.target.value),placeholder:"Type a location name or create a new one"}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Known places"}),r?e.jsx("div",{className:"mt-3 text-sm text-white/58",children:"Loading saved places…"}):h.length>0?e.jsx("div",{className:"mt-3 grid gap-2",children:h.map(p=>{const f=o==null?null:vo(o.latitude,o.longitude,p.latitude,p.longitude);return e.jsxs("button",{type:"button",onClick:()=>void n(p).then(b=>{b&&s(!1)}),className:"rounded-[18px] border border-white/8 bg-black/10 px-4 py-3 text-left transition hover:border-[var(--primary)]/40 hover:bg-white/[0.05]",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-sm text-white",children:p.label}),f!=null?e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[Ur(f)," away"]}):null]}),p.aliases.length>0||p.categoryTags.length>0?e.jsx("div",{className:"mt-1 text-xs text-white/52",children:[...p.aliases,...p.categoryTags].join(" · ")}):null]},p.id)})}):e.jsx("div",{className:"mt-3 text-sm text-white/58",children:"No saved place matches this stay yet."})]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-2",children:[e.jsx(W,{variant:"ghost",onClick:()=>s(!1),className:"border border-white/10 bg-white/[0.04]",children:"Cancel"}),e.jsx(W,{onClick:()=>{!a||!o||l(a,x?"":d.trim())},disabled:!a||!o,children:u.length>0&&!x?`Create "${d.trim()}"`:"Create new location"})]})]})]})})}function YC({open:t,segment:s,draft:a,creating:i,saving:r,preflight:n,preflightLoading:l,onDraftChange:o,onFitMissing:d,onSave:m,onOpenChange:h}){return e.jsx(Yt,{open:t,onOpenChange:h,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs(es,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(34rem,calc(100vw-1.25rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ts,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:i?"Create movement box":"Edit movement box"}),e.jsx(rs,{className:"mt-2 text-sm leading-6 text-white/62",children:a?i?"Create a canonical user-defined stay, move, or missing-data box without mutating raw phone measurements.":`Adjust this user-defined ${a.kind} box. Automatic boxes stay immutable and can only be invalidated.`:"No segment selected."})]}),e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/72 transition hover:bg-white/[0.08]",children:e.jsx(Es,{className:"size-4 rotate-45"})})})]}),a?e.jsxs("div",{className:"mt-5 grid gap-4",children:[e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Kind",e.jsx("div",{className:"grid grid-cols-3 gap-2",children:[["stay","Stay"],["trip","Move"],["missing","Missing"]].map(([u,x])=>e.jsx(W,{type:"button",variant:"ghost",className:te("border border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]",a.kind===u?"ring-1 ring-[rgba(126,229,255,0.42)]":""),onClick:()=>o({...a,kind:u}),children:x},u))})]}),e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Label",e.jsx(ye,{value:a.label,onChange:u=>o({...a,label:u.target.value})})]}),a.kind!=="trip"?e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Place",e.jsx(ye,{value:a.placeLabel,onChange:u=>o({...a,placeLabel:u.target.value}),placeholder:"Home, Office, Riverside path..."})]}):null,e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Tags",e.jsx(ye,{value:a.tagsInput,onChange:u=>o({...a,tagsInput:u.target.value}),placeholder:"movement, social, errand"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Started",e.jsx(ye,{type:"datetime-local",value:a.startedAtInput,onChange:u=>o({...a,startedAtInput:u.target.value})})]}),e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Ended",e.jsx(ye,{type:"datetime-local",value:a.endedAtInput,onChange:u=>o({...a,endedAtInput:u.target.value})})]})]}),e.jsxs(ce,{className:"grid gap-3 border-white/10 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Overlap guidance"}),e.jsx(W,{type:"button",variant:"ghost",className:"border border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]",onClick:d,disabled:!(n!=null&&n.nearestMissingStartedAt)||!(n!=null&&n.nearestMissingEndedAt),children:"Fit Missing Time"})]}),e.jsx("div",{className:"text-sm leading-6 text-white/62",children:l?"Checking visible overlaps and missing windows…":n!=null&&n.overlapsAnything?`This box overlaps ${n.affectedAutomaticBoxIds.length} automatic and ${n.affectedUserBoxIds.length} manual boxes. Saving will fully override ${n.fullyOverriddenUserBoxIds.length} manual boxes and trim ${n.trimmedUserBoxIds.length}.`:"No overlap in the currently visible timeline window."}),e.jsxs("div",{className:"grid gap-1 text-xs text-white/50",children:[e.jsxs("div",{children:["Visible range:"," ",n!=null&&n.visibleRangeStart&&(n!=null&&n.visibleRangeEnd)?`${ei(n.visibleRangeStart)} -> ${ei(n.visibleRangeEnd)}`:"Unavailable"]}),e.jsxs("div",{children:["Suggested missing slot:"," ",n!=null&&n.nearestMissingStartedAt&&(n!=null&&n.nearestMissingEndedAt)?`${ei(n.nearestMissingStartedAt)} -> ${ei(n.nearestMissingEndedAt)}`:"No missing interval in view"]})]})]})]}):null,e.jsxs("div",{className:"mt-6 flex items-center justify-end gap-3",children:[e.jsx(Qt,{asChild:!0,children:e.jsx(W,{type:"button",variant:"ghost",className:"border border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]",children:"Cancel"})}),e.jsxs(W,{onClick:m,disabled:!a||r,children:[e.jsx(oi,{className:"size-4"}),r?"Saving…":i?"Create box":"Save changes"]})]})]})]})})}function Up({side:t,vertical:s,emphasized:a=!1}){return e.jsx("div",{className:te("absolute z-10 h-7 w-8 rounded-[12px] border bg-[linear-gradient(180deg,rgba(10,16,28,0.94),rgba(7,12,24,0.88))] shadow-[0_12px_30px_rgba(0,0,0,0.22)] backdrop-blur-sm",a?"border-[rgba(152,208,255,0.34)]":"border-white/10",t==="left"?"left-[8%]":t==="right"?"right-[8%]":"left-1/2 -translate-x-1/2",s==="top"?"top-0":"bottom-0")})}function JC({layout:t,selected:s,onToggle:a,onEdit:i,onOpenDetail:r,onDefinePlace:n}){var p,f,b,A;const{segment:l}=t,d=l.laneSide==="right"?"left":"right",m=s?d==="right"?-176:176:0,h=qm(l),u=t.displayHeight,x=l.kind==="stay"?h?"bg-[linear-gradient(180deg,rgba(39,127,173,0.28),rgba(16,51,79,0.22))] border-[rgba(138,227,255,0.28)]":"bg-[linear-gradient(180deg,rgba(98,130,238,0.22),rgba(18,34,79,0.22))] border-[rgba(152,208,255,0.24)]":"",g=l.kind==="trip"?{start:Hi(l,"start",{includeCoordinates:!1,useHistoryAnchorFallback:!0}),end:Hi(l,"end",{includeCoordinates:!1})}:null;return e.jsxs("div",{className:te("absolute left-0 w-full px-6",s?"z-40":"z-10"),"data-testid":"movement-timeline-row","data-selected":s?"true":"false",style:{top:`${t.boxTop}px`,height:`${u}px`},children:[e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-[linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0.08),rgba(255,255,255,0.02))]"}),e.jsxs("div",{className:"relative h-full",children:[l.kind==="trip"?e.jsxs(Ts.div,{layout:!0,animate:{x:m},transition:{type:"spring",stiffness:240,damping:30},className:"absolute inset-x-0 top-0 h-full z-10",children:[g&&s?e.jsxs(e.Fragment,{children:[e.jsx(Up,{side:"center",vertical:"top",emphasized:!0}),e.jsx(Up,{side:"center",vertical:"bottom",emphasized:!0})]}):null,e.jsx(HC,{fromSide:"center",toSide:"center",height:u,emphasized:s}),e.jsxs("button",{type:"button",onClick:a,className:te("group absolute top-1/2 max-w-[min(9rem,calc(100vw-9rem))] -translate-y-1/2 rounded-[18px] border border-white/8 bg-[linear-gradient(180deg,rgba(9,14,24,0.58),rgba(8,12,22,0.42))] px-3 py-2 text-left shadow-[0_12px_24px_rgba(0,0,0,0.14)] backdrop-blur-sm transition hover:border-white/14","left-1/2 -translate-x-1/2",s?"ring-1 ring-[rgba(126,229,255,0.38)]":""),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.18em] text-white/34",children:"Move"}),e.jsx("div",{className:"text-[11px] tracking-[0.18em] text-white/44",children:rl(l.durationSeconds)})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:Ur(((p=l.trip)==null?void 0:p.distanceMeters)??0)}),(((f=l.trip)==null?void 0:f.stops.length)??0)>0?e.jsxs(I,{className:"bg-white/[0.08] text-white/74",children:[(b=l.trip)==null?void 0:b.stops.length," stop",((A=l.trip)==null?void 0:A.stops.length)===1?"":"s"]}):null]}),e.jsxs("div",{className:"mt-2 font-label text-[9px] uppercase tracking-[0.22em] text-white/28",children:[Ws(l.startedAt)," → ",Ws(l.endedAt)]})]})]}):e.jsx(Ts.div,{layout:!0,animate:{x:m},transition:{type:"spring",stiffness:260,damping:28},className:"absolute top-0 left-1/2 z-10 w-[min(22rem,calc(100vw-5rem))] -translate-x-1/2",children:e.jsxs("button",{type:"button",onClick:a,className:te("group relative w-full overflow-hidden rounded-[30px] border text-left shadow-[0_26px_68px_rgba(3,8,20,0.42)] transition",x,s?"ring-1 ring-[rgba(126,229,255,0.42)]":"hover:border-white/22"),style:{minHeight:`${u}px`},children:[e.jsx(bu,{position:"top"}),e.jsx(bu,{position:"bottom"}),e.jsxs("div",{className:"relative z-10 flex h-full flex-col justify-between p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(I,{tone:"signal",className:"bg-white/10 text-white/82",children:h?"Sleep":"Stay"}),e.jsx("div",{className:"text-xs tracking-[0.18em] text-white/46",children:rl(l.durationSeconds)})]}),e.jsxs("div",{className:"mt-5 min-w-0",children:[e.jsx("div",{className:"truncate font-display text-[1.12rem] tracking-[-0.04em] text-white",children:ti(l)}),l.kind==="stay"&&Wi(l)&&!h?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(I,{className:"max-w-full truncate bg-white/[0.08] text-white/76",children:Wi(l)})}):h?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(I,{className:"max-w-full truncate bg-cyan-400/12 text-cyan-50",children:l.subtitle})}):null]}),e.jsx("div",{className:"mt-auto pt-8",children:e.jsxs("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-white/34",children:[Ws(l.startedAt)," → ",Ws(l.endedAt)]})})]})]})}),s?e.jsx(Ts.div,{layout:!0,initial:{opacity:0,x:d==="right"?28:-28},animate:{opacity:1,x:0},exit:{opacity:0,x:d==="right"?28:-28},className:te("absolute top-0 z-50 w-[min(22rem,calc(100vw-4rem))]",d==="right"?"right-[3%]":"left-[3%]"),children:e.jsx(QC,{segment:l,onEdit:i,onOpenDetail:r,onDefinePlace:n})}):null]})]})}function ZC({userIds:t=[]}){var He,lt,Nt;const s=ct(),a=c.useRef(null),i=c.useRef(null),r=c.useRef(!1),n=c.useRef(!1),l=c.useRef(null),[o,d]=c.useState(null),[m,h]=c.useState({}),[u,x]=c.useState(null),[g,p]=c.useState(null),[f,b]=c.useState(null),[A,C]=c.useState(null),[T,w]=c.useState(!1),[S,y]=c.useState(!1),[N,P]=c.useState(null),[v,H]=c.useState(null),[j,R]=c.useState(!1),[Q,X]=c.useState(!1),[Y,z]=c.useState(!1),[K,$]=c.useState(""),[D,J]=c.useState([]),[q,_]=c.useState(0),[B,G]=c.useState(0),ae=()=>{const me=a.current;me&&(_(me.scrollTop),G(me.clientHeight))},ke=Bc({queryKey:["forge-movement-life-timeline",...t],initialPageParam:null,queryFn:({pageParam:me})=>xh({before:me??void 0,limit:$p,userIds:t}).then(Pe=>Pe.movement),getNextPageParam:me=>me.nextCursor??void 0,retry:!1,refetchOnWindowFocus:!1}),Ae=Bc({queryKey:["forge-movement-life-timeline-data",...t],initialPageParam:null,queryFn:({pageParam:me})=>xh({before:me??void 0,includeInvalid:!0,limit:$p,userIds:t}).then(Pe=>Pe.movement),getNextPageParam:me=>me.nextCursor??void 0,retry:!1,refetchOnWindowFocus:!1}),ie=c.useMemo(()=>{var me;return((me=ke.data)==null?void 0:me.pages.flatMap(Pe=>Pe.segments))??[]},[ke.data]),Ie=c.useMemo(()=>{var me;return((me=Ae.data)==null?void 0:me.pages.flatMap(Pe=>Pe.segments))??[]},[Ae.data]),Ne=c.useMemo(()=>{var me;return((me=ke.data)==null?void 0:me.pages.reduce((Pe,k)=>Math.max(Pe,k.invalidSegmentCount??0),0))??0},[ke.data]),M=c.useMemo(()=>[...ie].reverse(),[ie]),E=c.useMemo(()=>[...Ie].reverse(),[Ie]),O=c.useMemo(()=>{var Pe;const me=new Map;for(const k of((Pe=ke.data)==null?void 0:Pe.pages)??[])for(const se of k.sleepOverlays??[])me.set(se.id,se);return[...me.values()].sort((k,se)=>new Date(k.startedAt).getTime()-new Date(se.startedAt).getTime())},[ke.data]),xe=c.useMemo(()=>NC(M,O),[M,O]),V=c.useMemo(()=>Y?xe:M,[M,xe,Y]),Se=c.useMemo(()=>xe.filter(me=>me.syncSource==="sleep overlay"),[xe]),Ee=((He=Se.at(-1))==null?void 0:He.id)??null,Ce=c.useMemo(()=>V.find(me=>me.id===f)??null,[f,V]),qe=Fe({queryKey:["forge-movement-box-detail",(Ce==null?void 0:Ce.boxId)??null,...t],queryFn:async()=>Ce!=null&&Ce.boxId?(await A1(Ce.boxId,t)).movement:null,enabled:!!(Ce!=null&&Ce.boxId)}),oe=c.useMemo(()=>M.find(me=>me.id===A)??null,[A,M]),L=Fe({queryKey:["forge-movement-places",...t],queryFn:async()=>(await hf(t)).places,retry:!1,refetchOnWindowFocus:!1}),U=c.useMemo(()=>UC({segments:V,viewportHeight:B}),[V,B]),ge=c.useMemo(()=>new Map(U.items.map(me=>[me.segment.id,me])),[U.items]),Te=(me,Pe="smooth")=>{const k=a.current,se=ge.get(me);if(!k||!se)return;const _e=Math.max(0,se.boxTop-k.clientHeight/2+se.displayHeight/2);if(typeof k.scrollTo=="function"){k.scrollTo({top:_e,behavior:Pe});return}k.scrollTop=_e};c.useEffect(()=>{j&&(!Ae.hasNextPage||Ae.isFetchingNextPage||Ae.fetchNextPage())},[j,Ae.fetchNextPage,Ae.hasNextPage,Ae.isFetchingNextPage]),c.useEffect(()=>{const me=V.at(-1);!n.current&&me&&(n.current=!0,d(me.id))},[V]),c.useEffect(()=>{if(!r.current&&V.length>0){r.current=!0,requestAnimationFrame(()=>{var Pe;const me=(Pe=V[V.length-1])==null?void 0:Pe.id;me&&Te(me,"auto"),requestAnimationFrame(()=>{ae()})});return}if(l.current&&V.length>l.current.count&&a.current){const me=l.current;l.current=null,requestAnimationFrame(()=>{const Pe=a.current;if(!Pe)return;const k=U.totalHeight-me.size;Pe.scrollTop+=k,ae()})}},[V.length,U.totalHeight,ge]),c.useEffect(()=>{if(!a.current)return;const Pe=()=>{ae()};return Pe(),window.addEventListener("resize",Pe),()=>window.removeEventListener("resize",Pe)},[]),c.useEffect(()=>{if(!o)return;const me=M.find(Pe=>Pe.id===o);me&&h(Pe=>Pe[o]?Pe:{...Pe,[o]:gu(me)})},[M,o]),c.useEffect(()=>{var me;o&&(V.some(Pe=>Pe.id===o)||d(((me=V.at(-1))==null?void 0:me.id)??null))},[V,o]),c.useEffect(()=>{if(!Y||!Ee)return;const me=V.findIndex(Pe=>Pe.id===Ee);me<0||(d(Ee),requestAnimationFrame(()=>{var k;const Pe=(k=V[me])==null?void 0:k.id;Pe&&Te(Pe)}))},[V,Ee,Y,ge]);const ve=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-movement-life-timeline"]}),s.invalidateQueries({queryKey:["forge-movement-life-timeline-data"]}),s.invalidateQueries({queryKey:["forge-movement-box-detail"]}),s.invalidateQueries({queryKey:["forge-movement-day"]}),s.invalidateQueries({queryKey:["forge-movement-month"]}),s.invalidateQueries({queryKey:["forge-movement-all-time"]}),s.invalidateQueries({queryKey:["forge-movement-places"]}),s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]})])},Le=Re({mutationFn:async me=>{const{segment:Pe,draft:k,creating:se}=me,_e=fu(k,Pe);if(se){await gh(_e,t);return}if(!Pe)throw new Error("No movement box selected.");if(Pe.sourceKind!=="user_defined")throw new Error("Automatic movement boxes are immutable. Invalidate them into missing data or create a user-defined override instead.");await fh(Pe.boxId,{..._e,metadata:{updatedFrom:"movement-life-timeline"}},t)},onSuccess:ve}),Qe=async(me,Pe)=>{if(me.kind!=="stay")throw new Error("Only stays can be linked to a saved place.");const k=DC(me,Pe.label);if(me.sourceKind==="user_defined"){await fh(me.boxId,{...k,metadata:{updatedFrom:"movement-life-timeline-place-label"}},t);return}await gh({...k,metadata:{createdFrom:"movement-life-timeline-place-label"}},t)},st=async(me,Pe)=>{if(me.rawStayIds.length===0)throw new Error("This stay has no raw stay ids to relabel.");await Promise.all(me.rawStayIds.map(k=>T1(k,{placeExternalUid:Pe.externalUid,placeLabel:Pe.label})))},F=(me,Pe)=>{const k=xu(me);if(!k)return!0;const se=vo(k.latitude,k.longitude,Pe.latitude,Pe.longitude);return se<=100||typeof window>"u"||typeof window.confirm!="function"?!0:window.confirm(`"${Pe.label}" is ${Ur(se)} away from this stay's recorded center. Link it anyway?`)},he=Re({mutationFn:async me=>{const{segment:Pe,...k}=me,se=await pf(k,t);return Pe&&ka(Pe)&&await st(Pe,se.place),se},onSuccess:ve}),we=Re({mutationFn:async me=>{const{segment:Pe,place:k}=me;if(!F(Pe,k))return{assigned:!1};if(ka(Pe))return await st(Pe,k),{assigned:!0};if(Pe.kind!=="stay")throw new Error("Only stays can be linked to a saved place.");return await Qe(Pe,k),{assigned:!0}},onSuccess:async me=>{me.assigned&&await ve()}}),Z=Re({mutationFn:async me=>{if(me.sourceKind==="user_defined"){await E1(me.boxId,t);return}await L1(me.boxId,{title:"User invalidated automatic movement",subtitle:`Overrides ${ti(me)} with missing data.`},t)},onSuccess:async(me,Pe)=>{d(k=>k===Pe.id?null:k),x(k=>k===Pe.id?null:k),s.setQueryData(["forge-movement-life-timeline",...t],k=>qp(k,Pe.id)),s.setQueryData(["forge-movement-life-timeline-data",...t],k=>qp(k,Pe.id)),await Promise.all([s.invalidateQueries({queryKey:["forge-movement-life-timeline"]}),s.invalidateQueries({queryKey:["forge-movement-life-timeline-data"]}),s.invalidateQueries({queryKey:["forge-movement-day"]}),s.invalidateQueries({queryKey:["forge-movement-month"]}),s.invalidateQueries({queryKey:["forge-movement-all-time"]}),s.invalidateQueries({queryKey:["forge-movement-selection"]}),s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]})])}}),De=c.useMemo(()=>_C(E),[E]),ee=c.useMemo(()=>{const me=Xa(K);return[...E].sort((Pe,k)=>new Date(k.endedAt).getTime()-new Date(Pe.endedAt).getTime()).filter(Pe=>(me.length===0||FC(Pe).includes(me))&&RC(Pe,D))},[E,K,D]),ze=c.useMemo(()=>E.length===0?"No movement records loaded yet.":ee.length===E.length&&K.trim().length===0&&D.length===0?`${E.length} loaded movement records visible`:`${ee.length} of ${E.length} loaded records visible`,[E.length,ee.length,K,D.length]),et=nd({count:ee.length,getScrollElement:()=>i.current,estimateSize:()=>136,overscan:8}),Ve=u?M.find(me=>me.id===u)??null:null,re=Ve?m[Ve.id]??gu(Ve):null,ne=g!==null,be=g??re,je=((lt=M[0])==null?void 0:lt.startedAt)??null,pe=((Nt=M[M.length-1])==null?void 0:Nt.endedAt)??null,$e=Fe({queryKey:["forge-movement-user-box-preflight",(Ve==null?void 0:Ve.boxId)??"create",(be==null?void 0:be.kind)??null,(be==null?void 0:be.startedAtInput)??null,(be==null?void 0:be.endedAtInput)??null,je,pe,...t],enabled:be!==null&&Wo(be.startedAtInput)!==null&&Wo(be.endedAtInput)!==null,queryFn:async()=>{if(!be)return null;const me=fu(be,Ve);return(await M1({...me,excludeBoxId:(Ve==null?void 0:Ve.sourceKind)==="user_defined"?Ve.boxId:null,rangeStart:je,rangeEnd:pe},t)).preflight}}),Xe=me=>{ka(me)&&(C(me.id),w(!0))},Ue=(me,Pe)=>{const k=xu(me);k&&(w(!1),C(me.id),P({...k,label:Pe.trim()||k.label}),H(me.id),y(!0))},le=()=>{const me=a.current;me&&(_(me.scrollTop),G(me.clientHeight),!(!ke.hasNextPage||ke.isFetchingNextPage)&&me.scrollTop<=960&&(l.current={count:V.length,size:U.totalHeight},ke.fetchNextPage()))};if(ke.isPending)return e.jsx(ls,{eyebrow:"Movement",title:"Loading life timeline",description:"Reconstructing the longer road of stays, moves, and places.",columns:1,blocks:6});if(ke.isError)return e.jsx(it,{eyebrow:"Movement",error:ke.error,onRetry:()=>void ke.refetch()});const Me=U.totalHeight;return e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(ce,{className:"overflow-hidden rounded-[34px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(88,182,255,0.08),transparent_28%),linear-gradient(180deg,rgba(4,8,17,0.99),rgba(5,9,18,0.97))] p-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3 px-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.22em] text-white/34",children:"Movement"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",onClick:()=>p(lc("stay",M.at(-1)??null)),children:[e.jsx(da,{className:"size-3.5"}),"Add box"]}),e.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",onClick:()=>z(me=>{const Pe=!me;return Pe&&Ee&&d(Ee),Pe}),children:[e.jsx(Wu,{className:"size-3.5"}),Y?"Hide sleep":"Show sleep"]}),e.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",onClick:()=>R(!0),children:[e.jsx(_r,{className:"size-3.5"}),"View data"]}),Ne>0?e.jsxs(I,{className:"bg-amber-500/10 text-amber-100",children:[Ne," invalid hidden"]}):null,e.jsxs(I,{className:"bg-white/[0.06] text-white/68",children:[V.length," visible"]})]})]}),Y&&Se.length===0?e.jsx("p",{className:"mb-3 px-1 text-sm text-amber-100/80",children:"No sleep session overlaps the currently loaded timeline range yet. Scroll further back to load older history."}):null,e.jsxs("div",{ref:a,onScroll:le,className:"relative h-[82vh] overflow-auto rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(4,7,15,0.98),rgba(6,10,18,0.96))]",children:[e.jsx(WC,{layout:U,scrollTop:q,viewportHeight:B}),e.jsxs("div",{className:"relative",style:{height:`${Me}px`},children:[U.historyHeaderHeight>0?e.jsx("div",{className:"absolute inset-x-0 top-0",style:{height:`${U.historyHeaderHeight}px`},children:e.jsx(GC,{segment:V[0]??null})}):null,U.items.map(me=>{const Pe=me.segment;return e.jsx(JC,{layout:me,selected:o===Pe.id,onToggle:()=>d(k=>k===Pe.id?null:Pe.id),onEdit:()=>{Pe.editable&&x(Pe.id)},onOpenDetail:()=>b(Pe.id),onDefinePlace:()=>Xe(Pe)},Pe.id)})]})]})]}),e.jsx(YC,{open:Ve!==null||g!==null,segment:Ve,draft:be,creating:ne,saving:Le.isPending,preflight:$e.data??null,preflightLoading:$e.isFetching,onDraftChange:me=>{if(ne){p(me);return}Ve&&h(Pe=>({...Pe,[Ve.id]:me}))},onFitMissing:()=>{const me=$e.data;if(!(me!=null&&me.nearestMissingStartedAt)||!me.nearestMissingEndedAt)return;const Pe={...be??lc("stay",Ve),startedAtInput:Br(me.nearestMissingStartedAt),endedAtInput:Br(me.nearestMissingEndedAt)};if(ne){p(Pe);return}Ve&&h(k=>({...k,[Ve.id]:Pe}))},onSave:()=>{be&&Le.mutateAsync({segment:Ve,draft:be,creating:ne},{onSuccess:()=>{x(null),p(null),Q&&(X(!1),R(!0))}})},onOpenChange:me=>{me||(x(null),p(null),Q&&(X(!1),R(!0)))}}),e.jsx(VC,{open:Ce!==null,onOpenChange:me=>{me||b(null)},segment:Ce,detail:qe.data??null,loading:qe.isFetching,onEdit:()=>{!Ce||!Ce.editable||(x(Ce.id),b(null))},onDefinePlace:()=>{Ce&&Xe(Ce)}}),e.jsx(XC,{open:T,onOpenChange:me=>{w(me),me||C(null)},segment:oe,places:L.data??[],loading:L.isFetching,onSelectPlace:async me=>oe?(await we.mutateAsync({segment:oe,place:me})).assigned:!1,onCreatePlace:(me,Pe)=>{Ue(me,Pe)}}),e.jsx(Mw,{open:S,onOpenChange:me=>{y(me),me||(P(null),H(null))},place:null,seed:N,onSave:async me=>{await he.mutateAsync({...me,segment:M.find(Pe=>Pe.id===v)??null})}}),e.jsx(pa,{open:j,onOpenChange:me=>{R(me),me||Q||($(""),J([]))},eyebrow:"Movement data",title:"View data",description:"",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(mi,{title:"",description:"",query:K,onQueryChange:$,options:De,selectedOptionIds:D,onSelectedOptionIdsChange:J,resultSummary:ze,placeholder:"Search movement labels, places, times, tags, or add time and kind filters",emptyStateMessage:"Keep typing or pick filters to narrow the movement history."}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Canonical boxes"}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/56",children:"This list shows the canonical movement boxes projected by Forge. Automatic boxes are derived from immutable raw phone measurements. User-defined boxes override the projection without mutating raw movement data."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/70",onClick:()=>{X(!0),R(!1),p(lc("stay",ee.at(-1)??null))},children:"Add box"}),e.jsx(I,{tone:"meta",children:ze}),Ne>0?e.jsxs(I,{className:"bg-amber-500/10 text-amber-100",children:[Ne," invalid hidden included"]}):null,Ae.hasNextPage?e.jsx(W,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/70",pending:Ae.isFetchingNextPage,pendingLabel:"Loading…",onClick:()=>void Ae.fetchNextPage(),children:"Load older"}):null]})]}),e.jsx("div",{ref:i,className:"h-[36rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:ee.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No movement record matches the current search. Clear filters or load older timeline history."}):e.jsx("div",{className:"relative w-full",style:{height:`${et.getTotalSize()}px`},children:et.getVirtualItems().map(me=>{var k;const Pe=ee[me.index];return e.jsx("div",{ref:et.measureElement,"data-index":me.index,className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${me.start}px)`},children:e.jsxs("div",{className:"flex items-start gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[e.jsx("button",{type:"button",className:"min-w-0 flex-1 text-left transition hover:opacity-100",onClick:()=>{Pe.editable&&(X(!0),R(!1),x(Pe.id))},children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[Pe.kind==="stay"?e.jsx(qu,{className:"size-3.5 shrink-0 text-[var(--primary)]"}):Pe.kind==="missing"?e.jsx(_r,{className:"size-3.5 shrink-0 text-slate-300/80"}):e.jsx(Hn,{className:"size-3.5 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-sm font-medium",children:ti(Pe)})]}),e.jsxs("div",{className:"mt-1 text-xs text-white/56",children:[Go(Pe.startedAt)," →"," ",Go(Pe.endedAt)]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-1.5",children:[e.jsx(I,{tone:Pe.kind==="trip"?"signal":"meta",children:Pe.kind==="trip"?"Move":Pe.kind==="missing"?"Missing":"Stay"}),e.jsx(I,{className:Pe.sourceKind==="user_defined"?"bg-fuchsia-400/12 text-fuchsia-100":"bg-white/[0.06] text-white/70",children:Pe.sourceKind==="user_defined"?Pe.origin==="user_invalidated"?"User invalidated":"User-defined":"Automatic"}),e.jsx(I,{tone:"meta",children:rl(Pe.durationSeconds)}),Pe.origin==="continued_stay"?e.jsx(I,{className:"bg-sky-400/10 text-sky-100",children:"Continued stay"}):null,Pe.origin==="repaired_gap"?e.jsx(I,{className:"bg-amber-400/10 text-amber-100",children:"Repaired"}):null,Pe.kind==="missing"?e.jsx(I,{className:"bg-slate-300/10 text-slate-100",children:"Missing"}):null,Pe.isInvalid?e.jsx(I,{className:"bg-amber-500/10 text-amber-100",children:"Invalid"}):null,Pe.placeLabel?e.jsx(I,{tone:"default",children:Pe.placeLabel}):null,Pe.overrideCount>0?e.jsxs(I,{className:"bg-amber-400/10 text-amber-100",children:["Overrides ",Pe.overrideCount]}):null,e.jsxs(I,{className:"bg-white/[0.06] text-white/66",children:["Raw stays ",Pe.rawStayIds.length]}),e.jsxs(I,{className:"bg-white/[0.06] text-white/66",children:["Raw trips ",Pe.rawTripIds.length]}),e.jsxs(I,{className:"bg-white/[0.06] text-white/66",children:["Raw points ",Pe.rawPointCount]}),Pe.hasLegacyCorrections?e.jsx(I,{className:"bg-amber-400/10 text-amber-100",children:"Legacy corrections"}):null]})]})}),e.jsx(W,{type:"button",variant:"ghost",size:"sm",className:te("h-8 shrink-0 rounded-full border px-2.5",Pe.sourceKind==="user_defined"?"border-rose-400/22 bg-rose-500/10 text-rose-100 hover:bg-rose-500/18":"border-amber-400/22 bg-amber-500/10 text-amber-100 hover:bg-amber-500/18"),pending:Z.isPending&&((k=Z.variables)==null?void 0:k.id)===Pe.id,pendingLabel:"",onClick:()=>{window.confirm(Pe.sourceKind==="user_defined"?`Delete ${ti(Pe)} and remove this user-defined box from every synced surface?`:`Invalidate ${ti(Pe)} into missing data and hide the automatic box everywhere?`)&&Z.mutateAsync(Pe)},children:e.jsx(Rt,{className:"size-3.5"})})]})},Pe.id)})})})]})]})})]})}function e8(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}).format(new Date(t))}function t8(t,s){const a=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${a.format(new Date(t))} - ${a.format(new Date(s))}`}function Cs(t){return t>=3600?`${(t/3600).toFixed(1)}h`:`${Math.round(t/60)}m`}function Ni(t){return t>=1e3?`${(t/1e3).toFixed(1)} km`:`${Math.round(t)} m`}function s8(t,s){return t==="distanceMeters"?Ni(s):t==="caloriesKcal"?`${Math.round(s)} kcal`:Cs(s)}function Dw(t){return t.trim().toLowerCase()}function Cd(t){const s=new Date(t).getHours();return s<6?"night":s<12?"morning":s<18?"afternoon":"evening"}function Bm(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function a8(t){const s=new Date(t);return Number.isNaN(s.getTime())?"":new Date(s.getTime()-s.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function Wp(t){return{recordedAt:a8(t.recordedAt),latitude:String(t.latitude),longitude:String(t.longitude),accuracyMeters:t.accuracyMeters!=null?String(t.accuracyMeters):"",altitudeMeters:t.altitudeMeters!=null?String(t.altitudeMeters):"",speedMps:t.speedMps!=null?String(t.speedMps):"",isStopAnchor:t.isStopAnchor}}function i8(t){return Dw([Bm(t.recordedAt),t.externalUid,t.isStopAnchor?"stop anchor stop":"path trace point",t.accuracyMeters!=null?`${Math.round(t.accuracyMeters)} meters accuracy`:"",Cd(t.recordedAt)].join(" "))}function r8(t){const s=new Map;return s.set("anchor:stop",{id:"anchor:stop",label:"Stop anchors",description:"Only the canonical pause anchors",badge:e.jsx(I,{tone:"meta",children:"Stop anchors"})}),s.set("anchor:path",{id:"anchor:path",label:"Path points",description:"Non-anchor trace points",badge:e.jsx(I,{tone:"meta",children:"Path points"})}),s.set("accuracy:precise",{id:"accuracy:precise",label:"Precise",description:"GPS accuracy below 20m",badge:e.jsx(I,{tone:"meta",children:"Precise"})}),s.set("accuracy:loose",{id:"accuracy:loose",label:"Loose accuracy",description:"GPS accuracy at or above 20m",badge:e.jsx(I,{tone:"meta",children:"Loose accuracy"})}),t.forEach(a=>{const i=Cd(a.recordedAt);s.has(`time:${i}`)||s.set(`time:${i}`,{id:`time:${i}`,label:i,description:"Recorded during this time band",badge:e.jsx(I,{tone:"meta",className:"capitalize",children:i})})}),[...s.values()]}function n8(t,s){return s.every(a=>a==="anchor:stop"?t.isStopAnchor:a==="anchor:path"?!t.isStopAnchor:a==="accuracy:precise"?t.accuracyMeters!=null&&t.accuracyMeters<20:a==="accuracy:loose"?t.accuracyMeters==null||t.accuracyMeters>=20:a.startsWith("time:")?Cd(t.recordedAt)===a.slice(5):!0)}function l8(t){if(t.length===0)return[];const s=Math.min(...t.map(o=>o.latitude)),a=Math.max(...t.map(o=>o.latitude)),i=Math.min(...t.map(o=>o.longitude)),r=Math.max(...t.map(o=>o.longitude)),n=Math.max(a-s,1e-4),l=Math.max(r-i,1e-4);return t.map(o=>({x:12+(o.longitude-i)/l*76,y:12+(1-(o.latitude-s)/n)*76}))}function o8({curve:t,startLabel:s,endLabel:a,stopLabels:i}){const r=t.map((n,l)=>`${l===0?"M":"Q"} ${n.x} ${n.y}`).join(" ");return e.jsxs(ce,{className:"overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(114,204,255,0.18),transparent_44%),linear-gradient(180deg,rgba(6,11,26,0.98),rgba(8,14,28,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Stylized trajectory"}),e.jsx(vt,{content:"This graph is a softened trip trace. It emphasizes rhythm, stops, and endpoints instead of raw GPS jitter."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/64",children:"A softened path that prioritizes rhythm, stops, and landmarks over raw map noise."})]}),e.jsxs(I,{tone:"signal",children:[s," → ",a]})]}),e.jsxs("div",{className:"mt-5 rounded-[26px] border border-white/8 bg-[rgba(255,255,255,0.03)] p-4",children:[e.jsxs("svg",{viewBox:"0 0 100 60",className:"h-48 w-full",children:[e.jsx("defs",{children:e.jsxs("filter",{id:"movementGlow",children:[e.jsx("feGaussianBlur",{stdDeviation:"1.8",result:"blur"}),e.jsxs("feMerge",{children:[e.jsx("feMergeNode",{in:"blur"}),e.jsx("feMergeNode",{in:"SourceGraphic"})]})]})}),e.jsx("path",{d:r,fill:"none",stroke:"rgba(255,255,255,0.86)",strokeWidth:"1.5",strokeDasharray:"2.8 2.8",filter:"url(#movementGlow)"}),t.map((n,l)=>e.jsx("g",{children:e.jsx("circle",{cx:n.x,cy:n.y,r:l===0||l===t.length-1?2.6:1.6,fill:l===0||l===t.length-1?"#ffffff":"rgba(170,229,255,0.96)"})},`${n.x}-${n.y}-${l}`))]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:i.map(n=>e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:n},n))})]})]})}function d8({points:t}){const s=l8(t),a=s.map((i,r)=>`${r===0?"M":"L"} ${i.x} ${i.y}`).join(" ");return e.jsxs(ce,{className:"rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,13,25,0.95),rgba(10,17,30,0.88))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Exact path"}),e.jsx(vt,{content:"This keeps the recent raw location points. Use it when you want the literal recorded trace instead of the cleaned movement graph."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/62",children:"Recent raw points preserved by the companion before long-term simplification."}),e.jsx("div",{className:"mt-5 rounded-[24px] border border-white/8 bg-[rgba(255,255,255,0.03)] p-3",children:e.jsxs("svg",{viewBox:"0 0 100 100",className:"h-52 w-full",children:[e.jsx("rect",{x:"0",y:"0",width:"100",height:"100",rx:"18",fill:"rgba(255,255,255,0.02)"}),e.jsx("path",{d:a,fill:"none",stroke:"rgba(92,225,230,0.95)",strokeWidth:"1.6"}),s.map((i,r)=>e.jsx("circle",{cx:i.x,cy:i.y,r:r===0||r===s.length-1?2:1.1,fill:r===0||r===s.length-1?"#ffffff":"rgba(92,225,230,0.9)"},`${i.x}-${i.y}-${r}`))]})})]})}function c8({point:t,draft:s}){return e.jsxs(ce,{className:"grid gap-4 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(12,18,32,0.98),rgba(8,13,24,0.98))] p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Raw datapoint"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Bm(t.recordedAt)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Raw phone measurements are immutable in product UI. To change the visible movement story, create or edit user-defined boxes in the Life Timeline instead."})]}),e.jsx(I,{tone:t.isStopAnchor?"signal":"meta",children:t.isStopAnchor?"Stop anchor":"Path point"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Recorded at"}),e.jsx(ye,{type:"datetime-local",value:s.recordedAt,disabled:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Speed (m/s)"}),e.jsx(ye,{value:s.speedMps,disabled:!0,placeholder:"Optional"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Latitude"}),e.jsx(ye,{value:s.latitude,disabled:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Longitude"}),e.jsx(ye,{value:s.longitude,disabled:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Accuracy (m)"}),e.jsx(ye,{value:s.accuracyMeters,disabled:!0,placeholder:"Optional"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Altitude (m)"}),e.jsx(ye,{value:s.altitudeMeters,disabled:!0,placeholder:"Optional"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(W,{variant:"ghost",className:te("h-10 rounded-full border px-4",s.isStopAnchor?"border-[var(--primary)] bg-[var(--primary)]/16 text-white":"border-white/10 bg-white/[0.04] text-white/64"),disabled:!0,children:[e.jsx(Hn,{className:"mr-2 size-4"}),s.isStopAnchor?"Stop anchor":"Path point"]}),e.jsxs("div",{className:"text-sm text-white/50",children:["External id: ",e.jsx("span",{className:"text-white/72",children:t.externalUid})]})]}),e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm leading-6 text-white/56",children:"This browser is read-only now. Raw points stay immutable so the web app and iPhone can both project the same repaired canonical boxes from the backend."})]})}function u8(){var oe,L,U,ge,Te;const t=jt(),s=ct(),a=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[i,r]=c.useState("life"),[n,l]=c.useState(new Date().toISOString().slice(0,10)),[o,d]=c.useState(new Date().toISOString().slice(0,7)),[m,h]=c.useState(null),[u,x]=c.useState(!1),[g,p]=c.useState(!1),[f,b]=c.useState(""),[A,C]=c.useState([]),[T,w]=c.useState(null),[S,y]=c.useState(null),[N,P]=c.useState({stayIds:[],tripIds:[]}),[v,H]=c.useState(!1),[j,R]=c.useState(null),[Q,X]=c.useState(""),[Y,z]=c.useState("distanceMeters"),K=c.useRef(null),$=Fe({queryKey:["forge-movement-day",n,...a],queryFn:async()=>(await mf({date:n,userIds:a})).movement}),D=Fe({queryKey:["forge-movement-month",o,...a],queryFn:async()=>(await w1({month:o,userIds:a})).movement}),J=Fe({queryKey:["forge-movement-all-time",...a],queryFn:async()=>(await y1(a)).movement}),q=Fe({queryKey:["forge-life-force",...a],queryFn:async()=>(await Ji(a)).lifeForce}),_=Fe({queryKey:["forge-movement-settings",...a],queryFn:async()=>(await S1(a)).settings}),B=Fe({queryKey:["forge-movement-places",...a],queryFn:async()=>(await hf(a)).places}),G=Fe({queryKey:["forge-movement-trip",m],queryFn:async()=>m?(await P1(m)).movement:null,enabled:!!m}),ae=Fe({queryKey:["forge-movement-selection",n,N.stayIds.join(","),N.tripIds.join(","),...a],queryFn:async()=>(await D1({...N,userIds:a})).movement,enabled:N.stayIds.length>0||N.tripIds.length>0}),ke=Re({mutationFn:async ve=>I1({trackingEnabled:ve},a),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-movement-settings"]}),await s.invalidateQueries({queryKey:["forge-movement-day"]})}}),Ae=Re({mutationFn:async ve=>ve.id?C1(ve.id,ve):pf(ve,a),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-movement-places"]}),await s.invalidateQueries({queryKey:["forge-movement-day"]}),await s.invalidateQueries({queryKey:["forge-movement-all-time"]})}}),ie=c.useMemo(()=>{const ve=B.data??[],Le=Q.trim().toLowerCase();return Le?ve.filter(Qe=>[Qe.label,...Qe.aliases,...Qe.categoryTags].join(" ").toLowerCase().includes(Le)):ve},[Q,B.data]),Ie=c.useMemo(()=>{var ve;return r8(((ve=G.data)==null?void 0:ve.trip.points)??[])},[(oe=G.data)==null?void 0:oe.trip.points]),Ne=c.useMemo(()=>{var Qe;const ve=((Qe=G.data)==null?void 0:Qe.trip.points)??[],Le=Dw(f);return[...ve].sort((st,F)=>new Date(F.recordedAt).getTime()-new Date(st.recordedAt).getTime()).filter(st=>(Le.length===0||i8(st).includes(Le))&&n8(st,A))},[f,A,(L=G.data)==null?void 0:L.trip.points]),M=c.useMemo(()=>{var Le;const ve=((Le=G.data)==null?void 0:Le.trip.points.length)??0;return ve===0?"No raw datapoints on this trip yet.":Ne.length===ve&&f.trim().length===0&&A.length===0?`${ve} datapoints visible`:`${Ne.length} of ${ve} datapoints visible`},[Ne.length,f,A.length,(U=G.data)==null?void 0:U.trip.points.length]),E=nd({count:Ne.length,getScrollElement:()=>K.current,estimateSize:()=>96,overscan:8}),O=Ne.find(ve=>ve.id===T)??((ge=G.data)==null?void 0:ge.trip.points.find(ve=>ve.id===T))??Ne[0]??((Te=G.data)==null?void 0:Te.trip.points[0])??null;if(c.useEffect(()=>{if(g){if(!O){w(null),y(null);return}w(O.id),y(Wp(O))}},[O,g]),c.useEffect(()=>{b(""),C([]),w(null),y(null),p(!1)},[m]),$.isLoading||D.isLoading||J.isLoading||_.isLoading||B.isLoading)return e.jsx(ls,{eyebrow:"Movement",title:"Loading movement workspace",description:"Reconstructing stays, trips, and place intelligence across Forge.",columns:2,blocks:8});if($.isError||D.isError||J.isError||_.isError||B.isError||!$.data||!D.data||!J.data||!_.data)return e.jsx(it,{eyebrow:"Movement",error:$.error??D.error??J.error??_.error??B.error??new Error("Movement data unavailable"),onRetry:()=>{$.refetch(),D.refetch(),J.refetch(),_.refetch(),B.refetch()}});const xe=$.data,V=D.data,Se=J.data,Ee=_.data,Ce=ae.data??xe.selectionAggregate,qe=xe.trips.reduce((ve,Le)=>ve+Dl(Le).totalAp,0);return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{entityKind:"project",title:"Movement",description:"Turn passive place and travel signals into a real Forge domain: day rhythm, travel arcs, known landmarks, linked work, and reflective evidence.",badge:`${xe.summary.tripCount} trips today`,actions:e.jsx("div",{className:"flex flex-wrap gap-2",children:["life","day","month","all_time"].map(ve=>e.jsx(W,{variant:"ghost",className:te("h-9 rounded-full border px-4 text-sm",i===ve?"border-[var(--primary)] bg-[var(--primary)]/16 text-white":"border-white/10 bg-white/[0.04] text-white/64"),onClick:()=>r(ve),children:ve==="all_time"?"All time":ve==="life"?"Life":ve.charAt(0).toUpperCase()+ve.slice(1)},ve))})}),e.jsxs(ce,{className:"grid gap-3 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(12,20,34,0.98),rgba(8,14,25,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:"Movement AP today"}),e.jsx("div",{className:"mt-2 text-3xl font-semibold text-white",children:St(qe)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Trips and transitions now contribute to the same Action Point ledger as work, habits, and notes."})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Typical trip drain"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-[var(--primary)]",children:xe.trips[0]?Kt(Dl(xe.trips[0]).rateApPerHour):"0 AP/h"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Movement uses a MET-like drain under the hood, translated into Forge Action Points."})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Life Force sync"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white",children:q.data?`${Math.round(q.data.spentTodayAp??0)}/${Math.round(q.data.dailyBudgetAp??0)} AP`:"Loading..."}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:q.data?`${Kt(q.data.instantFreeApPerHour)} free right now`:"Movement can now be read against today’s live capacity."})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.65fr)_minmax(20rem,0.95fr)]",children:[e.jsx(bb,{children:e.jsxs(ce,{className:"overflow-hidden rounded-[30px] border border-white/8 bg-[radial-gradient(circle_at_top_left,rgba(107,214,255,0.16),transparent_42%),linear-gradient(180deg,rgba(10,18,35,0.98),rgba(9,15,28,0.92))]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Movement operating mode"}),e.jsx(vt,{content:"This is the passive capture state of the movement system: whether tracking is running, how much is published into Forge, and how aggressive retention is."})]}),e.jsx("div",{className:"mt-2 text-[clamp(1.05rem,1.8vw,1.35rem)] text-white",children:"Background stays and trips as structured life evidence"}),e.jsx("div",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/58",children:"The companion samples quietly while stationary, switches to denser trip capture when you move, and keeps only simplified long-term traces."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(I,{tone:"signal",children:Ee.trackingEnabled?"Tracking on":"Tracking off"}),e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/72",children:Ee.publishMode.replaceAll("_"," ")}),e.jsx(W,{variant:"ghost",className:"h-9 rounded-full border border-white/10 bg-white/[0.04] px-4",onClick:()=>ke.mutate(!Ee.trackingEnabled),children:Ee.trackingEnabled?"Pause passive capture":"Enable passive capture"})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-3",children:[e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Distance today"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Ni(xe.summary.totalDistanceMeters)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Across trips, stops, and linked place changes."})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Idle time"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.totalIdleSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Time spent settled enough to count as a real stay."})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Estimated phone time"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.estimatedScreenTimeSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Estimated from hourly Screen Time bins, not exact foreground traces."})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Known places"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:xe.summary.knownPlaceCount}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Shared between Forge and the iPhone companion."})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(148,163,184,0.12),rgba(71,85,105,0.12))] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Missing data"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.missingDurationSeconds)}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[xe.summary.missingCount," grey gap",xe.summary.missingCount===1?"":"s"," where Forge had over one hour without enough movement signal."]})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(251,191,36,0.12),rgba(16,185,129,0.08))] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Repaired gaps"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.repairedGapDurationSeconds)}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[xe.summary.repairedGapCount," inferred span",xe.summary.repairedGapCount===1?"":"s"," classified as stay or move instead of leaving blank holes in the day."]})]}),e.jsxs(ce,{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(56,189,248,0.12),rgba(99,102,241,0.08))] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Continued stays"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Cs(xe.summary.continuedStayDurationSeconds)}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[xe.summary.continuedStayCount," short stationary span",xe.summary.continuedStayCount===1?"":"s"," carried forward so quiet home time stays continuous instead of disappearing."]})]})]})]})}),e.jsx(wb,{children:e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Selection aggregate"}),e.jsx(vt,{content:"When you select stays or trips, Forge totals their span, distance, work overlap, notes, and places here."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Select any combination of stays and trips to sum movement, time, and work evidence."}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Span"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Cs(Ce.durationSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ni(Ce.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Work overlap"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Cs(Ce.trackedWorkSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Notes"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ce.noteCount})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Estimated phone time"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Cs(Ce.estimatedScreenTimeSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Pickups"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ce.pickupCount})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Notifications"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ce.notificationCount})]})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:Ce.placeLabels.map(ve=>e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:ve},ve))}),Ce.topApps.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:Ce.topApps.map(ve=>e.jsx(I,{tone:"default",className:"bg-[rgba(114,204,255,0.12)] text-white/80",children:(ve.displayName||ve.bundleIdentifier)+" · "+Cs(ve.totalActivitySeconds)},ve.id))}):null,Ce.topCategories.length>0?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Ce.topCategories.map(ve=>e.jsx(I,{tone:"default",className:"bg-white/[0.05] text-white/64",children:ve.categoryLabel},ve.id))}):null]})})]}),i==="life"?e.jsx(yb,{children:e.jsxs("section",{className:"grid gap-3",children:[e.jsx("div",{className:"flex items-center justify-between gap-3 px-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/38",children:"Life graph"}),e.jsx(vt,{content:"This graph shows the movement road of your life: stays are blocks, moves connect them, and the hour/day lines live in the background. Click a segment for details, then use edit when you want to correct it."})]})}),e.jsx(ZC,{userIds:a})]})}):null,i==="day"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.55fr)_minmax(22rem,1fr)]",children:[e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(7,12,22,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Day strip"}),e.jsx(vt,{content:"A compressed 24-hour strip. Each segment keeps its true order and duration, but the whole day stays navigable on one line."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"A single-row timeline from 00:00 to 24:00, always compressed into one navigable strip."})]}),e.jsx(ye,{type:"date",value:n,onChange:ve=>l(ve.target.value),className:"w-[11rem]"})]}),e.jsx("div",{className:"mt-6 overflow-x-auto pb-2",children:e.jsxs("div",{className:"min-w-[52rem]",children:[e.jsx("div",{className:"mb-3 flex justify-between text-[11px] uppercase tracking-[0.18em] text-white/36",children:["00:00","06:00","12:00","18:00","24:00"].map(ve=>e.jsx("span",{children:ve},ve))}),e.jsx("div",{className:"flex h-28 items-stretch overflow-hidden rounded-[28px] border border-white/10 bg-[rgba(255,255,255,0.03)] p-2",children:xe.segments.map(ve=>{const Le=Math.max(9,ve.durationSeconds/86400*100),Qe=ve.kind==="stay"?N.stayIds.includes(ve.id):ve.kind==="trip"?N.tripIds.includes(ve.id):!1;return e.jsxs("button",{type:"button",className:te("relative flex min-w-[5.5rem] flex-col justify-between rounded-[22px] border px-3 py-2 text-left transition",ve.kind==="missing"?"border-slate-400/20 bg-[linear-gradient(180deg,rgba(148,163,184,0.18),rgba(51,65,85,0.14))] hover:border-slate-300/30 hover:bg-[rgba(148,163,184,0.14)]":Qe?"border-[rgba(171,232,255,0.5)] bg-[rgba(171,232,255,0.16)]":"border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.02))] hover:border-white/14 hover:bg-white/[0.08]"),style:{width:`${Le}%`},onClick:()=>{ve.kind!=="missing"&&P(st=>{const F=new Set(st.stayIds),he=new Set(st.tripIds);return ve.kind==="stay"?F.has(ve.id)?F.delete(ve.id):F.add(ve.id):he.has(ve.id)?he.delete(ve.id):(he.add(ve.id),h(ve.id)),{stayIds:[...F],tripIds:[...he]}})},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(I,{tone:ve.kind==="trip"?"signal":ve.kind==="missing"?"meta":"default",className:"bg-white/[0.08] text-white/82",children:ve.kind==="missing"?"gap":ve.kind}),e.jsx("span",{className:"text-[11px] text-white/46",children:Cs(ve.durationSeconds)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"line-clamp-2 text-sm font-semibold text-white",children:ve.label}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/52",children:ve.subtitle})]})]},ve.id)})})]})}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{tone:"signal",children:e8(n)}),e.jsxs(I,{tone:"default",className:"bg-white/[0.06] text-white/72",children:[xe.summary.tripCount," trips"]}),e.jsxs(I,{tone:"default",className:"bg-white/[0.06] text-white/72",children:[xe.summary.stayCount," stays"]}),e.jsxs(I,{tone:"meta",children:[xe.summary.missingCount," gaps"]})]})]}),e.jsx("div",{className:"grid gap-4",children:G.data?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Selected trip"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsx(W,{variant:"ghost",className:"h-9 rounded-full border border-white/10 bg-white/[0.04] px-4",onClick:()=>x(ve=>!ve),children:u?"Stylized graph":"Exact path"})})]}),u?e.jsx(d8,{points:G.data.trip.points}):e.jsx(o8,{curve:G.data.stylizedPath.curve,startLabel:G.data.stylizedPath.startLabel,endLabel:G.data.stylizedPath.endLabel,stopLabels:G.data.stylizedPath.stops.map(ve=>ve.label)}),e.jsxs(ce,{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Trip context"}),(()=>{const ve=Dl(G.data.trip);return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(I,{tone:"signal",children:Ni(G.data.trip.distanceMeters)}),e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:G.data.trip.activityType||G.data.trip.travelMode}),e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:Cs(G.data.trip.durationSeconds)}),e.jsx(I,{tone:"default",className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:Kt(ve.rateApPerHour)}),e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:St(ve.totalAp)})]})})})(),e.jsx("div",{className:"mt-4 text-sm leading-6 text-white/58",children:t8(G.data.trip.startedAt,G.data.trip.endedAt)}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Hourly estimate"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Cs(G.data.trip.estimatedScreenTimeSeconds)})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Pickups"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:G.data.trip.pickupCount})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Notifications"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:G.data.trip.notificationCount})]})]}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/48",children:"Derived from Screen Time hourly bins, not exact foreground traces."}),G.data.trip.topApps.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:G.data.trip.topApps.map(ve=>e.jsx(I,{tone:"default",className:"bg-[rgba(114,204,255,0.12)] text-white/80",children:(ve.displayName||ve.bundleIdentifier)+" · "+Cs(ve.totalActivitySeconds)},ve.id))}):null,G.data.trip.topCategories.length>0?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:G.data.trip.topCategories.map(ve=>e.jsx(I,{tone:"default",className:"bg-white/[0.05] text-white/64",children:ve.categoryLabel},ve.id))}):null]})]}):e.jsx(ce,{className:"rounded-[30px] border border-dashed border-white/12 bg-white/[0.03] p-6 text-white/58",children:"Select a trip segment to open the stylized trajectory card and exact path toggle."})})]}):null,i==="month"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.4fr)_minmax(18rem,0.85fr)]",children:[e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(9,15,28,0.97),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Month view"}),e.jsx(vt,{content:"This chart stays quantitative. Switch the metric to compare daily distance, moving time, idle time, or calories across the month."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Switch the Y-axis between motion, idle time, and energy without losing the same monthly frame."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ye,{type:"month",value:o,onChange:ve=>d(ve.target.value),className:"w-[10.5rem]"}),["distanceMeters","movingSeconds","idleSeconds","caloriesKcal"].map(ve=>e.jsx(W,{variant:"ghost",className:te("h-9 rounded-full border px-4 text-sm",Y===ve?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/10 bg-white/[0.04] text-white/62"),onClick:()=>z(ve),children:ve==="distanceMeters"?"Distance":ve==="movingSeconds"?"Moving":ve==="idleSeconds"?"Idle":"Calories"},ve))]})]}),e.jsx("div",{className:"mt-6 h-[24rem]",children:e.jsx(Fi,{width:"100%",height:"100%",children:e.jsxs(Er,{data:V.days,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"movementMonthFill",x1:"0",x2:"0",y1:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgba(110,220,255,0.7)"}),e.jsx("stop",{offset:"100%",stopColor:"rgba(110,220,255,0.05)"})]})}),e.jsx(Fn,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(ai,{dataKey:"dateKey",tick:{fill:"rgba(255,255,255,0.46)",fontSize:11},axisLine:!1,tickLine:!1}),e.jsx(ii,{tick:{fill:"rgba(255,255,255,0.46)",fontSize:11},axisLine:!1,tickLine:!1}),e.jsx(Lr,{contentStyle:{background:"rgba(7,12,24,0.94)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:16},formatter:ve=>s8(Y,Number(ve))}),e.jsx(Za,{type:"monotone",dataKey:Y,stroke:"rgba(126,233,255,0.95)",fill:"url(#movementMonthFill)",strokeWidth:2.4})]})})})]}),e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Month totals"}),e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Ni(V.totals.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Moving time"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Cs(V.totals.movingSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Settled time"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Cs(V.totals.idleSeconds)})]})]})]})]}):null,i==="all_time"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.35fr)_minmax(20rem,0.95fr)]",children:[e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(8,13,25,0.97),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Trips"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:Se.summary.tripCount})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Known places"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:Se.summary.knownPlaceCount})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:Ni(Se.summary.totalDistanceMeters)})]}),e.jsxs(ce,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Countries"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:Se.summary.visitedCountries})]})]}),e.jsx("div",{className:"mt-6 grid gap-3 sm:grid-cols-2",children:Se.recentTrips.map(ve=>e.jsx("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4 text-left transition hover:bg-white/[0.06]",onClick:()=>{r("day"),h(ve.id)},children:(()=>{const Le=Dl({startedAt:ve.startedAt,endedAt:new Date(new Date(ve.startedAt).getTime()+36e5).toISOString(),expectedMet:2});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Recent travel"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ve.label||"Untitled trip"}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[Ni(ve.distanceMeters)," · ",ve.activityType||"travel"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(I,{tone:"default",className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:Kt(Le.rateApPerHour)})})]})})()},ve.id))})]}),e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Place categories"}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:Se.categoryBreakdown.map(ve=>e.jsxs(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:[ve.tag," · ",ve.count]},ve.tag))})]})]}):null,e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.25fr)_minmax(22rem,0.95fr)]",children:[e.jsx(vb,{children:e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(8,14,28,0.96),rgba(9,15,28,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Known places"}),e.jsx(vt,{content:"Known places turn raw stationary spans into named contexts like home, work, gym, nature, or any custom place tag you want Forge to remember."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"These landmarks anchor stays, travel XP, and contextual reasoning in both Forge and the companion. Seeded tags like home, workplace, gym, holiday, grocery, or nature matter for downstream calculations, but place tags stay open-ended."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:Q,onChange:ve=>X(ve.target.value),placeholder:"Search places",className:"w-[11rem]"}),e.jsx(W,{onClick:()=>{R(null),H(!0)},children:"Add place"})]})]}),e.jsx("div",{className:"mt-5 grid gap-3",children:ie.map(ve=>e.jsxs("button",{type:"button",className:"flex items-start justify-between gap-3 rounded-[24px] border border-white/8 bg-white/[0.03] p-4 text-left transition hover:bg-white/[0.06]",onClick:()=>{R(ve),H(!0)},children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg text-white",children:ve.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[ve.latitude.toFixed(4),", ",ve.longitude.toFixed(4)," · radius ",Math.round(ve.radiusMeters)," m"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:ve.categoryTags.map(Le=>e.jsx(I,{tone:"default",className:"bg-white/[0.06] text-white/74",children:Le},Le))})]}),e.jsx(da,{className:"mt-1 size-4 text-white/42"})]},ve.id))})]})}),e.jsxs(ce,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Movement help"}),e.jsx(vt,{content:"Most movement surfaces on this page have help buttons. Use them to understand the graph, the day strip, the month chart, and the place system without keeping a large prose block on screen."})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Use the small help icons across this page for graph explanations, timeline semantics, and metric meanings."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Life graph"}),e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Day strip"}),e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Month chart"}),e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Known places"}),e.jsx(I,{className:"bg-white/[0.06] text-white/74",children:"Selection aggregate"})]})]})]}),G.data?e.jsx(pa,{open:g,onOpenChange:ve=>{p(ve),ve||(b(""),C([]),w(null),y(null))},eyebrow:"Movement data",title:G.data.trip.label||"Trip datapoints",description:"Inspect the raw datapoints behind this trip. Raw measurements are read-only here; visible movement corrections now happen through canonical user-defined boxes.",children:e.jsx(jb,{children:e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,24rem)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(mi,{title:"Datapoint browser",description:"Search raw points by time band, anchor status, or accuracy before opening the point editor.",query:f,onQueryChange:b,options:Ie,selectedOptionIds:A,onSelectedOptionIdsChange:C,resultSummary:M,placeholder:"Search timestamps, accuracy, point ids, or filter chips",emptyStateMessage:"Keep typing or pick a time/quality chip to narrow the trip datapoints."}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Raw datapoints"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a point to correct or delete it."})]}),e.jsx(I,{tone:"meta",children:M})]}),e.jsx("div",{ref:K,className:"h-[34rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:Ne.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No datapoint matches the current search. Clear some filters or search by time, anchor type, or accuracy."}):e.jsx("div",{className:"relative w-full",style:{height:`${E.getTotalSize()}px`},children:E.getVirtualItems().map(ve=>{const Le=Ne[ve.index];return e.jsx("div",{className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${ve.start}px)`},children:e.jsxs("button",{type:"button",className:te("grid w-full gap-3 rounded-[20px] border px-4 py-3 text-left transition",T===Le.id?"border-[rgba(171,232,255,0.34)] bg-[rgba(171,232,255,0.12)]":"border-white/8 bg-white/[0.04] hover:bg-white/[0.07]"),onClick:()=>{w(Le.id),y(Wp(Le))},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Fa,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:Bm(Le.recordedAt)})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[Le.latitude.toFixed(5),", ",Le.longitude.toFixed(5)]})]}),e.jsx(I,{tone:Le.isStopAnchor?"signal":"meta",children:Le.isStopAnchor?"Stop anchor":"Path point"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(I,{tone:"meta",className:"capitalize",children:Cd(Le.recordedAt)}),Le.accuracyMeters!=null?e.jsxs(I,{tone:"meta",children:[Math.round(Le.accuracyMeters)," m accuracy"]}):null,Le.speedMps!=null?e.jsxs(I,{tone:"meta",children:[Le.speedMps.toFixed(1)," m/s"]}):null]})]})},Le.id)})})})]})]}),O&&S?e.jsx(c8,{point:O,draft:S}):e.jsx(ce,{className:"rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] p-6 text-white/56",children:"Pick a datapoint to inspect its raw measurement details. To correct what the user sees, use canonical user-defined movement boxes in the Life Timeline."})]})})}):null,e.jsx(Mw,{open:v,onOpenChange:H,place:j,onSave:async ve=>{await Ae.mutateAsync(ve)}})]})}function m8(t){return t.trim().toLowerCase()}function h8(t,s){return t.includes(s)?t:[...t,s]}function p8({entityOptions:t,selectedEntityValues:s,onSelectedEntityValuesChange:a,selectedTextTerms:i,onSelectedTextTermsChange:r,placeholder:n="Filter by linked entity or add free text"}){const[l,o]=c.useState(""),[d,m]=c.useState(!1),[h,u]=c.useState(0),x=m8(l),g=c.useMemo(()=>s.map(w=>t.find(S=>S.value===w)).filter(Boolean),[t,s]),p=c.useMemo(()=>{const w=t.filter(S=>!s.includes(S.value));return x?w.filter(S=>`${S.label} ${S.description??""} ${S.searchText??""}`.toLowerCase().includes(x)).slice(0,8):w.slice(0,8)},[t,x,s]),f=l.trim().length>0&&!i.includes(l.trim()),b=w=>{a(h8(s,w)),o(""),u(0),m(!1)},A=(w=l)=>{const S=w.trim();!S||i.includes(S)||(r([...i,S]),o(""),u(0),m(!1))},C=w=>{a(s.filter(S=>S!==w))},T=w=>{r(i.filter(S=>S!==w))};return e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-[11px] uppercase tracking-[0.16em] text-white/40",children:[e.jsx("span",{children:"Search hints: entity chips match linked records, free-text chips match note body or author."}),e.jsx("button",{type:"button",onClick:()=>A(),disabled:!f,className:"rounded-full border border-white/8 bg-white/[0.04] px-2.5 py-1 text-[10px] tracking-[0.14em] text-white/62 transition hover:bg-white/[0.08] hover:text-white disabled:cursor-not-allowed disabled:opacity-40",children:"Free text"})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,28,48,0.88),rgba(10,14,26,0.98))] px-4 py-3 shadow-[0_24px_70px_rgba(3,8,18,0.2)]",children:[g.length>0||i.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[g.map(w=>e.jsxs("span",{className:"inline-flex max-w-full items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[w.kind?e.jsx(We,{kind:w.kind,label:w.label,compact:!0,gradient:!1,className:"max-w-[16rem]"}):e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:w.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>C(w.value),"aria-label":`Remove ${w.label}`,children:e.jsx(Tt,{className:"size-3.5"})})]},w.value)),i.map(w=>e.jsxs("span",{className:"inline-flex max-w-full items-center gap-2 rounded-full border border-cyan-300/16 bg-cyan-400/10 px-2.5 py-1.5 text-sm text-cyan-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Zm,{className:"size-3.5"}),e.jsx("span",{className:"max-w-[16rem] truncate",children:w})]}),e.jsx("button",{type:"button",className:"rounded-full text-cyan-100/70 transition hover:text-white",onClick:()=>T(w),"aria-label":`Remove free-text filter ${w}`,children:e.jsx(Tt,{className:"size-3.5"})})]},w))]}):null,i.length>1?e.jsx("div",{className:"mb-3 text-xs text-white/42",children:"Free-text chips are combined with OR."}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/34"}),e.jsx("input",{value:l,onChange:w=>{o(w.target.value),m(!0),u(0)},onFocus:()=>m(!0),onBlur:()=>{window.setTimeout(()=>m(!1),120)},onKeyDown:w=>{if(w.key==="Backspace"&&!l){if(i.length>0){T(i[i.length-1]);return}s.length>0&&C(s[s.length-1]);return}if(w.key==="ArrowDown"){w.preventDefault(),m(!0),u(y=>p.length===0?0:Math.min(p.length-1,y+1));return}if(w.key==="ArrowUp"){w.preventDefault(),u(y=>Math.max(0,y-1));return}if(w.key==="Escape"){m(!1);return}if(w.key!=="Enter")return;w.preventDefault();const S=p[h];if(S){b(S.value);return}A()},placeholder:n,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),d?e.jsxs("div",{className:"absolute top-full z-20 mt-2 w-full rounded-[22px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:[p.map((w,S)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",S===h?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>u(S),onMouseDown:y=>y.preventDefault(),onClick:()=>b(w.value),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:w.kind?e.jsx(We,{kind:w.kind,label:w.label,compact:!0,gradient:!1}):w.label}),w.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:w.description}):null]})},w.value)),f?e.jsxs("button",{type:"button",className:"mt-1 flex w-full items-center gap-2 rounded-[18px] px-3 py-2.5 text-left text-sm text-cyan-100 transition hover:bg-white/[0.06]",onMouseDown:w=>w.preventDefault(),onClick:()=>A(),children:[e.jsx(Zm,{className:"size-4"}),e.jsxs("span",{className:"truncate",children:['Add free text "',l.trim(),'"']})]}):null,p.length===0&&!f?e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:"Keep typing to find a linked entity, or press Enter to add a free-text badge."}):null]}):null]})]})]})}const x8=new Set(["goal","project","task","strategy","habit","tag","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","trigger_report"]);function Fw(t){return x8.has(t)}function Fs(t,s){return`${t}:${s}`}function Ql(t){const s=t.indexOf(":");if(s<=0||s>=t.length-1)return null;const a=t.slice(0,s);return Fw(a)?{entityType:a,entityId:t.slice(s+1)}:null}function Hp(t){return t!==null}function Gp(t){const s=t.getAll("linkedTo"),a=t.get("entityType"),i=t.get("entityId");return a&&i&&Fw(a)&&s.unshift(Fs(a,i)),Array.from(new Set(s.map(r=>r.trim()).filter(Boolean)))}function g8(t){return Array.from(new Set(t.getAll("textTerms").map(s=>s.trim()).filter(Boolean)))}function f8(t){return js(t.getAll("tags"))}function bn(t,s=[]){return{contentMarkdown:(t==null?void 0:t.contentMarkdown)??"",author:(t==null?void 0:t.author)??"",linkedValues:(t==null?void 0:t.links.map(a=>Fs(a.entityType,a.entityId)))??s,tags:js((t==null?void 0:t.tags)??[]),destroyAtInput:Yb((t==null?void 0:t.destroyAt)??null),destroyDelayValue:"",destroyDelayUnit:"days"}}function b8(t){return[...t].sort((s,a)=>s.label.localeCompare(a.label))}function Qp(t){return qo(t.destroyAtInput)??Jb(t.destroyDelayValue,t.destroyDelayUnit)}function w8(){var V,Se,Ee,Ce,qe,oe,L;const t=$t(),s=ct(),a=jt(),[i,r]=ms(),[n,l]=c.useState(()=>Gp(i)),[o,d]=c.useState(()=>f8(i)),[m,h]=c.useState(()=>g8(i)),[u,x]=c.useState(i.get("author")??""),[g,p]=c.useState(i.get("updatedFrom")??""),[f,b]=c.useState(i.get("updatedTo")??""),[A,C]=c.useState(!1),[T,w]=c.useState(()=>bn(null,Gp(i))),[S,y]=c.useState(null),[N,P]=c.useState(null),[v,H]=c.useState(null),j=Fe({queryKey:["forge-psyche-values"],queryFn:Vs}),R=Fe({queryKey:["forge-psyche-patterns"],queryFn:Oa}),Q=Fe({queryKey:["forge-psyche-behaviors"],queryFn:Xs}),X=Fe({queryKey:["forge-psyche-beliefs"],queryFn:Ca}),Y=Fe({queryKey:["forge-psyche-modes"],queryFn:za}),z=Fe({queryKey:["forge-psyche-reports"],queryFn:xi}),K=Array.isArray(a.selectedUserIds)?a.selectedUserIds:[],$=Fe({queryKey:["forge-life-force",...K],queryFn:async()=>(await Ji(K)).lifeForce});c.useEffect(()=>{const U=new URLSearchParams;for(const ge of n)U.append("linkedTo",ge);for(const ge of o)U.append("tags",ge);for(const ge of m)U.append("textTerms",ge);u.trim()&&U.set("author",u.trim()),g&&U.set("updatedFrom",g),f&&U.set("updatedTo",f),r(U,{replace:!0})},[u,n,o,m,r,g,f]);const D=c.useMemo(()=>{var ge,Te,ve,Le,Qe,st;const U=[...a.snapshot.goals.map(F=>({value:Fs("goal",F.id),label:F.title,description:ut(F.description,F.user,"Goal"),searchText:dt([F.title,F.description],F),kind:Xt("goal")??void 0})),...a.snapshot.dashboard.projects.map(F=>({value:Fs("project",F.id),label:F.title,description:ut(`${F.description}${F.description?" · ":""}${F.goalTitle}`,F.user,F.goalTitle),searchText:dt([F.title,F.description,F.goalTitle],F),kind:Xt("project")??void 0})),...a.snapshot.tasks.map(F=>({value:Fs("task",F.id),label:F.title,description:ut(`${F.description}${F.description?" · ":""}${F.owner}`,F.user,F.owner),searchText:dt([F.title,F.description,F.owner],F),kind:Xt("task")??void 0})),...a.snapshot.strategies.map(F=>({value:Fs("strategy",F.id),label:F.title,description:ut(F.overview,F.user,"Strategy"),searchText:dt([F.title,F.overview,F.endStateDescription],F),kind:Xt("strategy")??void 0})),...a.snapshot.habits.map(F=>({value:Fs("habit",F.id),label:F.title,description:ut(F.description,F.user,"Habit"),searchText:dt([F.title,F.description],F),kind:Xt("habit")??void 0})),...a.snapshot.tags.map(F=>({value:Fs("tag",F.id),label:F.name,description:ut(F.description,F.user,F.kind),searchText:dt([F.name,F.kind,F.description],F),kind:Xt("tag")??void 0})),...(((ge=j.data)==null?void 0:ge.values)??[]).map(F=>({value:Fs("psyche_value",F.id),label:F.title,description:ut(F.description,F.user,"Psyche value"),searchText:dt([F.title,F.description,F.valuedDirection],F),kind:Xt("psyche_value")??void 0})),...(((Te=R.data)==null?void 0:Te.patterns)??[]).map(F=>({value:Fs("behavior_pattern",F.id),label:F.title,description:ut(F.description,F.user,"Behavior pattern"),searchText:dt([F.title,F.description,F.targetBehavior],F),kind:Xt("behavior_pattern")??void 0})),...(((ve=Q.data)==null?void 0:ve.behaviors)??[]).map(F=>({value:Fs("behavior",F.id),label:F.title,description:ut(F.description,F.user,"Behavior"),searchText:dt([F.title,F.description,F.kind],F),kind:Xt("behavior")??void 0})),...(((Le=X.data)==null?void 0:Le.beliefs)??[]).map(F=>({value:Fs("belief_entry",F.id),label:F.statement,description:ut(F.flexibleAlternative||F.originNote,F.user,"Belief"),searchText:dt([F.statement,F.flexibleAlternative,F.originNote],F),kind:Xt("belief_entry")??void 0})),...(((Qe=Y.data)==null?void 0:Qe.modes)??[]).map(F=>({value:Fs("mode_profile",F.id),label:F.title,description:ut(F.archetype||F.family,F.user,"Mode"),searchText:dt([F.title,F.archetype,F.family,F.persona],F),kind:Xt("mode_profile")??void 0})),...(((st=z.data)==null?void 0:st.reports)??[]).map(F=>({value:Fs("trigger_report",F.id),label:F.title,description:ut(F.eventSituation,F.user,"Trigger report"),searchText:dt([F.title,F.eventSituation,F.customEventType??""],F),kind:Xt("trigger_report")??void 0}))];return b8(U)},[(V=Q.data)==null?void 0:V.behaviors,(Se=X.data)==null?void 0:Se.beliefs,(Ee=Y.data)==null?void 0:Ee.modes,(Ce=R.data)==null?void 0:Ce.patterns,(qe=z.data)==null?void 0:qe.reports,a.snapshot.dashboard.projects,a.snapshot.goals,a.snapshot.habits,a.snapshot.strategies,a.snapshot.tags,a.snapshot.tasks,(oe=j.data)==null?void 0:oe.values]),J=c.useMemo(()=>D.map(U=>{const ge=Ql(U.value);return{value:U.value,label:U.label,description:U.description,searchText:U.searchText,kind:U.kind,entityType:(ge==null?void 0:ge.entityType)??"goal",entityId:(ge==null?void 0:ge.entityId)??""}}),[D]),q=c.useMemo(()=>n.map(U=>Ql(U)).filter(Boolean),[n]),_=Fe({queryKey:["notes-index",n.join("|"),o.join("|"),m.join("|"),u.trim(),g,f],queryFn:()=>tf({linkedTo:q,tags:o,textTerms:m,author:u.trim()||void 0,updatedFrom:g||void 0,updatedTo:f||void 0,limit:200})}),B=async()=>{await Promise.all([s.invalidateQueries({queryKey:["notes-index"]}),Ut(s)])},G=Re({mutationFn:async U=>wl({contentMarkdown:U.contentMarkdown.trim(),author:U.author.trim()||null,tags:js(U.tags),destroyAt:Qp(U),links:U.linkedValues.map(ge=>Ql(ge)).filter(Hp).map(ge=>({entityType:ge.entityType,entityId:ge.entityId}))}),onSuccess:async()=>{w(bn(null,n)),C(!1),await B()}}),ae=Re({mutationFn:async({noteId:U,draft:ge})=>Zn(U,{contentMarkdown:ge.contentMarkdown.trim(),author:ge.author.trim()||null,tags:js(ge.tags),destroyAt:Qp(ge),links:ge.linkedValues.map(Te=>Ql(Te)).filter(Hp).map(Te=>({entityType:Te.entityType,entityId:Te.entityId}))}),onSuccess:async()=>{y(null),P(null),await B()}}),ke=Re({mutationFn:U=>em(U),onSuccess:B}),Ae=((L=_.data)==null?void 0:L.notes)??[],ie=new Date().toISOString().slice(0,10),Ne=Ae.filter(U=>U.createdAt.slice(0,10)===ie).length*Fl().totalAp,M=v?Ae.find(U=>U.id===v.noteId)??null:null,E=M?jh(M):null,O=E?ci(E.entityType,E.entityId):null,xe=c.useMemo(()=>M?[{id:"open-linked",label:"Open linked record",description:O?"Jump back into the main entity this note is attached to.":"This note has no navigable linked record yet.",icon:Es,disabled:!O,onSelect:()=>{O&&t(O.includes("#")?O:`${O}#notes`)}},{id:"edit-note",label:"Edit note",description:"Update the Markdown body, note tags, expiry, or connected entity links.",icon:pi,onSelect:()=>{y(M.id),P(bn(M))}},{id:"delete-note",label:"Delete note",description:"Soft-delete this note from the main workspace.",icon:Rt,tone:"danger",disabled:ke.isPending,onSelect:()=>{ke.mutateAsync(M.id)}}]:[],[O,M,ke,t]);return _.isError?e.jsx(it,{eyebrow:"Notes",error:_.error,onRetry:()=>void _.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:"Notes",titleText:"Notes",description:"Notes are first-class Markdown entities in Forge. Search them by linked records, note tags, date, or free text, then create durable or ephemeral notes that stay connected to the rest of the graph.",badge:`${Ae.length} visible`,actions:e.jsxs(W,{onClick:()=>{w(bn(null,n)),C(!0)},children:[e.jsx(ds,{className:"size-4"}),"New note"]})}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(ce,{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:"Quick note default"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:St(Fl().totalAp)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Standalone notes count as a tiny Action Point impulse unless a richer active work context already covers them."})]}),e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Notes created today"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:St(Ne)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Visible notes created today in this workspace at the default quick note cost."})]}),e.jsxs(ce,{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:$.data?`${St($.data.spentTodayAp)} / ${St($.data.dailyBudgetAp)}`:"Loading..."}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Notes participate in the same Action Point ledger as tasks, habits, movement, and calendar work."})]}),e.jsxs(ce,{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:$.data?Kt($.data.instantFreeApPerHour):"Loading..."}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Useful when deciding whether to just capture a quick note or stay inside a heavier work stream."})]})]}),e.jsx(Nb,{children:e.jsxs(ce,{className:"grid gap-4",children:[e.jsx(p8,{entityOptions:J,selectedEntityValues:n,onSelectedEntityValuesChange:l,selectedTextTerms:m,onSelectedTextTermsChange:h}),e.jsx(Oi,{value:o,onChange:d,placeholder:"Filter by memory tag or custom note tag"}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(12rem,0.38fr)_minmax(12rem,0.38fr)]",children:[e.jsx(ye,{value:u,onChange:U=>x(U.target.value),placeholder:"Filter by author"}),e.jsx(ye,{type:"date",value:g,onChange:U=>p(U.target.value)}),e.jsx(ye,{type:"date",value:f,onChange:U=>b(U.target.value)})]})]})}),A?e.jsx(kb,{children:e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"New note"}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/58",children:["Notes are independent Markdown entities. Link them to one or more real records, add memory-system or custom tags, and optionally make them ephemeral with an automatic destroy time. Standalone notes default to"," ",St(Fl().totalAp),"."]})]}),e.jsx(W,{variant:"ghost",onClick:()=>{C(!1),w(bn(null,n))},children:"Cancel"})]}),e.jsx(Ze,{value:T.contentMarkdown,onChange:U=>w(ge=>({...ge,contentMarkdown:U.target.value})),className:"min-h-[16rem]",placeholder:"Write the note in Markdown. This can be as short as a handoff line or as long as a wiki page."}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]",children:[e.jsx(ye,{value:T.author,onChange:U=>w(ge=>({...ge,author:U.target.value})),placeholder:"Optional author"}),e.jsx(mt,{options:D,selectedValues:T.linkedValues,onChange:U=>w(ge=>({...ge,linkedValues:U})),placeholder:"Link this note to strategies, goals, projects, tasks, habits, or human/bot-owned records",emptyMessage:"No matching entities found yet."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(Oi,{value:T.tags,onChange:U=>w(ge=>({...ge,tags:U}))}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Ephemeral auto-destroy"}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/48",children:"Set an exact destroy time or a relative delay. Leaving both blank keeps the note durable."})]}),e.jsx(ye,{type:"datetime-local",value:T.destroyAtInput,onChange:U=>w(ge=>({...ge,destroyAtInput:U.target.value}))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ye,{type:"number",min:"1",value:T.destroyDelayValue,onChange:U=>w(ge=>({...ge,destroyDelayValue:U.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:T.destroyDelayUnit,onChange:U=>w(ge=>({...ge,destroyDelayUnit:U.target.value})),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Preview"}),e.jsx("div",{className:"mt-3",children:T.contentMarkdown.trim()?e.jsx(Rs,{markdown:T.contentMarkdown}):e.jsx("div",{className:"text-sm text-white/42",children:"Markdown preview appears here."})})]}),e.jsx("div",{className:"flex flex-wrap justify-end gap-2",children:e.jsx(W,{pending:G.isPending,pendingLabel:"Saving",disabled:T.contentMarkdown.trim().length===0||T.linkedValues.length===0,onClick:()=>void G.mutateAsync(T),children:"Save note"})})]})}):null,_.isLoading?e.jsx(ce,{className:"text-sm text-white/58",children:"Loading notes…"}):Ae.length===0?e.jsx(Bt,{eyebrow:"Notes",title:"No matching notes yet",description:"Try broader linked-entity filters, remove a date bound, or add the first durable note from the button above."}):e.jsx(Sb,{children:e.jsx("div",{className:"grid gap-3",children:Ae.map(U=>{const ge=jh(U),Te=ge?ci(ge.entityType,ge.entityId):null,ve=S===U.id&&N!==null;return e.jsxs(ce,{className:"min-w-0 overflow-hidden p-5",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:[(U.author??"Unknown author").toString()," •"," ",new Date(U.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-[var(--primary)]/12 text-[var(--primary)]",wrap:!0,children:[St(Fl().totalAp)," ","quick note"]}),U.links.map(Le=>e.jsxs(I,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[Ea(Le.entityType),Le.anchorKey?` · ${$n(Le.anchorKey)}`:""]},`${U.id}-${Le.entityType}-${Le.entityId}-${Le.anchorKey??""}`)),(U.tags??[]).map(Le=>e.jsx(I,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:Le},`${U.id}-tag-${Le}`)),U.destroyAt?e.jsxs(I,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(U.destroyAt).toLocaleString()]}):null]})]}),e.jsx("button",{type:"button",className:"rounded-full border border-white/8 bg-white/[0.04] p-2 text-white/58 transition hover:bg-white/[0.08] hover:text-white",onClick:Le=>{Le.preventDefault(),Le.stopPropagation();const Qe=Le.currentTarget.getBoundingClientRect();H({noteId:U.id,position:{x:Qe.right-8,y:Qe.bottom+8}})},"aria-label":`Open actions for note ${U.id}`,children:e.jsx(Di,{className:"size-4"})})]}),ve?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(Ze,{value:N.contentMarkdown,onChange:Le=>P(Qe=>Qe&&{...Qe,contentMarkdown:Le.target.value}),className:"min-h-[14rem]"}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]",children:[e.jsx(ye,{value:N.author,onChange:Le=>P(Qe=>Qe&&{...Qe,author:Le.target.value}),placeholder:"Optional author"}),e.jsx(mt,{options:D,selectedValues:N.linkedValues,onChange:Le=>P(Qe=>Qe&&{...Qe,linkedValues:Le}),placeholder:"Update the linked entities",emptyMessage:"No matching entities found yet."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(Oi,{value:N.tags,onChange:Le=>P(Qe=>Qe&&{...Qe,tags:Le})}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Ephemeral auto-destroy"}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/48",children:"Set an exact destroy time or a relative delay. Leaving both blank keeps the note durable."})]}),e.jsx(ye,{type:"datetime-local",value:N.destroyAtInput,onChange:Le=>P(Qe=>Qe&&{...Qe,destroyAtInput:Le.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ye,{type:"number",min:"1",value:N.destroyDelayValue,onChange:Le=>P(Qe=>Qe&&{...Qe,destroyDelayValue:Le.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:N.destroyDelayUnit,onChange:Le=>P(Qe=>Qe&&{...Qe,destroyDelayUnit:Le.target.value}),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Preview"}),e.jsx("div",{className:"mt-3",children:N.contentMarkdown.trim()?e.jsx(Rs,{markdown:N.contentMarkdown}):e.jsx("div",{className:"text-sm text-white/42",children:"No content yet."})})]}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx(W,{variant:"ghost",onClick:()=>{y(null),P(null)},children:"Cancel"}),e.jsx(W,{pending:ae.isPending,pendingLabel:"Saving",disabled:N.contentMarkdown.trim().length===0||N.linkedValues.length===0,onClick:()=>void ae.mutateAsync({noteId:U.id,draft:N}),children:"Save changes"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"mt-4 w-full text-left",onClick:()=>{Te&&t(Te.includes("#")?Te:`${Te}#notes`)},disabled:!Te,children:e.jsx(Rs,{markdown:U.contentMarkdown,className:"line-clamp-none"})}),Te?e.jsx("div",{className:"mt-4 inline-flex text-xs uppercase tracking-[0.16em] text-[var(--secondary)]",children:"Open linked record"}):null]})]},U.id)})})}),e.jsx(vd,{open:!!v,title:"Note actions",subtitle:M?M.contentPlain.slice(0,80)||"Markdown note":void 0,items:xe,position:(v==null?void 0:v.position)??null,onClose:()=>H(null)})]})}const Vl={lg:1280,md:996,sm:768,xs:480},wu={lg:12,md:10,sm:6,xs:4,xxs:2},y8="forge.surface-layout.v3";function _w(t){return`${y8}.${t}`}function yu(t,s,a){return Math.min(Math.max(t,s),a)}function v8(t){return t>=Vl.lg?"lg":t>=Vl.md?"md":t>=Vl.sm?"sm":t>=Vl.xs?"xs":"xxs"}function j8(t,s){const a=wu[s];if(s==="lg")return yu(t.defaultWidth,t.minWidth??1,Math.min(t.maxWidth??a,a));const i=Math.round(t.defaultWidth/wu.lg*a);return yu(Math.max(t.minWidth??1,i||(t.minWidth??1)),t.minWidth??1,Math.min(t.maxWidth??a,a))}function N8(t){return{hidden:t.defaultHidden??!1,fullWidth:t.defaultFullWidth??!1,titleVisible:t.defaultTitleVisible??!0,descriptionVisible:t.defaultDescriptionVisible??!0}}function vu(t,s){const a=[...s.filter(i=>i.defaultPlacement==="top"),...s.filter(i=>i.defaultPlacement!=="top")];return{surfaceId:t,order:a.map(i=>i.id),widgets:Object.fromEntries(s.map(i=>[i.id,N8(i)])),updatedAt:new Date(0).toISOString()}}function oc(t,s,a){const i=vu(t,s),r=new Set(s.map(d=>d.id)),n=((a==null?void 0:a.order)??[]).filter(d=>r.has(d)),l=i.order.filter(d=>!n.includes(d)),o=Object.fromEntries(s.map(d=>{var h,u,x,g,p;const m=(h=a==null?void 0:a.widgets)==null?void 0:h[d.id];return[d.id,{...i.widgets[d.id],hidden:(m==null?void 0:m.hidden)??((u=i.widgets[d.id])==null?void 0:u.hidden)??!1,fullWidth:(m==null?void 0:m.fullWidth)??((x=i.widgets[d.id])==null?void 0:x.fullWidth)??!1,titleVisible:(m==null?void 0:m.titleVisible)??((g=i.widgets[d.id])==null?void 0:g.titleVisible)??!0,descriptionVisible:(m==null?void 0:m.descriptionVisible)??((p=i.widgets[d.id])==null?void 0:p.descriptionVisible)??!0}]}));return{surfaceId:t,order:[...n,...l],widgets:o,updatedAt:typeof(a==null?void 0:a.updatedAt)=="string"?a.updatedAt:i.updatedAt}}function k8(t,s){const a=new Map(s.order.map((i,r)=>[i,r]));return[...t].sort((i,r)=>{const n=a.get(i.id)??Number.MAX_SAFE_INTEGER,l=a.get(r.id)??Number.MAX_SAFE_INTEGER;return n!==l?n-l:i.id.localeCompare(r.id)})}function S8(t,s,a){const i=t.indexOf(s);if(i===-1)return t;const r=yu(a,0,t.length-1);if(i===r)return t;const n=[...t];return n.splice(i,1),n.splice(r,0,s),n}function dc(t){if(typeof window>"u")return null;try{const s=window.localStorage.getItem(_w(t));return s?JSON.parse(s):null}catch{return null}}function cc(t){if(!(typeof window>"u"))try{window.localStorage.setItem(_w(t.surfaceId),JSON.stringify(t))}catch{}}const I8=500;function Vp(t,s){return t.surfaceId===s.surfaceId&&JSON.stringify(t.order)===JSON.stringify(s.order)&&JSON.stringify(t.widgets)===JSON.stringify(s.widgets)}function C8({definition:t,preferences:s,editing:a,width:i,children:r}){const n=i<=4;return t.surfaceChrome==="none"?e.jsx("div",{"data-surface-card":"true",className:te("min-w-0",a&&"rounded-[28px] ring-1 ring-white/8 ring-inset"),children:r}):e.jsxs(ce,{"data-surface-card":"true",className:te("surface-grid-card flex min-w-0 flex-col gap-3 overflow-visible p-4 md:p-5",a&&"ring-1 ring-white/8"),children:[s.titleVisible||s.descriptionVisible&&t.description?e.jsxs("div",{className:"min-w-0",children:[s.titleVisible?e.jsx("div",{className:"truncate text-[0.72rem] font-semibold uppercase tracking-[0.16em] text-white/40",children:t.title}):null,s.descriptionVisible&&t.description&&!n?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/52",children:t.description}):null]}):null,e.jsx("div",{className:"min-h-0 flex-1",children:r})]})}function T8({widget:t,preferences:s,index:a,total:i,onMove:r,onToggleHidden:n,onToggleFullWidth:l}){const o=pl({id:t.id});return e.jsxs("div",{ref:o.setNodeRef,style:{transform:xl.Transform.toString(o.transform),transition:o.transition},className:"flex min-w-0 items-center gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[e.jsx("button",{type:"button",className:"inline-flex size-8 shrink-0 items-center justify-center rounded-full bg-white/[0.05] text-white/50 transition hover:bg-white/[0.08] hover:text-white","aria-label":`Drag ${t.title}`,...o.attributes,...o.listeners,children:e.jsx(ul,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:t.title}),t.description?e.jsx("div",{className:"truncate text-[12px] text-white/48",children:t.description}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx("button",{type:"button",className:"inline-flex size-8 items-center justify-center rounded-full bg-white/[0.05] text-white/60 transition hover:bg-white/[0.08] hover:text-white disabled:opacity-40",onClick:()=>r(a-1),disabled:a===0,"aria-label":`Move ${t.title} up`,children:e.jsx(_v,{className:"size-3.5"})}),e.jsx("button",{type:"button",className:"inline-flex size-8 items-center justify-center rounded-full bg-white/[0.05] text-white/60 transition hover:bg-white/[0.08] hover:text-white disabled:opacity-40",onClick:()=>r(a+1),disabled:a===i-1,"aria-label":`Move ${t.title} down`,children:e.jsx(Rv,{className:"size-3.5"})}),e.jsxs("button",{type:"button",className:te("inline-flex h-8 items-center gap-2 rounded-full px-3 text-[12px] transition",s.fullWidth?"bg-[var(--primary)] text-slate-950":"bg-white/[0.05] text-white/72 hover:bg-white/[0.08] hover:text-white"),onClick:l,children:[s.fullWidth?e.jsx($v,{className:"size-3.5"}):e.jsx(Ov,{className:"size-3.5"}),s.fullWidth?"Normal width":"Full width"]}),t.removable!==!1?e.jsxs("button",{type:"button",className:"inline-flex h-8 items-center gap-2 rounded-full bg-white/[0.05] px-3 text-[12px] text-white/72 transition hover:bg-white/[0.08] hover:text-white",onClick:n,children:[e.jsx(Pg,{className:"size-3.5"}),"Hide"]}):null]})]})}function P8({surfaceId:t,widgets:s,defaultEditing:a=!1,actions:i,normalizeLayout:r}){var Y;const n=c.useMemo(()=>JSON.stringify(s.map(z=>({id:z.id,defaultWidth:z.defaultWidth,defaultHidden:z.defaultHidden,defaultPlacement:z.defaultPlacement,defaultFullWidth:z.defaultFullWidth,defaultTitleVisible:z.defaultTitleVisible,defaultDescriptionVisible:z.defaultDescriptionVisible}))),[s]),l=c.useMemo(()=>{const z=vu(t,s);return r?r(z):z},[r,t,n]),o=z=>r?r(z):z,[d,m]=c.useState(a),[h,u]=c.useState(1280),[x,g]=c.useState(()=>o(oc(t,s,dc(t)??l))),p=c.useRef(null),f=c.useRef(!1),b=c.useRef(o(oc(t,s,dc(t)??l))),A=c.useRef(null),C=ld(od(cd,{activationConstraint:{distance:6}})),T=Fe({queryKey:["forge-surface-layout",t],queryFn:()=>i1(t)}),w=Re({mutationFn:z=>r1(t,{order:z.order,widgets:z.widgets})}),S=Re({mutationFn:()=>n1(t)});c.useEffect(()=>{var K;const z=o(oc(t,s,((K=T.data)==null?void 0:K.layout)??dc(t)??l));g($=>Vp($,z)?$:z),cc(z),b.current=z,f.current=!0},[l,(Y=T.data)==null?void 0:Y.layout,r,t,n,s]),c.useEffect(()=>{const z=A.current;if(!z||typeof ResizeObserver>"u")return;const K=new ResizeObserver($=>{var J;const D=((J=$[0])==null?void 0:J.contentRect.width)??z.clientWidth;u(Math.max(320,Math.round(D)))});return K.observe(z),u(Math.max(320,Math.round(z.clientWidth||1280))),()=>K.disconnect()},[]),c.useEffect(()=>{if(f.current&&!Vp(x,b.current))return cc(x),p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{const z=x;w.mutateAsync(z).then(()=>{b.current=z})},I8),()=>{p.current!==null&&window.clearTimeout(p.current)}},[x,w,t]);const y=v8(h),N=wu[y],P=c.useMemo(()=>k8(s,x),[x,s]),v=P.filter(z=>{var K;return!((K=x.widgets[z.id])!=null&&K.hidden)}),H=P.filter(z=>{var K;return(K=x.widgets[z.id])==null?void 0:K.hidden});function j(z,K){g($=>o({...$,widgets:{...$.widgets,[z]:{...$.widgets[z],...K}}}))}function R(z,K){g($=>o({...$,order:S8($.order,z,K)}))}function Q(z){const{active:K,over:$}=z;!$||K.id===$.id||g(D=>{const J=D.order.indexOf(String(K.id)),q=D.order.indexOf(String($.id));return J===-1||q===-1?D:o({...D,order:Vu(D.order,J,q)})})}function X(){const z=o(vu(t,s));g(z),cc(z),b.current=z,S.mutateAsync()}return e.jsxs("div",{className:"grid gap-4",children:[d?e.jsx(dd,{sensors:C,collisionDetection:Qu,onDragEnd:Q,children:e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Visible boxes"}),e.jsx(Xn,{items:v.map(z=>z.id),strategy:Yn,children:e.jsx("div",{className:"grid gap-2",children:v.map((z,K)=>{const $=x.widgets[z.id]??{hidden:!1,fullWidth:!1,titleVisible:!0,descriptionVisible:!0};return e.jsx(T8,{widget:z,preferences:$,index:K,total:v.length,onMove:D=>R(z.id,D),onToggleHidden:()=>j(z.id,{hidden:!0}),onToggleFullWidth:()=>j(z.id,{fullWidth:!$.fullWidth})},z.id)})})}),H.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"pt-2 text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Hidden boxes"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:H.map(z=>e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.06] px-3 py-2 text-sm text-white/76 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>j(z.id,{hidden:!1}),children:z.title},z.id))})]}):null]})}):null,e.jsxs("div",{ref:A,className:"relative",children:[e.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 flex max-w-[calc(100%-1.5rem)] flex-wrap items-center justify-end gap-1.5",children:e.jsxs("div",{className:"pointer-events-auto flex flex-wrap items-center justify-end gap-1.5",children:[i,d?e.jsxs(W,{type:"button",size:"sm",variant:"secondary",className:"h-8 rounded-full border-white/10 bg-[rgba(30,39,69,0.82)] px-2.5 text-[12px] text-white/78 backdrop-blur-xl hover:bg-[rgba(37,47,81,0.94)] hover:text-white",onClick:X,children:[e.jsx(Tg,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Reset"})]}):null,e.jsxs(W,{type:"button",size:"sm",variant:d?"primary":"secondary",className:te("h-8 rounded-full px-2.5 text-[12px] backdrop-blur-xl",d?"bg-[var(--primary)] text-slate-950 hover:opacity-95":"border-white/10 bg-[rgba(30,39,69,0.82)] text-white/78 hover:bg-[rgba(37,47,81,0.94)] hover:text-white"),onClick:()=>m(z=>!z),children:[e.jsx(Fv,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:d?"Done":"Layout"})]})]})}),e.jsx("div",{className:"surface-flow-grid",style:{display:"grid",gap:"16px",gridTemplateColumns:`repeat(${N}, minmax(0, 1fr))`,alignItems:"start"},children:v.map(z=>{const K=x.widgets[z.id]??{hidden:!1,fullWidth:!1,titleVisible:!0,descriptionVisible:!0},$=K.fullWidth?N:Math.min(j8(z,y),N);return e.jsx("div",{style:{gridColumn:`span ${$} / span ${$}`},children:e.jsx(C8,{definition:z,preferences:K,editing:d,width:$,children:e.jsx(X5,{boxId:z.workbenchBoxId??`surface:${t}:${z.id}`,surfaceId:t,children:z.render({compact:$<=4,width:$,editing:d,preferences:K})})})},z.id)})})]})]})}function Td({surfaceId:t,baseWidgets:s,actions:a,normalizeLayout:i}){return e.jsx(P8,{surfaceId:t,widgets:s,normalizeLayout:i,actions:e.jsxs(e.Fragment,{children:[a,e.jsxs(Je,{to:`/workbench?surface=${encodeURIComponent(t)}`,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-white/10 bg-[rgba(32,40,70,0.78)] px-2.5 text-[12px] font-medium text-white/78 backdrop-blur-xl transition hover:border-white/16 hover:bg-[rgba(40,49,82,0.9)] hover:text-white",children:[e.jsx(og,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Workbench"})]})]})})}function Rw({eyebrow:t,title:s,description:a,items:i,tone:r="core",className:n}){return e.jsxs("section",{className:te("min-w-0 overflow-hidden rounded-[28px] border border-white/6 shadow-[0_20px_54px_rgba(4,8,18,0.24)]",r==="core"?"bg-[linear-gradient(180deg,rgba(22,28,46,0.98),rgba(12,17,30,0.95))]":"bg-[linear-gradient(180deg,rgba(16,29,33,0.98),rgba(12,22,27,0.95))]",n),children:[e.jsxs("div",{className:te("grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:px-5",r==="core"?"bg-[radial-gradient(circle_at_top_right,rgba(192,193,255,0.12),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]":"bg-[radial-gradient(circle_at_top_right,rgba(110,231,183,0.1),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]"),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:te("font-label text-[11px] uppercase tracking-[0.2em]",r==="core"?"text-[var(--secondary)]":"text-[rgba(110,231,183,0.82)]"),children:t}),e.jsx("h2",{className:"mt-2 max-w-3xl font-display text-[clamp(1.35rem,2vw,1.9rem)] leading-none text-white",children:s}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:a})]}),e.jsx("div",{className:"grid min-w-0 gap-2 sm:grid-cols-3",children:i.slice(0,3).map(l=>l.href?e.jsxs(Je,{to:l.href,className:te("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm transition hover:bg-white/[0.08]",r==="core"?"bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.025))]":"bg-[linear-gradient(180deg,rgba(110,231,183,0.08),rgba(255,255,255,0.02))]"),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-1.5 min-w-0 font-medium text-white",children:l.title})]},l.id):e.jsxs("div",{className:te("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm",r==="core"?"bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.025))]":"bg-[linear-gradient(180deg,rgba(110,231,183,0.08),rgba(255,255,255,0.02))]"),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-1.5 min-w-0 font-medium text-white",children:l.title})]},l.id))})]}),e.jsx("div",{className:"grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-2 lg:px-5",children:i.map((l,o)=>{const d=te("group flex min-h-[13.5rem] min-w-0 flex-col overflow-hidden rounded-[24px] border border-white/7 p-0 transition hover:-translate-y-0.5 hover:shadow-[0_22px_46px_rgba(3,8,18,0.28)] sm:min-h-[15.5rem]",r==="core"?"bg-[linear-gradient(180deg,rgba(19,26,42,0.98),rgba(11,16,28,0.96))] hover:border-white/12 hover:bg-[linear-gradient(180deg,rgba(24,31,50,0.98),rgba(13,19,33,0.97))]":"bg-[linear-gradient(180deg,rgba(17,29,32,0.98),rgba(9,18,22,0.97))] hover:border-white/12 hover:bg-[linear-gradient(180deg,rgba(21,36,40,0.98),rgba(11,22,27,0.97))]"),m=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:te("flex min-w-0 flex-1 flex-col p-4",r==="core"?"bg-[radial-gradient(circle_at_top_left,rgba(192,193,255,0.1),transparent_28%),linear-gradient(180deg,rgba(255,255,255,0.025),rgba(255,255,255,0))]":"bg-[radial-gradient(circle_at_top_left,rgba(110,231,183,0.08),transparent_28%),linear-gradient(180deg,rgba(255,255,255,0.025),rgba(255,255,255,0))]"),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-2.5 min-w-0 font-display text-[1.25rem] leading-tight text-white sm:text-[1.4rem]",children:l.title})]}),l.badge?e.jsx(I,{wrap:!0,className:"max-w-[10rem] shrink-0 self-start bg-white/[0.08] text-white/72",children:l.badge}):null]}),e.jsx("div",{className:"mt-2.5 text-sm leading-6 text-white/60",children:l.detail}),e.jsx("div",{className:"flex-1"})]}),l.href?e.jsx("div",{className:"border-t border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0.01))] px-4 py-3",children:e.jsxs("div",{className:"inline-flex min-h-10 min-w-0 max-w-full items-center gap-2 rounded-full border border-white/8 bg-white/[0.05] px-4 text-sm text-white/68 transition group-hover:border-white/14 group-hover:bg-white/[0.08] group-hover:text-white",children:[l.actionLabel??"Open",e.jsx(ha,{className:"size-3.5"})]})}):null]});return e.jsx(Ts.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.22,delay:.04*o,ease:"easeOut"},children:l.href?e.jsx(Je,{to:l.href,className:d,children:m}):e.jsx("div",{className:d,children:m})},l.id)})})]})}function A8(t){const s=["summary","body-signals","signals"],a=[...t.order];let i=!1;for(const d of s)a.includes(d)||(a.push(d),i=!0);const r=a.indexOf("summary"),n=a.indexOf("body-signals"),l=a.indexOf("signals");if(r===-1||n===-1||l===-1)return i?{...t,order:a}:t;if(r<n&&n<l&&!i)return t;for(const d of s){const m=a.indexOf(d);m!==-1&&a.splice(m,1)}const o=a.indexOf("goals");return a.splice(o===-1?0:o,0,...s),{...t,order:a}}function M8(t=new Date){const s=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${s}-${a}-${i}`}function Xl(t){if(t>=3600){const s=t/3600;return s>=10||Number.isInteger(s)?`${Math.round(s)}h`:`${s.toFixed(1)}h`}return`${Math.max(1,Math.round(t/60))}m`}function E8(t){return t>=1e3?`${(t/1e3).toFixed(1)} km`:`${Math.round(t)} m`}function L8(t){if(!t)return[];const s=new Map;for(const a of t.segments){if(a.kind!=="stay"||a.durationSeconds<=0)continue;const i=a.label.trim()||"Unlabeled stay";s.set(i,(s.get(i)??0)+a.durationSeconds)}return[...s.entries()].map(([a,i])=>({label:a,seconds:i})).sort((a,i)=>i.seconds-a.seconds).slice(0,3)}function D8(t){return t?["restingHeartRate","heartRateVariabilitySDNN","vo2Max","oxygenSaturation"].map(a=>t.metrics.find(i=>i.metric===a)).filter(a=>!!a).slice(0,3):[]}function F8(t){if(t.latestValue==null)return"No reading";const s=t.unit==="steps"||t.unit==="flights"||t.unit==="kcal"||t.unit==="min"?0:1;return`${t.latestValue.toLocaleString(void 0,{maximumFractionDigits:s,minimumFractionDigits:s===0||t.latestValue>=100?0:1})} ${t.unit}`}function _8(){var R,Q;const{t}=Ot(),s=jt(),a=s.snapshot,i=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],r=M8(),n=Fe({queryKey:["forge-overview-sleep",...i],queryFn:async()=>(await tm(i)).sleep})??{},l=Fe({queryKey:["forge-overview-fitness",...i],queryFn:async()=>(await cf(i)).fitness})??{},o=Fe({queryKey:["forge-overview-movement-day",r,...i],queryFn:async()=>(await mf({date:r,userIds:i})).movement})??{},d=Fe({queryKey:["forge-overview-vitals",...i],queryFn:async()=>(await uf(i)).vitals})??{},m=a.dashboard.milestoneRewards.find(X=>!X.completed)??a.dashboard.milestoneRewards[0]??null,h=a.overview.topTasks[0]??null,u=a.overview.dueHabits[0]??null,x=a.overview.neglectedGoals[0]??null,g=a.overview.recentEvidence[0]??null,p=new Map(a.projects.map(X=>[X.id,X])),f=a.metrics.momentumScore>=80?"Strong":a.metrics.momentumScore>=60?"Steady":"Needs attention",b=((R=n.data)==null?void 0:R.summary)??null,A=((Q=l.data)==null?void 0:Q.summary)??null,C=o.data,T=d.data??null,w=D8(T??void 0),S=L8(C),y=b!==null||A!==null||T!==null,N=C!==void 0&&(C.summary.tripCount>0||C.summary.stayCount>0||C.summary.totalMovingSeconds>0||S.length>0),P=a.lifeForce!==void 0||a.overview.activeGoals.length>0||a.overview.projects.length>0||a.overview.topTasks.length>0||a.overview.recentEvidence.length>0||a.overview.dueHabits.length>0||a.overview.neglectedGoals.length>0||n.isLoading||l.isLoading||o.isLoading||d.isLoading||y||N,v=a.lifeForce?[{label:"Life Force",value:`${Math.round(a.lifeForce.spentTodayAp)} / ${Math.round(a.lifeForce.dailyBudgetAp)} AP`,detail:`Remaining ${St(a.lifeForce.remainingAp)}`},{label:"Momentum",value:`${a.metrics.momentumScore}`,detail:`${f} · ${a.metrics.streakDays} day streak`},{label:"Instant",value:Kt(a.lifeForce.instantFreeApPerHour),detail:a.lifeForce.overloadApPerHour>0?`${Kt(a.lifeForce.overloadApPerHour)} overload`:"Headroom right now"},{label:"Level",value:`L${a.metrics.level}`,detail:`${a.metrics.currentLevelXp} XP in level`},{label:"Weekly XP",value:`${a.metrics.weeklyXp}`,detail:`${a.metrics.totalXp} total XP`}]:[{label:"Level",value:`L${a.metrics.level}`,detail:`${a.metrics.currentLevelXp} XP in level`},{label:"Weekly XP",value:`${a.metrics.weeklyXp}`,detail:`${a.metrics.totalXp} total XP`},{label:"Momentum",value:`${a.metrics.momentumScore}`,detail:`${f} · ${a.metrics.streakDays} day streak`}];function H(X){return X.entityType==="goal"?`/goals/${X.entityId}`:X.entityType==="project"?`/projects/${X.entityId}`:X.entityType==="task"?`/tasks/${X.entityId}`:X.entityType==="habit"?"/habits":X.entityType==="task_run"&&typeof X.metadata.taskId=="string"?`/tasks/${X.metadata.taskId}`:`/activity?eventId=${X.id}`}if(!P)return e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsx(nt,{title:"Overview",titleText:"Overview",description:"See your main goals, active projects, top tasks, and recent activity in one place.",badge:"0 live signals"}),e.jsx(Bt,{eyebrow:t("common.overview.heroEyebrow"),title:t("common.overview.emptyTitle"),description:t("common.overview.emptyDescription"),action:e.jsx(Je,{to:"/goals",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium whitespace-nowrap text-slate-950 transition hover:opacity-90",children:t("common.overview.emptyAction")})})]});const j=[{id:"hero",title:"Overview",description:"The route header stays movable like any other surface block.",defaultWidth:12,defaultHeight:2,removable:!1,minHeight:2,maxHeight:3,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(nt,{title:"Overview",titleText:"Overview",description:`${f}. Life Force, momentum, XP, goals, active projects, and top tasks all start here.`,badge:`Momentum ${a.metrics.momentumScore}`})},{id:"summary",title:"Momentum summary",description:"Smaller titles and denser metrics free space for the widgets themselves.",defaultWidth:12,defaultHeight:4,minWidth:6,render:({compact:X})=>e.jsxs("div",{className:"grid h-full gap-3 xl:grid-cols-[minmax(0,1.4fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Momentum summary"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:"Core live metrics"}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/56",children:"Life Force, momentum, XP, and instant headroom stay grouped here so the title bar can stay clean."})]}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:f})]}),e.jsx("div",{className:te("mt-4 grid gap-3",X?"grid-cols-2":"sm:grid-cols-2 xl:grid-cols-5"),children:v.map(Y=>e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-white/40",children:Y.label}),e.jsx("div",{className:"mt-1 text-lg font-semibold text-white",children:Y.value}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/54",children:Y.detail})]},Y.label))})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Goal needing attention"}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:(x==null?void 0:x.risk)??"stable"})]}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:(x==null?void 0:x.title)??"No goal is drifting hard right now"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(x==null?void 0:x.summary)??`Only ${a.overview.strategicHeader.overdueTasks} overdue task${a.overview.strategicHeader.overdueTasks===1?"":"s"} are slowing the system.`})]})]})},{id:"life-force",title:"Life Force",description:"Dynamic Action Points, the editable capacity curve, current drains, and stat growth all live here.",defaultWidth:12,defaultHeight:7,minWidth:6,render:()=>a.lifeForce?e.jsx(Aw,{selectedUserIds:i,fallbackLifeForce:a.lifeForce,onRefresh:s.refresh,showEditor:!1}):e.jsx(ce,{className:"rounded-[24px] border-white/8 bg-white/[0.04] p-5 text-sm leading-6 text-white/60",children:"Life Force is not configured for this user yet. Once a profile exists, the full capacity curve, drains, and recommendations will appear here."})},{id:"body-signals",title:"Life, health, movement",description:"Health imports and movement context make the overview feel like a real daily operating page.",defaultWidth:12,defaultHeight:4,minWidth:6,render:()=>e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-3",children:[e.jsxs(ce,{className:"rounded-[24px] border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Life Force"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:a.lifeForce?`${Math.round(a.lifeForce.remainingAp)} AP remaining`:"No Life Force profile yet"})]}),a.lifeForce?e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:Kt(a.lifeForce.instantFreeApPerHour)}):null]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:a.lifeForce?`${Math.round(a.lifeForce.spentTodayAp)} / ${Math.round(a.lifeForce.dailyBudgetAp)} AP spent today. Remaining ${St(a.lifeForce.remainingAp)} with ${Kt(a.lifeForce.currentDrainApPerHour)} current drain.`:"Once Life Force is configured, this block will show today's budget, remaining headroom, and live drain."})]}),e.jsxs(ce,{className:"rounded-[24px] border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Body signals"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:y?"Recovery, training, and vitals":"No health data yet"})]}),T?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[T.summary.metricCount," metrics"]}):null]}),n.isLoading||l.isLoading||d.isLoading?e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Loading recent sleep, workout, and body-signal metrics…"}):y?e.jsxs("div",{className:"mt-3 grid gap-2 text-sm text-white/72",children:[b?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:"Average sleep"}),e.jsx("span",{className:"font-medium text-white",children:Xl(b.averageSleepSeconds)})]}):null,b?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:"Sleep score"}),e.jsx("span",{className:"font-medium text-white",children:Math.round(b.averageSleepScore)})]}):null,A?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:"Exercise"}),e.jsxs("span",{className:"font-medium text-white",children:[Math.round(A.exerciseMinutes)," min"]})]}):null,A?e.jsx("div",{className:"text-xs leading-5 text-white/54",children:A.topWorkoutType?`${A.topWorkoutType} is the top workout type right now.`:"Workout imports are available when Apple Health or habit-generated sessions exist."}):null,w.length>0?e.jsx("div",{className:"mt-1 grid gap-2",children:w.map(X=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-[14px] border border-white/8 bg-white/[0.03] px-3 py-2",children:[e.jsx("span",{children:X.label}),e.jsx("span",{className:"font-medium text-white",children:F8(X)})]},X.metric))}):null]}):e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Sleep, workout, and vitals summaries appear here as soon as Forge has recent HealthKit records."})]}),e.jsxs(ce,{className:"rounded-[24px] border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Movement"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:N?"Today's place balance":"No movement timeline yet"})]}),N?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Xl((C==null?void 0:C.summary.totalMovingSeconds)??0)," moving"]}):null]}),o.isLoading?e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Loading today's stays, trips, and place balance…"}):N?e.jsxs("div",{className:"mt-3 grid gap-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[S.map(X=>e.jsxs(I,{className:"bg-white/[0.08] text-white/78",children:[Xl(X.seconds)," at ",X.label]},X.label)),((C==null?void 0:C.summary.totalMovingSeconds)??0)>0?e.jsxs(I,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[Xl((C==null?void 0:C.summary.totalMovingSeconds)??0)," moving"]}):null]}),e.jsxs("div",{className:"text-sm leading-6 text-white/58",children:[(C==null?void 0:C.summary.tripCount)??0," trip",((C==null?void 0:C.summary.tripCount)??0)===1?"":"s"," and"," ",E8((C==null?void 0:C.summary.totalDistanceMeters)??0)," tracked today."]})]}):e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Movement summaries appear here once the companion has synced stays, trips, or known places."})]})]})},{id:"signals",title:"Action signals",description:"Direct links to the next things worth opening.",defaultWidth:7,defaultHeight:4,minWidth:4,render:()=>e.jsx(Rw,{eyebrow:"Actions",title:"Open what matters now",description:"These cards stay compact by default so the page can fit more live context at once.",items:[{id:"top-task",label:h?"Top task":u?"Due habit":"Recovery lane",title:(h==null?void 0:h.title)??(u==null?void 0:u.title)??"Get a real task moving",detail:(h==null?void 0:h.description)||(u==null?void 0:u.description)||"There is no single top task yet, so use this surface to choose one clean next move.",badge:h?`${h.points} xp`:u?`${u.rewardXp} xp`:`${a.metrics.weeklyXp} weekly xp`,href:h?`/tasks/${h.id}`:u?"/habits":"/today",actionLabel:h?"Open task":u?"Open habits":"Open today"},{id:"reward",label:"Next reward",title:(m==null?void 0:m.title)??"Keep the streak alive",detail:(m==null?void 0:m.progressLabel)??`Level ${a.metrics.level} is active. ${a.metrics.weeklyXp} weekly XP is already logged.`,badge:(m==null?void 0:m.rewardLabel)??`${a.metrics.comboMultiplier.toFixed(2)}x combo`,href:"/today",actionLabel:"Open today"},{id:"recent-activity",label:"Recent activity",title:g?kd(g):"No recent evidence",detail:g?Sd(g):"The next work closeout or note will appear here.",badge:(g==null?void 0:g.source)??"activity",href:g?H(g):"/activity",actionLabel:"Open"}]})},{id:"goals",title:"Goals",description:"Long-range direction stays visible without taking over the whole page.",defaultWidth:8,defaultHeight:5,minWidth:4,render:({compact:X})=>e.jsx("div",{className:"grid gap-3",children:a.overview.activeGoals.slice(0,X?2:4).map(Y=>{var z;return e.jsxs(Je,{to:`/goals/${Y.id}`,className:"rounded-[20px] bg-white/[0.04] p-4 transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx(We,{kind:"goal",label:((z=Y.tags[0])==null?void 0:z.name)??Y.horizon,compact:!0,gradient:!1}),e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:[Y.progress,"%"]})]}),e.jsx("div",{className:"mt-3",children:e.jsx(yt,{kind:"goal",label:Y.title,variant:"heading",size:X?"md":"lg",lines:2,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"})}),X?null:e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:Y.description}),e.jsx("div",{className:"mt-3",children:e.jsx(xa,{value:Y.progress})}),e.jsx("div",{className:"mt-3",children:e.jsx(Ks,{entityType:"goal",entityId:Y.id,count:Js(a.dashboard.notesSummaryByEntity,"goal",Y.id).count})})]},Y.id)})})},{id:"pipeline",title:"Projects, habits, tasks",description:"Execution blocks can shrink while keeping the useful subtitles visible.",defaultWidth:12,defaultHeight:5,minWidth:6,render:({compact:X})=>e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-3",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Projects"}),a.overview.projects.slice(0,X?3:4).map(Y=>{var z;return e.jsxs(Je,{to:`/projects/${Y.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex min-w-0 items-center 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:Y.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:((z=p.get(Y.id))==null?void 0:z.status)??"active"})]}),e.jsxs(I,{wrap:!0,className:"max-w-[7rem] shrink-0",children:[Y.earnedPoints," xp"]})]}),X?null:e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:Y.description})]},Y.id)})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Due habits"}),a.overview.dueHabits.slice(0,X?3:4).map(Y=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:e.jsxs("div",{className:"flex min-w-0 items-center 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:Y.title}),X?null:e.jsx("div",{className:"mt-1 text-sm text-white/56",children:Y.description})]}),e.jsxs(I,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[Y.rewardXp," xp"]})]})},Y.id))]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Top tasks"}),a.overview.topTasks.slice(0,X?3:4).map(Y=>e.jsx(Je,{to:`/tasks/${Y.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex min-w-0 items-center 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:Y.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:Y.status.replaceAll("_"," ")})]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Y.points," xp"]})]})},Y.id))]})]})},{id:"time",title:"Clock",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:X})=>e.jsx(Nl,{compact:X})},{id:"weather",title:"Weather",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:X})=>e.jsx(Il,{compact:X})},{id:"mini-calendar",title:"Mini calendar",description:"Optional utility widget.",defaultWidth:4,defaultHeight:3,defaultHidden:!0,render:({compact:X})=>e.jsx(kl,{compact:X})},{id:"spotify",title:"Spotify",description:"Optional utility widget.",defaultWidth:4,defaultHeight:2,defaultHidden:!0,render:()=>e.jsx(Sl,{surfaceId:"overview"})},{id:"quick-capture",title:"Quick capture",description:"Save a standalone note or wiki draft from any dashboard.",defaultWidth:5,defaultHeight:3,defaultHidden:!0,render:({compact:X})=>{var Y;return e.jsx(Cl,{compact:X,defaultUserId:i[0]??((Y=a.users[0])==null?void 0:Y.id)??null})}}];return e.jsx(Td,{surfaceId:"overview",baseWidgets:j,normalizeLayout:A8})}const R8=[10,15,30,45,60];function Xp(){return{mode:"add",minutes:15,note:""}}function $w({open:t,onOpenChange:s,entityType:a,entityId:i,targetLabel:r,currentCreditedSeconds:n,pending:l=!1,onSubmit:o}){const[d,m]=c.useState(Xp),[h,u]=c.useState(null);c.useEffect(()=>{t&&(m(Xp()),u(null))},[t]);const x=Fe({queryKey:["forge-xp-metrics"],queryFn:ff,enabled:t}),g=c.useMemo(()=>{var T;const b=(T=x.data)==null?void 0:T.metrics.rules.find(w=>w.code==="task_run_progress"),A=Math.max(1,Number((b==null?void 0:b.config.intervalMinutes)??10)),C=Number((b==null?void 0:b.config.fixedXp)??4);return{intervalMinutes:A,fixedXp:C,intervalSeconds:A*60}},[x.data]),p=c.useMemo(()=>{const b=Math.max(0,Math.trunc(d.minutes||0)),A=d.mode==="add"?b:-b,C=Math.max(0,Math.floor(n/60)),T=A>=0?A:-Math.min(Math.abs(A),C),w=Math.max(0,n+T*60),S=Math.floor(Math.max(0,n)/g.intervalSeconds),N=Math.floor(w/g.intervalSeconds)-S;return{requestedDeltaMinutes:A,appliedDeltaMinutes:T,nextCreditedSeconds:w,bucketDelta:N,xpDelta:N*g.fixedXp,maxRemovableMinutes:C}},[g.fixedXp,g.intervalSeconds,n,d.minutes,d.mode]),f=[{id:"adjustment",eyebrow:a==="task"?"Task work":"Project work",title:`Adjust tracked work for ${r}`,description:"Use this for retrospective minute corrections. Forge will add or remove tracked minutes and adjust progress XP automatically when a reward bucket is crossed.",render:(b,A)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Mode",labelHelp:"Add minutes when work happened off-timer. Remove minutes when the tracked total needs a correction.",children:e.jsx(wt,{value:b.mode,onChange:C=>A({mode:C}),options:[{value:"add",label:"Add minutes",description:"Record extra work that already happened."},{value:"remove",label:"Remove minutes",description:"Correct tracked time without deleting the work history."}]})}),e.jsx(de,{label:"Minutes",description:`Currently tracked: ${Math.floor(n/60)} minutes.`,hint:b.mode==="remove"?`You can remove up to ${p.maxRemovableMinutes} whole minutes from the current credited total.`:void 0,children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(ye,{type:"number",min:1,className:"w-36",value:b.minutes,onChange:C=>A({minutes:Number(C.target.value)||0})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:R8.map(C=>e.jsxs(W,{type:"button",variant:b.minutes===C?"primary":"secondary",onClick:()=>A({minutes:C}),children:[C," min"]},C))})]})}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Preview"}),e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Applied minutes"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[p.appliedDeltaMinutes>0?"+":"",p.appliedDeltaMinutes]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"XP delta"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[p.xpDelta>0?"+":"",p.xpDelta]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"New tracked total"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[Math.floor(p.nextCreditedSeconds/60)," min"]})]})]}),e.jsxs("div",{className:"mt-3 text-sm leading-6 text-white/58",children:["Reward cadence: ",g.fixedXp," XP every"," ",g.intervalMinutes," credited minutes."," ",p.bucketDelta===0?"This change does not cross a reward bucket.":`This change crosses ${Math.abs(p.bucketDelta)} reward bucket${Math.abs(p.bucketDelta)===1?"":"s"}.`]})]}),e.jsx(de,{label:"Note",description:"Optional context for why this correction is being added. The note stays attached to the adjustment metadata.",children:e.jsx(Ze,{className:"min-h-28",value:b.note,onChange:C=>A({note:C.target.value}),placeholder:"Captured the review session that happened away from the live timer."})})]})}];return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:a==="task"?"Adjust task work":"Adjust project work",title:`Adjust work for ${r}`,description:"Add or remove tracked minutes without creating a live task run.",value:d,onChange:m,draftPersistenceKey:`work-adjustment.${a}.${i}`,steps:f,submitLabel:"Save adjustment",pending:l,pendingLabel:"Saving adjustment...",error:h,onSubmit:async()=>{var T;u(null);const b=Math.max(0,Math.trunc(d.minutes||0)),A=d.mode==="add"?b:-b,C=y2.safeParse({entityType:a,entityId:i,deltaMinutes:A,note:d.note});if(!C.success){u(((T=C.error.issues[0])==null?void 0:T.message)??"Enter a valid minute adjustment.");return}try{await o({entityType:a,entityId:i,deltaMinutes:C.data.deltaMinutes,note:C.data.note||void 0}),s(!1)}catch(w){u(w instanceof Error?w.message:"Could not save the work adjustment right now.")}}})}const Ow={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function $8(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean)}function uc(t,s){const a=$8(t);if(a.length===0)return!1;const i=s.join(" ").toLowerCase();return a.some(r=>i.includes(r))}function O8(t){return t.allowWorkBlockKinds.length>0||t.allowCalendarIds.length>0||t.allowEventTypes.length>0||t.allowEventKeywords.length>0||t.allowAvailability.length>0}function z8(t,s){return t??s??Ow}function zw(t){const s=t.rules??Ow,i=(t.at??new Date).getTime(),r=t.overview,n=(r==null?void 0:r.workBlockInstances.filter(x=>{const g=new Date(x.startAt).getTime(),p=new Date(x.endAt).getTime();return g<=i&&i<p}))??[],l=(r==null?void 0:r.events.filter(x=>{if(x.deletedAt)return!1;const g=new Date(x.startAt).getTime(),p=new Date(x.endAt).getTime();return g<=i&&i<p}))??[],o=[],d=n.some(x=>s.blockWorkBlockKinds.includes(x.kind))||l.some(x=>(x.calendarId?s.blockCalendarIds.includes(x.calendarId):!1)||s.blockEventTypes.includes(x.eventType)||s.blockAvailability.includes(x.availability)||uc(s.blockEventKeywords,[x.title,x.description,x.location,...x.categories]));d&&(n.some(x=>s.blockWorkBlockKinds.includes(x.kind))&&o.push("The current work block is marked as blocked."),l.some(x=>x.calendarId?s.blockCalendarIds.includes(x.calendarId):!1)&&o.push("The active calendar belongs to a blocked calendar source."),l.some(x=>s.blockEventTypes.includes(x.eventType))&&o.push("The active calendar event type is blocked."),l.some(x=>s.blockAvailability.includes(x.availability))&&o.push("The active calendar availability is blocked."),l.some(x=>uc(s.blockEventKeywords,[x.title,x.description,x.location,...x.categories]))&&o.push("The active calendar event matches a blocked keyword."));const m=O8(s),h=n.some(x=>s.allowWorkBlockKinds.includes(x.kind))||l.some(x=>(x.calendarId?s.allowCalendarIds.includes(x.calendarId):!1)||s.allowEventTypes.includes(x.eventType)||s.allowAvailability.includes(x.availability)||uc(s.allowEventKeywords,[x.title,x.description,x.location,...x.categories]));!d&&m&&!h&&o.push("The current calendar context does not match the allowed rules yet.");const u=[...n.map(x=>`${x.title} (${x.kind.replaceAll("_"," ")})`),...l.map(x=>x.title)];return o.length>0?{blocked:!0,label:"Blocked right now",tone:"blocked",conflicts:o,context:u}:u.length>0?{blocked:!1,label:"Allowed right now",tone:"allowed",conflicts:[],context:u}:{blocked:!1,label:m?"Waiting for an allowed calendar context":"No live calendar conflict right now",tone:m?"waiting":"allowed",conflicts:[],context:[]}}function K8(t,s){return z8(t.schedulingRules,s)}function q8(t){return!!(t&&t.startsWith("campaign:"))}function B8(){var _;const{t}=Ot(),s=jt(),a=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],i=Qs(),r=$t(),n=ct(),[l,o]=c.useState(!1),[d,m]=c.useState(!1),[h,u]=c.useState(!1),[x]=c.useState(()=>{const B=new Date,G=new Date(B);G.setHours(0,0,0,0);const ae=new Date(B);return ae.setHours(23,59,59,999),{from:G.toISOString(),to:ae.toISOString()}}),g=ys(a),p=s.snapshot.dashboard.projects.find(B=>B.id===i.projectId)??null,f=p?s.snapshot.goals.find(B=>B.id===p.goalId)??null:null,b=p?s.snapshot.tasks.filter(B=>B.projectId===p.id||!B.projectId&&B.goalId===p.goalId):[],A=new Set(b.map(B=>B.id)),C=p?s.snapshot.activity.filter(B=>B.entityId===p.goalId||B.entityId===p.id||A.has(B.entityId)||B.entityType==="task_run"&&typeof B.metadata.taskId=="string"&&A.has(B.metadata.taskId)):[],T=q8(i.projectId),w=Fe({queryKey:["project-board",i.projectId],queryFn:()=>VN(i.projectId),enabled:!!i.projectId&&!T}),S=Fe({queryKey:["project-calendar-overview",i.projectId,x.from,x.to,...a],queryFn:()=>Or({...x,userIds:a}),enabled:!!i.projectId&&!T}),y=Re({mutationFn:B=>nm(B),onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]})])}}),N=Re({mutationFn:lm,onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]}),n.invalidateQueries({queryKey:["forge-xp-metrics"]}),n.invalidateQueries({queryKey:["forge-reward-ledger"]}),n.invalidateQueries({queryKey:["forge-operator-context"]})])}}),P=Re({mutationFn:B=>wf(i.projectId,{status:B}),onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]}),n.invalidateQueries({queryKey:["forge-xp-metrics"]}),n.invalidateQueries({queryKey:["forge-reward-ledger"]}),n.invalidateQueries({queryKey:["forge-operator-context"]})])}}),v=Re({mutationFn:()=>fk(i.projectId),onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]})]),r("/projects")}}),H=Re({mutationFn:B=>rm(B),onSuccess:async()=>{await Promise.all([Ut(n),n.invalidateQueries({queryKey:["project-board",i.projectId]}),n.invalidateQueries({queryKey:["task-context"]})])}}),j=w.data??(p&&f?{project:p,goal:f,tasks:b,activity:C}:void 0),R=s.snapshot.dashboard.projects.find(B=>B.id===i.projectId)??null;if(w.isError&&!T)return e.jsx(it,{eyebrow:t("common.projectDetail.errorEyebrow"),error:w.error,onRetry:()=>void w.refetch()});if(!j)return e.jsx(ls,{});const Q=j.tasks.find(B=>B.status==="focus"||B.status==="in_progress")??j.tasks[0]??null,X=j.tasks.find(B=>B.status==="blocked")??j.tasks.find(B=>B.status==="backlog")??null;j.activity[0];const Y="notesSummaryByEntity"in j?j.notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,z=P.isPending||v.isPending,K=zw({rules:j.project.schedulingRules,overview:(_=S.data)==null?void 0:_.calendar}),$=s.snapshot.strategies.filter(B=>B.targetGoalIds.includes(j.goal.id)),D=s.snapshot.strategies.filter(B=>B.targetProjectIds.includes(j.project.id)),J=async B=>{await P.mutateAsync(B)},q=async()=>{window.confirm(t("common.projectDetail.deleteProjectConfirm",{title:j.project.title}))&&await v.mutateAsync()};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Id,{}),e.jsx(nt,{entityKind:"project",title:e.jsx(yt,{kind:"project",label:j.project.title,variant:"heading",size:"lg"}),titleText:j.project.title,description:j.project.description?e.jsx(Rs,{markdown:j.project.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):"No project description yet.",badge:e.jsx(We,{kind:"goal",label:j.goal.title,compact:!0,gradient:!1}),actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Nd,{userId:g,domain:"projects",entityType:"project",entityId:j.project.id,label:j.project.title,description:j.project.description}),e.jsx(er,{entityType:"project",entityId:j.project.id})]})}),j.project.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(ot,{user:j.project.user}),j.project.assignees&&j.project.assignees.length>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-white/35",children:"Assigned with"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:j.project.assignees.map(B=>e.jsx(ot,{user:B,compact:!0},B.id))})]}):null]}):null,j.project.productRequirementsDocument?e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Product requirements document"}),e.jsx("div",{className:"mt-3",children:e.jsx(Rs,{markdown:j.project.productRequirementsDocument,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"})})]}):null,$.length>0||D.length>0?e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Strategy stack"}),e.jsxs("div",{className:"mt-3 grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/42",children:"Goal-level strategies"}),$.length===0?e.jsx("div",{className:"text-sm text-white/48",children:"No goal-level strategies linked yet."}):$.map(B=>e.jsxs(Je,{to:`/strategies/${B.id}`,className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:B.title}),e.jsx("div",{className:"mt-1 text-xs text-white/48",children:B.overview||B.endStateDescription})]},B.id))]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/42",children:"Project-level strategies"}),D.length===0?e.jsx("div",{className:"text-sm text-white/48",children:"No lower-level strategies linked yet."}):D.map(B=>e.jsxs(Je,{to:`/strategies/${B.id}`,className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:B.title}),e.jsx("div",{className:"mt-1 text-xs text-white/48",children:B.overview||B.endStateDescription})]},B.id))]})]})]}):null,T?e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.projectDetail.compatibility")}),e.jsx("p",{className:"mt-3 text-sm leading-7 text-white/60",children:t("common.projectDetail.compatibilityDescription")})]}):null,e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(W,{onClick:()=>m(!0),children:t("common.projectDetail.addTask")}),T?null:e.jsx(W,{variant:"secondary",onClick:()=>u(!0),children:"Adjust work"}),T?null:e.jsx(W,{variant:"secondary",onClick:()=>o(!0),children:t("common.projectDetail.editProject")}),!T&&j.project.status==="active"?e.jsx(W,{variant:"secondary",pending:z&&P.variables==="paused",pendingLabel:t("common.projectDetail.suspending"),onClick:()=>void J("paused"),children:t("common.projectDetail.suspendProject")}):null,!T&&j.project.status!=="completed"?e.jsx(W,{pending:z&&P.variables==="completed",pendingLabel:t("common.projectDetail.finishing"),onClick:()=>void J("completed"),children:t("common.projectDetail.finishProject")}):null,!T&&j.project.status!=="active"?e.jsx(W,{variant:"secondary",pending:z&&P.variables==="active",pendingLabel:t("common.projectDetail.restarting"),onClick:()=>void J("active"),children:t("common.projectDetail.restartProject")}):null,T?null:e.jsx(W,{variant:"ghost",pending:v.isPending,pendingLabel:t("common.projectDetail.deleting"),onClick:()=>void q(),children:t("common.projectDetail.deleteProject")}),e.jsx(Je,{to:`/goals/${j.goal.id}`,children:e.jsx(W,{variant:"ghost",children:t("common.projectDetail.openGoal")})})]}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1fr)_22rem]",children:[e.jsxs(ce,{children:[e.jsxs("div",{className:"flex flex-wrap 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/45",children:t("common.projectDetail.commandEyebrow")}),e.jsx("h2",{className:"mt-2 font-display text-[clamp(1.35rem,2vw,1.9rem)] text-white",children:t("common.projectDetail.commandTitle")}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:t("common.projectDetail.commandDescription")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(We,{kind:"project",compact:!0,gradient:!1}),e.jsx(We,{kind:"goal",label:j.goal.title,compact:!0,gradient:!1})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:[e.jsxs(Je,{to:Q?`/tasks/${Q.id}`:`/projects/${j.project.id}`,className:"rounded-[20px] bg-white/[0.04] p-4 transition hover:bg-white/[0.08]",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.projectDetail.signalNext")}),Q?e.jsx(We,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(Q==null?void 0:Q.title)??t("common.projectDetail.noNextTask")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(Q==null?void 0:Q.description)||t("common.projectDetail.noNextTaskDetail")})]}),e.jsxs(Je,{to:X?`/tasks/${X.id}`:`/projects/${j.project.id}`,className:"rounded-[20px] bg-white/[0.04] p-4 transition hover:bg-white/[0.08]",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.projectDetail.signalRisk")}),X?e.jsx(We,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(X==null?void 0:X.title)??t("common.projectDetail.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(X==null?void 0:X.description)||t("common.projectDetail.noRiskDetail")})]})]})]}),e.jsxs(ce,{className:"h-fit min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.projectDetail.sectionHealth")}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.projectStatus.${j.project.status}`)}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:j.project.momentumLabel}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(j.project.time.totalCreditedSeconds/60)," min tracked"]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",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.projectDetail.fieldProgress")}),e.jsxs("div",{className:"mt-2 font-display text-xl text-white",children:[j.project.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.projectDetail.fieldMomentum")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:j.project.momentumLabel})]}),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.projectDetail.fieldStatus")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:t(`common.enums.projectStatus.${j.project.status}`)})]}),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:"Live tasks"}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:j.tasks.filter(B=>B.status==="focus"||B.status==="in_progress").length})]})]})]})]}),T?null:e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1fr)_22rem]",children:[e.jsx(qb,{title:"Project scheduling defaults",subtitle:"Define the calendar contexts where work from this project is allowed or blocked. Tasks can inherit these defaults or override them.",initialRules:j.project.schedulingRules,saveLabel:"Save project scheduling",onSave:async({schedulingRules:B})=>{await s.patchProject(j.project.id,{schedulingRules:B}),await n.invalidateQueries({queryKey:["project-board",i.projectId]}),await n.invalidateQueries({queryKey:["project-calendar-overview",i.projectId]})}}),e.jsxs(ce,{className:"h-fit min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar status"}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(I,{className:K.tone==="blocked"?"bg-rose-500/14 text-rose-100":K.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:K.label}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:"Project defaults"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"These rules act as the default calendar gate for every task in the project unless a task sets its own override."}),K.context.length>0?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Current context"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:K.context.map(B=>e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:B},B))})]}):null,K.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:K.conflicts.map(B=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:B},B))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(Je,{to:"/calendar",children:e.jsx(W,{variant:"secondary",children:"Open calendar workspace"})})})]})]}),e.jsx(uw,{tasks:j.tasks,activeRuns:s.snapshot.activeTaskRuns,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:Y,selectedTaskId:null,onMove:async(B,G)=>{await s.patchTaskStatus(B,G),await n.invalidateQueries({queryKey:["project-board",i.projectId]})},onSelectTask:B=>r(`/tasks/${B}`),onStopTask:async B=>{await s.stopTaskRun(B),await n.invalidateQueries({queryKey:["project-board",i.projectId]}),await n.invalidateQueries({queryKey:["task-context",B.taskId]})},onQuickReopenTask:async B=>{await y.mutateAsync(B)},onDeleteTask:async B=>{await H.mutateAsync(B)}}),T?null:e.jsx(jd,{entityType:"project",entityId:j.project.id,title:"Project notes",description:"Keep rollout notes, checkpoints, and cross-task context attached to the project itself.",invalidateQueryKeys:[["project-board",i.projectId]]}),e.jsxs(ce,{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.projectDetail.sectionEvidence")}),e.jsx("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:j.activity.slice(0,6).map(B=>e.jsxs(Je,{to:Ra(B)??`/activity?eventId=${B.id}`,className:"rounded-[18px] bg-white/[0.04] p-4 transition hover:bg-white/[0.08]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:kd(B)}),e.jsx(I,{children:B.source})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Sd(B)})]},B.id))})]}),e.jsx(fd,{open:l,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:R,defaultUserId:(R==null?void 0:R.userId)??g,onOpenChange:o,onSubmit:async(B,G)=>{G&&(await s.patchProject(G,B),await n.invalidateQueries({queryKey:["project-board",i.projectId]}))}}),e.jsx(bd,{open:d,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,workItems:s.snapshot.workItems,tags:s.snapshot.tags,users:s.snapshot.users,editingTask:null,initialProjectId:T?null:j.project.id,defaultUserId:j.project.userId??g,onRefreshEntities:s.refresh,onOpenChange:m,onSubmit:async(B,G)=>{G?await s.patchTask(G,B):await s.createTask(B),await n.invalidateQueries({queryKey:["project-board",i.projectId]})}}),T?null:e.jsx($w,{open:h,onOpenChange:u,entityType:"project",entityId:j.project.id,targetLabel:j.project.title,currentCreditedSeconds:j.project.time.totalCreditedSeconds,pending:N.isPending,onSubmit:async B=>{await N.mutateAsync(B)}})]})}const Li={user:"user:",kind:"kind:"},Kw=["goal","strategy","project","issue","task","subtask"],wn=[...Kw],yn=["active","paused","completed","backlog","focus","in_progress","blocked","done"];function Ii(t){return t.trim().toLowerCase()}function U8(t){return t.reduce((s,a)=>{if(a.startsWith(Li.user))s.userIds.push(a.slice(Li.user.length));else if(a.startsWith(Li.kind)){const i=a.slice(Li.kind.length);(i==="human"||i==="bot")&&s.kinds.push(i)}return s},{userIds:[],kinds:[]})}function W8(t,s){return`${s}:${Ii(t)}`}function H8(t){const s=t.trim();return s.length===0?[]:["any",...Kw].map(a=>({id:W8(s,a),query:s,kind:a}))}function G8(t){switch(t){case"done":case"completed":return 1;case"in_progress":case"active":return .66;case"focus":return .45;case"blocked":return .5;case"paused":return .28;default:return .08}}function vn(t,s){const a=t.replace(/\s+/g," ").trim();return a.length===0?s:a}function Nr(t){const s=(t.children??[]).map(Nr);if(t.kind==="project")return{...t,children:s,progressPercent:t.progressPercent,progressLabel:t.progressLabel??(typeof t.progressPercent=="number"?`${t.progressPercent}% complete`:null)};if(s.length>0){const i=s.map(r=>r.progressPercent).filter(r=>typeof r=="number");if(i.length>0){const r=Math.round(i.reduce((n,l)=>n+l,0)/i.length);return{...t,children:s,progressPercent:r,progressLabel:`${s.length} child item${s.length===1?"":"s"}`}}}const a=Math.round(G8(t.statusLabel)*100);return{...t,children:s,progressPercent:a,progressLabel:t.statusLabel?t.statusLabel.replaceAll("_"," "):null}}function Yp(t){const{goals:s,strategies:a,projects:i,workItems:r,tagNameById:n}=t,l=new Map,o=new Map,d=new Map;for(const u of r)if(u.parentWorkItemId){const x=l.get(u.parentWorkItemId)??[];x.push(u),l.set(u.parentWorkItemId,x)}else if(u.level==="issue"&&u.projectId){const x=o.get(u.projectId)??[];x.push(u),o.set(u.projectId,x)}else if(u.projectId){const x=d.get(u.projectId)??[];x.push(u),d.set(u.projectId,x)}const m=u=>{var x;return Nr({id:`${u.level}:${u.id}`,entityId:u.id,kind:u.level,label:u.title,description:vn(u.description,u.level==="issue"?"Vertical slice issue":u.level==="subtask"?"Granular child step":"Focused AI session task"),searchText:Ii([u.title,u.description,u.aiInstructions,u.executionMode??"",u.status,((x=u.user)==null?void 0:x.displayName)??"",...(u.assignees??[]).map(g=>g.displayName),...u.tagIds.map(g=>n.get(g)??"")].join(" ")),href:`/tasks/${u.id}`,statusLabel:u.status,executionMode:u.executionMode,goalId:u.goalId,projectId:u.projectId,tagIds:u.tagIds,user:u.user,assignees:u.assignees??[],linkedUserIds:[...u.user?[u.user.id]:[],...u.assigneeUserIds??[]],progressPercent:null,progressLabel:null,children:(l.get(u.id)??[]).map(m)})},h=u=>{var g;const x=a.filter(p=>p.targetProjectIds.includes(u.id));return Nr({id:`project:${u.id}`,entityId:u.id,kind:"project",label:u.title,description:vn(u.description||u.productRequirementsDocument,"PRD-backed initiative"),searchText:Ii([u.title,u.description,u.productRequirementsDocument,u.goalTitle,u.workflowStatus,u.status,((g=u.user)==null?void 0:g.displayName)??"",...(u.assignees??[]).map(p=>p.displayName)].join(" ")),href:`/projects/${u.id}`,statusLabel:u.workflowStatus,executionMode:null,goalId:u.goalId,projectId:u.id,tagIds:[],user:u.user,assignees:u.assignees??[],linkedUserIds:[...u.user?[u.user.id]:[],...u.assigneeUserIds??[]],progressPercent:u.progress,progressLabel:`${u.completedTaskCount}/${u.totalTasks} done`,children:[...x.map(p=>{var f;return Nr({id:`strategy:${p.id}`,entityId:p.id,kind:"strategy",label:p.title,description:vn(p.overview||p.endStateDescription,"Execution strategy"),searchText:Ii([p.title,p.overview,p.endStateDescription,p.status,((f=p.user)==null?void 0:f.displayName)??""].join(" ")),href:`/strategies/${p.id}`,statusLabel:p.status,executionMode:null,goalId:u.goalId,projectId:u.id,tagIds:[],user:p.user,assignees:[],linkedUserIds:p.user?[p.user.id]:[],progressPercent:null,progressLabel:null,children:[]})}),...(o.get(u.id)??[]).map(m),...(d.get(u.id)??[]).map(m)]})};return s.map(u=>{var C,T;const x=i.filter(w=>w.goalId===u.id),g=a.filter(w=>w.targetGoalIds.includes(u.id)),p=new Map(g.map(w=>[w.id,[]])),f=new Set;for(const w of x){const S=g.find(y=>y.targetProjectIds.includes(w.id));S&&((C=p.get(S.id))==null||C.push(w),f.add(w.id))}const b=g.map(w=>{var S;return Nr({id:`strategy:${w.id}`,entityId:w.id,kind:"strategy",label:w.title,description:vn(w.overview||w.endStateDescription,"High-level strategy"),searchText:Ii([w.title,w.overview,w.endStateDescription,w.status,((S=w.user)==null?void 0:S.displayName)??""].join(" ")),href:`/strategies/${w.id}`,statusLabel:w.status,executionMode:null,goalId:u.id,projectId:null,tagIds:[],user:w.user,assignees:[],linkedUserIds:w.user?[w.user.id]:[],progressPercent:null,progressLabel:null,children:(p.get(w.id)??[]).map(h)})}),A=x.filter(w=>!f.has(w.id)).map(h);return Nr({id:`goal:${u.id}`,entityId:u.id,kind:"goal",label:u.title,description:vn(u.description,"Strategic goal"),searchText:Ii([u.title,u.description,u.status,((T=u.user)==null?void 0:T.displayName)??""].join(" ")),href:`/goals/${u.id}`,statusLabel:u.status,executionMode:null,goalId:u.id,projectId:null,tagIds:u.tagIds,user:u.user,assignees:[],linkedUserIds:u.user?[u.user.id]:[],progressPercent:null,progressLabel:null,children:[...b,...A]})})}function qw(t){return t.reduce((s,a)=>s+1+qw(a.children??[]),0)}function Q8(t,s){return t.searchText.includes(Ii(s.query))&&(s.kind==="any"||s.kind===t.kind)}function Bw(t,s,a=!1){const{clauses:i,statusFilters:r,ownerUserIds:n,ownerKinds:l,selectedUserIds:o}=s,d=i.length===0||i.some(f=>Q8(t,f)),m=r.length===0||t.statusLabel!==null&&r.includes(t.statusLabel),h=n.length===0&&o.length===0?!0:[...n,...o].some(f=>t.linkedUserIds.includes(f)),u=l.length===0||[t.user,...t.assignees].some(f=>f&&l.includes(f.kind)),x=m&&h&&u,g=i.length===0||a||d,p=(t.children??[]).map(f=>Bw(f,s,a||x&&d)).filter(f=>f!==null);return x&&g||p.length>0?{...t,children:p}:null}function Uw(t,s){return t.flatMap(a=>{const i=Uw(a.children??[],s);return s.includes(a.kind)?[{...a,children:i}]:i})}function V8(t){switch(t){case"goal":return"bg-amber-400/12 text-amber-100";case"strategy":return"bg-cyan-400/12 text-cyan-100";case"project":return"bg-sky-400/12 text-sky-100";case"issue":return"bg-orange-400/12 text-orange-100";case"subtask":return"border-indigo-300/18 bg-indigo-400/12 text-indigo-100";default:return"bg-indigo-400/12 text-indigo-100"}}function mc(t){switch(t){case"done":case"completed":return"bg-emerald-400/12 text-emerald-100";case"blocked":return"bg-rose-400/12 text-rose-100";case"in_progress":case"active":return"bg-sky-400/12 text-sky-100";case"focus":return"bg-violet-400/12 text-violet-100";default:return"bg-white/[0.08] text-white/70"}}function Jp(t){return t==="any"?e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:"Any"}):t==="subtask"?e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"}):e.jsx(We,{kind:t==="issue"?"issue":t,label:t,compact:!0,gradient:!1})}function X8({query:t,onQueryChange:s,clauses:a,onClausesChange:i,resultSummary:r}){const[n,l]=c.useState(!1),[o,d]=c.useState(0),m=c.useMemo(()=>H8(t).filter(x=>!a.some(g=>g.id===x.id)),[a,t]),h=x=>{i([...a,x]),s(""),d(0),l(!1)},u=x=>{i(a.filter(g=>g.id!==x))};return e.jsx("div",{className:"grid gap-3",children:e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,28,48,0.9),rgba(10,14,26,0.98))] p-4 shadow-[0_30px_80px_rgba(3,8,18,0.28)] sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Hierarchy search"}),e.jsxs("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/62",children:["Build OR clauses like ",e.jsx("span",{className:"text-white",children:'Goal + "MD"'})," or ",e.jsx("span",{className:"text-white",children:'Any + "Happy"'}),". Matching ancestors keep their branches visible so you can explore the hierarchy, not lose it."]})]}),a.length>0||t.trim().length>0?e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{s(""),i([]),d(0),l(!1)},children:"Clear search"}):null]}),e.jsxs("div",{className:"mt-4 rounded-[24px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[a.length>0?e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:a.map(x=>e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[Jp(x.kind),e.jsxs("span",{className:"max-w-[14rem] truncate text-sm text-white/78",children:['"',x.query,'"']}),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>u(x.id),"aria-label":`Remove ${x.kind} ${x.query}`,children:e.jsx(Tt,{className:"size-3.5"})})]},x.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/36"}),e.jsx("input",{value:t,onChange:x=>{s(x.target.value),l(!0),d(0)},onFocus:()=>l(!0),onBlur:()=>{window.setTimeout(()=>l(!1),120)},onKeyDown:x=>{if(x.key==="Backspace"&&!t&&a.length>0){u(a[a.length-1].id);return}if(x.key==="ArrowDown"){x.preventDefault(),l(!0),d(g=>m.length===0?0:Math.min(m.length-1,g+1));return}if(x.key==="ArrowUp"){x.preventDefault(),d(g=>Math.max(0,g-1));return}if(x.key==="Escape"){l(!1);return}x.key==="Enter"&&m[o]&&(x.preventDefault(),h(m[o]))},placeholder:'Type text, then pick a clause like Goal + "MD" or Any + "Happy"',className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),n?e.jsx("div",{className:"absolute top-full z-20 mt-2 w-full rounded-[22px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:m.length>0?m.map((x,g)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",g===o?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>d(g),onMouseDown:p=>p.preventDefault(),onClick:()=>h(x),children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Jp(x.kind),e.jsxs("span",{className:"truncate text-sm font-medium text-white",children:['"',x.query,'"']})]}),e.jsxs("div",{className:"mt-1 text-xs leading-5 text-white/46",children:["Match ",x.kind==="any"?"any visible hierarchy node":`${x.kind} nodes`," that mention this text."]})]})},x.id)):e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:"Type a word or phrase to create a new OR clause."})}):null]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/52",children:r})]})})}function Y8(){const t=jt(),s=c.useRef(null),[a,i]=c.useState(""),[r,n]=c.useState([]),[l,o]=c.useState([]),[d,m]=c.useState([...yn]),[h,u]=c.useState(wn),x=Fe({queryKey:["work-items-hierarchy",...t.selectedUserIds],queryFn:()=>XN({userIds:t.selectedUserIds})}),g=c.useMemo(()=>{const N=t.snapshot.users.filter(v=>v.kind==="bot"),P=t.snapshot.users.filter(v=>v.kind==="human");return[{value:`${Li.kind}bot`,label:"Bots",description:`${N.length} bot collaborators`,searchText:`bots bot ai agents assistants ${N.map(v=>`${v.displayName} ${v.handle}`).join(" ")}`,badge:e.jsx(I,{className:"border-cyan-300/18 bg-cyan-400/12 text-cyan-50",children:"Bots"}),menuBadge:e.jsx(I,{className:"border-cyan-300/18 bg-cyan-400/12 text-cyan-50",children:"Bots"})},{value:`${Li.kind}human`,label:"Humans",description:`${P.length} human collaborators`,searchText:`humans human people operators ${P.map(v=>`${v.displayName} ${v.handle}`).join(" ")}`,badge:e.jsx(I,{className:"border-amber-300/18 bg-amber-400/12 text-amber-50",children:"Humans"}),menuBadge:e.jsx(I,{className:"border-amber-300/18 bg-amber-400/12 text-amber-50",children:"Humans"})},...t.snapshot.users.map(v=>({value:`${Li.user}${v.id}`,label:v.displayName,description:`${v.kind}${v.handle?` · @${v.handle}`:""}`,searchText:`${v.displayName} ${v.handle} ${v.kind} ${v.description}`,badge:e.jsx(ot,{user:v,compact:!0}),menuBadge:e.jsx(ot,{user:v,compact:!0})}))]},[t.snapshot.users]),p=c.useMemo(()=>[{value:"goal",label:"Goal",searchText:"goal direction objective",kind:"goal"},{value:"strategy",label:"Strategy",searchText:"strategy plan sequencing",kind:"strategy"},{value:"project",label:"Project",searchText:"project initiative prd",kind:"project"},{value:"issue",label:"Issue",searchText:"issue vertical slice tracer bullet",kind:"issue"},{value:"task",label:"Task",searchText:"task execution ai session",kind:"task"},{value:"subtask",label:"Subtask",searchText:"subtask child step",badge:e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"}),menuBadge:e.jsx(We,{kind:"task",label:"Subtask",compact:!0,gradient:!1,className:"border-indigo-300/18 bg-indigo-400/12 text-indigo-100"})}],[]),f=c.useMemo(()=>[{value:"active",label:"Active",searchText:"active in progress live"},{value:"paused",label:"Paused",searchText:"paused suspended"},{value:"completed",label:"Completed",searchText:"completed finished"},{value:"backlog",label:"Backlog",searchText:"backlog queued"},{value:"focus",label:"Focus",searchText:"focus ready"},{value:"in_progress",label:"In progress",searchText:"in progress active doing"},{value:"blocked",label:"Blocked",searchText:"blocked stuck"},{value:"done",label:"Done",searchText:"done complete finished"}].map(N=>({...N,badge:e.jsx(I,{className:mc(N.value),children:N.label}),menuBadge:e.jsx(I,{className:mc(N.value),children:N.label})})),[]),b=c.useMemo(()=>new Map(t.snapshot.tags.map(N=>[N.id,N.name])),[t.snapshot.tags]),A=c.useMemo(()=>x.data?Yp({...x.data,tagNameById:b}):Yp({goals:t.snapshot.goals,strategies:t.snapshot.strategies,projects:t.snapshot.dashboard.projects,tagNameById:b,workItems:t.snapshot.workItems&&t.snapshot.workItems.length>0?t.snapshot.workItems:t.snapshot.tasks}),[x.data,t.snapshot,b]),C=a.trim().length>0||r.length>0||l.length>0||d.length!==yn.length||yn.some(N=>!d.includes(N))||h.length!==wn.length||wn.some(N=>!h.includes(N)),T=c.useMemo(()=>U8(l),[l]),w=c.useMemo(()=>{const N=A.map(P=>Bw(P,{clauses:r,statusFilters:d,ownerUserIds:T.userIds,ownerKinds:T.kinds,selectedUserIds:t.selectedUserIds})).filter(P=>P!==null);return Uw(N,h)},[A,T.kinds,T.userIds,r,d,t.selectedUserIds,h]),S=c.useMemo(()=>qw(w),[w]),y=`${r.length>0?`${r.length} OR clause${r.length===1?"":"s"} active`:"Search across the full hierarchy"} · ${S} visible node${S===1?"":"s"}.`;return x.isLoading&&A.length===0?e.jsx(Et,{eyebrow:"Hierarchy",title:"Building Forge hierarchy",description:"Loading goals, strategies, projects, issues, tasks, and subtasks into the compact hierarchy view."}):x.isError&&A.length===0?e.jsx(it,{eyebrow:"Hierarchy",error:x.error,onRetry:()=>void x.refetch()}):e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Id,{}),e.jsx(nt,{title:"Hierarchy",description:"Explore the full Forge stack from goal to subtask in one compact operational tree, with both strategy layers visible and the same control surfaces as the board.",badge:`${S} visible nodes`}),e.jsxs(ce,{className:"min-w-0 overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(16,23,38,0.92),rgba(9,14,24,0.98))]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 border-b border-white/8 px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Hierarchy controls"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:"Filter across goals, projects, tags, humans, bots, and work-item types, then expand or collapse the full tree without losing the hierarchy context."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{var N,P;return(P=(N=s.current)==null?void 0:N.openAll)==null?void 0:P.call(N)},children:"Expand all"}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{var N,P;return(P=(N=s.current)==null?void 0:N.closeAll)==null?void 0:P.call(N)},children:"Collapse all"}),C?e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{i(""),n([]),o([]),m([...yn]),u(wn)},children:"Reset"}):null]})]}),e.jsxs("div",{className:"grid gap-4 px-5 py-5",children:[e.jsx(X8,{query:a,onQueryChange:i,clauses:r,onClausesChange:n,resultSummary:y}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsx(mt,{options:f,selectedValues:d,onChange:N=>m(N),placeholder:"Visible states",emptyMessage:"No states available.",variant:"action-bar"}),e.jsx(mt,{options:p,selectedValues:h,onChange:N=>u(N),placeholder:"Visible levels",emptyMessage:"No hierarchy levels.",className:"min-w-0",variant:"action-bar"}),e.jsx(mt,{options:g,selectedValues:l,onChange:o,placeholder:"Filter by human, bot, or collaborator",emptyMessage:"No matching collaborators."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[w.length," top-level nodes"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[S," visible nodes"]}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:h.join(" + ")})]})]})]}),w.length===0?e.jsx(Bt,{eyebrow:"Hierarchy",title:"No hierarchy nodes match the current filters",description:"Clear some filters or broaden the search to bring the full planning ladder back into view.",action:e.jsx(W,{variant:"secondary",onClick:()=>{i(""),n([]),o([]),m([...yn]),u(wn)},children:"Reset hierarchy filters"})}):e.jsxs(ce,{className:"min-w-0 overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(13,20,31,0.96),rgba(9,15,24,0.98))] p-0",children:[e.jsxs("div",{className:"grid grid-cols-[minmax(0,1.8fr)_auto_auto_auto] gap-3 border-b border-white/8 px-5 py-3 text-[11px] uppercase tracking-[0.18em] text-white/38",children:[e.jsx("div",{children:"Name"}),e.jsx("div",{className:"hidden lg:block",children:"State"}),e.jsx("div",{className:"hidden xl:block",children:"People"}),e.jsx("div",{className:"hidden lg:block",children:"Progress"})]}),e.jsx("div",{className:"p-2",children:e.jsx(zv,{ref:s,data:w,width:"100%",height:760,rowHeight:64,overscanCount:10,childrenAccessor:N=>N.children??null,openByDefault:!0,paddingTop:8,paddingBottom:8,disableDrag:!0,className:"text-sm",children:({node:N,style:P})=>{const v=N.data.kind==="subtask"?"task":N.data.kind,H=zs(v),j=H.colorToken.rgb.join(", ");return e.jsx("div",{style:P,className:"px-2 py-1.5",children:e.jsxs("div",{className:te("grid min-w-0 items-center gap-3 rounded-[16px] border border-white/8 px-3 py-2 transition hover:border-white/14 hover:bg-white/[0.05]","grid-cols-[minmax(0,1.8fr)_auto] lg:grid-cols-[minmax(0,1.8fr)_auto_auto] xl:grid-cols-[minmax(0,1.8fr)_auto_auto_auto]"),style:{marginLeft:`${N.level*14}px`,background:`linear-gradient(180deg, rgba(${j}, 0.07), rgba(255,255,255,0.02))`},children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("button",{type:"button",className:"inline-flex size-7 shrink-0 items-center justify-center rounded-full bg-white/[0.06] text-white/62 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>N.toggle(),disabled:N.isLeaf,"aria-label":N.isOpen?`Collapse ${N.data.label}`:`Expand ${N.data.label}`,children:N.isLeaf?e.jsx("span",{className:"size-2 rounded-full bg-white/22"}):N.isOpen?e.jsx(Sa,{className:"size-4"}):e.jsx(Hu,{className:"size-4"})}),e.jsx("span",{className:te("inline-flex size-9 shrink-0 items-center justify-center rounded-[12px] border",H.subtleBadgeClassName),children:e.jsx(H.icon,{className:te("size-4",H.iconClassName)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:V8(N.data.kind),children:N.data.kind}),N.data.executionMode?e.jsx(I,{className:N.data.executionMode==="afk"?"bg-emerald-400/12 text-emerald-100":"bg-amber-400/12 text-amber-100",children:N.data.executionMode.toUpperCase()}):null,e.jsx("div",{className:"truncate text-[13px] font-medium text-white",children:N.data.label})]}),e.jsx("div",{className:"mt-0.5 truncate text-[11px] leading-5 text-white/46",children:N.data.description})]})]}),e.jsx("div",{className:"hidden lg:flex justify-end",children:e.jsx(I,{className:mc(N.data.statusLabel),children:N.data.statusLabel?N.data.statusLabel.replaceAll("_"," "):"linked"})}),e.jsxs("div",{className:"hidden xl:flex items-center justify-end gap-2",children:[N.data.user?e.jsx(ot,{user:N.data.user,compact:!0}):null,N.data.assignees.length>0?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:["+",N.data.assignees.length]}):null]}),e.jsxs("div",{className:"hidden lg:flex min-w-[11rem] items-center justify-end gap-3",children:[e.jsxs("div",{className:"min-w-[7.5rem]",children:[e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full",style:{width:`${N.data.progressPercent??0}%`,background:`linear-gradient(90deg, rgba(${j}, 0.96), rgba(${j}, 0.72))`}})}),e.jsx("div",{className:"mt-1 text-[11px] text-white/44",children:N.data.progressLabel??`${N.data.progressPercent??0}% complete`})]}),N.data.href?e.jsx(Je,{to:N.data.href,className:"rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] uppercase tracking-[0.16em] text-white/72 transition hover:border-white/18 hover:bg-white/[0.08] hover:text-white",children:"Open"}):e.jsx("span",{className:"w-[3.75rem]"})]})]})})}})})]})]})}function J8({children:t,columns:s="single",className:a}){return e.jsx("section",{className:te("grid gap-4",s==="two"&&"lg:grid-cols-2",s==="sidebar"&&"xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",a),children:t})}function Z8(t){return t.trim().toLowerCase()}function Zp(t,s=!1){switch(t.kind){case"goal":return e.jsx(We,{kind:"goal",label:t.label,compact:!0,gradient:!1});case"task":return e.jsx(We,{kind:"task",label:t.label,compact:!0,gradient:!1});case"tag":return e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:t.label});case"status":return e.jsx(I,{className:"bg-[rgba(192,193,255,0.12)] text-white/84",children:t.label});case"type":return e.jsx(I,{className:"bg-[rgba(86,170,255,0.12)] text-white/84",children:t.label});case"user":return e.jsx(I,{className:"bg-[rgba(110,231,183,0.12)] text-white/84",children:t.label});default:return t.label}}function eT({query:t,onQueryChange:s,options:a,selectedOptionIds:i,onSelectedOptionIdsChange:r,resultSummary:n}){const[l,o]=c.useState(!1),[d,m]=c.useState(0),h=c.useMemo(()=>i.map(b=>a.find(A=>A.id===b)).filter(Boolean),[a,i]),u=Z8(t),x=c.useMemo(()=>{const b=a.filter(A=>!i.includes(A.id));return u?b.filter(A=>`${A.label} ${A.description??""} ${A.searchText??""}`.toLowerCase().includes(u)).slice(0,10):b.slice(0,10)},[u,a,i]),g=b=>{i.includes(b)||(r([...i,b]),s(""),m(0),o(!1))},p=b=>{r(i.filter(A=>A!==b))},f=()=>{s(""),r([]),m(0),o(!1)};return e.jsx("div",{className:"grid gap-3",children:e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,28,48,0.9),rgba(10,14,26,0.98))] p-4 shadow-[0_30px_80px_rgba(3,8,18,0.28)] sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Project search"}),e.jsx("div",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/62",children:"Search with free text, then pin matching goals, tasks, tags, human users, bot users, statuses, or project-type chips as you narrow the list."})]}),t.trim().length>0||i.length>0?e.jsx("button",{type:"button",onClick:f,className:"rounded-full border border-white/8 bg-white/[0.04] px-3 py-2 text-sm text-white/62 transition hover:bg-white/[0.08] hover:text-white",children:"Clear search"}):null]}),e.jsxs("div",{className:"mt-4 rounded-[24px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[h.length>0?e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:h.map(b=>e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[Zp(b,!0),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>p(b.id),"aria-label":`Remove ${b.label}`,children:e.jsx(Tt,{className:"size-3.5"})})]},b.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/36"}),e.jsx("input",{value:t,onChange:b=>{s(b.target.value),o(!0),m(0)},onFocus:()=>o(!0),onBlur:()=>{window.setTimeout(()=>o(!1),120)},onKeyDown:b=>{if(b.key==="Backspace"&&!t&&i.length>0){p(i[i.length-1]);return}if(b.key==="ArrowDown"){b.preventDefault(),o(!0),m(A=>x.length===0?0:Math.min(x.length-1,A+1));return}if(b.key==="ArrowUp"){b.preventDefault(),m(A=>Math.max(0,A-1));return}if(b.key==="Escape"){o(!1);return}b.key==="Enter"&&x[d]&&(b.preventDefault(),g(x[d].id))},placeholder:"Type a project, goal, task, human, bot, user, or tag",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),l?e.jsx("div",{className:"absolute top-full z-20 mt-2 w-full rounded-[22px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:x.length>0?x.map((b,A)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",A===d?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>m(A),onMouseDown:C=>C.preventDefault(),onClick:()=>g(b.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:Zp(b)}),b.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:b.description}):null]})},b.id)):e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:"Keep typing to search by free text, or select a suggested goal, task, human or bot owner, tag, status, or type chip when it appears."})}):null]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/52",children:n})]})})}const tT={execution:"Execution",value:"Value",category:"Category"};function sT(t){return t.trim().toLowerCase()}function aT(){const t=jt(),[s,a]=c.useState("active"),[i,r]=c.useState(""),[n,l]=c.useState([]),[o,d]=c.useState(null),m=c.useMemo(()=>$m(t.snapshot.dashboard.projects),[t.snapshot.dashboard.projects]),h=c.useMemo(()=>{const w=new Map(t.snapshot.dashboard.goals.map(P=>[P.id,P])),S=new Map(t.snapshot.tags.map(P=>[P.id,P])),y=new Map(t.snapshot.users.map(P=>[P.id,P])),N=new Map;for(const P of t.snapshot.tasks){if(!P.projectId)continue;const v=N.get(P.projectId)??[];v.push(P),N.set(P.projectId,v)}return new Map(t.snapshot.dashboard.projects.map(P=>{const v=w.get(P.goalId)??null,H=N.get(P.id)??[],j=P.userId?y.get(P.userId)??null:null,R=new Map;for(const Y of(v==null?void 0:v.tags)??[])R.set(Y.id,{id:Y.id,name:Y.name,kind:Y.kind});for(const Y of H)for(const z of Y.tagIds){const K=S.get(z);K&&R.set(K.id,{id:K.id,name:K.name,kind:K.kind})}const Q=Array.from(new Set(Array.from(R.values()).map(Y=>Y.kind))),X=[P.title,P.description,P.goalTitle,(j==null?void 0:j.displayName)??"",(j==null?void 0:j.handle)??"",(j==null?void 0:j.kind)??"",(v==null?void 0:v.description)??"",P.nextTaskTitle??"",P.momentumLabel,P.status,H.map(Y=>Y.title).join(" "),Array.from(R.values()).map(Y=>`${Y.name} ${Y.kind}`).join(" ")].join(" ").toLowerCase();return[P.id,{tagIds:Array.from(R.keys()),tags:Array.from(R.values()),taskIds:H.map(Y=>Y.id),typeKeys:Q,userId:P.userId,searchText:X}]}))},[t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks,t.snapshot.users]),u=c.useMemo(()=>{var j,R,Q,X,Y;const w=new Map,S=new Map,y=new Map,N=new Map,P=new Map,v=new Map,H=new Map;for(const z of t.snapshot.dashboard.projects){const K=h.get(z.id);if(K){S.has(z.goalId)||S.set(z.goalId,new Set),S.get(z.goalId).add(z.id),P.has(z.status)||P.set(z.status,new Set),P.get(z.status).add(z.id);for(const $ of K.taskIds)y.has($)||y.set($,new Set),y.get($).add(z.id);for(const $ of K.tags)N.has($.id)||N.set($.id,new Set),N.get($.id).add(z.id);for(const $ of K.typeKeys)v.has($)||v.set($,new Set),v.get($).add(z.id);K.userId&&(H.has(K.userId)||H.set(K.userId,new Set),H.get(K.userId).add(z.id))}}for(const z of t.snapshot.dashboard.goals){const K=((j=S.get(z.id))==null?void 0:j.size)??0;K!==0&&w.set(`goal:${z.id}`,{id:`goal:${z.id}`,kind:"goal",value:z.id,label:z.title,description:ut(`${K} project${K===1?"":"s"} linked to this goal`,z.user,`${K} project${K===1?"":"s"} linked to this goal`),searchText:dt([z.title,z.description],z)})}for(const z of t.snapshot.tasks){const K=((R=y.get(z.id))==null?void 0:R.size)??0;K!==0&&w.set(`task:${z.id}`,{id:`task:${z.id}`,kind:"task",value:z.id,label:z.title,description:ut(`${K} project${K===1?"":"s"} linked to this task`,z.user,`${K} project${K===1?"":"s"} linked to this task`),searchText:dt([z.title,z.description],z)})}for(const z of t.snapshot.tags){const K=((Q=N.get(z.id))==null?void 0:Q.size)??0;K!==0&&w.set(`tag:${z.id}`,{id:`tag:${z.id}`,kind:"tag",value:z.id,label:z.name,description:ut(`${K} project${K===1?"":"s"} touching this tag`,z.user,`${K} project${K===1?"":"s"} touching this tag`),searchText:dt([z.name,z.kind,z.description],z)})}for(const[z,K]of Object.entries(m))z==="all"||K===0||w.set(`status:${z}`,{id:`status:${z}`,kind:"status",value:z,label:z==="paused"?"Suspended":z==="completed"?"Finished":"Active",description:`${K} project${K===1?"":"s"} currently ${z==="paused"?"suspended":z==="completed"?"finished":"active"}`,searchText:`${z} ${z==="paused"?"suspended":""} ${z==="completed"?"finished":""}`});for(const[z,K]of Object.entries(tT)){const $=((X=v.get(z))==null?void 0:X.size)??0;$!==0&&w.set(`type:${z}`,{id:`type:${z}`,kind:"type",value:z,label:K,description:`${$} project${$===1?"":"s"} linked to ${K.toLowerCase()} tags`,searchText:`${K} ${z} project type`})}for(const z of t.snapshot.users){const K=((Y=H.get(z.id))==null?void 0:Y.size)??0;K!==0&&w.set(`user:${z.id}`,{id:`user:${z.id}`,kind:"user",value:z.id,label:z.displayName,description:`${K} project${K===1?"":"s"} owned by this ${z.kind}`,searchText:`${z.displayName} ${z.handle} ${z.kind} ${z.description}`})}return Array.from(w.values()).sort((z,K)=>z.label.localeCompare(K.label))},[m,h,t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks,t.snapshot.users]),x=c.useMemo(()=>n.map(w=>u.find(S=>S.id===w)).filter(Boolean),[u,n]),g=c.useMemo(()=>{const w=sT(i);return Om(t.snapshot.dashboard.projects,s).filter(S=>{const y=h.get(S.id);return!y||!x.every(P=>{switch(P.kind){case"goal":return S.goalId===P.value;case"task":return y.taskIds.includes(P.value);case"tag":return y.tagIds.includes(P.value);case"status":return S.status===P.value;case"type":return y.typeKeys.includes(P.value);case"user":return y.userId===P.value;default:return!0}})?!1:w?y.searchText.includes(w):!0})},[s,h,i,x,t.snapshot.dashboard.projects]),p=s==="all"?m.all:m[s],b=i.trim().length>0||n.length>0?`${g.length} matching project${g.length===1?"":"s"} in the current collection view`:`${p} project${p===1?"":"s"} in ${s==="all"?"all project states":s==="paused"?"the suspended view":s==="completed"?"the finished view":"the active view"}`,A=async w=>{d(w);try{await t.patchProject(w,{status:"active"})}finally{d(null)}},C=e.jsx(J8,{columns:"two",className:"2xl:grid-cols-3",children:g.map(w=>{const S=Js(t.snapshot.dashboard.notesSummaryByEntity,"project",w.id),y=h.get(w.id),N=(y==null?void 0:y.tags.slice(0,3))??[];return e.jsxs(ce,{className:"flex h-full flex-col transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"goal",label:w.goalTitle,compact:!0}),e.jsx(ot,{user:w.user,compact:!0})]}),e.jsx(I,{className:w.status==="completed"?"text-emerald-300":w.status==="paused"?"text-amber-300":"text-[var(--primary)]",children:w.status==="paused"?"Suspended":w.status==="completed"?"Finished":"Active"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Je,{to:`/projects/${w.id}`,className:"transition hover:opacity-90",children:e.jsx(yt,{kind:"project",label:w.title,variant:"heading",size:"xl",lines:2})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:w.description}),N.length>0?e.jsx(ew,{className:"mt-4",children:N.map(P=>e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:P.name},P.id))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(xa,{value:w.progress,tone:w.status==="completed"?"secondary":"primary"})}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Active"}),e.jsx("div",{className:"mt-2 text-white",children:w.activeTaskCount})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Completed"}),e.jsx("div",{className:"mt-2 text-white",children:w.completedTaskCount})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"XP"}),e.jsx("div",{className:"mt-2 text-white",children:w.earnedPoints})]})]}),e.jsx("div",{className:"mt-5 text-[11px] uppercase tracking-[0.16em] text-white/40",children:w.nextTaskTitle?`Next move: ${w.nextTaskTitle}`:"Ready for the next task"}),e.jsx("div",{className:"mt-4",children:e.jsx(Ks,{entityType:"project",entityId:w.id,count:S.count})}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 pt-1",children:[e.jsx(Je,{to:`/projects/${w.id}`,children:e.jsx(W,{variant:"ghost",children:"Open project"})}),s!=="active"&&w.status!=="active"?e.jsx(W,{variant:"secondary",pending:o===w.id,pendingLabel:"Restarting…",onClick:()=>void A(w.id),children:"Restart"}):null]})]},w.id)})}),T=[{id:"hero",title:"Projects",description:"Route header",defaultWidth:12,defaultHeight:2,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(Ib,{children:e.jsx(nt,{entityKind:"project",title:e.jsx(yt,{kind:"project",label:"Projects",variant:"heading",size:"lg"}),titleText:"Projects",description:"Projects are the concrete paths that move a life goal forward.",badge:`${t.snapshot.dashboard.projects.length} total projects`})})},{id:"search-results",title:"Search and results",description:"Search stays grouped with its live result set.",defaultWidth:8,defaultHeight:6,minWidth:6,render:({compact:w})=>e.jsx(Cb,{children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(eT,{query:i,onQueryChange:r,options:u,selectedOptionIds:n,onSelectedOptionIdsChange:l,resultSummary:b}),e.jsx(Rm,{value:s,counts:m,onChange:a}),g.length===0?e.jsxs(ce,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"No matching projects"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Nothing in this project collection matches the current search and chips."})]}):w?e.jsx("div",{className:"grid gap-3",children:g.slice(0,5).map(S=>e.jsx(Je,{to:`/projects/${S.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex items-center 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:S.title}),e.jsx("div",{className:"text-sm text-white/54",children:S.goalTitle})]}),e.jsxs(I,{className:"shrink-0 bg-white/[0.08] text-white/72",children:[S.earnedPoints," xp"]})]})},S.id))}):C]})})},{id:"summary",title:"Collection summary",description:"Counts and spotlight cards.",defaultWidth:4,defaultHeight:5,minWidth:4,render:()=>{const w=g[0]??t.snapshot.dashboard.projects[0]??null;return e.jsx(Tb,{children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-1",children:[e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Active"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:m.active})]}),e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Finished"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:m.completed})]})]}),w?e.jsxs(ce,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Spotlight"}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:w.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:w.description}),e.jsx("div",{className:"mt-3",children:e.jsx(xa,{value:w.progress})})]}):null]})})}}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Id,{}),t.snapshot.dashboard.projects.length===0?e.jsx(Bt,{eyebrow:"Projects",title:"No projects in flight",description:"Create the first practical path under a life goal so execution, kanban, and evidence all have a concrete home.",action:e.jsx(Je,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-white/[0.08] px-4 py-3 text-sm whitespace-nowrap text-white transition hover:bg-white/[0.12]",children:"Open goals"})}):e.jsx(Td,{surfaceId:"projects",baseWidgets:T})]})}const Yl=[{to:"/settings",label:"General",icon:Po},{to:"/settings/data",label:"Data",icon:_r},{to:"/settings/users",label:"Users",icon:Ku},{to:"/settings/calendar",label:"Calendar",icon:cs},{to:"/settings/mobile",label:"Mobile",icon:Kv},{to:"/settings/models",label:"Models",icon:qv},{to:"/settings/agents",label:"Agents",icon:ma},{to:"/settings/wiki",label:"KarpaWiki",icon:ed},{to:"/settings/logs",label:"Logs",icon:Bv},{to:"/settings/rewards",label:"Rewards",icon:Uv},{to:"/settings/bin",label:"Bin",icon:Uc}];function hc(t,s){return s==="/settings"?t==="/settings":t===s||t.startsWith(`${s}/`)}function ga({className:t}){const s=hi(),[a,i]=c.useState(!1),r=c.useMemo(()=>[...Yl].sort((n,l)=>l.to.length-n.to.length).find(n=>hc(s.pathname,n.to))??Yl[0],[s.pathname]);return c.useEffect(()=>{if(!a)return;const n=document.body.style.overflow,l=document.body.style.touchAction,o=d=>{d.key==="Escape"&&i(!1)};return document.body.style.overflow="hidden",document.body.style.touchAction="none",window.addEventListener("keydown",o),()=>{document.body.style.overflow=n,document.body.style.touchAction=l,window.removeEventListener("keydown",o)}},[a]),e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:te("surface-shell-panel overflow-hidden p-2",t),children:[e.jsx("div",{className:"hidden items-center gap-3 lg:flex",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Yl.map(n=>e.jsxs(_a,{to:n.to,end:n.to==="/settings",className:({isActive:l})=>te("inline-flex items-center gap-2 whitespace-nowrap rounded-full px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",l||hc(s.pathname,n.to)?"border border-[var(--primary)]/14 bg-[var(--ui-accent-soft)] text-[var(--primary)]":"border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-soft)] hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)] hover:text-[var(--ui-ink-strong)]"),children:[e.jsx(n.icon,{className:"size-3.5"}),e.jsx("span",{children:n.label})]},n.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsxs("button",{type:"button",className:"surface-shell-panel inline-flex min-w-0 flex-1 items-center justify-between gap-3 rounded-[22px] border px-3.5 py-2.5 text-left transition hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)]",onClick:()=>i(!0),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-2xl border border-[var(--primary)]/20 bg-[var(--primary)]/12",children:e.jsx(r.icon,{className:"size-4 text-[var(--primary)]"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[10px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Settings section"}),e.jsx("span",{className:"mt-0.5 block truncate text-sm font-medium text-[var(--ui-ink-strong)]",children:r.label})]})]}),e.jsx("span",{className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Browse"})]})})]}),a&&typeof document<"u"?Qi.createPortal(e.jsxs("div",{className:"lg:hidden",children:[e.jsx("div",{className:"surface-overlay fixed inset-0 z-50 backdrop-blur-xl"}),e.jsx("button",{type:"button","aria-label":"Close settings sections",className:"fixed inset-0 z-[51]",onClick:()=>i(!1)}),e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[52] flex items-end justify-center px-3 pt-3 sm:px-4 sm:pt-4",style:{paddingLeft:"max(0.75rem, calc(var(--forge-safe-area-left) + 0.75rem))",paddingRight:"max(0.75rem, calc(var(--forge-safe-area-right) + 0.75rem))",paddingTop:"max(0.75rem, calc(env(safe-area-inset-top) + 0.75rem))",paddingBottom:"calc(var(--forge-mobile-nav-clearance) - 0.25rem)"},children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Settings sections",className:"surface-modal-panel pointer-events-auto flex max-h-[min(34rem,calc(100dvh-var(--forge-mobile-nav-clearance)-1rem))] w-full max-w-xl min-h-0 flex-col overflow-hidden rounded-[30px] border",children:[e.jsx("div",{className:"shrink-0 border-b border-[var(--ui-border-subtle)] px-4 pb-3 pt-4 sm:px-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-[var(--ui-ink-faint)]",children:"Settings"}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("div",{className:"truncate text-base font-semibold text-[var(--ui-ink-strong)]",children:"Tune Forge"}),e.jsx("span",{className:"rounded-full border border-[var(--primary)]/20 bg-[var(--primary)]/12 px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[var(--primary)]",children:r.label})]}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-soft)]",children:"Jump between users, calendar, models, rewards, and more."})]}),e.jsx("button",{type:"button","aria-label":"Close settings sections",className:"inline-flex size-10 shrink-0 items-center justify-center rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-soft)] transition hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)] hover:text-[var(--ui-ink-strong)]",onClick:()=>i(!1),children:e.jsx(Tt,{className:"size-4"})})]})}),e.jsx("div",{className:"min-h-0 overflow-y-auto p-3 overscroll-contain sm:p-4",children:e.jsx("div",{className:"grid gap-2",children:Yl.map(n=>{const l=hc(s.pathname,n.to);return e.jsxs(_a,{to:n.to,end:n.to==="/settings",onClick:()=>i(!1),className:te("group flex items-center justify-between gap-3 rounded-[22px] border px-3.5 py-3 transition-[transform,border-color,background-color,color] duration-150 hover:-translate-y-[1px] hover:text-white",l?"border-[var(--primary)]/18 bg-[var(--ui-accent-soft)] text-[var(--ui-ink-strong)]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-medium)] hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)]"),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:te("flex size-10 shrink-0 items-center justify-center rounded-2xl border transition",l?"border-[var(--primary)]/18 bg-[var(--primary)]/14 text-[var(--primary)]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-soft)] group-hover:border-[var(--ui-border-strong)] group-hover:text-[var(--ui-ink-strong)]"),children:e.jsx(n.icon,{className:"size-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-semibold text-[var(--ui-ink-strong)]",children:n.label}),e.jsx("span",{className:"mt-0.5 block text-[10px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Forge settings"})]})]}),e.jsx("span",{className:te("rounded-full px-2.5 py-1 text-[10px] uppercase tracking-[0.16em]",l?"bg-[var(--primary)]/16 text-[var(--primary)]":"bg-[var(--ui-surface-1)] text-[var(--ui-ink-faint)]"),children:l?"Current":"Open"})]},n.to)})})})]})})]}),document.body):null]})}const Ww=[{value:"gpt-5.4",label:"GPT-5.4",description:"Highest quality drafting for long, connected wiki pages."},{value:"gpt-5.4-mini",label:"GPT-5.4 mini",description:"Balanced speed and quality for regular ingest jobs."},{value:"gpt-5.4-nano",label:"GPT-5.4 nano",description:"Fastest and cheapest option for smaller imports."}];Ww[1].value;const iT="medium",rT="medium";function nT(t){const s=t==null?void 0:t.reasoningEffort;return s==="none"||s==="low"||s==="medium"||s==="high"||s==="xhigh"?s:iT}function lT(t){const s=t==null?void 0:t.verbosity;return s==="low"||s==="medium"||s==="high"?s:rT}function ex(t){var a;return{model:((a=Ww.find(i=>i.value===t.model))==null?void 0:a.label)??t.model,reasoning:nT(t.metadata),verbosity:lT(t.metadata),hasKey:!!t.secretId}}function oT(){var z,K;const t=ct(),[s,a]=c.useState(""),[i,r]=c.useState(""),[n,l]=c.useState("personal"),[o,d]=c.useState("Fast wiki search"),[m,h]=c.useState("text-embedding-3-small"),[u,x]=c.useState("https://api.openai.com/v1"),[g,p]=c.useState(""),[f,b]=c.useState("1200"),[A,C]=c.useState("200"),T=Fe({queryKey:["forge-wiki-settings"],queryFn:pd}),w=Fe({queryKey:["forge-settings"],queryFn:Xr}),S=async()=>{await Promise.all([t.invalidateQueries({queryKey:["forge-wiki-settings"]}),t.invalidateQueries({queryKey:["forge-wiki-pages"]}),t.invalidateQueries({queryKey:["forge-wiki-page"]}),t.invalidateQueries({queryKey:["forge-wiki-search"]})])},y=Re({mutationFn:()=>Yj({label:s.trim(),description:i.trim(),visibility:n}),onSuccess:async()=>{a(""),r(""),l("personal"),await S()}}),N=Re({mutationFn:()=>oN({label:o.trim(),model:m.trim(),baseUrl:u.trim(),apiKey:g.trim()||void 0,chunkSize:Number(f),chunkOverlap:Number(A)}),onSuccess:async()=>{p(""),await S()}}),P=Re({mutationFn:({kind:$,profileId:D})=>dN($,D),onSuccess:S}),v=Re({mutationFn:()=>nN(),onSuccess:S}),H=Re({mutationFn:()=>lN(),onSuccess:S});if(T.isLoading)return e.jsx(Et,{eyebrow:"KarpaWiki settings",title:"Loading KarpaWiki controls",description:"Fetching spaces and profile configuration for KarpaWiki."});if(T.isError)return e.jsx(it,{eyebrow:"KarpaWiki settings",error:T.error,onRetry:()=>void T.refetch()});const j=(z=T.data)==null?void 0:z.settings;if(!j)return e.jsx(it,{eyebrow:"KarpaWiki settings",error:new Error("Forge returned an empty KarpaWiki settings payload."),onRetry:()=>void T.refetch()});const R=j.llmProfiles.find($=>$.enabled)??j.llmProfiles[0]??null,Q=R?ex(R):null,X="Canonical knowledge lives in SQLite notes, with Forge maintaining metadata, links, search, and optional embedding indexes in the database. Text search and entity-linked search work without embeddings, while semantic search stays additive and profile-driven. Ingest jobs can create pages and media assets now, with room for richer OCR, transcription, and multimodal compilation later.",Y=(K=w.data)==null?void 0:K.settings.modelSettings.forgeAgent.wiki;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(nt,{eyebrow:"SQLite memory",title:"KarpaWiki Settings",titleText:"KarpaWiki Settings",description:"Configure SQLite-backed spaces, parse models, and embedding profiles for the KarpaWiki memory system.",badge:`${j.spaces.length} spaces · ${j.embeddingProfiles.length} embedding profiles`,actions:e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"secondary",pending:v.isPending,pendingLabel:"Syncing",onClick:()=>void v.mutateAsync(),children:"Refresh indexes"}),e.jsx(W,{pending:H.isPending,pendingLabel:"Reindexing",onClick:()=>void H.mutateAsync(),disabled:j.embeddingProfiles.length===0,children:"Reindex embeddings"})]})}),e.jsx(ga,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Auto-ingest model"}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"KarpaWiki ingest now reads its credentials and model slot from the dedicated Models settings page instead of owning the OpenAI setup flow here."})]})}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.8fr)_minmax(24rem,0.9fr)]",children:[e.jsxs("div",{className:"grid gap-5 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(22,32,49,0.9),rgba(12,18,31,0.9))] p-6",children:[e.jsxs("div",{className:"flex 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:"Current profile"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:(Y==null?void 0:Y.connectionLabel)??(R==null?void 0:R.label)??"No external KarpaWiki model selected"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:Y!=null&&Y.connectionLabel?"Forge now resolves wiki ingest through the selected Models connection and syncs the managed wiki profile automatically.":"Pick a Models connection when you want Forge wiki ingest to run through the OpenAI API or a local compatible endpoint."})]}),e.jsx(Je,{to:"/settings/models",className:"inline-flex min-h-11 items-center rounded-[16px] bg-white/[0.08] px-4 py-3 text-sm text-white transition hover:bg-white/[0.12]",children:"Open model settings"})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Model"}),e.jsx("div",{className:"mt-2 text-white",children:(Y==null?void 0:Y.model)??(Q==null?void 0:Q.model)??"Not set"})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Provider"}),e.jsx("div",{className:"mt-2 text-white",children:(Y==null?void 0:Y.connectionLabel)??"Not set"})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Endpoint"}),e.jsx("div",{className:"mt-2 flex items-center gap-2 text-white",children:(Y==null?void 0:Y.baseUrl)??(R==null?void 0:R.baseUrl)??"Not set"})]})]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[28px] border border-white/8 bg-white/[0.03] p-6",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Supported controls"}),e.jsxs("div",{className:"text-sm leading-6 text-white/58",children:["OpenAI API and local compatible endpoints are configured under Settings ","->"," Models. OpenAI Codex OAuth lives there as a chat agent path, while Wiki keeps the SQLite memory controls here and consumes the selected ingest model slot."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:["GPT-5.4","GPT-5.4 mini","GPT-5.4 nano"].map($=>e.jsx(I,{className:"bg-white/[0.06] text-white/78",children:$},$))}),e.jsxs(Je,{to:"/settings/models",className:"inline-flex min-h-11 items-center rounded-[16px] bg-white/[0.08] px-4 py-3 text-sm text-white transition hover:bg-white/[0.12]",children:["Open model settings",e.jsx(Es,{className:"ml-2 size-4"})]})]})]}),e.jsxs("div",{className:"grid gap-3",children:[j.llmProfiles.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-5 text-sm leading-6 text-white/58",children:"No LLM profile yet. Set up OpenAI once, test it, and Forge will use it for wiki auto-ingest."}):null,j.llmProfiles.map($=>{const D=ex($);return e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-white",children:$.label}),e.jsxs("div",{className:"mt-1 text-xs text-white/46",children:[D.model," · thinking ",D.reasoning," · verbosity ",D.verbosity]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{type:"button",className:"rounded-full p-2 text-white/48 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>void P.mutateAsync({kind:"llm",profileId:$.id}),children:e.jsx(Rt,{className:"size-4"})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-white/58",children:[e.jsx(I,{className:"bg-white/[0.06] text-white/76",children:$.baseUrl}),e.jsx(I,{className:"bg-white/[0.06] text-white/76",children:D.hasKey?"key saved":"key missing"})]})]},$.id)})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wv,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm text-white",children:"Spaces"}),e.jsx(vt,{content:X,label:"Explain the wiki operating model"})]}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"Personal and shared wiki spaces map to explicit SQLite namespaces."})]})]}),e.jsx("div",{className:"grid gap-3",children:j.spaces.map($=>e.jsxs("div",{className:"grid gap-1 rounded-[18px] 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:"text-white",children:$.label}),e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/42",children:$.visibility})]}),e.jsx("div",{className:"text-xs text-white/46",children:$.slug}),e.jsx("div",{className:"text-sm text-white/60",children:$.description||"No description yet."})]},$.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsx(ye,{value:s,onChange:$=>a($.target.value),placeholder:"New space label"}),e.jsx(ye,{value:i,onChange:$=>r($.target.value),placeholder:"Description"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:n,onChange:$=>l($.target.value),children:[e.jsx("option",{value:"personal",children:"Personal"}),e.jsx("option",{value:"shared",children:"Shared"})]}),e.jsx(W,{pending:y.isPending,pendingLabel:"Creating",disabled:!s.trim(),onClick:()=>void y.mutateAsync(),children:"Create space"})]})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Hv,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Embedding profiles"}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"Semantic search stays opt-in. The recommended starter is fast and cheap, with heading-aware chunking for agent memory retrieval."})]})]}),e.jsx("div",{className:"grid gap-3",children:j.embeddingProfiles.map($=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] 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:"text-white",children:$.label}),e.jsx("button",{type:"button",className:"rounded-full p-2 text-white/48 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>void P.mutateAsync({kind:"embedding",profileId:$.id}),children:e.jsx(Rt,{className:"size-4"})})]}),e.jsxs("div",{className:"text-xs text-white/46",children:[$.model," · ",$.baseUrl]}),e.jsxs("div",{className:"text-sm text-white/60",children:["chunkSize ",$.chunkSize," · overlap"," ",$.chunkOverlap]})]},$.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsx(ye,{value:o,onChange:$=>d($.target.value),placeholder:"Profile label"}),e.jsx(ye,{value:m,onChange:$=>h($.target.value),placeholder:"Model"}),e.jsx(ye,{value:u,onChange:$=>x($.target.value),placeholder:"Base URL"}),e.jsx(ye,{value:g,onChange:$=>p($.target.value),placeholder:"API key (optional)",type:"password"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsx(ye,{value:f,onChange:$=>b($.target.value),placeholder:"Chunk size",type:"number"}),e.jsx(ye,{value:A,onChange:$=>C($.target.value),placeholder:"Chunk overlap",type:"number"})]}),e.jsx(W,{pending:N.isPending,pendingLabel:"Saving",disabled:!o.trim()||!m.trim(),onClick:()=>void N.mutateAsync(),children:"Save embedding profile"})]})]})]})]})]})}function Um(t){return[{id:"title",label:"Strategy title is set",satisfied:t.title.trim().length>0},{id:"graph",label:"Graph contains at least one linked project or task",satisfied:t.graph.nodes.length>0},{id:"targets",label:"At least one target goal or project is selected",satisfied:t.targetGoalIds.length>0||t.targetProjectIds.length>0},{id:"narrative",label:"The plan already names an overview or end state",satisfied:t.overview.trim().length>0||t.endStateDescription.trim().length>0}]}function Hw(t){return Um(t).every(s=>s.satisfied)}function Wm(t){return[{id:"coverage",label:"Agreed work moving",value:t.planCoverageScore,detail:`${t.startedNodeCount}/${t.totalNodeCount} agreed steps have started or finished.`},{id:"order",label:"Order respected",value:t.sequencingScore,detail:`${t.outOfOrderNodeIds.length} step${t.outOfOrderNodeIds.length===1?"":"s"} started before prerequisites were complete.`},{id:"scope",label:"Scope held",value:t.scopeDisciplineScore,detail:`${t.offPlanEntityCount} unagreed item${t.offPlanEntityCount===1?"":"s"} are inside the strategy scope, ${t.offPlanActiveEntityCount} still active.`},{id:"satisfaction",label:"End-state satisfaction",value:t.qualityScore,detail:`${t.targetProgressScore}% target progress with ${t.blockedNodeIds.length} blocked step${t.blockedNodeIds.length===1?"":"s"}.`}]}function dT(t){return t.trim().toLowerCase()}function kr(t,s){return t.includes(s)?t.filter(a=>a!==s):[...t,s]}function tx(t,s){return t.some(a=>a.entityType===s.entityType&&a.entityId===s.entityId)?t.filter(a=>!(a.entityType===s.entityType&&a.entityId===s.entityId)):[...t,s]}function sx(t,s){if(t.length!==s.length)return!1;const a=new Set(s);return t.every(i=>a.has(i))}function Qo(t="project",s){return{id:`strategy_node_${Math.random().toString(36).slice(2,10)}`,entityType:t,entityId:"",branchLabel:"",notes:"",dependencyMode:"after_previous",customPredecessorIds:[],...s}}function cT(t){const s=new Map(t.graph.nodes.map(o=>[o.id,o])),a=new Map(t.graph.nodes.map(o=>[o.id,0])),i=new Map,r=new Map(t.graph.nodes.map((o,d)=>[o.id,d]));for(const o of t.graph.nodes)i.set(o.id,[]);for(const o of t.graph.edges)a.set(o.to,(a.get(o.to)??0)+1),i.set(o.from,[...i.get(o.from)??[],o.to]);const n=t.graph.nodes.filter(o=>(a.get(o.id)??0)===0).sort((o,d)=>(r.get(o.id)??0)-(r.get(d.id)??0)).map(o=>o.id),l=[];for(;n.length>0;){n.sort((m,h)=>(r.get(m)??0)-(r.get(h)??0));const o=n.shift();if(!o)continue;const d=s.get(o);if(d){l.push(d);for(const m of i.get(o)??[]){const h=(a.get(m)??0)-1;a.set(m,h),h===0&&n.push(m)}}}return l.length===t.graph.nodes.length?l:t.graph.nodes}function uT(t){const s=new Map;for(const i of t.graph.nodes)s.set(i.id,[]);for(const i of t.graph.edges)s.set(i.to,[...s.get(i.to)??[],i.from]);const a=cT(t);return{title:t.title,overview:t.overview,endStateDescription:t.endStateDescription,status:t.status,userId:t.userId??null,targetGoalIds:t.targetGoalIds,targetProjectIds:t.targetProjectIds,linkedEntities:t.linkedEntities,nodes:a.map((i,r)=>{const n=s.get(i.id)??[],l=a[r-1],o=l?s.get(l.id)??[]:[];let d="custom";return n.length===0?d="start":l&&sx(n,[l.id])?d="after_previous":l&&n.length>0&&sx(n,o)&&(d="parallel_with_previous"),Qo(i.entityType,{id:i.id,entityId:i.entityId,branchLabel:i.branchLabel,notes:i.notes,dependencyMode:d,customPredecessorIds:n})})}}function Gw(t){const s=new Map,a=new Set;for(const[i,r]of t.entries()){const n=t[i-1];let l;switch(r.dependencyMode){case"after_previous":l=n?[n.id]:[];break;case"parallel_with_previous":l=n?[...s.get(n.id)??[]]:[];break;case"custom":l=r.customPredecessorIds.filter(o=>a.has(o));break;case"start":default:l=[];break}s.set(r.id,l),a.add(r.id)}return s}function ax(t){const s=Gw(t),a=new Set,i=new Set;function r(n){if(i.has(n))return!0;if(a.has(n))return!1;a.add(n),i.add(n);for(const l of s.get(n)??[])if(r(l))return!0;return i.delete(n),!1}return t.some(n=>r(n.id))}const ix={title:"",overview:"",endStateDescription:"",status:"active",userId:null,targetGoalIds:[],targetProjectIds:[],linkedEntities:[],nodes:[Qo("project",{dependencyMode:"start"})]};function cr(t,s){const a=s[0];return{title:"",description:"",goalId:(a==null?void 0:a.goalId)??"",projectId:(a==null?void 0:a.id)??"",userId:(a==null?void 0:a.userId)??t,priority:"medium",effort:"deep",energy:"steady",points:60}}function mT(t,s,a){const i=Gw(t.nodes),r=new Set(t.nodes.filter(n=>n.entityId).map(n=>n.id));return{nodes:t.nodes.filter(n=>n.entityId).map(n=>{var l,o;return{id:n.id,entityType:n.entityType,entityId:n.entityId,title:n.entityType==="project"?((l=s.get(n.entityId))==null?void 0:l.title)??n.entityId:((o=a.get(n.entityId))==null?void 0:o.title)??n.entityId,branchLabel:n.branchLabel.trim(),notes:n.notes.trim()}}),edges:t.nodes.flatMap(n=>r.has(n.id)?(i.get(n.id)??[]).filter(l=>r.has(l)).map(l=>({from:l,to:n.id,label:"",condition:""})):[])}}function rx(t){return((t==null?void 0:t.progress)??0)/100}function hT(t){switch(t==null?void 0:t.status){case"done":return 1;case"in_progress":return .66;case"focus":return .5;case"blocked":return .25;default:return 0}}function pT(t){const{draft:s,graph:a,goals:i,projects:r,projectsById:n,tasks:l,tasksById:o}=t,d=new Map(a.nodes.map(D=>[D.id,D.entityType==="project"?rx(n.get(D.entityId)):hT(o.get(D.entityId))])),m=new Map;for(const D of a.nodes)m.set(D.id,[]);for(const D of a.edges)m.set(D.to,[...m.get(D.to)??[],D.from]);const h=a.nodes.filter(D=>(d.get(D.id)??0)>=1).map(D=>D.id),u=a.nodes.filter(D=>(d.get(D.id)??0)>0).map(D=>D.id),x=a.nodes.filter(D=>{var J,q;return D.entityType==="project"?((J=n.get(D.entityId))==null?void 0:J.status)==="paused":((q=o.get(D.entityId))==null?void 0:q.status)==="blocked"}).map(D=>D.id),g=a.nodes.filter(D=>(d.get(D.id)??0)<=0?!1:(m.get(D.id)??[]).some(q=>(d.get(q)??0)<1)).map(D=>D.id),p=a.nodes.filter(D=>(d.get(D.id)??0)>=1?!1:(m.get(D.id)??[]).every(q=>(d.get(q)??0)>=1)).map(D=>D.id),f=new Map(i.map(D=>[D.id,D])),b=s.targetGoalIds.map(D=>{var q;const J=l.filter(_=>_.goalId===D);return J.length===0?((q=f.get(D))==null?void 0:q.status)==="completed"?1:0:J.filter(_=>_.status==="done").length/J.length}),A=s.targetProjectIds.map(D=>rx(n.get(D))),C=[...b,...A],T=a.nodes.length===0?0:a.nodes.reduce((D,J)=>D+(d.get(J.id)??0),0)/a.nodes.length,w=C.length===0?T:C.reduce((D,J)=>D+J,0)/C.length,S=new Set(a.nodes.filter(D=>D.entityType==="project").map(D=>D.entityId)),y=new Set(a.nodes.filter(D=>D.entityType==="task").map(D=>D.entityId)),N=new Set,P=new Set,v=new Set;for(const D of s.targetProjectIds){const J=r.find(q=>q.id===D);if(J&&!S.has(J.id)&&J.status!=="completed"){const q=`project:${J.id}`;N.add(q),P.add(q)}for(const q of l.filter(_=>_.projectId===D))if(!y.has(q.id)&&["focus","in_progress","done","blocked"].includes(q.status)){const _=`task:${q.id}`;N.add(_),q.status==="done"?v.add(_):P.add(_)}}for(const D of s.targetGoalIds)for(const J of l.filter(q=>q.goalId===D))if(!y.has(J.id)&&["focus","in_progress","done","blocked"].includes(J.status)){const q=`task:${J.id}`;N.add(q),J.status==="done"?v.add(q):P.add(q)}const H=Math.max(1,a.nodes.length),j=N.size,R=x.length/H,Q=Math.max(0,Math.min(100,Math.round(T*100))),X=Math.max(0,Math.min(100,Math.round(100-g.length/H*100))),Y=Math.max(0,Math.min(100,Math.round(100-j/H*100))),z=Math.max(0,Math.min(100,Math.round(Math.max(0,Math.min(1,w*.8+(1-R)*.2))*100))),K=Math.max(0,Math.min(100,Math.round(w*100)));return{alignmentScore:Math.max(0,Math.min(100,Math.round(Q*.35+X*.3+Y*.2+z*.15))),planCoverageScore:Q,sequencingScore:X,scopeDisciplineScore:Y,qualityScore:z,targetProgressScore:K,completedNodeCount:h.length,startedNodeCount:u.length,readyNodeCount:p.length,totalNodeCount:H,completedTargetCount:C.filter(D=>D>=1).length,totalTargetCount:C.length,offPlanEntityCount:j,offPlanActiveEntityCount:P.size,offPlanCompletedEntityCount:v.size,activeNodeIds:p.slice(0,8),nextNodeIds:p.slice(0,5),blockedNodeIds:x,outOfOrderNodeIds:g}}function xT({node:t,index:s,total:a,projectsById:i,tasksById:r,usersById:n,allNodes:l,onUpdate:o,onRemove:d}){const{attributes:m,listeners:h,setNodeRef:u,transform:x,transition:g,isDragging:p}=pl({id:t.id}),f=t.entityType==="project"?i.get(t.entityId):r.get(t.entityId),b=f&&"userId"in f&&f.userId?n.get(f.userId)??f.user??null:null,A=l.slice(0,s);return e.jsxs("div",{ref:u,style:{transform:xl.Transform.toString(x),transition:g},className:te("min-w-0 overflow-hidden rounded-[24px] border border-white/8 bg-[rgba(8,14,26,0.8)] p-4 shadow-[0_24px_60px_rgba(0,0,0,0.2)]",p&&"opacity-70"),children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("button",{type:"button",className:"mt-1 rounded-full bg-white/[0.06] p-2 text-white/58 transition hover:bg-white/[0.1] hover:text-white",...m,...h,children:e.jsx(ul,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/76",children:["Step ",s+1]}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:t.entityType}),f?e.jsx(We,{kind:t.entityType,label:f.title,compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-3 text-base font-medium text-white",children:(f==null?void 0:f.title)||"Select an entity for this step"}),e.jsx("div",{className:"mt-2 break-words text-sm leading-6 text-white/54",children:t.notes||(f&&"description"in f?f.description:"")||"Add an optional note if this phase needs intent or setup context."}),b?e.jsx("div",{className:"mt-3",children:e.jsx(ot,{user:b,compact:!0})}):null]})]}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"w-full sm:w-auto",disabled:a===1,onClick:()=>d(t.id),children:[e.jsx(Rt,{className:"size-4"}),"Remove"]})]}),e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsx(de,{label:"Relationship to the flow",labelHelp:"Keep the sequence mostly linear in the form. Use parallel when this step should open beside the previous one, or custom only when the dependency is special.",children:e.jsx(wt,{value:t.dependencyMode,columns:2,onChange:C=>o(t.id,{dependencyMode:C}),options:[{value:"start",label:"Start here",description:"This step opens immediately."},{value:"after_previous",label:"After previous",description:"Use the prior step as the gate."},{value:"parallel_with_previous",label:"Parallel with previous",description:"Open beside the prior branch."},{value:"custom",label:"Custom dependency",description:"Pick earlier steps manually."}]})}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(de,{label:"Branch label",children:e.jsx(ye,{value:t.branchLabel,onChange:C=>o(t.id,{branchLabel:C.target.value}),placeholder:"Core path, fallback lane, support branch"})}),e.jsx(de,{label:"Step note",children:e.jsx(Ze,{value:t.notes,onChange:C=>o(t.id,{notes:C.target.value}),placeholder:"Explain what has to be true before or after this step."})})]})]}),t.dependencyMode==="custom"?e.jsxs("div",{className:"mt-4 rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Depends on"}),e.jsx("div",{className:"mt-3 grid gap-2",children:A.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No earlier steps available yet."}):A.map(C=>{const T=C.entityType==="project"?i.get(C.entityId):r.get(C.entityId);return e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:(T==null?void 0:T.title)||`Step ${l.indexOf(C)+1}`}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/52",children:C.branchLabel||C.entityType})]}),e.jsx("input",{type:"checkbox",checked:t.customPredecessorIds.includes(C.id),onChange:()=>o(t.id,{customPredecessorIds:kr(t.customPredecessorIds,C.id)})})]},C.id)})})]}):null]})}function Qw({open:t,pending:s=!1,editingStrategy:a,goals:i,projects:r,tasks:n,habits:l,strategies:o,users:d,defaultUserId:m=null,initialStepId:h,onOpenChange:u,onSubmit:x}){const[g,p]=c.useState(ix),[f,b]=c.useState(""),[A,C]=c.useState(""),[T,w]=c.useState(""),[S,y]=c.useState(null),[N,P]=c.useState([]),[v,H]=c.useState(cr(m,r)),[j,R]=c.useState(!1),[Q,X]=c.useState(null),[Y,z]=c.useState(!1);c.useEffect(()=>{var se,_e,Be;if(!t)return;const k=a?uT(a):{...ix,userId:m,nodes:[Qo("project",{dependencyMode:"start"})]};p(k),b(""),C(""),w(""),P([]),R(!1),H(cr(m,r).projectId&&k.targetProjectIds[0]?{...cr(m,r),goalId:((se=r.find(Ge=>Ge.id===k.targetProjectIds[0]))==null?void 0:se.goalId)??"",projectId:k.targetProjectIds[0]??((_e=r[0])==null?void 0:_e.id)??"",userId:((Be=r.find(Ge=>Ge.id===k.targetProjectIds[0]))==null?void 0:Be.userId)??m}:cr(m,r)),X(null),y(null)},[m,a,t,r]);const K=c.useDeferredValue(f),$=c.useDeferredValue(A),D=c.useDeferredValue(T),J=c.useMemo(()=>{const k=new Set(N.map(se=>se.id));return[...N,...n.filter(se=>!k.has(se.id))]},[N,n]),q=c.useMemo(()=>new Map(i.map(k=>[k.id,k])),[i]),_=c.useMemo(()=>new Map(r.map(k=>[k.id,k])),[r]),B=c.useMemo(()=>new Map(J.map(k=>[k.id,k])),[J]),G=c.useMemo(()=>new Map(d.map(k=>[k.id,k])),[d]),ae=d.find(k=>k.id===m)??null,ke=d.find(k=>k.id===g.userId)??ae,Ae=(k,se,_e)=>{const Be=dT(k);return Be.length===0||dt(se,_e).includes(Be)},ie=c.useMemo(()=>i.filter(k=>Ae($,[k.title,k.description],k.user)),[$,i]),Ie=c.useMemo(()=>i.filter(k=>Ae(K,[k.title,k.description],k.user)),[i,K]),Ne=c.useMemo(()=>r.filter(k=>Ae(K,[k.title,k.description,k.goalTitle,k.status],k.user)),[K,r]),M=c.useMemo(()=>r.filter(k=>Ae($,[k.title,k.description,k.goalTitle,k.status],k.user)),[$,r]),E=c.useMemo(()=>J.filter(k=>Ae($,[k.title,k.description,k.owner,k.status],k.user)),[J,$]),O=c.useMemo(()=>l.filter(k=>Ae($,[k.title,k.description,k.frequency,k.status],k.user)),[$,l]),xe=c.useMemo(()=>o.filter(k=>k.id!==(a==null?void 0:a.id)&&Ae($,[k.title,k.overview,k.endStateDescription,k.status],k.user)),[$,a==null?void 0:a.id,o]),V=c.useMemo(()=>[...ie.map(se=>({key:`goal:${se.id}`,entityType:"goal",entityId:se.id,label:se.title,description:ut(se.description,se.user,"Goal"),user:se.user??null})),...M.map(se=>({key:`project:${se.id}`,entityType:"project",entityId:se.id,label:se.title,description:ut(`${se.goalTitle}${se.goalTitle?" · ":""}${se.status}`,se.user,`Project · ${se.goalTitle}`),user:se.user??null})),...E.map(se=>({key:`task:${se.id}`,entityType:"task",entityId:se.id,label:se.title,description:ut(`${se.status} · ${se.owner}`,se.user,`Task · ${se.owner}`),user:se.user??null})),...O.map(se=>({key:`habit:${se.id}`,entityType:"habit",entityId:se.id,label:se.title,description:ut(se.description,se.user,"Habit"),user:se.user??null})),...xe.map(se=>({key:`strategy:${se.id}`,entityType:"strategy",entityId:se.id,label:se.title,description:ut(se.overview,se.user,"Strategy"),user:se.user??null}))].sort((se,_e)=>se.label.localeCompare(_e.label)),[ie,O,M,xe,E]),Se=c.useMemo(()=>mT(g,_,B),[g,_,B]),Ee=c.useMemo(()=>pT({draft:g,graph:Se,goals:i,projects:r,projectsById:_,tasks:J,tasksById:B}),[J,g,Se,i,r,_,B]),Ce=c.useMemo(()=>[...Um({title:g.title,overview:g.overview,endStateDescription:g.endStateDescription,targetGoalIds:g.targetGoalIds,targetProjectIds:g.targetProjectIds,graph:Se}),{id:"acyclic",label:"Graph stays directed and non-looping",satisfied:!ax(g.nodes)}],[g.endStateDescription,g.nodes,g.overview,g.targetGoalIds,g.targetProjectIds,g.title,Se]),qe=c.useMemo(()=>Hw({title:g.title,overview:g.overview,endStateDescription:g.endStateDescription,targetGoalIds:g.targetGoalIds,targetProjectIds:g.targetProjectIds,graph:Se}),[g.endStateDescription,g.overview,g.targetGoalIds,g.targetProjectIds,g.title,Se]),oe=c.useMemo(()=>Wm(Ee),[Ee]),L=c.useMemo(()=>{if(!g.title.trim())return"Strategy title is required.";if(g.nodes.length===0)return"Add at least one project or task step.";const k=new Set;for(const se of g.nodes){if(!se.entityId)return"Every step needs a linked project or task.";const _e=`${se.entityType}:${se.entityId}`;if(k.has(_e))return"Each project or task should appear only once in the sequence.";k.add(_e)}return ax(g.nodes)?"Strategy graph must stay directed and non-loopy.":null},[g.nodes,g.title]),U=k=>k==="sequence"?S??L??(qe?null:"This can still be saved as a draft. Add the target plus the overview or end state later, then lock it as the contract from the strategy detail page."):null,ge=c.useMemo(()=>i.filter(k=>Ae(D,[k.title,k.description],k.user)),[i,D]),Te=c.useMemo(()=>r.filter(k=>Ae(D,[k.title,k.description,k.goalTitle,k.status],k.user)),[r,D]),ve=c.useMemo(()=>J.filter(k=>Ae(D,[k.title,k.description,k.owner,k.status],k.user)),[J,D]),Le=c.useMemo(()=>new Set(g.targetGoalIds),[g.targetGoalIds]),Qe=c.useMemo(()=>new Set(g.targetProjectIds),[g.targetProjectIds]),st=c.useMemo(()=>new Set(g.nodes.map(k=>`${k.entityType}:${k.entityId}`)),[g.nodes]),F=c.useMemo(()=>g.targetGoalIds.map(k=>q.get(k)).filter(k=>!!k),[g.targetGoalIds,q]),he=c.useMemo(()=>g.targetProjectIds.map(k=>_.get(k)).filter(k=>!!k),[g.targetProjectIds,_]),we=c.useMemo(()=>Te.filter(k=>Qe.has(k.id)||Le.has(k.goalId)),[Te,Le,Qe]),Z=c.useMemo(()=>ve.filter(k=>Qe.has(k.projectId??"")||Le.has(k.goalId??"")),[ve,Le,Qe]),De=c.useMemo(()=>Ie.slice(0,8),[Ie]),ee=c.useMemo(()=>Ne.slice(0,8),[Ne]),ze=c.useMemo(()=>V.slice(0,12),[V]),et=c.useMemo(()=>ge.slice(0,6),[ge]),Ve=c.useMemo(()=>Te.slice(0,8),[Te]),re=c.useMemo(()=>ve.slice(0,10),[ve]),ne=c.useMemo(()=>we.slice(0,4),[we]),be=c.useMemo(()=>Z.slice(0,6),[Z]),je=c.useMemo(()=>{if(!v.goalId)return r;const k=r.filter(se=>se.goalId===v.goalId);return k.length>0?k:r},[v.goalId,r]),pe=D.length>0,$e=et.length>0||Ve.length>0||re.length>0,Xe=(k,se)=>{p(_e=>({..._e,nodes:_e.nodes.map(Be=>Be.id===k?{...Be,...se}:Be)}))},Ue=(k,se)=>{g.nodes.some(_e=>_e.entityType===k&&_e.entityId===se)||p(_e=>({..._e,nodes:[..._e.nodes,Qo(k,{entityId:se,dependencyMode:_e.nodes.length===0?"start":"after_previous"})]}))},le=k=>{p(se=>{const _e=se.nodes.filter(Be=>Be.id!==k);return{...se,nodes:_e.map((Be,Ge)=>({...Be,dependencyMode:Ge===0&&Be.dependencyMode==="after_previous"?"start":Be.dependencyMode,customPredecessorIds:Be.customPredecessorIds.filter(gt=>gt!==k)}))}})},Me=ld(od(cd,{activationConstraint:{distance:6}})),He=k=>{!k.over||k.active.id===k.over.id||p(se=>{const _e=se.nodes.findIndex(Ge=>Ge.id===k.active.id),Be=se.nodes.findIndex(Ge=>{var gt;return Ge.id===((gt=k.over)==null?void 0:gt.id)});return _e<0||Be<0?se:{...se,nodes:Vu(se.nodes,_e,Be)}})},lt=()=>{const k=T.trim(),se=g.targetProjectIds.map(Ge=>_.get(Ge)).find(Ge=>!!Ge)??_.get(v.projectId)??r[0]??null,_e=(se==null?void 0:se.goalId)??g.targetGoalIds[0]??"",Be=r.find(Ge=>Ge.goalId===_e&&(se?Ge.id===se.id:!0))??r.find(Ge=>Ge.goalId===_e)??se;H(Ge=>({...cr(m,r),title:k||Ge.title,description:Ge.description,goalId:_e,projectId:(Be==null?void 0:Be.id)??Ge.projectId,userId:(Be==null?void 0:Be.userId)??Ge.userId??m})),X(null),R(!0)},Nt=async()=>{const k=_.get(v.projectId);if(!v.title.trim()){X("Task title is required.");return}if(!k){X("Pick a project for the new task.");return}z(!0),X(null);try{const se=G.get(v.userId??k.userId??"")??k.user??ke??ae,_e=(await im({title:v.title.trim(),description:v.description.trim(),level:"task",owner:(se==null?void 0:se.displayName)??"Albert",userId:v.userId??k.userId??g.userId,assigneeUserIds:[],goalId:k.goalId,projectId:k.id,parentWorkItemId:null,priority:v.priority,status:"focus",effort:v.effort,energy:v.energy,dueDate:"",points:v.points,plannedDurationSeconds:86400,aiInstructions:"",executionMode:null,acceptanceCriteria:[],blockerLinks:[],completionReport:null,gitRefs:[],tagIds:[],notes:[]})).task;P(Be=>[_e,...Be]),Ue("task",_e.id),H({...cr(m,r),goalId:k.goalId,projectId:k.id,userId:_e.userId??k.userId??g.userId}),w(""),R(!1)}catch(se){X(se instanceof Error?se.message:"Task creation failed.")}finally{z(!1)}},me=async()=>{if(L){y(L);return}try{await x({title:g.title.trim(),overview:g.overview.trim(),endStateDescription:g.endStateDescription.trim(),status:g.status,userId:g.userId,targetGoalIds:g.targetGoalIds,targetProjectIds:g.targetProjectIds,linkedEntities:g.linkedEntities,graph:Se},a==null?void 0:a.id),y(null),u(!1)}catch(k){y(k instanceof Error?k.message:"Strategy save failed.")}},Pe=[{id:"foundation",eyebrow:"Foundation",title:"Set the owner and the strategic frame",description:"Start with who owns the strategy, what the plan is called, and whether this should open as active, paused, or already landed.",render:(k,se)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(16rem,0.8fr)]",children:[e.jsx(de,{label:"Strategy title",children:e.jsx(ye,{value:k.title,onChange:_e=>se({title:_e.target.value}),placeholder:"Land the multi-user planning system"})}),e.jsx(de,{label:"Status",children:e.jsx(wt,{value:k.status,onChange:_e=>se({status:_e}),options:[{value:"active",label:"Active",description:"Use this when the plan should drive work now."},{value:"paused",label:"Paused",description:"Keep the strategy visible without active pressure."},{value:"completed",label:"Completed",description:"The end state is already landed."}]})})]}),e.jsx(Zs,{value:k.userId,users:d,onChange:_e=>se({userId:_e}),label:"Owner user",defaultLabel:Ys(ae),help:"Strategies can belong to a human or a bot even when the sequence spans multiple owners."}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(135deg,rgba(192,193,255,0.16),rgba(125,211,252,0.08))] px-5 py-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Live posture"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"strategy",label:k.title.trim()||"Untitled strategy",compact:!0,gradient:!1}),e.jsx(I,{className:"bg-white/[0.12] text-white/86",children:k.status}),ke?e.jsx(ot,{user:ke,compact:!0}):null]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"This flow is built to keep strategy creation as guided as the other major entities in Forge: clear questions first, then a focused sequence stage at the end."})]})]})},{id:"objective",eyebrow:"Objective",title:"Define the objective and the end targets",description:"Capture what this strategy is coordinating, what done looks like, and which goals or projects are the real targets.",render:(k,se)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(de,{label:"Overview",children:e.jsx(Ze,{value:k.overview,onChange:_e=>se({overview:_e.target.value}),placeholder:"Explain what this strategy is coordinating and why it matters right now."})}),e.jsx(de,{label:"End state",children:e.jsx(Ze,{value:k.endStateDescription,onChange:_e=>se({endStateDescription:_e.target.value}),placeholder:"Describe what reality should look like when this strategy lands."})})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,28,44,0.9),rgba(12,17,30,0.88))] px-5 py-5",children:[e.jsx(de,{label:"Search goals or projects",description:"Keep this page search-first. Add only the targets that truly define what this strategy is trying to land.",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(_t,{className:"size-4 text-white/42"}),e.jsx(ye,{className:"border-none bg-transparent px-0 py-0",value:f,onChange:_e=>b(_e.target.value),placeholder:"Search goals, projects, owners, humans, or bots"})]})}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected goals"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:F.length===0?e.jsx(I,{className:"bg-white/[0.08] text-white/62",children:"No target goals yet"}):F.map(_e=>e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white transition hover:bg-[rgba(192,193,255,0.2)]",onClick:()=>se({targetGoalIds:kr(k.targetGoalIds,_e.id)}),children:[e.jsx(We,{kind:"goal",label:_e.title,compact:!0,gradient:!1}),e.jsx("span",{children:"Remove"})]},_e.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected projects"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:he.length===0?e.jsx(I,{className:"bg-white/[0.08] text-white/62",children:"No target projects yet"}):he.map(_e=>e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white transition hover:bg-[rgba(192,193,255,0.2)]",onClick:()=>se({targetProjectIds:kr(k.targetProjectIds,_e.id)}),children:[e.jsx(We,{kind:"project",label:_e.title,compact:!0,gradient:!1}),e.jsx("span",{children:"Remove"})]},_e.id))})]})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-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:"Goal matches"}),K?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Ie.length," found"]}):null]}),e.jsx("div",{className:"mt-3 grid gap-3",children:K?De.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No goals match this search yet."}):De.map(_e=>{const Be=k.targetGoalIds.includes(_e.id);return e.jsxs("button",{type:"button",className:te("rounded-[22px] border px-4 py-4 text-left transition",Be?"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]"),onClick:()=>se({targetGoalIds:kr(k.targetGoalIds,_e.id)}),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx(yt,{kind:"goal",label:_e.title,className:"max-w-full min-w-0"}),e.jsx(ot,{user:_e.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:_e.description||"No strategic note attached yet."})]},_e.id)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search for the goal this strategy is meant to land."})})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-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:"Project matches"}),K?e.jsxs(I,{className:"bg-white/[0.08] text-white/72",children:[Ne.length," found"]}):null]}),e.jsx("div",{className:"mt-3 grid gap-3",children:K?ee.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No projects match this search yet."}):ee.map(_e=>{const Be=k.targetProjectIds.includes(_e.id);return e.jsxs("button",{type:"button",className:te("rounded-[22px] border px-4 py-4 text-left transition",Be?"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]"),onClick:()=>se({targetProjectIds:kr(k.targetProjectIds,_e.id)}),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx(yt,{kind:"project",label:_e.title,className:"max-w-full min-w-0",showIcon:!1}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:_e.goalTitle}),e.jsx(ot,{user:_e.user,compact:!0})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:_e.description||"No project summary attached yet."})]},_e.id)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search for the concrete project this strategy should land or organize."})})]})]})]})},{id:"context",eyebrow:"Context",title:"Keep the right supporting entities in view",description:"Linked entities stay visible in the strategy context without becoming part of the main execution sequence.",render:(k,se)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Search supporting context",description:"Search across goals, projects, tasks, habits, and other strategies.",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(_t,{className:"size-4 text-white/42"}),e.jsx(ye,{className:"border-none bg-transparent px-0 py-0",value:A,onChange:_e=>C(_e.target.value),placeholder:"Search by title, owner, @handle, human, or bot"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.linkedEntities.length===0?e.jsx(I,{className:"bg-white/[0.08] text-white/62",children:"No extra linked context yet"}):k.linkedEntities.map(_e=>{const Be=V.find(Ge=>Ge.entityType===_e.entityType&&Ge.entityId===_e.entityId);return e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white/82 transition hover:bg-[rgba(192,193,255,0.22)]",onClick:()=>se({linkedEntities:k.linkedEntities.filter(Ge=>!(Ge.entityType===_e.entityType&&Ge.entityId===_e.entityId))}),children:[e.jsx($s,{className:"mr-1 size-3.5"}),(Be==null?void 0:Be.label)??`${_e.entityType}:${_e.entityId}`,e.jsx("span",{children:"Remove"})]},`${_e.entityType}:${_e.entityId}`)})}),e.jsx("div",{className:"grid gap-3",children:$?ze.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No supporting entities match this search yet."}):ze.map(_e=>{const Be=k.linkedEntities.some(Ge=>Ge.entityType===_e.entityType&&Ge.entityId===_e.entityId);return e.jsxs("label",{className:te("flex items-start justify-between gap-3 rounded-[20px] border px-4 py-4",Be?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)]":"border-white/8 bg-white/[0.04]"),children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:_e.entityType,label:_e.label,compact:!0,gradient:!1}),_e.user?e.jsx(ot,{user:_e.user,compact:!0}):null]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:_e.description})]}),e.jsx("input",{type:"checkbox",checked:Be,onChange:()=>se({linkedEntities:tx(k.linkedEntities,{entityType:_e.entityType,entityId:_e.entityId})})})]},_e.key)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search when you want to pull another entity into the background context. This keeps the page focused instead of dumping every record into one long list."})})]})},{id:"sequence",eyebrow:"Sequence",title:"Build the execution sequence",description:"Search, add steps, and create missing tasks.",render:()=>e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,28,44,0.9),rgba(12,17,30,0.88))] px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Search and add"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Search goals, projects, tasks, humans, and bots."})]}),e.jsxs(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[g.nodes.length," planned steps"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(_t,{className:"size-4 text-white/42"}),e.jsx(ye,{className:"border-none bg-transparent px-0 py-0",value:T,onChange:k=>w(k.target.value),placeholder:"Search goals, projects, tasks, owners, humans, or bots"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs(W,{type:"button",className:"w-full justify-start",variant:"secondary",onClick:lt,children:[e.jsx(ds,{className:"size-4"}),"Create new task"]}),j?e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"New task"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Add the task and place it in the sequence."})]}),e.jsx(W,{type:"button",variant:"secondary",className:"w-full sm:w-auto",onClick:()=>{R(!1),X(null)},children:"Close"})]}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(de,{label:"Task title",children:e.jsx(ye,{value:v.title,onChange:k=>H(se=>({...se,title:k.target.value})),placeholder:"Draft the shared strategy hierarchy view"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(de,{label:"Goal",children:e.jsxs("select",{value:v.goalId,onChange:k=>{const se=k.target.value,_e=r.find(Be=>Be.goalId===se)??null;H(Be=>({...Be,goalId:se,projectId:(_e==null?void 0:_e.id)??"",userId:(_e==null?void 0:_e.userId)??Be.userId??m}))},className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"",children:"Select goal"}),i.map(k=>e.jsx("option",{value:k.id,children:k.title},k.id))]})}),e.jsx(de,{label:"Project",children:e.jsxs("select",{value:v.projectId,onChange:k=>H(se=>{var _e,Be;return{...se,projectId:k.target.value,goalId:((_e=_.get(k.target.value))==null?void 0:_e.goalId)??se.goalId,userId:((Be=_.get(k.target.value))==null?void 0:Be.userId)??se.userId}}),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"",children:"Select project"}),je.map(k=>e.jsx("option",{value:k.id,children:k.title},k.id))]})})]}),e.jsx(de,{label:"Notes",children:e.jsx(Ze,{value:v.description,onChange:k=>H(se=>({...se,description:k.target.value})),placeholder:"Optional detail or acceptance note."})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(de,{label:"Priority",children:e.jsxs("select",{value:v.priority,onChange:k=>H(se=>({...se,priority:k.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"critical",children:"Critical"})]})}),e.jsx(de,{label:"Points",children:e.jsx(ye,{type:"number",value:v.points,onChange:k=>H(se=>({...se,points:Number(k.target.value)||0}))})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(de,{label:"Effort",children:e.jsxs("select",{value:v.effort,onChange:k=>H(se=>({...se,effort:k.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"light",children:"Light"}),e.jsx("option",{value:"deep",children:"Deep"}),e.jsx("option",{value:"extended",children:"Extended"})]})}),e.jsx(de,{label:"Energy",children:e.jsxs("select",{value:v.energy,onChange:k=>H(se=>({...se,energy:k.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"calm",children:"Calm"}),e.jsx("option",{value:"steady",children:"Steady"}),e.jsx("option",{value:"intense",children:"Intense"})]})})]}),Q?e.jsx("div",{className:"rounded-[18px] border border-rose-400/20 bg-rose-500/[0.08] px-4 py-3 text-sm text-rose-100/90",children:Q}):null,e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx(W,{type:"button",variant:"secondary",className:"w-full sm:w-auto",onClick:()=>{R(!1),X(null)},children:"Cancel"}),e.jsxs(W,{type:"button",className:"w-full sm:w-auto",pending:Y,pendingLabel:"Creating task",onClick:()=>void Nt(),children:[e.jsx(ds,{className:"size-4"}),"Create task"]})]})]})]}):null,pe?$e?e.jsxs("div",{className:"grid gap-3",children:[et.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Goals"}):null,et.map(k=>{const se=g.targetGoalIds.includes(k.id),_e=g.linkedEntities.some(Be=>Be.entityType==="goal"&&Be.entityId===k.id);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"goal",label:k.title,compact:!0,gradient:!1}),e.jsx(ot,{user:k.user,compact:!0})]}),k.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",onClick:()=>p(Be=>({...Be,targetGoalIds:kr(Be.targetGoalIds,k.id)})),children:se?"Targeted":"Add target"}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:"secondary",onClick:()=>p(Be=>({...Be,linkedEntities:tx(Be.linkedEntities,{entityType:"goal",entityId:k.id})})),children:_e?"Unlink":"Link"})]})]})},k.id)}),Ve.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Projects"}):null,Ve.map(k=>{const se=st.has(`project:${k.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"project",label:k.title,compact:!0,gradient:!1}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:k.goalTitle}),e.jsx(ot,{user:k.user,compact:!0})]}),k.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description}):null]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",disabled:se,onClick:()=>Ue("project",k.id),children:se?"In sequence":"Add step"})]})},`sequence-project:${k.id}`)}),re.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Tasks"}):null,re.map(k=>{const se=st.has(`task:${k.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"task",label:k.title,compact:!0,gradient:!1}),e.jsx(I,{className:"bg-white/[0.08] text-white/72",children:k.status}),e.jsx(ot,{user:k.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description||`${k.owner} · ${k.projectId}`})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",disabled:se,onClick:()=>Ue("task",k.id),children:se?"In sequence":"Add step"})]})},`sequence-task:${k.id}`)})]}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No goals, projects, or tasks match this search."}):ne.length>0||be.length>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Suggested from targets"}),ne.map(k=>{const se=st.has(`project:${k.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"project",label:k.title,compact:!0,gradient:!1}),e.jsx(ot,{user:k.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description||k.goalTitle})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",disabled:se,onClick:()=>Ue("project",k.id),children:se?"In sequence":"Add step"})]})},`suggested-project:${k.id}`)}),be.map(k=>{const se=st.has(`task:${k.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(We,{kind:"task",label:k.title,compact:!0,gradient:!1}),e.jsx(ot,{user:k.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:k.description||`${k.owner} · ${k.status}`})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:se?"secondary":"primary",disabled:se,onClick:()=>Ue("task",k.id),children:se?"In sequence":"Add step"})]})},`suggested-task:${k.id}`)})]}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Type to search."})]})]}),e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sequence"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Keep the flow mostly linear here. When a step should open beside the previous one, switch it to parallel. Use custom only for special joins."})]}),e.jsxs(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[g.nodes.length," planned steps"]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[g.targetGoalIds.map(k=>{const se=q.get(k);return se?e.jsx(We,{kind:"goal",label:se.title,compact:!0,gradient:!1},k):null}),g.targetProjectIds.map(k=>{const se=_.get(k);return se?e.jsx(We,{kind:"project",label:se.title,compact:!0,gradient:!1},k):null})]})]}),e.jsx(dd,{sensors:Me,collisionDetection:Qu,onDragEnd:He,children:e.jsx(Xn,{items:g.nodes.map(k=>k.id),strategy:Yn,children:e.jsx("div",{className:"grid gap-3",children:g.nodes.map((k,se)=>e.jsx(xT,{node:k,index:se,total:g.nodes.length,projectsById:_,tasksById:B,usersById:G,allNodes:g.nodes,onUpdate:Xe,onRemove:le},k.id))})})})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Contract readiness"}),e.jsx("div",{className:"mt-3 grid gap-2",children:Ce.map(k=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[14px] bg-white/[0.03] px-3 py-2",children:[e.jsx("div",{className:"text-sm text-white/62",children:k.label}),e.jsx(I,{className:k.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:k.satisfied?"Ready":"Missing"})]},k.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Alignment preview"}),e.jsx("div",{className:"mt-3 grid gap-3",children:oe.map(k=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm text-white/60",children:[e.jsx("span",{children:k.label}),e.jsxs("span",{children:[k.value,"%"]})]}),e.jsx(xa,{value:k.value,className:"mt-2"})]},k.id))})]})]})]})}];return e.jsx(Lt,{open:t,onOpenChange:u,eyebrow:"Strategy",title:a?"Edit strategy":"Create strategy",description:"Strategies connect goals, projects, and tasks into a guided multi-step plan with a focused sequence builder at the end.",value:g,onChange:p,draftPersistenceKey:a?`strategy.${a.id}`:"strategy.new",steps:Pe,initialStepId:h,contentClassName:"lg:h-[min(56rem,calc(100vh-1rem))] lg:w-[min(78rem,calc(100vw-1.5rem))]",submitLabel:a?qe?"Save strategy":"Save draft":qe?"Create strategy":"Create draft",pending:s,pendingLabel:"Saving strategy",resolveError:U,onSubmit:me})}function gT(t){return t.trim().toLowerCase()}function fT(){const t=jt(),s=$t(),a=ct(),[i,r]=ms(),[n,l]=c.useState(!1),[o,d]=c.useState(null),[m,h]=c.useState(""),u=ys(t.selectedUserIds);c.useEffect(()=>{i.get("create")==="1"&&(d(null),l(!0),r(T=>{const w=new URLSearchParams(T);return w.delete("create"),w},{replace:!0}))},[i,r]);const x=async()=>{await a.invalidateQueries({queryKey:["strategy-detail"]}),await t.refresh()},g=Re({mutationFn:async({input:T,strategyId:w})=>w?(await Qc(w,T)).strategy:(await U1(T)).strategy,onSuccess:async()=>{await x()}}),p=Re({mutationFn:async T=>gf(T),onSuccess:async()=>{await x()}}),f=c.useMemo(()=>new Map(t.snapshot.goals.map(T=>[T.id,T])),[t.snapshot.goals]),b=c.useMemo(()=>new Map(t.snapshot.dashboard.projects.map(T=>[T.id,T])),[t.snapshot.dashboard.projects]),A=c.useMemo(()=>new Map(t.snapshot.tasks.map(T=>[T.id,T])),[t.snapshot.tasks]),C=c.useMemo(()=>{const T=gT(m);return T?t.snapshot.strategies.filter(w=>{var P,v,H;const S=w.targetGoalIds.map(j=>{var R;return((R=f.get(j))==null?void 0:R.title)??""}).join(" "),y=w.targetProjectIds.map(j=>{var R;return((R=b.get(j))==null?void 0:R.title)??""}).join(" "),N=w.graph.nodes.map(j=>{var R,Q;return j.entityType==="project"?((R=b.get(j.entityId))==null?void 0:R.title)??"":((Q=A.get(j.entityId))==null?void 0:Q.title)??""}).join(" ");return[w.title,w.overview,w.endStateDescription,w.status,((P=w.user)==null?void 0:P.displayName)??"",((v=w.user)==null?void 0:v.handle)??"",((H=w.user)==null?void 0:H.kind)??"",S,y,N].join(" ").toLowerCase().includes(T)}):t.snapshot.strategies},[f,b,m,t.snapshot.strategies,A]);return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:"Strategies",titleText:"Strategies",description:"Strategies connect human and bot work into a directed plan, with explicit end goals, ownership, and live alignment metrics.",badge:`${t.snapshot.strategies.length} strategies`,actions:e.jsxs(W,{onClick:()=>{d(null),l(!0)},children:[e.jsx(ds,{className:"size-4"}),"New strategy"]})}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:m,onChange:T=>h(T.target.value),placeholder:"Search strategy title, target, graph node, human, or bot"})]}),e.jsx("div",{className:"text-sm text-white/56",children:"Search includes owners, target goals/projects, and graph nodes so cross-user plans stay discoverable."})]}),C.length===0?e.jsx(Bt,{eyebrow:"Strategies",title:"No strategies in this scope",description:"Create a strategy to connect projects and tasks into a non-looping execution plan across human and bot actors.",action:e.jsx(W,{onClick:()=>{d(null),l(!0)},children:"Create strategy"})}):e.jsx("div",{className:"grid gap-4",children:C.map(T=>{const w=T.graph.nodes.filter(y=>T.metrics.activeNodeIds.includes(y.id)),S=Wm(T.metrics);return e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("button",{type:"button",className:"text-left",onClick:()=>s(`/strategies/${T.id}`),children:[e.jsx("div",{className:"font-display text-2xl text-white",children:T.title}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:T.overview||T.endStateDescription})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ot,{user:T.user}),e.jsx(I,{className:T.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:T.isLocked?"Contract locked":"Editable draft"}),e.jsx(I,{className:"bg-white/[0.08] text-white/78",children:T.status}),e.jsxs(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[T.metrics.alignmentScore,"% aligned"]})]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Graph progress"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[T.metrics.startedNodeCount,"/",T.metrics.totalNodeCount]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[T.metrics.completedNodeCount," completed"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Ready branches"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:T.metrics.readyNodeCount}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Nodes whose prerequisites are already satisfied."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"End targets"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[T.metrics.completedTargetCount,"/",T.metrics.totalTargetCount||0]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[T.metrics.targetProgressScore,"% target progress"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Sequencing"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[T.metrics.sequencingScore,"%"]})]})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(16rem,0.8fr)]",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Active next nodes"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:w.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No currently open branch."}):w.map(y=>e.jsx(I,{className:"bg-white/[0.08] text-white/80",children:y.title},y.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Alignment breakdown"}),e.jsx("div",{className:"mt-3 grid gap-2 text-sm text-white/58",children:S.map(y=>e.jsxs("div",{children:[y.label," ",y.value,"%"]},y.id))})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-end justify-end gap-2",children:[T.isLocked?null:e.jsxs(W,{variant:"secondary",onClick:()=>{d(T),l(!0)},children:[e.jsx(pi,{className:"size-4"}),"Edit"]}),e.jsxs(W,{variant:"secondary",pending:p.isPending&&p.variables===T.id,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${T.title}"?`)&&p.mutateAsync(T.id)},children:[e.jsx(Rt,{className:"size-4"}),"Delete"]}),e.jsx(W,{onClick:()=>s(`/strategies/${T.id}`),children:"Open strategy"})]})]})]},T.id)})}),e.jsx(Qw,{open:n,pending:g.isPending,editingStrategy:o,goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,habits:t.snapshot.habits,strategies:t.snapshot.strategies,users:t.snapshot.users,defaultUserId:u,onOpenChange:l,onSubmit:async(T,w)=>{await g.mutateAsync({input:T,strategyId:w})}})]})}function Vw(t){const s=new Map;for(const r of t.nodes)s.set(r.id,[]);for(const r of t.edges)s.set(r.to,[...s.get(r.to)??[],r.from]);const a=new Map,i=r=>{const n=a.get(r);if(n!==void 0)return n;const l=s.get(r)??[],o=l.length===0?0:Math.max(...l.map(d=>i(d)))+1;return a.set(r,o),o};for(const r of t.nodes)i(r.id);return a}function bT(t){const s=Vw(t),a=new Map;for(const i of t.nodes){const r=s.get(i.id)??0;a.set(r,[...a.get(r)??[],i.id])}return Array.from(a.entries()).sort((i,r)=>i[0]-r[0]).map(([i,r])=>({level:i,nodeIds:r}))}function wT(t,s){const a=Vw(t.graph),i=new Map;for(const r of t.graph.nodes){const n=a.get(r.id)??0;i.set(n,[...i.get(n)??[],r.id])}return t.graph.nodes.map(r=>{const n=a.get(r.id)??0,l=(i.get(n)??[]).indexOf(r.id),o=t.metrics.activeNodeIds.includes(r.id),d=t.metrics.blockedNodeIds.includes(r.id),m=t.metrics.outOfOrderNodeIds.includes(r.id),h=!o&&!d&&!m,u=(s==null?void 0:s.get(r.id))??null;let x="border-white/10 bg-[rgba(8,14,26,0.92)]";return o?x="border-emerald-400/30 bg-emerald-500/[0.08]":d?x="border-rose-400/28 bg-rose-500/[0.08]":m?x="border-amber-400/28 bg-amber-500/[0.08]":t.metrics.completedNodeCount>0&&(x="border-sky-400/20 bg-sky-500/[0.05]"),{id:r.id,position:{x:72+n*308,y:56+l*168},draggable:!1,selectable:!1,data:{label:e.jsxs("div",{className:`min-w-[220px] rounded-[22px] border px-4 py-4 shadow-[0_24px_70px_rgba(0,0,0,0.24)] ${x}`,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:r.entityType}),o?e.jsx(I,{className:"bg-emerald-500/12 text-emerald-200",children:"Active"}):null,d?e.jsx(I,{className:"bg-rose-500/12 text-rose-200",children:"Blocked"}):null,m?e.jsx(I,{className:"bg-amber-500/12 text-amber-200",children:"Out of order"}):null,h&&!d&&!m?e.jsx(I,{className:"bg-sky-500/12 text-sky-200",children:"In plan"}):null]}),e.jsx("div",{className:"mt-3 text-base font-medium leading-6 text-white",children:r.title}),r.branchLabel?e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/45",children:r.branchLabel}):null,r.notes?e.jsx("div",{className:"mt-2 text-sm leading-5 text-white/56",children:r.notes}):null,u?e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-xs text-white/52",children:[e.jsx("span",{className:"inline-block size-2.5 rounded-full",style:{backgroundColor:u.color}}),e.jsx("span",{children:u.label})]}):null]})},style:{background:"transparent",border:"none",padding:0}}})}function yT(t){return t.graph.edges.map(s=>{const a=t.metrics.activeNodeIds.includes(s.to),i=t.metrics.blockedNodeIds.includes(s.to),r=t.metrics.outOfOrderNodeIds.includes(s.to);let n="rgba(255,255,255,0.3)";return a?n="#4ade80":i?n="#fb7185":r&&(n="#f59e0b"),{id:`${s.from}->${s.to}`,source:s.from,target:s.to,label:s.label||void 0,animated:a,markerEnd:{type:Uu.ArrowClosed,color:n},style:{stroke:n,strokeWidth:a?2.4:1.5},labelStyle:{fill:"rgba(255,255,255,0.56)",fontSize:11,fontWeight:600}}})}function vT({strategy:t,ownerByNodeId:s,heightClassName:a="h-[540px]"}){const i=c.useMemo(()=>wT(t,s),[s,t]),r=c.useMemo(()=>yT(t),[t]);return e.jsx("div",{className:`${a} rounded-[24px] bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.08),transparent_32%),radial-gradient(circle_at_bottom_right,rgba(244,185,122,0.10),transparent_38%),linear-gradient(180deg,rgba(6,10,20,0.97),rgba(8,14,26,0.94))]`,children:e.jsxs(id,{fitView:!0,nodes:i,edges:r,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,attributionPosition:"bottom-left",children:[e.jsx(Bu,{showInteractive:!1}),e.jsx(rd,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})}function jT(t,s){const a=t.metrics.activeNodeIds.includes(s),i=t.metrics.blockedNodeIds.includes(s),r=t.metrics.outOfOrderNodeIds.includes(s);return i?{label:"Blocked",className:"bg-rose-500/12 text-rose-200"}:r?{label:"Out of order",className:"bg-amber-500/12 text-amber-200"}:a?{label:"Ready now",className:"bg-emerald-500/12 text-emerald-200"}:{label:"In plan",className:"bg-sky-500/12 text-sky-200"}}function NT({strategy:t,projectsById:s,tasksById:a,className:i}){const r=c.useMemo(()=>bT(t.graph),[t.graph]),n=c.useMemo(()=>{const d=new Map;for(const m of t.graph.nodes)d.set(m.id,[]);for(const m of t.graph.edges)d.set(m.to,[...d.get(m.to)??[],m.from]);return d},[t.graph]),[l,o]=c.useState([]);return e.jsxs("div",{className:i??"grid gap-3",children:[r.map(d=>{const m=l.includes(d.level),h=d.level===0?"Launch phase":`Phase ${d.level+1}`,u=d.nodeIds.length>1;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 px-4 py-4",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-3 text-left",onClick:()=>o(x=>m?x.filter(g=>g!==d.level):[...x,d.level]),children:[e.jsx("span",{className:"rounded-full bg-white/[0.06] p-2 text-white/72",children:m?e.jsx(Hu,{className:"size-4"}):e.jsx(Sa,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:h}),e.jsx("div",{className:"mt-1 text-sm text-white/60",children:u?"These branches can progress in parallel once the previous phase is complete.":"This phase advances as one focused step in the strategy."})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(I,{className:"bg-white/[0.08] text-white/76",children:[d.nodeIds.length," node",d.nodeIds.length===1?"":"s"]}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:u?e.jsxs(e.Fragment,{children:[e.jsx(Gv,{className:"mr-1 size-3.5"}),"Parallel"]}):e.jsxs(e.Fragment,{children:[e.jsx(Sg,{className:"mr-1 size-3.5"}),"Sequential"]})})]})]}),m?null:e.jsx("div",{className:"grid gap-3 border-t border-white/8 px-4 py-4 lg:grid-cols-2",children:d.nodeIds.map(x=>{var T,w,S;const g=t.graph.nodes.find(y=>y.id===x);if(!g)return null;const p=g.entityType==="project"?s.get(g.entityId):a.get(g.entityId),f=g.entityType==="project"?`/projects/${g.entityId}`:`/tasks/${g.entityId}`,b=g.entityType==="project"?(T=s.get(g.entityId))==null?void 0:T.user:(w=a.get(g.entityId))==null?void 0:w.user,A=((S=n.get(g.id))==null?void 0:S.map(y=>{var N;return((N=t.graph.nodes.find(P=>P.id===y))==null?void 0:N.title)??y}))??[],C=jT(t,g.id);return e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-[rgba(8,14,26,0.76)] 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:"flex flex-wrap gap-2",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:g.entityType}),e.jsx(I,{className:C.className,children:C.label})]}),e.jsx(Je,{to:f,className:"mt-3 block text-lg font-medium text-white transition hover:text-[var(--primary)]",children:g.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:g.notes||("description"in(p??{})?p==null?void 0:p.description:"")||"No extra step note attached yet."})]}),e.jsx(ot,{user:b,compact:!0})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[g.branchLabel?e.jsx(I,{className:"bg-[rgba(192,193,255,0.12)] text-white/82",children:g.branchLabel}):null,A.length===0?e.jsx(I,{className:"bg-emerald-500/10 text-emerald-200",children:"Start node"}):A.map(y=>e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:["Depends on ",y]},`${g.id}:${y}`))]})]},g.id)})})]},d.level)}),r.length===0?e.jsx("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm text-white/56",children:"No phases mapped yet."}):null]})}function kT(){var P;const t=jt(),{strategyId:s}=Qs(),a=$t(),i=ct(),[r,n]=c.useState(!1),[l,o]=c.useState(),d=ys(t.selectedUserIds),m=t.snapshot.strategies.find(v=>v.id===s)??null,h=Fe({queryKey:["strategy-detail",s],queryFn:async()=>(await W1(s)).strategy,enabled:!!(s&&!m)}),u=m??h.data??null,x=async()=>{await Promise.all([i.invalidateQueries({queryKey:["strategy-detail",s]}),t.refresh()])},g=Re({mutationFn:async({input:v,currentStrategyId:H})=>(await Qc(H,v)).strategy,onSuccess:x}),p=Re({mutationFn:async v=>gf(v),onSuccess:async()=>{await x(),a("/strategies")}}),f=Re({mutationFn:async v=>(await Qc(s,{isLocked:v,lockedByUserId:v?d??(u==null?void 0:u.userId)??"user_operator":null})).strategy,onSuccess:x}),b=c.useMemo(()=>new Map(t.snapshot.goals.map(v=>[v.id,v])),[t.snapshot.goals]),A=c.useMemo(()=>new Map(t.snapshot.dashboard.projects.map(v=>[v.id,v])),[t.snapshot.dashboard.projects]),C=c.useMemo(()=>new Map(t.snapshot.tasks.map(v=>[v.id,v])),[t.snapshot.tasks]),T=c.useMemo(()=>u?new Map(u.graph.nodes.map(v=>{var j,R;const H=v.entityType==="project"?(j=A.get(v.entityId))==null?void 0:j.user:(R=C.get(v.entityId))==null?void 0:R.user;return[v.id,H?{label:`${H.displayName} (${H.kind})`,color:H.accentColor}:null]})):new Map,[A,u,C]),w=u??{title:"",overview:"",endStateDescription:"",targetGoalIds:[],targetProjectIds:[],graph:{nodes:[],edges:[]}},S=c.useMemo(()=>Um(w),[w]),y=c.useMemo(()=>Hw(w),[w]),N=c.useMemo(()=>Wm((u==null?void 0:u.metrics)??{planCoverageScore:0,sequencingScore:0,scopeDisciplineScore:0,qualityScore:0,targetProgressScore:0,startedNodeCount:0,totalNodeCount:1,offPlanEntityCount:0,offPlanActiveEntityCount:0,blockedNodeIds:[],outOfOrderNodeIds:[]}),[u==null?void 0:u.metrics]);return h.isLoading&&!u?e.jsx(Et,{eyebrow:"Strategy",title:"Loading strategy",description:"Resolving the directed plan, targets, and current alignment."}):h.isError?e.jsx(it,{eyebrow:"Strategy",error:h.error,onRetry:()=>void h.refetch()}):u?e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:u.title,titleText:u.title,description:u.overview||u.endStateDescription,badge:`${u.metrics.alignmentScore}% aligned`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Nd,{userId:d,domain:"strategies",entityType:"strategy",entityId:u.id,label:u.title,description:u.overview||u.endStateDescription}),e.jsx(er,{entityType:"strategy",entityId:u.id}),u.isLocked?null:e.jsx(W,{variant:"secondary",onClick:()=>{o(void 0),n(!0)},children:"Edit strategy"}),e.jsx(W,{variant:"secondary",disabled:!u.isLocked&&!y,pending:f.isPending,pendingLabel:u.isLocked?"Unlocking contract":"Locking contract",onClick:()=>{f.mutateAsync(!u.isLocked)},children:u.isLocked?"Unlock contract":"Lock as contract"}),e.jsx(W,{variant:"secondary",pending:p.isPending,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${u.title}"?`)&&p.mutateAsync(u.id)},children:"Delete"})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ot,{user:u.user}),e.jsx(I,{className:u.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:u.isLocked?"Contract locked":"Editable draft"}),e.jsx(I,{className:"bg-white/[0.08] text-white/76",children:u.status}),e.jsxs(I,{className:"bg-white/[0.08] text-white/76",children:[u.graph.nodes.length," nodes"]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/76",children:[u.graph.edges.length," edges"]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.15fr)_minmax(18rem,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End state"}),e.jsx("div",{className:"text-sm leading-7 text-white/64",children:u.endStateDescription||"No end-state description yet."})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Directed execution graph"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"The graph is the contract surface for this strategy. It shows which branches are available now, where work is blocked, and whether any node is moving out of sequence."})]}),u.isLocked?null:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",onClick:()=>{o("sequence"),n(!0)},children:"Refine sequence"}),e.jsx(W,{onClick:()=>{o("sequence"),n(!0)},children:"Add parallel work"})]})]}),e.jsx(vT,{strategy:u,ownerByNodeId:T}),e.jsx(NT,{strategy:u,projectsById:A,tasksById:C})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Contract state"}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:u.isLocked?"This strategy is currently locked as a contract. The graph, targets, and descriptive plan stay frozen until you explicitly unlock it.":"This strategy is still a draft. Agents and users can keep refining the plan until you lock it."}),u.isLocked?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs("span",{children:["Locked by"," ",((P=u.lockedByUser)==null?void 0:P.displayName)??"Unknown user"]}),u.lockedAt?e.jsxs("span",{children:["· ",new Date(u.lockedAt).toLocaleString()]}):null]}):null,u.isLocked?null:e.jsx("div",{className:"mt-4 grid gap-2",children:S.map(v=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[14px] bg-white/[0.03] px-3 py-2",children:[e.jsx("div",{className:"text-sm text-white/64",children:v.label}),e.jsx(I,{className:v.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:v.satisfied?"Ready":"Missing"})]},v.id))})]}),!u.isLocked&&!y?e.jsx("div",{className:"rounded-[18px] border border-amber-400/18 bg-amber-500/[0.08] px-4 py-3 text-sm leading-6 text-amber-100/86",children:"Add a target goal or project plus an overview or end state before locking this draft as the execution contract."}):null,u.isLocked?null:e.jsx("div",{className:"mt-4 text-xs leading-5 text-white/46",children:"Drafts may stay incomplete while humans and agents negotiate the plan. Only the lock action requires the contract checks to pass."})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Alignment metrics"}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/56",children:"Alignment score"}),e.jsxs("div",{className:"mt-2 font-display text-3xl text-[var(--primary)]",children:[u.metrics.alignmentScore,"%"]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/48",children:[u.metrics.startedNodeCount,"/",u.metrics.totalNodeCount," planned nodes started,"," ",u.metrics.completedNodeCount," completed,"," ",u.metrics.readyNodeCount," ready now."]})]}),N.map(v=>e.jsxs("div",{className:"rounded-[18px] 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:"text-sm text-white/56",children:v.label}),e.jsxs("div",{className:"text-sm font-medium text-white",children:[v.value,"%"]})]}),e.jsx(xa,{value:v.value,className:"mt-3"}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/48",children:v.detail})]},v.id))]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End targets"}),u.targetGoalIds.map(v=>{const H=b.get(v);return H?e.jsx(Je,{to:`/goals/${H.id}`,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{children:["Goal: ",H.title]}),e.jsx(ot,{user:H.user,compact:!0})]})},H.id):null}),u.targetProjectIds.map(v=>{const H=A.get(v);return H?e.jsx(Je,{to:`/projects/${H.id}`,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{children:["Project: ",H.title]}),e.jsx(ot,{user:H.user,compact:!0})]})},H.id):null}),u.targetGoalIds.length===0&&u.targetProjectIds.length===0?e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:"No end targets linked yet."}):null]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked entities"}),u.linkedEntities.length===0?e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:"No additional linked entities."}):u.linkedEntities.map(v=>{var R,Q,X,Y,z,K,$;const H=ci(v.entityType,v.entityId),j=v.entityType==="goal"?(R=b.get(v.entityId))==null?void 0:R.title:v.entityType==="project"?(Q=A.get(v.entityId))==null?void 0:Q.title:v.entityType==="task"?(X=C.get(v.entityId))==null?void 0:X.title:`${v.entityType}:${v.entityId}`;return H?e.jsx(Je,{to:H,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:j}),e.jsx(ot,{user:v.entityType==="goal"?(Y=b.get(v.entityId))==null?void 0:Y.user:v.entityType==="project"?(z=A.get(v.entityId))==null?void 0:z.user:v.entityType==="task"?(K=C.get(v.entityId))==null?void 0:K.user:v.entityType==="strategy"?($=t.snapshot.strategies.find(D=>D.id===v.entityId))==null?void 0:$.user:null,compact:!0})]})},`${v.entityType}:${v.entityId}`):e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:j},`${v.entityType}:${v.entityId}`)})]})]})]}),e.jsx(Qw,{open:r,pending:g.isPending,editingStrategy:u,goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,habits:t.snapshot.habits,strategies:t.snapshot.strategies,users:t.snapshot.users,defaultUserId:d,initialStepId:l,onOpenChange:v=>{n(v),v||o(void 0)},onSubmit:async v=>{await g.mutateAsync({input:v,currentStrategyId:u.id})}})]}):e.jsx(it,{eyebrow:"Strategy",error:new Error("Strategy not found."),onRetry:()=>a("/strategies")})}const Xw=[{id:"overview",label:"Overview",icon:Lu},{id:"map",label:"Map",icon:fg},{id:"table",label:"Table",icon:Qv},{id:"history",label:"History",icon:Ag},{id:"contexts",label:"Contexts",icon:Ki},{id:"concepts",label:"Concepts",icon:Wt}],ST=new Set(["projects","tasks","strategies","habits"]),Jl=[{value:"projects",label:"Projects",description:"Goals and projects already living in Forge.",mode:"forge"},{value:"tasks",label:"Tasks",description:"Execution-level work choices inside Forge.",mode:"forge"},{value:"strategies",label:"Strategies",description:"Plan shapes and sequencing choices in Forge.",mode:"forge"},{value:"habits",label:"Habits",description:"Recurring behaviors and routines from Forge.",mode:"forge"},{value:"activities",label:"Activities",description:"Movement, leisure, and social setting concepts.",mode:"concept"},{value:"food",label:"Food",description:"Cuisine, meal mood, and drink preferences.",mode:"concept"},{value:"places",label:"Places",description:"Living environments, venues, and trip shapes.",mode:"concept"},{value:"countries",label:"Countries",description:"Country-level attraction and lifestyle fit.",mode:"concept"},{value:"fashion",label:"Fashion",description:"Silhouette, material, and palette preferences.",mode:"concept"},{value:"people",label:"People",description:"Presence, body-type, and conversation preferences.",mode:"concept"},{value:"media",label:"Media",description:"Film, reading, and music taste.",mode:"concept"},{value:"tools",label:"Tools",description:"Workflow and capture preferences.",mode:"concept"},{value:"custom",label:"Custom",description:"General-purpose concept libraries you control.",mode:"concept"}],ju={novelty:"Novelty",simplicity:"Simplicity",rigor:"Rigor",aesthetics:"Aesthetics",depth:"Depth",structure:"Structure",familiarity:"Familiarity",surprise:"Surprise"},Zl={novelty:0,simplicity:0,rigor:0,aesthetics:0,depth:0,structure:0,familiarity:0,surprise:0},nx={liked:"bg-emerald-500/12 text-emerald-200",disliked:"bg-rose-500/12 text-rose-200",uncertain:"bg-white/[0.08] text-white/70",vetoed:"bg-rose-500/15 text-rose-100",bookmarked:"bg-sky-500/12 text-sky-200",favorite:"bg-amber-500/12 text-amber-200",must_have:"bg-indigo-500/15 text-indigo-100",neutral:"bg-white/[0.08] text-white/70"},IT=[{signalType:"favorite",label:"Favorite"},{signalType:"must_have",label:"Must-have"},{signalType:"bookmark",label:"Bookmark"},{signalType:"compare_later",label:"Later"},{signalType:"neutral",label:"Neutral"},{signalType:"veto",label:"Veto"}];function eo(t){return t.trim().toLowerCase()}function Ar(t){return`${Math.round(t*100)}%`}function CT(t){return[...t.goals.map(s=>({entityType:"goal",entityId:s.id,domain:"projects",label:s.title,description:s.description,user:s.user,href:`/goals/${s.id}`,searchText:dt([s.title,s.description,s.status,s.horizon],s)})),...t.dashboard.projects.map(s=>({entityType:"project",entityId:s.id,domain:"projects",label:s.title,description:s.description,user:s.user,href:`/projects/${s.id}`,searchText:dt([s.title,s.description,s.status,s.goalTitle],s)})),...t.tasks.map(s=>({entityType:"task",entityId:s.id,domain:"tasks",label:s.title,description:s.description,user:s.user,href:`/tasks/${s.id}`,searchText:dt([s.title,s.description,s.status,s.priority,s.owner],s)})),...t.strategies.map(s=>({entityType:"strategy",entityId:s.id,domain:"strategies",label:s.title,description:s.overview||s.endStateDescription,user:s.user,href:`/strategies/${s.id}`,searchText:dt([s.title,s.overview,s.endStateDescription,s.status],s)})),...t.habits.map(s=>({entityType:"habit",entityId:s.id,domain:"habits",label:s.title,description:s.description,user:s.user,href:null,searchText:dt([s.title,s.description,s.status,s.frequency],s)}))]}function TT(t,s){return!t||!s?null:t==="goal"?`/goals/${s}`:t==="project"?`/projects/${s}`:t==="task"?`/tasks/${s}`:t==="strategy"?`/strategies/${s}`:null}function to(t){return t.manualStatus??t.status}function PT(t){return t&&Xw.some(s=>s.id===t)?t:"overview"}function AT(t){return t.summary.totalItems<2?{title:"Forge does not know enough yet.",description:"Start the game so Forge can ask a few clean comparisons and build a real preference model."}:t.summary.averageConfidence<.28?{title:"Forge has a rough sketch, not a stable read.",description:"There is some signal, but the model still needs more rounds before its preferences are trustworthy."}:{title:"This is what Forge currently thinks.",description:"The summary below is the current best model for this user, this domain, and the active context."}}function MT({summary:t}){const s=Math.max(-1,Math.min(1,t.leaning)),a=(s+1)/2*100;return e.jsxs("div",{className:"grid gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-white/56",children:[e.jsx("span",{children:ju[t.dimensionId]}),e.jsxs("span",{children:[t.movement>.08?"Rising":t.movement<-.08?"Falling":"Stable"," ","· ",Ar(t.confidence)]})]}),e.jsxs("div",{className:"relative h-2 rounded-full bg-white/[0.08]",children:[e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/10"}),e.jsx("div",{className:te("absolute top-1/2 size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border border-white/12",s>=0?"bg-emerald-300":"bg-rose-300"),style:{left:`${a}%`}})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.12em] text-white/38",children:[e.jsxs("span",{children:[s>=0?"Leans toward":"Leans away from"," ",ju[t.dimensionId].toLowerCase()]}),e.jsxs("span",{children:["Context ",Ar(t.contextSensitivity)]})]})]})}function lx({title:t,description:s,sideLabel:a,onClick:i}){return e.jsxs("button",{type:"button",className:"grid min-h-[220px] gap-4 rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.07),rgba(255,255,255,0.03))] p-5 text-left transition hover:border-[var(--primary)]/40 hover:bg-[linear-gradient(180deg,rgba(192,193,255,0.14),rgba(255,255,255,0.05))]",onClick:i,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:a}),e.jsx("div",{className:"font-display text-3xl text-white",children:t}),e.jsx("div",{className:"max-w-[36ch] text-sm leading-6 text-white/56",children:s||"Choose the one that feels more right."}),e.jsx("div",{className:"mt-auto text-sm text-[var(--primary)]",children:"Click this card"})]})}function ET(){var He,lt,Nt,me,Pe;const t=jt(),s=ct(),[a,i]=ms(),[r,n]=c.useState(""),[l,o]=c.useState(""),[d,m]=c.useState(""),[h,u]=c.useState(""),[x,g]=c.useState(""),[p,f]=c.useState({open:!1,phase:"domain",domain:a.get("domain")??"projects"}),[b,A]=c.useState(null),[C,T]=c.useState(!1),[w,S]=c.useState(null),[y,N]=c.useState({label:"",description:"",tags:"",manualStatus:"",manualScore:"",confidenceLock:"",bookmarked:!1,compareLater:!1,frozen:!1,featureWeights:{novelty:"0",simplicity:"0",rigor:"0",aesthetics:"0",depth:"0",structure:"0",familiarity:"0",surprise:"0"}}),[P,v]=c.useState({label:"",description:"",tags:""}),[H,j]=c.useState({name:"",description:"",shareMode:"blended",decayDays:"90"}),[R,Q]=c.useState({title:"",description:""}),[X,Y]=c.useState({}),[z,K]=c.useState(null),[$,D]=c.useState({title:"",description:""}),[J,q]=c.useState(null),[_,B]=c.useState({label:"",description:"",tags:""}),G=a.get("userId")??ys(t.selectedUserIds)??((He=t.snapshot.users[0])==null?void 0:He.id)??null,ae=a.get("domain")??"projects",ke=PT(a.get("tab")),Ae=a.get("contextId"),ie=a.get("focusItem"),Ie=c.useMemo(()=>t.snapshot.users.find(k=>k.id===G)??null,[G,t.snapshot.users]),Ne=c.useMemo(()=>CT(t.snapshot),[t.snapshot]),M=Fe({queryKey:["forge-preferences",G,ae,Ae],queryFn:async()=>(await ch({userId:G??void 0,domain:ae,contextId:Ae??void 0})).workspace,enabled:!!G}),E=Fe({queryKey:["forge-preferences-game",G,p.domain,Ae],queryFn:async()=>(await ch({userId:G??void 0,domain:p.domain,contextId:Ae??void 0})).workspace,enabled:!!G&&p.open}),O=M.data??null,xe=p.domain===ae?O:E.data??null;c.useEffect(()=>{var se;if(!O)return;const k=ie&&O.scores.some(_e=>_e.itemId===ie)?ie:((se=O.scores[0])==null?void 0:se.itemId)??null;S(_e=>_e&&O.scores.some(Be=>Be.itemId===_e)?_e:k)},[ie,O]);const V=c.useMemo(()=>{if(!O)return[];const k=eo(r);return k?O.scores.filter(se=>{var _e,Be,Ge;return[((_e=se.item)==null?void 0:_e.label)??"",((Be=se.item)==null?void 0:Be.description)??"",((Ge=se.item)==null?void 0:Ge.tags.join(" "))??"",se.status,se.manualStatus??"",se.dominantDimensions.join(" "),se.explanation.join(" ")].join(" ").toLowerCase().includes(k)}):O.scores},[r,O]),Se=V.find(k=>k.itemId===w)??(O==null?void 0:O.scores.find(k=>k.itemId===w))??V[0]??(O==null?void 0:O.scores[0])??null;c.useEffect(()=>{var k,se,_e,Be,Ge,gt,Mt,Vt,Os,qa,Ba;Se&&N({label:((k=Se.item)==null?void 0:k.label)??"",description:((se=Se.item)==null?void 0:se.description)??"",tags:((_e=Se.item)==null?void 0:_e.tags.join(", "))??"",manualStatus:Se.manualStatus??"",manualScore:typeof Se.manualScore=="number"?String(Se.manualScore):"",confidenceLock:typeof Se.confidenceLock=="number"?String(Se.confidenceLock):"",bookmarked:Se.bookmarked,compareLater:Se.compareLater,frozen:Se.frozen,featureWeights:{novelty:String(((Be=Se.item)==null?void 0:Be.featureWeights.novelty)??0),simplicity:String(((Ge=Se.item)==null?void 0:Ge.featureWeights.simplicity)??0),rigor:String(((gt=Se.item)==null?void 0:gt.featureWeights.rigor)??0),aesthetics:String(((Mt=Se.item)==null?void 0:Mt.featureWeights.aesthetics)??0),depth:String(((Vt=Se.item)==null?void 0:Vt.featureWeights.depth)??0),structure:String(((Os=Se.item)==null?void 0:Os.featureWeights.structure)??0),familiarity:String(((qa=Se.item)==null?void 0:qa.featureWeights.familiarity)??0),surprise:String(((Ba=Se.item)==null?void 0:Ba.featureWeights.surprise)??0)}})},[Se]);const Ee=c.useMemo(()=>{const k=eo(l);return Ne.filter(se=>se.domain===ae).filter(se=>k?se.searchText.includes(k):!0).slice(0,12)},[Ne,l,ae]),Ce=c.useMemo(()=>{const k=ke==="concepts"?O:xe??O,se=(k==null?void 0:k.catalogs)??[],_e=eo(d);return _e?se.filter(Be=>[Be.title,Be.description,Be.source,...Be.items.flatMap(Ge=>[Ge.label,Ge.description,Ge.tags.join(" ")])].join(" ").toLowerCase().includes(_e)):se},[xe,d,ke,O]),qe=async()=>{await s.invalidateQueries({queryKey:["forge-preferences"]}),await s.invalidateQueries({queryKey:["forge-preferences-game"]})},oe=Re({mutationFn:Hc,onSuccess:qe}),L=Re({mutationFn:Cj,onSuccess:async({item:k})=>{await qe(),v({label:"",description:"",tags:""}),S(k.id)}}),U=Re({mutationFn:bj,onSuccess:async()=>{await qe(),Q({title:"",description:""}),i(k=>{const se=new URLSearchParams(k);return se.set("tab","concepts"),se})}}),ge=Re({mutationFn:({catalogId:k,patch:se})=>wj(k,se),onSuccess:async()=>{await qe(),K(null)}}),Te=Re({mutationFn:yj,onSuccess:qe}),ve=Re({mutationFn:vj,onSuccess:async()=>{await qe()}}),Le=Re({mutationFn:({catalogItemId:k,patch:se})=>jj(k,se),onSuccess:async()=>{await qe(),q(null)}}),Qe=Re({mutationFn:Nj,onSuccess:qe}),st=Re({mutationFn:fj,onSuccess:async()=>{await qe(),f(k=>({...k,phase:"play"}))}}),F=Re({mutationFn:Pj,onSuccess:qe}),he=Re({mutationFn:Aj,onSuccess:qe}),we=Re({mutationFn:async()=>{!(Se!=null&&Se.item)||!G||!O||(await Tj(Se.item.id,{label:y.label,description:y.description,tags:y.tags.split(",").map(k=>k.trim()).filter(Boolean),featureWeights:Object.fromEntries(Object.keys(Zl).map(k=>[k,Number(y.featureWeights[k]||0)]))}),await Mj(Se.item.id,{userId:G,domain:ae,contextId:O.selectedContext.id,manualStatus:y.manualStatus||null,manualScore:y.manualScore.trim().length>0?Number(y.manualScore):null,confidenceLock:y.confidenceLock.trim().length>0?Number(y.confidenceLock):null,bookmarked:y.bookmarked,compareLater:y.compareLater,frozen:y.frozen}))},onSuccess:qe}),Z=Re({mutationFn:kj,onSuccess:async({context:k})=>{await qe(),j({name:"",description:"",shareMode:"blended",decayDays:"90"}),i(se=>{const _e=new URLSearchParams(se);return _e.set("contextId",k.id),_e.set("tab","contexts"),_e})}}),De=Re({mutationFn:Ij,onSuccess:async()=>{await qe(),u(""),g("")}}),ee=Re({mutationFn:({contextId:k,patch:se})=>Sj(k,se),onSuccess:qe}),ze=k=>{i(se=>{const _e=new URLSearchParams(se);for(const[Be,Ge]of Object.entries(k))Ge?_e.set(Be,Ge):_e.delete(Be);return _e})},et=(k=ae)=>{A(null),f({open:!0,phase:"domain",domain:k})},Ve=async k=>{if(!G)return;A(null),T(!0);const se=Ne.filter(Ge=>{var gt;return Ge.domain===k&&((gt=Ge.user)==null?void 0:gt.id)===G}),_e=Ne.filter(Ge=>Ge.domain===k),Be=(se.length>0?se:_e).slice(0,12);if(Be.length<2){A("Forge needs at least two matching records in this domain before it can start the game."),T(!1),f(Ge=>({...Ge,phase:"domain"}));return}try{ze({domain:k,tab:"overview",contextId:null,focusItem:null}),await Promise.all(Be.map(Ge=>Hc({userId:G,domain:k,entityType:Ge.entityType,entityId:Ge.entityId,label:Ge.label,description:Ge.description,tags:[]}))),await qe(),f({open:!0,phase:"play",domain:k})}catch(Ge){A(Ge instanceof Error?Ge.message:"Forge could not start the game."),f(gt=>({...gt,phase:"domain"}))}finally{T(!1)}},re=async(k,se)=>{if(G){A(null),ze({domain:k,tab:"overview",contextId:null,focusItem:null});try{await st.mutateAsync({userId:G,domain:k,contextId:Ae??void 0,catalogId:se}),f({open:!0,phase:"play",domain:k})}catch(_e){A(_e instanceof Error?_e.message:"Forge could not start the game.")}}},ne=async k=>{if(ST.has(k)){await Ve(k);return}A(null),f({open:!0,phase:"catalog",domain:k})},be=async(k,se=1)=>{if(!G||!(xe!=null&&xe.compare.nextPair))return;const _e=xe.compare.nextPair;await F.mutateAsync({userId:G,domain:p.domain,contextId:xe.selectedContext.id,leftItemId:_e.left.id,rightItemId:_e.right.id,outcome:k,strength:se})},je=async(k,se)=>{!G||!xe||await he.mutateAsync({userId:G,domain:p.domain,contextId:xe.selectedContext.id,itemId:k,signalType:se,strength:1})};if(!G)return e.jsx(Bt,{eyebrow:"Preferences",title:"No Forge user available",description:"Forge needs at least one human or bot user before it can learn preferences."});if(M.isLoading&&!O)return e.jsx(Et,{eyebrow:"Preferences",title:"Loading preference model",description:"Reconstructing current scores, uncertainty, and concept libraries."});if(M.isError)return e.jsx(it,{eyebrow:"Preferences",error:M.error,onRetry:()=>void M.refetch()});if(!O)return null;const pe=[...O.dimensions].sort((k,se)=>se.confidence-k.confidence).slice(0,6),$e=O.scores.filter(k=>to(k)==="liked"||to(k)==="favorite").slice(0,4),Xe=O.scores.filter(k=>k.uncertainty>=.5).slice(0,4),Ue=AT(O),le=TT(((lt=Se==null?void 0:Se.item)==null?void 0:lt.sourceEntityType)??null,((Nt=Se==null?void 0:Se.item)==null?void 0:Nt.sourceEntityId)??null),Me=(xe==null?void 0:xe.compare.nextPair)??null;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{title:"Preferences",titleText:"Preferences",description:"Forge keeps an explicit, editable model of what one user prefers in one domain. The first job of this page is to show what Forge currently knows.",badge:`${O.summary.totalItems} items · ${Ar(O.summary.averageConfidence)} confidence`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{className:"min-w-[10rem]",onClick:()=>et(),children:"Start the game"}),e.jsx(W,{variant:"secondary",onClick:()=>void qe(),children:"Refresh model"})]})}),e.jsx(ks,{}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Active user"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("select",{value:G,onChange:k=>ze({userId:k.target.value,contextId:null,focusItem:null}),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:t.snapshot.users.map(k=>e.jsxs("option",{value:k.id,children:[k.displayName," · ",k.kind]},k.id))}),e.jsx(ot,{user:Ie}),e.jsx("div",{className:"text-sm text-white/54",children:os(Ie)})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Domain"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Jl.map(k=>e.jsx("button",{type:"button",className:te("rounded-full border px-3 py-2 text-sm transition",k.value===ae?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"),onClick:()=>ze({domain:k.value,contextId:null,focusItem:null}),children:k.label},k.value))}),e.jsx("div",{className:"text-sm text-white/48",children:(me=Jl.find(k=>k.value===ae))==null?void 0:me.description})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/50",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:O.selectedContext.name}),e.jsx("span",{children:O.selectedContext.shareMode}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[O.compare.pendingCount," queued comparisons"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[O.libraries.totalCatalogItems," concept items ready"]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Xw.map(k=>e.jsxs("button",{type:"button",className:te("inline-flex items-center gap-2 rounded-full border px-3 py-2 text-sm transition",k.id===ke?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"),onClick:()=>ze({tab:k.id}),children:[e.jsx(k.icon,{className:"size-4"}),k.label]},k.id))}),ke==="overview"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_360px]",children:[e.jsxs(ce,{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"What Forge knows"}),e.jsx("div",{className:"font-display text-3xl text-white",children:Ue.title}),e.jsx("div",{className:"max-w-[70ch] text-sm leading-6 text-white/58",children:Ue.description})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[{label:"Known items",value:O.summary.totalItems,detail:"Items inside this domain"},{label:"Confidence",value:Ar(O.summary.averageConfidence),detail:"Average certainty"},{label:"Unknowns",value:O.summary.uncertainCount,detail:"Need more rounds"},{label:"Libraries",value:O.libraries.totalCatalogItems,detail:"Seeded concepts ready"}].map(k=>e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:k.label}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:k.value}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:k.detail})]},k.label))}),e.jsx("div",{className:"grid gap-4 lg:grid-cols-2",children:pe.map(k=>e.jsx(MT,{summary:k},k.dimensionId))})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Next move"}),e.jsx("div",{className:"font-display text-2xl text-white",children:"Start the game"}),e.jsx("div",{className:"text-sm leading-6 text-white/58",children:"Forge will ask a small number of pairwise questions. You choose a domain, Forge supplies the candidates, and the model tightens from there."}),e.jsx(W,{className:"w-full",onClick:()=>et(),children:"Start the game"}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:[e.jsxs("div",{children:["Current queue: ",O.compare.pendingCount," comparison",O.compare.pendingCount===1?"":"s"]}),e.jsxs("div",{children:["Active context: ",O.selectedContext.name]}),e.jsxs("div",{children:["Library coverage: ",O.libraries.seededCatalogCount," ","seeded lists and ",O.libraries.customCatalogCount," ","custom lists"]})]})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_360px]",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Preference map"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Green drifts positive, red drifts negative, and low opacity still means uncertainty."})]}),e.jsx(Je,{to:"?tab=map",className:"text-sm text-[var(--primary)]",children:"Open full map"})]}),e.jsxs("div",{className:"relative min-h-[340px] overflow-hidden rounded-[24px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(87,196,138,0.18),transparent_35%),radial-gradient(circle_at_bottom_right,rgba(255,104,130,0.14),transparent_30%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0.01))]",children:[e.jsx("div",{className:"absolute inset-x-0 top-1/2 h-px bg-white/8"}),e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/8"}),O.map.map(k=>e.jsx("button",{type:"button",className:te("absolute -translate-x-1/2 -translate-y-1/2 rounded-full border px-2 py-1 text-[11px] shadow-[0_10px_25px_rgba(5,8,16,0.32)] transition hover:scale-[1.04]",k.itemId===(Se==null?void 0:Se.itemId)?"border-white/30 bg-white/16 text-white":k.score>=0?"border-emerald-300/30 bg-emerald-500/14 text-emerald-100":"border-rose-300/30 bg-rose-500/14 text-rose-100"),style:{left:`${50+k.x*30}%`,top:`${50-k.y*30}%`,opacity:.55+k.confidence*.45},onClick:()=>S(k.itemId),children:k.label},k.itemId))]})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Best read so far"}),e.jsx("div",{className:"grid gap-2",children:$e.length>0?$e.map(k=>{var se;return e.jsxs("button",{type:"button",className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>{S(k.itemId),ze({focusItem:k.itemId})},children:[e.jsx("div",{className:"font-medium text-white",children:((se=k.item)==null?void 0:se.label)??k.itemId}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:k.explanation[0]||"Forge has positive evidence here."})]},k.itemId)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:"No clear positives yet. A few comparison rounds will change that."})}),e.jsxs("div",{className:"border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Biggest unknowns"}),e.jsx("div",{className:"mt-3 grid gap-2",children:Xe.length>0?Xe.map(k=>{var se;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:[e.jsx("div",{className:"font-medium text-white",children:((se=k.item)==null?void 0:se.label)??k.itemId}),e.jsxs("div",{className:"mt-1",children:["Uncertainty ",Ar(k.uncertainty)]})]},k.itemId)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:"The current unknown list is short."})})]})]})]}),e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Bring in Forge records"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Search goals, projects, tasks, strategies, or habits across human and bot users, then send them straight into this model."})]}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[Ee.length," visible"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:l,onChange:k=>o(k.target.value),placeholder:"Search across owners, handles, user kind, title, and description"})]}),e.jsx("div",{className:"grid gap-2",children:Ee.map(k=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium text-white",children:k.label}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:k.entityType}),k.user?e.jsx(ot,{user:k.user,compact:!0}):null]}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:k.description||"No description yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[k.href?e.jsx(Je,{to:k.href,children:e.jsx(W,{variant:"ghost",size:"sm",children:"Open"})}):null,e.jsx(W,{variant:"secondary",size:"sm",pending:oe.isPending,pendingLabel:"Adding",onClick:()=>void oe.mutateAsync({userId:G,domain:ae,entityType:k.entityType,entityId:k.entityId,label:k.label,description:k.description,tags:[]}),children:"Add to model"})]})]},`${k.entityType}-${k.entityId}`))})]})]}):null,ke==="map"?e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Full map"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Click a point to inspect why Forge believes it belongs there."})]}),e.jsxs("div",{className:"text-sm text-white/52",children:[O.map.length," plotted items"]})]}),e.jsxs("div",{className:"relative min-h-[520px] overflow-hidden rounded-[24px] border border-white/8 bg-[radial-gradient(circle_at_20%_20%,rgba(87,196,138,0.2),transparent_25%),radial-gradient(circle_at_80%_80%,rgba(255,104,130,0.2),transparent_26%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0.01))]",children:[e.jsx("div",{className:"absolute inset-x-0 top-1/2 h-px bg-white/8"}),e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/8"}),O.map.map(k=>e.jsx("button",{type:"button",className:te("absolute -translate-x-1/2 -translate-y-1/2 rounded-full border px-3 py-1 text-xs transition hover:scale-[1.04]",k.itemId===(Se==null?void 0:Se.itemId)?"border-white/30 bg-white/16 text-white":k.score>=0?"border-emerald-300/30 bg-emerald-500/14 text-emerald-100":"border-rose-300/30 bg-rose-500/14 text-rose-100"),style:{left:`${50+k.x*34}%`,top:`${50-k.y*34}%`,opacity:.45+k.confidence*.55},onClick:()=>{S(k.itemId),ze({focusItem:k.itemId})},children:k.label},k.itemId))]})]}):null,ke==="table"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_380px]",children:[e.jsxs(ce,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:r,onChange:k=>n(k.target.value),placeholder:"Search learned items, explanations, tags, or dominant dimensions"})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full text-left text-sm",children:[e.jsx("thead",{className:"text-[11px] uppercase tracking-[0.14em] text-white/38",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"Item"}),e.jsx("th",{className:"px-3 py-2",children:"Score"}),e.jsx("th",{className:"px-3 py-2",children:"Confidence"}),e.jsx("th",{className:"px-3 py-2",children:"Status"}),e.jsx("th",{className:"px-3 py-2",children:"Evidence"})]})}),e.jsx("tbody",{children:V.map(k=>{var se,_e;return e.jsxs("tr",{className:te("cursor-pointer border-t border-white/6 transition hover:bg-white/[0.04]",k.itemId===(Se==null?void 0:Se.itemId)?"bg-white/[0.05]":""),onClick:()=>{S(k.itemId),ze({focusItem:k.itemId})},children:[e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"font-medium text-white",children:((se=k.item)==null?void 0:se.label)??k.itemId}),e.jsx("div",{className:"text-xs text-white/48",children:(((_e=k.item)==null?void 0:_e.tags)??[]).join(" · ")})]}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:k.latentScore.toFixed(2)}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:Ar(k.confidence)}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(I,{className:nx[to(k)],children:to(k)})}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:k.evidenceCount})]},k.itemId)})})]})})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Item editor"}),Se!=null&&Se.item?e.jsxs(e.Fragment,{children:[e.jsx(ye,{value:y.label,onChange:k=>N(se=>({...se,label:k.target.value})),placeholder:"Item label"}),e.jsx(Ze,{value:y.description,onChange:k=>N(se=>({...se,description:k.target.value})),className:"min-h-24",placeholder:"Item description"}),e.jsx(ye,{value:y.tags,onChange:k=>N(se=>({...se,tags:k.target.value})),placeholder:"comma, separated, tags"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("select",{value:y.manualStatus,onChange:k=>N(se=>({...se,manualStatus:k.target.value})),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Inferred status"}),Object.keys(nx).map(k=>e.jsx("option",{value:k,children:k},k))]}),e.jsx(ye,{value:y.manualScore,onChange:k=>N(se=>({...se,manualScore:k.target.value})),placeholder:"Manual score"}),e.jsx(ye,{value:y.confidenceLock,onChange:k=>N(se=>({...se,confidenceLock:k.target.value})),placeholder:"Confidence lock 0-1"})]}),e.jsx("div",{className:"grid gap-2",children:Object.keys(Zl).map(k=>e.jsxs("div",{className:"grid grid-cols-[110px_minmax(0,1fr)] items-center gap-3",children:[e.jsx("div",{className:"text-sm text-white/56",children:ju[k]}),e.jsx(ye,{value:y.featureWeights[k],onChange:se=>N(_e=>({..._e,featureWeights:{..._e.featureWeights,[k]:se.target.value}}))})]},k))}),e.jsx("div",{className:"grid gap-2 text-sm text-white/58",children:[["bookmarked","Bookmarked"],["compareLater","Compare later"],["frozen","Frozen"]].map(([k,se])=>e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:y[k],onChange:_e=>N(Be=>({...Be,[k]:_e.target.checked}))}),e.jsx("span",{children:se})]},k))}),e.jsx(W,{pending:we.isPending,pendingLabel:"Saving item",onClick:()=>void we.mutateAsync(),children:"Save item model"}),le?e.jsx(Je,{className:"text-sm text-[var(--primary)]",to:le,children:"Open linked entity"}):null]}):e.jsx("div",{className:"text-sm text-white/52",children:"Select a row to inspect or edit it."}),e.jsxs("div",{className:"mt-3 border-t border-white/8 pt-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Add custom item"}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsx(ye,{value:P.label,onChange:k=>v(se=>({...se,label:k.target.value})),placeholder:"Custom item label"}),e.jsx(Ze,{value:P.description,onChange:k=>v(se=>({...se,description:k.target.value})),className:"min-h-24",placeholder:"What is this preference item?"}),e.jsx(ye,{value:P.tags,onChange:k=>v(se=>({...se,tags:k.target.value})),placeholder:"comma, separated, tags"}),e.jsx(W,{disabled:!P.label.trim(),pending:L.isPending,pendingLabel:"Creating item",onClick:()=>void L.mutateAsync({userId:G,domain:ae,label:P.label,description:P.description,tags:P.tags.split(",").map(k=>k.trim()).filter(Boolean),featureWeights:Zl,queueForCompare:!0}),children:"Create custom item"})]})]})]})]}):null,ke==="history"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-3",children:[e.jsxs(ce,{className:"grid gap-3 xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Recent pairwise judgments"}),e.jsx("div",{className:"grid gap-2",children:O.history.judgments.slice(0,12).map(k=>{var Be,Ge,gt,Mt;const se=((Ge=(Be=O.scores.find(Vt=>Vt.itemId===k.leftItemId))==null?void 0:Be.item)==null?void 0:Ge.label)??k.leftItemId,_e=((Mt=(gt=O.scores.find(Vt=>Vt.itemId===k.rightItemId))==null?void 0:gt.item)==null?void 0:Mt.label)??k.rightItemId;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/58",children:[e.jsxs("div",{className:"font-medium text-white",children:[se," vs ",_e]}),e.jsxs("div",{className:"mt-1",children:["Outcome ",k.outcome," · strength"," ",k.strength," ·"," ",new Date(k.createdAt).toLocaleString()]})]},k.id)})})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Signals and snapshots"}),e.jsx("div",{className:"grid gap-2",children:O.history.signals.slice(0,8).map(k=>{var _e,Be;const se=((Be=(_e=O.scores.find(Ge=>Ge.itemId===k.itemId))==null?void 0:_e.item)==null?void 0:Be.label)??k.itemId;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-2 text-sm text-white/58",children:[se," · ",k.signalType," ·"," ",new Date(k.createdAt).toLocaleString()]},k.id)})}),e.jsx("div",{className:"grid gap-2",children:O.history.snapshots.slice(0,5).map(k=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-2 text-sm text-white/58",children:["Snapshot ",new Date(k.createdAt).toLocaleString()]},k.id))}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:["Stale items: ",O.history.staleItemIds.length," · Flipped items: ",O.history.flippedItemIds.length]})]})]}):null,ke==="contexts"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_360px]",children:[e.jsx("div",{className:"grid gap-4",children:O.contexts.map(k=>e.jsxs(ce,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-2xl text-white",children:k.name}),e.jsx("div",{className:"text-sm text-white/54",children:k.description||"No description yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[k.isDefault?e.jsx(I,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Default"}):null,e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:k.shareMode}),k.active?null:e.jsx(I,{className:"bg-amber-500/12 text-amber-200",children:"Inactive"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[e.jsx(ye,{value:k.name,onChange:se=>void ee.mutateAsync({contextId:k.id,patch:{name:se.target.value}}),placeholder:"Context name"}),e.jsxs("select",{value:k.shareMode,onChange:se=>void ee.mutateAsync({contextId:k.id,patch:{shareMode:se.target.value}}),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"shared",children:"shared"}),e.jsx("option",{value:"blended",children:"blended"}),e.jsx("option",{value:"isolated",children:"isolated"})]}),e.jsx(ye,{value:String(k.decayDays),onChange:se=>void ee.mutateAsync({contextId:k.id,patch:{decayDays:Number(se.target.value||90)}}),placeholder:"Decay days"}),e.jsx(W,{variant:"secondary",onClick:()=>ze({contextId:k.id,tab:"overview"}),children:"Open context"})]}),e.jsx(Ze,{value:k.description,onChange:se=>void ee.mutateAsync({contextId:k.id,patch:{description:se.target.value}}),className:"min-h-20"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",onClick:()=>void ee.mutateAsync({contextId:k.id,patch:{active:!k.active}}),children:k.active?"Deactivate":"Activate"}),k.isDefault?null:e.jsx(W,{variant:"secondary",onClick:()=>void ee.mutateAsync({contextId:k.id,patch:{isDefault:!0}}),children:"Make default"})]})]},k.id))}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Create context"}),e.jsx(ye,{value:H.name,onChange:k=>j(se=>({...se,name:k.target.value})),placeholder:"Context name"}),e.jsx(Ze,{value:H.description,onChange:k=>j(se=>({...se,description:k.target.value})),className:"min-h-24",placeholder:"What changes in this context?"}),e.jsxs("select",{value:H.shareMode,onChange:k=>j(se=>({...se,shareMode:k.target.value})),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"blended",children:"blended"}),e.jsx("option",{value:"shared",children:"shared"}),e.jsx("option",{value:"isolated",children:"isolated"})]}),e.jsx(ye,{value:H.decayDays,onChange:k=>j(se=>({...se,decayDays:k.target.value})),placeholder:"Decay days"}),e.jsx(W,{disabled:!H.name.trim(),pending:Z.isPending,pendingLabel:"Creating context",onClick:()=>void Z.mutateAsync({userId:G,domain:ae,name:H.name,description:H.description,shareMode:H.shareMode,decayDays:Number(H.decayDays||90),active:!0,isDefault:!1}),children:"Create context"})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Merge contexts"}),e.jsxs("select",{value:h,onChange:k=>u(k.target.value),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Source context"}),O.contexts.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id))]}),e.jsxs("select",{value:x,onChange:k=>g(k.target.value),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Target context"}),O.contexts.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id))]}),e.jsx(W,{pending:De.isPending,pendingLabel:"Merging",disabled:!h||!x||h===x,onClick:()=>void De.mutateAsync({sourceContextId:h,targetContextId:x}),children:"Merge into target"})]})]})]}):null,ke==="concepts"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_380px]",children:[e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Concept libraries"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"These are the lists Forge can use when you start the game in a concept domain. Seeded lists are editable, and custom lists are fully yours."})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-4",children:[["Lists",O.libraries.totalCatalogs],["Concepts",O.libraries.totalCatalogItems],["Seeded",O.libraries.seededCatalogCount],["Custom",O.libraries.customCatalogCount]].map(([k,se])=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:k}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:se})]},k))}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:d,onChange:k=>m(k.target.value),placeholder:"Search lists, concepts, tags, and seeded domains"})]})]}),e.jsxs(ce,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Create concept list"}),e.jsx(ye,{value:R.title,onChange:k=>Q(se=>({...se,title:k.target.value})),placeholder:"List title"}),e.jsx(Ze,{value:R.description,onChange:k=>Q(se=>({...se,description:k.target.value})),className:"min-h-24",placeholder:"What should this list help compare?"}),e.jsx(W,{disabled:!R.title.trim(),pending:U.isPending,pendingLabel:"Creating list",onClick:()=>void U.mutateAsync({userId:G,domain:ae,title:R.title,description:R.description}),children:"Create list"})]})]}),e.jsx("div",{className:"grid gap-4",children:Ce.map(k=>{const se=X[k.id]??{label:"",description:"",tags:""},_e=k.items.filter(Be=>d.trim()?[Be.label,Be.description,Be.tags.join(" ")].join(" ").toLowerCase().includes(eo(d)):!0);return e.jsxs(ce,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:z===k.id?e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ye,{value:$.title,onChange:Be=>D(Ge=>({...Ge,title:Be.target.value}))}),e.jsx(Ze,{value:$.description,onChange:Be=>D(Ge=>({...Ge,description:Be.target.value})),className:"min-h-24"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"font-display text-2xl text-white",children:k.title}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:k.source}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[k.items.length," items"]})]}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:k.description||"No description yet."})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>void re(ae,k.id),children:"Start from this list"}),z===k.id?e.jsxs(e.Fragment,{children:[e.jsx(W,{size:"sm",pending:ge.isPending,pendingLabel:"Saving",onClick:()=>void ge.mutateAsync({catalogId:k.id,patch:{title:$.title,description:$.description}}),children:"Save"}),e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>K(null),children:"Cancel"})]}):e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>{K(k.id),D({title:k.title,description:k.description})},children:"Edit list"}),e.jsx(W,{variant:"ghost",size:"sm",pending:Te.isPending,pendingLabel:"Deleting",onClick:()=>void Te.mutateAsync(k.id),children:"Delete list"})]})]}),e.jsx("div",{className:"grid gap-2",children:_e.map(Be=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:J===Be.id?e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ye,{value:_.label,onChange:Ge=>B(gt=>({...gt,label:Ge.target.value}))}),e.jsx(Ze,{value:_.description,onChange:Ge=>B(gt=>({...gt,description:Ge.target.value})),className:"min-h-20"}),e.jsx(ye,{value:_.tags,onChange:Ge=>B(gt=>({...gt,tags:Ge.target.value})),placeholder:"comma, separated, tags"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{size:"sm",pending:Le.isPending,pendingLabel:"Saving",onClick:()=>void Le.mutateAsync({catalogItemId:Be.id,patch:{label:_.label,description:_.description,tags:_.tags.split(",").map(Ge=>Ge.trim()).filter(Boolean)}}),children:"Save concept"}),e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>q(null),children:"Cancel"})]})]}):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-medium text-white",children:Be.label}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:Be.description||"No description yet."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Be.tags.map(Ge=>e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:Ge},`${Be.id}-${Ge}`))})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>{q(Be.id),B({label:Be.label,description:Be.description,tags:Be.tags.join(", ")})},children:"Edit"}),e.jsxs(W,{variant:"ghost",size:"sm",pending:Qe.isPending,pendingLabel:"Deleting",onClick:()=>void Qe.mutateAsync(Be.id),children:[e.jsx(Rt,{className:"mr-1 size-4"}),"Delete"]})]})]})},Be.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] border border-white/8 bg-white/[0.02] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/68",children:[e.jsx(ds,{className:"size-4"}),"Add concept to ",k.title]}),e.jsx(ye,{value:se.label,onChange:Be=>Y(Ge=>({...Ge,[k.id]:{...se,label:Be.target.value}})),placeholder:"Concept label"}),e.jsx(Ze,{value:se.description,onChange:Be=>Y(Ge=>({...Ge,[k.id]:{...se,description:Be.target.value}})),className:"min-h-20",placeholder:"Short description"}),e.jsx(ye,{value:se.tags,onChange:Be=>Y(Ge=>({...Ge,[k.id]:{...se,tags:Be.target.value}})),placeholder:"comma, separated, tags"}),e.jsx(W,{disabled:!se.label.trim(),pending:ve.isPending,pendingLabel:"Adding",onClick:()=>void ve.mutateAsync({catalogId:k.id,label:se.label,description:se.description,tags:se.tags.split(",").map(Be=>Be.trim()).filter(Boolean),featureWeights:Zl}).then(()=>Y(Be=>({...Be,[k.id]:{label:"",description:"",tags:""}}))),children:"Add concept"})]})]},k.id)})})]}):null]}),e.jsx(Yt,{open:p.open,onOpenChange:k=>{k||A(null),f(se=>({...se,open:k}))},children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.74)] backdrop-blur-xl"}),e.jsxs(es,{className:"fixed inset-x-4 bottom-4 top-4 z-50 overflow-y-auto rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(17,24,39,0.98),rgba(10,14,24,0.98))] shadow-[0_30px_90px_rgba(3,8,18,0.45)] md:inset-x-10 lg:left-1/2 lg:right-auto lg:w-[min(72rem,calc(100vw-3rem))] lg:-translate-x-1/2",children:[e.jsx(ts,{className:"sr-only",children:"Preference game"}),e.jsx(rs,{className:"sr-only",children:"Start comparison rounds from a Forge domain or concept list."}),e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between gap-4 border-b border-white/8 bg-[rgba(10,14,24,0.92)] px-5 py-4 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Preference game"}),e.jsx("div",{className:"mt-1 font-display text-2xl text-white",children:p.phase==="domain"?"Choose a domain":p.phase==="catalog"?"Choose a concept list":"Pick the better fit"})]}),e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Close preference game",className:"rounded-full bg-white/6 p-2 text-white/65 transition hover:bg-white/10 hover:text-white",children:e.jsx(Tt,{className:"size-4"})})})]}),e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[b?e.jsx("div",{className:"rounded-[18px] border border-rose-400/25 bg-rose-500/10 px-4 py-3 text-sm text-rose-100",children:b}):null,p.phase==="domain"?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:Jl.map(k=>e.jsxs("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.04] px-5 py-5 text-left transition hover:border-[var(--primary)]/30 hover:bg-[var(--primary)]/10",onClick:()=>void ne(k.value),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:k.label}),e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:k.mode==="forge"?"Forge":"Concept"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:k.description})]},k.value))}):null,p.phase==="catalog"?e.jsxs("div",{className:"grid gap-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Pick the concept list Forge should draw from. You do not need to assemble the items yourself."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"size-4 text-white/38"}),e.jsx(ye,{value:d,onChange:k=>m(k.target.value),placeholder:"Search concept lists"})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:Ce.length>0?Ce.map(k=>e.jsxs("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.04] px-5 py-5 text-left transition hover:border-[var(--primary)]/30 hover:bg-[var(--primary)]/10",onClick:()=>void re(p.domain,k.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:k.title}),e.jsxs(I,{className:"bg-white/[0.08] text-white/70",children:[k.items.length," items"]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:k.description||"No description yet."})]},k.id)):e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] px-5 py-6 text-sm text-white/58",children:"No concept list matches that search yet."})})]}):null,p.phase==="play"?e.jsx("div",{className:"grid gap-5",children:C||E.isLoading?e.jsx(Et,{eyebrow:"Preference game",title:"Preparing the next round",description:"Forge is lining up comparison candidates."}):Me?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/52",children:[e.jsx(I,{className:"bg-white/[0.08] text-white/70",children:((Pe=Jl.find(k=>k.value===p.domain))==null?void 0:Pe.label)??p.domain}),e.jsx("span",{children:xe==null?void 0:xe.selectedContext.name}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[(xe==null?void 0:xe.compare.pendingCount)??0," ","queued comparisons"]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(lx,{title:Me.left.label,description:Me.left.description,sideLabel:"Left",onClick:()=>void be("left",1)}),e.jsx(lx,{title:Me.right.label,description:Me.right.description,sideLabel:"Right",onClick:()=>void be("right",1)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{onClick:()=>void be("left",1),children:"Left"}),e.jsx(W,{onClick:()=>void be("right",1),children:"Right"}),e.jsx(W,{variant:"secondary",onClick:()=>void be("left",1.75),children:"Strong left"}),e.jsx(W,{variant:"secondary",onClick:()=>void be("right",1.75),children:"Strong right"}),e.jsx(W,{variant:"secondary",onClick:()=>void be("tie",1),children:"Tie"}),e.jsx(W,{variant:"secondary",onClick:()=>void be("skip",1),children:"Skip"})]}),e.jsx("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-4 lg:grid-cols-2",children:[Me.left,Me.right].map(k=>e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:k.label}),e.jsx("div",{className:"text-sm text-white/56",children:"Quick signals"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:IT.map(se=>e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>void je(k.id,se.signalType),children:se.label},`${k.id}-${se.signalType}`))})]},k.id))})]}):e.jsx(Bt,{eyebrow:"Preference game",title:"No pair is ready yet",description:"Forge needs more items in this domain before it can keep asking comparisons."})}):null]})]})]})})]})}function ur(t,s,a){return`${s}:${t}:${a}`}function Hm(t,s,a){return Math.min(Math.max(t,s),a)}function Gm(t,s,a){return Math.min(a,Math.max(1,Math.ceil(t.trim().length/s)))}function LT(t,{compact:s}){const a=Gm(t,s?13:14,4),r=(s?114:156)+(a-1)*(s?12:18)+Math.min(24,Math.max(0,t.trim().length-18))*(s?.7:1);return Hm(r,s?118:164,s?154:210)}function DT(t,{compact:s}){const a=Gm(t,s?11:13,3),r=(s?40:48)+(a-1)*(s?6:8)+Math.min(s?18:26,Math.max(0,t.trim().length-(s?12:16)))*(s?.45:.55);return Hm(r,s?42:50,s?56:68)}function jn(t,{compact:s,emphasis:a=!1}){const r=Gm(t,s?16:a?22:20,a?3:2);return{width:Hm((s?a?184:152:a?224:176)+Math.min(t.length,48)*(s?1.8:2.15),s?a?188:156:a?228:184,s?a?248:208:a?300:244),height:r===1?s?64:70:r===2?s?82:92:s?98:110}}function ox(t){if(t.kind==="goal"||t.kind==="value"||t.kind==="ghost"){const s=t.radius??(t.kind==="goal"?76:34);return{halfWidth:s,halfHeight:s}}return{halfWidth:(t.width??146)/2,halfHeight:(t.height??58)/2}}function FT(t,{compact:s}){const a=t.map(n=>({...n,homeX:n.x,homeY:n.y,locked:n.kind==="goal"||n.kind==="ghost"})),i=s?28:40,r=s?.08:.06;for(let n=0;n<180;n+=1){for(const l of a)l.locked||(l.x+=(l.homeX-l.x)*r,l.y+=(l.homeY-l.y)*r);for(let l=0;l<a.length;l+=1)for(let o=l+1;o<a.length;o+=1){const d=a[l],m=a[o],h=ox(d),u=ox(m),x=m.x-d.x,g=m.y-d.y,p=h.halfWidth+u.halfWidth+i-Math.abs(x),f=h.halfHeight+u.halfHeight+i-Math.abs(g);if(p<=0||f<=0)continue;const b=p<f?"x":"y",A=Math.sign(b==="x"?x||o-l||1:g||o-l||1),C=(b==="x"?p:f)/(d.locked||m.locked?1:2);d.locked||(b==="x"?d.x-=A*C:d.y-=A*C),m.locked||(b==="x"?m.x+=A*C:m.y+=A*C)}}return a.map(({homeX:n,homeY:l,locked:o,...d})=>d)}function _T(){return{nodes:[{id:"ghost_goal_north",kind:"ghost",x:-250,y:-20,radius:68,label:"First goal",meta:"Goal",href:"/goals"},{id:"ghost_goal_center",kind:"ghost",x:0,y:34,radius:74,label:"Life goals",meta:"Goal",href:"/goals"},{id:"ghost_goal_south",kind:"ghost",x:250,y:-10,radius:68,label:"Direction",meta:"Goal",href:"/goals"}],edges:[],fields:[],inspectors:{ghost_goal_center:{id:"ghost_goal_center",eyebrow:"Goals",title:"Add the first life goal",summary:"The graph is already laid out. Once a goal exists, values, reports, beliefs, and behaviors will start orbiting it instead of staying fragmented.",href:"/goals",ctaLabel:"Open life goals",tone:"sky",entityKind:"goal",chips:["Goals","Values","Reports"],stats:["0 goals mapped yet"]}},defaultSelectedId:"ghost_goal_center"}}function Yw(t,{compact:s=!1}={}){var m;if(t.length===0)return _T();const a=[],i=[],r=[],n={},l=s?560:840,o=-((t.length-1)*l)/2;t.forEach((h,u)=>{const x=o+u*l,g=u%2===0?92:146,p=h.linkedBehaviors.length+h.linkedBeliefs.length+h.linkedReports.length+h.linkedHabits.length,f=`goal:${h.goal.id}`;a.push({id:f,kind:"goal",x,y:g,radius:LT(h.goal.title,{compact:s}),tone:"amber",label:h.goal.title,href:`/goals/${h.goal.id}`}),n[f]={id:f,eyebrow:"Goal",title:h.goal.title,summary:h.goal.description,href:`/goals/${h.goal.id}`,ctaLabel:"Open goal",tone:"amber",entityKind:"goal",chips:h.linkedValues.slice(0,4).map(j=>j.title),stats:[`${h.linkedValues.length} linked value${h.linkedValues.length===1?"":"s"}`,`${h.linkedProjects.length} live project${h.linkedProjects.length===1?"":"s"}`,`${h.linkedHabits.length} linked habit${h.linkedHabits.length===1?"":"s"}`,`${p} friction signal${p===1?"":"s"}`]},p>0&&r.push({id:`field:${h.goal.id}`,x:x+18,y:g+20,radiusX:s?144:176,radiusY:s?104:132,tone:"rose",opacity:Math.min(.42,.14+p*.04)});const b=s?208:282;h.linkedValues.slice(0,s?4:5).forEach((j,R)=>{const Q=(-95+R*(s?78:64))*(Math.PI/180),X=DT(j.title,{compact:s}),Y=x+Math.cos(Q)*b,z=g+Math.sin(Q)*b,K=ur(h.goal.id,"value",j.id);a.push({id:K,kind:"value",x:Y,y:z,radius:X,tone:"mint",label:j.title,meta:`${j.linkedGoalIds.length} goal${j.linkedGoalIds.length===1?"":"s"}`,href:`/psyche/values?focus=${j.id}#values-atlas`}),i.push({id:`${f}->${K}`,from:f,to:K,tone:"mint",strength:"medium"}),n[K]={id:K,eyebrow:"Value",title:j.title,summary:j.valuedDirection||j.whyItMatters||j.description,href:`/psyche/values?focus=${j.id}#values-atlas`,ctaLabel:"Open values",tone:"mint",entityKind:"value",chips:j.committedActions.slice(0,3),stats:[`${j.linkedProjectIds.length} linked project${j.linkedProjectIds.length===1?"":"s"}`,`${j.linkedTaskIds.length} linked task${j.linkedTaskIds.length===1?"":"s"}`]}});const A=h.linkedProjects.slice(0,s?2:3).map(j=>({project:j,size:jn(j.title,{compact:s,emphasis:!0})})),C=s?24:30;let w=-(A.reduce((j,R)=>j+R.size.width,0)+Math.max(0,A.length-1)*C)/2;A.forEach(({project:j,size:R},Q)=>{const X=ur(h.goal.id,"project",j.id),Y=x+w+R.width/2,z=g-(s?330:434)-Q*(s?16:20);w+=R.width+C,a.push({id:X,kind:"project",x:Y,y:z,width:R.width,height:R.height,tone:"sky",label:j.title,meta:"Project",href:`/projects/${j.id}`}),i.push({id:`${f}->${X}`,from:f,to:X,tone:"sky",strength:"medium"}),n[X]={id:X,eyebrow:"Project",title:j.title,summary:j.description,href:`/projects/${j.id}`,ctaLabel:"Open project",tone:"sky",entityKind:"project",chips:[j.status,j.goalTitle],stats:[`${j.progress}% progress`,`${j.activeTaskCount} active task${j.activeTaskCount===1?"":"s"}`]}}),h.linkedHabits.slice(0,s?2:3).forEach((j,R)=>{const Q=ur(h.goal.id,"habit",j.id),X=jn(j.title,{compact:s}),Y=x-(s?44:58),z=g+(s?228:294)+R*(s?92:104);a.push({id:Q,kind:"habit",x:Y,y:z,width:X.width,height:X.height,tone:"mint",label:j.title,meta:j.polarity,href:"/habits"}),i.push({id:`${f}->${Q}`,from:f,to:Q,tone:"mint",strength:j.dueToday?"high":"medium"}),n[Q]={id:Q,eyebrow:"Habit",title:j.title,summary:j.description||"Recurring operating record connected directly to this goal field.",href:"/habits",ctaLabel:"Open habits",tone:"mint",entityKind:"habit",chips:[j.polarity,j.frequency,j.dueToday?"due today":"checked in"],stats:[`${j.streakCount} streak`,`${j.rewardXp}/${j.penaltyXp} xp flow`]}});let S=g+(s?132:156);h.linkedBehaviors.slice(0,s?2:3).forEach(j=>{const R=ur(h.goal.id,"behavior",j.id),Q=jn(j.title,{compact:s}),X=x-(s?272:352);a.push({id:R,kind:"behavior",x:X,y:S,width:Q.width,height:Q.height,tone:"orange",label:j.title,meta:j.kind,href:`/psyche/behaviors?focus=${j.id}#behavior-columns`}),i.push({id:`${f}->${R}`,from:f,to:R,tone:"orange",dashed:j.kind!=="committed",strength:j.kind==="committed"?"medium":"low"}),n[R]={id:R,eyebrow:"Behavior",title:j.title,summary:j.replacementMove||j.description||j.urgeStory,href:`/psyche/behaviors?focus=${j.id}#behavior-columns`,ctaLabel:"Open behaviors",tone:"orange",entityKind:"behavior",chips:[j.kind,...j.commonCues.slice(0,2)],stats:[j.shortTermPayoff?"Short-term payoff mapped":"Payoff still to map",j.longTermCost?"Long-term cost mapped":"Cost still to map"]},S+=Q.height+(s?18:22)});let y=g+(s?8:10);h.linkedBeliefs.slice(0,s?2:3).forEach(j=>{const R=ur(h.goal.id,"belief",j.id),Q=jn(j.statement,{compact:s,emphasis:!0}),X=x+(s?278:362);a.push({id:R,kind:"belief",x:X,y,width:Q.width,height:Q.height,tone:"violet",label:j.statement,meta:"belief",href:`/psyche/schemas-beliefs?focus=${j.id}`}),i.push({id:`${f}->${R}`,from:f,to:R,tone:"violet",dashed:!0,strength:"low"}),n[R]={id:R,eyebrow:"Belief",title:j.statement,summary:j.flexibleAlternative||j.originNote||"Belief script attached to this part of the map.",href:`/psyche/schemas-beliefs?focus=${j.id}`,ctaLabel:"Open beliefs",tone:"violet",entityKind:"belief",chips:[j.beliefType,`${j.confidence}% grip`],stats:[`${j.linkedBehaviorIds.length} linked behavior${j.linkedBehaviorIds.length===1?"":"s"}`,`${j.linkedReportIds.length} linked report${j.linkedReportIds.length===1?"":"s"}`]},y+=Q.height+(s?18:22)});const N=h.linkedReports.slice(0,s?2:3).map(j=>({report:j,size:jn(j.title,{compact:s})})),P=s?20:26;let H=-(N.reduce((j,R)=>j+R.size.width,0)+Math.max(0,N.length-1)*P)/2;N.forEach(({report:j,size:R})=>{const Q=ur(h.goal.id,"report",j.id),X=x+H+R.width/2,Y=g+(s?332:430);H+=R.width+P,a.push({id:Q,kind:"report",x:X,y:Y,width:R.width,height:R.height,tone:"blue",label:j.title,meta:j.status,href:`/psyche/reports/${j.id}`}),i.push({id:`${f}->${Q}`,from:f,to:Q,tone:"sky",strength:"medium"}),n[Q]={id:Q,eyebrow:"Report",title:j.title,summary:j.eventSituation||j.customEventType||"Reflective chain linked into this goal.",href:`/psyche/reports/${j.id}`,ctaLabel:"Open report",tone:"blue",entityKind:"report",chips:[j.status,...j.nextMoves.slice(0,2)],stats:[`${j.emotions.length} emotion${j.emotions.length===1?"":"s"}`,`${j.behaviors.length} move${j.behaviors.length===1?"":"s"}`]}})});const d=((m=a[0])==null?void 0:m.id)??"ghost_goal_center";return{nodes:FT(a,{compact:s}),edges:i,fields:r,inspectors:n,defaultSelectedId:d}}const bi={mint:"rgba(110,231,183,0.64)",sky:"rgba(125,211,252,0.66)",violet:"rgba(196,181,253,0.72)",rose:"rgba(251,113,133,0.68)",amber:"rgba(251,191,36,0.68)",orange:"rgba(251,146,60,0.72)",blue:"rgba(96,165,250,0.72)",slate:"rgba(148,163,184,0.52)"},pc={mint:"rgba(16,185,129,0.18)",sky:"rgba(56,189,248,0.18)",violet:"rgba(167,139,250,0.18)",rose:"rgba(251,113,133,0.18)",amber:"rgba(251,191,36,0.18)",orange:"rgba(251,146,60,0.18)",blue:"rgba(96,165,250,0.18)",slate:"rgba(148,163,184,0.12)"},wi={mint:"rgba(209,250,229,0.98)",sky:"rgba(224,242,254,0.98)",violet:"rgba(237,233,254,0.98)",rose:"rgba(255,228,230,0.98)",amber:"rgba(254,243,199,0.98)",orange:"rgba(255,237,213,0.98)",blue:"rgba(219,234,254,0.98)",slate:"rgba(241,245,249,0.9)"};function Jw(t){switch(t){case"goal":case"value":case"behavior":case"belief":case"report":case"project":case"habit":return t;default:return null}}function RT(t){if(t.tone)return t.tone;switch(t.kind){case"goal":return"amber";case"value":return"mint";case"belief":return"violet";case"behavior":return"orange";case"project":return"sky";case"habit":return"mint";case"report":return"blue";default:return"slate"}}function $T(t){if(t.kind==="ghost")return t.meta??null;const s=Jw(t.kind);return s?zs(s).label:t.meta??null}function xc(t,s,a){return Math.min(Math.max(t,s),a)}function so(t,s,a=3){const i=t.trim().split(/\s+/),r=[];let n="";for(let d=0;d<i.length;d+=1){const m=i[d],h=n?`${n} ${m}`:m;if(h.length>s&&n){if(r.push(n),r.length>=a-1){n=[m,...i.slice(d+1)].join(" ");break}n=m}else n=h}n&&r.push(n);const l=r.slice(0,a),o=l.length-1;return o>=0&&l[o].length>s&&(l[o]=`${l[o].slice(0,Math.max(1,s-1)).trimEnd()}…`),l}function OT(t,s){if(t.length===0&&s.length===0)return{minX:-360,maxX:360,minY:-240,maxY:240};let a=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const l of t){const o=l.kind==="goal"||l.kind==="value"||l.kind==="ghost"?l.radius??32:(l.width??124)/2,d=l.kind==="goal"||l.kind==="value"||l.kind==="ghost"?l.radius??32:(l.height??56)/2,m=l.meta&&(l.kind==="goal"||l.kind==="ghost")?48:0;a=Math.min(a,l.x-o),i=Math.max(i,l.x+o),r=Math.min(r,l.y-d-m),n=Math.max(n,l.y+d)}for(const l of s)a=Math.min(a,l.x-l.radiusX),i=Math.max(i,l.x+l.radiusX),r=Math.min(r,l.y-l.radiusY),n=Math.max(n,l.y+l.radiusY);return{minX:a,maxX:i,minY:r,maxY:n}}function dx(t){return{x:t.x,y:t.y}}function zT(t){if(t.kind==="goal"){const s=t.radius??112;return so(t.label,Math.max(14,Math.floor(s/7.2)),4)}if(t.kind==="value"||t.kind==="ghost"){const s=t.radius??40;return so(t.label,Math.max(12,Math.floor(s/3)),3)}return t.kind==="project"?so(t.label,Math.max(18,Math.floor((t.width??220)/10)),3):so(t.label,Math.max(16,Math.floor((t.width??180)/10.5)),2)}function KT(t){switch(t){case"goal":return"amber";case"project":return"sky";case"value":return"mint";case"behavior":return"orange";case"belief":return"violet";case"report":return"blue";default:return"slate"}}function Zw({nodes:t,edges:s,fields:a=[],title:i,hint:r,action:n,legend:l,selectedNodeId:o,onSelectNode:d,minHeightClassName:m="min-h-[34rem] lg:min-h-[44rem]",compact:h=!1,testId:u}){const x=c.useRef(null),g=$t(),[p,f]=c.useState({width:0,height:0}),[b,A]=c.useState({scale:1,x:0,y:0}),[C,T]=c.useState(null),w=c.useRef(null),S=c.useRef({scale:1,x:0,y:0}),y=c.useRef(new Map),N=c.useRef(null),P=c.useRef(0),v=c.useRef(!1),H=c.useMemo(()=>new Map(t.map(_=>[_.id,_])),[t]),j=c.useMemo(()=>OT(t,a),[a,t]),R=p.width>0&&p.width<640;c.useEffect(()=>{if(!x.current||typeof ResizeObserver>"u")return;const _=new ResizeObserver(B=>{const G=B[0];f({width:G.contentRect.width,height:G.contentRect.height})});return _.observe(x.current),()=>_.disconnect()},[]);const Q=c.useCallback(()=>{if(!p.width||!p.height)return;const _=R?132:h?140:190,B=Math.max(j.maxX-j.minX,1),G=Math.max(j.maxY-j.minY,1),ae=xc(Math.min(p.width/(B+_),p.height/(G+_)),R?.24:h?.4:.46,R?.76:h?1.04:1.18),ke=(j.minX+j.maxX)/2,Ae=(j.minY+j.maxY)/2;A({scale:ae,x:p.width/2-ke*ae,y:p.height/2-Ae*ae})},[j.maxX,j.maxY,j.minX,j.minY,h,p.height,p.width,R]);c.useEffect(()=>{S.current=b},[b]),c.useEffect(()=>{v.current||Q()},[Q]);const X=c.useCallback((_,B,G)=>{const ae=xc(_,.28,1.9);A(ke=>{if(B==null||G==null)return{...ke,scale:ae};const Ae=(B-ke.x)/ke.scale,ie=(G-ke.y)/ke.scale;return{scale:ae,x:B-Ae*ae,y:G-ie*ae}})},[]),Y=c.useCallback(()=>{const _=[...y.current.values()];if(_.length<2){N.current=null;return}const[B,G]=_,ae=Math.hypot(G.x-B.x,G.y-B.y);if(!Number.isFinite(ae)||ae<=0){N.current=null;return}const ke=S.current;N.current={startDistance:ae,startScale:ke.scale,startViewportX:ke.x,startViewportY:ke.y,startMidpointX:(B.x+G.x)/2,startMidpointY:(B.y+G.y)/2}},[]),z=_=>{var ae;_.preventDefault();const B=(ae=x.current)==null?void 0:ae.getBoundingClientRect();if(!B)return;v.current=!0;const G=_.deltaY<0?1.1:.9;X(b.scale*G,_.clientX-B.left,_.clientY-B.top)},K=_=>{var ke;const B=(ke=x.current)==null?void 0:ke.getBoundingClientRect(),G=_.clientX-((B==null?void 0:B.left)??0),ae=_.clientY-((B==null?void 0:B.top)??0);if(y.current.set(_.pointerId,{x:G,y:ae}),y.current.size===1){const Ae=S.current;w.current={pointerId:_.pointerId,originX:Ae.x,originY:Ae.y,startX:G,startY:ae}}else w.current=null,Y();_.currentTarget.setPointerCapture(_.pointerId)},$=_=>{var ie;const B=(ie=x.current)==null?void 0:ie.getBoundingClientRect(),G=_.clientX-((B==null?void 0:B.left)??0),ae=_.clientY-((B==null?void 0:B.top)??0);if(y.current.has(_.pointerId)&&y.current.set(_.pointerId,{x:G,y:ae}),N.current&&y.current.size>=2){const[Ie,Ne]=[...y.current.values()],M=Math.hypot(Ne.x-Ie.x,Ne.y-Ie.y);if(Number.isFinite(M)&&M>0){v.current=!0,P.current=Date.now()+240;const E=(Ie.x+Ne.x)/2,O=(Ie.y+Ne.y)/2,xe=N.current,V=xc(xe.startScale*M/xe.startDistance,.24,1.42),Se=(xe.startMidpointX-xe.startViewportX)/xe.startScale,Ee=(xe.startMidpointY-xe.startViewportY)/xe.startScale;A({scale:V,x:E-Se*V,y:O-Ee*V})}return}if(!w.current||w.current.pointerId!==_.pointerId||y.current.size!==1)return;v.current=!0;const ke=G-w.current.startX,Ae=ae-w.current.startY;(Math.abs(ke)>3||Math.abs(Ae)>3)&&(P.current=Date.now()+240),A(Ie=>{var Ne,M;return{...Ie,x:(((Ne=w.current)==null?void 0:Ne.originX)??Ie.x)+ke,y:(((M=w.current)==null?void 0:M.originY)??Ie.y)+Ae}})},D=_=>{if(y.current.delete(_.pointerId),y.current.size<2&&(N.current=null),y.current.size===1){const[B,G]=[...y.current.entries()][0]??[];if(B!=null&&G){const ae=S.current;w.current={pointerId:B,originX:ae.x,originY:ae.y,startX:G.x,startY:G.y}}}else w.current=null;_.currentTarget.hasPointerCapture(_.pointerId)&&_.currentTarget.releasePointerCapture(_.pointerId)},J=C??o??null,q=c.useCallback(_=>{Date.now()<P.current||(d==null||d(_.id),_.href&&g(_.href))},[g,d]);return e.jsxs("section",{"data-testid":u,className:te("overflow-hidden rounded-[32px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.12),transparent_32%),linear-gradient(180deg,rgba(11,18,31,0.985),rgba(7,12,23,0.98))] shadow-[0_26px_90px_rgba(2,6,16,0.38)]","px-3 py-3 sm:px-4 sm:py-4 lg:px-5 lg:py-5"),children:[e.jsxs("div",{className:"mb-3 flex min-w-0 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-[rgba(125,211,252,0.82)]",children:"Gravity well"}),e.jsx("h2",{className:te("mt-2 font-display leading-none text-white",h?"text-[clamp(1.25rem,2vw,1.7rem)]":"text-[clamp(1.45rem,2.8vw,2.3rem)]"),children:i}),r?e.jsx("p",{className:"mt-1.5 max-w-3xl text-sm leading-6 text-white/54",children:R?"Select a node, pan the field, and open the full map when you need the wider structure.":r}):null]}),e.jsx("div",{className:"flex min-w-0 flex-wrap items-center justify-end gap-2",children:n})]}),e.jsxs("div",{ref:x,className:te("group relative overflow-hidden rounded-[30px] border border-white/6 bg-[radial-gradient(circle_at_center,rgba(255,255,255,0.04),transparent_46%)] touch-none",m),style:{touchAction:"none"},onWheel:z,onPointerDown:K,onPointerMove:$,onPointerUp:D,onPointerCancel:D,children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(110,231,183,0.06),transparent_28%),radial-gradient(circle_at_20%_20%,rgba(196,181,253,0.08),transparent_24%),linear-gradient(180deg,rgba(255,255,255,0.015),rgba(4,8,18,0.24))]"}),e.jsxs("div",{className:"absolute left-3 top-3 z-10 inline-flex max-w-[calc(100%-7rem)] items-center gap-2 rounded-full border border-white/8 bg-[rgba(8,14,25,0.78)] px-2.5 py-1.5 text-[11px] uppercase tracking-[0.18em] text-white/42 backdrop-blur-xl sm:left-4 sm:top-4 sm:max-w-none sm:px-3",onPointerDown:_=>_.stopPropagation(),children:[e.jsx(Vv,{className:"size-3.5"}),R?"Drag or pinch":"Drag to pan, scroll to zoom"]}),e.jsxs("div",{className:"absolute right-3 top-3 z-10 flex max-w-[calc(100%-1.5rem)] flex-wrap items-center justify-end gap-1.5 sm:right-4 sm:top-4 sm:max-w-none sm:gap-2",onPointerDown:_=>_.stopPropagation(),children:[e.jsx(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom in",onClick:()=>{v.current=!0,X(b.scale*1.12,p.width-96,72)},children:e.jsx(ds,{className:"size-4"})}),e.jsx(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom out",onClick:()=>{v.current=!0,X(b.scale*.88,p.width-96,72)},children:e.jsx(Ig,{className:"size-4"})}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:min-w-[4.75rem] sm:px-3","aria-label":"Fit graph",onClick:()=>{v.current=!0,Q()},children:[e.jsx(Xv,{className:"size-4"}),R?null:"Fit"]}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:min-w-[5.5rem] sm:px-3","aria-label":"Reset graph",onClick:()=>{v.current=!1,Q()},children:[e.jsx(Tg,{className:"size-4"}),R?null:"Reset"]})]}),l&&l.length>0&&!R?e.jsx("div",{className:"absolute bottom-4 left-4 z-10 flex flex-wrap items-center gap-2 rounded-[24px] border border-white/8 bg-[rgba(8,14,25,0.76)] px-3 py-2 text-xs text-white/58 backdrop-blur-xl",children:l.map(_=>{const B=_.kind?KT(_.kind):_.tone??"slate",G=_.kind?zs(_.kind).icon:null;return e.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap rounded-full bg-white/[0.04] px-2.5 py-1.5",children:[G?e.jsx(G,{className:"size-3.5",color:wi[B],strokeWidth:2.1}):e.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:bi[B]}}),_.label]},_.label)})}):null,e.jsxs("svg",{className:"relative z-[1] h-full w-full",viewBox:`0 0 ${p.width||1200} ${p.height||760}`,role:"img","aria-label":i,children:[e.jsx("defs",{children:e.jsx("filter",{id:"forge-graph-blur",children:e.jsx("feGaussianBlur",{stdDeviation:"34"})})}),e.jsxs("g",{transform:`translate(${b.x} ${b.y}) scale(${b.scale})`,children:[a.map(_=>e.jsx("ellipse",{cx:_.x,cy:_.y,rx:_.radiusX,ry:_.radiusY,fill:pc[_.tone??"rose"],opacity:_.opacity??.42,filter:"url(#forge-graph-blur)"},_.id)),t.filter(_=>_.kind==="goal"||_.kind==="ghost").map(_=>{const B=_.radius??76;return e.jsx("g",{opacity:_.kind==="ghost"?.28:.55,children:[B+74,B+124].map((G,ae)=>e.jsx("circle",{cx:_.x,cy:_.y,r:G,fill:"none",stroke:ae===0?"rgba(255,255,255,0.08)":"rgba(255,255,255,0.045)",strokeDasharray:ae===0?"0":"10 10"},`${_.id}-ring-${G}`))},`${_.id}-orbital-lanes`)}),s.map(_=>{const B=H.get(_.from),G=H.get(_.to);if(!B||!G)return null;const ae=dx(B),ke=dx(G),Ae=(ae.x+ke.x)/2,ie=(ae.y+ke.y)/2,Ie=Math.max(24,Math.abs(ae.x-ke.x)*.08),Ne=Ae,M=ie-Ie;return e.jsx("path",{d:`M ${ae.x} ${ae.y} Q ${Ne} ${M} ${ke.x} ${ke.y}`,fill:"none",stroke:bi[_.tone??"slate"],strokeWidth:_.strength==="high"?3:_.strength==="medium"?2.2:1.6,strokeDasharray:_.dashed?"8 8":void 0,opacity:J&&_.from!==J&&_.to!==J?.18:.62},_.id)}),t.map(_=>{_.id;const B=C===_.id,G=J===_.id,ae=RT(_),ke=$T(_),Ae=zT(_),ie=Jw(_.kind),Ie=ie?zs(ie).icon:null;if(_.kind==="goal"||_.kind==="value"||_.kind==="ghost"){const L=_.radius??(_.kind==="goal"?76:34),U=ke?_.y-L-(_.kind==="goal"?18:10):null,ge=_.kind==="goal"?20:14.5,Te=_.kind==="goal"?28:16,ve=_.kind==="goal"?_.y-L*.34:_.kind==="value"?_.y-L*.3:_.y-L*.2,Le=_.kind==="goal"?_.y+L*.2:_.y+10;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{T(_.id),d==null||d(_.id)},onPointerLeave:()=>T(Qe=>Qe===_.id?null:Qe),onFocus:()=>d==null?void 0:d(_.id),onClick:()=>q(_),onKeyDown:Qe=>{(Qe.key==="Enter"||Qe.key===" ")&&(Qe.preventDefault(),q(_))},className:"cursor-pointer outline-none",children:[e.jsx("circle",{cx:_.x,cy:_.y,r:L+(G?14:0),fill:G?`${bi[ae]}22`:"transparent",stroke:G?bi[ae]:"transparent",opacity:B?.98:.9}),e.jsx("circle",{cx:_.x,cy:_.y,r:L+(B?2:0),fill:_.kind==="ghost"?"rgba(255,255,255,0.03)":pc[ae],stroke:_.kind==="ghost"?"rgba(255,255,255,0.18)":bi[ae],strokeDasharray:_.kind==="ghost"?"8 8":void 0,strokeWidth:G?2.8:1.6}),ke?e.jsx("text",{x:_.x,y:U??_.y-12,textAnchor:"middle",fontSize:_.kind==="goal"?"11.5":"10.5",fill:_.kind==="ghost"?"rgba(255,255,255,0.62)":wi[ae],style:{letterSpacing:"0.18em",textTransform:"uppercase"},children:ke}):null,Ie?e.jsx(Ie,{x:_.x-Te/2,y:ve-Te/2,width:Te,height:Te,color:wi[ae],strokeWidth:2.1}):null,Ae.map((Qe,st)=>e.jsx("text",{x:_.x,y:Le+st*ge-(Ae.length-1)*ge/2,textAnchor:"middle",fontSize:_.kind==="goal"?21:12.8,fontWeight:_.kind==="goal"?600:500,fill:_.kind==="ghost"?"rgba(255,255,255,0.92)":wi[ae],children:Qe},`${_.id}-${Qe}-${st}`))]},_.id)}const Ne=_.width??146,M=_.height??58,E=_.x-Ne/2,O=_.y-M/2,xe=_.kind==="project"?14:13,V=E+14,Se=O+13,Ee=O+22,Ce=ke?O+M*.65:O+M*.56,qe=_.kind==="project"?16:15,oe=_.kind==="project"?14.2:13.2;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{T(_.id),d==null||d(_.id)},onPointerLeave:()=>T(L=>L===_.id?null:L),onFocus:()=>d==null?void 0:d(_.id),onClick:()=>q(_),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),q(_))},className:"cursor-pointer outline-none",children:[e.jsx("rect",{x:E-(G?6:0),y:O-(G?6:0),rx:"28",ry:"28",width:Ne+(G?12:0),height:M+(G?12:0),fill:G?`${bi[ae]}22`:"transparent"}),e.jsx("rect",{x:E-(B?2:0),y:O-(B?2:0),rx:"22",ry:"22",width:Ne+(B?4:0),height:M+(B?4:0),fill:pc[ae],stroke:bi[ae],strokeWidth:G?2.3:1.3}),Ie?e.jsx(Ie,{x:V,y:Se,width:xe,height:xe,color:wi[ae],strokeWidth:2.1}):null,ke?e.jsx("text",{x:V+xe+8,y:Ee,textAnchor:"start",fontSize:"9.5",fill:wi[ae],style:{letterSpacing:"0.16em",textTransform:"uppercase",opacity:.82},children:ke}):null,Ae.map((L,U)=>e.jsx("text",{x:_.x,y:Ce+U*qe-(Ae.length-1)*qe/2,textAnchor:"middle",fontSize:oe,fontWeight:600,fill:wi[ae],children:L},`${_.id}-${L}-${U}`))]},_.id)})]})]})]})]})}const cx={intent:"trigger_report",linkedGoalId:"",linkedProjectId:"",linkedTaskId:""};function qT({open:t,onOpenChange:s}){const a=$t(),i=jt(),[r,n]=c.useState(cx),l=[{id:"intent",eyebrow:"Reflect",title:"What do you want to reflect on?",description:"Choose the entrypoint first. Forge will route you into the right guided flow instead of dropping you into a generic form.",render:(d,m)=>e.jsx(wt,{columns:3,value:d.intent,onChange:h=>m({intent:h}),options:[{value:"trigger_report",label:"A situation",description:"Start a Spark-to-Pivot report about something that happened."},{value:"behavior",label:"A behavior",description:"Trace an away move, committed action, or recovery path."},{value:"belief",label:"A belief script",description:"Capture or refine the belief beneath the reaction."},{value:"pattern",label:"A recurring pattern",description:"Map the loop, payoff, cost, and better response."},{value:"value",label:"A blocked value",description:"Clarify which value is being challenged or needs support."},{value:"execution_tension",label:"A goal tension",description:"Reflect on a goal, project, or task that carries friction."}]})},{id:"placement",eyebrow:"Placement",title:"Attach the reflection to the wider system",description:"This keeps the reflection connected to values, behaviors, and live work instead of becoming an isolated note.",render:(d,m)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(de,{label:"Goal / project / task tension",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(We,{kind:"goal",label:"Goal",compact:!0,gradient:!1}),e.jsx(We,{kind:"project",label:"Project",compact:!0,gradient:!1}),e.jsx(We,{kind:"task",label:"Task",compact:!0,gradient:!1})]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:d.linkedGoalId,onChange:h=>m({linkedGoalId:h.target.value}),children:[e.jsx("option",{value:"",children:"No goal selected"}),i.snapshot.goals.map(h=>e.jsxs("option",{value:h.id,children:["Goal · ",h.title]},h.id))]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:d.linkedProjectId,onChange:h=>m({linkedProjectId:h.target.value}),children:[e.jsx("option",{value:"",children:"No project selected"}),i.snapshot.dashboard.projects.map(h=>e.jsxs("option",{value:h.id,children:["Project · ",h.title]},h.id))]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:d.linkedTaskId,onChange:h=>m({linkedTaskId:h.target.value}),children:[e.jsx("option",{value:"",children:"No task selected"}),i.snapshot.tasks.slice(0,40).map(h=>e.jsxs("option",{value:h.id,children:["Task · ",h.title]},h.id))]})]})})})}],o=async()=>{const d=new URLSearchParams({create:"1",intent:r.intent});switch(r.linkedGoalId&&d.set("goalId",r.linkedGoalId),r.linkedProjectId&&d.set("projectId",r.linkedProjectId),r.linkedTaskId&&d.set("taskId",r.linkedTaskId),r.intent){case"behavior":a(`/psyche/behaviors?${d.toString()}`);break;case"belief":a(`/psyche/schemas-beliefs?${d.toString()}`);break;case"pattern":a(`/psyche/patterns?${d.toString()}`);break;case"value":a(`/psyche/values?${d.toString()}`);break;case"execution_tension":case"trigger_report":default:a(`/psyche/reports?${d.toString()}`);break}s(!1),n(cx)};return e.jsx(Lt,{open:t,onOpenChange:s,eyebrow:"Reflect",title:"Start from the right reflective doorway",description:"Choose what you want to reflect on first. Forge will take you into the right guided flow instead of leaving you in a generic form.",value:r,onChange:n,draftPersistenceKey:"psyche.reflect.launcher",steps:l,submitLabel:"Open guided reflection",onSubmit:o})}function gc({to:t,children:s,className:a}){return e.jsx(Je,{to:t,className:"group block transition-transform duration-[var(--motion-medium)] ease-[var(--ease-standard)] hover:-translate-y-0.5 focus-visible:outline-none",children:e.jsx(ce,{className:te("transition-[transform,box-shadow,background,border-color] duration-[var(--motion-medium)] ease-[var(--ease-standard)] group-hover:border-[var(--ui-border-strong)] group-hover:bg-[var(--ui-surface-hover)] group-hover:shadow-[var(--card-shadow-hover)] group-focus-visible:shadow-[var(--card-shadow-hover)]",a),children:s})})}function BT(){var T,w;const t=jt(),[s,a]=ms(),[i,r]=c.useState(s.get("reflect")==="1"),[n,l]=c.useState(null),o=Fe({queryKey:["forge-psyche-overview"],queryFn:md}),d=Fe({queryKey:["forge-psyche-questionnaires-hub"],queryFn:()=>Xg()}),m=(T=o.data)==null?void 0:T.overview,h=c.useMemo(()=>m?t.snapshot.goals.slice(0,3).map(S=>{const y=m.values.filter(R=>R.linkedGoalIds.includes(S.id)),N=t.snapshot.dashboard.projects.filter(R=>R.goalId===S.id),P=t.snapshot.habits.filter(R=>R.linkedGoalIds.includes(S.id)||R.linkedValueIds.some(Q=>y.some(X=>X.id===Q))),v=m.reports.filter(R=>R.linkedGoalIds.includes(S.id)),H=m.behaviors.filter(R=>R.linkedValueIds.some(Q=>y.some(X=>X.id===Q))),j=m.beliefs.filter(R=>R.linkedValueIds.some(Q=>y.some(X=>X.id===Q)));return{goal:S,linkedValues:y,linkedProjects:N,linkedHabits:P,linkedReports:v,linkedBehaviors:H,linkedBeliefs:j}}):[],[m,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits]),u=c.useMemo(()=>Yw(h,{compact:!0}),[h]);if(c.useEffect(()=>{l(u.defaultSelectedId)},[u.defaultSelectedId]),o.isLoading)return e.jsx(ls,{});if(o.isError||!m)return e.jsx(it,{eyebrow:"Psyche",error:o.error,onRetry:()=>void o.refetch()});const x=u.inspectors[n??u.defaultSelectedId]??u.inspectors[u.defaultSelectedId],g=m.patterns[0]??null,p=m.reports[0]??null,f=[...((w=d.data)==null?void 0:w.instruments)??[]].sort((S,y)=>{const N=S.latestRunAt?new Date(S.latestRunAt).getTime():0;return(y.latestRunAt?new Date(y.latestRunAt).getTime():0)-N})[0]??null,b="Values, patterns, behaviors, beliefs, habits, and reports in one live field.",A=e.jsx(Je,{to:"/psyche/goal-map",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center rounded-full bg-white/[0.08] px-4 py-2 text-sm whitespace-nowrap text-white transition hover:bg-white/[0.12]",children:"Open goal map"}),C=[{id:"hero",title:"Psyche",description:"Top route composition",defaultWidth:12,defaultHeight:1,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(nt,{title:"Psyche",titleText:"Psyche",description:b,actions:A})},{id:"sections",title:"Psyche sections",description:"Section switcher",defaultWidth:12,defaultHeight:1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(ks,{})},{id:"field",title:"Live field",description:"Graph and inspector stay as movable widgets.",defaultWidth:8,defaultHeight:5,minWidth:6,render:()=>e.jsx(Zw,{testId:"psyche-hub-graph",compact:!0,title:"Reflective pulse and live entity field",hint:"Select any goal, value, habit, belief, behavior, project, or report.",nodes:u.nodes,edges:u.edges,fields:u.fields,selectedNodeId:n,onSelectNode:l,minHeightClassName:"min-h-[20rem] sm:min-h-[24rem] lg:min-h-[34rem]",legend:[{label:"Goals",kind:"goal"},{label:"Values",kind:"value"},{label:"Habits",kind:"habit"},{label:"Behaviors",kind:"behavior"}],action:e.jsxs(e.Fragment,{children:[e.jsx(Je,{to:"/psyche/goal-map",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center rounded-[var(--radius-control)] bg-white/8 px-4 py-2 text-sm font-medium whitespace-nowrap text-white transition hover:bg-white/12",children:"Open goal map"}),e.jsx(W,{size:"sm",className:"min-w-0 sm:min-w-[6.5rem]",onClick:()=>r(!0),children:"Reflect"})]})})},{id:"inspector",title:"Inspector",description:"Selected-node inspector widget.",defaultWidth:4,defaultHeight:5,minWidth:4,render:()=>e.jsxs(ce,{className:"h-full min-w-0",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:x.entityKind?e.jsx(We,{kind:x.entityKind,compact:!0,gradient:!1,iconOnly:!0}):e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:x.eyebrow})}),e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:x.entityKind?e.jsx(yt,{kind:x.entityKind,label:x.title,variant:"heading",size:"lg",showKind:!1}):e.jsx("h2",{className:"font-display text-[clamp(1.25rem,2.2vw,1.8rem)] leading-none text-white",children:x.title})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:x.summary}),x.chips.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:x.chips.map(S=>e.jsx(I,{className:"bg-white/[0.08] text-white/74",children:S},S))}):null,x.stats.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:x.stats.map(S=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/68",children:S},S))}):null,e.jsx("div",{className:"mt-5",children:e.jsx(Je,{to:x.href,className:te("inline-flex min-h-11 w-full items-center justify-center rounded-[var(--radius-control)] px-4 py-2.5 text-sm font-medium whitespace-nowrap shadow-[0_12px_30px_rgba(192,193,255,0.08)]",x.entityKind?_n(x.entityKind,!0):"bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] text-white"),children:x.ctaLabel})})]})},{id:"actions",title:"Open threads",description:"Action and pulse cards.",defaultWidth:12,defaultHeight:3,render:()=>e.jsxs("div",{className:"grid min-w-0 gap-4 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsxs(gc,{to:"/psyche/behaviors",className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,29,32,0.96),rgba(11,21,23,0.94))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[rgba(110,231,183,0.82)]",children:"Best next reflective move"}),e.jsx("div",{className:"mt-3 font-display text-[clamp(1.45rem,2.2vw,2rem)] leading-none text-white",children:(g==null?void 0:g.preferredResponse)||"Map the active loop, then name the committed move that brings you back."}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:(g==null?void 0:g.targetBehavior)||"When the loop is explicit, the return path stops feeling abstract."})]}),e.jsxs(gc,{to:p?`/psyche/reports/${p.id}`:"/psyche/reports",className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(24,19,37,0.96),rgba(13,12,22,0.94))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-violet-100/72",children:"Open threads"}),e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Insights"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:m.openInsights})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Notes"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:m.openNotes})]})]})]})]})},{id:"questionnaires",title:"Questionnaire pulse",description:"Recent questionnaire state.",defaultWidth:12,defaultHeight:2,render:()=>{var S;return e.jsxs(gc,{to:f!=null&&f.latestRunId?`/psyche/questionnaire-runs/${f.latestRunId}`:"/psyche/questionnaires",className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,31,39,0.97),rgba(10,18,24,0.95))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-sky-100/72",children:"Questionnaire pulse"}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-display text-[clamp(1.4rem,2.2vw,2rem)] leading-none text-white",children:(f==null?void 0:f.title)??"Questionnaire library ready"}),e.jsxs(I,{className:"bg-white/[0.08] text-white/78",children:[(((S=d.data)==null?void 0:S.instruments)??[]).length," available"]})]})]})}}];return e.jsxs("div",{className:"grid min-w-0 gap-4 overflow-x-clip",children:[e.jsx(Td,{surfaceId:"psyche",baseWidgets:C}),e.jsx(qT,{open:i,onOpenChange:S=>{r(S);const y=new URLSearchParams(s);y.delete("reflect"),a(y,{replace:!0})}})]})}function $a({eyebrow:t,title:s,description:a,titleHelp:i,tone:r="default",children:n,className:l}){const o={default:"bg-[linear-gradient(180deg,rgba(17,24,35,0.96),rgba(11,16,24,0.94))]",mint:"bg-[radial-gradient(circle_at_top_left,rgba(110,231,183,0.14),transparent_42%),linear-gradient(180deg,rgba(14,28,31,0.96),rgba(10,20,24,0.94))]",sky:"bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.14),transparent_42%),linear-gradient(180deg,rgba(16,25,34,0.96),rgba(10,17,24,0.94))]",violet:"bg-[radial-gradient(circle_at_top_left,rgba(196,181,253,0.14),transparent_42%),linear-gradient(180deg,rgba(20,19,35,0.96),rgba(12,13,24,0.94))]",rose:"bg-[radial-gradient(circle_at_top_left,rgba(251,113,133,0.14),transparent_42%),linear-gradient(180deg,rgba(31,18,24,0.96),rgba(18,11,16,0.94))]",amber:"bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.14),transparent_42%),linear-gradient(180deg,rgba(32,24,16,0.96),rgba(20,15,10,0.94))]"};return e.jsxs("section",{className:te("min-w-0 overflow-hidden rounded-[30px] border border-white/8 px-4 py-5 shadow-[0_24px_70px_rgba(4,8,18,0.28)] sm:px-5 lg:px-6",o[r],l),children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsxs("div",{className:"mt-3 flex min-w-0 items-start gap-2",children:[e.jsx("h2",{className:"min-w-0 font-display text-[clamp(1.8rem,3.2vw,3rem)] leading-none text-white",children:s}),i?e.jsx(vt,{content:i,label:`Explain ${s.toLowerCase()}`,className:"mt-1 shrink-0"}):null]}),a?e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/60",children:a}):null,e.jsx("div",{className:"mt-5 min-w-0",children:n})]})}function UT({entries:t}){const s={away:"border-rose-400/20 bg-[rgba(251,113,133,0.08)]",committed:"border-emerald-400/20 bg-[rgba(110,231,183,0.08)]",recovery:"border-amber-400/20 bg-[rgba(251,191,36,0.08)]"};return e.jsx("div",{className:"grid gap-3 lg:grid-cols-3",children:t.map(a=>e.jsxs(Je,{to:a.href,className:`rounded-[22px] border px-4 py-4 transition hover:-translate-y-0.5 ${s[a.tone]}`,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:a.tone}),e.jsx("div",{className:"mt-2 font-medium text-white",children:a.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:a.summary}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 text-sm text-white/54",children:["Open",e.jsx(ha,{className:"size-3.5"})]})]},a.id))})}const WT={maladaptive:"Maladaptive schema",adaptive:"Adaptive schema"},HT={maladaptive:"A recurring pressure pattern that can distort how you interpret situations or respond.",adaptive:"A stable healthy belief pattern you want to strengthen and rely on."},GT={disconnection_rejection:"Disconnection & rejection",impaired_autonomy:"Autonomy & competence",other_directedness:"Boundaries & mutuality",overvigilance_inhibition:"Standards & inhibition",healthy_selfhood:"Healthy selfhood"};function Pd(t){return WT[t]}function Kn(t){return HT[t]}function Qm(t){return GT[t]??t.replaceAll("_"," ")}function Wr(t){return t==="adaptive"?{sectionTone:"border-emerald-400/14 bg-[linear-gradient(180deg,rgba(26,53,48,0.72),rgba(10,18,30,0.92))]",sectionEyebrow:"text-emerald-200/84",cardTone:"border-emerald-400/14 bg-[linear-gradient(180deg,rgba(28,63,56,0.44),rgba(14,24,36,0.92))]",badgeTone:"border-emerald-300/18 bg-[linear-gradient(135deg,rgba(16,185,129,0.18),rgba(56,189,248,0.12))] text-emerald-50",subtleBadgeTone:"border-emerald-300/12 bg-[rgba(16,185,129,0.1)] text-emerald-100/88",countLabel:"support links",linkSummary:"linked strengthening belief",emptyCopy:"No adaptive schema is linked yet. Add one when you want to capture the healthier pattern you are building from."}:{sectionTone:"border-fuchsia-400/14 bg-[linear-gradient(180deg,rgba(44,28,58,0.72),rgba(10,18,30,0.92))]",sectionEyebrow:"text-fuchsia-200/84",cardTone:"border-violet-400/14 bg-[linear-gradient(180deg,rgba(48,33,68,0.44),rgba(14,18,34,0.92))]",badgeTone:"border-rose-300/18 bg-[linear-gradient(135deg,rgba(244,63,94,0.16),rgba(168,85,247,0.12))] text-rose-50",subtleBadgeTone:"border-rose-300/12 bg-[rgba(244,63,94,0.1)] text-rose-100/88",countLabel:"linked records",linkSummary:"linked belief",emptyCopy:"No maladaptive schema is linked yet. Add one when you want to capture the recurring old pattern clearly."}}function ux(t){return t.trim().toLowerCase()}function ey(t,s){const a=ux(s);return[t.id,t.slug,t.title].some(i=>ux(i)===a)}function Hr(t,s){return s.find(a=>ey(a,t))??null}function ty(t,s){const a=t.filter(i=>!ey(s,i));return a.length===t.length?[...a,s.id]:a}function ni({label:t,schemaType:s,compact:a=!1,showType:i=!1,className:r}){const n=Wr(s);return e.jsxs("span",{className:te("inline-flex max-w-full min-w-0 items-center gap-2 rounded-full border px-3 py-1.5 text-sm leading-tight shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]",a?"min-h-8":"min-h-9",n.badgeTone,r),children:[i?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/58",children:Pd(s)}):null,e.jsx("span",{className:"min-w-0 break-words whitespace-normal",children:t})]})}function Ns(t,s,a,i){t.setQueryData(s,r=>{const n=(r==null?void 0:r[a])??[];return n.some(l=>l.id===i.id)?r:{...r??{},[a]:[i,...n]}})}const pt=Ke().trim(),qt=pt.min(1),QT=tt(qt).transform(t=>Array.from(new Set(t))),Ka=Ke().trim().min(1).nullable().optional(),mx=ft({title:qt,description:pt,valuedDirection:qt,whyItMatters:pt,linkedGoalIds:tt(Ke()).default([]),linkedProjectIds:tt(Ke()).default([]),linkedTaskIds:tt(Ke()).default([]),committedActions:tt(pt).default([]),userId:Ka}),hx=ft({title:qt,description:pt,targetBehavior:qt,cueContexts:tt(pt).default([]),shortTermPayoff:pt,longTermCost:pt,preferredResponse:qt,linkedValueIds:tt(Ke()).default([]),linkedSchemaLabels:QT.default([]),linkedModeIds:tt(Ke()).default([]),linkedBeliefIds:tt(Ke()).default([]),userId:Ka}),px=ft({kind:Ft(["away","committed","recovery"]),title:qt,description:pt,commonCues:tt(pt).default([]),urgeStory:pt,shortTermPayoff:pt,longTermCost:pt,replacementMove:pt,repairPlan:pt,linkedPatternIds:tt(Ke()).default([]),linkedValueIds:tt(Ke()).default([]),linkedSchemaIds:tt(Ke()).default([]),linkedModeIds:tt(Ke()).default([]),userId:Ka}),xx=ft({schemaId:Ke().nullable(),statement:qt,beliefType:Ft(["absolute","conditional"]),originNote:pt,confidence:Ru().int().min(0).max(100),evidenceFor:tt(pt).default([]),evidenceAgainst:tt(pt).default([]),flexibleAlternative:pt,linkedValueIds:tt(Ke()).default([]),linkedBehaviorIds:tt(Ke()).default([]),linkedModeIds:tt(Ke()).default([]),linkedReportIds:tt(Ke()).default([]),userId:Ka}),gx=ft({family:Ft(["coping","child","critic_parent","healthy_adult","happy_child"]),archetype:pt,title:qt,persona:pt,imagery:pt,symbolicForm:pt,facialExpression:pt,fear:pt,burden:pt,protectiveJob:pt,originContext:pt,firstAppearanceAt:Ke().trim().nullable(),linkedPatternIds:tt(Ke()).default([]),linkedBehaviorIds:tt(Ke()).default([]),linkedValueIds:tt(Ke()).default([]),userId:Ka}),VT=ft({summary:qt,answers:tt(ft({questionKey:qt,value:qt})).min(1),userId:Ka});ft({label:qt,description:pt,userId:Ka});ft({label:qt,description:pt,category:pt,userId:Ka});const XT=ft({id:qt,emotionDefinitionId:Ke().nullable(),label:qt,intensity:Ru().int().min(0).max(100),note:pt}),YT=ft({id:qt,text:qt,parentMode:pt,criticMode:pt,beliefId:Ke().nullable()}),JT=ft({id:qt,text:qt,mode:pt,behaviorId:Ke().nullable()}),ZT=ft({id:qt,stage:qt,modeId:Ke().nullable(),label:qt,note:pt}),Nu=ft({title:qt,status:Ft(["draft","reviewed","integrated"]).default("draft"),eventTypeId:Ke().nullable(),customEventType:pt,eventSituation:qt,occurredAt:Ke().trim().nullable(),emotions:tt(XT).default([]),thoughts:tt(YT).default([]),behaviors:tt(JT).default([]),consequences:ft({selfShortTerm:tt(pt).default([]),selfLongTerm:tt(pt).default([]),othersShortTerm:tt(pt).default([]),othersLongTerm:tt(pt).default([])}),linkedPatternIds:tt(Ke()).default([]),linkedValueIds:tt(Ke()).default([]),linkedGoalIds:tt(Ke()).default([]),linkedProjectIds:tt(Ke()).default([]),linkedTaskIds:tt(Ke()).default([]),linkedBehaviorIds:tt(Ke()).default([]),linkedBeliefIds:tt(Ke()).default([]),linkedModeIds:tt(Ke()).default([]),modeOverlays:tt(pt).default([]),schemaLinks:tt(pt).default([]),modeTimeline:tt(ZT).default([]),nextMoves:tt(pt).default([]),userId:Ka}),Nn={kind:"away",title:"",description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:null};function eP(t){return{kind:t.kind,title:t.title,description:t.description,commonCues:t.commonCues,urgeStory:t.urgeStory,shortTermPayoff:t.shortTermPayoff,longTermCost:t.longTermCost,replacementMove:t.replacementMove,repairPlan:t.repairPlan,linkedPatternIds:t.linkedPatternIds,linkedValueIds:t.linkedValueIds,linkedSchemaIds:t.linkedSchemaIds,linkedModeIds:t.linkedModeIds,userId:t.userId??null}}const fx={away:"Away moves",committed:"Committed actions",recovery:"Recovery moves"};function tP(){var J,q,_,B,G,ae,ke,Ae,ie,Ie,Ne;const t=jt(),s=ct(),[a,i]=ms(),[r,n]=c.useState(!1),[l,o]=c.useState(null),[d,m]=c.useState(Nn),[h,u]=c.useState(null),x=Fe({queryKey:["forge-psyche-behaviors"],queryFn:Xs}),g=Fe({queryKey:["forge-psyche-patterns"],queryFn:Oa}),p=Fe({queryKey:["forge-psyche-values"],queryFn:Vs}),f=Fe({queryKey:["forge-psyche-schema-catalog"],queryFn:fl}),b=Fe({queryKey:["forge-psyche-modes"],queryFn:za}),A=((J=x.data)==null?void 0:J.behaviors)??[],C=((q=g.data)==null?void 0:q.patterns)??[],T=((_=p.data)==null?void 0:_.values)??[],w=((B=f.data)==null?void 0:B.schemas)??[],S=((G=b.data)==null?void 0:G.modes)??[],y=ys(t.selectedUserIds),N=a.get("focus"),P=t.snapshot.dashboard.notesSummaryByEntity;Zr(N),c.useEffect(()=>{if(a.get("create")==="1"){n(!0),o(null),m({...Nn,userId:y});const M=new URLSearchParams(a);M.delete("create"),i(M,{replace:!0})}},[y,a,i]);const v=Re({mutationFn:async M=>{const E=px.parse(M);return l?Uj(l.id,E):hd(E)},onSuccess:async()=>{n(!1),o(null),m({...Nn,userId:y}),u(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-behaviors"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),H=C.map(M=>({value:M.id,label:Dt(M.title,M.user),description:ut(M.preferredResponse||M.targetBehavior,M.user),searchText:dt([M.title,M.preferredResponse,M.targetBehavior,M.description],M),kind:"pattern"})),j=T.map(M=>({value:M.id,label:Dt(M.title,M.user),description:ut(M.valuedDirection,M.user),searchText:dt([M.title,M.valuedDirection,M.description],M),kind:"value"})),R=w.map(M=>({value:M.id,label:M.title,description:`${M.description} ${Qm(M.family)}`,searchText:`${M.slug} ${M.family} ${M.schemaType}`,badge:e.jsx(ni,{label:M.title,schemaType:M.schemaType,compact:!0}),menuBadge:e.jsx(ni,{label:M.title,schemaType:M.schemaType,compact:!0})})),Q=S.map(M=>({value:M.id,label:Dt(M.title,M.user),description:ut(M.archetype||M.family,M.user),searchText:dt([M.title,M.archetype,M.family,M.persona],M),kind:"mode"})),X=async M=>{const{pattern:E}=await Ju({title:M,description:"",targetBehavior:M,cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[],userId:d.userId});return Ns(s,["forge-psyche-patterns"],"patterns",E),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:E.id,label:E.title,description:E.preferredResponse||E.targetBehavior,kind:"pattern"}},Y=async M=>{const{value:E}=await Vr({title:M,description:"",valuedDirection:M,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:d.userId});return Ns(s,["forge-psyche-values"],"values",E),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:E.id,label:E.title,description:E.valuedDirection,kind:"value"}},z=async M=>{const{mode:E}=await bl({family:"coping",archetype:"",title:M,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:d.userId});return Ns(s,["forge-psyche-modes"],"modes",E),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:E.id,label:E.title,description:E.archetype||E.family,kind:"mode"}},K=[{id:"behavior",eyebrow:"Behavior",title:"Describe the move or urge in plain language",description:"Start with the behavior itself so the map reads like something you can instantly recognize in real life.",render:(M,E)=>e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:M.userId??null,users:t.snapshot.users,onChange:O=>E({userId:O}),defaultLabel:Ys(t.snapshot.users.find(O=>O.id===y)??null,"Choose behavior owner"),help:"Behaviors can belong to a human or bot user while still linking across shared patterns, schemas, and modes."}),e.jsx(de,{label:"Behavior title",children:e.jsx(ye,{value:M.title,onChange:O=>E({title:O.target.value}),placeholder:"Scroll to numb the impact"})}),e.jsx(de,{label:"What does the move look like?",children:e.jsx(Ze,{value:M.description,onChange:O=>E({description:O.target.value}),placeholder:"Describe the move the way you would recognize it in the moment, not in therapist shorthand."})})]})},{id:"context",eyebrow:"Context",title:"Capture the cue, the pull, and the immediate payoff",description:"Make the move readable as a real pattern instead of a label.",render:(M,E)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Common cues",children:e.jsx(Ze,{value:M.commonCues.join(`
28
28
  `),onChange:O=>E({commonCues:O.target.value.split(`
29
29
  `).map(xe=>xe.trim()).filter(Boolean)}),placeholder:`One line per cue
30
30
  Late-night ambiguity
@@ -88,4 +88,4 @@ ${g.trim()}
88
88
  `):s}function pE(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 xE(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 gE(t,s){return Oy(t,s)[0]??null}function Oy(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 m=i.get(d.source),h=i.get(d.target),u=(m==null?void 0:m.data.outputs)??[],x=(h==null?void 0:h.data.inputs)??[];m&&(d.sourceHandle&&!u.some(g=>g.key===d.sourceHandle)?a.push(`Edge from "${m.data.label}" points to missing output "${d.sourceHandle}". Update the edge or restore that output contract.`):!d.sourceHandle&&u.length>1&&a.push(`Edge from "${m.data.label}" does not name which output it should use. Pick one explicit output handle.`)),h&&(d.targetHandle&&!x.some(g=>g.key===d.targetHandle)?a.push(`Edge into "${h.data.label}" points to missing input "${d.targetHandle}". Update the edge or restore that input contract.`):!d.targetHandle&&x.length>1&&a.push(`Edge into "${h.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 m=s.filter(h=>h.target===d.id).flatMap(h=>{const u=i.get(h.source),x=(u==null?void 0:u.data.outputs)??[];return h.sourceHandle?x.filter(g=>g.key===h.sourceHandle).map(g=>g.key):x.map(g=>g.key)});d.data.outputKey&&m.length>0&&!m.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 m=n.get(d.id)??0,h=s.filter(u=>u.source===d.id).length;d.data.nodeType!=="user_input"&&d.data.nodeType!=="value"&&m===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"&&m<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"&&h===0&&a.push(`Connect the output of "${d.data.label}" somewhere useful or remove the node from the graph.`)}for(const d of t)Ln(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 Tn({open:t,onOpenChange:s,title:a,description:i,children:r}){return e.jsx(Yt,{open:t,onOpenChange:s,children:e.jsxs(Jt,{children:[e.jsx(Zt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs(es,{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(ts,{className:"font-display text-[1.28rem] tracking-[-0.04em] text-white",children:a}),i?e.jsx(rs,{className:"mt-1 text-sm leading-6 text-white/54",children:i}):null]}),e.jsx(Qt,{asChild:!0,children:e.jsx(Zi,{"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 ng({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($y),edges:n.map(rE)}}}function fE({flow:t,boxes:s,modelConnections:a,runs:i,onSave:r,onDelete:n,onRun:l,onChat:o}){var k,se,_e,Be,Ge,gt,Mt,Vt,Os,qa,Ba,tn,sn,an,rn,nn,ln,on,dn,cn,un,mn;const[d,m]=c.useState(t.title),[h,u]=c.useState(t.description),[x,g]=c.useState(t.kind),[p,f]=c.useState(t.publicInputs??[]),[b,A]=c.useState(()=>_c(t,s).nodes),[C,T]=c.useState(()=>_c(t,s).edges),[w,S]=c.useState(null),[y,N]=c.useState(!1),[P,v]=c.useState(!1),[H,j]=c.useState("overview"),[R,Q]=c.useState(void 0),[X,Y]=c.useState(!1),[z,K]=c.useState(!1),[$,D]=c.useState(!1),[J,q]=c.useState(""),[_,B]=c.useState([]),[G,ae]=c.useState(""),[ke,Ae]=c.useState({}),[ie,Ie]=c.useState(!0),[Ne,M]=c.useState(null),[E,O]=c.useState("idle"),[xe,V]=c.useState(null),[Se,Ee]=c.useState(((k=i[0])==null?void 0:k.id)??null),[Ce,qe]=c.useState(null),oe=c.useMemo(()=>JSON.stringify(ng({title:t.title,description:t.description,kind:t.kind,publicInputs:t.publicInputs??[],nodes:t.graph.nodes.map(ue=>Au(ue,s)),edges:t.graph.edges.map(Ry)})),[s,t]),L=c.useRef(oe),U=c.useRef(oe),ge=c.useRef({}),Te=c.useRef(oe),ve=c.useRef(null),Le=c.useRef(!1);c.useEffect(()=>{if(oe===U.current)return;U.current=oe,L.current=oe,Te.current=oe,m(t.title),u(t.description),g(t.kind),f(t.publicInputs??[]);const ue=_c(t,s);A(ue.nodes),T(ue.edges),O("idle"),V(null)},[s,t,oe]),c.useEffect(()=>{Ae(Object.fromEntries((t.publicInputs??[]).filter(ue=>ue.defaultValue!==void 0).map(ue=>[ue.key,ue.defaultValue])))},[t.publicInputs]),c.useEffect(()=>{var ue;Ee(((ue=i[0])==null?void 0:ue.id)??null)},[i]),c.useEffect(()=>{A(ue=>ue.map(Oe=>Oe.data.nodeType!=="box"||!Oe.data.boxId?Oe:Au($y(Oe),s)))},[s]);const Qe=c.useMemo(()=>Array.from(new Set(s.map(Oe=>Oe.category))).map(Oe=>({id:`category:${Oe}`,label:Oe,description:"Workbench box category"})),[s]),st=c.useMemo(()=>{const ue=J.trim().toLowerCase();return s.filter(Oe=>{const Ye=ue.length===0||[Oe.title,Oe.description,Oe.category,Oe.routePath??"",...Oe.tags].join(" ").toLowerCase().includes(ue),It=_.every(At=>At.startsWith("category:")?Oe.category===At.replace("category:",""):!0);return Ye&&It})},[_,J,s]),F=c.useMemo(()=>b.find(ue=>ue.id===w)??null,[b,w]),he=i[0]??null,we=i.find(ue=>ue.id===Se)??he??null,Z=eS({flowId:t.id,runId:Se??""},{skip:!Se||!$}),De=((se=Z.data)==null?void 0:se.nodeResults.find(ue=>ue.nodeId===Ce))??null,ee=Z2({flowId:t.id,runId:Se??"",nodeId:Ce??""},{skip:!Se||!Ce||!$}),ze=c.useMemo(()=>Oy(b,C),[b,C]),et=c.useMemo(()=>b.some(ue=>Ln(ue.data.nodeType)),[b]),Ve=c.useMemo(()=>b.some(ue=>ue.data.nodeType==="user_input")||(p??[]).length===0,[b,p]);c.useEffect(()=>{var Oe,Ye;const ue=((Ye=(Oe=Z.data)==null?void 0:Oe.nodeResults[0])==null?void 0:Ye.nodeId)??null;qe(ue)},[(_e=Z.data)==null?void 0:_e.nodeResults]);const re=c.useMemo(()=>!!(F&&F.data.nodeType!=="box"&&F.data.nodeType!=="box_input"),[F]),ne=c.useMemo(()=>F?C.filter(ue=>ue.target===F.id).flatMap(ue=>{const Oe=b.find(It=>It.id===ue.source),Ye=(Oe==null?void 0:Oe.data.outputs)??[];return ue.sourceHandle?Ye.filter(It=>It.key===ue.sourceHandle):Ye}):[],[C,b,F]),be=c.useMemo(()=>tE(s),[s]),je=c.useMemo(()=>{if(!F||!Ln(F.data.nodeType))return[];const ue=new Set(F.data.enabledToolKeys??[]);return be.filter(Oe=>ue.has(Oe.key))},[be,F]),pe=c.useMemo(()=>ng({title:d,description:h,kind:x,publicInputs:p,nodes:b,edges:C}),[h,C,x,b,p,d]),$e=c.useMemo(()=>JSON.stringify(pe),[pe]),Xe=$e!==L.current;c.useEffect(()=>{if(ge.current=pe,Te.current=$e,$e===L.current){V(null),O(ue=>ue==="saved"?ue:"idle");return}O(ue=>ue==="saving"?ue:"dirty")},[$e]);const Ue=c.useMemo(()=>!F||!Ln(F.data.nodeType)?[]:[{id:"overview",eyebrow:F.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:(ue,Oe)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Label",description:"This is the name shown on the canvas and in debug traces.",children:e.jsx("input",{value:ue.label,onChange:Ye=>Oe({label:Ye.target.value}),className:ht})}),e.jsx(de,{label:"Description",description:"Explain what this node should do with the incoming flow context.",children:e.jsx("textarea",{rows:4,value:ue.description,onChange:Ye=>Oe({description:Ye.target.value}),className:ht})})]})},{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:(ue,Oe)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{label:"Prompt template",description:"This is the main instruction the node sends with the current flow input.",children:e.jsx("textarea",{rows:8,value:ue.promptTemplate??ue.prompt??"",onChange:Ye=>Oe({promptTemplate:Ye.target.value,prompt:Ye.target.value}),className:ht})}),e.jsx(de,{label:"System prompt",description:"Use this for durable behavior and output rules that should stay consistent.",children:e.jsx("textarea",{rows:5,value:ue.systemPrompt??"",onChange:Ye=>Oe({systemPrompt:Ye.target.value}),className:ht})})]})},{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:(ue,Oe)=>{var Ye,It,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(de,{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:((Ye=ue.modelConfig)==null?void 0:Ye.connectionId)??"",onChange:kt=>{var ea,ta;const as=a.find(hs=>hs.id===kt.target.value);Oe({modelConfig:{connectionId:(as==null?void 0:as.id)??null,provider:(as==null?void 0:as.provider)??null,baseUrl:(as==null?void 0:as.baseUrl)??null,model:(as==null?void 0:as.model)??"",thinking:((ea=ue.modelConfig)==null?void 0:ea.thinking)??null,verbosity:((ta=ue.modelConfig)==null?void 0:ta.verbosity)??null}})},className:ht,children:[e.jsx("option",{value:"",children:"Use Forge default model"}),a.map(kt=>e.jsx("option",{value:kt.id,children:kt.label},kt.id))]})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(de,{label:"Thinking effort",description:"Optional reasoning setting for models that support it.",children:e.jsxs("select",{value:((It=ue.modelConfig)==null?void 0:It.thinking)??"",onChange:kt=>{var as,ea,ta,hs,hn;return Oe({modelConfig:{connectionId:((as=ue.modelConfig)==null?void 0:as.connectionId)??null,provider:((ea=ue.modelConfig)==null?void 0:ea.provider)??null,baseUrl:((ta=ue.modelConfig)==null?void 0:ta.baseUrl)??null,model:((hs=ue.modelConfig)==null?void 0:hs.model)??"",thinking:kt.target.value||null,verbosity:((hn=ue.modelConfig)==null?void 0:hn.verbosity)??null}})},className:ht,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(de,{label:"Verbosity",description:"Optional output detail setting for models that support it.",children:e.jsxs("select",{value:((At=ue.modelConfig)==null?void 0:At.verbosity)??"",onChange:kt=>{var as,ea,ta,hs,hn;return Oe({modelConfig:{connectionId:((as=ue.modelConfig)==null?void 0:as.connectionId)??null,provider:((ea=ue.modelConfig)==null?void 0:ea.provider)??null,baseUrl:((ta=ue.modelConfig)==null?void 0:ta.baseUrl)??null,model:((hs=ue.modelConfig)==null?void 0:hs.model)??"",thinking:((hn=ue.modelConfig)==null?void 0:hn.thinking)??null,verbosity:kt.target.value||null}})},className:ht,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:(ue,Oe)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(go,{title:"Inputs",description:"Name the upstream values this AI node expects to receive.",ports:ue.inputs??[],onChange:Ye=>Oe({inputs:Ye}),prefix:"input"}),e.jsx(go,{title:"Outputs",description:"Describe exactly what this AI node will publish for later nodes.",ports:ue.outputs??[],onChange:Ye=>Oe({outputs:Ye}),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:(ue,Oe)=>e.jsxs(e.Fragment,{children:[e.jsx(de,{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:be.length>0?be.map(Ye=>{const It=(ue.enabledToolKeys??[]).includes(Ye.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:It,onChange:At=>{const kt=new Set(ue.enabledToolKeys??[]);At.target.checked?kt.add(Ye.key):kt.delete(Ye.key),Oe({enabledToolKeys:[...kt]})}}),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:Ye.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:Ye.accessMode.replace("_"," ")})]}),e.jsx("div",{className:"text-[12px] leading-5 text-white/46",children:Ye.description}),Ye.sources.length>0?e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Ye.sources.map(At=>e.jsx("span",{className:"rounded-full bg-white/[0.05] px-2 py-1 text-[10px] text-white/44",children:At},`${Ye.key}-${At}`))}):null,e.jsx("div",{className:"mt-1 font-mono text-[10px] text-white/32",children:Ye.key}),Ye.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(Ye.argsSchema,null,2)})]}):null]})]},Ye.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(de,{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:je.length>0?`${je.length} tool contract${je.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(je.map(Ye=>({key:Ye.key,label:Ye.label,accessMode:Ye.accessMode,sources:Ye.sources,argsSchema:Ye.argsSchema})),null,2)})]})}),e.jsx(de,{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:[(ue.outputs??[]).length," published output",(ue.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(pE(ue.outputs??[]),null,2)})]})})]}),e.jsx(de,{label:"Named outputs",description:"Add comma-separated output keys when later nodes should read more than the primary answer.",children:e.jsx("input",{value:(ue.outputs??[]).filter(Ye=>Ye.key!=="answer").map(Ye=>Ye.key).join(", "),onChange:Ye=>Oe({outputs:xE(["answer",...Ye.target.value.split(",")])}),placeholder:"summary, plan, next_steps",className:ht})}),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(W,{type:"button",variant:"secondary",className:"mt-4",onClick:()=>{Nt(F.id),v(!1)},children:[e.jsx(Rt,{className:"size-4"}),"Delete node"]})]})]})}],[be,a,je,F]),le=c.useCallback(async()=>{const ue=Te.current,Oe=ge.current;if(ue===L.current)return O("saved"),!0;if(ve.current)return Le.current=!0,ve.current;O("saving"),V(null);const Ye=r(Oe).then(()=>(L.current=ue,U.current=ue,O("saved"),!0)).catch(It=>{const At=It instanceof Ia||It instanceof Error?It.message:String(It);return V(At),O("error"),!1}).finally(()=>{ve.current=null,Le.current&&Te.current!==L.current?(Le.current=!1,le()):Le.current=!1});return ve.current=Ye,Ye},[r]);c.useEffect(()=>{if(!Xe)return;const ue=window.setTimeout(()=>{le()},2e3);return()=>window.clearTimeout(ue)},[Xe,le,$e]);const Me=c.useCallback((ue,Oe="overview")=>{S(ue),j(Oe),Q(Oe==="contracts"?"contracts":"overview"),v(!0)},[]),He=c.useMemo(()=>b.map(ue=>({...ue,data:{...ue.data,onEditRequest:()=>Me(ue.id,"overview"),onContractEditRequest:()=>Me(ue.id,"contracts"),onParameterEditRequest:()=>Me(ue.id,"parameters")}})),[b,Me]);function lt(ue){w&&A(Oe=>Oe.map(Ye=>Ye.id===w?ue(Ye):Ye))}function Nt(ue){A(Oe=>Oe.filter(Ye=>Ye.id!==ue)),T(Oe=>Oe.filter(Ye=>Ye.source!==ue&&Ye.target!==ue)),S(Oe=>Oe===ue?null:Oe)}async function me(){await le()}async function Pe(ue){if(!await le()){M("Forge could not save the latest flow changes before running. Fix the save error and try again.");return}const Ye=gE(b,C);if(Ye){M(Ye);return}if(et&&a.length===0){M(["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(`
89
89
 
90
90
  `));return}M(null);const It={};for(const At of p){const kt=ke[At.key];if(!sE(At,kt)){M(`Flow input "${At.label}" must match the ${At.kind} type.`);return}kt!=null&&!(typeof kt=="string"&&kt.trim().length===0)&&(It[At.key]=kt)}try{ue==="run"?await l({userInput:Ve?G:"",inputs:It,debug:ie}):await o({userInput:Ve?G:"",inputs:It,debug:ie}),Y(!1)}catch(At){M(hE(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(Je,{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(Gn,{className:"size-4"}),"Flows"]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(We,{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(We,{kind:zg(x),label:x==="chat"?"Chat flow":"Functor flow",compact:!0,gradient:!1}),e.jsx("div",{className:te("rounded-full border px-3 py-2 text-[12px]",E==="error"?"border-rose-300/20 bg-rose-300/10 text-rose-100":E==="saving"?"border-sky-300/20 bg-sky-300/10 text-sky-100":E==="dirty"?"border-amber-300/20 bg-amber-300/10 text-amber-100":"border-emerald-300/20 bg-emerald-300/10 text-emerald-100"),children:lE(E,xe)}),he?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:()=>D(!0),children:["Latest ",he.mode," · ",he.status]}):null,e.jsxs(W,{type:"button",variant:"secondary",onClick:()=>Y(!0),children:[e.jsx(Hs,{className:"size-4"}),"Run"]}),e.jsxs(W,{type:"button",variant:"primary",pending:E==="saving",pendingLabel:"Saving…",onClick:()=>void me(),children:[e.jsx(oi,{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:[ze.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(vt,{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:ze.map(ue=>e.jsx("li",{className:"list-inside list-disc",children:ue},ue))})]}):null,e.jsx(id,{nodeTypes:mE,nodes:He,edges:C,onNodesChange:ue=>A(Oe=>j0(ue,Oe)),onEdgesChange:ue=>T(Oe=>v0(ue,Oe)),onConnect:ue=>T(Oe=>y0({...ue,id:`edge_${crypto.randomUUID().replaceAll("-","").slice(0,8)}`,style:{stroke:"rgba(188, 194, 255, 0.44)",strokeWidth:1.6}},Oe)),onEdgeClick:(ue,Oe)=>{T(Ye=>Ye.filter(It=>It.id!==Oe.id))},onNodeClick:(ue,Oe)=>{S(Oe.id)},onNodeDoubleClick:(ue,Oe)=>{Me(Oe.id,"overview")},fitView:!0,proOptions:{hideAttribution:!0},className:"bg-transparent",children:e.jsx(rd,{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:()=>N(!0),children:[e.jsx(Di,{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:()=>K(!0),children:[e.jsx(Po,{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(Hs,{className:"size-4"}),"Run flow"]}),he?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:()=>D(!0),children:[e.jsx(N0,{className:"size-4"}),"Latest trace"]}):null]})})]}),e.jsx(Tn,{open:y,onOpenChange:N,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(Lg,{className:"size-4"})},{type:"functor",label:"Functor",icon:e.jsx(Wt,{className:"size-4"})},{type:"chat",label:"Chat",icon:e.jsx(ma,{className:"size-4"})},{type:"merge",label:"Merge",icon:e.jsx(Dg,{className:"size-4"})},{type:"template",label:"Template",icon:e.jsx(Mo,{className:"size-4"})},{type:"pick_key",label:"Pick key",icon:e.jsx(Fg,{className:"size-4"})},{type:"output",label:"Output",icon:e.jsx(_g,{className:"size-4"})}].map(ue=>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:()=>{A(Oe=>[...Oe,ig(ue.type,Oe)]),N(!1)},children:[ue.icon,e.jsx("span",{children:ue.label})]},ue.type))}),e.jsx(mi,{title:"Forge boxes",description:"",query:J,onQueryChange:q,options:Qe,selectedOptionIds:_,onSelectedOptionIdsChange:B,resultSummary:`${st.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:st.map(ue=>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:()=>{A(Oe=>[...Oe,ig("box",Oe,ue)]),N(!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:ue.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:[ue.output.length," output",ue.output.length===1?"":"s"]}),e.jsxs("span",{children:[ue.tools.length," tool",ue.tools.length===1?"":"s"]})]})]}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/50",children:ue.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:ue.category}),ue.routePath?e.jsx("div",{className:"rounded-full bg-white/[0.05] px-2.5 py-1 text-[11px] text-white/56",children:ue.routePath}):null]})]},ue.id))})]})}),F&&Ln(F.data.nodeType)?e.jsx(Lt,{open:P,onOpenChange:ue=>{v(ue),ue||Q(void 0)},eyebrow:`Workbench · ${F.data.nodeType==="chat"?"Chat node":"Functor node"}`,title:F.data.label??"Edit node",description:"Configure this AI node with the same paged editor Forge uses elsewhere.",value:F.data,onChange:ue=>lt(Oe=>({...Oe,data:ue})),draftPersistenceKey:`workbench.ai-node.${F.id}`,steps:Ue,initialStepId:R,onSubmit:async()=>{v(!1),Q(void 0)},submitLabel:"Done",contentClassName:"md:w-[min(60rem,calc(100vw-1.5rem))]"}):e.jsx(Tn,{open:P,onOpenChange:ue=>{v(ue),ue||j("overview")},title:(F==null?void 0:F.data.label)??"Edit node",description:"Edit the selected node without covering the graph with permanent forms.",children:F?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(ue=>ue.id!=="contracts"||re).filter(ue=>{var Oe;return ue.id!=="parameters"||(((Oe=F.data.params)==null?void 0:Oe.length)??0)>0}).map(ue=>e.jsx("button",{type:"button",className:te("rounded-full px-3 py-2 text-sm transition",H===ue.id?"bg-[rgba(192,193,255,0.18)] text-white":"text-white/58 hover:bg-white/[0.05] hover:text-white"),onClick:()=>j(ue.id),children:ue.label},ue.id))}),H==="overview"?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("input",{value:F.data.label,onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,label:ue.target.value}})),className:ht}),e.jsx("textarea",{rows:3,value:F.data.description,onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,description:ue.target.value}})),className:ht}),F.data.nodeType==="box"||F.data.nodeType==="box_input"?e.jsxs("select",{value:F.data.boxId??"",onChange:ue=>{const Oe=s.find(Ye=>Ye.id===ue.target.value);lt(Ye=>({...Ye,data:{...Ye.data,boxId:ue.target.value,label:(Oe==null?void 0:Oe.title)??Ye.data.label,description:(Oe==null?void 0:Oe.description)??Ye.data.description,inputs:(Oe==null?void 0:Oe.inputs)??[],outputs:(Oe==null?void 0:Oe.output)??[],params:(Oe==null?void 0:Oe.params)??[],enabledToolKeys:((Oe==null?void 0:Oe.tools)??[]).map(It=>It.key)}}))},className:ht,children:[e.jsx("option",{value:"",children:"Select Forge box"}),s.map(ue=>e.jsx("option",{value:ue.id,children:ue.title},ue.id))]}):null,F.data.nodeType==="template"?e.jsx("textarea",{rows:4,value:F.data.template??"",onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,template:ue.target.value}})),placeholder:"Template string",className:ht}):null,F.data.nodeType==="pick_key"?e.jsx("input",{value:F.data.selectedKey??"",onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,selectedKey:ue.target.value}})),placeholder:"Key to select from object input",className:ht}):null,F.data.nodeType==="output"?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("select",{value:F.data.outputKey??"answer",onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,outputKey:ue.target.value}})),className:ht,children:ne.length>0?ne.map(ue=>e.jsxs("option",{value:ue.key,children:[ue.label," (",ue.key,")"]},ue.key)):e.jsx("option",{value:F.data.outputKey??"answer",children:F.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,F.data.nodeType==="value"?e.jsxs(e.Fragment,{children:[e.jsx("select",{value:F.data.valueType??"string",onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,valueType:ue.target.value}})),className:ht,children:["string","number","boolean","null","array","object"].map(ue=>e.jsx("option",{value:ue,children:ue},ue))}),e.jsx("textarea",{rows:4,value:F.data.valueLiteral??"",onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,valueLiteral:ue.target.value}})),placeholder:"Value literal or JSON",className:ht})]}):null]}):null,H==="contracts"?re?e.jsxs("div",{className:"grid gap-4",children:[e.jsx(go,{title:"Inputs",description:"Name the values this node expects so upstream wiring stays obvious.",ports:F.data.inputs??[],onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,inputs:ue}})),prefix:"input"}),e.jsx(go,{title:"Outputs",description:"Describe exactly what this node publishes, including semantic model names.",ports:F.data.outputs??[],onChange:ue=>lt(Oe=>({...Oe,data:{...Oe.data,outputs:ue}})),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,H==="parameters"?e.jsxs("div",{className:"grid gap-3",children:[(F.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,(F.data.params??[]).map(ue=>{var Oe,Ye,It;return e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:ue.label}),ue.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:!!((Oe=F.data.paramValues)!=null&&Oe[ue.key]),onChange:At=>lt(kt=>({...kt,data:{...kt.data,paramValues:{...kt.data.paramValues??{},[ue.key]:At.target.checked}}}))}),ue.description??"Enabled"]}):ue.kind==="array"||ue.kind==="json"?e.jsx("textarea",{value:Io((Ye=F.data.paramValues)==null?void 0:Ye[ue.key]),onChange:At=>lt(kt=>({...kt,data:{...kt.data,paramValues:{...kt.data.paramValues??{},[ue.key]:At.target.value}}})),placeholder:ue.description??ue.label,className:te(ht,"min-h-[104px] resize-y")}):e.jsx("input",{type:ue.kind==="number"?"number":"text",value:Io((It=F.data.paramValues)==null?void 0:It[ue.key]),onChange:At=>lt(kt=>({...kt,data:{...kt.data,paramValues:{...kt.data.paramValues??{},[ue.key]:Dy(ue.kind,At.target.value)}}})),placeholder:ue.description??ue.label,className:ht})]},ue.key)})]}):null,e.jsxs("div",{className:"flex flex-wrap justify-between gap-2 pt-2",children:[e.jsxs(W,{type:"button",variant:"secondary",onClick:()=>{Nt(F.id),v(!1)},children:[e.jsx(Rt,{className:"size-4"}),"Delete node"]}),e.jsx(W,{type:"button",variant:"primary",onClick:()=>{v(!1),j("overview")},children:"Done"})]})]}):null}),e.jsx(Tn,{open:z,onOpenChange:K,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:ue=>m(ue.target.value),placeholder:"Flow title",className:ht}),e.jsx("textarea",{rows:4,value:h,onChange:ue=>u(ue.target.value),placeholder:"Flow description",className:ht}),e.jsxs("select",{value:x,onChange:ue=>g(ue.target.value),className:ht,children:[e.jsx("option",{value:"functor",children:"Functor flow"}),e.jsx("option",{value:"chat",children:"Chat flow"})]}),e.jsx(cE,{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(W,{type:"button",variant:"secondary",onClick:async()=>{await n()},children:[e.jsx(Rt,{className:"size-4"}),"Delete flow"]}),e.jsxs(W,{type:"button",variant:"primary",onClick:async()=>{await me(),K(!1)},children:[e.jsx(oi,{className:"size-4"}),"Save settings"]})]})]})}),e.jsx(Tn,{open:X,onOpenChange:ue=>{Y(ue),ue&&M(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:[Ne?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:Ne}):null,!Ne&&ze.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:ze.slice(0,4).map(ue=>e.jsxs("li",{children:["• ",ue]},ue))})]}):null,!Ne&&et&&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(vt,{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(ue=>e.jsx(de,{label:ue.label,description:ue.description||"Typed input for this flow.",children:ue.kind==="boolean"?e.jsxs("label",{className:"flex items-center gap-2 text-sm text-white/68",children:[e.jsx("input",{type:"checkbox",checked:!!ke[ue.key],onChange:Oe=>Ae(Ye=>({...Ye,[ue.key]:Oe.target.checked}))}),ue.label]}):ue.kind==="number"?e.jsx("input",{type:"number",value:typeof ke[ue.key]=="number"?String(ke[ue.key]):"",onChange:Oe=>Ae(Ye=>({...Ye,[ue.key]:Oe.target.value.trim().length===0?void 0:Number(Oe.target.value)})),className:ht}):ue.kind==="array"||ue.kind==="entity_list"||ue.kind==="record_list"||ue.kind==="object"||ue.kind==="json"||ue.kind==="record"||ue.kind==="context"||ue.kind==="filters"||ue.kind==="metrics"||ue.kind==="timeline"||ue.kind==="selection"||ue.kind==="entity"?e.jsx("textarea",{rows:4,value:Io(ke[ue.key]),onChange:Oe=>{const Ye=Oe.target.value;let It=Ye;if(!Ye.trim())It=void 0;else try{It=JSON.parse(Ye)}catch{It=Ye}Ae(At=>({...At,[ue.key]:It}))},placeholder:'{"key":"value"}',className:ht}):e.jsx("input",{value:typeof ke[ue.key]=="string"?ke[ue.key]:"",onChange:Oe=>Ae(Ye=>({...Ye,[ue.key]:Oe.target.value})),placeholder:ue.exampleValue||ue.label,className:ht})},ue.key))})]}):null,Ve?e.jsx("textarea",{rows:5,value:G,onChange:ue=>ae(ue.target.value),placeholder:"User input",className:ht}):null,e.jsxs("label",{className:"flex items-center gap-2 text-sm text-white/64",children:[e.jsx("input",{type:"checkbox",checked:ie,onChange:ue=>Ie(ue.target.checked)}),"Return debug trace"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(W,{type:"button",variant:"primary",onClick:()=>void Pe("run"),children:[e.jsx(Hs,{className:"size-4"}),"Run"]}),e.jsxs(W,{type:"button",variant:"secondary",onClick:()=>void Pe("chat"),children:[e.jsx(Rg,{className:"size-4"}),"Chat"]})]}),e.jsx("div",{className:"grid gap-2 pt-2",children:i.slice(0,5).map(ue=>{var Oe;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:ue.mode}),e.jsx("span",{children:new Date(ue.createdAt).toLocaleString()})]}),e.jsx("div",{className:"mt-2 text-sm text-white/78",children:((Oe=ue.result)==null?void 0:Oe.primaryText)??ue.error??"No output yet."})]},ue.id)})})]})}),e.jsx(Tn,{open:$,onOpenChange:D,title:"Run inspector",description:"Inspect whole-flow outputs and stable node-level results for any saved run.",children:we?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(ue=>{var Oe;return e.jsxs("button",{type:"button",className:te("rounded-[18px] border px-4 py-3 text-left transition",Se===ue.id?"border-[var(--secondary)]/40 bg-[var(--secondary)]/12":"border-white/8 bg-black/20 hover:bg-white/[0.05]"),onClick:()=>Ee(ue.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[12px] text-white/50",children:[e.jsx("span",{children:ue.mode}),e.jsx("span",{children:new Date(ue.createdAt).toLocaleString()})]}),e.jsx("div",{className:"mt-2 text-sm text-white/80",children:((Oe=ue.result)==null?void 0:Oe.primaryText)??ue.error??"No output yet."})]},ue.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:we.mode}),e.jsx("span",{children:new Date(we.createdAt).toLocaleString()})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/82",children:((Be=we.result)==null?void 0:Be.primaryText)??we.error??"No output yet."}),(Ge=we.result)!=null&&Ge.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(we.result.outputs,null,2)})]}):null]}),(((gt=Z.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=Z.data)==null?void 0:Mt.nodeResults)??[]).map(ue=>e.jsx("button",{type:"button",className:te("rounded-[18px] border px-4 py-3 text-left transition",Ce===ue.nodeId?"border-[var(--secondary)]/40 bg-[var(--secondary)]/12":"border-white/8 bg-black/20 hover:bg-white/[0.05]"),onClick:()=>qe(ue.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:ue.label}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:ue.nodeType})]}),e.jsxs("div",{className:"rounded-full bg-white/[0.05] px-3 py-1 text-[11px] text-white/56",children:[Object.keys(ue.outputMap).length," outputs"]})]})},ue.nodeId))})]}),e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-4",children:De||(Vt=ee.data)!=null&&Vt.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:(qa=((Os=ee.data)==null?void 0:Os.nodeResult)??De)==null?void 0:qa.label}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:(tn=((Ba=ee.data)==null?void 0:Ba.nodeResult)??De)==null?void 0:tn.nodeType})]}),e.jsxs("div",{className:"rounded-full bg-white/[0.05] px-3 py-1 text-[11px] text-white/56",children:[(((an=((sn=ee.data)==null?void 0:sn.nodeResult)??De)==null?void 0:an.tools)??[]).length," ","tool",(((nn=((rn=ee.data)==null?void 0:rn.nodeResult)??De)==null?void 0:nn.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(((on=((ln=ee.data)==null?void 0:ln.nodeResult)??De)==null?void 0:on.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(((cn=((dn=ee.data)==null?void 0:dn.nodeResult)??De)==null?void 0:cn.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(((mn=((un=ee.data)==null?void 0:un.nodeResult)??De)==null?void 0:mn.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:Z.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 bE(){const t=Qs(),s=$t(),a=t.flowId??"",i=Q5(),r=J2(a,{skip:a.length===0}),n=_f(),[l]=uS(),[o]=iS(),[d]=cS(),[m]=aS();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(it,{eyebrow:"Workbench Flow",error:r.error??n.error??null}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(nt,{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(er,{entityType:"workbench_flow",entityId:r.data.flow.id})}),e.jsx(fE,{flow:r.data.flow,boxes:i,modelConnections:(n.data.settings.modelSettings.connections??[]).map(h=>({id:h.id,label:h.label,provider:h.provider,model:h.model,baseUrl:h.baseUrl})),runs:r.data.runs,onSave:async h=>{await l({flowId:a,patch:h}).unwrap()},onDelete:async()=>{await o(a).unwrap(),s("/workbench")},onRun:async h=>{await d({flowId:a,input:h}).unwrap()},onChat:async h=>{await m({flowId:a,input:h}).unwrap()}})]})}function wE(){const t=hi();return c.useEffect(()=>{const s=`${t.pathname}${t.search}${t.hash}`,a=Gg({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]),c.useEffect(()=>{const s=`${t.pathname}${t.search}${t.hash}`;Lo({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 yE(){function t(s,a,i,r){return e.jsx(Y5,{surfaceId:s,children:r})}return e.jsxs(G5,{children:[e.jsx(wE,{}),e.jsxs(k0,{children:[e.jsxs(at,{element:e.jsx(N4,{}),children:[e.jsx(at,{index:!0,element:e.jsx(Ld,{to:"/overview",replace:!0})}),e.jsx(at,{path:"overview",element:e.jsx(_8,{})}),e.jsx(at,{path:"life-force",element:t("life-force-index","Life Force","Action Point capacity, weekday curves, and dynamic drains.",e.jsx(wC,{}))}),e.jsx(at,{path:"goals",element:t("goals-index","Goals","Goal planning and long-horizon direction.",e.jsx(jI,{}))}),e.jsx(at,{path:"habits",element:t("habits-index","Habits","Recurring commitments, streaks, and check-ins.",e.jsx(zI,{}))}),e.jsx(at,{path:"goals/:goalId",element:t("goal-detail","Goal detail","Goal detail, progress, and linked execution context.",e.jsx(wI,{}))}),e.jsx(at,{path:"projects",element:e.jsx(aT,{})}),e.jsx(at,{path:"projects/hierarchy",element:t("project-hierarchy","Project hierarchy","Full hierarchy from goals down to subtasks.",e.jsx(Y8,{}))}),e.jsx(at,{path:"projects/:projectId",element:t("project-detail","Project detail","Project detail, tasks, and execution health.",e.jsx(B8,{}))}),e.jsx(at,{path:"strategies",element:t("strategies-index","Strategies","Strategy graphs and long-range execution plans.",e.jsx(fT,{}))}),e.jsx(at,{path:"strategies/:strategyId",element:t("strategy-detail","Strategy detail","Strategy DAG detail, targets, and progress.",e.jsx(kT,{}))}),e.jsx(at,{path:"preferences",element:t("preferences-index","Preferences","Preference profiles, pairwise judgments, and model state.",e.jsx(ET,{}))}),e.jsx(at,{path:"campaigns",element:e.jsx(Ld,{to:"/projects",replace:!0})}),e.jsx(at,{path:"calendar",element:t("calendar-index","Calendar","Calendar planning, timeboxes, and provider sync.",e.jsx(pI,{}))}),e.jsx(at,{path:"knowledge-graph",element:t("knowledge-graph-index","Knowledge Graph","One connected map of Forge entities and explicit relationships.",e.jsx(iC,{}))}),e.jsx(at,{path:"movement",element:t("movement-index","Movement","Movement traces, places, and trip evidence.",e.jsx(u8,{}))}),e.jsx(at,{path:"sleep",element:t("sleep-index","Sleep","Sleep sessions, health context, and recovery trends.",e.jsx(ZM,{}))}),e.jsx(at,{path:"sports",element:t("sports-index","Sports","Fitness, workouts, and sports context.",e.jsx(n6,{}))}),e.jsx(at,{path:"vitals",element:t("vitals-index","Vitals","Body signals, recovery, cardio fitness, and daily HealthKit metrics.",e.jsx(N6,{}))}),e.jsx(at,{path:"psyche",element:e.jsx(BT,{})}),e.jsx(at,{path:"psyche/values",element:t("psyche-values","Psyche values","Values and linked goal context.",e.jsx(vA,{}))}),e.jsx(at,{path:"psyche/patterns",element:t("psyche-patterns","Psyche patterns","Behavior patterns and recurring loops.",e.jsx(fP,{}))}),e.jsx(at,{path:"psyche/questionnaires",element:t("psyche-questionnaires","Questionnaires","Questionnaire library and recent runs.",e.jsx(FP,{}))}),e.jsx(at,{path:"psyche/questionnaires/new",element:t("psyche-questionnaire-new","New questionnaire","Questionnaire builder workspace.",e.jsx(wx,{}))}),e.jsx(at,{path:"psyche/questionnaires/:instrumentId",element:t("psyche-questionnaire-detail","Questionnaire detail","Questionnaire detail and scores.",e.jsx(jP,{}))}),e.jsx(at,{path:"psyche/questionnaires/:instrumentId/edit",element:t("psyche-questionnaire-edit","Edit questionnaire","Questionnaire builder workspace.",e.jsx(wx,{}))}),e.jsx(at,{path:"psyche/questionnaires/:instrumentId/take",element:t("psyche-questionnaire-run","Take questionnaire","Questionnaire runner and answers.",e.jsx(EP,{}))}),e.jsx(at,{path:"psyche/questionnaire-runs/:runId",element:t("psyche-questionnaire-run-detail","Questionnaire run detail","Questionnaire result review.",e.jsx(NP,{}))}),e.jsx(at,{path:"psyche/self-observation",element:t("psyche-self-observation","Self observation","Self-observation notes and reflective tracking.",e.jsx(pA,{}))}),e.jsx(at,{path:"psyche/screen-time",element:t("psyche-screen-time","Screen Time","Apple-compliant device-activity patterns and reflective usage history.",e.jsx(fA,{}))}),e.jsx(at,{path:"psyche/behaviors",element:t("psyche-behaviors","Behaviors","Behavior records and linked evidence.",e.jsx(tP,{}))}),e.jsx(at,{path:"psyche/reports",element:t("psyche-reports","Reports","Trigger and reflective report review.",e.jsx(HP,{}))}),e.jsx(at,{path:"psyche/reports/:reportId",element:t("psyche-report-detail","Report detail","Detailed reflective report view.",e.jsx(UP,{}))}),e.jsx(at,{path:"psyche/goal-map",element:t("psyche-goal-map","Goal map","Goal-to-values relationship map.",e.jsx(sP,{}))}),e.jsx(at,{path:"psyche/schemas-beliefs",element:t("psyche-schemas-beliefs","Schemas and beliefs","Beliefs, schemas, and linked patterns.",e.jsx(wA,{}))}),e.jsx(at,{path:"psyche/modes",element:t("psyche-modes","Modes","Mode profiles and guides.",e.jsx(cP,{}))}),e.jsx(at,{path:"psyche/modes/guide",element:t("psyche-mode-guide","Mode guide","Guided mode session flow.",e.jsx(nP,{}))}),e.jsx(at,{path:"kanban",element:t("kanban-index","Kanban","Task board execution surface.",e.jsx(f3,{}))}),e.jsx(at,{path:"notes",element:t("notes-index","Notes","Notes, evidence, and writing surfaces.",e.jsx(w8,{}))}),e.jsx(at,{path:"wiki",element:t("wiki-index","KarpaWiki","KarpaWiki search and page navigation.",e.jsx(Jx,{}))}),e.jsx(at,{path:"wiki/ingest-history",element:t("wiki-ingest-history","KarpaWiki ingest history","Ingest jobs and processing history.",e.jsx(U6,{}))}),e.jsx(at,{path:"wiki/page/:slug",element:t("wiki-page-detail","KarpaWiki page","KarpaWiki page detail and backlinks.",e.jsx(Jx,{}))}),e.jsx(at,{path:"wiki/new",element:t("wiki-new","New KarpaWiki page","KarpaWiki editor for new pages.",e.jsx(tg,{}))}),e.jsx(at,{path:"wiki/edit/:pageId",element:t("wiki-edit","Edit KarpaWiki page","KarpaWiki editor for existing pages.",e.jsx(tg,{}))}),e.jsx(at,{path:"today",element:e.jsx(w6,{})}),e.jsx(at,{path:"workbench",element:t("workbench","Workbench","Search, organize, and launch Forge flows.",e.jsx(Z6,{}))}),e.jsx(at,{path:"workbench/:flowId",element:t("workbench-flow","Workbench flow","Graph editor and runtime surface for a single flow.",e.jsx(bE,{}))}),e.jsx(at,{path:"activity",element:t("activity-index","Activity","Activity log and event history.",e.jsx(eI,{}))}),e.jsx(at,{path:"insights",element:t("insights-index","Insights","Insight review and decisions.",e.jsx(t3,{}))}),e.jsx(at,{path:"review/weekly",element:t("weekly-review","Weekly review","Weekly review workflow and closeout.",e.jsx(J6,{}))}),e.jsx(at,{path:"settings",element:t("settings-index","Settings","Operator settings and runtime configuration.",e.jsx(kA,{}))}),e.jsx(at,{path:"settings/data",element:t("settings-data","Settings data","Runtime storage, backups, exports, and recovery.",e.jsx(TA,{}))}),e.jsx(at,{path:"settings/users",element:t("settings-users","Settings users","User directory and ownership settings.",e.jsx(_M,{}))}),e.jsx(at,{path:"settings/calendar",element:t("settings-calendar","Settings calendar","Calendar provider settings and sync.",e.jsx(aM,{}))}),e.jsx(at,{path:"settings/mobile",element:t("settings-mobile","Settings mobile","Mobile companion settings and pairing.",e.jsx(dM,{}))}),null,e.jsx(at,{path:"settings/models",element:t("settings-models","Settings models","Model connections and defaults.",e.jsx(uM,{}))}),e.jsx(at,{path:"settings/agents",element:t("settings-agents","Settings agents","Agent tokens and runtime access.",e.jsx(_A,{}))}),e.jsx(at,{path:"settings/rewards",element:t("settings-rewards","Settings rewards","Rewards and XP rule settings.",e.jsx(IM,{}))}),e.jsx(at,{path:"settings/wiki",element:t("settings-wiki","KarpaWiki settings","KarpaWiki ingestion and profile settings.",e.jsx(oT,{}))}),e.jsx(at,{path:"settings/logs",element:t("settings-logs","Settings logs","Diagnostics and event logs.",e.jsx(vM,{}))}),e.jsx(at,{path:"settings/bin",element:t("settings-bin","Settings bin","Deleted entity recovery.",e.jsx(OA,{}))}),e.jsx(at,{path:"tasks/:taskId",element:t("task-detail","Task detail","Task detail, timer, and notes.",e.jsx(c6,{}))})]}),e.jsx(at,{path:"*",element:e.jsx(Ld,{to:"/overview",replace:!0})})]})]})}const vE=new S0({defaultOptions:{queries:{staleTime:2e4,refetchOnWindowFocus:!1}}});I0.createRoot(document.getElementById("root")).render(e.jsx(C0.StrictMode,{children:e.jsx(T0,{store:xm,children:e.jsx(P0,{client:vE,children:e.jsx(A0,{basename:aj("/forge/"),children:e.jsx(yE,{})})})})}));
91
- //# sourceMappingURL=index-CHP_xh1Q.js.map
91
+ //# sourceMappingURL=index-DQ-j4l4x.js.map